@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
  // ../../packages/plugin-sdk/src/config.ts
495
- import { existsSync as existsSync5 } from "fs";
496
- import { join as join8 } from "path";
495
+ import { existsSync as existsSync6 } from "fs";
496
+ import { join as join10 } from "path";
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 table of ["events", "findings"]) {
19210
+ try {
19211
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
19212
+ if (row === void 0) {
19213
+ holdsRows = true;
19214
+ marks.push(`${table}:unreadable`);
19215
+ continue;
19216
+ }
19217
+ if (row.n > 0) holdsRows = true;
19218
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
19219
+ } catch {
19220
+ holdsRows = true;
19221
+ marks.push(`${table}: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,25 @@ 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
+ function keysDir(base = defaultDataDir()) {
25866
+ return join5(base, "keys");
25867
+ }
25868
+ async function ensureDataDir(dir = defaultDataDir()) {
25869
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
25870
+ tightenDir(dir);
25630
25871
  }
25631
25872
  function ensureLayoutDirSync(dir = defaultDataDir()) {
25632
25873
  ensureDataDirSync(dir);
@@ -25639,8 +25880,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25639
25880
  for (const { name, dest } of moves) {
25640
25881
  try {
25641
25882
  ensureDataDirSync(dest);
25642
- const moved = join4(dest, name);
25643
- renameSync3(join4(base, name), moved);
25883
+ const moved = join5(dest, name);
25884
+ renameSync3(join5(base, name), moved);
25644
25885
  tightenFile(moved);
25645
25886
  } catch {
25646
25887
  }
@@ -25648,7 +25889,7 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25648
25889
  }
25649
25890
 
25650
25891
  // ../../packages/persistence/src/managed-settings.ts
25651
- import { readFileSync as readFileSync3 } from "fs";
25892
+ import { readFileSync as readFileSync4 } from "fs";
25652
25893
  import { posix, win32 } from "path";
25653
25894
  function managedSettingsPaths(platform2 = process.platform) {
25654
25895
  if (platform2 === "darwin") {
@@ -25666,14 +25907,14 @@ function readManagedSettings(paths = managedSettingsPaths()) {
25666
25907
  for (const path of paths) {
25667
25908
  let text;
25668
25909
  try {
25669
- text = readFileSync3(path, "utf8");
25910
+ text = readFileSync4(path, "utf8");
25670
25911
  } catch {
25671
25912
  continue;
25672
25913
  }
25673
25914
  const record2 = parseJsonObject(text);
25674
25915
  if (!record2) continue;
25675
- const parsed = ManagedSettings.safeParse(record2);
25676
- if (parsed.success) return parsed.data;
25916
+ const parsed2 = ManagedSettings.safeParse(record2);
25917
+ if (parsed2.success) return parsed2.data;
25677
25918
  }
25678
25919
  return null;
25679
25920
  }
@@ -25713,14 +25954,14 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
25713
25954
  }
25714
25955
 
25715
25956
  // ../../packages/persistence/src/settings.ts
25716
- import { readFileSync as readFileSync4 } from "fs";
25717
- import { join as join5 } from "path";
25957
+ import { readFileSync as readFileSync5 } from "fs";
25958
+ import { join as join6 } from "path";
25718
25959
  var SETTINGS_FILENAME = "settings.json";
25719
25960
  function readWorkspaceSettings(base = defaultDataDir()) {
25720
25961
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
25721
25962
  }
25722
25963
  function readUserSettings(base) {
25723
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
25964
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
25724
25965
  if (!record2) return defaultWorkspaceSettings();
25725
25966
  try {
25726
25967
  return WorkspaceSettings.parse(record2);
@@ -25731,13 +25972,64 @@ function readUserSettings(base) {
25731
25972
  function readJson(file2) {
25732
25973
  let text;
25733
25974
  try {
25734
- text = readFileSync4(file2, "utf8");
25975
+ text = readFileSync5(file2, "utf8");
25735
25976
  } catch {
25736
25977
  return null;
25737
25978
  }
25738
25979
  return parseJsonObject(text) ?? null;
25739
25980
  }
25740
25981
 
25982
+ // ../../packages/persistence/src/store-symlinks.ts
25983
+ import { existsSync as existsSync4, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
25984
+ import { dirname as dirname2, join as join7, resolve } from "path";
25985
+ var STORE_DB = "the store database (including the prompt corpus)";
25986
+ var STORE_SETTINGS = "your settings file";
25987
+ function storeContents(home) {
25988
+ return /* @__PURE__ */ new Map([
25989
+ [home, "the store (including the prompt corpus in aka.db)"],
25990
+ [settingsDir(home), STORE_SETTINGS],
25991
+ [dataDir(home), STORE_DB],
25992
+ [keysDir(home), "the vault key"],
25993
+ [join7(settingsDir(home), "settings.json"), STORE_SETTINGS],
25994
+ [dbPath(home), STORE_DB]
25995
+ ]);
25996
+ }
25997
+ function symlinkedStorePaths(home, platform2 = process.platform) {
25998
+ return [...storeContents(home)].flatMap(([path, holds]) => {
25999
+ try {
26000
+ if (!lstatSync3(path).isSymbolicLink()) return [];
26001
+ return [
26002
+ {
26003
+ path,
26004
+ target: linkTarget(path),
26005
+ holds,
26006
+ // existsSync follows the link, so a target that is gone reads as
26007
+ // absent here while lstat above still sees the link itself.
26008
+ missing: !existsSync4(path),
26009
+ mode: targetMode(path, platform2)
26010
+ }
26011
+ ];
26012
+ } catch {
26013
+ return [];
26014
+ }
26015
+ });
26016
+ }
26017
+ function linkTarget(path) {
26018
+ try {
26019
+ return realpathSync(path);
26020
+ } catch {
26021
+ return resolve(dirname2(path), readlinkSync(path));
26022
+ }
26023
+ }
26024
+ function targetMode(path, platform2) {
26025
+ if (platform2 === "win32") return void 0;
26026
+ try {
26027
+ return statSync4(path).mode & 511;
26028
+ } catch {
26029
+ return void 0;
26030
+ }
26031
+ }
26032
+
25741
26033
  // ../../packages/persistence/src/vault/crypto.ts
25742
26034
  import {
25743
26035
  createCipheriv,
@@ -25750,20 +26042,20 @@ import {
25750
26042
  // ../../packages/persistence/src/vault/key-provider.ts
25751
26043
  import { execFileSync } from "child_process";
25752
26044
  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";
26045
+ import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync5, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
26046
+ import { join as join8 } from "path";
25755
26047
 
25756
26048
  // ../../packages/persistence/src/vault/vault.ts
25757
26049
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
25758
26050
 
25759
26051
  // ../../packages/persistence/src/warn-era-cap.ts
25760
- import { existsSync as existsSync4, writeFileSync as writeFileSync4 } from "fs";
25761
- import { join as join7 } from "path";
26052
+ import { existsSync as existsSync5, writeFileSync as writeFileSync4 } from "fs";
26053
+ import { join as join9 } from "path";
25762
26054
  var MARKER = "warn-era-capped";
25763
26055
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
25764
26056
  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" };
26057
+ const marker = join9(dataDir2, MARKER);
26058
+ if (existsSync5(marker)) return { capped: 0, skipped: "already-run" };
25767
26059
  const capped = db.policies.capCategoryActions();
25768
26060
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
25769
26061
  `, { mode: DATA_FILE_MODE });
@@ -25804,8 +26096,8 @@ function hostOf(url2) {
25804
26096
  }
25805
26097
  }
25806
26098
  function resolveProvider() {
25807
- const parsed = ProviderEnvSchema.safeParse(process.env);
25808
- const env = parsed.success ? parsed.data : ProviderEnvSchema.parse({});
26099
+ const parsed2 = ProviderEnvSchema.safeParse(process.env);
26100
+ const env = parsed2.success ? parsed2.data : ProviderEnvSchema.parse({});
25809
26101
  if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
25810
26102
  if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
25811
26103
  const baseUrl = env.ANTHROPIC_BASE_URL;
@@ -25822,8 +26114,8 @@ function resolveProvider() {
25822
26114
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
25823
26115
  try {
25824
26116
  ensureLayoutDirSync(base);
25825
- const settingsFile = join8(settingsDir(base), "settings.json");
25826
- if (existsSync5(settingsFile)) tightenFile(settingsFile);
26117
+ const settingsFile = join10(settingsDir(base), "settings.json");
26118
+ if (existsSync6(settingsFile)) tightenFile(settingsFile);
25827
26119
  } catch {
25828
26120
  }
25829
26121
  migrateLegacyLayout(base);
@@ -25846,9 +26138,9 @@ function resolveProviderSafe(resolveProviderFn) {
25846
26138
  }
25847
26139
 
25848
26140
  // ../../packages/plugin-sdk/src/config-inventory.ts
25849
- import { readdirSync as readdirSync2, readFileSync as readFileSync7, realpathSync, statSync as statSync5 } from "fs";
26141
+ import { readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
25850
26142
  import { homedir as homedir2 } from "os";
25851
- import { basename as basename3, join as join10 } from "path";
26143
+ import { basename as basename3, join as join12 } from "path";
25852
26144
 
25853
26145
  // ../../packages/detections/src/egress/registry.ts
25854
26146
  var EXTRACTOR_VERSION = "1";
@@ -27625,10 +27917,10 @@ var localhost_ref_default = {
27625
27917
  severity: "low",
27626
27918
  matcher: {
27627
27919
  type: "regex",
27628
- pattern: "\\b(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|::1)\\b",
27920
+ 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_])",
27629
27921
  flags: "g"
27630
27922
  },
27631
- examples: ["localhost", "127.0.0.1"]
27923
+ examples: ["localhost", "127.0.0.1", "0.0.0.0", "::1"]
27632
27924
  };
27633
27925
 
27634
27926
  // ../../rules/core-code-context/stack-trace.json
@@ -28940,8 +29232,8 @@ function uniqueRuleIds(findings) {
28940
29232
  }
28941
29233
 
28942
29234
  // ../../packages/plugin-sdk/src/repo.ts
28943
- import { existsSync as existsSync6, readFileSync as readFileSync6, statSync as statSync4 } from "fs";
28944
- import { basename as basename2, dirname as dirname2, isAbsolute, join as join9, sep as sep2 } from "path";
29235
+ import { existsSync as existsSync7, readFileSync as readFileSync7, statSync as statSync6 } from "fs";
29236
+ import { basename as basename2, dirname as dirname3, isAbsolute, join as join11, sep as sep2 } from "path";
28945
29237
  function resolveRepo(cwd) {
28946
29238
  try {
28947
29239
  const root = findGitRoot(cwd);
@@ -28956,36 +29248,36 @@ function resolveRepo(cwd) {
28956
29248
  function findGitRoot(start) {
28957
29249
  let dir = start;
28958
29250
  for (; ; ) {
28959
- if (existsSync6(join9(dir, ".git"))) return dir;
28960
- const parent = dirname2(dir);
29251
+ if (existsSync7(join11(dir, ".git"))) return dir;
29252
+ const parent = dirname3(dir);
28961
29253
  if (parent === dir) return void 0;
28962
29254
  dir = parent;
28963
29255
  }
28964
29256
  }
28965
29257
  function resolveGitContext(root) {
28966
- const dotGit = join9(root, ".git");
29258
+ const dotGit = join11(root, ".git");
28967
29259
  try {
28968
- if (statSync4(dotGit).isDirectory()) {
28969
- return { configPath: join9(dotGit, "config"), headRoot: root };
29260
+ if (statSync6(dotGit).isDirectory()) {
29261
+ return { configPath: join11(dotGit, "config"), headRoot: root };
28970
29262
  }
28971
29263
  } catch {
28972
29264
  return void 0;
28973
29265
  }
28974
29266
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
28975
29267
  if (!target) return void 0;
28976
- const gitdir = isAbsolute(target) ? target : join9(root, target);
28977
- if (existsSync6(join9(gitdir, "config"))) {
28978
- return { configPath: join9(gitdir, "config"), headRoot: root };
29268
+ const gitdir = isAbsolute(target) ? target : join11(root, target);
29269
+ if (existsSync7(join11(gitdir, "config"))) {
29270
+ return { configPath: join11(gitdir, "config"), headRoot: root };
28979
29271
  }
28980
- const commonRaw = safeRead(join9(gitdir, "commondir"))?.trim();
29272
+ const commonRaw = safeRead(join11(gitdir, "commondir"))?.trim();
28981
29273
  if (!commonRaw) return void 0;
28982
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join9(gitdir, commonRaw);
28983
- const headRoot = basename2(commonGitDir) === ".git" ? dirname2(commonGitDir) : root;
28984
- return { configPath: join9(commonGitDir, "config"), headRoot };
29274
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join11(gitdir, commonRaw);
29275
+ const headRoot = basename2(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
29276
+ return { configPath: join11(commonGitDir, "config"), headRoot };
28985
29277
  }
28986
29278
  function safeRead(path) {
28987
29279
  try {
28988
- return readFileSync6(path, "utf8");
29280
+ return readFileSync7(path, "utf8");
28989
29281
  } catch {
28990
29282
  return void 0;
28991
29283
  }
@@ -29046,7 +29338,7 @@ function buildIngestEvent(input) {
29046
29338
  }
29047
29339
 
29048
29340
  // ../../packages/plugin-sdk/src/isolated-scan.ts
29049
- import { existsSync as existsSync7 } from "fs";
29341
+ import { existsSync as existsSync8 } from "fs";
29050
29342
  import { fileURLToPath } from "url";
29051
29343
  import { Worker } from "worker_threads";
29052
29344
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -29060,7 +29352,7 @@ function resolveWorkerUrl() {
29060
29352
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
29061
29353
  const candidate = new URL(name, import.meta.url);
29062
29354
  try {
29063
- if (existsSync7(fileURLToPath(candidate))) {
29355
+ if (existsSync8(fileURLToPath(candidate))) {
29064
29356
  resolvedWorkerUrl = candidate;
29065
29357
  return candidate;
29066
29358
  }
@@ -29245,8 +29537,8 @@ function createIsolatedScanner(data, opts = {}) {
29245
29537
  }
29246
29538
  function enqueue(spec) {
29247
29539
  const next = chain.then(
29248
- () => new Promise((resolve) => {
29249
- spec(resolve);
29540
+ () => new Promise((resolve2) => {
29541
+ spec(resolve2);
29250
29542
  })
29251
29543
  );
29252
29544
  chain = next.then(
@@ -29257,7 +29549,7 @@ function createIsolatedScanner(data, opts = {}) {
29257
29549
  }
29258
29550
  return {
29259
29551
  scan(text, context, scanOpts) {
29260
- return enqueue((resolve) => {
29552
+ return enqueue((resolve2) => {
29261
29553
  runOne(
29262
29554
  {
29263
29555
  budgetMs,
@@ -29270,23 +29562,23 @@ function createIsolatedScanner(data, opts = {}) {
29270
29562
  }),
29271
29563
  reply: (message) => {
29272
29564
  if (message.kind !== "result") return false;
29273
- resolve({ status: "ok", findings: message.findings });
29565
+ resolve2({ status: "ok", findings: message.findings });
29274
29566
  return true;
29275
29567
  }
29276
29568
  },
29277
- resolve
29569
+ resolve2
29278
29570
  );
29279
29571
  });
29280
29572
  },
29281
29573
  probe(rule) {
29282
- return enqueue((resolve) => {
29574
+ return enqueue((resolve2) => {
29283
29575
  runOne(
29284
29576
  {
29285
29577
  budgetMs: probeBudgetMs,
29286
29578
  build: (id) => ({ kind: "probe", id, rule }),
29287
29579
  reply: (message) => {
29288
29580
  if (message.kind !== "probed") return false;
29289
- resolve({
29581
+ resolve2({
29290
29582
  status: "ok",
29291
29583
  verdict: message.verdict,
29292
29584
  worstMs: message.worstMs,
@@ -29295,7 +29587,7 @@ function createIsolatedScanner(data, opts = {}) {
29295
29587
  return true;
29296
29588
  }
29297
29589
  },
29298
- resolve
29590
+ resolve2
29299
29591
  );
29300
29592
  });
29301
29593
  },
@@ -29525,24 +29817,24 @@ function createGuardedScanner(partition, gateway, opts) {
29525
29817
 
29526
29818
  // ../../packages/plugin-sdk/src/ignore-layers.ts
29527
29819
  var import_ignore = __toESM(require_ignore(), 1);
29528
- import { readFileSync as readFileSync8 } from "fs";
29529
- import { join as join11 } from "path";
29820
+ import { readFileSync as readFileSync9 } from "fs";
29821
+ import { join as join13 } from "path";
29530
29822
 
29531
29823
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
29532
29824
  import { arch, hostname as hostname4, platform, release } from "os";
29533
29825
 
29534
29826
  // ../../packages/plugin-sdk/src/nudge.ts
29535
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
29536
- import { join as join12 } from "path";
29827
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "fs";
29828
+ import { join as join14 } from "path";
29537
29829
  var NUDGE_MARKER = "nudge-last-session";
29538
29830
  function claimOnboardingNudge(dataDir2, sessionId) {
29539
29831
  return claimOncePerSession(dataDir2, NUDGE_MARKER, sessionId);
29540
29832
  }
29541
29833
  function claimOncePerSession(dataDir2, marker, sessionId) {
29542
29834
  if (!sessionId) return true;
29543
- const path = join12(dataDir2, marker);
29835
+ const path = join14(dataDir2, marker);
29544
29836
  try {
29545
- if (readFileSync9(path, "utf8") === sessionId) return false;
29837
+ if (readFileSync10(path, "utf8") === sessionId) return false;
29546
29838
  } catch {
29547
29839
  }
29548
29840
  try {
@@ -29554,12 +29846,12 @@ function claimOncePerSession(dataDir2, marker, sessionId) {
29554
29846
  }
29555
29847
 
29556
29848
  // ../../packages/plugin-sdk/src/paths.ts
29557
- import { readdirSync as readdirSync3, realpathSync as realpathSync2 } from "fs";
29558
- import { basename as basename4, dirname as dirname3, sep as sep3 } from "path";
29849
+ import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
29850
+ import { basename as basename4, dirname as dirname4, sep as sep3 } from "path";
29559
29851
 
29560
29852
  // ../../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";
29853
+ import { existsSync as existsSync9, readdirSync as readdirSync4 } from "fs";
29854
+ import { basename as basename5, join as join15 } from "path";
29563
29855
 
29564
29856
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
29565
29857
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -29930,8 +30222,8 @@ function createPluginRuntime(gateway, settings, opts) {
29930
30222
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
29931
30223
 
29932
30224
  // ../../packages/plugin-sdk/src/throttle.ts
29933
- import { mkdirSync as mkdirSync3, statSync as statSync6, writeFileSync as writeFileSync6 } from "fs";
29934
- import { join as join14 } from "path";
30225
+ import { mkdirSync as mkdirSync3, statSync as statSync8, writeFileSync as writeFileSync6 } from "fs";
30226
+ import { join as join16 } from "path";
29935
30227
 
29936
30228
  // src/present.ts
29937
30229
  var fg = (hex3) => (text) => {
@@ -29982,7 +30274,7 @@ function exceptionPointer(references) {
29982
30274
 
29983
30275
  // src/hooks/shared.ts
29984
30276
  async function readStdin() {
29985
- return new Promise((resolve) => {
30277
+ return new Promise((resolve2) => {
29986
30278
  let data = "";
29987
30279
  let settled = false;
29988
30280
  const finish = () => {
@@ -29991,7 +30283,7 @@ async function readStdin() {
29991
30283
  clearTimeout(timer);
29992
30284
  process.stdin.removeListener("data", onData);
29993
30285
  process.stdin.removeListener("end", finish);
29994
- resolve(data);
30286
+ resolve2(data);
29995
30287
  };
29996
30288
  const onData = (chunk) => {
29997
30289
  data += chunk;
@@ -30005,8 +30297,8 @@ async function readStdin() {
30005
30297
  }
30006
30298
  function parseJson(raw) {
30007
30299
  try {
30008
- const parsed = JSON.parse(raw);
30009
- return typeof parsed === "object" && parsed !== null ? parsed : null;
30300
+ const parsed2 = JSON.parse(raw);
30301
+ return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
30010
30302
  } catch {
30011
30303
  return null;
30012
30304
  }
@@ -30016,12 +30308,12 @@ function getString(record2, key) {
30016
30308
  return typeof value === "string" ? value : void 0;
30017
30309
  }
30018
30310
  function emit(output) {
30019
- return new Promise((resolve) => {
30311
+ return new Promise((resolve2) => {
30020
30312
  let settled = false;
30021
30313
  const finish = () => {
30022
30314
  if (settled) return;
30023
30315
  settled = true;
30024
- resolve();
30316
+ resolve2();
30025
30317
  };
30026
30318
  process.stdout.on("error", finish);
30027
30319
  process.stdout.write(JSON.stringify(output), finish);
@@ -30037,57 +30329,1247 @@ function baseMetadata(input) {
30037
30329
  }
30038
30330
 
30039
30331
  // src/hooks/store-health.ts
30040
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync10, writeFileSync as writeFileSync7 } from "fs";
30041
- import { join as join15 } from "path";
30332
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync14, writeFileSync as writeFileSync7 } from "fs";
30333
+ import { dirname as dirname5, join as join22 } from "path";
30334
+
30335
+ // ../../packages/plugin-runtime/src/attached/failure.ts
30336
+ function statusOf(err) {
30337
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
30338
+ const { status } = err;
30339
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
30340
+ return status >= 100 && status <= 599 ? status : null;
30341
+ }
30342
+ function classifyFailure(err) {
30343
+ switch (statusOf(err)) {
30344
+ case 401:
30345
+ return "unauthorized";
30346
+ case 403:
30347
+ return "forbidden";
30348
+ default:
30349
+ return "unreachable";
30350
+ }
30351
+ }
30042
30352
 
30043
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
30044
- import { randomUUID as randomUUID15 } from "crypto";
30353
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
30354
+ import { readFileSync as readFileSync11 } from "fs";
30355
+ import { join as join17 } from "path";
30356
+ var FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
30357
+ function forwardDropsPath(dataDir2) {
30358
+ return join17(dataDir2, FORWARD_DROPS_FILENAME);
30359
+ }
30360
+ function recordForwardDrops(dataDir2, count, nowMs) {
30361
+ if (count <= 0) return;
30362
+ try {
30363
+ ensureDataDirSync(dataDir2);
30364
+ const previous = readForwardDrops(dataDir2);
30365
+ const next = {
30366
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
30367
+ lastDropAtMs: nowMs
30368
+ };
30369
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
30370
+ `);
30371
+ } catch {
30372
+ }
30373
+ }
30374
+ function readForwardDrops(dataDir2) {
30375
+ try {
30376
+ const parsed2 = JSON.parse(readFileSync11(forwardDropsPath(dataDir2), "utf8"));
30377
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30378
+ const record2 = parsed2;
30379
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
30380
+ return null;
30381
+ }
30382
+ if (record2.droppedForwards <= 0) return null;
30383
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
30384
+ return null;
30385
+ }
30386
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
30387
+ } catch {
30388
+ return null;
30389
+ }
30390
+ }
30045
30391
 
30046
- // ../../packages/plugin-runtime/src/recorder.ts
30047
- var PLUGIN_RECORDER_BINARY = "plugin";
30392
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
30393
+ import { randomUUID as randomUUID15 } from "crypto";
30394
+ import { readFileSync as readFileSync12 } from "fs";
30395
+ import { readFile, rename, writeFile } from "fs/promises";
30396
+ import { join as join18 } from "path";
30397
+
30398
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
30399
+ var REQUEST_TIMEOUT_MS = 2e3;
30400
+ function withTimeout(promise2, ms) {
30401
+ let timer;
30402
+ const timeout = new Promise((_, reject) => {
30403
+ timer = setTimeout(() => {
30404
+ reject(new Error("attached gateway request timed out"));
30405
+ }, ms);
30406
+ });
30407
+ promise2.catch(() => void 0);
30408
+ return Promise.race([promise2, timeout]).finally(() => {
30409
+ clearTimeout(timer);
30410
+ });
30411
+ }
30048
30412
 
30049
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
30050
- var StandaloneDataGateway = class {
30051
- db;
30052
- // Kept for the fingerprint key lookup (exception.key lives beside the store).
30053
- dataDir;
30054
- // One notice per gateway — see warnRulesetDiscarded.
30055
- warnedRulesetDiscarded = false;
30056
- constructor(dataDir2, detections = [], meta3) {
30057
- this.db = openLocalDatabase(dataDir2);
30058
- this.dataDir = dataDir2;
30059
- this.db.installedPacks.recordInventory(detections, meta3);
30060
- }
30061
- recordCapture(record2) {
30062
- this.db.recordCapture(record2.event, record2.findings);
30063
- return Promise.resolve();
30413
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
30414
+ function isInvalidRequest(err) {
30415
+ return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
30416
+ }
30417
+ var FORWARD_BUDGET_MS = 1500;
30418
+ var DECISION_PATH_BUDGET_MS = 800;
30419
+ var BREAKER_FAILURE_THRESHOLD = 3;
30420
+ var BREAKER_COOLDOWN_MS = 3e4;
30421
+ var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
30422
+ var FAILURES = /* @__PURE__ */ new Set([
30423
+ "unauthorized",
30424
+ "forbidden",
30425
+ "unreachable"
30426
+ ]);
30427
+ var FORWARD_STATE_FILENAME = "attached-state.json";
30428
+ var STATE_FILENAME = FORWARD_STATE_FILENAME;
30429
+ function parseBreakerState(raw, nowMs) {
30430
+ try {
30431
+ const parsed2 = JSON.parse(raw);
30432
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30433
+ const record2 = parsed2;
30434
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
30435
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
30436
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
30437
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
30438
+ } catch {
30439
+ return null;
30064
30440
  }
30065
- ensureInventory(ctx) {
30066
- return Promise.resolve(this.db.ensureInventory(ctx));
30441
+ }
30442
+ function createForwardPolicy(deps) {
30443
+ const now = deps.now ?? (() => Date.now());
30444
+ const file2 = join18(deps.dir, STATE_FILENAME);
30445
+ let state = null;
30446
+ let loading = null;
30447
+ async function readState() {
30448
+ let raw;
30449
+ try {
30450
+ raw = await readFile(file2, "utf8");
30451
+ } catch {
30452
+ return { ...CLOSED };
30453
+ }
30454
+ return parseBreakerState(raw, now()) ?? { ...CLOSED };
30067
30455
  }
30068
- recordAuditEvent(event) {
30069
- this.db.auditEvents.insertAuditEvent(event);
30070
- return Promise.resolve();
30456
+ async function load() {
30457
+ if (state !== null) return state;
30458
+ loading ??= readState().then((loaded) => {
30459
+ state = loaded;
30460
+ loading = null;
30461
+ return loaded;
30462
+ });
30463
+ return loading;
30071
30464
  }
30072
- // The id is minted inside the repository from the natural key — the plugin can't
30073
- // import @akasecurity/persistence to compute it, so the gateway is the boundary that
30074
- // hands the natural key across. UPSERT-take-MAX → idempotent re-reads that also
30075
- // converge a streaming partial/final split (see insertLlmCall).
30076
- recordLlmCall(input) {
30077
- this.db.auditEvents.insertLlmCall(input);
30078
- return Promise.resolve();
30465
+ async function persist(next) {
30466
+ state = next;
30467
+ try {
30468
+ await ensureDataDir(deps.dir);
30469
+ const tmp = `${file2}.${randomUUID15()}.tmp`;
30470
+ await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
30471
+ await rename(tmp, file2);
30472
+ } catch {
30473
+ }
30079
30474
  }
30080
- // One reconcile pass = one transaction. All leaves commit together
30475
+ return {
30476
+ async run(op, opts) {
30477
+ const budget = opts?.decisionPath === true ? DECISION_PATH_BUDGET_MS : FORWARD_BUDGET_MS;
30478
+ let current;
30479
+ try {
30480
+ current = await load();
30481
+ } catch {
30482
+ current = { ...CLOSED };
30483
+ }
30484
+ const at = now();
30485
+ if (current.openedAtMs !== null) {
30486
+ if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
30487
+ return { ok: false, reason: "breaker-open" };
30488
+ }
30489
+ await persist({
30490
+ consecutiveFailures: current.consecutiveFailures,
30491
+ openedAtMs: at,
30492
+ lastFailure: current.lastFailure
30493
+ });
30494
+ }
30495
+ try {
30496
+ const value = await withTimeout(op(), budget);
30497
+ if (current.openedAtMs !== null || current.consecutiveFailures > 0) {
30498
+ await persist({ ...CLOSED });
30499
+ }
30500
+ return { ok: true, value };
30501
+ } catch (err) {
30502
+ if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
30503
+ const reason = classifyFailure(err);
30504
+ const failures = current.consecutiveFailures + 1;
30505
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
30506
+ await persist({
30507
+ consecutiveFailures: failures,
30508
+ openedAtMs: shouldOpen ? now() : null,
30509
+ lastFailure: reason
30510
+ });
30511
+ return { ok: false, reason };
30512
+ }
30513
+ }
30514
+ };
30515
+ }
30516
+
30517
+ // ../../packages/plugin-runtime/src/attached/gateway.ts
30518
+ var ACTION_STRENGTH = {
30519
+ allow: 0,
30520
+ log: 1,
30521
+ warn: 2,
30522
+ redact: 3,
30523
+ block: 4
30524
+ };
30525
+ function ruleCategoryMap(wireRules, localRules) {
30526
+ const map2 = /* @__PURE__ */ new Map();
30527
+ for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
30528
+ for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
30529
+ for (const pack of bundledDetections()) {
30530
+ for (const rule of pack.rules) map2.set(rule.id, rule.category);
30531
+ }
30532
+ return map2;
30533
+ }
30534
+ function strongerOf(a, b) {
30535
+ if (a === null) return b;
30536
+ if (b === null) return a;
30537
+ return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
30538
+ }
30539
+ function policyKey(policy) {
30540
+ return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
30541
+ }
30542
+ function floorFor(policy, categoryByRuleId) {
30543
+ const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
30544
+ return category === void 0 ? null : DEFAULT_ACTIONS[category];
30545
+ }
30546
+ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
30547
+ const merged = /* @__PURE__ */ new Map();
30548
+ const disabled = [];
30549
+ const remoteCategoryAction = /* @__PURE__ */ new Map();
30550
+ for (const policy of remotePolicies) {
30551
+ if (!policy.enabled) continue;
30552
+ if (!("category" in policy.target)) continue;
30553
+ if (remoteCategoryAction.has(policy.target.category)) continue;
30554
+ const floor = floorFor(policy, categoryByRuleId);
30555
+ remoteCategoryAction.set(
30556
+ policy.target.category,
30557
+ floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
30558
+ );
30559
+ }
30560
+ for (const policy of localPolicies) {
30561
+ if (!policy.enabled) {
30562
+ disabled.push(policy);
30563
+ continue;
30564
+ }
30565
+ const key = policyKey(policy);
30566
+ if (merged.has(key)) continue;
30567
+ let remoteFloor = null;
30568
+ if ("ruleId" in policy.target) {
30569
+ const category = categoryByRuleId.get(policy.target.ruleId);
30570
+ if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
30571
+ }
30572
+ merged.set(
30573
+ key,
30574
+ remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
30575
+ );
30576
+ }
30577
+ const localCategoryAction = /* @__PURE__ */ new Map();
30578
+ for (const policy of merged.values()) {
30579
+ if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
30580
+ }
30581
+ for (const policy of remotePolicies) {
30582
+ if (!policy.enabled) {
30583
+ disabled.push(policy);
30584
+ continue;
30585
+ }
30586
+ const key = policyKey(policy);
30587
+ const floor = floorFor(policy, categoryByRuleId);
30588
+ let localFloor = null;
30589
+ if ("ruleId" in policy.target) {
30590
+ const category = categoryByRuleId.get(policy.target.ruleId);
30591
+ if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
30592
+ }
30593
+ const effectiveFloor = strongerOf(floor, localFloor);
30594
+ const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
30595
+ const existing = merged.get(key);
30596
+ if (existing === void 0) {
30597
+ merged.set(key, clamped);
30598
+ continue;
30599
+ }
30600
+ if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
30601
+ merged.set(key, clamped);
30602
+ }
30603
+ }
30604
+ return [...merged.values(), ...disabled];
30605
+ }
30606
+ var AttachedDataGateway = class {
30607
+ constructor(deps) {
30608
+ this.deps = deps;
30609
+ }
30610
+ deps;
30611
+ /**
30612
+ * The control plane's OWN resolution of this session's inventory, captured by
30613
+ * ensureInventory. Null until the first successful forward — and it stays
30614
+ * null for the whole session when the control plane is unreachable, which is fine:
30615
+ * reKeyForForward then leaves the event's ids alone and the control plane resolves
30616
+ * what it can from the descriptors it already has.
30617
+ */
30618
+ remoteInventory = null;
30619
+ // ---------------------------------------------------------------------
30620
+ // Writes: local first, then forward.
30621
+ // ---------------------------------------------------------------------
30622
+ async recordCapture(record2) {
30623
+ await this.deps.local.recordCapture(record2);
30624
+ await this.deps.forward.run(
30625
+ () => this.deps.client.ingestEvents({
30626
+ events: [record2.event],
30627
+ ...record2.dedupe ? { dedupe: record2.dedupe } : {}
30628
+ }),
30629
+ { decisionPath: true }
30630
+ );
30631
+ }
30632
+ async ensureInventory(ctx) {
30633
+ const resolved = await this.deps.local.ensureInventory(ctx);
30634
+ const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
30635
+ this.remoteInventory = remote.ok ? remote.value : null;
30636
+ const snapshot = await (async () => {
30637
+ try {
30638
+ return await this.deps.posture?.prepare() ?? null;
30639
+ } catch {
30640
+ return null;
30641
+ }
30642
+ })();
30643
+ if (snapshot) {
30644
+ try {
30645
+ await withTimeout(
30646
+ this.deps.posture?.send(snapshot) ?? Promise.resolve(),
30647
+ REQUEST_TIMEOUT_MS
30648
+ );
30649
+ } catch {
30650
+ }
30651
+ }
30652
+ return resolved;
30653
+ }
30654
+ // The id is minted CLIENT-side and stored verbatim: the control plane does NOT
30655
+ // re-key it. `pgAuditValues` writes `id: event.id` and carries tenancy in
30656
+ // its own scoping columns, so the device and the forwarded copy
30657
+ // share one id space — which is what makes a re-post idempotent at all.
30658
+ //
30659
+ // Re-posts collapse via `onConflictDoUpdate` on the `id` PK, guarded by
30660
+ // `setWhere eventType = 'session'` (NOT onConflictDoNothing). That guard is
30661
+ // what makes an attached retry safe: a capture-stubbed session row can still
30662
+ // be HEALED by the authoritative root, while a duplicate non-session event —
30663
+ // a retried tool_call, exactly this path — can never stomp a populated row.
30664
+ async recordAuditEvent(event) {
30665
+ await this.deps.local.recordAuditEvent(event);
30666
+ await this.deps.forward.run(
30667
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
30668
+ );
30669
+ }
30670
+ // Attached `llm_call` is written locally by the inner gateway, then routed to
30671
+ // the control plane through the existing `recordAuditEvent` ingest (no dedicated
30672
+ // client method yet) by pre-building the audit event from the natural key.
30673
+ // The forward goes DIRECTLY to the client rather than through this.recordAuditEvent,
30674
+ // which would write the event to the local store a second time.
30675
+ async recordLlmCall(input) {
30676
+ await this.deps.local.recordLlmCall(input);
30677
+ await this.deps.forward.run(
30678
+ () => this.deps.client.recordAuditEvent(
30679
+ reKeyForForward(llmAuditEvent(input), this.remoteInventory)
30680
+ )
30681
+ );
30682
+ }
30683
+ /**
30684
+ * Forward one batch, item by item, under ONE aggregate deadline.
30685
+ *
30686
+ * Per-item budgets bound each request and nothing bounded their sum — see
30687
+ * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
30688
+ * rather than sent: the local write has already succeeded, so every caller
30689
+ * has a correct result to return, and a drop is the outcome this path is
30690
+ * built to accept (G8) where a blown hook timeout is not.
30691
+ *
30692
+ * Serial rather than concurrent on purpose. Firing N requests at once would
30693
+ * trade a latency problem for a burst the plane's own per-key rate limiting
30694
+ * would answer with the refusals the breaker then counts.
30695
+ *
30696
+ * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
30697
+ * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
30698
+ * lets status call the forward unhealthy; this path returns BEFORE `run` is
30699
+ * reached, so without the tally in `forward-drops.ts` a slow-but-answering
30700
+ * plane produces no failures, keeps the breaker closed, renders a healthy
30701
+ * block, and discards the tail of every batch indefinitely.
30702
+ */
30703
+ async forwardBatch(inputs, toEvent) {
30704
+ const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
30705
+ for (let i = 0; i < inputs.length; i += 1) {
30706
+ const now = Date.now();
30707
+ if (now >= deadline) {
30708
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
30709
+ return;
30710
+ }
30711
+ const input = inputs[i];
30712
+ await this.deps.forward.run(
30713
+ () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input), this.remoteInventory))
30714
+ );
30715
+ }
30716
+ }
30717
+ // Delegated as a BATCH rather than looped over recordLlmCall: the inner
30718
+ // gateway may write the whole batch in one local transaction, and looping
30719
+ // here would replace that with N separate local writes.
30720
+ async recordLlmCalls(inputs) {
30721
+ await this.deps.local.recordLlmCalls(inputs);
30722
+ await this.forwardBatch(inputs, (input) => llmAuditEvent(input));
30723
+ }
30724
+ // `input.inspections` (secrets detected client-side in the tool's masked
30725
+ // target) ride along on the request's `inspections` field — the control plane
30726
+ // persists each as an inspection_findings row linked to this audit event
30727
+ // (see RecordAuditEventRequest in @akasecurity/schema). The masked
30728
+ // `target` already rides `input.attributes`, so no raw secret leaks either
30729
+ // way — this only stops the FINDING row itself from being dropped.
30730
+ async recordToolCalls(inputs) {
30731
+ await this.deps.local.recordToolCalls(inputs);
30732
+ await this.forwardBatch(inputs, (input) => toolAuditEvent(input));
30733
+ }
30734
+ // Forwarded as a `config_scan` audit event: there is no dedicated
30735
+ // config-scan ingest endpoint, and the audit-event door is the one the
30736
+ // control plane already opens for client-minted, idempotent records.
30737
+ //
30738
+ // ONLY `scanEvent` CROSSES, and unlike `recordCapture` the plane cannot
30739
+ // re-derive the rest. A `ConfigScanRecord` is four things committed together
30740
+ // locally — the inventory `items`, this audit event, and the posture
30741
+ // `definitions`/`findings` that reference it — and three of them stay on the
30742
+ // device. Say that plainly rather than let the asymmetry with `recordCapture`
30743
+ // read as the same argument: there, findings are omitted BECAUSE the plane
30744
+ // re-derives them from `Event.content`; here there is no content to re-derive
30745
+ // from, so what is omitted is simply not sent.
30746
+ //
30747
+ // That is the wire contract as it stands rather than an oversight to patch
30748
+ // here. `items` has no route at all, and `RecordAuditEventRequest.inspections`
30749
+ // is documented as tool-call findings — widening it to carry config-scan
30750
+ // findings is an egress change (a posture finding's `maskedMatch` holds the
30751
+ // matched command) and a decision about what an attached deployment is
30752
+ // entitled to, not a bug fix. An attached machine's config posture therefore
30753
+ // reaches the plane as the event only; the dashboard's own view of it is the
30754
+ // local store.
30755
+ async recordConfigScan(record2) {
30756
+ await this.deps.local.recordConfigScan(record2);
30757
+ await this.deps.forward.run(
30758
+ () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
30759
+ );
30760
+ }
30761
+ async recordBlockedDetection(entry) {
30762
+ return this.deps.local.recordBlockedDetection(entry);
30763
+ }
30764
+ /**
30765
+ * LOCAL-ONLY, deliberately. The shares API is read-plus-decision-override
30766
+ * with no egress ingest endpoint, so there is nothing to forward to; adding a
30767
+ * forward here would be inventing a wire contract that does not exist. The
30768
+ * local write is the whole operation, and its summary is the real one — the
30769
+ * scanner reads a throw as a FAILED WRITE and skips its ledger commit, so
30770
+ * returning the inner gateway's result keeps the retry semantics honest.
30771
+ */
30772
+ async recordProjectEgress(input) {
30773
+ return this.deps.local.recordProjectEgress(input);
30774
+ }
30775
+ // ---------------------------------------------------------------------
30776
+ // Reads and device-local ledgers: pure delegation.
30777
+ // ---------------------------------------------------------------------
30778
+ async configInventoryReport() {
30779
+ return this.deps.local.configInventoryReport();
30780
+ }
30781
+ async readSessionProvider(sessionId) {
30782
+ return this.deps.local.readSessionProvider(sessionId);
30783
+ }
30784
+ async facets() {
30785
+ return this.deps.local.facets();
30786
+ }
30787
+ /**
30788
+ * Delegated UNMODIFIED — including its refusals.
30789
+ *
30790
+ * This is a fail-secure boundary: it decides whether an approved exception
30791
+ * lets a blocked action through. Under local-first the local store owns the
30792
+ * exception ledger, so the honest answer is whatever it says; wrapping this
30793
+ * in a fallback (`catch { return true }`, or defaulting on a timeout) would
30794
+ * turn a store error into a granted bypass. If the inner gateway rejects,
30795
+ * this rejects, and the runtime's own handling decides — which is asserted
30796
+ * end-to-end through runtime.capture rather than here.
30797
+ */
30798
+ async consumeException(id) {
30799
+ return this.deps.local.consumeException(id);
30800
+ }
30801
+ async recentFindings(opts) {
30802
+ return this.deps.local.recentFindings(opts);
30803
+ }
30804
+ async healthSummary() {
30805
+ return this.deps.local.healthSummary();
30806
+ }
30807
+ async activityByDay(days) {
30808
+ return this.deps.local.activityByDay(days);
30809
+ }
30810
+ async tokenReports() {
30811
+ return this.deps.local.tokenReports();
30812
+ }
30813
+ async knownContentHashes() {
30814
+ return this.deps.local.knownContentHashes();
30815
+ }
30816
+ async scanLedger(rulesetHash) {
30817
+ return this.deps.local.scanLedger(rulesetHash);
30818
+ }
30819
+ async recordScanned(entries) {
30820
+ return this.deps.local.recordScanned(entries);
30821
+ }
30822
+ async getRuleProbeVerdict(ruleKey) {
30823
+ return this.deps.local.getRuleProbeVerdict(ruleKey);
30824
+ }
30825
+ async setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2) {
30826
+ return this.deps.local.setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2);
30827
+ }
30828
+ async openAtRestKeysForPath(path) {
30829
+ return this.deps.local.openAtRestKeysForPath(path);
30830
+ }
30831
+ async resolvedAtRestKeysForPath(path) {
30832
+ return this.deps.local.resolvedAtRestKeysForPath(path);
30833
+ }
30834
+ async insertResolution(input) {
30835
+ return this.deps.local.insertResolution(input);
30836
+ }
30837
+ async close() {
30838
+ return this.deps.local.close();
30839
+ }
30840
+ // ---------------------------------------------------------------------
30841
+ // Policy
30842
+ // ---------------------------------------------------------------------
30843
+ async getPolicyBundle() {
30844
+ const local = await this.deps.local.getPolicyBundle();
30845
+ const cached2 = await (async () => {
30846
+ try {
30847
+ return await this.deps.readCachedBundle();
30848
+ } catch {
30849
+ return null;
30850
+ }
30851
+ })();
30852
+ if (cached2 === null) return local;
30853
+ const byRuleId = /* @__PURE__ */ new Map();
30854
+ for (const rule of [...local.rules ?? [], ...cached2.rules ?? []]) {
30855
+ if (!byRuleId.has(rule.id)) byRuleId.set(rule.id, rule);
30856
+ }
30857
+ const rules = [...byRuleId.values()];
30858
+ return {
30859
+ ...local,
30860
+ // The remote version identifies the composed bundle for the poller.
30861
+ version: cached2.version,
30862
+ rules,
30863
+ policies: mergeRaiseOnly(
30864
+ local.policies,
30865
+ cached2.policies,
30866
+ ruleCategoryMap(cached2.rules, local.rules)
30867
+ ),
30868
+ customKeywords: [...local.customKeywords, ...cached2.customKeywords]
30869
+ // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
30870
+ // snapshot) and is taken from the LOCAL bundle only — never from the wire
30871
+ // or the on-disk cache. Honoring a cached one would hand the control plane, or
30872
+ // anything able to write policy-cache.json, a kill-switch over the
30873
+ // compiled-in bundled packs: `{ rulesComplete: true, rules: [] }` would
30874
+ // zero local detection. Spread from `local` above, and deliberately not
30875
+ // re-read from `cached` here.
30876
+ //
30877
+ // THREE MORE OF THE CACHED BUNDLE'S FIELDS ARE DROPPED, each on purpose,
30878
+ // and each named here so a reader can tell a decision from an omission:
30879
+ //
30880
+ // `exceptions` — an exception SUPPRESSES a detection, so honoring
30881
+ // one from an unsigned on-disk cache would let
30882
+ // anything able to write that file turn rules off.
30883
+ // Every other field this merge accepts can only
30884
+ // RAISE enforcement; this is the one that cannot,
30885
+ // so it stays local-only until the bundle is
30886
+ // signed. Exceptions remain a device-local ledger.
30887
+ // `reversibleRuleIds` — the Redact & Vault archetype makes a redaction
30888
+ // recoverable, which is a CUSTODY change: it puts
30889
+ // the detected value in the local vault instead of
30890
+ // destroying it. Taking that instruction from the
30891
+ // cache would let a remote party turn one-way
30892
+ // redaction into retention. Dropping it keeps the
30893
+ // one-way behaviour, which the schema itself calls
30894
+ // "the safe direction to default".
30895
+ // `ruleVersions` — remote rules fall back to their own spec version.
30896
+ // Cosmetic rather than protective: it only affects
30897
+ // how a finding is version-attributed, and the two
30898
+ // sides may therefore attribute org rules
30899
+ // differently. Worth carrying once there is a
30900
+ // reader that needs it; nothing reads it today.
30901
+ };
30902
+ }
30903
+ // ---------------------------------------------------------------------
30904
+ // LocalStoreMaintenance — by delegation (D3).
30905
+ //
30906
+ // Implementing these is what actually closes the skipped-local-maintenance
30907
+ // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
30908
+ // any object carrying all five, so the composite qualifies and SessionStart
30909
+ // runs maintenance on the device's real store.
30910
+ //
30911
+ // ⚠ Two of the five are SYNCHRONOUS and must stay that way. `handle-session-start`
30912
+ // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
30913
+ // return value directly; declaring them `async` here would hand those call
30914
+ // sites a Promise and silently break both.
30915
+ // ---------------------------------------------------------------------
30916
+ async sweepTerminalExceptions(retentionMs) {
30917
+ return this.deps.local.sweepTerminalExceptions(retentionMs);
30918
+ }
30919
+ capWarnEraEnforcement(policyMode) {
30920
+ return this.deps.local.capWarnEraEnforcement(policyMode);
30921
+ }
30922
+ async recordProjectFiles(projectId, scan2) {
30923
+ return this.deps.local.recordProjectFiles(projectId, scan2);
30924
+ }
30925
+ async reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot) {
30926
+ return this.deps.local.reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot);
30927
+ }
30928
+ staleBinaryNotice(currentVersion) {
30929
+ return this.deps.local.staleBinaryNotice(currentVersion);
30930
+ }
30931
+ };
30932
+ function reKeyForForward(event, remote) {
30933
+ if (remote === null) {
30934
+ const stripped = { ...event };
30935
+ delete stripped.hostId;
30936
+ delete stripped.harnessId;
30937
+ delete stripped.sourceProjectId;
30938
+ return stripped;
30939
+ }
30940
+ const rekeyed = { ...event };
30941
+ delete rekeyed.hostId;
30942
+ delete rekeyed.harnessId;
30943
+ delete rekeyed.sourceProjectId;
30944
+ if (remote.hostId !== void 0) rekeyed.hostId = remote.hostId;
30945
+ if (remote.harnessId !== void 0) rekeyed.harnessId = remote.harnessId;
30946
+ if (remote.sourceProjectId !== void 0) rekeyed.sourceProjectId = remote.sourceProjectId;
30947
+ return rekeyed;
30948
+ }
30949
+ var BATCH_FORWARD_BUDGET_MS = 3e3;
30950
+ function llmAuditEvent(input) {
30951
+ return {
30952
+ id: llmCallId(input.sessionId, input.messageId),
30953
+ eventType: "llm_call",
30954
+ startedAt: input.startedAt,
30955
+ parentId: input.parentId,
30956
+ rootSessionId: input.rootSessionId,
30957
+ attributes: input.attributes
30958
+ };
30959
+ }
30960
+ function toolAuditEvent(input) {
30961
+ return {
30962
+ id: toolCallId(input.sessionId, input.toolUseId),
30963
+ eventType: "tool_call",
30964
+ startedAt: input.startedAt,
30965
+ parentId: input.parentId,
30966
+ rootSessionId: input.rootSessionId,
30967
+ attributes: input.attributes,
30968
+ inspections: input.inspections
30969
+ };
30970
+ }
30971
+
30972
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
30973
+ import { randomUUID as randomUUID16 } from "crypto";
30974
+ import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
30975
+ import { join as join19 } from "path";
30976
+
30977
+ // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
30978
+ import { rename as rename2 } from "fs/promises";
30979
+ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
30980
+ var ATTEMPTS = 5;
30981
+ var delay = (ms) => new Promise((resolve2) => {
30982
+ setTimeout(resolve2, ms);
30983
+ });
30984
+ async function publishByRename(tmp, file2, move = rename2) {
30985
+ for (let attempt = 1; ; attempt += 1) {
30986
+ try {
30987
+ await move(tmp, file2);
30988
+ return;
30989
+ } catch (err) {
30990
+ const code = err.code;
30991
+ if (attempt >= ATTEMPTS || code === void 0 || !RETRYABLE.has(code)) throw err;
30992
+ await delay(attempt * 10);
30993
+ }
30994
+ }
30995
+ }
30996
+
30997
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
30998
+ function createPolicyStore(dir = dataDir()) {
30999
+ const file2 = join19(dir, "policy-cache.json");
31000
+ async function read() {
31001
+ try {
31002
+ const raw = await readFile2(file2, "utf8");
31003
+ const parsed2 = JSON.parse(raw);
31004
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
31005
+ const record2 = parsed2;
31006
+ const bundle = PolicyBundle.parse(record2.bundle);
31007
+ const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
31008
+ const etag = typeof record2.etag === "string" ? record2.etag : void 0;
31009
+ return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
31010
+ } catch {
31011
+ return null;
31012
+ }
31013
+ }
31014
+ async function write(bundle, etag) {
31015
+ await ensureDataDir(dir);
31016
+ const stored = {
31017
+ bundle,
31018
+ fetchedAtMs: Date.now(),
31019
+ ...etag === void 0 ? {} : { etag }
31020
+ };
31021
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
31022
+ try {
31023
+ await writeFile2(tmp, JSON.stringify(stored), {
31024
+ encoding: "utf8",
31025
+ mode: DATA_FILE_MODE,
31026
+ flag: "wx"
31027
+ });
31028
+ await publishByRename(tmp, file2);
31029
+ } catch (err) {
31030
+ await rm(tmp, { force: true }).catch(() => void 0);
31031
+ throw err;
31032
+ }
31033
+ }
31034
+ return { read, write, file: file2 };
31035
+ }
31036
+
31037
+ // ../../packages/remote/src/http.ts
31038
+ import { request as httpRequest } from "http";
31039
+ import { request as httpsRequest } from "https";
31040
+ var DEFAULT_TIMEOUT_MS = 1e4;
31041
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
31042
+ var RemoteRequestError = class extends Error {
31043
+ constructor(status) {
31044
+ super(`control-plane request failed with status ${String(status)}`);
31045
+ this.status = status;
31046
+ this.name = "RemoteRequestError";
31047
+ }
31048
+ status;
31049
+ };
31050
+ var RemoteRequestInvalid = class extends Error {
31051
+ constructor(route, cause) {
31052
+ super(`refusing to send a malformed body to ${route}`);
31053
+ this.cause = cause;
31054
+ this.name = "RemoteRequestInvalid";
31055
+ }
31056
+ cause;
31057
+ };
31058
+ var RemoteResponseInvalid = class extends Error {
31059
+ constructor(route, detail) {
31060
+ super(`control plane answered ${route} with ${detail}`);
31061
+ this.name = "RemoteResponseInvalid";
31062
+ }
31063
+ };
31064
+ var RemoteTransportError = class extends Error {
31065
+ /**
31066
+ * The status the peer sent, when headers arrived and only the BODY was
31067
+ * refused.
31068
+ *
31069
+ * Undefined for the ordinary case this class was written for — no answer at
31070
+ * all. It exists because two paths reject after a status has already been
31071
+ * delivered: an oversized body and an aborted response. Discarding it there
31072
+ * reported a deployment answering 401 with a verbose body as a network
31073
+ * outage, which sends the reader to look at their network instead of their
31074
+ * credential.
31075
+ */
31076
+ constructor(reason, status) {
31077
+ super(`control-plane request did not complete: ${reason}`);
31078
+ this.status = status;
31079
+ this.name = "RemoteTransportError";
31080
+ }
31081
+ status;
31082
+ };
31083
+ async function send(options) {
31084
+ const url2 = new URL(options.url);
31085
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
31086
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
31087
+ const requestOptions = {
31088
+ method: options.method,
31089
+ headers: {
31090
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
31091
+ // last they win, and two of the values below are ones no caller may
31092
+ // replace: `x-api-key` is the credential, and `content-length` is the
31093
+ // byte count that stops a multi-byte body being truncated by the
31094
+ // receiver. `SendOptions.headers` is a free-form record on an exported
31095
+ // function, so "no caller does that today" is not the guarantee to rely
31096
+ // on. The one header any caller actually passes — `if-none-match` on the
31097
+ // conditional GET — is untouched by this order.
31098
+ ...options.headers,
31099
+ // The credential. One header, matching what the deployment authenticates
31100
+ // on; a second copy in an `Authorization` header would be one more place
31101
+ // it can be logged by an intermediary for no gain.
31102
+ "x-api-key": options.apiKey,
31103
+ accept: "application/json",
31104
+ ...options.body === void 0 ? {} : {
31105
+ "content-type": "application/json",
31106
+ // Byte length, not string length: a multi-byte body sent with a
31107
+ // character count is truncated by the receiver.
31108
+ "content-length": String(Buffer.byteLength(options.body))
31109
+ }
31110
+ }
31111
+ };
31112
+ return new Promise((resolve2, reject) => {
31113
+ let settled = false;
31114
+ const fail = (reason, status) => {
31115
+ if (settled) return;
31116
+ settled = true;
31117
+ reject(new RemoteTransportError(reason, status));
31118
+ };
31119
+ const req = send_(url2, requestOptions, (res) => {
31120
+ const chunks = [];
31121
+ let size = 0;
31122
+ res.on("data", (chunk) => {
31123
+ size += chunk.length;
31124
+ if (size > MAX_RESPONSE_BYTES) {
31125
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
31126
+ res.destroy();
31127
+ req.destroy();
31128
+ return;
31129
+ }
31130
+ chunks.push(chunk);
31131
+ });
31132
+ res.on("aborted", () => {
31133
+ fail("the response was aborted", res.statusCode);
31134
+ });
31135
+ res.on("end", () => {
31136
+ if (settled) return;
31137
+ settled = true;
31138
+ resolve2({
31139
+ status: res.statusCode ?? 0,
31140
+ headers: res.headers,
31141
+ body: Buffer.concat(chunks).toString("utf8")
31142
+ });
31143
+ });
31144
+ });
31145
+ const deadline = setTimeout(() => {
31146
+ fail(`no response within ${String(timeoutMs)}ms`);
31147
+ req.destroy();
31148
+ }, timeoutMs);
31149
+ deadline.unref();
31150
+ req.on("upgrade", (_res, socket) => {
31151
+ fail("the deployment answered with a protocol upgrade");
31152
+ socket.destroy();
31153
+ });
31154
+ req.on("close", () => {
31155
+ fail("the connection closed before a response was read");
31156
+ clearTimeout(deadline);
31157
+ });
31158
+ req.on("error", (err) => {
31159
+ fail(err.message);
31160
+ });
31161
+ if (options.body !== void 0) req.write(options.body);
31162
+ req.end();
31163
+ });
31164
+ }
31165
+
31166
+ // ../../packages/remote/src/client.ts
31167
+ var ROUTES = {
31168
+ events: "/v1/events",
31169
+ auditEvents: "/v1/audit-events",
31170
+ inventory: "/v1/inventory",
31171
+ storePosture: "/v1/store-posture",
31172
+ policyBundle: "/v1/policy-bundle",
31173
+ whoami: "/v1/plugin/whoami"
31174
+ };
31175
+ function headerValue(response, name) {
31176
+ const raw = response.headers[name];
31177
+ if (raw === void 0) return void 0;
31178
+ return Array.isArray(raw) ? raw[0] : raw;
31179
+ }
31180
+ function okBody(response) {
31181
+ if (response.status < 200 || response.status >= 300) {
31182
+ throw new RemoteRequestError(response.status);
31183
+ }
31184
+ return response.body;
31185
+ }
31186
+ function parsed(schema, body, route) {
31187
+ let json2;
31188
+ try {
31189
+ json2 = JSON.parse(body);
31190
+ } catch {
31191
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
31192
+ }
31193
+ const result = schema.safeParse(json2);
31194
+ if (!result.success) {
31195
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
31196
+ }
31197
+ return result.data;
31198
+ }
31199
+ function withoutTrailingSlashes(endpoint) {
31200
+ let end = endpoint.length;
31201
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
31202
+ return endpoint.slice(0, end);
31203
+ }
31204
+ var SLASH = "/".charCodeAt(0);
31205
+ function createRemoteClient(options) {
31206
+ const base = withoutTrailingSlashes(options.endpoint);
31207
+ const url2 = (route) => `${base}${route}`;
31208
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
31209
+ return {
31210
+ async ingestEvents(batch) {
31211
+ const response = await send({
31212
+ ...common,
31213
+ method: "POST",
31214
+ url: url2(ROUTES.events),
31215
+ body: JSON.stringify(batch)
31216
+ });
31217
+ return parsed(IngestAck, okBody(response), ROUTES.events);
31218
+ },
31219
+ async ingestInventory(context) {
31220
+ const response = await send({
31221
+ ...common,
31222
+ method: "POST",
31223
+ url: url2(ROUTES.inventory),
31224
+ body: JSON.stringify(context)
31225
+ });
31226
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
31227
+ },
31228
+ async recordAuditEvent(event) {
31229
+ const validated = RecordAuditEventRequest.safeParse(event);
31230
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
31231
+ const submission = validated.data;
31232
+ const response = await send({
31233
+ ...common,
31234
+ method: "POST",
31235
+ url: url2(ROUTES.auditEvents),
31236
+ body: JSON.stringify(submission)
31237
+ });
31238
+ okBody(response);
31239
+ },
31240
+ async reportStorePosture(snapshot) {
31241
+ const response = await send({
31242
+ ...common,
31243
+ method: "POST",
31244
+ url: url2(ROUTES.storePosture),
31245
+ body: JSON.stringify(snapshot)
31246
+ });
31247
+ okBody(response);
31248
+ },
31249
+ async getPolicyBundle(etag) {
31250
+ const response = await send({
31251
+ ...common,
31252
+ method: "GET",
31253
+ url: url2(ROUTES.policyBundle),
31254
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
31255
+ });
31256
+ if (response.status === 304) {
31257
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
31258
+ }
31259
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
31260
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
31261
+ },
31262
+ async whoami() {
31263
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
31264
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
31265
+ }
31266
+ };
31267
+ }
31268
+
31269
+ // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
31270
+ var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
31271
+ function createPostureReporter(deps) {
31272
+ async function prepare() {
31273
+ try {
31274
+ const state = await withTimeout(deps.store.read(), REQUEST_TIMEOUT_MS);
31275
+ if (state === null) return null;
31276
+ const nowMs = deps.now();
31277
+ const elapsed = nowMs - state.lastAttemptedAtMs;
31278
+ if (elapsed >= 0 && elapsed < POSTURE_REPORT_INTERVAL_MS) return null;
31279
+ try {
31280
+ await withTimeout(deps.store.markAttempted(state.deviceId, nowMs), REQUEST_TIMEOUT_MS);
31281
+ } catch {
31282
+ }
31283
+ const { readError, ...measurement } = deps.readStore();
31284
+ if (readError) return null;
31285
+ let plugin;
31286
+ try {
31287
+ plugin = await deps.pluginBlock?.();
31288
+ } catch {
31289
+ plugin = void 0;
31290
+ }
31291
+ return {
31292
+ deviceId: state.deviceId,
31293
+ hostname: deps.hostname(),
31294
+ capturedAt: nowMs,
31295
+ ...measurement,
31296
+ // Omit the key rather than spread an explicit `undefined` —
31297
+ // exactOptionalPropertyTypes distinguishes the two, and the bridge in
31298
+ // factory.ts keys on presence.
31299
+ ...plugin === void 0 ? {} : { plugin }
31300
+ };
31301
+ } catch {
31302
+ return null;
31303
+ }
31304
+ }
31305
+ async function send2(snapshot) {
31306
+ try {
31307
+ await deps.report(snapshot);
31308
+ } catch {
31309
+ }
31310
+ }
31311
+ return { prepare, send: send2 };
31312
+ }
31313
+
31314
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31315
+ import { statSync as statSync9 } from "fs";
31316
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
31317
+
31318
+ // ../../packages/plugin-runtime/src/attached/action-counts.ts
31319
+ function emptyActionCounts() {
31320
+ return Object.fromEntries(ACTION_TAKEN_KEYS.map((a) => [a, 0]));
31321
+ }
31322
+ function isActionTaken(value) {
31323
+ return ACTION_TAKEN_KEYS.includes(value);
31324
+ }
31325
+
31326
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31327
+ var CAPTURE_EVENT_TYPES_SQL2 = `('prompt','response','code_change','tool_use')`;
31328
+ function isSchemaAbsent(err) {
31329
+ return err instanceof Error && /no such table/i.test(err.message);
31330
+ }
31331
+ function emptyReadout(readError = false) {
31332
+ const byAction = emptyActionCounts();
31333
+ return {
31334
+ storePresent: false,
31335
+ schemaVersion: null,
31336
+ findingsTotal: 0,
31337
+ findingsFirstAt: null,
31338
+ findingsLastAt: null,
31339
+ packs: [],
31340
+ policyCounts: { total: 0, disabled: 0, byAction },
31341
+ readError
31342
+ };
31343
+ }
31344
+ function readStorePosture(dbPath2) {
31345
+ try {
31346
+ statSync9(dbPath2);
31347
+ } catch (err) {
31348
+ const code = err.code;
31349
+ if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
31350
+ return emptyReadout(true);
31351
+ }
31352
+ let db = null;
31353
+ let version2 = null;
31354
+ let packs2 = [];
31355
+ let policyCounts = {
31356
+ total: 0,
31357
+ disabled: 0,
31358
+ byAction: emptyActionCounts()
31359
+ };
31360
+ let findingsTotal = 0;
31361
+ let findingsFirstAt = null;
31362
+ let findingsLastAt = null;
31363
+ const currentReadout = () => ({
31364
+ storePresent: true,
31365
+ schemaVersion: version2,
31366
+ findingsTotal,
31367
+ findingsFirstAt,
31368
+ findingsLastAt,
31369
+ packs: packs2,
31370
+ policyCounts,
31371
+ readError: false
31372
+ });
31373
+ try {
31374
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
31375
+ db.exec("PRAGMA busy_timeout = 2000");
31376
+ version2 = db.prepare("PRAGMA user_version").get().user_version;
31377
+ try {
31378
+ const packRows = db.prepare(
31379
+ `SELECT namespace, pack_id, version, enabled, updated_at FROM installed_packs ORDER BY namespace, pack_id`
31380
+ ).all();
31381
+ packs2 = packRows.map((r) => ({
31382
+ packId: `${r.namespace}/${r.pack_id}`,
31383
+ version: r.version,
31384
+ enabled: r.enabled !== 0,
31385
+ updatedAt: r.updated_at == null ? null : String(r.updated_at)
31386
+ }));
31387
+ } catch (err) {
31388
+ if (!isSchemaAbsent(err)) throw err;
31389
+ }
31390
+ try {
31391
+ const policyRows = db.prepare(`SELECT action, enabled FROM policies`).all();
31392
+ const byAction = emptyActionCounts();
31393
+ let disabled = 0;
31394
+ for (const row of policyRows) {
31395
+ if (row.enabled === 0) disabled += 1;
31396
+ if (isActionTaken(row.action)) byAction[row.action] += 1;
31397
+ }
31398
+ policyCounts = { total: policyRows.length, disabled, byAction };
31399
+ } catch (err) {
31400
+ if (!isSchemaAbsent(err)) throw err;
31401
+ }
31402
+ try {
31403
+ const agg = db.prepare(
31404
+ `SELECT count(*) AS n, min(f.first_detected_at) AS firstAt, max(f.first_detected_at) AS lastAt
31405
+ FROM inspection_findings f JOIN audit_events e ON e.id = f.audit_event_id
31406
+ WHERE e.event_type IN ${CAPTURE_EVENT_TYPES_SQL2}`
31407
+ ).get();
31408
+ findingsTotal = agg.n;
31409
+ findingsFirstAt = agg.firstAt;
31410
+ findingsLastAt = agg.lastAt;
31411
+ } catch (err) {
31412
+ if (!isSchemaAbsent(err)) throw err;
31413
+ }
31414
+ return currentReadout();
31415
+ } catch {
31416
+ return emptyReadout(true);
31417
+ } finally {
31418
+ try {
31419
+ db?.close();
31420
+ } catch {
31421
+ }
31422
+ }
31423
+ }
31424
+
31425
+ // ../../packages/plugin-runtime/src/attached/posture-store.ts
31426
+ import { randomUUID as randomUUID17 } from "crypto";
31427
+ import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
31428
+ import { join as join20 } from "path";
31429
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
31430
+ function createPostureStore(dir = settingsDir(), legacyDir) {
31431
+ const file2 = join20(dir, "posture-state.json");
31432
+ const legacyFile = legacyDir === void 0 ? null : join20(legacyDir, "posture-state.json");
31433
+ async function persist(state) {
31434
+ await ensureDataDir(dir);
31435
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
31436
+ try {
31437
+ await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
31438
+ await publishByRename(tmp, file2);
31439
+ } catch (err) {
31440
+ await rm2(tmp, { force: true }).catch(() => void 0);
31441
+ throw err;
31442
+ }
31443
+ }
31444
+ async function readFrom(path) {
31445
+ let raw;
31446
+ try {
31447
+ raw = await readFile3(path, "utf8");
31448
+ } catch (err) {
31449
+ const code = err.code;
31450
+ if (code === "ENOENT" || code === "ENOTDIR") return null;
31451
+ throw err;
31452
+ }
31453
+ try {
31454
+ const parsed2 = JSON.parse(raw);
31455
+ if (typeof parsed2 === "object" && parsed2 !== null) {
31456
+ const record2 = parsed2;
31457
+ if (typeof record2.deviceId === "string" && UUID_RE.test(record2.deviceId)) {
31458
+ const stamp = typeof record2.lastAttemptedAtMs === "number" ? record2.lastAttemptedAtMs : typeof record2.lastReportedAtMs === "number" ? record2.lastReportedAtMs : 0;
31459
+ return { deviceId: record2.deviceId, lastAttemptedAtMs: stamp };
31460
+ }
31461
+ }
31462
+ } catch {
31463
+ }
31464
+ return null;
31465
+ }
31466
+ async function read() {
31467
+ const current = await readFrom(file2);
31468
+ if (current) return current;
31469
+ const legacy = legacyFile === null || legacyFile === file2 ? null : await readFrom(legacyFile).catch(() => null);
31470
+ if (legacy) {
31471
+ try {
31472
+ await persist(legacy);
31473
+ } catch {
31474
+ }
31475
+ return legacy;
31476
+ }
31477
+ const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
31478
+ try {
31479
+ await ensureDataDir(dir);
31480
+ if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
31481
+ } catch {
31482
+ return null;
31483
+ }
31484
+ const winner = await readFrom(file2).catch(() => null);
31485
+ if (winner) return winner;
31486
+ try {
31487
+ await persist(fresh);
31488
+ } catch {
31489
+ return null;
31490
+ }
31491
+ return fresh;
31492
+ }
31493
+ async function markAttempted(deviceId, atMs) {
31494
+ await persist({ deviceId, lastAttemptedAtMs: atMs });
31495
+ }
31496
+ return { read, markAttempted, file: file2 };
31497
+ }
31498
+
31499
+ // ../../packages/plugin-runtime/src/attached/sync-state.ts
31500
+ import { readFileSync as readFileSync13 } from "fs";
31501
+ import { join as join21 } from "path";
31502
+
31503
+ // ../../packages/plugin-runtime/src/attached/status.ts
31504
+ var REFUSAL_LINES = {
31505
+ unauthorized: "KEY REJECTED \u2014 re-attach with a valid plugin key",
31506
+ forbidden: "ACCESS REFUSED \u2014 key is valid but not permitted; ask your org admin"
31507
+ };
31508
+ var OUTCOME_LINES = {
31509
+ ok: "policy synced",
31510
+ "not-modified": "policy up to date",
31511
+ unauthorized: REFUSAL_LINES.unauthorized,
31512
+ forbidden: REFUSAL_LINES.forbidden,
31513
+ unreachable: "control plane unreachable at last attempt",
31514
+ "invalid-bundle": "control plane sent a policy bundle this build cannot read"
31515
+ };
31516
+
31517
+ // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
31518
+ import { spawn } from "child_process";
31519
+ import { fileURLToPath as fileURLToPath2 } from "url";
31520
+ var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
31521
+
31522
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31523
+ import { hostname as hostname5 } from "os";
31524
+
31525
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
31526
+ import { randomUUID as randomUUID18 } from "crypto";
31527
+
31528
+ // ../../packages/plugin-runtime/src/recorder.ts
31529
+ var PLUGIN_RECORDER_BINARY = "plugin";
31530
+
31531
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
31532
+ var StandaloneDataGateway = class {
31533
+ db;
31534
+ // Kept for the fingerprint key lookup (exception.key lives beside the store).
31535
+ dataDir;
31536
+ // One notice per gateway — see warnRulesetDiscarded.
31537
+ warnedRulesetDiscarded = false;
31538
+ constructor(dataDir2, detections = [], meta3) {
31539
+ this.db = openLocalDatabase(dataDir2);
31540
+ this.dataDir = dataDir2;
31541
+ this.db.installedPacks.recordInventory(detections, meta3);
31542
+ }
31543
+ recordCapture(record2) {
31544
+ this.db.recordCapture(record2.event, record2.findings);
31545
+ return Promise.resolve();
31546
+ }
31547
+ ensureInventory(ctx) {
31548
+ return Promise.resolve(this.db.ensureInventory(ctx));
31549
+ }
31550
+ recordAuditEvent(event) {
31551
+ this.db.auditEvents.insertAuditEvent(event);
31552
+ return Promise.resolve();
31553
+ }
31554
+ // The id is minted inside the repository from the natural key — the plugin can't
31555
+ // import @akasecurity/persistence to compute it, so the gateway is the boundary that
31556
+ // hands the natural key across. UPSERT-take-MAX → idempotent re-reads that also
31557
+ // converge a streaming partial/final split (see insertLlmCall).
31558
+ recordLlmCall(input) {
31559
+ this.db.auditEvents.insertLlmCall(input);
31560
+ return Promise.resolve();
31561
+ }
31562
+ // One reconcile pass = one transaction. All leaves commit together
30081
31563
  // (single lock + WAL fsync); a contended SQLITE_BUSY rolls back and rejects so the
30082
31564
  // reconciler drops the whole pass and recovers it idempotently on the next read.
30083
31565
  recordLlmCalls(inputs) {
30084
31566
  if (inputs.length === 0) return Promise.resolve();
30085
- return new Promise((resolve, reject) => {
31567
+ return new Promise((resolve2, reject) => {
30086
31568
  try {
30087
31569
  this.db.auditEvents.runInTransaction(() => {
30088
31570
  for (const input of inputs) this.db.auditEvents.insertLlmCall(input);
30089
31571
  });
30090
- resolve();
31572
+ resolve2();
30091
31573
  } catch (err) {
30092
31574
  reject(err instanceof Error ? err : new Error(String(err)));
30093
31575
  }
@@ -30099,12 +31581,12 @@ var StandaloneDataGateway = class {
30099
31581
  // drops the whole pass and recovers it idempotently next time.
30100
31582
  recordToolCalls(inputs) {
30101
31583
  if (inputs.length === 0) return Promise.resolve();
30102
- return new Promise((resolve, reject) => {
31584
+ return new Promise((resolve2, reject) => {
30103
31585
  try {
30104
31586
  this.db.auditEvents.runInTransaction(() => {
30105
31587
  for (const input of inputs) this.writeToolCall(input);
30106
31588
  });
30107
- resolve();
31589
+ resolve2();
30108
31590
  } catch (err) {
30109
31591
  reject(err instanceof Error ? err : new Error(String(err)));
30110
31592
  }
@@ -30246,7 +31728,7 @@ var StandaloneDataGateway = class {
30246
31728
  const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
30247
31729
  const installed = this.installedScanRules();
30248
31730
  const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
30249
- id: randomUUID15(),
31731
+ id: randomUUID18(),
30250
31732
  scope: "global",
30251
31733
  target: { ruleId },
30252
31734
  action,
@@ -30400,19 +31882,66 @@ var StandaloneDataGateway = class {
30400
31882
  }
30401
31883
  };
30402
31884
 
31885
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31886
+ function resolveGatewayForConfig(config2, meta3) {
31887
+ const local = new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
31888
+ try {
31889
+ if (!isAttached(config2.settings)) return local;
31890
+ const connection = config2.settings.controlPlane;
31891
+ if (connection === void 0) return local;
31892
+ const state = readControlPlaneCredentialState(config2.settingsDir, connection);
31893
+ if (!state.usable) return local;
31894
+ const client = createRemoteClient({
31895
+ endpoint: connection.endpoint,
31896
+ apiKey: state.credential.apiKey
31897
+ });
31898
+ const store = createPolicyStore(config2.dataDir);
31899
+ const postureStore = createPostureStore(config2.settingsDir, config2.dataDir);
31900
+ const forward = createForwardPolicy({ dir: config2.dataDir });
31901
+ return new AttachedDataGateway({
31902
+ local,
31903
+ client,
31904
+ dataDir: config2.dataDir,
31905
+ readCachedBundle: () => store.read().then((cached2) => cached2?.bundle ?? null),
31906
+ forward,
31907
+ posture: createPostureReporter({
31908
+ // THROUGH THE BREAKER, and wrapped HERE rather than around
31909
+ // `PostureReporter.send`. The reporter swallows every error by
31910
+ // contract, so a wrap outside it would hand `forward.run` a resolved
31911
+ // promise for a send that failed — recording a SUCCESS, clearing
31912
+ // `consecutiveFailures` and `lastFailure`, and telling `aka status` the
31913
+ // forward recovered when nothing did. Wrapping the raw client call puts
31914
+ // the breaker above the swallow, where it can see the truth.
31915
+ //
31916
+ // What it buys: once the breaker is open — the plane already confirmed
31917
+ // down by the gateway's own writes — this stops paying a request
31918
+ // timeout per throttle interval to re-learn it.
31919
+ report: (snapshot) => forward.run(() => client.reportStorePosture(snapshot)).then(() => void 0),
31920
+ store: postureStore,
31921
+ readStore: () => readStorePosture(config2.dbPath),
31922
+ hostname: () => hostname5(),
31923
+ now: () => Date.now()
31924
+ })
31925
+ });
31926
+ } catch {
31927
+ return local;
31928
+ }
31929
+ }
31930
+
30403
31931
  // ../../packages/plugin-runtime/src/resolve.ts
30404
- var standaloneGatewayFactory = (config2, meta3) => new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
30405
- var defaultGatewayFactory = standaloneGatewayFactory;
31932
+ var configuredGatewayFactory = (config2, meta3) => resolveGatewayForConfig(config2, meta3);
31933
+ var defaultGatewayFactory = configuredGatewayFactory;
30406
31934
  function resolveDataGateway(config2, meta3, gatewayFactory = defaultGatewayFactory) {
30407
31935
  return gatewayFactory(config2, meta3);
30408
31936
  }
30409
31937
 
30410
31938
  // ../../packages/plugin-runtime/src/handle-session-start.ts
30411
- import { randomUUID as randomUUID16 } from "crypto";
31939
+ import { randomUUID as randomUUID19 } from "crypto";
30412
31940
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
30413
31941
 
30414
31942
  // src/hooks/store-health.ts
30415
31943
  var STORE_WARNING_MARKER = "store-warning-last-session";
31944
+ var STORE_REDIRECT_MARKER = "store-redirect-last-session";
30416
31945
  function openGatewayOrNull(config2) {
30417
31946
  try {
30418
31947
  return resolveDataGateway(config2);
@@ -30425,17 +31954,64 @@ function storeUnavailableMessage(dbPath2) {
30425
31954
  }
30426
31955
  function claimStoreUnavailableWarning(dataDir2, sessionId) {
30427
31956
  if (!sessionId) return true;
30428
- const path = join15(dataDir2, STORE_WARNING_MARKER);
30429
- try {
30430
- if (readFileSync10(path, "utf8") === sessionId) return false;
30431
- } catch {
31957
+ const dirs = markerDirs(dataDir2);
31958
+ if (alreadyClaimed(dirs, STORE_WARNING_MARKER, sessionId)) return false;
31959
+ recordClaim(dirs, STORE_WARNING_MARKER, sessionId);
31960
+ return true;
31961
+ }
31962
+ function markerDirs(dataDir2) {
31963
+ return [dataDir2, dirname5(dataDir2)];
31964
+ }
31965
+ function alreadyClaimed(dirs, marker, sessionId) {
31966
+ return dirs.some((dir) => {
31967
+ try {
31968
+ return readFileSync14(join22(dir, marker), "utf8") === sessionId;
31969
+ } catch {
31970
+ return false;
31971
+ }
31972
+ });
31973
+ }
31974
+ function recordClaim(dirs, marker, sessionId) {
31975
+ for (const dir of dirs) {
31976
+ try {
31977
+ mkdirSync4(dir, { recursive: true, mode: DATA_DIR_MODE });
31978
+ writeFileSync7(join22(dir, marker), sessionId, { mode: DATA_FILE_MODE });
31979
+ return;
31980
+ } catch {
31981
+ }
30432
31982
  }
31983
+ }
31984
+ function storeRedirectedMessage(paths, platform2 = process.platform) {
31985
+ const where = paths.map(({ path, target, holds, missing, mode }) => {
31986
+ if (missing) return `${path} -> ${target} (which does not exist; ${holds} cannot land there)`;
31987
+ const loose = mode !== void 0 && (mode & 63) !== 0 ? ", NOT owner-only" : "";
31988
+ const inherited = mode === void 0 ? "" : ` (${formatMode(mode)}${loose})`;
31989
+ return `${path} -> ${target}${inherited}, holding ${holds}`;
31990
+ }).join("; ");
31991
+ const subject = paths.length === 1 ? "a store path is a symlink" : `${String(paths.length)} store paths are symlinks`;
31992
+ const anyResolves = paths.some(({ missing }) => !missing);
31993
+ const lead = anyResolves ? `${subject}, so AKA is writing into the target instead: ${where}. ` : `${subject} resolving nowhere, so AKA cannot write there: ${where}. `;
31994
+ const kept = anyResolves && platform2 !== "win32" ? "Permissions are never changed through a symlink, so the store keeps whatever the target already had. " : "";
31995
+ return `[aka] ${lead}${kept}If you did not create that link, treat it as untrusted and run \`aka init\` for the full report.
31996
+ `;
31997
+ }
31998
+ function formatMode(mode) {
31999
+ return `0${mode.toString(8).padStart(3, "0")}`;
32000
+ }
32001
+ function warnIfStoreRedirected(config2, sessionId, write = (message) => void process.stderr.write(message)) {
30433
32002
  try {
30434
- mkdirSync4(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
30435
- writeFileSync7(path, sessionId, { mode: DATA_FILE_MODE });
32003
+ const paths = symlinkedStorePaths(dirname5(config2.dataDir));
32004
+ if (paths.length === 0) return;
32005
+ if (!sessionId) {
32006
+ write(storeRedirectedMessage(paths));
32007
+ return;
32008
+ }
32009
+ const dirs = markerDirs(config2.dataDir);
32010
+ if (alreadyClaimed(dirs, STORE_REDIRECT_MARKER, sessionId)) return;
32011
+ write(storeRedirectedMessage(paths));
32012
+ recordClaim(dirs, STORE_REDIRECT_MARKER, sessionId);
30436
32013
  } catch {
30437
32014
  }
30438
- return true;
30439
32015
  }
30440
32016
 
30441
32017
  // src/hooks/user-prompt-submit.ts
@@ -30445,6 +32021,7 @@ async function main() {
30445
32021
  if (prompt === void 0 || prompt === "") return;
30446
32022
  const config2 = loadConfig();
30447
32023
  const sessionId = input ? getString(input, "session_id") : void 0;
32024
+ warnIfStoreRedirected(config2, sessionId);
30448
32025
  const metadata = input ? baseMetadata(input) : void 0;
30449
32026
  const gateway = openGatewayOrNull(config2);
30450
32027
  if (gateway === null) {