@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
@@ -491,14 +491,31 @@ var require_ignore = __commonJS({
491
491
  }
492
492
  });
493
493
 
494
- // ../../packages/plugin-sdk/src/config.ts
495
- import { existsSync as existsSync5 } from "fs";
496
- import { join as join8 } from "path";
494
+ // ../../packages/plugin-runtime/src/attached/failure.ts
495
+ function statusOf(err) {
496
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
497
+ const { status } = err;
498
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
499
+ return status >= 100 && status <= 599 ? status : null;
500
+ }
501
+ function classifyFailure(err) {
502
+ switch (statusOf(err)) {
503
+ case 401:
504
+ return "unauthorized";
505
+ case 403:
506
+ return "forbidden";
507
+ default:
508
+ return "unreachable";
509
+ }
510
+ }
497
511
 
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";
512
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
513
+ import { readFileSync as readFileSync7 } from "fs";
514
+ import { join as join10 } from "path";
515
+
516
+ // ../../packages/persistence/src/control-plane-credential.ts
517
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync2, statSync } from "fs";
518
+ import { join } from "path";
502
519
 
503
520
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
504
521
  var SQLITE_MIGRATIONS = [
@@ -16202,6 +16219,125 @@ var ConfigScanRecord = external_exports.object({
16202
16219
  findings: external_exports.array(ConfigPostureFindingInput).optional()
16203
16220
  });
16204
16221
 
16222
+ // ../../packages/schema/src/zod/control-plane.ts
16223
+ var ATTACHED_CREDENTIAL_FILENAME = "control-plane-credential.json";
16224
+ var ATTACHED_CREDENTIAL_SPEC_VERSION = 1;
16225
+ var AttachedCredential = external_exports.object({
16226
+ specVersion: external_exports.literal(ATTACHED_CREDENTIAL_SPEC_VERSION),
16227
+ // The control-plane endpoint this credential was minted against.
16228
+ endpoint: external_exports.string().min(1),
16229
+ // The bearer credential itself. Never logged, never rendered — status
16230
+ // surfaces show `keyPrefix` and nothing else.
16231
+ apiKey: external_exports.string().min(1),
16232
+ // First few characters of the key, safe to display so a user can match the
16233
+ // credential against their organization's key list.
16234
+ keyPrefix: external_exports.string().min(1).max(16).optional(),
16235
+ mintedAt: external_exports.iso.datetime().optional()
16236
+ });
16237
+ var MAX_DATE_MS = 253402300799999;
16238
+ var MAX_INT4 = 2147483647;
16239
+ var StorePosturePack = external_exports.object({
16240
+ packId: external_exports.string().min(1),
16241
+ // 'namespace/packId'
16242
+ version: external_exports.string().min(1),
16243
+ enabled: external_exports.boolean(),
16244
+ // Stringified pass-through of the local store's `installed_packs.updated_at`
16245
+ // — the column format is store-version-dependent (epoch millis vs ISO), so
16246
+ // the wire shape assumes neither.
16247
+ updatedAt: external_exports.string().nullable()
16248
+ }).meta({ id: "StorePosturePack" });
16249
+ var StorePosturePolicyCounts = external_exports.object({
16250
+ total: external_exports.number().int().min(0),
16251
+ disabled: external_exports.number().int().min(0),
16252
+ // Exhaustive per-action map; the builder pre-fills every action with 0.
16253
+ //
16254
+ // Spelled out member-by-member rather than `z.record(ActionTaken, …)`. Zod
16255
+ // enforces exhaustiveness either way, but z.record emits `propertyNames` +
16256
+ // `additionalProperties` into a generated schema document, and a type
16257
+ // generator renders THAT with every key optional — a sender built against
16258
+ // the generated type would typecheck and still be rejected at runtime. An
16259
+ // explicit object emits `properties` + `required`, so generated types
16260
+ // demand all five.
16261
+ //
16262
+ // `satisfies Record<ActionTaken, …>` keeps the link to the enum: adding an
16263
+ // ActionTaken member is a COMPILE error here instead of silent drift.
16264
+ // `.strict()` is load-bearing — it rejects an unknown action key, which a
16265
+ // bare object would silently STRIP, accepting a miscounted map as valid.
16266
+ byAction: external_exports.object({
16267
+ warn: external_exports.number().int().min(0),
16268
+ redact: external_exports.number().int().min(0),
16269
+ block: external_exports.number().int().min(0),
16270
+ allow: external_exports.number().int().min(0),
16271
+ log: external_exports.number().int().min(0)
16272
+ }).strict()
16273
+ }).meta({ id: "StorePosturePolicyCounts" });
16274
+ var StorePosturePlugin = external_exports.object({
16275
+ /** Package name of the reporting plugin. */
16276
+ package: external_exports.string().min(1).max(200),
16277
+ version: external_exports.string().min(1).max(64),
16278
+ /** Version of the bundled core, when the build records one separately. */
16279
+ ossVersion: external_exports.string().max(64).nullable(),
16280
+ /**
16281
+ * `version` of the policy bundle this machine last fetched. Bounded at 200
16282
+ * rather than the 64 a bare sha256 hex digest needs today, so a later
16283
+ * format with an algorithm prefix does not start rejecting the channel.
16284
+ */
16285
+ policyBundleVersion: external_exports.string().max(200).nullable(),
16286
+ /** Epoch millis, on the CLIENT clock, of that fetch. */
16287
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
16288
+ }).meta({ id: "StorePosturePlugin" });
16289
+ var StorePostureSnapshot = external_exports.object({
16290
+ deviceId: external_exports.guid(),
16291
+ hostname: external_exports.string().min(1).max(253),
16292
+ // Epoch millis on the CLIENT clock. Bounded by what a receiving store
16293
+ // accepts (see MAX_DATE_MS), not by what a JavaScript Date can hold.
16294
+ capturedAt: external_exports.number().int().min(0).max(MAX_DATE_MS),
16295
+ // False is a measurement, not an error state: "no local store exists on
16296
+ // this machine".
16297
+ storePresent: external_exports.boolean(),
16298
+ schemaVersion: external_exports.number().int().min(0).max(MAX_INT4).nullable(),
16299
+ // PRAGMA user_version
16300
+ findingsTotal: external_exports.number().int().min(0).max(MAX_INT4),
16301
+ // Epoch millis, bounded like `capturedAt` — see MAX_DATE_MS on what that
16302
+ // bound does and does not do. Worth stating for these two specifically:
16303
+ // they are read from the local store's own ROWS rather than from this
16304
+ // machine's clock, so a damaged or hand-edited store is enough to produce
16305
+ // an out-of-range value with no clock skew involved.
16306
+ findingsFirstAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16307
+ findingsLastAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16308
+ packs: external_exports.array(StorePosturePack).max(500),
16309
+ policyCounts: StorePosturePolicyCounts,
16310
+ // OPTIONAL, not nullable: a reporter that predates this member keeps
16311
+ // getting its 200 without a payload change.
16312
+ plugin: StorePosturePlugin.optional()
16313
+ }).meta({ id: "StorePostureSnapshot" });
16314
+ var CAPTURE_VERSION_PREFIX = "capture/";
16315
+ var RecordAuditEventRequest = AuditEventInput.extend({
16316
+ inspections: external_exports.array(ToolCallInspection).default([])
16317
+ }).refine((v) => v.inspections.every((i) => !i.ruleVersion.startsWith(CAPTURE_VERSION_PREFIX)), {
16318
+ message: `inspections[].ruleVersion must not start with \`${CAPTURE_VERSION_PREFIX}\` \u2014 that namespace is reserved for capture definitions the control plane mints itself`,
16319
+ path: ["inspections"]
16320
+ }).meta({ id: "RecordAuditEventRequest" });
16321
+ var IngestAck = external_exports.object({
16322
+ accepted: external_exports.number().int().nonnegative(),
16323
+ duplicates: external_exports.number().int().nonnegative()
16324
+ });
16325
+ var PRINTABLE = /^[^\p{Cc}\p{Cf}]*$/u;
16326
+ var printable = (max) => external_exports.string().max(max).regex(PRINTABLE, "must not contain control characters");
16327
+ var PluginWhoami = external_exports.object({
16328
+ tenantName: printable(200),
16329
+ userEmail: printable(320),
16330
+ role: printable(64),
16331
+ keyKind: printable(64),
16332
+ serverTime: printable(64)
16333
+ });
16334
+ var ControlPlaneErrorBody = external_exports.object({
16335
+ error: external_exports.object({
16336
+ code: external_exports.string().optional(),
16337
+ message: external_exports.string().optional()
16338
+ }).optional()
16339
+ });
16340
+
16205
16341
  // ../../packages/schema/src/zod/registry.ts
16206
16342
  var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
16207
16343
  var PackId = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -16504,15 +16640,15 @@ function summaryToDetectionListItem(s) {
16504
16640
  }
16505
16641
  function rowToDetectionDetail(row, findingsLast30d, update) {
16506
16642
  const rules = row.rules.flatMap((r) => {
16507
- const parsed = Matcher.safeParse(r.matcher);
16508
- if (!parsed.success) return [];
16643
+ const parsed2 = Matcher.safeParse(r.matcher);
16644
+ if (!parsed2.success) return [];
16509
16645
  return [
16510
16646
  {
16511
16647
  id: r.id,
16512
16648
  name: r.name,
16513
16649
  category: r.category,
16514
16650
  severity: r.severity,
16515
- matcher: parsed.data
16651
+ matcher: parsed2.data
16516
16652
  }
16517
16653
  ];
16518
16654
  });
@@ -17158,8 +17294,8 @@ function toApiAction(dbVal) {
17158
17294
  }
17159
17295
  function toApiCategory(dbVal) {
17160
17296
  if (dbVal === "code_context") return "source_code";
17161
- const parsed = FindingCategory.safeParse(dbVal);
17162
- return parsed.success ? parsed.data : "custom";
17297
+ const parsed2 = FindingCategory.safeParse(dbVal);
17298
+ return parsed2.success ? parsed2.data : "custom";
17163
17299
  }
17164
17300
  function toApiProvider(sourceTool) {
17165
17301
  return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
@@ -17789,6 +17925,9 @@ var WorkspaceSettings = external_exports.object({
17789
17925
  function defaultWorkspaceSettings() {
17790
17926
  return WorkspaceSettings.parse({});
17791
17927
  }
17928
+ function isAttached(settings) {
17929
+ return settings.runMode === "attached" && settings.controlPlane !== void 0;
17930
+ }
17792
17931
  function toInventoryRow(input, id, now) {
17793
17932
  return {
17794
17933
  id,
@@ -18056,8 +18195,8 @@ function builtinPolicyIsReversible(id) {
18056
18195
  return BUILTIN_POLICY_SPECS[id].reversible;
18057
18196
  }
18058
18197
  function policyIdIsReversible(policyId) {
18059
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18060
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18198
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18199
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18061
18200
  return builtinPolicyIsReversible(id);
18062
18201
  }
18063
18202
  var DEFAULT_ACTIONS = Object.fromEntries(
@@ -18068,8 +18207,8 @@ var BUILTIN_POLICIES = Object.fromEntries(
18068
18207
  );
18069
18208
  var DEFAULT_PACK_POLICY_ID = "monitor";
18070
18209
  function policyIdToAction(policyId) {
18071
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18072
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18210
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18211
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18073
18212
  return BUILTIN_POLICIES[id].action;
18074
18213
  }
18075
18214
  var UsedByItem = external_exports.object({
@@ -18512,53 +18651,6 @@ function reviewSeverityRank(reasons) {
18512
18651
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
18513
18652
  }
18514
18653
 
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
18654
  // ../../packages/persistence/src/paths.ts
18563
18655
  import {
18564
18656
  chmodSync,
@@ -18609,6 +18701,23 @@ function tightenPerms(file2) {
18609
18701
  function writeExclusiveOwnerOnlySync(file2, data) {
18610
18702
  writeFileSync(file2, data, { mode: DATA_FILE_MODE, flag: "wx" });
18611
18703
  }
18704
+ function writeOwnerOnlyFileSync(file2, data) {
18705
+ const tmp = `${file2}.${String(process.pid)}.tmp`;
18706
+ try {
18707
+ rmSync(tmp, { force: true });
18708
+ } catch {
18709
+ }
18710
+ try {
18711
+ writeExclusiveOwnerOnlySync(tmp, data);
18712
+ renameSync(tmp, file2);
18713
+ } finally {
18714
+ try {
18715
+ rmSync(tmp, { force: true });
18716
+ } catch {
18717
+ }
18718
+ }
18719
+ tightenFile(file2);
18720
+ }
18612
18721
  function classifyOccupant(file2) {
18613
18722
  try {
18614
18723
  if (lstatSync(file2).isSymbolicLink()) return { kind: "symlink" };
@@ -18667,7 +18776,123 @@ function publishByLink(tmp, file2, data) {
18667
18776
  }
18668
18777
  }
18669
18778
 
18779
+ // ../../packages/persistence/src/control-plane-credential.ts
18780
+ function controlPlaneCredentialPath(settingsDir2) {
18781
+ return join(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
18782
+ }
18783
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
18784
+ function isSafeEndpoint(endpoint) {
18785
+ let parsed2;
18786
+ try {
18787
+ parsed2 = new URL(endpoint);
18788
+ } catch {
18789
+ return false;
18790
+ }
18791
+ if (parsed2.protocol === "https:") return true;
18792
+ return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname);
18793
+ }
18794
+ function repairOrRefuseMode(file2) {
18795
+ const link = lstatSync2(file2, { throwIfNoEntry: false });
18796
+ if (link === void 0) return "absent";
18797
+ if (link.isSymbolicLink()) return "untrusted";
18798
+ const stat = statSync(file2, { throwIfNoEntry: false });
18799
+ if (stat === void 0) return "absent";
18800
+ const uid = process.getuid?.();
18801
+ if (uid !== void 0 && stat.uid !== uid) return "untrusted";
18802
+ if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
18803
+ try {
18804
+ chmodSync2(file2, DATA_FILE_MODE);
18805
+ } catch {
18806
+ return "untrusted";
18807
+ }
18808
+ }
18809
+ return "ok";
18810
+ }
18811
+ function readControlPlaneCredentialState(settingsDir2, connection) {
18812
+ const file2 = controlPlaneCredentialPath(settingsDir2);
18813
+ let raw;
18814
+ const gate = repairOrRefuseMode(file2);
18815
+ if (gate === "absent") return { usable: false, reason: "absent" };
18816
+ if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
18817
+ try {
18818
+ raw = readFileSync(file2, "utf8");
18819
+ } catch (err) {
18820
+ const code = err.code;
18821
+ return { usable: false, reason: code === "ENOENT" ? "absent" : "unreadable" };
18822
+ }
18823
+ let parsed2;
18824
+ try {
18825
+ parsed2 = JSON.parse(raw);
18826
+ } catch {
18827
+ return { usable: false, reason: "malformed" };
18828
+ }
18829
+ const result = AttachedCredential.safeParse(parsed2);
18830
+ if (!result.success) return { usable: false, reason: "malformed" };
18831
+ if (!isSafeEndpoint(result.data.endpoint)) {
18832
+ return { usable: false, reason: "unsafe-endpoint" };
18833
+ }
18834
+ if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
18835
+ return {
18836
+ usable: false,
18837
+ reason: "endpoint-mismatch",
18838
+ credentialEndpoint: result.data.endpoint,
18839
+ settingsEndpoint: connection.endpoint
18840
+ };
18841
+ }
18842
+ return { usable: true, credential: result.data };
18843
+ }
18844
+
18845
+ // ../../packages/persistence/src/database.ts
18846
+ import { randomUUID as randomUUID10 } from "crypto";
18847
+ import { join as join3, sep } from "path";
18848
+ import { DatabaseSync } from "node:sqlite";
18849
+
18850
+ // ../../packages/persistence/src/ids.ts
18851
+ import { createHash } from "crypto";
18852
+ function sha256Hex(input) {
18853
+ return createHash("sha256").update(input).digest("hex");
18854
+ }
18855
+ function inventoryId(objectType, identityKey) {
18856
+ return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18857
+ }
18858
+ function sourceProjectId(url2) {
18859
+ return sha256Hex(canonicalIdentity(["source_project", url2]));
18860
+ }
18861
+ function classifiedDataId(cls) {
18862
+ return sha256Hex(canonicalIdentity(["classified_data", cls]));
18863
+ }
18864
+ function inspectionDefinitionId(ruleId, version2) {
18865
+ return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18866
+ }
18867
+ function llmCallId(sessionId, messageId) {
18868
+ return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18869
+ }
18870
+ function toolCallId(sessionId, toolUseId) {
18871
+ return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18872
+ }
18873
+ function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18874
+ return sha256Hex(
18875
+ canonicalIdentity([
18876
+ "inspection_finding",
18877
+ auditEventId,
18878
+ ruleId,
18879
+ String(spanStart),
18880
+ String(spanEnd)
18881
+ ])
18882
+ );
18883
+ }
18884
+ var NO_SESSION = "no_session";
18885
+ var NO_PATH = "no_path";
18886
+ function captureId(sessionId, contentHash, filePath = null) {
18887
+ return sha256Hex(
18888
+ canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18889
+ );
18890
+ }
18891
+
18670
18892
  // ../../packages/persistence/src/internal/snapshot.ts
18893
+ import { randomUUID } from "crypto";
18894
+ import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync3, statSync as statSync2 } from "fs";
18895
+ import { basename, dirname, join as join2 } from "path";
18671
18896
  function backupPath(file2, tag) {
18672
18897
  return `${file2}.${tag}.${String(Date.now())}.${randomUUID().slice(0, 8)}.bak`;
18673
18898
  }
@@ -18677,15 +18902,15 @@ var STAGED_NAME_SUFFIX = `.bak${SNAPSHOT_STAGING_SUFFIX}`;
18677
18902
  var SNAPSHOT_STAGING_COPY = "copy";
18678
18903
  function createSnapshotStaging(backup) {
18679
18904
  const stage = `${backup}${SNAPSHOT_STAGING_SUFFIX}`;
18680
- rmSync2(stage, { recursive: true, force: true });
18905
+ rmSync3(stage, { recursive: true, force: true });
18681
18906
  mkdirOwnerOnlySync(stage);
18682
18907
  tightenDir(stage);
18683
- return { stage, copy: join(stage, SNAPSHOT_STAGING_COPY) };
18908
+ return { stage, copy: join2(stage, SNAPSHOT_STAGING_COPY) };
18684
18909
  }
18685
18910
  function idleMs(entry) {
18686
- for (const candidate of [join(entry, SNAPSHOT_STAGING_COPY), entry]) {
18911
+ for (const candidate of [join2(entry, SNAPSHOT_STAGING_COPY), entry]) {
18687
18912
  try {
18688
- return Date.now() - statSync(candidate).mtimeMs;
18913
+ return Date.now() - statSync2(candidate).mtimeMs;
18689
18914
  } catch {
18690
18915
  }
18691
18916
  }
@@ -18702,11 +18927,11 @@ function reapStalePartials(file2) {
18702
18927
  }
18703
18928
  for (const name of entries) {
18704
18929
  if (!name.startsWith(prefix) || !name.endsWith(STAGED_NAME_SUFFIX)) continue;
18705
- const staging = join(dir, name);
18930
+ const staging = join2(dir, name);
18706
18931
  try {
18707
18932
  const idle = idleMs(staging);
18708
18933
  if (idle !== null && idle > STALE_PARTIAL_MS) {
18709
- rmSync2(staging, { recursive: true, force: true });
18934
+ rmSync3(staging, { recursive: true, force: true });
18710
18935
  }
18711
18936
  } catch {
18712
18937
  }
@@ -18720,13 +18945,13 @@ function snapshotStore(db, backup) {
18720
18945
  renameSync2(copy, backup);
18721
18946
  } catch (error51) {
18722
18947
  try {
18723
- rmSync2(stage, { recursive: true, force: true });
18948
+ rmSync3(stage, { recursive: true, force: true });
18724
18949
  } catch {
18725
18950
  }
18726
18951
  throw error51;
18727
18952
  }
18728
18953
  try {
18729
- rmSync2(stage, { recursive: true, force: true });
18954
+ rmSync3(stage, { recursive: true, force: true });
18730
18955
  } catch {
18731
18956
  }
18732
18957
  }
@@ -18741,7 +18966,7 @@ function moveStoreAside(file2, backup) {
18741
18966
  renameSync2(sidecar, moved);
18742
18967
  undo.push([moved, sidecar]);
18743
18968
  } catch {
18744
- rmSync2(sidecar, { force: true });
18969
+ rmSync3(sidecar, { force: true });
18745
18970
  }
18746
18971
  }
18747
18972
  } catch (error51) {
@@ -18757,14 +18982,14 @@ function moveStoreAside(file2, backup) {
18757
18982
  }
18758
18983
  function discardStore(file2, backup) {
18759
18984
  try {
18760
- rmSync2(file2, { force: true });
18985
+ rmSync3(file2, { force: true });
18761
18986
  for (const sidecar of dbSidecars(file2)) {
18762
- rmSync2(sidecar, { force: true });
18987
+ rmSync3(sidecar, { force: true });
18763
18988
  }
18764
18989
  } catch (error51) {
18765
18990
  if (existsSync(file2)) {
18766
18991
  try {
18767
- rmSync2(backup, { force: true });
18992
+ rmSync3(backup, { force: true });
18768
18993
  } catch {
18769
18994
  }
18770
18995
  }
@@ -18996,10 +19221,31 @@ function applyMigrations(db, file2) {
18996
19221
  if (drained) applyLegacyDropMigration(db, file2);
18997
19222
  }
18998
19223
  }
19224
+ function readLegacyTables(db) {
19225
+ let holdsRows = false;
19226
+ const marks = [];
19227
+ for (const table of ["events", "findings"]) {
19228
+ try {
19229
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
19230
+ if (row === void 0) {
19231
+ holdsRows = true;
19232
+ marks.push(`${table}:unreadable`);
19233
+ continue;
19234
+ }
19235
+ if (row.n > 0) holdsRows = true;
19236
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
19237
+ } catch {
19238
+ holdsRows = true;
19239
+ marks.push(`${table}:unreadable`);
19240
+ }
19241
+ }
19242
+ return { holdsRows, mark: marks.join("|") };
19243
+ }
18999
19244
  function applyLegacyDropMigration(db, file2) {
19000
19245
  const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
19001
19246
  if (!migration) return;
19002
- if (file2) {
19247
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
19248
+ if (file2 !== void 0 && before?.holdsRows === true) {
19003
19249
  try {
19004
19250
  backupBeforeLegacyDrop(db, file2);
19005
19251
  } catch (error51) {
@@ -19013,6 +19259,12 @@ function applyLegacyDropMigration(db, file2) {
19013
19259
  () => {
19014
19260
  const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
19015
19261
  if (alreadyDropped) return;
19262
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
19263
+ akaWarn(
19264
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
19265
+ );
19266
+ return;
19267
+ }
19016
19268
  for (const statement of splitStatements(migration.sql)) {
19017
19269
  db.exec(statement);
19018
19270
  }
@@ -19367,8 +19619,8 @@ function safeJson(s, fallback) {
19367
19619
  function parseJsonObject(s) {
19368
19620
  if (s == null) return void 0;
19369
19621
  try {
19370
- const parsed = JSON.parse(s);
19371
- if (typeof parsed === "object" && parsed !== null) return parsed;
19622
+ const parsed2 = JSON.parse(s);
19623
+ if (typeof parsed2 === "object" && parsed2 !== null) return parsed2;
19372
19624
  } catch {
19373
19625
  }
19374
19626
  return void 0;
@@ -19379,16 +19631,16 @@ function encodeKeysetCursor(payload) {
19379
19631
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
19380
19632
  }
19381
19633
  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
19634
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19635
+ if (parsed2 !== void 0 && "startedAtMs" in parsed2 && "id" in parsed2 && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19384
19636
  // resumes from is epoch millis, and a payload carrying ±Infinity or a
19385
19637
  // fraction binds cleanly rather than failing — returning an EMPTY page with
19386
19638
  // a null cursor, which a caller reads as "end of list". That is the one
19387
19639
  // outcome a cursor that does not decode must never produce, since the
19388
19640
  // documented behaviour above is to restart from the top. (`1e999` is valid
19389
19641
  // 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;
19642
+ Number.isInteger(parsed2.startedAtMs) && typeof parsed2.id === "string") {
19643
+ return parsed2;
19392
19644
  }
19393
19645
  return null;
19394
19646
  }
@@ -19453,18 +19705,18 @@ var DB_EVENT_TYPE_TO_KIND = {
19453
19705
  };
19454
19706
  function safeParseStringArray(raw) {
19455
19707
  if (!raw) return [];
19456
- const parsed = safeJson(raw, null);
19457
- return Array.isArray(parsed) ? parsed : [];
19708
+ const parsed2 = safeJson(raw, null);
19709
+ return Array.isArray(parsed2) ? parsed2 : [];
19458
19710
  }
19459
19711
  var DEFAULT_HARNESS = HARNESS.ClaudeCode;
19460
19712
  function toHarness(raw) {
19461
- const parsed = Harness.safeParse(raw);
19462
- return parsed.success ? parsed.data : DEFAULT_HARNESS;
19713
+ const parsed2 = Harness.safeParse(raw);
19714
+ return parsed2.success ? parsed2.data : DEFAULT_HARNESS;
19463
19715
  }
19464
19716
  function resolveLifecycle(row, lastActivityMs, nowMs) {
19465
19717
  if (row.status) {
19466
- const parsed = SessionStatus.safeParse(row.status);
19467
- if (parsed.success) return { status: parsed.data, endedAtMs: row.ended_at };
19718
+ const parsed2 = SessionStatus.safeParse(row.status);
19719
+ if (parsed2.success) return { status: parsed2.data, endedAtMs: row.ended_at };
19468
19720
  }
19469
19721
  if (row.ended_at !== null) return { status: "completed", endedAtMs: row.ended_at };
19470
19722
  if (lastActivityMs >= nowMs - LIVE_ACTIVITY_WINDOW_MS) {
@@ -20423,9 +20675,9 @@ var SqliteDetectionsRepository = class {
20423
20675
  const ruleIds = /* @__PURE__ */ new Set();
20424
20676
  for (const r of rows) {
20425
20677
  if (intToBool(r.enabled)) active += 1;
20426
- const parsed = parseRules(r.rulesJson);
20427
- rules += parsed.length;
20428
- for (const rule of parsed) {
20678
+ const parsed2 = parseRules(r.rulesJson);
20679
+ rules += parsed2.length;
20680
+ for (const rule of parsed2) {
20429
20681
  if (typeof rule.id === "string") ruleIds.add(rule.id);
20430
20682
  }
20431
20683
  }
@@ -20959,12 +21211,12 @@ function encodeGroupCursor(group) {
20959
21211
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
20960
21212
  }
20961
21213
  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") {
21214
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
21215
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.id === "string") {
20964
21216
  return {
20965
- severity: parsed.sev,
20966
- latestDetectedAt: parsed.t,
20967
- id: parsed.id
21217
+ severity: parsed2.sev,
21218
+ latestDetectedAt: parsed2.t,
21219
+ id: parsed2.id
20968
21220
  };
20969
21221
  }
20970
21222
  return null;
@@ -22098,16 +22350,16 @@ var SqliteInstalledPacksRepository = class {
22098
22350
  continue;
22099
22351
  }
22100
22352
  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);
22353
+ const parsed2 = Rule.safeParse(entry);
22354
+ if (parsed2.success) {
22355
+ out.rules.push(parsed2.data);
22356
+ out.ruleActions.set(parsed2.data.id, action);
22357
+ out.ruleVersions.set(parsed2.data.id, row.version);
22358
+ if (reversible) out.reversibleRules.add(parsed2.data.id);
22359
+ else out.reversibleRules.delete(parsed2.data.id);
22108
22360
  } else {
22109
22361
  out.invalidRules += 1;
22110
- reject(pack, printableRuleId(entry), firstIssueReason(parsed.error));
22362
+ reject(pack, printableRuleId(entry), firstIssueReason(parsed2.error));
22111
22363
  }
22112
22364
  }
22113
22365
  }
@@ -23497,15 +23749,15 @@ function encodeReuseCursor(payload) {
23497
23749
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
23498
23750
  }
23499
23751
  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
23752
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23753
+ if (parsed2 !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23502
23754
  // ±Infinity or a fraction binds cleanly and returns an EMPTY page with a
23503
23755
  // null cursor, which the caller reads as "end of list" — the one outcome a
23504
23756
  // malformed cursor must never produce, since restarting from the top is the
23505
23757
  // documented behaviour and the only recoverable one. (`1e999` is valid JSON
23506
23758
  // 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 };
23759
+ Number.isInteger(parsed2.occurrences) && typeof parsed2.pointerId === "string") {
23760
+ return { occurrences: parsed2.occurrences, pointerId: parsed2.pointerId };
23509
23761
  }
23510
23762
  return null;
23511
23763
  }
@@ -25234,7 +25486,7 @@ function openAndInitialize(file2) {
25234
25486
  }
25235
25487
  function openLocalDatabase(dir) {
25236
25488
  ensureDataDirSync(dir);
25237
- const file2 = join2(dir, DB_FILENAME);
25489
+ const file2 = join3(dir, DB_FILENAME);
25238
25490
  reapStalePartials(file2);
25239
25491
  const {
25240
25492
  db,
@@ -25470,9 +25722,9 @@ import {
25470
25722
  closeSync,
25471
25723
  existsSync as existsSync2,
25472
25724
  openSync,
25473
- readFileSync,
25474
- rmSync as rmSync3,
25475
- statSync as statSync2,
25725
+ readFileSync as readFileSync2,
25726
+ rmSync as rmSync4,
25727
+ statSync as statSync3,
25476
25728
  writeFileSync as writeFileSync2
25477
25729
  } from "fs";
25478
25730
  import { hostname as hostname3 } from "os";
@@ -25490,20 +25742,20 @@ function computeFindingKey(input) {
25490
25742
 
25491
25743
  // ../../packages/persistence/src/fingerprint.ts
25492
25744
  import { createHmac, randomBytes } from "crypto";
25493
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
25494
- import { join as join3 } from "path";
25745
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
25746
+ import { join as join4 } from "path";
25495
25747
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
25496
25748
  var EXCEPTION_KEY_FILENAME = "exception.key";
25497
25749
  var KEY_MATERIAL_BYTES = 32;
25498
25750
  function keyFilePath(dataDir2) {
25499
- return join3(dataDir2, EXCEPTION_KEY_FILENAME);
25751
+ return join4(dataDir2, EXCEPTION_KEY_FILENAME);
25500
25752
  }
25501
25753
  function parseKeyFile(raw) {
25502
- const parsed = JSON.parse(raw);
25503
- if (typeof parsed !== "object" || parsed === null) {
25754
+ const parsed2 = JSON.parse(raw);
25755
+ if (typeof parsed2 !== "object" || parsed2 === null) {
25504
25756
  throw new Error("exception key file is corrupt: not a JSON object");
25505
25757
  }
25506
- const { version: version2, material } = parsed;
25758
+ const { version: version2, material } = parsed2;
25507
25759
  if (typeof version2 !== "number" || !Number.isInteger(version2) || version2 < 1) {
25508
25760
  throw new Error("exception key file is corrupt: bad version");
25509
25761
  }
@@ -25534,7 +25786,7 @@ var FloorUnreadableError = class extends Error {
25534
25786
  }
25535
25787
  };
25536
25788
  function storedKeyVersionFloor(dataDir2) {
25537
- const file2 = join3(dataDir2, DB_FILENAME);
25789
+ const file2 = join4(dataDir2, DB_FILENAME);
25538
25790
  if (!existsSync3(file2)) return 0;
25539
25791
  let db;
25540
25792
  try {
@@ -25589,7 +25841,7 @@ function occupantMessage(file2, kind) {
25589
25841
  function readFingerprintKey(dataDir2) {
25590
25842
  let raw;
25591
25843
  try {
25592
- raw = readFileSync2(keyFilePath(dataDir2), "utf8");
25844
+ raw = readFileSync3(keyFilePath(dataDir2), "utf8");
25593
25845
  } catch (err) {
25594
25846
  if (err.code === "ENOENT") return null;
25595
25847
  throw err instanceof Error ? err : new Error(String(err));
@@ -25615,18 +25867,25 @@ function fingerprintValue(key, raw) {
25615
25867
  import { renameSync as renameSync3 } from "fs";
25616
25868
  import { mkdir } from "fs/promises";
25617
25869
  import { homedir } from "os";
25618
- import { join as join4 } from "path";
25870
+ import { join as join5 } from "path";
25619
25871
  function defaultDataDir() {
25620
- return join4(homedir(), ".aka");
25872
+ return join5(homedir(), ".aka");
25621
25873
  }
25622
25874
  function settingsDir(base = defaultDataDir()) {
25623
- return join4(base, "settings");
25875
+ return join5(base, "settings");
25624
25876
  }
25625
25877
  function dataDir(base = defaultDataDir()) {
25626
- return join4(base, "data");
25878
+ return join5(base, "data");
25627
25879
  }
25628
25880
  function dbPath(base = defaultDataDir()) {
25629
- return join4(dataDir(base), "aka.db");
25881
+ return join5(dataDir(base), "aka.db");
25882
+ }
25883
+ function keysDir(base = defaultDataDir()) {
25884
+ return join5(base, "keys");
25885
+ }
25886
+ async function ensureDataDir(dir = defaultDataDir()) {
25887
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
25888
+ tightenDir(dir);
25630
25889
  }
25631
25890
  function ensureLayoutDirSync(dir = defaultDataDir()) {
25632
25891
  ensureDataDirSync(dir);
@@ -25639,8 +25898,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25639
25898
  for (const { name, dest } of moves) {
25640
25899
  try {
25641
25900
  ensureDataDirSync(dest);
25642
- const moved = join4(dest, name);
25643
- renameSync3(join4(base, name), moved);
25901
+ const moved = join5(dest, name);
25902
+ renameSync3(join5(base, name), moved);
25644
25903
  tightenFile(moved);
25645
25904
  } catch {
25646
25905
  }
@@ -25648,7 +25907,7 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25648
25907
  }
25649
25908
 
25650
25909
  // ../../packages/persistence/src/managed-settings.ts
25651
- import { readFileSync as readFileSync3 } from "fs";
25910
+ import { readFileSync as readFileSync4 } from "fs";
25652
25911
  import { posix, win32 } from "path";
25653
25912
  function managedSettingsPaths(platform2 = process.platform) {
25654
25913
  if (platform2 === "darwin") {
@@ -25666,14 +25925,14 @@ function readManagedSettings(paths = managedSettingsPaths()) {
25666
25925
  for (const path of paths) {
25667
25926
  let text;
25668
25927
  try {
25669
- text = readFileSync3(path, "utf8");
25928
+ text = readFileSync4(path, "utf8");
25670
25929
  } catch {
25671
25930
  continue;
25672
25931
  }
25673
25932
  const record2 = parseJsonObject(text);
25674
25933
  if (!record2) continue;
25675
- const parsed = ManagedSettings.safeParse(record2);
25676
- if (parsed.success) return parsed.data;
25934
+ const parsed2 = ManagedSettings.safeParse(record2);
25935
+ if (parsed2.success) return parsed2.data;
25677
25936
  }
25678
25937
  return null;
25679
25938
  }
@@ -25713,14 +25972,14 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
25713
25972
  }
25714
25973
 
25715
25974
  // ../../packages/persistence/src/settings.ts
25716
- import { readFileSync as readFileSync4 } from "fs";
25717
- import { join as join5 } from "path";
25975
+ import { readFileSync as readFileSync5 } from "fs";
25976
+ import { join as join6 } from "path";
25718
25977
  var SETTINGS_FILENAME = "settings.json";
25719
25978
  function readWorkspaceSettings(base = defaultDataDir()) {
25720
25979
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
25721
25980
  }
25722
25981
  function readUserSettings(base) {
25723
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
25982
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
25724
25983
  if (!record2) return defaultWorkspaceSettings();
25725
25984
  try {
25726
25985
  return WorkspaceSettings.parse(record2);
@@ -25731,13 +25990,64 @@ function readUserSettings(base) {
25731
25990
  function readJson(file2) {
25732
25991
  let text;
25733
25992
  try {
25734
- text = readFileSync4(file2, "utf8");
25993
+ text = readFileSync5(file2, "utf8");
25735
25994
  } catch {
25736
25995
  return null;
25737
25996
  }
25738
25997
  return parseJsonObject(text) ?? null;
25739
25998
  }
25740
25999
 
26000
+ // ../../packages/persistence/src/store-symlinks.ts
26001
+ import { existsSync as existsSync4, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
26002
+ import { dirname as dirname2, join as join7, resolve } from "path";
26003
+ var STORE_DB = "the store database (including the prompt corpus)";
26004
+ var STORE_SETTINGS = "your settings file";
26005
+ function storeContents(home) {
26006
+ return /* @__PURE__ */ new Map([
26007
+ [home, "the store (including the prompt corpus in aka.db)"],
26008
+ [settingsDir(home), STORE_SETTINGS],
26009
+ [dataDir(home), STORE_DB],
26010
+ [keysDir(home), "the vault key"],
26011
+ [join7(settingsDir(home), "settings.json"), STORE_SETTINGS],
26012
+ [dbPath(home), STORE_DB]
26013
+ ]);
26014
+ }
26015
+ function symlinkedStorePaths(home, platform2 = process.platform) {
26016
+ return [...storeContents(home)].flatMap(([path, holds]) => {
26017
+ try {
26018
+ if (!lstatSync3(path).isSymbolicLink()) return [];
26019
+ return [
26020
+ {
26021
+ path,
26022
+ target: linkTarget(path),
26023
+ holds,
26024
+ // existsSync follows the link, so a target that is gone reads as
26025
+ // absent here while lstat above still sees the link itself.
26026
+ missing: !existsSync4(path),
26027
+ mode: targetMode(path, platform2)
26028
+ }
26029
+ ];
26030
+ } catch {
26031
+ return [];
26032
+ }
26033
+ });
26034
+ }
26035
+ function linkTarget(path) {
26036
+ try {
26037
+ return realpathSync(path);
26038
+ } catch {
26039
+ return resolve(dirname2(path), readlinkSync(path));
26040
+ }
26041
+ }
26042
+ function targetMode(path, platform2) {
26043
+ if (platform2 === "win32") return void 0;
26044
+ try {
26045
+ return statSync4(path).mode & 511;
26046
+ } catch {
26047
+ return void 0;
26048
+ }
26049
+ }
26050
+
25741
26051
  // ../../packages/persistence/src/vault/crypto.ts
25742
26052
  import {
25743
26053
  createCipheriv,
@@ -25750,26 +26060,73 @@ import {
25750
26060
  // ../../packages/persistence/src/vault/key-provider.ts
25751
26061
  import { execFileSync } from "child_process";
25752
26062
  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";
26063
+ import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync5, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
26064
+ import { join as join8 } from "path";
25755
26065
 
25756
26066
  // ../../packages/persistence/src/vault/vault.ts
25757
26067
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
25758
26068
 
25759
26069
  // ../../packages/persistence/src/warn-era-cap.ts
25760
- import { existsSync as existsSync4, writeFileSync as writeFileSync4 } from "fs";
25761
- import { join as join7 } from "path";
26070
+ import { existsSync as existsSync5, writeFileSync as writeFileSync4 } from "fs";
26071
+ import { join as join9 } from "path";
25762
26072
  var MARKER = "warn-era-capped";
25763
26073
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
25764
26074
  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" };
26075
+ const marker = join9(dataDir2, MARKER);
26076
+ if (existsSync5(marker)) return { capped: 0, skipped: "already-run" };
25767
26077
  const capped = db.policies.capCategoryActions();
25768
26078
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
25769
26079
  `, { mode: DATA_FILE_MODE });
25770
26080
  return { capped };
25771
26081
  }
25772
26082
 
26083
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
26084
+ var FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
26085
+ function forwardDropsPath(dataDir2) {
26086
+ return join10(dataDir2, FORWARD_DROPS_FILENAME);
26087
+ }
26088
+ function recordForwardDrops(dataDir2, count, nowMs) {
26089
+ if (count <= 0) return;
26090
+ try {
26091
+ ensureDataDirSync(dataDir2);
26092
+ const previous = readForwardDrops(dataDir2);
26093
+ const next = {
26094
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
26095
+ lastDropAtMs: nowMs
26096
+ };
26097
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
26098
+ `);
26099
+ } catch {
26100
+ }
26101
+ }
26102
+ function readForwardDrops(dataDir2) {
26103
+ try {
26104
+ const parsed2 = JSON.parse(readFileSync7(forwardDropsPath(dataDir2), "utf8"));
26105
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
26106
+ const record2 = parsed2;
26107
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
26108
+ return null;
26109
+ }
26110
+ if (record2.droppedForwards <= 0) return null;
26111
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
26112
+ return null;
26113
+ }
26114
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
26115
+ } catch {
26116
+ return null;
26117
+ }
26118
+ }
26119
+
26120
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
26121
+ import { randomUUID as randomUUID15 } from "crypto";
26122
+ import { readFileSync as readFileSync12 } from "fs";
26123
+ import { readFile, rename, writeFile } from "fs/promises";
26124
+ import { join as join18 } from "path";
26125
+
26126
+ // ../../packages/plugin-sdk/src/config.ts
26127
+ import { existsSync as existsSync6 } from "fs";
26128
+ import { join as join11 } from "path";
26129
+
25773
26130
  // ../../packages/plugin-sdk/src/provider-env.ts
25774
26131
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
25775
26132
  var booleanish = external_exports.string().optional().transform((v) => {
@@ -25804,8 +26161,8 @@ function hostOf(url2) {
25804
26161
  }
25805
26162
  }
25806
26163
  function resolveProvider() {
25807
- const parsed = ProviderEnvSchema.safeParse(process.env);
25808
- const env = parsed.success ? parsed.data : ProviderEnvSchema.parse({});
26164
+ const parsed2 = ProviderEnvSchema.safeParse(process.env);
26165
+ const env = parsed2.success ? parsed2.data : ProviderEnvSchema.parse({});
25809
26166
  if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
25810
26167
  if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
25811
26168
  const baseUrl = env.ANTHROPIC_BASE_URL;
@@ -25822,8 +26179,8 @@ function resolveProvider() {
25822
26179
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
25823
26180
  try {
25824
26181
  ensureLayoutDirSync(base);
25825
- const settingsFile = join8(settingsDir(base), "settings.json");
25826
- if (existsSync5(settingsFile)) tightenFile(settingsFile);
26182
+ const settingsFile = join11(settingsDir(base), "settings.json");
26183
+ if (existsSync6(settingsFile)) tightenFile(settingsFile);
25827
26184
  } catch {
25828
26185
  }
25829
26186
  migrateLegacyLayout(base);
@@ -25846,9 +26203,9 @@ function resolveProviderSafe(resolveProviderFn) {
25846
26203
  }
25847
26204
 
25848
26205
  // ../../packages/plugin-sdk/src/config-inventory.ts
25849
- import { readdirSync as readdirSync2, readFileSync as readFileSync7, realpathSync, statSync as statSync5 } from "fs";
26206
+ import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
25850
26207
  import { homedir as homedir2 } from "os";
25851
- import { basename as basename3, join as join10 } from "path";
26208
+ import { basename as basename3, join as join13 } from "path";
25852
26209
 
25853
26210
  // ../../packages/detections/src/egress/registry.ts
25854
26211
  var EXTRACTOR_VERSION = "1";
@@ -27625,10 +27982,10 @@ var localhost_ref_default = {
27625
27982
  severity: "low",
27626
27983
  matcher: {
27627
27984
  type: "regex",
27628
- pattern: "\\b(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|::1)\\b",
27985
+ 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
27986
  flags: "g"
27630
27987
  },
27631
- examples: ["localhost", "127.0.0.1"]
27988
+ examples: ["localhost", "127.0.0.1", "0.0.0.0", "::1"]
27632
27989
  };
27633
27990
 
27634
27991
  // ../../rules/core-code-context/stack-trace.json
@@ -28940,8 +29297,8 @@ function uniqueRuleIds(findings) {
28940
29297
  }
28941
29298
 
28942
29299
  // ../../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";
29300
+ import { existsSync as existsSync7, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
29301
+ import { basename as basename2, dirname as dirname3, isAbsolute, join as join12, sep as sep2 } from "path";
28945
29302
  function resolveRepo(cwd) {
28946
29303
  try {
28947
29304
  const root = findGitRoot(cwd);
@@ -28956,36 +29313,36 @@ function resolveRepo(cwd) {
28956
29313
  function findGitRoot(start) {
28957
29314
  let dir = start;
28958
29315
  for (; ; ) {
28959
- if (existsSync6(join9(dir, ".git"))) return dir;
28960
- const parent = dirname2(dir);
29316
+ if (existsSync7(join12(dir, ".git"))) return dir;
29317
+ const parent = dirname3(dir);
28961
29318
  if (parent === dir) return void 0;
28962
29319
  dir = parent;
28963
29320
  }
28964
29321
  }
28965
29322
  function resolveGitContext(root) {
28966
- const dotGit = join9(root, ".git");
29323
+ const dotGit = join12(root, ".git");
28967
29324
  try {
28968
- if (statSync4(dotGit).isDirectory()) {
28969
- return { configPath: join9(dotGit, "config"), headRoot: root };
29325
+ if (statSync6(dotGit).isDirectory()) {
29326
+ return { configPath: join12(dotGit, "config"), headRoot: root };
28970
29327
  }
28971
29328
  } catch {
28972
29329
  return void 0;
28973
29330
  }
28974
29331
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
28975
29332
  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 };
29333
+ const gitdir = isAbsolute(target) ? target : join12(root, target);
29334
+ if (existsSync7(join12(gitdir, "config"))) {
29335
+ return { configPath: join12(gitdir, "config"), headRoot: root };
28979
29336
  }
28980
- const commonRaw = safeRead(join9(gitdir, "commondir"))?.trim();
29337
+ const commonRaw = safeRead(join12(gitdir, "commondir"))?.trim();
28981
29338
  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 };
29339
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join12(gitdir, commonRaw);
29340
+ const headRoot = basename2(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
29341
+ return { configPath: join12(commonGitDir, "config"), headRoot };
28985
29342
  }
28986
29343
  function safeRead(path) {
28987
29344
  try {
28988
- return readFileSync6(path, "utf8");
29345
+ return readFileSync8(path, "utf8");
28989
29346
  } catch {
28990
29347
  return void 0;
28991
29348
  }
@@ -29046,7 +29403,7 @@ function buildIngestEvent(input) {
29046
29403
  }
29047
29404
 
29048
29405
  // ../../packages/plugin-sdk/src/isolated-scan.ts
29049
- import { existsSync as existsSync7 } from "fs";
29406
+ import { existsSync as existsSync8 } from "fs";
29050
29407
  import { fileURLToPath } from "url";
29051
29408
  import { Worker } from "worker_threads";
29052
29409
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -29060,7 +29417,7 @@ function resolveWorkerUrl() {
29060
29417
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
29061
29418
  const candidate = new URL(name, import.meta.url);
29062
29419
  try {
29063
- if (existsSync7(fileURLToPath(candidate))) {
29420
+ if (existsSync8(fileURLToPath(candidate))) {
29064
29421
  resolvedWorkerUrl = candidate;
29065
29422
  return candidate;
29066
29423
  }
@@ -29245,8 +29602,8 @@ function createIsolatedScanner(data, opts = {}) {
29245
29602
  }
29246
29603
  function enqueue(spec) {
29247
29604
  const next = chain.then(
29248
- () => new Promise((resolve) => {
29249
- spec(resolve);
29605
+ () => new Promise((resolve2) => {
29606
+ spec(resolve2);
29250
29607
  })
29251
29608
  );
29252
29609
  chain = next.then(
@@ -29257,7 +29614,7 @@ function createIsolatedScanner(data, opts = {}) {
29257
29614
  }
29258
29615
  return {
29259
29616
  scan(text, context, scanOpts) {
29260
- return enqueue((resolve) => {
29617
+ return enqueue((resolve2) => {
29261
29618
  runOne(
29262
29619
  {
29263
29620
  budgetMs,
@@ -29270,23 +29627,23 @@ function createIsolatedScanner(data, opts = {}) {
29270
29627
  }),
29271
29628
  reply: (message) => {
29272
29629
  if (message.kind !== "result") return false;
29273
- resolve({ status: "ok", findings: message.findings });
29630
+ resolve2({ status: "ok", findings: message.findings });
29274
29631
  return true;
29275
29632
  }
29276
29633
  },
29277
- resolve
29634
+ resolve2
29278
29635
  );
29279
29636
  });
29280
29637
  },
29281
29638
  probe(rule) {
29282
- return enqueue((resolve) => {
29639
+ return enqueue((resolve2) => {
29283
29640
  runOne(
29284
29641
  {
29285
29642
  budgetMs: probeBudgetMs,
29286
29643
  build: (id) => ({ kind: "probe", id, rule }),
29287
29644
  reply: (message) => {
29288
29645
  if (message.kind !== "probed") return false;
29289
- resolve({
29646
+ resolve2({
29290
29647
  status: "ok",
29291
29648
  verdict: message.verdict,
29292
29649
  worstMs: message.worstMs,
@@ -29295,7 +29652,7 @@ function createIsolatedScanner(data, opts = {}) {
29295
29652
  return true;
29296
29653
  }
29297
29654
  },
29298
- resolve
29655
+ resolve2
29299
29656
  );
29300
29657
  });
29301
29658
  },
@@ -29525,23 +29882,23 @@ function createGuardedScanner(partition, gateway, opts) {
29525
29882
 
29526
29883
  // ../../packages/plugin-sdk/src/ignore-layers.ts
29527
29884
  var import_ignore = __toESM(require_ignore(), 1);
29528
- import { readFileSync as readFileSync8 } from "fs";
29529
- import { join as join11 } from "path";
29885
+ import { readFileSync as readFileSync10 } from "fs";
29886
+ import { join as join14 } from "path";
29530
29887
 
29531
29888
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
29532
29889
  import { arch, hostname as hostname4, platform, release } from "os";
29533
29890
 
29534
29891
  // ../../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";
29892
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "fs";
29893
+ import { join as join15 } from "path";
29537
29894
 
29538
29895
  // ../../packages/plugin-sdk/src/paths.ts
29539
- import { readdirSync as readdirSync3, realpathSync as realpathSync2 } from "fs";
29540
- import { basename as basename4, dirname as dirname3, sep as sep3 } from "path";
29896
+ import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
29897
+ import { basename as basename4, dirname as dirname4, sep as sep3 } from "path";
29541
29898
 
29542
29899
  // ../../packages/plugin-sdk/src/project-files.ts
29543
- import { existsSync as existsSync8, readdirSync as readdirSync4 } from "fs";
29544
- import { basename as basename5, join as join13 } from "path";
29900
+ import { existsSync as existsSync9, readdirSync as readdirSync4 } from "fs";
29901
+ import { basename as basename5, join as join16 } from "path";
29545
29902
 
29546
29903
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
29547
29904
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -29912,39 +30269,1166 @@ function createPluginRuntime(gateway, settings, opts) {
29912
30269
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
29913
30270
 
29914
30271
  // ../../packages/plugin-sdk/src/throttle.ts
29915
- import { mkdirSync as mkdirSync3, statSync as statSync6, writeFileSync as writeFileSync6 } from "fs";
29916
- import { join as join14 } from "path";
29917
-
29918
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
29919
- import { randomUUID as randomUUID15 } from "crypto";
29920
-
29921
- // ../../packages/plugin-runtime/src/recorder.ts
29922
- var PLUGIN_RECORDER_BINARY = "plugin";
30272
+ import { mkdirSync as mkdirSync3, statSync as statSync8, writeFileSync as writeFileSync6 } from "fs";
30273
+ import { join as join17 } from "path";
30274
+
30275
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
30276
+ var REQUEST_TIMEOUT_MS = 2e3;
30277
+ function withTimeout(promise2, ms) {
30278
+ let timer;
30279
+ const timeout = new Promise((_, reject) => {
30280
+ timer = setTimeout(() => {
30281
+ reject(new Error("attached gateway request timed out"));
30282
+ }, ms);
30283
+ });
30284
+ promise2.catch(() => void 0);
30285
+ return Promise.race([promise2, timeout]).finally(() => {
30286
+ clearTimeout(timer);
30287
+ });
30288
+ }
29923
30289
 
29924
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
29925
- var StandaloneDataGateway = class {
29926
- db;
29927
- // Kept for the fingerprint key lookup (exception.key lives beside the store).
29928
- dataDir;
29929
- // One notice per gateway — see warnRulesetDiscarded.
29930
- warnedRulesetDiscarded = false;
29931
- constructor(dataDir2, detections = [], meta3) {
29932
- this.db = openLocalDatabase(dataDir2);
29933
- this.dataDir = dataDir2;
29934
- this.db.installedPacks.recordInventory(detections, meta3);
29935
- }
29936
- recordCapture(record2) {
29937
- this.db.recordCapture(record2.event, record2.findings);
29938
- return Promise.resolve();
30290
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
30291
+ function isInvalidRequest(err) {
30292
+ return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
30293
+ }
30294
+ var FORWARD_BUDGET_MS = 1500;
30295
+ var DECISION_PATH_BUDGET_MS = 800;
30296
+ var BREAKER_FAILURE_THRESHOLD = 3;
30297
+ var BREAKER_COOLDOWN_MS = 3e4;
30298
+ var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
30299
+ var FAILURES = /* @__PURE__ */ new Set([
30300
+ "unauthorized",
30301
+ "forbidden",
30302
+ "unreachable"
30303
+ ]);
30304
+ var FORWARD_STATE_FILENAME = "attached-state.json";
30305
+ var STATE_FILENAME = FORWARD_STATE_FILENAME;
30306
+ function parseBreakerState(raw, nowMs) {
30307
+ try {
30308
+ const parsed2 = JSON.parse(raw);
30309
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30310
+ const record2 = parsed2;
30311
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
30312
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
30313
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
30314
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
30315
+ } catch {
30316
+ return null;
29939
30317
  }
29940
- ensureInventory(ctx) {
29941
- return Promise.resolve(this.db.ensureInventory(ctx));
30318
+ }
30319
+ function createForwardPolicy(deps) {
30320
+ const now = deps.now ?? (() => Date.now());
30321
+ const file2 = join18(deps.dir, STATE_FILENAME);
30322
+ let state = null;
30323
+ let loading = null;
30324
+ async function readState() {
30325
+ let raw;
30326
+ try {
30327
+ raw = await readFile(file2, "utf8");
30328
+ } catch {
30329
+ return { ...CLOSED };
30330
+ }
30331
+ return parseBreakerState(raw, now()) ?? { ...CLOSED };
29942
30332
  }
29943
- recordAuditEvent(event) {
29944
- this.db.auditEvents.insertAuditEvent(event);
29945
- return Promise.resolve();
30333
+ async function load() {
30334
+ if (state !== null) return state;
30335
+ loading ??= readState().then((loaded) => {
30336
+ state = loaded;
30337
+ loading = null;
30338
+ return loaded;
30339
+ });
30340
+ return loading;
29946
30341
  }
29947
- // The id is minted inside the repository from the natural key — the plugin can't
30342
+ async function persist(next) {
30343
+ state = next;
30344
+ try {
30345
+ await ensureDataDir(deps.dir);
30346
+ const tmp = `${file2}.${randomUUID15()}.tmp`;
30347
+ await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
30348
+ await rename(tmp, file2);
30349
+ } catch {
30350
+ }
30351
+ }
30352
+ return {
30353
+ async run(op, opts) {
30354
+ const budget = opts?.decisionPath === true ? DECISION_PATH_BUDGET_MS : FORWARD_BUDGET_MS;
30355
+ let current;
30356
+ try {
30357
+ current = await load();
30358
+ } catch {
30359
+ current = { ...CLOSED };
30360
+ }
30361
+ const at = now();
30362
+ if (current.openedAtMs !== null) {
30363
+ if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
30364
+ return { ok: false, reason: "breaker-open" };
30365
+ }
30366
+ await persist({
30367
+ consecutiveFailures: current.consecutiveFailures,
30368
+ openedAtMs: at,
30369
+ lastFailure: current.lastFailure
30370
+ });
30371
+ }
30372
+ try {
30373
+ const value = await withTimeout(op(), budget);
30374
+ if (current.openedAtMs !== null || current.consecutiveFailures > 0) {
30375
+ await persist({ ...CLOSED });
30376
+ }
30377
+ return { ok: true, value };
30378
+ } catch (err) {
30379
+ if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
30380
+ const reason = classifyFailure(err);
30381
+ const failures = current.consecutiveFailures + 1;
30382
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
30383
+ await persist({
30384
+ consecutiveFailures: failures,
30385
+ openedAtMs: shouldOpen ? now() : null,
30386
+ lastFailure: reason
30387
+ });
30388
+ return { ok: false, reason };
30389
+ }
30390
+ }
30391
+ };
30392
+ }
30393
+
30394
+ // ../../packages/plugin-runtime/src/attached/gateway.ts
30395
+ var ACTION_STRENGTH = {
30396
+ allow: 0,
30397
+ log: 1,
30398
+ warn: 2,
30399
+ redact: 3,
30400
+ block: 4
30401
+ };
30402
+ function ruleCategoryMap(wireRules, localRules) {
30403
+ const map2 = /* @__PURE__ */ new Map();
30404
+ for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
30405
+ for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
30406
+ for (const pack of bundledDetections()) {
30407
+ for (const rule of pack.rules) map2.set(rule.id, rule.category);
30408
+ }
30409
+ return map2;
30410
+ }
30411
+ function strongerOf(a, b) {
30412
+ if (a === null) return b;
30413
+ if (b === null) return a;
30414
+ return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
30415
+ }
30416
+ function policyKey(policy) {
30417
+ return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
30418
+ }
30419
+ function floorFor(policy, categoryByRuleId) {
30420
+ const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
30421
+ return category === void 0 ? null : DEFAULT_ACTIONS[category];
30422
+ }
30423
+ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
30424
+ const merged = /* @__PURE__ */ new Map();
30425
+ const disabled = [];
30426
+ const remoteCategoryAction = /* @__PURE__ */ new Map();
30427
+ for (const policy of remotePolicies) {
30428
+ if (!policy.enabled) continue;
30429
+ if (!("category" in policy.target)) continue;
30430
+ if (remoteCategoryAction.has(policy.target.category)) continue;
30431
+ const floor = floorFor(policy, categoryByRuleId);
30432
+ remoteCategoryAction.set(
30433
+ policy.target.category,
30434
+ floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
30435
+ );
30436
+ }
30437
+ for (const policy of localPolicies) {
30438
+ if (!policy.enabled) {
30439
+ disabled.push(policy);
30440
+ continue;
30441
+ }
30442
+ const key = policyKey(policy);
30443
+ if (merged.has(key)) continue;
30444
+ let remoteFloor = null;
30445
+ if ("ruleId" in policy.target) {
30446
+ const category = categoryByRuleId.get(policy.target.ruleId);
30447
+ if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
30448
+ }
30449
+ merged.set(
30450
+ key,
30451
+ remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
30452
+ );
30453
+ }
30454
+ const localCategoryAction = /* @__PURE__ */ new Map();
30455
+ for (const policy of merged.values()) {
30456
+ if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
30457
+ }
30458
+ for (const policy of remotePolicies) {
30459
+ if (!policy.enabled) {
30460
+ disabled.push(policy);
30461
+ continue;
30462
+ }
30463
+ const key = policyKey(policy);
30464
+ const floor = floorFor(policy, categoryByRuleId);
30465
+ let localFloor = null;
30466
+ if ("ruleId" in policy.target) {
30467
+ const category = categoryByRuleId.get(policy.target.ruleId);
30468
+ if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
30469
+ }
30470
+ const effectiveFloor = strongerOf(floor, localFloor);
30471
+ const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
30472
+ const existing = merged.get(key);
30473
+ if (existing === void 0) {
30474
+ merged.set(key, clamped);
30475
+ continue;
30476
+ }
30477
+ if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
30478
+ merged.set(key, clamped);
30479
+ }
30480
+ }
30481
+ return [...merged.values(), ...disabled];
30482
+ }
30483
+ var AttachedDataGateway = class {
30484
+ constructor(deps) {
30485
+ this.deps = deps;
30486
+ }
30487
+ deps;
30488
+ /**
30489
+ * The control plane's OWN resolution of this session's inventory, captured by
30490
+ * ensureInventory. Null until the first successful forward — and it stays
30491
+ * null for the whole session when the control plane is unreachable, which is fine:
30492
+ * reKeyForForward then leaves the event's ids alone and the control plane resolves
30493
+ * what it can from the descriptors it already has.
30494
+ */
30495
+ remoteInventory = null;
30496
+ // ---------------------------------------------------------------------
30497
+ // Writes: local first, then forward.
30498
+ // ---------------------------------------------------------------------
30499
+ async recordCapture(record2) {
30500
+ await this.deps.local.recordCapture(record2);
30501
+ await this.deps.forward.run(
30502
+ () => this.deps.client.ingestEvents({
30503
+ events: [record2.event],
30504
+ ...record2.dedupe ? { dedupe: record2.dedupe } : {}
30505
+ }),
30506
+ { decisionPath: true }
30507
+ );
30508
+ }
30509
+ async ensureInventory(ctx) {
30510
+ const resolved = await this.deps.local.ensureInventory(ctx);
30511
+ const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
30512
+ this.remoteInventory = remote.ok ? remote.value : null;
30513
+ const snapshot = await (async () => {
30514
+ try {
30515
+ return await this.deps.posture?.prepare() ?? null;
30516
+ } catch {
30517
+ return null;
30518
+ }
30519
+ })();
30520
+ if (snapshot) {
30521
+ try {
30522
+ await withTimeout(
30523
+ this.deps.posture?.send(snapshot) ?? Promise.resolve(),
30524
+ REQUEST_TIMEOUT_MS
30525
+ );
30526
+ } catch {
30527
+ }
30528
+ }
30529
+ return resolved;
30530
+ }
30531
+ // The id is minted CLIENT-side and stored verbatim: the control plane does NOT
30532
+ // re-key it. `pgAuditValues` writes `id: event.id` and carries tenancy in
30533
+ // its own scoping columns, so the device and the forwarded copy
30534
+ // share one id space — which is what makes a re-post idempotent at all.
30535
+ //
30536
+ // Re-posts collapse via `onConflictDoUpdate` on the `id` PK, guarded by
30537
+ // `setWhere eventType = 'session'` (NOT onConflictDoNothing). That guard is
30538
+ // what makes an attached retry safe: a capture-stubbed session row can still
30539
+ // be HEALED by the authoritative root, while a duplicate non-session event —
30540
+ // a retried tool_call, exactly this path — can never stomp a populated row.
30541
+ async recordAuditEvent(event) {
30542
+ await this.deps.local.recordAuditEvent(event);
30543
+ await this.deps.forward.run(
30544
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
30545
+ );
30546
+ }
30547
+ // Attached `llm_call` is written locally by the inner gateway, then routed to
30548
+ // the control plane through the existing `recordAuditEvent` ingest (no dedicated
30549
+ // client method yet) by pre-building the audit event from the natural key.
30550
+ // The forward goes DIRECTLY to the client rather than through this.recordAuditEvent,
30551
+ // which would write the event to the local store a second time.
30552
+ async recordLlmCall(input) {
30553
+ await this.deps.local.recordLlmCall(input);
30554
+ await this.deps.forward.run(
30555
+ () => this.deps.client.recordAuditEvent(
30556
+ reKeyForForward(llmAuditEvent(input), this.remoteInventory)
30557
+ )
30558
+ );
30559
+ }
30560
+ /**
30561
+ * Forward one batch, item by item, under ONE aggregate deadline.
30562
+ *
30563
+ * Per-item budgets bound each request and nothing bounded their sum — see
30564
+ * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
30565
+ * rather than sent: the local write has already succeeded, so every caller
30566
+ * has a correct result to return, and a drop is the outcome this path is
30567
+ * built to accept (G8) where a blown hook timeout is not.
30568
+ *
30569
+ * Serial rather than concurrent on purpose. Firing N requests at once would
30570
+ * trade a latency problem for a burst the plane's own per-key rate limiting
30571
+ * would answer with the refusals the breaker then counts.
30572
+ *
30573
+ * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
30574
+ * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
30575
+ * lets status call the forward unhealthy; this path returns BEFORE `run` is
30576
+ * reached, so without the tally in `forward-drops.ts` a slow-but-answering
30577
+ * plane produces no failures, keeps the breaker closed, renders a healthy
30578
+ * block, and discards the tail of every batch indefinitely.
30579
+ */
30580
+ async forwardBatch(inputs, toEvent) {
30581
+ const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
30582
+ for (let i = 0; i < inputs.length; i += 1) {
30583
+ const now = Date.now();
30584
+ if (now >= deadline) {
30585
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
30586
+ return;
30587
+ }
30588
+ const input = inputs[i];
30589
+ await this.deps.forward.run(
30590
+ () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input), this.remoteInventory))
30591
+ );
30592
+ }
30593
+ }
30594
+ // Delegated as a BATCH rather than looped over recordLlmCall: the inner
30595
+ // gateway may write the whole batch in one local transaction, and looping
30596
+ // here would replace that with N separate local writes.
30597
+ async recordLlmCalls(inputs) {
30598
+ await this.deps.local.recordLlmCalls(inputs);
30599
+ await this.forwardBatch(inputs, (input) => llmAuditEvent(input));
30600
+ }
30601
+ // `input.inspections` (secrets detected client-side in the tool's masked
30602
+ // target) ride along on the request's `inspections` field — the control plane
30603
+ // persists each as an inspection_findings row linked to this audit event
30604
+ // (see RecordAuditEventRequest in @akasecurity/schema). The masked
30605
+ // `target` already rides `input.attributes`, so no raw secret leaks either
30606
+ // way — this only stops the FINDING row itself from being dropped.
30607
+ async recordToolCalls(inputs) {
30608
+ await this.deps.local.recordToolCalls(inputs);
30609
+ await this.forwardBatch(inputs, (input) => toolAuditEvent(input));
30610
+ }
30611
+ // Forwarded as a `config_scan` audit event: there is no dedicated
30612
+ // config-scan ingest endpoint, and the audit-event door is the one the
30613
+ // control plane already opens for client-minted, idempotent records.
30614
+ //
30615
+ // ONLY `scanEvent` CROSSES, and unlike `recordCapture` the plane cannot
30616
+ // re-derive the rest. A `ConfigScanRecord` is four things committed together
30617
+ // locally — the inventory `items`, this audit event, and the posture
30618
+ // `definitions`/`findings` that reference it — and three of them stay on the
30619
+ // device. Say that plainly rather than let the asymmetry with `recordCapture`
30620
+ // read as the same argument: there, findings are omitted BECAUSE the plane
30621
+ // re-derives them from `Event.content`; here there is no content to re-derive
30622
+ // from, so what is omitted is simply not sent.
30623
+ //
30624
+ // That is the wire contract as it stands rather than an oversight to patch
30625
+ // here. `items` has no route at all, and `RecordAuditEventRequest.inspections`
30626
+ // is documented as tool-call findings — widening it to carry config-scan
30627
+ // findings is an egress change (a posture finding's `maskedMatch` holds the
30628
+ // matched command) and a decision about what an attached deployment is
30629
+ // entitled to, not a bug fix. An attached machine's config posture therefore
30630
+ // reaches the plane as the event only; the dashboard's own view of it is the
30631
+ // local store.
30632
+ async recordConfigScan(record2) {
30633
+ await this.deps.local.recordConfigScan(record2);
30634
+ await this.deps.forward.run(
30635
+ () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
30636
+ );
30637
+ }
30638
+ async recordBlockedDetection(entry) {
30639
+ return this.deps.local.recordBlockedDetection(entry);
30640
+ }
30641
+ /**
30642
+ * LOCAL-ONLY, deliberately. The shares API is read-plus-decision-override
30643
+ * with no egress ingest endpoint, so there is nothing to forward to; adding a
30644
+ * forward here would be inventing a wire contract that does not exist. The
30645
+ * local write is the whole operation, and its summary is the real one — the
30646
+ * scanner reads a throw as a FAILED WRITE and skips its ledger commit, so
30647
+ * returning the inner gateway's result keeps the retry semantics honest.
30648
+ */
30649
+ async recordProjectEgress(input) {
30650
+ return this.deps.local.recordProjectEgress(input);
30651
+ }
30652
+ // ---------------------------------------------------------------------
30653
+ // Reads and device-local ledgers: pure delegation.
30654
+ // ---------------------------------------------------------------------
30655
+ async configInventoryReport() {
30656
+ return this.deps.local.configInventoryReport();
30657
+ }
30658
+ async readSessionProvider(sessionId) {
30659
+ return this.deps.local.readSessionProvider(sessionId);
30660
+ }
30661
+ async facets() {
30662
+ return this.deps.local.facets();
30663
+ }
30664
+ /**
30665
+ * Delegated UNMODIFIED — including its refusals.
30666
+ *
30667
+ * This is a fail-secure boundary: it decides whether an approved exception
30668
+ * lets a blocked action through. Under local-first the local store owns the
30669
+ * exception ledger, so the honest answer is whatever it says; wrapping this
30670
+ * in a fallback (`catch { return true }`, or defaulting on a timeout) would
30671
+ * turn a store error into a granted bypass. If the inner gateway rejects,
30672
+ * this rejects, and the runtime's own handling decides — which is asserted
30673
+ * end-to-end through runtime.capture rather than here.
30674
+ */
30675
+ async consumeException(id) {
30676
+ return this.deps.local.consumeException(id);
30677
+ }
30678
+ async recentFindings(opts) {
30679
+ return this.deps.local.recentFindings(opts);
30680
+ }
30681
+ async healthSummary() {
30682
+ return this.deps.local.healthSummary();
30683
+ }
30684
+ async activityByDay(days) {
30685
+ return this.deps.local.activityByDay(days);
30686
+ }
30687
+ async tokenReports() {
30688
+ return this.deps.local.tokenReports();
30689
+ }
30690
+ async knownContentHashes() {
30691
+ return this.deps.local.knownContentHashes();
30692
+ }
30693
+ async scanLedger(rulesetHash) {
30694
+ return this.deps.local.scanLedger(rulesetHash);
30695
+ }
30696
+ async recordScanned(entries) {
30697
+ return this.deps.local.recordScanned(entries);
30698
+ }
30699
+ async getRuleProbeVerdict(ruleKey) {
30700
+ return this.deps.local.getRuleProbeVerdict(ruleKey);
30701
+ }
30702
+ async setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2) {
30703
+ return this.deps.local.setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2);
30704
+ }
30705
+ async openAtRestKeysForPath(path) {
30706
+ return this.deps.local.openAtRestKeysForPath(path);
30707
+ }
30708
+ async resolvedAtRestKeysForPath(path) {
30709
+ return this.deps.local.resolvedAtRestKeysForPath(path);
30710
+ }
30711
+ async insertResolution(input) {
30712
+ return this.deps.local.insertResolution(input);
30713
+ }
30714
+ async close() {
30715
+ return this.deps.local.close();
30716
+ }
30717
+ // ---------------------------------------------------------------------
30718
+ // Policy
30719
+ // ---------------------------------------------------------------------
30720
+ async getPolicyBundle() {
30721
+ const local = await this.deps.local.getPolicyBundle();
30722
+ const cached2 = await (async () => {
30723
+ try {
30724
+ return await this.deps.readCachedBundle();
30725
+ } catch {
30726
+ return null;
30727
+ }
30728
+ })();
30729
+ if (cached2 === null) return local;
30730
+ const byRuleId = /* @__PURE__ */ new Map();
30731
+ for (const rule of [...local.rules ?? [], ...cached2.rules ?? []]) {
30732
+ if (!byRuleId.has(rule.id)) byRuleId.set(rule.id, rule);
30733
+ }
30734
+ const rules = [...byRuleId.values()];
30735
+ return {
30736
+ ...local,
30737
+ // The remote version identifies the composed bundle for the poller.
30738
+ version: cached2.version,
30739
+ rules,
30740
+ policies: mergeRaiseOnly(
30741
+ local.policies,
30742
+ cached2.policies,
30743
+ ruleCategoryMap(cached2.rules, local.rules)
30744
+ ),
30745
+ customKeywords: [...local.customKeywords, ...cached2.customKeywords]
30746
+ // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
30747
+ // snapshot) and is taken from the LOCAL bundle only — never from the wire
30748
+ // or the on-disk cache. Honoring a cached one would hand the control plane, or
30749
+ // anything able to write policy-cache.json, a kill-switch over the
30750
+ // compiled-in bundled packs: `{ rulesComplete: true, rules: [] }` would
30751
+ // zero local detection. Spread from `local` above, and deliberately not
30752
+ // re-read from `cached` here.
30753
+ //
30754
+ // THREE MORE OF THE CACHED BUNDLE'S FIELDS ARE DROPPED, each on purpose,
30755
+ // and each named here so a reader can tell a decision from an omission:
30756
+ //
30757
+ // `exceptions` — an exception SUPPRESSES a detection, so honoring
30758
+ // one from an unsigned on-disk cache would let
30759
+ // anything able to write that file turn rules off.
30760
+ // Every other field this merge accepts can only
30761
+ // RAISE enforcement; this is the one that cannot,
30762
+ // so it stays local-only until the bundle is
30763
+ // signed. Exceptions remain a device-local ledger.
30764
+ // `reversibleRuleIds` — the Redact & Vault archetype makes a redaction
30765
+ // recoverable, which is a CUSTODY change: it puts
30766
+ // the detected value in the local vault instead of
30767
+ // destroying it. Taking that instruction from the
30768
+ // cache would let a remote party turn one-way
30769
+ // redaction into retention. Dropping it keeps the
30770
+ // one-way behaviour, which the schema itself calls
30771
+ // "the safe direction to default".
30772
+ // `ruleVersions` — remote rules fall back to their own spec version.
30773
+ // Cosmetic rather than protective: it only affects
30774
+ // how a finding is version-attributed, and the two
30775
+ // sides may therefore attribute org rules
30776
+ // differently. Worth carrying once there is a
30777
+ // reader that needs it; nothing reads it today.
30778
+ };
30779
+ }
30780
+ // ---------------------------------------------------------------------
30781
+ // LocalStoreMaintenance — by delegation (D3).
30782
+ //
30783
+ // Implementing these is what actually closes the skipped-local-maintenance
30784
+ // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
30785
+ // any object carrying all five, so the composite qualifies and SessionStart
30786
+ // runs maintenance on the device's real store.
30787
+ //
30788
+ // ⚠ Two of the five are SYNCHRONOUS and must stay that way. `handle-session-start`
30789
+ // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
30790
+ // return value directly; declaring them `async` here would hand those call
30791
+ // sites a Promise and silently break both.
30792
+ // ---------------------------------------------------------------------
30793
+ async sweepTerminalExceptions(retentionMs) {
30794
+ return this.deps.local.sweepTerminalExceptions(retentionMs);
30795
+ }
30796
+ capWarnEraEnforcement(policyMode) {
30797
+ return this.deps.local.capWarnEraEnforcement(policyMode);
30798
+ }
30799
+ async recordProjectFiles(projectId, scan2) {
30800
+ return this.deps.local.recordProjectFiles(projectId, scan2);
30801
+ }
30802
+ async reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot) {
30803
+ return this.deps.local.reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot);
30804
+ }
30805
+ staleBinaryNotice(currentVersion) {
30806
+ return this.deps.local.staleBinaryNotice(currentVersion);
30807
+ }
30808
+ };
30809
+ function reKeyForForward(event, remote) {
30810
+ if (remote === null) {
30811
+ const stripped = { ...event };
30812
+ delete stripped.hostId;
30813
+ delete stripped.harnessId;
30814
+ delete stripped.sourceProjectId;
30815
+ return stripped;
30816
+ }
30817
+ const rekeyed = { ...event };
30818
+ delete rekeyed.hostId;
30819
+ delete rekeyed.harnessId;
30820
+ delete rekeyed.sourceProjectId;
30821
+ if (remote.hostId !== void 0) rekeyed.hostId = remote.hostId;
30822
+ if (remote.harnessId !== void 0) rekeyed.harnessId = remote.harnessId;
30823
+ if (remote.sourceProjectId !== void 0) rekeyed.sourceProjectId = remote.sourceProjectId;
30824
+ return rekeyed;
30825
+ }
30826
+ var BATCH_FORWARD_BUDGET_MS = 3e3;
30827
+ function llmAuditEvent(input) {
30828
+ return {
30829
+ id: llmCallId(input.sessionId, input.messageId),
30830
+ eventType: "llm_call",
30831
+ startedAt: input.startedAt,
30832
+ parentId: input.parentId,
30833
+ rootSessionId: input.rootSessionId,
30834
+ attributes: input.attributes
30835
+ };
30836
+ }
30837
+ function toolAuditEvent(input) {
30838
+ return {
30839
+ id: toolCallId(input.sessionId, input.toolUseId),
30840
+ eventType: "tool_call",
30841
+ startedAt: input.startedAt,
30842
+ parentId: input.parentId,
30843
+ rootSessionId: input.rootSessionId,
30844
+ attributes: input.attributes,
30845
+ inspections: input.inspections
30846
+ };
30847
+ }
30848
+
30849
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
30850
+ import { randomUUID as randomUUID16 } from "crypto";
30851
+ import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
30852
+ import { join as join19 } from "path";
30853
+
30854
+ // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
30855
+ import { rename as rename2 } from "fs/promises";
30856
+ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
30857
+ var ATTEMPTS = 5;
30858
+ var delay = (ms) => new Promise((resolve2) => {
30859
+ setTimeout(resolve2, ms);
30860
+ });
30861
+ async function publishByRename(tmp, file2, move = rename2) {
30862
+ for (let attempt = 1; ; attempt += 1) {
30863
+ try {
30864
+ await move(tmp, file2);
30865
+ return;
30866
+ } catch (err) {
30867
+ const code = err.code;
30868
+ if (attempt >= ATTEMPTS || code === void 0 || !RETRYABLE.has(code)) throw err;
30869
+ await delay(attempt * 10);
30870
+ }
30871
+ }
30872
+ }
30873
+
30874
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
30875
+ function createPolicyStore(dir = dataDir()) {
30876
+ const file2 = join19(dir, "policy-cache.json");
30877
+ async function read() {
30878
+ try {
30879
+ const raw = await readFile2(file2, "utf8");
30880
+ const parsed2 = JSON.parse(raw);
30881
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30882
+ const record2 = parsed2;
30883
+ const bundle = PolicyBundle.parse(record2.bundle);
30884
+ const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
30885
+ const etag = typeof record2.etag === "string" ? record2.etag : void 0;
30886
+ return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
30887
+ } catch {
30888
+ return null;
30889
+ }
30890
+ }
30891
+ async function write(bundle, etag) {
30892
+ await ensureDataDir(dir);
30893
+ const stored = {
30894
+ bundle,
30895
+ fetchedAtMs: Date.now(),
30896
+ ...etag === void 0 ? {} : { etag }
30897
+ };
30898
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
30899
+ try {
30900
+ await writeFile2(tmp, JSON.stringify(stored), {
30901
+ encoding: "utf8",
30902
+ mode: DATA_FILE_MODE,
30903
+ flag: "wx"
30904
+ });
30905
+ await publishByRename(tmp, file2);
30906
+ } catch (err) {
30907
+ await rm(tmp, { force: true }).catch(() => void 0);
30908
+ throw err;
30909
+ }
30910
+ }
30911
+ return { read, write, file: file2 };
30912
+ }
30913
+
30914
+ // ../../packages/remote/src/http.ts
30915
+ import { request as httpRequest } from "http";
30916
+ import { request as httpsRequest } from "https";
30917
+ var DEFAULT_TIMEOUT_MS = 1e4;
30918
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
30919
+ var RemoteRequestError = class extends Error {
30920
+ constructor(status) {
30921
+ super(`control-plane request failed with status ${String(status)}`);
30922
+ this.status = status;
30923
+ this.name = "RemoteRequestError";
30924
+ }
30925
+ status;
30926
+ };
30927
+ var RemoteRequestInvalid = class extends Error {
30928
+ constructor(route, cause) {
30929
+ super(`refusing to send a malformed body to ${route}`);
30930
+ this.cause = cause;
30931
+ this.name = "RemoteRequestInvalid";
30932
+ }
30933
+ cause;
30934
+ };
30935
+ var RemoteResponseInvalid = class extends Error {
30936
+ constructor(route, detail) {
30937
+ super(`control plane answered ${route} with ${detail}`);
30938
+ this.name = "RemoteResponseInvalid";
30939
+ }
30940
+ };
30941
+ var RemoteTransportError = class extends Error {
30942
+ /**
30943
+ * The status the peer sent, when headers arrived and only the BODY was
30944
+ * refused.
30945
+ *
30946
+ * Undefined for the ordinary case this class was written for — no answer at
30947
+ * all. It exists because two paths reject after a status has already been
30948
+ * delivered: an oversized body and an aborted response. Discarding it there
30949
+ * reported a deployment answering 401 with a verbose body as a network
30950
+ * outage, which sends the reader to look at their network instead of their
30951
+ * credential.
30952
+ */
30953
+ constructor(reason, status) {
30954
+ super(`control-plane request did not complete: ${reason}`);
30955
+ this.status = status;
30956
+ this.name = "RemoteTransportError";
30957
+ }
30958
+ status;
30959
+ };
30960
+ async function send(options) {
30961
+ const url2 = new URL(options.url);
30962
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
30963
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
30964
+ const requestOptions = {
30965
+ method: options.method,
30966
+ headers: {
30967
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
30968
+ // last they win, and two of the values below are ones no caller may
30969
+ // replace: `x-api-key` is the credential, and `content-length` is the
30970
+ // byte count that stops a multi-byte body being truncated by the
30971
+ // receiver. `SendOptions.headers` is a free-form record on an exported
30972
+ // function, so "no caller does that today" is not the guarantee to rely
30973
+ // on. The one header any caller actually passes — `if-none-match` on the
30974
+ // conditional GET — is untouched by this order.
30975
+ ...options.headers,
30976
+ // The credential. One header, matching what the deployment authenticates
30977
+ // on; a second copy in an `Authorization` header would be one more place
30978
+ // it can be logged by an intermediary for no gain.
30979
+ "x-api-key": options.apiKey,
30980
+ accept: "application/json",
30981
+ ...options.body === void 0 ? {} : {
30982
+ "content-type": "application/json",
30983
+ // Byte length, not string length: a multi-byte body sent with a
30984
+ // character count is truncated by the receiver.
30985
+ "content-length": String(Buffer.byteLength(options.body))
30986
+ }
30987
+ }
30988
+ };
30989
+ return new Promise((resolve2, reject) => {
30990
+ let settled = false;
30991
+ const fail = (reason, status) => {
30992
+ if (settled) return;
30993
+ settled = true;
30994
+ reject(new RemoteTransportError(reason, status));
30995
+ };
30996
+ const req = send_(url2, requestOptions, (res) => {
30997
+ const chunks = [];
30998
+ let size = 0;
30999
+ res.on("data", (chunk) => {
31000
+ size += chunk.length;
31001
+ if (size > MAX_RESPONSE_BYTES) {
31002
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
31003
+ res.destroy();
31004
+ req.destroy();
31005
+ return;
31006
+ }
31007
+ chunks.push(chunk);
31008
+ });
31009
+ res.on("aborted", () => {
31010
+ fail("the response was aborted", res.statusCode);
31011
+ });
31012
+ res.on("end", () => {
31013
+ if (settled) return;
31014
+ settled = true;
31015
+ resolve2({
31016
+ status: res.statusCode ?? 0,
31017
+ headers: res.headers,
31018
+ body: Buffer.concat(chunks).toString("utf8")
31019
+ });
31020
+ });
31021
+ });
31022
+ const deadline = setTimeout(() => {
31023
+ fail(`no response within ${String(timeoutMs)}ms`);
31024
+ req.destroy();
31025
+ }, timeoutMs);
31026
+ deadline.unref();
31027
+ req.on("upgrade", (_res, socket) => {
31028
+ fail("the deployment answered with a protocol upgrade");
31029
+ socket.destroy();
31030
+ });
31031
+ req.on("close", () => {
31032
+ fail("the connection closed before a response was read");
31033
+ clearTimeout(deadline);
31034
+ });
31035
+ req.on("error", (err) => {
31036
+ fail(err.message);
31037
+ });
31038
+ if (options.body !== void 0) req.write(options.body);
31039
+ req.end();
31040
+ });
31041
+ }
31042
+
31043
+ // ../../packages/remote/src/client.ts
31044
+ var ROUTES = {
31045
+ events: "/v1/events",
31046
+ auditEvents: "/v1/audit-events",
31047
+ inventory: "/v1/inventory",
31048
+ storePosture: "/v1/store-posture",
31049
+ policyBundle: "/v1/policy-bundle",
31050
+ whoami: "/v1/plugin/whoami"
31051
+ };
31052
+ function headerValue(response, name) {
31053
+ const raw = response.headers[name];
31054
+ if (raw === void 0) return void 0;
31055
+ return Array.isArray(raw) ? raw[0] : raw;
31056
+ }
31057
+ function okBody(response) {
31058
+ if (response.status < 200 || response.status >= 300) {
31059
+ throw new RemoteRequestError(response.status);
31060
+ }
31061
+ return response.body;
31062
+ }
31063
+ function parsed(schema, body, route) {
31064
+ let json2;
31065
+ try {
31066
+ json2 = JSON.parse(body);
31067
+ } catch {
31068
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
31069
+ }
31070
+ const result = schema.safeParse(json2);
31071
+ if (!result.success) {
31072
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
31073
+ }
31074
+ return result.data;
31075
+ }
31076
+ function withoutTrailingSlashes(endpoint) {
31077
+ let end = endpoint.length;
31078
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
31079
+ return endpoint.slice(0, end);
31080
+ }
31081
+ var SLASH = "/".charCodeAt(0);
31082
+ function createRemoteClient(options) {
31083
+ const base = withoutTrailingSlashes(options.endpoint);
31084
+ const url2 = (route) => `${base}${route}`;
31085
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
31086
+ return {
31087
+ async ingestEvents(batch) {
31088
+ const response = await send({
31089
+ ...common,
31090
+ method: "POST",
31091
+ url: url2(ROUTES.events),
31092
+ body: JSON.stringify(batch)
31093
+ });
31094
+ return parsed(IngestAck, okBody(response), ROUTES.events);
31095
+ },
31096
+ async ingestInventory(context) {
31097
+ const response = await send({
31098
+ ...common,
31099
+ method: "POST",
31100
+ url: url2(ROUTES.inventory),
31101
+ body: JSON.stringify(context)
31102
+ });
31103
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
31104
+ },
31105
+ async recordAuditEvent(event) {
31106
+ const validated = RecordAuditEventRequest.safeParse(event);
31107
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
31108
+ const submission = validated.data;
31109
+ const response = await send({
31110
+ ...common,
31111
+ method: "POST",
31112
+ url: url2(ROUTES.auditEvents),
31113
+ body: JSON.stringify(submission)
31114
+ });
31115
+ okBody(response);
31116
+ },
31117
+ async reportStorePosture(snapshot) {
31118
+ const response = await send({
31119
+ ...common,
31120
+ method: "POST",
31121
+ url: url2(ROUTES.storePosture),
31122
+ body: JSON.stringify(snapshot)
31123
+ });
31124
+ okBody(response);
31125
+ },
31126
+ async getPolicyBundle(etag) {
31127
+ const response = await send({
31128
+ ...common,
31129
+ method: "GET",
31130
+ url: url2(ROUTES.policyBundle),
31131
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
31132
+ });
31133
+ if (response.status === 304) {
31134
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
31135
+ }
31136
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
31137
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
31138
+ },
31139
+ async whoami() {
31140
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
31141
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
31142
+ }
31143
+ };
31144
+ }
31145
+
31146
+ // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
31147
+ var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
31148
+ function createPostureReporter(deps) {
31149
+ async function prepare() {
31150
+ try {
31151
+ const state = await withTimeout(deps.store.read(), REQUEST_TIMEOUT_MS);
31152
+ if (state === null) return null;
31153
+ const nowMs = deps.now();
31154
+ const elapsed = nowMs - state.lastAttemptedAtMs;
31155
+ if (elapsed >= 0 && elapsed < POSTURE_REPORT_INTERVAL_MS) return null;
31156
+ try {
31157
+ await withTimeout(deps.store.markAttempted(state.deviceId, nowMs), REQUEST_TIMEOUT_MS);
31158
+ } catch {
31159
+ }
31160
+ const { readError, ...measurement } = deps.readStore();
31161
+ if (readError) return null;
31162
+ let plugin;
31163
+ try {
31164
+ plugin = await deps.pluginBlock?.();
31165
+ } catch {
31166
+ plugin = void 0;
31167
+ }
31168
+ return {
31169
+ deviceId: state.deviceId,
31170
+ hostname: deps.hostname(),
31171
+ capturedAt: nowMs,
31172
+ ...measurement,
31173
+ // Omit the key rather than spread an explicit `undefined` —
31174
+ // exactOptionalPropertyTypes distinguishes the two, and the bridge in
31175
+ // factory.ts keys on presence.
31176
+ ...plugin === void 0 ? {} : { plugin }
31177
+ };
31178
+ } catch {
31179
+ return null;
31180
+ }
31181
+ }
31182
+ async function send2(snapshot) {
31183
+ try {
31184
+ await deps.report(snapshot);
31185
+ } catch {
31186
+ }
31187
+ }
31188
+ return { prepare, send: send2 };
31189
+ }
31190
+
31191
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31192
+ import { statSync as statSync9 } from "fs";
31193
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
31194
+
31195
+ // ../../packages/plugin-runtime/src/attached/action-counts.ts
31196
+ function emptyActionCounts() {
31197
+ return Object.fromEntries(ACTION_TAKEN_KEYS.map((a) => [a, 0]));
31198
+ }
31199
+ function isActionTaken(value) {
31200
+ return ACTION_TAKEN_KEYS.includes(value);
31201
+ }
31202
+
31203
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31204
+ var CAPTURE_EVENT_TYPES_SQL2 = `('prompt','response','code_change','tool_use')`;
31205
+ function isSchemaAbsent(err) {
31206
+ return err instanceof Error && /no such table/i.test(err.message);
31207
+ }
31208
+ function emptyReadout(readError = false) {
31209
+ const byAction = emptyActionCounts();
31210
+ return {
31211
+ storePresent: false,
31212
+ schemaVersion: null,
31213
+ findingsTotal: 0,
31214
+ findingsFirstAt: null,
31215
+ findingsLastAt: null,
31216
+ packs: [],
31217
+ policyCounts: { total: 0, disabled: 0, byAction },
31218
+ readError
31219
+ };
31220
+ }
31221
+ function readStorePosture(dbPath2) {
31222
+ try {
31223
+ statSync9(dbPath2);
31224
+ } catch (err) {
31225
+ const code = err.code;
31226
+ if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
31227
+ return emptyReadout(true);
31228
+ }
31229
+ let db = null;
31230
+ let version2 = null;
31231
+ let packs2 = [];
31232
+ let policyCounts = {
31233
+ total: 0,
31234
+ disabled: 0,
31235
+ byAction: emptyActionCounts()
31236
+ };
31237
+ let findingsTotal = 0;
31238
+ let findingsFirstAt = null;
31239
+ let findingsLastAt = null;
31240
+ const currentReadout = () => ({
31241
+ storePresent: true,
31242
+ schemaVersion: version2,
31243
+ findingsTotal,
31244
+ findingsFirstAt,
31245
+ findingsLastAt,
31246
+ packs: packs2,
31247
+ policyCounts,
31248
+ readError: false
31249
+ });
31250
+ try {
31251
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
31252
+ db.exec("PRAGMA busy_timeout = 2000");
31253
+ version2 = db.prepare("PRAGMA user_version").get().user_version;
31254
+ try {
31255
+ const packRows = db.prepare(
31256
+ `SELECT namespace, pack_id, version, enabled, updated_at FROM installed_packs ORDER BY namespace, pack_id`
31257
+ ).all();
31258
+ packs2 = packRows.map((r) => ({
31259
+ packId: `${r.namespace}/${r.pack_id}`,
31260
+ version: r.version,
31261
+ enabled: r.enabled !== 0,
31262
+ updatedAt: r.updated_at == null ? null : String(r.updated_at)
31263
+ }));
31264
+ } catch (err) {
31265
+ if (!isSchemaAbsent(err)) throw err;
31266
+ }
31267
+ try {
31268
+ const policyRows = db.prepare(`SELECT action, enabled FROM policies`).all();
31269
+ const byAction = emptyActionCounts();
31270
+ let disabled = 0;
31271
+ for (const row of policyRows) {
31272
+ if (row.enabled === 0) disabled += 1;
31273
+ if (isActionTaken(row.action)) byAction[row.action] += 1;
31274
+ }
31275
+ policyCounts = { total: policyRows.length, disabled, byAction };
31276
+ } catch (err) {
31277
+ if (!isSchemaAbsent(err)) throw err;
31278
+ }
31279
+ try {
31280
+ const agg = db.prepare(
31281
+ `SELECT count(*) AS n, min(f.first_detected_at) AS firstAt, max(f.first_detected_at) AS lastAt
31282
+ FROM inspection_findings f JOIN audit_events e ON e.id = f.audit_event_id
31283
+ WHERE e.event_type IN ${CAPTURE_EVENT_TYPES_SQL2}`
31284
+ ).get();
31285
+ findingsTotal = agg.n;
31286
+ findingsFirstAt = agg.firstAt;
31287
+ findingsLastAt = agg.lastAt;
31288
+ } catch (err) {
31289
+ if (!isSchemaAbsent(err)) throw err;
31290
+ }
31291
+ return currentReadout();
31292
+ } catch {
31293
+ return emptyReadout(true);
31294
+ } finally {
31295
+ try {
31296
+ db?.close();
31297
+ } catch {
31298
+ }
31299
+ }
31300
+ }
31301
+
31302
+ // ../../packages/plugin-runtime/src/attached/posture-store.ts
31303
+ import { randomUUID as randomUUID17 } from "crypto";
31304
+ import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
31305
+ import { join as join20 } from "path";
31306
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
31307
+ function createPostureStore(dir = settingsDir(), legacyDir) {
31308
+ const file2 = join20(dir, "posture-state.json");
31309
+ const legacyFile = legacyDir === void 0 ? null : join20(legacyDir, "posture-state.json");
31310
+ async function persist(state) {
31311
+ await ensureDataDir(dir);
31312
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
31313
+ try {
31314
+ await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
31315
+ await publishByRename(tmp, file2);
31316
+ } catch (err) {
31317
+ await rm2(tmp, { force: true }).catch(() => void 0);
31318
+ throw err;
31319
+ }
31320
+ }
31321
+ async function readFrom(path) {
31322
+ let raw;
31323
+ try {
31324
+ raw = await readFile3(path, "utf8");
31325
+ } catch (err) {
31326
+ const code = err.code;
31327
+ if (code === "ENOENT" || code === "ENOTDIR") return null;
31328
+ throw err;
31329
+ }
31330
+ try {
31331
+ const parsed2 = JSON.parse(raw);
31332
+ if (typeof parsed2 === "object" && parsed2 !== null) {
31333
+ const record2 = parsed2;
31334
+ if (typeof record2.deviceId === "string" && UUID_RE.test(record2.deviceId)) {
31335
+ const stamp = typeof record2.lastAttemptedAtMs === "number" ? record2.lastAttemptedAtMs : typeof record2.lastReportedAtMs === "number" ? record2.lastReportedAtMs : 0;
31336
+ return { deviceId: record2.deviceId, lastAttemptedAtMs: stamp };
31337
+ }
31338
+ }
31339
+ } catch {
31340
+ }
31341
+ return null;
31342
+ }
31343
+ async function read() {
31344
+ const current = await readFrom(file2);
31345
+ if (current) return current;
31346
+ const legacy = legacyFile === null || legacyFile === file2 ? null : await readFrom(legacyFile).catch(() => null);
31347
+ if (legacy) {
31348
+ try {
31349
+ await persist(legacy);
31350
+ } catch {
31351
+ }
31352
+ return legacy;
31353
+ }
31354
+ const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
31355
+ try {
31356
+ await ensureDataDir(dir);
31357
+ if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
31358
+ } catch {
31359
+ return null;
31360
+ }
31361
+ const winner = await readFrom(file2).catch(() => null);
31362
+ if (winner) return winner;
31363
+ try {
31364
+ await persist(fresh);
31365
+ } catch {
31366
+ return null;
31367
+ }
31368
+ return fresh;
31369
+ }
31370
+ async function markAttempted(deviceId, atMs) {
31371
+ await persist({ deviceId, lastAttemptedAtMs: atMs });
31372
+ }
31373
+ return { read, markAttempted, file: file2 };
31374
+ }
31375
+
31376
+ // ../../packages/plugin-runtime/src/attached/sync-state.ts
31377
+ import { readFileSync as readFileSync13 } from "fs";
31378
+ import { join as join21 } from "path";
31379
+
31380
+ // ../../packages/plugin-runtime/src/attached/status.ts
31381
+ var REFUSAL_LINES = {
31382
+ unauthorized: "KEY REJECTED \u2014 re-attach with a valid plugin key",
31383
+ forbidden: "ACCESS REFUSED \u2014 key is valid but not permitted; ask your org admin"
31384
+ };
31385
+ var OUTCOME_LINES = {
31386
+ ok: "policy synced",
31387
+ "not-modified": "policy up to date",
31388
+ unauthorized: REFUSAL_LINES.unauthorized,
31389
+ forbidden: REFUSAL_LINES.forbidden,
31390
+ unreachable: "control plane unreachable at last attempt",
31391
+ "invalid-bundle": "control plane sent a policy bundle this build cannot read"
31392
+ };
31393
+
31394
+ // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
31395
+ import { spawn } from "child_process";
31396
+ import { fileURLToPath as fileURLToPath2 } from "url";
31397
+ var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
31398
+
31399
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31400
+ import { hostname as hostname5 } from "os";
31401
+
31402
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
31403
+ import { randomUUID as randomUUID18 } from "crypto";
31404
+
31405
+ // ../../packages/plugin-runtime/src/recorder.ts
31406
+ var PLUGIN_RECORDER_BINARY = "plugin";
31407
+
31408
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
31409
+ var StandaloneDataGateway = class {
31410
+ db;
31411
+ // Kept for the fingerprint key lookup (exception.key lives beside the store).
31412
+ dataDir;
31413
+ // One notice per gateway — see warnRulesetDiscarded.
31414
+ warnedRulesetDiscarded = false;
31415
+ constructor(dataDir2, detections = [], meta3) {
31416
+ this.db = openLocalDatabase(dataDir2);
31417
+ this.dataDir = dataDir2;
31418
+ this.db.installedPacks.recordInventory(detections, meta3);
31419
+ }
31420
+ recordCapture(record2) {
31421
+ this.db.recordCapture(record2.event, record2.findings);
31422
+ return Promise.resolve();
31423
+ }
31424
+ ensureInventory(ctx) {
31425
+ return Promise.resolve(this.db.ensureInventory(ctx));
31426
+ }
31427
+ recordAuditEvent(event) {
31428
+ this.db.auditEvents.insertAuditEvent(event);
31429
+ return Promise.resolve();
31430
+ }
31431
+ // The id is minted inside the repository from the natural key — the plugin can't
29948
31432
  // import @akasecurity/persistence to compute it, so the gateway is the boundary that
29949
31433
  // hands the natural key across. UPSERT-take-MAX → idempotent re-reads that also
29950
31434
  // converge a streaming partial/final split (see insertLlmCall).
@@ -29957,12 +31441,12 @@ var StandaloneDataGateway = class {
29957
31441
  // reconciler drops the whole pass and recovers it idempotently on the next read.
29958
31442
  recordLlmCalls(inputs) {
29959
31443
  if (inputs.length === 0) return Promise.resolve();
29960
- return new Promise((resolve, reject) => {
31444
+ return new Promise((resolve2, reject) => {
29961
31445
  try {
29962
31446
  this.db.auditEvents.runInTransaction(() => {
29963
31447
  for (const input of inputs) this.db.auditEvents.insertLlmCall(input);
29964
31448
  });
29965
- resolve();
31449
+ resolve2();
29966
31450
  } catch (err) {
29967
31451
  reject(err instanceof Error ? err : new Error(String(err)));
29968
31452
  }
@@ -29974,12 +31458,12 @@ var StandaloneDataGateway = class {
29974
31458
  // drops the whole pass and recovers it idempotently next time.
29975
31459
  recordToolCalls(inputs) {
29976
31460
  if (inputs.length === 0) return Promise.resolve();
29977
- return new Promise((resolve, reject) => {
31461
+ return new Promise((resolve2, reject) => {
29978
31462
  try {
29979
31463
  this.db.auditEvents.runInTransaction(() => {
29980
31464
  for (const input of inputs) this.writeToolCall(input);
29981
31465
  });
29982
- resolve();
31466
+ resolve2();
29983
31467
  } catch (err) {
29984
31468
  reject(err instanceof Error ? err : new Error(String(err)));
29985
31469
  }
@@ -30121,7 +31605,7 @@ var StandaloneDataGateway = class {
30121
31605
  const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
30122
31606
  const installed = this.installedScanRules();
30123
31607
  const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
30124
- id: randomUUID15(),
31608
+ id: randomUUID18(),
30125
31609
  scope: "global",
30126
31610
  target: { ruleId },
30127
31611
  action,
@@ -30275,15 +31759,61 @@ var StandaloneDataGateway = class {
30275
31759
  }
30276
31760
  };
30277
31761
 
31762
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31763
+ function resolveGatewayForConfig(config2, meta3) {
31764
+ const local = new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
31765
+ try {
31766
+ if (!isAttached(config2.settings)) return local;
31767
+ const connection = config2.settings.controlPlane;
31768
+ if (connection === void 0) return local;
31769
+ const state = readControlPlaneCredentialState(config2.settingsDir, connection);
31770
+ if (!state.usable) return local;
31771
+ const client = createRemoteClient({
31772
+ endpoint: connection.endpoint,
31773
+ apiKey: state.credential.apiKey
31774
+ });
31775
+ const store = createPolicyStore(config2.dataDir);
31776
+ const postureStore = createPostureStore(config2.settingsDir, config2.dataDir);
31777
+ const forward = createForwardPolicy({ dir: config2.dataDir });
31778
+ return new AttachedDataGateway({
31779
+ local,
31780
+ client,
31781
+ dataDir: config2.dataDir,
31782
+ readCachedBundle: () => store.read().then((cached2) => cached2?.bundle ?? null),
31783
+ forward,
31784
+ posture: createPostureReporter({
31785
+ // THROUGH THE BREAKER, and wrapped HERE rather than around
31786
+ // `PostureReporter.send`. The reporter swallows every error by
31787
+ // contract, so a wrap outside it would hand `forward.run` a resolved
31788
+ // promise for a send that failed — recording a SUCCESS, clearing
31789
+ // `consecutiveFailures` and `lastFailure`, and telling `aka status` the
31790
+ // forward recovered when nothing did. Wrapping the raw client call puts
31791
+ // the breaker above the swallow, where it can see the truth.
31792
+ //
31793
+ // What it buys: once the breaker is open — the plane already confirmed
31794
+ // down by the gateway's own writes — this stops paying a request
31795
+ // timeout per throttle interval to re-learn it.
31796
+ report: (snapshot) => forward.run(() => client.reportStorePosture(snapshot)).then(() => void 0),
31797
+ store: postureStore,
31798
+ readStore: () => readStorePosture(config2.dbPath),
31799
+ hostname: () => hostname5(),
31800
+ now: () => Date.now()
31801
+ })
31802
+ });
31803
+ } catch {
31804
+ return local;
31805
+ }
31806
+ }
31807
+
30278
31808
  // ../../packages/plugin-runtime/src/resolve.ts
30279
- var standaloneGatewayFactory = (config2, meta3) => new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
30280
- var defaultGatewayFactory = standaloneGatewayFactory;
31809
+ var configuredGatewayFactory = (config2, meta3) => resolveGatewayForConfig(config2, meta3);
31810
+ var defaultGatewayFactory = configuredGatewayFactory;
30281
31811
  function resolveDataGateway(config2, meta3, gatewayFactory = defaultGatewayFactory) {
30282
31812
  return gatewayFactory(config2, meta3);
30283
31813
  }
30284
31814
 
30285
31815
  // ../../packages/plugin-runtime/src/handle-session-start.ts
30286
- import { randomUUID as randomUUID16 } from "crypto";
31816
+ import { randomUUID as randomUUID19 } from "crypto";
30287
31817
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
30288
31818
 
30289
31819
  // src/present.ts
@@ -30393,7 +31923,7 @@ function responseEmitPayload(outcome) {
30393
31923
 
30394
31924
  // src/hooks/shared.ts
30395
31925
  async function readStdin() {
30396
- return new Promise((resolve) => {
31926
+ return new Promise((resolve2) => {
30397
31927
  let data = "";
30398
31928
  let settled = false;
30399
31929
  const finish = () => {
@@ -30402,7 +31932,7 @@ async function readStdin() {
30402
31932
  clearTimeout(timer);
30403
31933
  process.stdin.removeListener("data", onData);
30404
31934
  process.stdin.removeListener("end", finish);
30405
- resolve(data);
31935
+ resolve2(data);
30406
31936
  };
30407
31937
  const onData = (chunk) => {
30408
31938
  data += chunk;
@@ -30416,8 +31946,8 @@ async function readStdin() {
30416
31946
  }
30417
31947
  function parseJson(raw) {
30418
31948
  try {
30419
- const parsed = JSON.parse(raw);
30420
- return typeof parsed === "object" && parsed !== null ? parsed : null;
31949
+ const parsed2 = JSON.parse(raw);
31950
+ return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
30421
31951
  } catch {
30422
31952
  return null;
30423
31953
  }
@@ -30427,12 +31957,12 @@ function getString(record2, key) {
30427
31957
  return typeof value === "string" ? value : void 0;
30428
31958
  }
30429
31959
  function emit(output) {
30430
- return new Promise((resolve) => {
31960
+ return new Promise((resolve2) => {
30431
31961
  let settled = false;
30432
31962
  const finish = () => {
30433
31963
  if (settled) return;
30434
31964
  settled = true;
30435
- resolve();
31965
+ resolve2();
30436
31966
  };
30437
31967
  process.stdout.on("error", finish);
30438
31968
  process.stdout.write(JSON.stringify(output), finish);
@@ -30447,6 +31977,65 @@ function baseMetadata(input) {
30447
31977
  return Object.keys(metadata).length > 0 ? metadata : void 0;
30448
31978
  }
30449
31979
 
31980
+ // src/hooks/store-health.ts
31981
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync14, writeFileSync as writeFileSync7 } from "fs";
31982
+ import { dirname as dirname5, join as join22 } from "path";
31983
+ var STORE_REDIRECT_MARKER = "store-redirect-last-session";
31984
+ function markerDirs(dataDir2) {
31985
+ return [dataDir2, dirname5(dataDir2)];
31986
+ }
31987
+ function alreadyClaimed(dirs, marker, sessionId) {
31988
+ return dirs.some((dir) => {
31989
+ try {
31990
+ return readFileSync14(join22(dir, marker), "utf8") === sessionId;
31991
+ } catch {
31992
+ return false;
31993
+ }
31994
+ });
31995
+ }
31996
+ function recordClaim(dirs, marker, sessionId) {
31997
+ for (const dir of dirs) {
31998
+ try {
31999
+ mkdirSync4(dir, { recursive: true, mode: DATA_DIR_MODE });
32000
+ writeFileSync7(join22(dir, marker), sessionId, { mode: DATA_FILE_MODE });
32001
+ return;
32002
+ } catch {
32003
+ }
32004
+ }
32005
+ }
32006
+ function storeRedirectedMessage(paths, platform2 = process.platform) {
32007
+ const where = paths.map(({ path, target, holds, missing, mode }) => {
32008
+ if (missing) return `${path} -> ${target} (which does not exist; ${holds} cannot land there)`;
32009
+ const loose = mode !== void 0 && (mode & 63) !== 0 ? ", NOT owner-only" : "";
32010
+ const inherited = mode === void 0 ? "" : ` (${formatMode(mode)}${loose})`;
32011
+ return `${path} -> ${target}${inherited}, holding ${holds}`;
32012
+ }).join("; ");
32013
+ const subject = paths.length === 1 ? "a store path is a symlink" : `${String(paths.length)} store paths are symlinks`;
32014
+ const anyResolves = paths.some(({ missing }) => !missing);
32015
+ const lead = anyResolves ? `${subject}, so AKA is writing into the target instead: ${where}. ` : `${subject} resolving nowhere, so AKA cannot write there: ${where}. `;
32016
+ const kept = anyResolves && platform2 !== "win32" ? "Permissions are never changed through a symlink, so the store keeps whatever the target already had. " : "";
32017
+ return `[aka] ${lead}${kept}If you did not create that link, treat it as untrusted and run \`aka init\` for the full report.
32018
+ `;
32019
+ }
32020
+ function formatMode(mode) {
32021
+ return `0${mode.toString(8).padStart(3, "0")}`;
32022
+ }
32023
+ function warnIfStoreRedirected(config2, sessionId, write = (message) => void process.stderr.write(message)) {
32024
+ try {
32025
+ const paths = symlinkedStorePaths(dirname5(config2.dataDir));
32026
+ if (paths.length === 0) return;
32027
+ if (!sessionId) {
32028
+ write(storeRedirectedMessage(paths));
32029
+ return;
32030
+ }
32031
+ const dirs = markerDirs(config2.dataDir);
32032
+ if (alreadyClaimed(dirs, STORE_REDIRECT_MARKER, sessionId)) return;
32033
+ write(storeRedirectedMessage(paths));
32034
+ recordClaim(dirs, STORE_REDIRECT_MARKER, sessionId);
32035
+ } catch {
32036
+ }
32037
+ }
32038
+
30450
32039
  // src/hooks/tool-response.ts
30451
32040
  var RESPONSE_TEXT_PATHS = {
30452
32041
  Bash: [["stdout"], ["stderr"]]
@@ -30487,6 +32076,7 @@ async function main() {
30487
32076
  const filePath = typeof rawToolInput === "object" && rawToolInput !== null ? getString(rawToolInput, "file_path") : void 0;
30488
32077
  if (filePath) metadata.filePath = filePath;
30489
32078
  const config2 = loadConfig();
32079
+ warnIfStoreRedirected(config2, getString(input, "session_id"));
30490
32080
  const gateway = resolveDataGateway(config2);
30491
32081
  const runtime = createPluginRuntime(gateway, config2.settings, { dataDir: config2.dataDir });
30492
32082
  let outcome;