@akasecurity/ai-tc-antigravity 0.9.7 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH = "/";
53
+ var SLASH2 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH).filter(Boolean);
425
+ const slices = path.split(SLASH2).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH) + SLASH,
429
+ slices.join(SLASH2) + SLASH2,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH).filter(Boolean);
445
+ slices = path.split(SLASH2).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH) + SLASH,
452
+ slices.join(SLASH2) + SLASH2,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,16 +492,33 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/hooks/pre-invocation.ts
495
- import { readFileSync as readFileSync11 } from "fs";
495
+ import { readFileSync as readFileSync16 } from "fs";
496
+
497
+ // ../../packages/plugin-runtime/src/attached/failure.ts
498
+ function statusOf(err) {
499
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
500
+ const { status } = err;
501
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
502
+ return status >= 100 && status <= 599 ? status : null;
503
+ }
504
+ function classifyFailure(err) {
505
+ switch (statusOf(err)) {
506
+ case 401:
507
+ return "unauthorized";
508
+ case 403:
509
+ return "forbidden";
510
+ default:
511
+ return "unreachable";
512
+ }
513
+ }
496
514
 
497
- // ../../packages/plugin-sdk/src/config.ts
498
- import { existsSync as existsSync5 } from "fs";
499
- import { join as join8 } from "path";
515
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
516
+ import { readFileSync as readFileSync7 } from "fs";
517
+ import { join as join10 } from "path";
500
518
 
501
- // ../../packages/persistence/src/database.ts
502
- import { randomUUID as randomUUID10 } from "crypto";
503
- import { join as join2, sep } from "path";
504
- import { DatabaseSync } from "node:sqlite";
519
+ // ../../packages/persistence/src/control-plane-credential.ts
520
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync2, statSync } from "fs";
521
+ import { join } from "path";
505
522
 
506
523
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
507
524
  var SQLITE_MIGRATIONS = [
@@ -16322,6 +16339,125 @@ var ConfigScanRecord = external_exports.object({
16322
16339
  findings: external_exports.array(ConfigPostureFindingInput).optional()
16323
16340
  });
16324
16341
 
16342
+ // ../../packages/schema/src/zod/control-plane.ts
16343
+ var ATTACHED_CREDENTIAL_FILENAME = "control-plane-credential.json";
16344
+ var ATTACHED_CREDENTIAL_SPEC_VERSION = 1;
16345
+ var AttachedCredential = external_exports.object({
16346
+ specVersion: external_exports.literal(ATTACHED_CREDENTIAL_SPEC_VERSION),
16347
+ // The control-plane endpoint this credential was minted against.
16348
+ endpoint: external_exports.string().min(1),
16349
+ // The bearer credential itself. Never logged, never rendered — status
16350
+ // surfaces show `keyPrefix` and nothing else.
16351
+ apiKey: external_exports.string().min(1),
16352
+ // First few characters of the key, safe to display so a user can match the
16353
+ // credential against their organization's key list.
16354
+ keyPrefix: external_exports.string().min(1).max(16).optional(),
16355
+ mintedAt: external_exports.iso.datetime().optional()
16356
+ });
16357
+ var MAX_DATE_MS = 253402300799999;
16358
+ var MAX_INT4 = 2147483647;
16359
+ var StorePosturePack = external_exports.object({
16360
+ packId: external_exports.string().min(1),
16361
+ // 'namespace/packId'
16362
+ version: external_exports.string().min(1),
16363
+ enabled: external_exports.boolean(),
16364
+ // Stringified pass-through of the local store's `installed_packs.updated_at`
16365
+ // — the column format is store-version-dependent (epoch millis vs ISO), so
16366
+ // the wire shape assumes neither.
16367
+ updatedAt: external_exports.string().nullable()
16368
+ }).meta({ id: "StorePosturePack" });
16369
+ var StorePosturePolicyCounts = external_exports.object({
16370
+ total: external_exports.number().int().min(0),
16371
+ disabled: external_exports.number().int().min(0),
16372
+ // Exhaustive per-action map; the builder pre-fills every action with 0.
16373
+ //
16374
+ // Spelled out member-by-member rather than `z.record(ActionTaken, …)`. Zod
16375
+ // enforces exhaustiveness either way, but z.record emits `propertyNames` +
16376
+ // `additionalProperties` into a generated schema document, and a type
16377
+ // generator renders THAT with every key optional — a sender built against
16378
+ // the generated type would typecheck and still be rejected at runtime. An
16379
+ // explicit object emits `properties` + `required`, so generated types
16380
+ // demand all five.
16381
+ //
16382
+ // `satisfies Record<ActionTaken, …>` keeps the link to the enum: adding an
16383
+ // ActionTaken member is a COMPILE error here instead of silent drift.
16384
+ // `.strict()` is load-bearing — it rejects an unknown action key, which a
16385
+ // bare object would silently STRIP, accepting a miscounted map as valid.
16386
+ byAction: external_exports.object({
16387
+ warn: external_exports.number().int().min(0),
16388
+ redact: external_exports.number().int().min(0),
16389
+ block: external_exports.number().int().min(0),
16390
+ allow: external_exports.number().int().min(0),
16391
+ log: external_exports.number().int().min(0)
16392
+ }).strict()
16393
+ }).meta({ id: "StorePosturePolicyCounts" });
16394
+ var StorePosturePlugin = external_exports.object({
16395
+ /** Package name of the reporting plugin. */
16396
+ package: external_exports.string().min(1).max(200),
16397
+ version: external_exports.string().min(1).max(64),
16398
+ /** Version of the bundled core, when the build records one separately. */
16399
+ ossVersion: external_exports.string().max(64).nullable(),
16400
+ /**
16401
+ * `version` of the policy bundle this machine last fetched. Bounded at 200
16402
+ * rather than the 64 a bare sha256 hex digest needs today, so a later
16403
+ * format with an algorithm prefix does not start rejecting the channel.
16404
+ */
16405
+ policyBundleVersion: external_exports.string().max(200).nullable(),
16406
+ /** Epoch millis, on the CLIENT clock, of that fetch. */
16407
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
16408
+ }).meta({ id: "StorePosturePlugin" });
16409
+ var StorePostureSnapshot = external_exports.object({
16410
+ deviceId: external_exports.guid(),
16411
+ hostname: external_exports.string().min(1).max(253),
16412
+ // Epoch millis on the CLIENT clock. Bounded by what a receiving store
16413
+ // accepts (see MAX_DATE_MS), not by what a JavaScript Date can hold.
16414
+ capturedAt: external_exports.number().int().min(0).max(MAX_DATE_MS),
16415
+ // False is a measurement, not an error state: "no local store exists on
16416
+ // this machine".
16417
+ storePresent: external_exports.boolean(),
16418
+ schemaVersion: external_exports.number().int().min(0).max(MAX_INT4).nullable(),
16419
+ // PRAGMA user_version
16420
+ findingsTotal: external_exports.number().int().min(0).max(MAX_INT4),
16421
+ // Epoch millis, bounded like `capturedAt` — see MAX_DATE_MS on what that
16422
+ // bound does and does not do. Worth stating for these two specifically:
16423
+ // they are read from the local store's own ROWS rather than from this
16424
+ // machine's clock, so a damaged or hand-edited store is enough to produce
16425
+ // an out-of-range value with no clock skew involved.
16426
+ findingsFirstAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16427
+ findingsLastAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16428
+ packs: external_exports.array(StorePosturePack).max(500),
16429
+ policyCounts: StorePosturePolicyCounts,
16430
+ // OPTIONAL, not nullable: a reporter that predates this member keeps
16431
+ // getting its 200 without a payload change.
16432
+ plugin: StorePosturePlugin.optional()
16433
+ }).meta({ id: "StorePostureSnapshot" });
16434
+ var CAPTURE_VERSION_PREFIX = "capture/";
16435
+ var RecordAuditEventRequest = AuditEventInput.extend({
16436
+ inspections: external_exports.array(ToolCallInspection).default([])
16437
+ }).refine((v) => v.inspections.every((i) => !i.ruleVersion.startsWith(CAPTURE_VERSION_PREFIX)), {
16438
+ message: `inspections[].ruleVersion must not start with \`${CAPTURE_VERSION_PREFIX}\` \u2014 that namespace is reserved for capture definitions the control plane mints itself`,
16439
+ path: ["inspections"]
16440
+ }).meta({ id: "RecordAuditEventRequest" });
16441
+ var IngestAck = external_exports.object({
16442
+ accepted: external_exports.number().int().nonnegative(),
16443
+ duplicates: external_exports.number().int().nonnegative()
16444
+ });
16445
+ var PRINTABLE = /^[^\p{Cc}\p{Cf}]*$/u;
16446
+ var printable = (max) => external_exports.string().max(max).regex(PRINTABLE, "must not contain control characters");
16447
+ var PluginWhoami = external_exports.object({
16448
+ tenantName: printable(200),
16449
+ userEmail: printable(320),
16450
+ role: printable(64),
16451
+ keyKind: printable(64),
16452
+ serverTime: printable(64)
16453
+ });
16454
+ var ControlPlaneErrorBody = external_exports.object({
16455
+ error: external_exports.object({
16456
+ code: external_exports.string().optional(),
16457
+ message: external_exports.string().optional()
16458
+ }).optional()
16459
+ });
16460
+
16325
16461
  // ../../packages/schema/src/zod/registry.ts
16326
16462
  var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
16327
16463
  var PackId = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -16624,15 +16760,15 @@ function summaryToDetectionListItem(s) {
16624
16760
  }
16625
16761
  function rowToDetectionDetail(row, findingsLast30d, update) {
16626
16762
  const rules = row.rules.flatMap((r) => {
16627
- const parsed = Matcher.safeParse(r.matcher);
16628
- if (!parsed.success) return [];
16763
+ const parsed2 = Matcher.safeParse(r.matcher);
16764
+ if (!parsed2.success) return [];
16629
16765
  return [
16630
16766
  {
16631
16767
  id: r.id,
16632
16768
  name: r.name,
16633
16769
  category: r.category,
16634
16770
  severity: r.severity,
16635
- matcher: parsed.data
16771
+ matcher: parsed2.data
16636
16772
  }
16637
16773
  ];
16638
16774
  });
@@ -17278,8 +17414,8 @@ function toApiAction(dbVal) {
17278
17414
  }
17279
17415
  function toApiCategory(dbVal) {
17280
17416
  if (dbVal === "code_context") return "source_code";
17281
- const parsed = FindingCategory.safeParse(dbVal);
17282
- return parsed.success ? parsed.data : "custom";
17417
+ const parsed2 = FindingCategory.safeParse(dbVal);
17418
+ return parsed2.success ? parsed2.data : "custom";
17283
17419
  }
17284
17420
  function toApiProvider(sourceTool) {
17285
17421
  return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
@@ -17909,6 +18045,9 @@ var WorkspaceSettings = external_exports.object({
17909
18045
  function defaultWorkspaceSettings() {
17910
18046
  return WorkspaceSettings.parse({});
17911
18047
  }
18048
+ function isAttached(settings) {
18049
+ return settings.runMode === "attached" && settings.controlPlane !== void 0;
18050
+ }
17912
18051
  function toInventoryRow(input, id, now) {
17913
18052
  return {
17914
18053
  id,
@@ -18176,8 +18315,8 @@ function builtinPolicyIsReversible(id) {
18176
18315
  return BUILTIN_POLICY_SPECS[id].reversible;
18177
18316
  }
18178
18317
  function policyIdIsReversible(policyId) {
18179
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18180
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18318
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18319
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18181
18320
  return builtinPolicyIsReversible(id);
18182
18321
  }
18183
18322
  var DEFAULT_ACTIONS = Object.fromEntries(
@@ -18188,8 +18327,8 @@ var BUILTIN_POLICIES = Object.fromEntries(
18188
18327
  );
18189
18328
  var DEFAULT_PACK_POLICY_ID = "monitor";
18190
18329
  function policyIdToAction(policyId) {
18191
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18192
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18330
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18331
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18193
18332
  return BUILTIN_POLICIES[id].action;
18194
18333
  }
18195
18334
  var UsedByItem = external_exports.object({
@@ -18632,53 +18771,6 @@ function reviewSeverityRank(reasons) {
18632
18771
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
18633
18772
  }
18634
18773
 
18635
- // ../../packages/persistence/src/ids.ts
18636
- import { createHash } from "crypto";
18637
- function sha256Hex(input) {
18638
- return createHash("sha256").update(input).digest("hex");
18639
- }
18640
- function inventoryId(objectType, identityKey) {
18641
- return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18642
- }
18643
- function sourceProjectId(url2) {
18644
- return sha256Hex(canonicalIdentity(["source_project", url2]));
18645
- }
18646
- function classifiedDataId(cls) {
18647
- return sha256Hex(canonicalIdentity(["classified_data", cls]));
18648
- }
18649
- function inspectionDefinitionId(ruleId, version2) {
18650
- return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18651
- }
18652
- function llmCallId(sessionId, messageId) {
18653
- return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18654
- }
18655
- function toolCallId(sessionId, toolUseId) {
18656
- return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18657
- }
18658
- function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18659
- return sha256Hex(
18660
- canonicalIdentity([
18661
- "inspection_finding",
18662
- auditEventId,
18663
- ruleId,
18664
- String(spanStart),
18665
- String(spanEnd)
18666
- ])
18667
- );
18668
- }
18669
- var NO_SESSION = "no_session";
18670
- var NO_PATH = "no_path";
18671
- function captureId(sessionId, contentHash, filePath = null) {
18672
- return sha256Hex(
18673
- canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18674
- );
18675
- }
18676
-
18677
- // ../../packages/persistence/src/internal/snapshot.ts
18678
- import { randomUUID } from "crypto";
18679
- import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync2, statSync } from "fs";
18680
- import { basename, dirname, join } from "path";
18681
-
18682
18774
  // ../../packages/persistence/src/paths.ts
18683
18775
  import {
18684
18776
  chmodSync,
@@ -18726,8 +18818,181 @@ function tightenFile(file2) {
18726
18818
  function tightenPerms(file2) {
18727
18819
  for (const path of [file2, ...dbSidecars(file2)]) chmodBestEffort(path, DATA_FILE_MODE);
18728
18820
  }
18821
+ function writeExclusiveOwnerOnlySync(file2, data) {
18822
+ writeFileSync(file2, data, { mode: DATA_FILE_MODE, flag: "wx" });
18823
+ }
18824
+ function writeOwnerOnlyFileSync(file2, data) {
18825
+ const tmp = `${file2}.${String(process.pid)}.tmp`;
18826
+ try {
18827
+ rmSync(tmp, { force: true });
18828
+ } catch {
18829
+ }
18830
+ try {
18831
+ writeExclusiveOwnerOnlySync(tmp, data);
18832
+ renameSync(tmp, file2);
18833
+ } finally {
18834
+ try {
18835
+ rmSync(tmp, { force: true });
18836
+ } catch {
18837
+ }
18838
+ }
18839
+ tightenFile(file2);
18840
+ }
18841
+ function createOwnerOnlyFileSync(file2, data) {
18842
+ const tmp = `${file2}.${String(process.pid)}.${String(threadId)}.new`;
18843
+ try {
18844
+ rmSync(tmp, { force: true });
18845
+ } catch {
18846
+ }
18847
+ let created;
18848
+ try {
18849
+ writeExclusiveOwnerOnlySync(tmp, data);
18850
+ created = publishByLink(tmp, file2, data);
18851
+ } finally {
18852
+ try {
18853
+ rmSync(tmp, { force: true });
18854
+ } catch {
18855
+ }
18856
+ }
18857
+ if (created) tightenFile(file2);
18858
+ return created;
18859
+ }
18860
+ var LINK_UNSUPPORTED = /* @__PURE__ */ new Set(["EPERM", "ENOSYS", "ENOTSUP", "EOPNOTSUPP", "EINVAL"]);
18861
+ function publishByLink(tmp, file2, data) {
18862
+ try {
18863
+ linkSync(tmp, file2);
18864
+ return true;
18865
+ } catch (err) {
18866
+ const code = err.code;
18867
+ if (code === "EEXIST") return false;
18868
+ if (!LINK_UNSUPPORTED.has(code ?? "")) throw err;
18869
+ }
18870
+ try {
18871
+ writeExclusiveOwnerOnlySync(file2, data);
18872
+ return true;
18873
+ } catch (err) {
18874
+ if (err.code === "EEXIST") return false;
18875
+ throw err;
18876
+ }
18877
+ }
18878
+
18879
+ // ../../packages/persistence/src/control-plane-credential.ts
18880
+ function controlPlaneCredentialPath(settingsDir2) {
18881
+ return join(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
18882
+ }
18883
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
18884
+ function isSafeEndpoint(endpoint) {
18885
+ let parsed2;
18886
+ try {
18887
+ parsed2 = new URL(endpoint);
18888
+ } catch {
18889
+ return false;
18890
+ }
18891
+ if (parsed2.protocol === "https:") return true;
18892
+ return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname);
18893
+ }
18894
+ function repairOrRefuseMode(file2) {
18895
+ const link = lstatSync2(file2, { throwIfNoEntry: false });
18896
+ if (link === void 0) return "absent";
18897
+ if (link.isSymbolicLink()) return "untrusted";
18898
+ const stat = statSync(file2, { throwIfNoEntry: false });
18899
+ if (stat === void 0) return "absent";
18900
+ const uid = process.getuid?.();
18901
+ if (uid !== void 0 && stat.uid !== uid) return "untrusted";
18902
+ if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
18903
+ try {
18904
+ chmodSync2(file2, DATA_FILE_MODE);
18905
+ } catch {
18906
+ return "untrusted";
18907
+ }
18908
+ }
18909
+ return "ok";
18910
+ }
18911
+ function readControlPlaneCredentialState(settingsDir2, connection) {
18912
+ const file2 = controlPlaneCredentialPath(settingsDir2);
18913
+ let raw;
18914
+ const gate = repairOrRefuseMode(file2);
18915
+ if (gate === "absent") return { usable: false, reason: "absent" };
18916
+ if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
18917
+ try {
18918
+ raw = readFileSync(file2, "utf8");
18919
+ } catch (err) {
18920
+ const code = err.code;
18921
+ return { usable: false, reason: code === "ENOENT" ? "absent" : "unreadable" };
18922
+ }
18923
+ let parsed2;
18924
+ try {
18925
+ parsed2 = JSON.parse(raw);
18926
+ } catch {
18927
+ return { usable: false, reason: "malformed" };
18928
+ }
18929
+ const result = AttachedCredential.safeParse(parsed2);
18930
+ if (!result.success) return { usable: false, reason: "malformed" };
18931
+ if (!isSafeEndpoint(result.data.endpoint)) {
18932
+ return { usable: false, reason: "unsafe-endpoint" };
18933
+ }
18934
+ if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
18935
+ return {
18936
+ usable: false,
18937
+ reason: "endpoint-mismatch",
18938
+ credentialEndpoint: result.data.endpoint,
18939
+ settingsEndpoint: connection.endpoint
18940
+ };
18941
+ }
18942
+ return { usable: true, credential: result.data };
18943
+ }
18944
+
18945
+ // ../../packages/persistence/src/database.ts
18946
+ import { randomUUID as randomUUID10 } from "crypto";
18947
+ import { join as join3, sep } from "path";
18948
+ import { DatabaseSync } from "node:sqlite";
18949
+
18950
+ // ../../packages/persistence/src/ids.ts
18951
+ import { createHash } from "crypto";
18952
+ function sha256Hex(input) {
18953
+ return createHash("sha256").update(input).digest("hex");
18954
+ }
18955
+ function inventoryId(objectType, identityKey) {
18956
+ return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18957
+ }
18958
+ function sourceProjectId(url2) {
18959
+ return sha256Hex(canonicalIdentity(["source_project", url2]));
18960
+ }
18961
+ function classifiedDataId(cls) {
18962
+ return sha256Hex(canonicalIdentity(["classified_data", cls]));
18963
+ }
18964
+ function inspectionDefinitionId(ruleId, version2) {
18965
+ return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18966
+ }
18967
+ function llmCallId(sessionId, messageId) {
18968
+ return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18969
+ }
18970
+ function toolCallId(sessionId, toolUseId) {
18971
+ return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18972
+ }
18973
+ function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18974
+ return sha256Hex(
18975
+ canonicalIdentity([
18976
+ "inspection_finding",
18977
+ auditEventId,
18978
+ ruleId,
18979
+ String(spanStart),
18980
+ String(spanEnd)
18981
+ ])
18982
+ );
18983
+ }
18984
+ var NO_SESSION = "no_session";
18985
+ var NO_PATH = "no_path";
18986
+ function captureId(sessionId, contentHash, filePath = null) {
18987
+ return sha256Hex(
18988
+ canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18989
+ );
18990
+ }
18729
18991
 
18730
18992
  // ../../packages/persistence/src/internal/snapshot.ts
18993
+ import { randomUUID } from "crypto";
18994
+ import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync3, statSync as statSync2 } from "fs";
18995
+ import { basename, dirname, join as join2 } from "path";
18731
18996
  function backupPath(file2, tag) {
18732
18997
  return `${file2}.${tag}.${String(Date.now())}.${randomUUID().slice(0, 8)}.bak`;
18733
18998
  }
@@ -18737,15 +19002,15 @@ var STAGED_NAME_SUFFIX = `.bak${SNAPSHOT_STAGING_SUFFIX}`;
18737
19002
  var SNAPSHOT_STAGING_COPY = "copy";
18738
19003
  function createSnapshotStaging(backup) {
18739
19004
  const stage = `${backup}${SNAPSHOT_STAGING_SUFFIX}`;
18740
- rmSync2(stage, { recursive: true, force: true });
19005
+ rmSync3(stage, { recursive: true, force: true });
18741
19006
  mkdirOwnerOnlySync(stage);
18742
19007
  tightenDir(stage);
18743
- return { stage, copy: join(stage, SNAPSHOT_STAGING_COPY) };
19008
+ return { stage, copy: join2(stage, SNAPSHOT_STAGING_COPY) };
18744
19009
  }
18745
19010
  function idleMs(entry) {
18746
- for (const candidate of [join(entry, SNAPSHOT_STAGING_COPY), entry]) {
19011
+ for (const candidate of [join2(entry, SNAPSHOT_STAGING_COPY), entry]) {
18747
19012
  try {
18748
- return Date.now() - statSync(candidate).mtimeMs;
19013
+ return Date.now() - statSync2(candidate).mtimeMs;
18749
19014
  } catch {
18750
19015
  }
18751
19016
  }
@@ -18762,11 +19027,11 @@ function reapStalePartials(file2) {
18762
19027
  }
18763
19028
  for (const name of entries) {
18764
19029
  if (!name.startsWith(prefix) || !name.endsWith(STAGED_NAME_SUFFIX)) continue;
18765
- const staging = join(dir, name);
19030
+ const staging = join2(dir, name);
18766
19031
  try {
18767
19032
  const idle = idleMs(staging);
18768
19033
  if (idle !== null && idle > STALE_PARTIAL_MS) {
18769
- rmSync2(staging, { recursive: true, force: true });
19034
+ rmSync3(staging, { recursive: true, force: true });
18770
19035
  }
18771
19036
  } catch {
18772
19037
  }
@@ -18780,13 +19045,13 @@ function snapshotStore(db, backup) {
18780
19045
  renameSync2(copy, backup);
18781
19046
  } catch (error51) {
18782
19047
  try {
18783
- rmSync2(stage, { recursive: true, force: true });
19048
+ rmSync3(stage, { recursive: true, force: true });
18784
19049
  } catch {
18785
19050
  }
18786
19051
  throw error51;
18787
19052
  }
18788
19053
  try {
18789
- rmSync2(stage, { recursive: true, force: true });
19054
+ rmSync3(stage, { recursive: true, force: true });
18790
19055
  } catch {
18791
19056
  }
18792
19057
  }
@@ -18801,7 +19066,7 @@ function moveStoreAside(file2, backup) {
18801
19066
  renameSync2(sidecar, moved);
18802
19067
  undo.push([moved, sidecar]);
18803
19068
  } catch {
18804
- rmSync2(sidecar, { force: true });
19069
+ rmSync3(sidecar, { force: true });
18805
19070
  }
18806
19071
  }
18807
19072
  } catch (error51) {
@@ -18817,14 +19082,14 @@ function moveStoreAside(file2, backup) {
18817
19082
  }
18818
19083
  function discardStore(file2, backup) {
18819
19084
  try {
18820
- rmSync2(file2, { force: true });
19085
+ rmSync3(file2, { force: true });
18821
19086
  for (const sidecar of dbSidecars(file2)) {
18822
- rmSync2(sidecar, { force: true });
19087
+ rmSync3(sidecar, { force: true });
18823
19088
  }
18824
19089
  } catch (error51) {
18825
19090
  if (existsSync(file2)) {
18826
19091
  try {
18827
- rmSync2(backup, { force: true });
19092
+ rmSync3(backup, { force: true });
18828
19093
  } catch {
18829
19094
  }
18830
19095
  }
@@ -19056,10 +19321,31 @@ function applyMigrations(db, file2) {
19056
19321
  if (drained) applyLegacyDropMigration(db, file2);
19057
19322
  }
19058
19323
  }
19324
+ function readLegacyTables(db) {
19325
+ let holdsRows = false;
19326
+ const marks = [];
19327
+ for (const table of ["events", "findings"]) {
19328
+ try {
19329
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
19330
+ if (row === void 0) {
19331
+ holdsRows = true;
19332
+ marks.push(`${table}:unreadable`);
19333
+ continue;
19334
+ }
19335
+ if (row.n > 0) holdsRows = true;
19336
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
19337
+ } catch {
19338
+ holdsRows = true;
19339
+ marks.push(`${table}:unreadable`);
19340
+ }
19341
+ }
19342
+ return { holdsRows, mark: marks.join("|") };
19343
+ }
19059
19344
  function applyLegacyDropMigration(db, file2) {
19060
19345
  const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
19061
19346
  if (!migration) return;
19062
- if (file2) {
19347
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
19348
+ if (file2 !== void 0 && before?.holdsRows === true) {
19063
19349
  try {
19064
19350
  backupBeforeLegacyDrop(db, file2);
19065
19351
  } catch (error51) {
@@ -19073,6 +19359,12 @@ function applyLegacyDropMigration(db, file2) {
19073
19359
  () => {
19074
19360
  const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
19075
19361
  if (alreadyDropped) return;
19362
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
19363
+ akaWarn(
19364
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
19365
+ );
19366
+ return;
19367
+ }
19076
19368
  for (const statement of splitStatements(migration.sql)) {
19077
19369
  db.exec(statement);
19078
19370
  }
@@ -19427,8 +19719,8 @@ function safeJson(s, fallback) {
19427
19719
  function parseJsonObject(s) {
19428
19720
  if (s == null) return void 0;
19429
19721
  try {
19430
- const parsed = JSON.parse(s);
19431
- if (typeof parsed === "object" && parsed !== null) return parsed;
19722
+ const parsed2 = JSON.parse(s);
19723
+ if (typeof parsed2 === "object" && parsed2 !== null) return parsed2;
19432
19724
  } catch {
19433
19725
  }
19434
19726
  return void 0;
@@ -19439,16 +19731,16 @@ function encodeKeysetCursor(payload) {
19439
19731
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
19440
19732
  }
19441
19733
  function decodeKeysetCursor(cursor) {
19442
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19443
- if (parsed !== void 0 && "startedAtMs" in parsed && "id" in parsed && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19734
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19735
+ if (parsed2 !== void 0 && "startedAtMs" in parsed2 && "id" in parsed2 && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19444
19736
  // resumes from is epoch millis, and a payload carrying ±Infinity or a
19445
19737
  // fraction binds cleanly rather than failing — returning an EMPTY page with
19446
19738
  // a null cursor, which a caller reads as "end of list". That is the one
19447
19739
  // outcome a cursor that does not decode must never produce, since the
19448
19740
  // documented behaviour above is to restart from the top. (`1e999` is valid
19449
19741
  // JSON and parses to Infinity; a bare `NaN` is not, so it cannot arrive.)
19450
- Number.isInteger(parsed.startedAtMs) && typeof parsed.id === "string") {
19451
- return parsed;
19742
+ Number.isInteger(parsed2.startedAtMs) && typeof parsed2.id === "string") {
19743
+ return parsed2;
19452
19744
  }
19453
19745
  return null;
19454
19746
  }
@@ -19513,18 +19805,18 @@ var DB_EVENT_TYPE_TO_KIND = {
19513
19805
  };
19514
19806
  function safeParseStringArray(raw) {
19515
19807
  if (!raw) return [];
19516
- const parsed = safeJson(raw, null);
19517
- return Array.isArray(parsed) ? parsed : [];
19808
+ const parsed2 = safeJson(raw, null);
19809
+ return Array.isArray(parsed2) ? parsed2 : [];
19518
19810
  }
19519
19811
  var DEFAULT_HARNESS = HARNESS.ClaudeCode;
19520
19812
  function toHarness(raw) {
19521
- const parsed = Harness.safeParse(raw);
19522
- return parsed.success ? parsed.data : DEFAULT_HARNESS;
19813
+ const parsed2 = Harness.safeParse(raw);
19814
+ return parsed2.success ? parsed2.data : DEFAULT_HARNESS;
19523
19815
  }
19524
19816
  function resolveLifecycle(row, lastActivityMs, nowMs) {
19525
19817
  if (row.status) {
19526
- const parsed = SessionStatus.safeParse(row.status);
19527
- if (parsed.success) return { status: parsed.data, endedAtMs: row.ended_at };
19818
+ const parsed2 = SessionStatus.safeParse(row.status);
19819
+ if (parsed2.success) return { status: parsed2.data, endedAtMs: row.ended_at };
19528
19820
  }
19529
19821
  if (row.ended_at !== null) return { status: "completed", endedAtMs: row.ended_at };
19530
19822
  if (lastActivityMs >= nowMs - LIVE_ACTIVITY_WINDOW_MS) {
@@ -20483,9 +20775,9 @@ var SqliteDetectionsRepository = class {
20483
20775
  const ruleIds = /* @__PURE__ */ new Set();
20484
20776
  for (const r of rows) {
20485
20777
  if (intToBool(r.enabled)) active += 1;
20486
- const parsed = parseRules(r.rulesJson);
20487
- rules += parsed.length;
20488
- for (const rule of parsed) {
20778
+ const parsed2 = parseRules(r.rulesJson);
20779
+ rules += parsed2.length;
20780
+ for (const rule of parsed2) {
20489
20781
  if (typeof rule.id === "string") ruleIds.add(rule.id);
20490
20782
  }
20491
20783
  }
@@ -21019,12 +21311,12 @@ function encodeGroupCursor(group) {
21019
21311
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
21020
21312
  }
21021
21313
  function decodeGroupCursor(cursor) {
21022
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
21023
- if (parsed !== void 0 && typeof parsed.sev === "string" && typeof parsed.t === "string" && typeof parsed.id === "string") {
21314
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
21315
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.id === "string") {
21024
21316
  return {
21025
- severity: parsed.sev,
21026
- latestDetectedAt: parsed.t,
21027
- id: parsed.id
21317
+ severity: parsed2.sev,
21318
+ latestDetectedAt: parsed2.t,
21319
+ id: parsed2.id
21028
21320
  };
21029
21321
  }
21030
21322
  return null;
@@ -22158,16 +22450,16 @@ var SqliteInstalledPacksRepository = class {
22158
22450
  continue;
22159
22451
  }
22160
22452
  for (const entry of raw) {
22161
- const parsed = Rule.safeParse(entry);
22162
- if (parsed.success) {
22163
- out.rules.push(parsed.data);
22164
- out.ruleActions.set(parsed.data.id, action);
22165
- out.ruleVersions.set(parsed.data.id, row.version);
22166
- if (reversible) out.reversibleRules.add(parsed.data.id);
22167
- else out.reversibleRules.delete(parsed.data.id);
22453
+ const parsed2 = Rule.safeParse(entry);
22454
+ if (parsed2.success) {
22455
+ out.rules.push(parsed2.data);
22456
+ out.ruleActions.set(parsed2.data.id, action);
22457
+ out.ruleVersions.set(parsed2.data.id, row.version);
22458
+ if (reversible) out.reversibleRules.add(parsed2.data.id);
22459
+ else out.reversibleRules.delete(parsed2.data.id);
22168
22460
  } else {
22169
22461
  out.invalidRules += 1;
22170
- reject(pack, printableRuleId(entry), firstIssueReason(parsed.error));
22462
+ reject(pack, printableRuleId(entry), firstIssueReason(parsed2.error));
22171
22463
  }
22172
22464
  }
22173
22465
  }
@@ -23557,15 +23849,15 @@ function encodeReuseCursor(payload) {
23557
23849
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
23558
23850
  }
23559
23851
  function decodeReuseCursor(cursor) {
23560
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23561
- if (parsed !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23852
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23853
+ if (parsed2 !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23562
23854
  // ±Infinity or a fraction binds cleanly and returns an EMPTY page with a
23563
23855
  // null cursor, which the caller reads as "end of list" — the one outcome a
23564
23856
  // malformed cursor must never produce, since restarting from the top is the
23565
23857
  // documented behaviour and the only recoverable one. (`1e999` is valid JSON
23566
23858
  // and parses to Infinity; a bare `NaN` is not, so it cannot arrive here.)
23567
- Number.isInteger(parsed.occurrences) && typeof parsed.pointerId === "string") {
23568
- return { occurrences: parsed.occurrences, pointerId: parsed.pointerId };
23859
+ Number.isInteger(parsed2.occurrences) && typeof parsed2.pointerId === "string") {
23860
+ return { occurrences: parsed2.occurrences, pointerId: parsed2.pointerId };
23569
23861
  }
23570
23862
  return null;
23571
23863
  }
@@ -25294,7 +25586,7 @@ function openAndInitialize(file2) {
25294
25586
  }
25295
25587
  function openLocalDatabase(dir) {
25296
25588
  ensureDataDirSync(dir);
25297
- const file2 = join2(dir, DB_FILENAME);
25589
+ const file2 = join3(dir, DB_FILENAME);
25298
25590
  reapStalePartials(file2);
25299
25591
  const {
25300
25592
  db,
@@ -25530,9 +25822,9 @@ import {
25530
25822
  closeSync,
25531
25823
  existsSync as existsSync2,
25532
25824
  openSync,
25533
- readFileSync,
25534
- rmSync as rmSync3,
25535
- statSync as statSync2,
25825
+ readFileSync as readFileSync2,
25826
+ rmSync as rmSync4,
25827
+ statSync as statSync3,
25536
25828
  writeFileSync as writeFileSync2
25537
25829
  } from "fs";
25538
25830
  import { hostname as hostname3 } from "os";
@@ -25543,20 +25835,20 @@ import { createHash as createHash3 } from "crypto";
25543
25835
 
25544
25836
  // ../../packages/persistence/src/fingerprint.ts
25545
25837
  import { createHmac, randomBytes } from "crypto";
25546
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
25547
- import { join as join3 } from "path";
25838
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
25839
+ import { join as join4 } from "path";
25548
25840
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
25549
25841
  var EXCEPTION_KEY_FILENAME = "exception.key";
25550
25842
  var KEY_MATERIAL_BYTES = 32;
25551
25843
  function keyFilePath(dataDir2) {
25552
- return join3(dataDir2, EXCEPTION_KEY_FILENAME);
25844
+ return join4(dataDir2, EXCEPTION_KEY_FILENAME);
25553
25845
  }
25554
25846
  function parseKeyFile(raw) {
25555
- const parsed = JSON.parse(raw);
25556
- if (typeof parsed !== "object" || parsed === null) {
25847
+ const parsed2 = JSON.parse(raw);
25848
+ if (typeof parsed2 !== "object" || parsed2 === null) {
25557
25849
  throw new Error("exception key file is corrupt: not a JSON object");
25558
25850
  }
25559
- const { version: version2, material } = parsed;
25851
+ const { version: version2, material } = parsed2;
25560
25852
  if (typeof version2 !== "number" || !Number.isInteger(version2) || version2 < 1) {
25561
25853
  throw new Error("exception key file is corrupt: bad version");
25562
25854
  }
@@ -25572,7 +25864,7 @@ function parseKeyFile(raw) {
25572
25864
  function readFingerprintKey(dataDir2) {
25573
25865
  let raw;
25574
25866
  try {
25575
- raw = readFileSync2(keyFilePath(dataDir2), "utf8");
25867
+ raw = readFileSync3(keyFilePath(dataDir2), "utf8");
25576
25868
  } catch (err) {
25577
25869
  if (err.code === "ENOENT") return null;
25578
25870
  throw err instanceof Error ? err : new Error(String(err));
@@ -25584,18 +25876,25 @@ function readFingerprintKey(dataDir2) {
25584
25876
  import { renameSync as renameSync3 } from "fs";
25585
25877
  import { mkdir } from "fs/promises";
25586
25878
  import { homedir } from "os";
25587
- import { join as join4 } from "path";
25879
+ import { join as join5 } from "path";
25588
25880
  function defaultDataDir() {
25589
- return join4(homedir(), ".aka");
25881
+ return join5(homedir(), ".aka");
25590
25882
  }
25591
25883
  function settingsDir(base = defaultDataDir()) {
25592
- return join4(base, "settings");
25884
+ return join5(base, "settings");
25593
25885
  }
25594
25886
  function dataDir(base = defaultDataDir()) {
25595
- return join4(base, "data");
25887
+ return join5(base, "data");
25596
25888
  }
25597
25889
  function dbPath(base = defaultDataDir()) {
25598
- return join4(dataDir(base), "aka.db");
25890
+ return join5(dataDir(base), "aka.db");
25891
+ }
25892
+ function keysDir(base = defaultDataDir()) {
25893
+ return join5(base, "keys");
25894
+ }
25895
+ async function ensureDataDir(dir = defaultDataDir()) {
25896
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
25897
+ tightenDir(dir);
25599
25898
  }
25600
25899
  function ensureLayoutDirSync(dir = defaultDataDir()) {
25601
25900
  ensureDataDirSync(dir);
@@ -25608,8 +25907,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25608
25907
  for (const { name, dest } of moves) {
25609
25908
  try {
25610
25909
  ensureDataDirSync(dest);
25611
- const moved = join4(dest, name);
25612
- renameSync3(join4(base, name), moved);
25910
+ const moved = join5(dest, name);
25911
+ renameSync3(join5(base, name), moved);
25613
25912
  tightenFile(moved);
25614
25913
  } catch {
25615
25914
  }
@@ -25617,7 +25916,7 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25617
25916
  }
25618
25917
 
25619
25918
  // ../../packages/persistence/src/managed-settings.ts
25620
- import { readFileSync as readFileSync3 } from "fs";
25919
+ import { readFileSync as readFileSync4 } from "fs";
25621
25920
  import { posix, win32 } from "path";
25622
25921
  function managedSettingsPaths(platform2 = process.platform) {
25623
25922
  if (platform2 === "darwin") {
@@ -25635,14 +25934,14 @@ function readManagedSettings(paths = managedSettingsPaths()) {
25635
25934
  for (const path of paths) {
25636
25935
  let text;
25637
25936
  try {
25638
- text = readFileSync3(path, "utf8");
25937
+ text = readFileSync4(path, "utf8");
25639
25938
  } catch {
25640
25939
  continue;
25641
25940
  }
25642
25941
  const record2 = parseJsonObject(text);
25643
25942
  if (!record2) continue;
25644
- const parsed = ManagedSettings.safeParse(record2);
25645
- if (parsed.success) return parsed.data;
25943
+ const parsed2 = ManagedSettings.safeParse(record2);
25944
+ if (parsed2.success) return parsed2.data;
25646
25945
  }
25647
25946
  return null;
25648
25947
  }
@@ -25682,14 +25981,14 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
25682
25981
  }
25683
25982
 
25684
25983
  // ../../packages/persistence/src/settings.ts
25685
- import { readFileSync as readFileSync4 } from "fs";
25686
- import { join as join5 } from "path";
25984
+ import { readFileSync as readFileSync5 } from "fs";
25985
+ import { join as join6 } from "path";
25687
25986
  var SETTINGS_FILENAME = "settings.json";
25688
25987
  function readWorkspaceSettings(base = defaultDataDir()) {
25689
25988
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
25690
25989
  }
25691
25990
  function readUserSettings(base) {
25692
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
25991
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
25693
25992
  if (!record2) return defaultWorkspaceSettings();
25694
25993
  try {
25695
25994
  return WorkspaceSettings.parse(record2);
@@ -25700,13 +25999,64 @@ function readUserSettings(base) {
25700
25999
  function readJson(file2) {
25701
26000
  let text;
25702
26001
  try {
25703
- text = readFileSync4(file2, "utf8");
26002
+ text = readFileSync5(file2, "utf8");
25704
26003
  } catch {
25705
26004
  return null;
25706
26005
  }
25707
26006
  return parseJsonObject(text) ?? null;
25708
26007
  }
25709
26008
 
26009
+ // ../../packages/persistence/src/store-symlinks.ts
26010
+ import { existsSync as existsSync4, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
26011
+ import { dirname as dirname2, join as join7, resolve } from "path";
26012
+ var STORE_DB = "the store database (including the prompt corpus)";
26013
+ var STORE_SETTINGS = "your settings file";
26014
+ function storeContents(home) {
26015
+ return /* @__PURE__ */ new Map([
26016
+ [home, "the store (including the prompt corpus in aka.db)"],
26017
+ [settingsDir(home), STORE_SETTINGS],
26018
+ [dataDir(home), STORE_DB],
26019
+ [keysDir(home), "the vault key"],
26020
+ [join7(settingsDir(home), "settings.json"), STORE_SETTINGS],
26021
+ [dbPath(home), STORE_DB]
26022
+ ]);
26023
+ }
26024
+ function symlinkedStorePaths(home, platform2 = process.platform) {
26025
+ return [...storeContents(home)].flatMap(([path, holds]) => {
26026
+ try {
26027
+ if (!lstatSync3(path).isSymbolicLink()) return [];
26028
+ return [
26029
+ {
26030
+ path,
26031
+ target: linkTarget(path),
26032
+ holds,
26033
+ // existsSync follows the link, so a target that is gone reads as
26034
+ // absent here while lstat above still sees the link itself.
26035
+ missing: !existsSync4(path),
26036
+ mode: targetMode(path, platform2)
26037
+ }
26038
+ ];
26039
+ } catch {
26040
+ return [];
26041
+ }
26042
+ });
26043
+ }
26044
+ function linkTarget(path) {
26045
+ try {
26046
+ return realpathSync(path);
26047
+ } catch {
26048
+ return resolve(dirname2(path), readlinkSync(path));
26049
+ }
26050
+ }
26051
+ function targetMode(path, platform2) {
26052
+ if (platform2 === "win32") return void 0;
26053
+ try {
26054
+ return statSync4(path).mode & 511;
26055
+ } catch {
26056
+ return void 0;
26057
+ }
26058
+ }
26059
+
25710
26060
  // ../../packages/persistence/src/vault/crypto.ts
25711
26061
  import {
25712
26062
  createCipheriv,
@@ -25719,26 +26069,73 @@ import {
25719
26069
  // ../../packages/persistence/src/vault/key-provider.ts
25720
26070
  import { execFileSync } from "child_process";
25721
26071
  import { randomBytes as randomBytes2 } from "crypto";
25722
- import { chmodSync as chmodSync2, readFileSync as readFileSync5, renameSync as renameSync4, rmSync as rmSync4, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
25723
- import { join as join6 } from "path";
26072
+ import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync5, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
26073
+ import { join as join8 } from "path";
25724
26074
 
25725
26075
  // ../../packages/persistence/src/vault/vault.ts
25726
26076
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
25727
26077
 
25728
26078
  // ../../packages/persistence/src/warn-era-cap.ts
25729
- import { existsSync as existsSync4, writeFileSync as writeFileSync4 } from "fs";
25730
- import { join as join7 } from "path";
26079
+ import { existsSync as existsSync5, writeFileSync as writeFileSync4 } from "fs";
26080
+ import { join as join9 } from "path";
25731
26081
  var MARKER = "warn-era-capped";
25732
26082
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
25733
26083
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
25734
- const marker = join7(dataDir2, MARKER);
25735
- if (existsSync4(marker)) return { capped: 0, skipped: "already-run" };
26084
+ const marker = join9(dataDir2, MARKER);
26085
+ if (existsSync5(marker)) return { capped: 0, skipped: "already-run" };
25736
26086
  const capped = db.policies.capCategoryActions();
25737
26087
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
25738
26088
  `, { mode: DATA_FILE_MODE });
25739
26089
  return { capped };
25740
26090
  }
25741
26091
 
26092
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
26093
+ var FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
26094
+ function forwardDropsPath(dataDir2) {
26095
+ return join10(dataDir2, FORWARD_DROPS_FILENAME);
26096
+ }
26097
+ function recordForwardDrops(dataDir2, count, nowMs) {
26098
+ if (count <= 0) return;
26099
+ try {
26100
+ ensureDataDirSync(dataDir2);
26101
+ const previous = readForwardDrops(dataDir2);
26102
+ const next = {
26103
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
26104
+ lastDropAtMs: nowMs
26105
+ };
26106
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
26107
+ `);
26108
+ } catch {
26109
+ }
26110
+ }
26111
+ function readForwardDrops(dataDir2) {
26112
+ try {
26113
+ const parsed2 = JSON.parse(readFileSync7(forwardDropsPath(dataDir2), "utf8"));
26114
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
26115
+ const record2 = parsed2;
26116
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
26117
+ return null;
26118
+ }
26119
+ if (record2.droppedForwards <= 0) return null;
26120
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
26121
+ return null;
26122
+ }
26123
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
26124
+ } catch {
26125
+ return null;
26126
+ }
26127
+ }
26128
+
26129
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
26130
+ import { randomUUID as randomUUID15 } from "crypto";
26131
+ import { readFileSync as readFileSync12 } from "fs";
26132
+ import { readFile, rename, writeFile } from "fs/promises";
26133
+ import { join as join18 } from "path";
26134
+
26135
+ // ../../packages/plugin-sdk/src/config.ts
26136
+ import { existsSync as existsSync6 } from "fs";
26137
+ import { join as join11 } from "path";
26138
+
25742
26139
  // ../../packages/plugin-sdk/src/provider-env.ts
25743
26140
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
25744
26141
  var booleanish = external_exports.string().optional().transform((v) => {
@@ -25773,8 +26170,8 @@ function hostOf(url2) {
25773
26170
  }
25774
26171
  }
25775
26172
  function resolveProvider() {
25776
- const parsed = ProviderEnvSchema.safeParse(process.env);
25777
- const env = parsed.success ? parsed.data : ProviderEnvSchema.parse({});
26173
+ const parsed2 = ProviderEnvSchema.safeParse(process.env);
26174
+ const env = parsed2.success ? parsed2.data : ProviderEnvSchema.parse({});
25778
26175
  if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
25779
26176
  if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
25780
26177
  const baseUrl = env.ANTHROPIC_BASE_URL;
@@ -25791,8 +26188,8 @@ function resolveProvider() {
25791
26188
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
25792
26189
  try {
25793
26190
  ensureLayoutDirSync(base);
25794
- const settingsFile = join8(settingsDir(base), "settings.json");
25795
- if (existsSync5(settingsFile)) tightenFile(settingsFile);
26191
+ const settingsFile = join11(settingsDir(base), "settings.json");
26192
+ if (existsSync6(settingsFile)) tightenFile(settingsFile);
25796
26193
  } catch {
25797
26194
  }
25798
26195
  migrateLegacyLayout(base);
@@ -25815,9 +26212,9 @@ function resolveProviderSafe(resolveProviderFn) {
25815
26212
  }
25816
26213
 
25817
26214
  // ../../packages/plugin-sdk/src/config-inventory.ts
25818
- import { readdirSync as readdirSync2, readFileSync as readFileSync7, realpathSync, statSync as statSync5 } from "fs";
26215
+ import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
25819
26216
  import { homedir as homedir2 } from "os";
25820
- import { basename as basename4, join as join10 } from "path";
26217
+ import { basename as basename4, join as join13 } from "path";
25821
26218
 
25822
26219
  // ../../packages/detections/src/egress/registry.ts
25823
26220
  var EXTRACTOR_VERSION = "1";
@@ -27589,10 +27986,10 @@ var localhost_ref_default = {
27589
27986
  severity: "low",
27590
27987
  matcher: {
27591
27988
  type: "regex",
27592
- pattern: "\\b(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|::1)\\b",
27989
+ 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_])",
27593
27990
  flags: "g"
27594
27991
  },
27595
- examples: ["localhost", "127.0.0.1"]
27992
+ examples: ["localhost", "127.0.0.1", "0.0.0.0", "::1"]
27596
27993
  };
27597
27994
 
27598
27995
  // ../../rules/core-code-context/stack-trace.json
@@ -28946,8 +29343,8 @@ function maskText(text) {
28946
29343
  }
28947
29344
 
28948
29345
  // ../../packages/plugin-sdk/src/repo.ts
28949
- import { existsSync as existsSync6, readFileSync as readFileSync6, statSync as statSync4 } from "fs";
28950
- import { basename as basename3, dirname as dirname2, isAbsolute, join as join9, sep as sep2 } from "path";
29346
+ import { existsSync as existsSync7, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
29347
+ import { basename as basename3, dirname as dirname3, isAbsolute, join as join12, sep as sep2 } from "path";
28951
29348
  function resolveRepoIdentity(cwd) {
28952
29349
  try {
28953
29350
  const root = findGitRoot(cwd);
@@ -28997,15 +29394,15 @@ function resolveGitBranch(cwd) {
28997
29394
  try {
28998
29395
  const root = findGitRoot(cwd);
28999
29396
  if (!root) return void 0;
29000
- const dotGit = join9(root, ".git");
29397
+ const dotGit = join12(root, ".git");
29001
29398
  let gitdir;
29002
29399
  try {
29003
- gitdir = statSync4(dotGit).isDirectory() ? dotGit : resolveWorktreeGitdir(root, dotGit);
29400
+ gitdir = statSync6(dotGit).isDirectory() ? dotGit : resolveWorktreeGitdir(root, dotGit);
29004
29401
  } catch {
29005
29402
  return void 0;
29006
29403
  }
29007
29404
  if (gitdir === void 0) return void 0;
29008
- const head = safeRead(join9(gitdir, "HEAD"));
29405
+ const head = safeRead(join12(gitdir, "HEAD"));
29009
29406
  if (!head) return void 0;
29010
29407
  return /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head)?.[1];
29011
29408
  } catch {
@@ -29015,41 +29412,41 @@ function resolveGitBranch(cwd) {
29015
29412
  function resolveWorktreeGitdir(root, dotGitFile) {
29016
29413
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGitFile) ?? "")?.[1];
29017
29414
  if (!target) return void 0;
29018
- return isAbsolute(target) ? target : join9(root, target);
29415
+ return isAbsolute(target) ? target : join12(root, target);
29019
29416
  }
29020
29417
  function findGitRoot(start) {
29021
29418
  let dir = start;
29022
29419
  for (; ; ) {
29023
- if (existsSync6(join9(dir, ".git"))) return dir;
29024
- const parent = dirname2(dir);
29420
+ if (existsSync7(join12(dir, ".git"))) return dir;
29421
+ const parent = dirname3(dir);
29025
29422
  if (parent === dir) return void 0;
29026
29423
  dir = parent;
29027
29424
  }
29028
29425
  }
29029
29426
  function resolveGitContext(root) {
29030
- const dotGit = join9(root, ".git");
29427
+ const dotGit = join12(root, ".git");
29031
29428
  try {
29032
- if (statSync4(dotGit).isDirectory()) {
29033
- return { configPath: join9(dotGit, "config"), headRoot: root };
29429
+ if (statSync6(dotGit).isDirectory()) {
29430
+ return { configPath: join12(dotGit, "config"), headRoot: root };
29034
29431
  }
29035
29432
  } catch {
29036
29433
  return void 0;
29037
29434
  }
29038
29435
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
29039
29436
  if (!target) return void 0;
29040
- const gitdir = isAbsolute(target) ? target : join9(root, target);
29041
- if (existsSync6(join9(gitdir, "config"))) {
29042
- return { configPath: join9(gitdir, "config"), headRoot: root };
29437
+ const gitdir = isAbsolute(target) ? target : join12(root, target);
29438
+ if (existsSync7(join12(gitdir, "config"))) {
29439
+ return { configPath: join12(gitdir, "config"), headRoot: root };
29043
29440
  }
29044
- const commonRaw = safeRead(join9(gitdir, "commondir"))?.trim();
29441
+ const commonRaw = safeRead(join12(gitdir, "commondir"))?.trim();
29045
29442
  if (!commonRaw) return void 0;
29046
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join9(gitdir, commonRaw);
29047
- const headRoot = basename3(commonGitDir) === ".git" ? dirname2(commonGitDir) : root;
29048
- return { configPath: join9(commonGitDir, "config"), headRoot };
29443
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join12(gitdir, commonRaw);
29444
+ const headRoot = basename3(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
29445
+ return { configPath: join12(commonGitDir, "config"), headRoot };
29049
29446
  }
29050
29447
  function safeRead(path) {
29051
29448
  try {
29052
- return readFileSync6(path, "utf8");
29449
+ return readFileSync8(path, "utf8");
29053
29450
  } catch {
29054
29451
  return void 0;
29055
29452
  }
@@ -29111,31 +29508,31 @@ function resolveConfigInventory(input) {
29111
29508
  };
29112
29509
  try {
29113
29510
  const home = input.homeDir ?? homedir2();
29114
- const claudeDir = join10(home, ".claude");
29511
+ const claudeDir = join13(home, ".claude");
29115
29512
  const repo = resolveRepoIdentity(input.cwd);
29116
29513
  const repoIdentity = repo?.url ?? input.cwd;
29117
29514
  const projectSource = `project:${repoIdentity}`;
29118
- collectSettingsHooks(scan2, join10(claudeDir, "settings.json"), "user");
29119
- collectSettingsHooks(scan2, join10(input.cwd, ".claude", "settings.json"), "project");
29120
- collectSettingsHooks(scan2, join10(input.cwd, ".claude", "settings.local.json"), "local");
29515
+ collectSettingsHooks(scan2, join13(claudeDir, "settings.json"), "user");
29516
+ collectSettingsHooks(scan2, join13(input.cwd, ".claude", "settings.json"), "project");
29517
+ collectSettingsHooks(scan2, join13(input.cwd, ".claude", "settings.local.json"), "local");
29121
29518
  const projectOrigin = { scope: "project", project: repoIdentity };
29122
- collectMcpFile(scan2, join10(input.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
29123
- collectUserClaudeJson(scan2, join10(home, ".claude.json"), input.cwd, repoIdentity);
29124
- collectMcpFile(scan2, join10(claudeDir, "settings.json"), { scope: "user" });
29125
- collectMcpFile(scan2, join10(input.cwd, ".claude", "settings.json"), projectOrigin);
29126
- collectMcpFile(scan2, join10(input.cwd, ".claude", "settings.local.json"), {
29519
+ collectMcpFile(scan2, join13(input.cwd, ".mcp.json"), projectOrigin, { recordErrors: true });
29520
+ collectUserClaudeJson(scan2, join13(home, ".claude.json"), input.cwd, repoIdentity);
29521
+ collectMcpFile(scan2, join13(claudeDir, "settings.json"), { scope: "user" });
29522
+ collectMcpFile(scan2, join13(input.cwd, ".claude", "settings.json"), projectOrigin);
29523
+ collectMcpFile(scan2, join13(input.cwd, ".claude", "settings.local.json"), {
29127
29524
  scope: "local",
29128
29525
  project: repoIdentity
29129
29526
  });
29130
29527
  collectConfigFiles(scan2, claudeDir, input.cwd);
29131
- collectSkillsDir(scan2, join10(claudeDir, "skills"), { source: "local", scope: "user" });
29132
- collectSkillsDir(scan2, join10(input.cwd, ".claude", "skills"), {
29528
+ collectSkillsDir(scan2, join13(claudeDir, "skills"), { source: "local", scope: "user" });
29529
+ collectSkillsDir(scan2, join13(input.cwd, ".claude", "skills"), {
29133
29530
  source: projectSource,
29134
29531
  scope: "project"
29135
29532
  });
29136
29533
  collectInstalledPlugins(scan2, claudeDir);
29137
29534
  collectMarketplaceSkills(scan2, claudeDir);
29138
- collectSkillsDir(scan2, join10(input.cwd, "skills"), { source: projectSource, scope: "project" });
29535
+ collectSkillsDir(scan2, join13(input.cwd, "skills"), { source: projectSource, scope: "project" });
29139
29536
  scan2.skills = dedupeSkills(scan2.skills);
29140
29537
  scan2.mcpServers = dedupeMcpServers(scan2.mcpServers);
29141
29538
  } catch (err) {
@@ -29170,9 +29567,9 @@ function collectSettingsHooks(scan2, path, scope) {
29170
29567
  const raw = readOptional(path);
29171
29568
  if (raw === void 0) return;
29172
29569
  try {
29173
- const parsed = JSON.parse(raw);
29174
- if (typeof parsed !== "object" || parsed === null) return;
29175
- collectHooksObject(scan2, parsed.hooks, path, scope);
29570
+ const parsed2 = JSON.parse(raw);
29571
+ if (typeof parsed2 !== "object" || parsed2 === null) return;
29572
+ collectHooksObject(scan2, parsed2.hooks, path, scope);
29176
29573
  } catch (err) {
29177
29574
  scan2.errors.push({ source: path, reason: parseErrorReason(err) });
29178
29575
  }
@@ -29218,9 +29615,9 @@ function collectMcpFile(scan2, path, origin, opts) {
29218
29615
  const raw = readOptional(path);
29219
29616
  if (raw === void 0) return;
29220
29617
  try {
29221
- const parsed = JSON.parse(raw);
29222
- if (typeof parsed !== "object" || parsed === null) return;
29223
- collectMcpObject(scan2, parsed.mcpServers, path, origin);
29618
+ const parsed2 = JSON.parse(raw);
29619
+ if (typeof parsed2 !== "object" || parsed2 === null) return;
29620
+ collectMcpObject(scan2, parsed2.mcpServers, path, origin);
29224
29621
  } catch (err) {
29225
29622
  if (opts?.recordErrors ?? false) {
29226
29623
  scan2.errors.push({ source: path, reason: parseErrorReason(err) });
@@ -29231,9 +29628,9 @@ function collectUserClaudeJson(scan2, path, cwd, repoIdentity) {
29231
29628
  const raw = readOptional(path);
29232
29629
  if (raw === void 0) return;
29233
29630
  try {
29234
- const parsed = JSON.parse(raw);
29235
- if (typeof parsed !== "object" || parsed === null) return;
29236
- const rec = parsed;
29631
+ const parsed2 = JSON.parse(raw);
29632
+ if (typeof parsed2 !== "object" || parsed2 === null) return;
29633
+ const rec = parsed2;
29237
29634
  collectMcpObject(scan2, rec.mcpServers, path, { scope: "user" });
29238
29635
  const projects = rec.projects;
29239
29636
  if (typeof projects === "object" && projects !== null) {
@@ -29254,7 +29651,7 @@ function projectEntryFor(projects, cwd) {
29254
29651
  const trimmed = cwd.replace(/\/+$/, "");
29255
29652
  if (trimmed.length > 0) candidates.add(trimmed);
29256
29653
  try {
29257
- candidates.add(realpathSync(cwd));
29654
+ candidates.add(realpathSync2(cwd));
29258
29655
  } catch {
29259
29656
  }
29260
29657
  for (const key of candidates) {
@@ -29264,15 +29661,15 @@ function projectEntryFor(projects, cwd) {
29264
29661
  return void 0;
29265
29662
  }
29266
29663
  function collectPluginManifestMcp(scan2, installPath, origin) {
29267
- const manifestPath = join10(installPath, ".claude-plugin", "plugin.json");
29664
+ const manifestPath = join13(installPath, ".claude-plugin", "plugin.json");
29268
29665
  const raw = readOptional(manifestPath);
29269
29666
  if (raw === void 0) return;
29270
29667
  try {
29271
- const parsed = JSON.parse(raw);
29272
- if (typeof parsed !== "object" || parsed === null) return;
29273
- const declared = parsed.mcpServers;
29668
+ const parsed2 = JSON.parse(raw);
29669
+ if (typeof parsed2 !== "object" || parsed2 === null) return;
29670
+ const declared = parsed2.mcpServers;
29274
29671
  if (typeof declared === "string" && declared.length > 0) {
29275
- collectMcpFile(scan2, join10(installPath, declared), origin, { recordErrors: true });
29672
+ collectMcpFile(scan2, join13(installPath, declared), origin, { recordErrors: true });
29276
29673
  } else {
29277
29674
  collectMcpObject(scan2, declared, manifestPath, origin);
29278
29675
  }
@@ -29289,18 +29686,18 @@ var SETTINGS_KEY_LABELS = [
29289
29686
  ["statusLine", "status line"]
29290
29687
  ];
29291
29688
  function collectConfigFiles(scan2, claudeDir, cwd) {
29292
- settingsConfigFile(scan2, join10(claudeDir, "settings.json"), "user", "User settings");
29293
- settingsConfigFile(scan2, join10(cwd, ".claude", "settings.json"), "project", "Project settings");
29294
- settingsConfigFile(scan2, join10(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
29295
- memoryConfigFile(scan2, join10(claudeDir, "CLAUDE.md"), "user", "User memory");
29296
- memoryConfigFile(scan2, join10(cwd, "CLAUDE.md"), "project", "Project memory");
29297
- mcpJsonConfigFile(scan2, join10(cwd, ".mcp.json"));
29298
- dirConfigFile(scan2, join10(cwd, ".claude", "commands"), "Slash commands", "command");
29299
- dirConfigFile(scan2, join10(cwd, ".claude", "agents"), "Subagents", "subagent");
29689
+ settingsConfigFile(scan2, join13(claudeDir, "settings.json"), "user", "User settings");
29690
+ settingsConfigFile(scan2, join13(cwd, ".claude", "settings.json"), "project", "Project settings");
29691
+ settingsConfigFile(scan2, join13(cwd, ".claude", "settings.local.json"), "local", "Local overrides");
29692
+ memoryConfigFile(scan2, join13(claudeDir, "CLAUDE.md"), "user", "User memory");
29693
+ memoryConfigFile(scan2, join13(cwd, "CLAUDE.md"), "project", "Project memory");
29694
+ mcpJsonConfigFile(scan2, join13(cwd, ".mcp.json"));
29695
+ dirConfigFile(scan2, join13(cwd, ".claude", "commands"), "Slash commands", "command");
29696
+ dirConfigFile(scan2, join13(cwd, ".claude", "agents"), "Subagents", "subagent");
29300
29697
  }
29301
29698
  function configFileEntry(path, scope, kind) {
29302
29699
  try {
29303
- const stat = statSync5(path);
29700
+ const stat = statSync7(path);
29304
29701
  return { name: basename4(path), path, scope, kind, updatedAt: stat.mtime.toISOString() };
29305
29702
  } catch {
29306
29703
  return void 0;
@@ -29312,9 +29709,9 @@ function settingsConfigFile(scan2, path, scope, kind) {
29312
29709
  const raw = readOptional(path);
29313
29710
  if (raw !== void 0) {
29314
29711
  try {
29315
- const parsed = JSON.parse(raw);
29316
- if (typeof parsed === "object" && parsed !== null) {
29317
- const labels = SETTINGS_KEY_LABELS.filter(([key]) => key in parsed).map(
29712
+ const parsed2 = JSON.parse(raw);
29713
+ if (typeof parsed2 === "object" && parsed2 !== null) {
29714
+ const labels = SETTINGS_KEY_LABELS.filter(([key]) => key in parsed2).map(
29318
29715
  ([, label]) => label
29319
29716
  );
29320
29717
  if (labels.length > 0) entry.detail = labels.join(", ");
@@ -29341,8 +29738,8 @@ function mcpJsonConfigFile(scan2, path) {
29341
29738
  const raw = readOptional(path);
29342
29739
  if (raw !== void 0) {
29343
29740
  try {
29344
- const parsed = JSON.parse(raw);
29345
- const servers = parsed?.mcpServers;
29741
+ const parsed2 = JSON.parse(raw);
29742
+ const servers = parsed2?.mcpServers;
29346
29743
  if (typeof servers === "object" && servers !== null) {
29347
29744
  const count = Object.values(servers).filter(
29348
29745
  (v) => typeof v === "object" && v !== null && (str2(v.command) !== void 0 || str2(v.url) !== void 0)
@@ -29371,7 +29768,7 @@ function countMarkdownFiles(dir, depth) {
29371
29768
  let count = 0;
29372
29769
  for (const dirent of readdirSync2(dir, { withFileTypes: true })) {
29373
29770
  if (dirent.name.startsWith(".")) continue;
29374
- if (dirent.isDirectory()) count += countMarkdownFiles(join10(dir, dirent.name), depth + 1);
29771
+ if (dirent.isDirectory()) count += countMarkdownFiles(join13(dir, dirent.name), depth + 1);
29375
29772
  else if (dirent.name.endsWith(".md")) count += 1;
29376
29773
  }
29377
29774
  return count;
@@ -29384,7 +29781,7 @@ function collectSkillsDir(scan2, dir, origin) {
29384
29781
  return;
29385
29782
  }
29386
29783
  for (const name of names) {
29387
- const skillFile = join10(dir, name, "SKILL.md");
29784
+ const skillFile = join13(dir, name, "SKILL.md");
29388
29785
  try {
29389
29786
  const raw = readOptional(skillFile);
29390
29787
  if (raw === void 0) continue;
@@ -29393,8 +29790,8 @@ function collectSkillsDir(scan2, dir, origin) {
29393
29790
  name: front.name ?? name,
29394
29791
  source: origin.source,
29395
29792
  scope: origin.scope,
29396
- location: join10(dir, name),
29397
- updatedAt: statSync5(skillFile).mtime.toISOString()
29793
+ location: join13(dir, name),
29794
+ updatedAt: statSync7(skillFile).mtime.toISOString()
29398
29795
  };
29399
29796
  const version2 = front.version ?? origin.defaultVersion;
29400
29797
  if (version2 !== void 0) entry.version = version2;
@@ -29424,13 +29821,13 @@ function parseFrontmatter(raw) {
29424
29821
  return out;
29425
29822
  }
29426
29823
  function collectInstalledPlugins(scan2, claudeDir) {
29427
- const manifestPath = join10(claudeDir, "plugins", "installed_plugins.json");
29824
+ const manifestPath = join13(claudeDir, "plugins", "installed_plugins.json");
29428
29825
  const raw = readOptional(manifestPath);
29429
29826
  if (raw === void 0) return;
29430
29827
  let plugins;
29431
29828
  try {
29432
- const parsed = JSON.parse(raw);
29433
- const p = parsed?.plugins;
29829
+ const parsed2 = JSON.parse(raw);
29830
+ const p = parsed2?.plugins;
29434
29831
  if (typeof p !== "object" || p === null) return;
29435
29832
  plugins = p;
29436
29833
  } catch (err) {
@@ -29449,15 +29846,15 @@ function collectInstalledPlugins(scan2, claudeDir) {
29449
29846
  if (typeof installPath !== "string" || seen.has(installPath)) continue;
29450
29847
  seen.add(installPath);
29451
29848
  const version2 = install.version;
29452
- const hooksPath = join10(installPath, "hooks", "hooks.json");
29849
+ const hooksPath = join13(installPath, "hooks", "hooks.json");
29453
29850
  const hooksRaw = readOptional(hooksPath);
29454
29851
  if (hooksRaw !== void 0) {
29455
29852
  try {
29456
- const parsed = JSON.parse(hooksRaw);
29457
- if (typeof parsed === "object" && parsed !== null) {
29853
+ const parsed2 = JSON.parse(hooksRaw);
29854
+ if (typeof parsed2 === "object" && parsed2 !== null) {
29458
29855
  collectHooksObject(
29459
29856
  scan2,
29460
- parsed.hooks,
29857
+ parsed2.hooks,
29461
29858
  hooksPath,
29462
29859
  "plugin",
29463
29860
  pluginName
@@ -29469,22 +29866,22 @@ function collectInstalledPlugins(scan2, claudeDir) {
29469
29866
  }
29470
29867
  const origin = { source: marketplace, scope: "plugin", pluginName };
29471
29868
  if (typeof version2 === "string") origin.defaultVersion = version2;
29472
- collectSkillsDir(scan2, join10(installPath, "skills"), origin);
29869
+ collectSkillsDir(scan2, join13(installPath, "skills"), origin);
29473
29870
  const mcpOrigin = { scope: "plugin", pluginName, marketplace };
29474
- collectMcpFile(scan2, join10(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
29871
+ collectMcpFile(scan2, join13(installPath, ".mcp.json"), mcpOrigin, { recordErrors: true });
29475
29872
  collectPluginManifestMcp(scan2, installPath, mcpOrigin);
29476
29873
  }
29477
29874
  }
29478
29875
  }
29479
29876
  function collectMarketplaceSkills(scan2, claudeDir) {
29480
- for (const mp of readMarketplaces(join10(claudeDir, "plugins", "known_marketplaces.json"))) {
29877
+ for (const mp of readMarketplaces(join13(claudeDir, "plugins", "known_marketplaces.json"))) {
29481
29878
  if (isClaudeOfficialMarketplace(mp.name, mp.repo)) continue;
29482
- collectSkillsDir(scan2, join10(mp.installLocation, "skills"), {
29879
+ collectSkillsDir(scan2, join13(mp.installLocation, "skills"), {
29483
29880
  source: mp.name,
29484
29881
  scope: "plugin"
29485
29882
  });
29486
- collectPluginSkillDirs(scan2, join10(mp.installLocation, "plugins"), mp.name);
29487
- collectPluginSkillDirs(scan2, join10(mp.installLocation, "external_plugins"), mp.name);
29883
+ collectPluginSkillDirs(scan2, join13(mp.installLocation, "plugins"), mp.name);
29884
+ collectPluginSkillDirs(scan2, join13(mp.installLocation, "external_plugins"), mp.name);
29488
29885
  }
29489
29886
  }
29490
29887
  function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
@@ -29495,7 +29892,7 @@ function collectPluginSkillDirs(scan2, pluginsDir, marketplace) {
29495
29892
  return;
29496
29893
  }
29497
29894
  for (const plugin of plugins) {
29498
- collectSkillsDir(scan2, join10(pluginsDir, plugin, "skills"), {
29895
+ collectSkillsDir(scan2, join13(pluginsDir, plugin, "skills"), {
29499
29896
  source: marketplace,
29500
29897
  scope: "plugin",
29501
29898
  pluginName: plugin
@@ -29506,10 +29903,10 @@ function readMarketplaces(manifestPath) {
29506
29903
  const raw = readOptional(manifestPath);
29507
29904
  if (raw === void 0) return [];
29508
29905
  try {
29509
- const parsed = JSON.parse(raw);
29510
- if (typeof parsed !== "object" || parsed === null) return [];
29906
+ const parsed2 = JSON.parse(raw);
29907
+ if (typeof parsed2 !== "object" || parsed2 === null) return [];
29511
29908
  const out = [];
29512
- for (const [name, entry] of Object.entries(parsed)) {
29909
+ for (const [name, entry] of Object.entries(parsed2)) {
29513
29910
  const rec = entry;
29514
29911
  const loc = rec?.installLocation;
29515
29912
  if (typeof loc !== "string" || loc.length === 0) continue;
@@ -29549,7 +29946,7 @@ function dedupeMcpServers(servers) {
29549
29946
  }
29550
29947
  function readOptional(path) {
29551
29948
  try {
29552
- return readFileSync7(path, "utf8");
29949
+ return readFileSync9(path, "utf8");
29553
29950
  } catch {
29554
29951
  return void 0;
29555
29952
  }
@@ -29577,17 +29974,17 @@ function offersMaintenance(gateway, member) {
29577
29974
  import { createHash as createHash4, randomUUID as randomUUID13 } from "crypto";
29578
29975
 
29579
29976
  // ../../packages/plugin-sdk/src/isolated-scan.ts
29580
- import { existsSync as existsSync7 } from "fs";
29977
+ import { existsSync as existsSync8 } from "fs";
29581
29978
  import { fileURLToPath } from "url";
29582
29979
  import { Worker } from "worker_threads";
29583
29980
 
29584
29981
  // ../../packages/plugin-sdk/src/ignore-layers.ts
29585
29982
  var import_ignore = __toESM(require_ignore(), 1);
29586
- import { readFileSync as readFileSync8 } from "fs";
29587
- import { join as join11 } from "path";
29983
+ import { readFileSync as readFileSync10 } from "fs";
29984
+ import { join as join14 } from "path";
29588
29985
  function readIgnoreLayer(dir, filename, anchorLen) {
29589
29986
  try {
29590
- return { matcher: (0, import_ignore.default)().add(readFileSync8(join11(dir, filename), "utf8")), anchorLen };
29987
+ return { matcher: (0, import_ignore.default)().add(readFileSync10(join14(dir, filename), "utf8")), anchorLen };
29591
29988
  } catch {
29592
29989
  return void 0;
29593
29990
  }
@@ -29644,17 +30041,17 @@ function resolveInventoryContext(input) {
29644
30041
  }
29645
30042
 
29646
30043
  // ../../packages/plugin-sdk/src/nudge.ts
29647
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
29648
- import { join as join12 } from "path";
30044
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "fs";
30045
+ import { join as join15 } from "path";
29649
30046
  var SESSION_START_MARKER = "session-start-last";
29650
30047
  function claimSessionStart(dataDir2, sessionId) {
29651
30048
  return claimOncePerSession(dataDir2, SESSION_START_MARKER, sessionId);
29652
30049
  }
29653
30050
  function claimOncePerSession(dataDir2, marker, sessionId) {
29654
30051
  if (!sessionId) return true;
29655
- const path = join12(dataDir2, marker);
30052
+ const path = join15(dataDir2, marker);
29656
30053
  try {
29657
- if (readFileSync9(path, "utf8") === sessionId) return false;
30054
+ if (readFileSync11(path, "utf8") === sessionId) return false;
29658
30055
  } catch {
29659
30056
  }
29660
30057
  try {
@@ -29666,12 +30063,12 @@ function claimOncePerSession(dataDir2, marker, sessionId) {
29666
30063
  }
29667
30064
 
29668
30065
  // ../../packages/plugin-sdk/src/paths.ts
29669
- import { readdirSync as readdirSync3, realpathSync as realpathSync2 } from "fs";
29670
- import { basename as basename5, dirname as dirname3, sep as sep3 } from "path";
30066
+ import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
30067
+ import { basename as basename5, dirname as dirname4, sep as sep3 } from "path";
29671
30068
 
29672
30069
  // ../../packages/plugin-sdk/src/project-files.ts
29673
- import { existsSync as existsSync8, readdirSync as readdirSync4 } from "fs";
29674
- import { basename as basename6, join as join13 } from "path";
30070
+ import { existsSync as existsSync9, readdirSync as readdirSync4 } from "fs";
30071
+ import { basename as basename6, join as join16 } from "path";
29675
30072
  var SKIP_DIRS = /* @__PURE__ */ new Set([
29676
30073
  ".git",
29677
30074
  "node_modules",
@@ -29768,8 +30165,8 @@ function resolveProjectFiles(cwd, opts = {}) {
29768
30165
  }
29769
30166
  if (entry.isDirectory()) {
29770
30167
  if (SKIP_DIRS.has(entry.name) || isIgnored(dirLayers, dirRel, entry.name, true)) continue;
29771
- const fullPath = join13(dir, entry.name);
29772
- if (existsSync8(join13(fullPath, ".git"))) continue;
30168
+ const fullPath = join16(dir, entry.name);
30169
+ if (existsSync9(join16(fullPath, ".git"))) continue;
29773
30170
  if (depth >= bounds.maxDepth) {
29774
30171
  walk.omitted = true;
29775
30172
  continue;
@@ -29840,8 +30237,8 @@ function hostOf2(url2) {
29840
30237
  }
29841
30238
  }
29842
30239
  function resolveAntigravityProvider() {
29843
- const parsed = AntigravityProviderEnvSchema.safeParse(process.env);
29844
- const env = parsed.success ? parsed.data : AntigravityProviderEnvSchema.parse({});
30240
+ const parsed2 = AntigravityProviderEnvSchema.safeParse(process.env);
30241
+ const env = parsed2.success ? parsed2.data : AntigravityProviderEnvSchema.parse({});
29845
30242
  const baseUrl = env.GOOGLE_GEMINI_BASE_URL;
29846
30243
  if (baseUrl !== void 0 && baseUrl !== "") {
29847
30244
  const host = hostOf2(baseUrl);
@@ -29870,12 +30267,12 @@ import { randomUUID as randomUUID14 } from "crypto";
29870
30267
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
29871
30268
 
29872
30269
  // ../../packages/plugin-sdk/src/throttle.ts
29873
- import { mkdirSync as mkdirSync3, statSync as statSync6, writeFileSync as writeFileSync6 } from "fs";
29874
- import { join as join14 } from "path";
30270
+ import { mkdirSync as mkdirSync3, statSync as statSync8, writeFileSync as writeFileSync6 } from "fs";
30271
+ import { join as join17 } from "path";
29875
30272
  function throttled(dataDir2, markerName, windowMs) {
29876
- const marker = join14(dataDir2, markerName);
30273
+ const marker = join17(dataDir2, markerName);
29877
30274
  try {
29878
- if (Date.now() - statSync6(marker).mtimeMs < windowMs) return true;
30275
+ if (Date.now() - statSync8(marker).mtimeMs < windowMs) return true;
29879
30276
  } catch {
29880
30277
  }
29881
30278
  try {
@@ -29886,28 +30283,1176 @@ function throttled(dataDir2, markerName, windowMs) {
29886
30283
  return false;
29887
30284
  }
29888
30285
 
29889
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
29890
- import { randomUUID as randomUUID15 } from "crypto";
29891
-
29892
- // ../../packages/plugin-runtime/src/recorder.ts
29893
- var PLUGIN_RECORDER_BINARY = "plugin";
29894
- function pluginRecordedBy(version2) {
29895
- return `${PLUGIN_RECORDER_BINARY}@${version2}`;
30286
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
30287
+ var REQUEST_TIMEOUT_MS = 2e3;
30288
+ function withTimeout(promise2, ms) {
30289
+ let timer;
30290
+ const timeout = new Promise((_, reject) => {
30291
+ timer = setTimeout(() => {
30292
+ reject(new Error("attached gateway request timed out"));
30293
+ }, ms);
30294
+ });
30295
+ promise2.catch(() => void 0);
30296
+ return Promise.race([promise2, timeout]).finally(() => {
30297
+ clearTimeout(timer);
30298
+ });
29896
30299
  }
29897
30300
 
29898
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
29899
- var StandaloneDataGateway = class {
29900
- db;
29901
- // Kept for the fingerprint key lookup (exception.key lives beside the store).
29902
- dataDir;
29903
- // One notice per gateway — see warnRulesetDiscarded.
29904
- warnedRulesetDiscarded = false;
29905
- constructor(dataDir2, detections = [], meta3) {
29906
- this.db = openLocalDatabase(dataDir2);
29907
- this.dataDir = dataDir2;
29908
- this.db.installedPacks.recordInventory(detections, meta3);
29909
- }
29910
- recordCapture(record2) {
30301
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
30302
+ function isInvalidRequest(err) {
30303
+ return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
30304
+ }
30305
+ var FORWARD_BUDGET_MS = 1500;
30306
+ var DECISION_PATH_BUDGET_MS = 800;
30307
+ var BREAKER_FAILURE_THRESHOLD = 3;
30308
+ var BREAKER_COOLDOWN_MS = 3e4;
30309
+ var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
30310
+ var FAILURES = /* @__PURE__ */ new Set([
30311
+ "unauthorized",
30312
+ "forbidden",
30313
+ "unreachable"
30314
+ ]);
30315
+ var FORWARD_STATE_FILENAME = "attached-state.json";
30316
+ var STATE_FILENAME = FORWARD_STATE_FILENAME;
30317
+ function parseBreakerState(raw, nowMs) {
30318
+ try {
30319
+ const parsed2 = JSON.parse(raw);
30320
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30321
+ const record2 = parsed2;
30322
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
30323
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
30324
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
30325
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
30326
+ } catch {
30327
+ return null;
30328
+ }
30329
+ }
30330
+ function createForwardPolicy(deps) {
30331
+ const now = deps.now ?? (() => Date.now());
30332
+ const file2 = join18(deps.dir, STATE_FILENAME);
30333
+ let state = null;
30334
+ let loading = null;
30335
+ async function readState() {
30336
+ let raw;
30337
+ try {
30338
+ raw = await readFile(file2, "utf8");
30339
+ } catch {
30340
+ return { ...CLOSED };
30341
+ }
30342
+ return parseBreakerState(raw, now()) ?? { ...CLOSED };
30343
+ }
30344
+ async function load() {
30345
+ if (state !== null) return state;
30346
+ loading ??= readState().then((loaded) => {
30347
+ state = loaded;
30348
+ loading = null;
30349
+ return loaded;
30350
+ });
30351
+ return loading;
30352
+ }
30353
+ async function persist(next) {
30354
+ state = next;
30355
+ try {
30356
+ await ensureDataDir(deps.dir);
30357
+ const tmp = `${file2}.${randomUUID15()}.tmp`;
30358
+ await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
30359
+ await rename(tmp, file2);
30360
+ } catch {
30361
+ }
30362
+ }
30363
+ return {
30364
+ async run(op, opts) {
30365
+ const budget = opts?.decisionPath === true ? DECISION_PATH_BUDGET_MS : FORWARD_BUDGET_MS;
30366
+ let current;
30367
+ try {
30368
+ current = await load();
30369
+ } catch {
30370
+ current = { ...CLOSED };
30371
+ }
30372
+ const at = now();
30373
+ if (current.openedAtMs !== null) {
30374
+ if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
30375
+ return { ok: false, reason: "breaker-open" };
30376
+ }
30377
+ await persist({
30378
+ consecutiveFailures: current.consecutiveFailures,
30379
+ openedAtMs: at,
30380
+ lastFailure: current.lastFailure
30381
+ });
30382
+ }
30383
+ try {
30384
+ const value = await withTimeout(op(), budget);
30385
+ if (current.openedAtMs !== null || current.consecutiveFailures > 0) {
30386
+ await persist({ ...CLOSED });
30387
+ }
30388
+ return { ok: true, value };
30389
+ } catch (err) {
30390
+ if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
30391
+ const reason = classifyFailure(err);
30392
+ const failures = current.consecutiveFailures + 1;
30393
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
30394
+ await persist({
30395
+ consecutiveFailures: failures,
30396
+ openedAtMs: shouldOpen ? now() : null,
30397
+ lastFailure: reason
30398
+ });
30399
+ return { ok: false, reason };
30400
+ }
30401
+ }
30402
+ };
30403
+ }
30404
+
30405
+ // ../../packages/plugin-runtime/src/attached/gateway.ts
30406
+ var ACTION_STRENGTH = {
30407
+ allow: 0,
30408
+ log: 1,
30409
+ warn: 2,
30410
+ redact: 3,
30411
+ block: 4
30412
+ };
30413
+ function ruleCategoryMap(wireRules, localRules) {
30414
+ const map2 = /* @__PURE__ */ new Map();
30415
+ for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
30416
+ for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
30417
+ for (const pack of bundledDetections()) {
30418
+ for (const rule of pack.rules) map2.set(rule.id, rule.category);
30419
+ }
30420
+ return map2;
30421
+ }
30422
+ function strongerOf(a, b) {
30423
+ if (a === null) return b;
30424
+ if (b === null) return a;
30425
+ return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
30426
+ }
30427
+ function policyKey(policy) {
30428
+ return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
30429
+ }
30430
+ function floorFor(policy, categoryByRuleId) {
30431
+ const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
30432
+ return category === void 0 ? null : DEFAULT_ACTIONS[category];
30433
+ }
30434
+ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
30435
+ const merged = /* @__PURE__ */ new Map();
30436
+ const disabled = [];
30437
+ const remoteCategoryAction = /* @__PURE__ */ new Map();
30438
+ for (const policy of remotePolicies) {
30439
+ if (!policy.enabled) continue;
30440
+ if (!("category" in policy.target)) continue;
30441
+ if (remoteCategoryAction.has(policy.target.category)) continue;
30442
+ const floor = floorFor(policy, categoryByRuleId);
30443
+ remoteCategoryAction.set(
30444
+ policy.target.category,
30445
+ floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
30446
+ );
30447
+ }
30448
+ for (const policy of localPolicies) {
30449
+ if (!policy.enabled) {
30450
+ disabled.push(policy);
30451
+ continue;
30452
+ }
30453
+ const key = policyKey(policy);
30454
+ if (merged.has(key)) continue;
30455
+ let remoteFloor = null;
30456
+ if ("ruleId" in policy.target) {
30457
+ const category = categoryByRuleId.get(policy.target.ruleId);
30458
+ if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
30459
+ }
30460
+ merged.set(
30461
+ key,
30462
+ remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
30463
+ );
30464
+ }
30465
+ const localCategoryAction = /* @__PURE__ */ new Map();
30466
+ for (const policy of merged.values()) {
30467
+ if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
30468
+ }
30469
+ for (const policy of remotePolicies) {
30470
+ if (!policy.enabled) {
30471
+ disabled.push(policy);
30472
+ continue;
30473
+ }
30474
+ const key = policyKey(policy);
30475
+ const floor = floorFor(policy, categoryByRuleId);
30476
+ let localFloor = null;
30477
+ if ("ruleId" in policy.target) {
30478
+ const category = categoryByRuleId.get(policy.target.ruleId);
30479
+ if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
30480
+ }
30481
+ const effectiveFloor = strongerOf(floor, localFloor);
30482
+ const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
30483
+ const existing = merged.get(key);
30484
+ if (existing === void 0) {
30485
+ merged.set(key, clamped);
30486
+ continue;
30487
+ }
30488
+ if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
30489
+ merged.set(key, clamped);
30490
+ }
30491
+ }
30492
+ return [...merged.values(), ...disabled];
30493
+ }
30494
+ var AttachedDataGateway = class {
30495
+ constructor(deps) {
30496
+ this.deps = deps;
30497
+ }
30498
+ deps;
30499
+ /**
30500
+ * The control plane's OWN resolution of this session's inventory, captured by
30501
+ * ensureInventory. Null until the first successful forward — and it stays
30502
+ * null for the whole session when the control plane is unreachable, which is fine:
30503
+ * reKeyForForward then leaves the event's ids alone and the control plane resolves
30504
+ * what it can from the descriptors it already has.
30505
+ */
30506
+ remoteInventory = null;
30507
+ // ---------------------------------------------------------------------
30508
+ // Writes: local first, then forward.
30509
+ // ---------------------------------------------------------------------
30510
+ async recordCapture(record2) {
30511
+ await this.deps.local.recordCapture(record2);
30512
+ await this.deps.forward.run(
30513
+ () => this.deps.client.ingestEvents({
30514
+ events: [record2.event],
30515
+ ...record2.dedupe ? { dedupe: record2.dedupe } : {}
30516
+ }),
30517
+ { decisionPath: true }
30518
+ );
30519
+ }
30520
+ async ensureInventory(ctx) {
30521
+ const resolved = await this.deps.local.ensureInventory(ctx);
30522
+ const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
30523
+ this.remoteInventory = remote.ok ? remote.value : null;
30524
+ const snapshot = await (async () => {
30525
+ try {
30526
+ return await this.deps.posture?.prepare() ?? null;
30527
+ } catch {
30528
+ return null;
30529
+ }
30530
+ })();
30531
+ if (snapshot) {
30532
+ try {
30533
+ await withTimeout(
30534
+ this.deps.posture?.send(snapshot) ?? Promise.resolve(),
30535
+ REQUEST_TIMEOUT_MS
30536
+ );
30537
+ } catch {
30538
+ }
30539
+ }
30540
+ return resolved;
30541
+ }
30542
+ // The id is minted CLIENT-side and stored verbatim: the control plane does NOT
30543
+ // re-key it. `pgAuditValues` writes `id: event.id` and carries tenancy in
30544
+ // its own scoping columns, so the device and the forwarded copy
30545
+ // share one id space — which is what makes a re-post idempotent at all.
30546
+ //
30547
+ // Re-posts collapse via `onConflictDoUpdate` on the `id` PK, guarded by
30548
+ // `setWhere eventType = 'session'` (NOT onConflictDoNothing). That guard is
30549
+ // what makes an attached retry safe: a capture-stubbed session row can still
30550
+ // be HEALED by the authoritative root, while a duplicate non-session event —
30551
+ // a retried tool_call, exactly this path — can never stomp a populated row.
30552
+ async recordAuditEvent(event) {
30553
+ await this.deps.local.recordAuditEvent(event);
30554
+ await this.deps.forward.run(
30555
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
30556
+ );
30557
+ }
30558
+ // Attached `llm_call` is written locally by the inner gateway, then routed to
30559
+ // the control plane through the existing `recordAuditEvent` ingest (no dedicated
30560
+ // client method yet) by pre-building the audit event from the natural key.
30561
+ // The forward goes DIRECTLY to the client rather than through this.recordAuditEvent,
30562
+ // which would write the event to the local store a second time.
30563
+ async recordLlmCall(input) {
30564
+ await this.deps.local.recordLlmCall(input);
30565
+ await this.deps.forward.run(
30566
+ () => this.deps.client.recordAuditEvent(
30567
+ reKeyForForward(llmAuditEvent(input), this.remoteInventory)
30568
+ )
30569
+ );
30570
+ }
30571
+ /**
30572
+ * Forward one batch, item by item, under ONE aggregate deadline.
30573
+ *
30574
+ * Per-item budgets bound each request and nothing bounded their sum — see
30575
+ * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
30576
+ * rather than sent: the local write has already succeeded, so every caller
30577
+ * has a correct result to return, and a drop is the outcome this path is
30578
+ * built to accept (G8) where a blown hook timeout is not.
30579
+ *
30580
+ * Serial rather than concurrent on purpose. Firing N requests at once would
30581
+ * trade a latency problem for a burst the plane's own per-key rate limiting
30582
+ * would answer with the refusals the breaker then counts.
30583
+ *
30584
+ * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
30585
+ * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
30586
+ * lets status call the forward unhealthy; this path returns BEFORE `run` is
30587
+ * reached, so without the tally in `forward-drops.ts` a slow-but-answering
30588
+ * plane produces no failures, keeps the breaker closed, renders a healthy
30589
+ * block, and discards the tail of every batch indefinitely.
30590
+ */
30591
+ async forwardBatch(inputs, toEvent) {
30592
+ const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
30593
+ for (let i = 0; i < inputs.length; i += 1) {
30594
+ const now = Date.now();
30595
+ if (now >= deadline) {
30596
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
30597
+ return;
30598
+ }
30599
+ const input = inputs[i];
30600
+ await this.deps.forward.run(
30601
+ () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input), this.remoteInventory))
30602
+ );
30603
+ }
30604
+ }
30605
+ // Delegated as a BATCH rather than looped over recordLlmCall: the inner
30606
+ // gateway may write the whole batch in one local transaction, and looping
30607
+ // here would replace that with N separate local writes.
30608
+ async recordLlmCalls(inputs) {
30609
+ await this.deps.local.recordLlmCalls(inputs);
30610
+ await this.forwardBatch(inputs, (input) => llmAuditEvent(input));
30611
+ }
30612
+ // `input.inspections` (secrets detected client-side in the tool's masked
30613
+ // target) ride along on the request's `inspections` field — the control plane
30614
+ // persists each as an inspection_findings row linked to this audit event
30615
+ // (see RecordAuditEventRequest in @akasecurity/schema). The masked
30616
+ // `target` already rides `input.attributes`, so no raw secret leaks either
30617
+ // way — this only stops the FINDING row itself from being dropped.
30618
+ async recordToolCalls(inputs) {
30619
+ await this.deps.local.recordToolCalls(inputs);
30620
+ await this.forwardBatch(inputs, (input) => toolAuditEvent(input));
30621
+ }
30622
+ // Forwarded as a `config_scan` audit event: there is no dedicated
30623
+ // config-scan ingest endpoint, and the audit-event door is the one the
30624
+ // control plane already opens for client-minted, idempotent records.
30625
+ //
30626
+ // ONLY `scanEvent` CROSSES, and unlike `recordCapture` the plane cannot
30627
+ // re-derive the rest. A `ConfigScanRecord` is four things committed together
30628
+ // locally — the inventory `items`, this audit event, and the posture
30629
+ // `definitions`/`findings` that reference it — and three of them stay on the
30630
+ // device. Say that plainly rather than let the asymmetry with `recordCapture`
30631
+ // read as the same argument: there, findings are omitted BECAUSE the plane
30632
+ // re-derives them from `Event.content`; here there is no content to re-derive
30633
+ // from, so what is omitted is simply not sent.
30634
+ //
30635
+ // That is the wire contract as it stands rather than an oversight to patch
30636
+ // here. `items` has no route at all, and `RecordAuditEventRequest.inspections`
30637
+ // is documented as tool-call findings — widening it to carry config-scan
30638
+ // findings is an egress change (a posture finding's `maskedMatch` holds the
30639
+ // matched command) and a decision about what an attached deployment is
30640
+ // entitled to, not a bug fix. An attached machine's config posture therefore
30641
+ // reaches the plane as the event only; the dashboard's own view of it is the
30642
+ // local store.
30643
+ async recordConfigScan(record2) {
30644
+ await this.deps.local.recordConfigScan(record2);
30645
+ await this.deps.forward.run(
30646
+ () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
30647
+ );
30648
+ }
30649
+ async recordBlockedDetection(entry) {
30650
+ return this.deps.local.recordBlockedDetection(entry);
30651
+ }
30652
+ /**
30653
+ * LOCAL-ONLY, deliberately. The shares API is read-plus-decision-override
30654
+ * with no egress ingest endpoint, so there is nothing to forward to; adding a
30655
+ * forward here would be inventing a wire contract that does not exist. The
30656
+ * local write is the whole operation, and its summary is the real one — the
30657
+ * scanner reads a throw as a FAILED WRITE and skips its ledger commit, so
30658
+ * returning the inner gateway's result keeps the retry semantics honest.
30659
+ */
30660
+ async recordProjectEgress(input) {
30661
+ return this.deps.local.recordProjectEgress(input);
30662
+ }
30663
+ // ---------------------------------------------------------------------
30664
+ // Reads and device-local ledgers: pure delegation.
30665
+ // ---------------------------------------------------------------------
30666
+ async configInventoryReport() {
30667
+ return this.deps.local.configInventoryReport();
30668
+ }
30669
+ async readSessionProvider(sessionId) {
30670
+ return this.deps.local.readSessionProvider(sessionId);
30671
+ }
30672
+ async facets() {
30673
+ return this.deps.local.facets();
30674
+ }
30675
+ /**
30676
+ * Delegated UNMODIFIED — including its refusals.
30677
+ *
30678
+ * This is a fail-secure boundary: it decides whether an approved exception
30679
+ * lets a blocked action through. Under local-first the local store owns the
30680
+ * exception ledger, so the honest answer is whatever it says; wrapping this
30681
+ * in a fallback (`catch { return true }`, or defaulting on a timeout) would
30682
+ * turn a store error into a granted bypass. If the inner gateway rejects,
30683
+ * this rejects, and the runtime's own handling decides — which is asserted
30684
+ * end-to-end through runtime.capture rather than here.
30685
+ */
30686
+ async consumeException(id) {
30687
+ return this.deps.local.consumeException(id);
30688
+ }
30689
+ async recentFindings(opts) {
30690
+ return this.deps.local.recentFindings(opts);
30691
+ }
30692
+ async healthSummary() {
30693
+ return this.deps.local.healthSummary();
30694
+ }
30695
+ async activityByDay(days) {
30696
+ return this.deps.local.activityByDay(days);
30697
+ }
30698
+ async tokenReports() {
30699
+ return this.deps.local.tokenReports();
30700
+ }
30701
+ async knownContentHashes() {
30702
+ return this.deps.local.knownContentHashes();
30703
+ }
30704
+ async scanLedger(rulesetHash) {
30705
+ return this.deps.local.scanLedger(rulesetHash);
30706
+ }
30707
+ async recordScanned(entries) {
30708
+ return this.deps.local.recordScanned(entries);
30709
+ }
30710
+ async getRuleProbeVerdict(ruleKey) {
30711
+ return this.deps.local.getRuleProbeVerdict(ruleKey);
30712
+ }
30713
+ async setRuleProbeVerdict(ruleKey, verdict, worstProbeMs) {
30714
+ return this.deps.local.setRuleProbeVerdict(ruleKey, verdict, worstProbeMs);
30715
+ }
30716
+ async openAtRestKeysForPath(path) {
30717
+ return this.deps.local.openAtRestKeysForPath(path);
30718
+ }
30719
+ async resolvedAtRestKeysForPath(path) {
30720
+ return this.deps.local.resolvedAtRestKeysForPath(path);
30721
+ }
30722
+ async insertResolution(input) {
30723
+ return this.deps.local.insertResolution(input);
30724
+ }
30725
+ async close() {
30726
+ return this.deps.local.close();
30727
+ }
30728
+ // ---------------------------------------------------------------------
30729
+ // Policy
30730
+ // ---------------------------------------------------------------------
30731
+ async getPolicyBundle() {
30732
+ const local = await this.deps.local.getPolicyBundle();
30733
+ const cached2 = await (async () => {
30734
+ try {
30735
+ return await this.deps.readCachedBundle();
30736
+ } catch {
30737
+ return null;
30738
+ }
30739
+ })();
30740
+ if (cached2 === null) return local;
30741
+ const byRuleId = /* @__PURE__ */ new Map();
30742
+ for (const rule of [...local.rules ?? [], ...cached2.rules ?? []]) {
30743
+ if (!byRuleId.has(rule.id)) byRuleId.set(rule.id, rule);
30744
+ }
30745
+ const rules = [...byRuleId.values()];
30746
+ return {
30747
+ ...local,
30748
+ // The remote version identifies the composed bundle for the poller.
30749
+ version: cached2.version,
30750
+ rules,
30751
+ policies: mergeRaiseOnly(
30752
+ local.policies,
30753
+ cached2.policies,
30754
+ ruleCategoryMap(cached2.rules, local.rules)
30755
+ ),
30756
+ customKeywords: [...local.customKeywords, ...cached2.customKeywords]
30757
+ // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
30758
+ // snapshot) and is taken from the LOCAL bundle only — never from the wire
30759
+ // or the on-disk cache. Honoring a cached one would hand the control plane, or
30760
+ // anything able to write policy-cache.json, a kill-switch over the
30761
+ // compiled-in bundled packs: `{ rulesComplete: true, rules: [] }` would
30762
+ // zero local detection. Spread from `local` above, and deliberately not
30763
+ // re-read from `cached` here.
30764
+ //
30765
+ // THREE MORE OF THE CACHED BUNDLE'S FIELDS ARE DROPPED, each on purpose,
30766
+ // and each named here so a reader can tell a decision from an omission:
30767
+ //
30768
+ // `exceptions` — an exception SUPPRESSES a detection, so honoring
30769
+ // one from an unsigned on-disk cache would let
30770
+ // anything able to write that file turn rules off.
30771
+ // Every other field this merge accepts can only
30772
+ // RAISE enforcement; this is the one that cannot,
30773
+ // so it stays local-only until the bundle is
30774
+ // signed. Exceptions remain a device-local ledger.
30775
+ // `reversibleRuleIds` — the Redact & Vault archetype makes a redaction
30776
+ // recoverable, which is a CUSTODY change: it puts
30777
+ // the detected value in the local vault instead of
30778
+ // destroying it. Taking that instruction from the
30779
+ // cache would let a remote party turn one-way
30780
+ // redaction into retention. Dropping it keeps the
30781
+ // one-way behaviour, which the schema itself calls
30782
+ // "the safe direction to default".
30783
+ // `ruleVersions` — remote rules fall back to their own spec version.
30784
+ // Cosmetic rather than protective: it only affects
30785
+ // how a finding is version-attributed, and the two
30786
+ // sides may therefore attribute org rules
30787
+ // differently. Worth carrying once there is a
30788
+ // reader that needs it; nothing reads it today.
30789
+ };
30790
+ }
30791
+ // ---------------------------------------------------------------------
30792
+ // LocalStoreMaintenance — by delegation (D3).
30793
+ //
30794
+ // Implementing these is what actually closes the skipped-local-maintenance
30795
+ // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
30796
+ // any object carrying all five, so the composite qualifies and SessionStart
30797
+ // runs maintenance on the device's real store.
30798
+ //
30799
+ // ⚠ Two of the five are SYNCHRONOUS and must stay that way. `handle-session-start`
30800
+ // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
30801
+ // return value directly; declaring them `async` here would hand those call
30802
+ // sites a Promise and silently break both.
30803
+ // ---------------------------------------------------------------------
30804
+ async sweepTerminalExceptions(retentionMs) {
30805
+ return this.deps.local.sweepTerminalExceptions(retentionMs);
30806
+ }
30807
+ capWarnEraEnforcement(policyMode) {
30808
+ return this.deps.local.capWarnEraEnforcement(policyMode);
30809
+ }
30810
+ async recordProjectFiles(projectId, scan2) {
30811
+ return this.deps.local.recordProjectFiles(projectId, scan2);
30812
+ }
30813
+ async reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot) {
30814
+ return this.deps.local.reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot);
30815
+ }
30816
+ staleBinaryNotice(currentVersion) {
30817
+ return this.deps.local.staleBinaryNotice(currentVersion);
30818
+ }
30819
+ };
30820
+ function reKeyForForward(event, remote) {
30821
+ if (remote === null) {
30822
+ const stripped = { ...event };
30823
+ delete stripped.hostId;
30824
+ delete stripped.harnessId;
30825
+ delete stripped.sourceProjectId;
30826
+ return stripped;
30827
+ }
30828
+ const rekeyed = { ...event };
30829
+ delete rekeyed.hostId;
30830
+ delete rekeyed.harnessId;
30831
+ delete rekeyed.sourceProjectId;
30832
+ if (remote.hostId !== void 0) rekeyed.hostId = remote.hostId;
30833
+ if (remote.harnessId !== void 0) rekeyed.harnessId = remote.harnessId;
30834
+ if (remote.sourceProjectId !== void 0) rekeyed.sourceProjectId = remote.sourceProjectId;
30835
+ return rekeyed;
30836
+ }
30837
+ var BATCH_FORWARD_BUDGET_MS = 3e3;
30838
+ function llmAuditEvent(input) {
30839
+ return {
30840
+ id: llmCallId(input.sessionId, input.messageId),
30841
+ eventType: "llm_call",
30842
+ startedAt: input.startedAt,
30843
+ parentId: input.parentId,
30844
+ rootSessionId: input.rootSessionId,
30845
+ attributes: input.attributes
30846
+ };
30847
+ }
30848
+ function toolAuditEvent(input) {
30849
+ return {
30850
+ id: toolCallId(input.sessionId, input.toolUseId),
30851
+ eventType: "tool_call",
30852
+ startedAt: input.startedAt,
30853
+ parentId: input.parentId,
30854
+ rootSessionId: input.rootSessionId,
30855
+ attributes: input.attributes,
30856
+ inspections: input.inspections
30857
+ };
30858
+ }
30859
+
30860
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
30861
+ import { randomUUID as randomUUID16 } from "crypto";
30862
+ import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
30863
+ import { join as join19 } from "path";
30864
+
30865
+ // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
30866
+ import { rename as rename2 } from "fs/promises";
30867
+ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
30868
+ var ATTEMPTS = 5;
30869
+ var delay = (ms) => new Promise((resolve2) => {
30870
+ setTimeout(resolve2, ms);
30871
+ });
30872
+ async function publishByRename(tmp, file2, move = rename2) {
30873
+ for (let attempt = 1; ; attempt += 1) {
30874
+ try {
30875
+ await move(tmp, file2);
30876
+ return;
30877
+ } catch (err) {
30878
+ const code = err.code;
30879
+ if (attempt >= ATTEMPTS || code === void 0 || !RETRYABLE.has(code)) throw err;
30880
+ await delay(attempt * 10);
30881
+ }
30882
+ }
30883
+ }
30884
+
30885
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
30886
+ function createPolicyStore(dir = dataDir()) {
30887
+ const file2 = join19(dir, "policy-cache.json");
30888
+ async function read() {
30889
+ try {
30890
+ const raw = await readFile2(file2, "utf8");
30891
+ const parsed2 = JSON.parse(raw);
30892
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30893
+ const record2 = parsed2;
30894
+ const bundle = PolicyBundle.parse(record2.bundle);
30895
+ const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
30896
+ const etag = typeof record2.etag === "string" ? record2.etag : void 0;
30897
+ return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
30898
+ } catch {
30899
+ return null;
30900
+ }
30901
+ }
30902
+ async function write(bundle, etag) {
30903
+ await ensureDataDir(dir);
30904
+ const stored = {
30905
+ bundle,
30906
+ fetchedAtMs: Date.now(),
30907
+ ...etag === void 0 ? {} : { etag }
30908
+ };
30909
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
30910
+ try {
30911
+ await writeFile2(tmp, JSON.stringify(stored), {
30912
+ encoding: "utf8",
30913
+ mode: DATA_FILE_MODE,
30914
+ flag: "wx"
30915
+ });
30916
+ await publishByRename(tmp, file2);
30917
+ } catch (err) {
30918
+ await rm(tmp, { force: true }).catch(() => void 0);
30919
+ throw err;
30920
+ }
30921
+ }
30922
+ return { read, write, file: file2 };
30923
+ }
30924
+
30925
+ // ../../packages/remote/src/http.ts
30926
+ import { request as httpRequest } from "http";
30927
+ import { request as httpsRequest } from "https";
30928
+ var DEFAULT_TIMEOUT_MS = 1e4;
30929
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
30930
+ var RemoteRequestError = class extends Error {
30931
+ constructor(status) {
30932
+ super(`control-plane request failed with status ${String(status)}`);
30933
+ this.status = status;
30934
+ this.name = "RemoteRequestError";
30935
+ }
30936
+ status;
30937
+ };
30938
+ var RemoteRequestInvalid = class extends Error {
30939
+ constructor(route, cause) {
30940
+ super(`refusing to send a malformed body to ${route}`);
30941
+ this.cause = cause;
30942
+ this.name = "RemoteRequestInvalid";
30943
+ }
30944
+ cause;
30945
+ };
30946
+ var RemoteResponseInvalid = class extends Error {
30947
+ constructor(route, detail) {
30948
+ super(`control plane answered ${route} with ${detail}`);
30949
+ this.name = "RemoteResponseInvalid";
30950
+ }
30951
+ };
30952
+ var RemoteTransportError = class extends Error {
30953
+ /**
30954
+ * The status the peer sent, when headers arrived and only the BODY was
30955
+ * refused.
30956
+ *
30957
+ * Undefined for the ordinary case this class was written for — no answer at
30958
+ * all. It exists because two paths reject after a status has already been
30959
+ * delivered: an oversized body and an aborted response. Discarding it there
30960
+ * reported a deployment answering 401 with a verbose body as a network
30961
+ * outage, which sends the reader to look at their network instead of their
30962
+ * credential.
30963
+ */
30964
+ constructor(reason, status) {
30965
+ super(`control-plane request did not complete: ${reason}`);
30966
+ this.status = status;
30967
+ this.name = "RemoteTransportError";
30968
+ }
30969
+ status;
30970
+ };
30971
+ async function send(options) {
30972
+ const url2 = new URL(options.url);
30973
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
30974
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
30975
+ const requestOptions = {
30976
+ method: options.method,
30977
+ headers: {
30978
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
30979
+ // last they win, and two of the values below are ones no caller may
30980
+ // replace: `x-api-key` is the credential, and `content-length` is the
30981
+ // byte count that stops a multi-byte body being truncated by the
30982
+ // receiver. `SendOptions.headers` is a free-form record on an exported
30983
+ // function, so "no caller does that today" is not the guarantee to rely
30984
+ // on. The one header any caller actually passes — `if-none-match` on the
30985
+ // conditional GET — is untouched by this order.
30986
+ ...options.headers,
30987
+ // The credential. One header, matching what the deployment authenticates
30988
+ // on; a second copy in an `Authorization` header would be one more place
30989
+ // it can be logged by an intermediary for no gain.
30990
+ "x-api-key": options.apiKey,
30991
+ accept: "application/json",
30992
+ ...options.body === void 0 ? {} : {
30993
+ "content-type": "application/json",
30994
+ // Byte length, not string length: a multi-byte body sent with a
30995
+ // character count is truncated by the receiver.
30996
+ "content-length": String(Buffer.byteLength(options.body))
30997
+ }
30998
+ }
30999
+ };
31000
+ return new Promise((resolve2, reject) => {
31001
+ let settled = false;
31002
+ const fail = (reason, status) => {
31003
+ if (settled) return;
31004
+ settled = true;
31005
+ reject(new RemoteTransportError(reason, status));
31006
+ };
31007
+ const req = send_(url2, requestOptions, (res) => {
31008
+ const chunks = [];
31009
+ let size = 0;
31010
+ res.on("data", (chunk) => {
31011
+ size += chunk.length;
31012
+ if (size > MAX_RESPONSE_BYTES) {
31013
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
31014
+ res.destroy();
31015
+ req.destroy();
31016
+ return;
31017
+ }
31018
+ chunks.push(chunk);
31019
+ });
31020
+ res.on("aborted", () => {
31021
+ fail("the response was aborted", res.statusCode);
31022
+ });
31023
+ res.on("end", () => {
31024
+ if (settled) return;
31025
+ settled = true;
31026
+ resolve2({
31027
+ status: res.statusCode ?? 0,
31028
+ headers: res.headers,
31029
+ body: Buffer.concat(chunks).toString("utf8")
31030
+ });
31031
+ });
31032
+ });
31033
+ const deadline = setTimeout(() => {
31034
+ fail(`no response within ${String(timeoutMs)}ms`);
31035
+ req.destroy();
31036
+ }, timeoutMs);
31037
+ deadline.unref();
31038
+ req.on("upgrade", (_res, socket) => {
31039
+ fail("the deployment answered with a protocol upgrade");
31040
+ socket.destroy();
31041
+ });
31042
+ req.on("close", () => {
31043
+ fail("the connection closed before a response was read");
31044
+ clearTimeout(deadline);
31045
+ });
31046
+ req.on("error", (err) => {
31047
+ fail(err.message);
31048
+ });
31049
+ if (options.body !== void 0) req.write(options.body);
31050
+ req.end();
31051
+ });
31052
+ }
31053
+
31054
+ // ../../packages/remote/src/client.ts
31055
+ var ROUTES = {
31056
+ events: "/v1/events",
31057
+ auditEvents: "/v1/audit-events",
31058
+ inventory: "/v1/inventory",
31059
+ storePosture: "/v1/store-posture",
31060
+ policyBundle: "/v1/policy-bundle",
31061
+ whoami: "/v1/plugin/whoami"
31062
+ };
31063
+ function headerValue(response, name) {
31064
+ const raw = response.headers[name];
31065
+ if (raw === void 0) return void 0;
31066
+ return Array.isArray(raw) ? raw[0] : raw;
31067
+ }
31068
+ function okBody(response) {
31069
+ if (response.status < 200 || response.status >= 300) {
31070
+ throw new RemoteRequestError(response.status);
31071
+ }
31072
+ return response.body;
31073
+ }
31074
+ function parsed(schema, body, route) {
31075
+ let json2;
31076
+ try {
31077
+ json2 = JSON.parse(body);
31078
+ } catch {
31079
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
31080
+ }
31081
+ const result = schema.safeParse(json2);
31082
+ if (!result.success) {
31083
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
31084
+ }
31085
+ return result.data;
31086
+ }
31087
+ function withoutTrailingSlashes(endpoint) {
31088
+ let end = endpoint.length;
31089
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
31090
+ return endpoint.slice(0, end);
31091
+ }
31092
+ var SLASH = "/".charCodeAt(0);
31093
+ function createRemoteClient(options) {
31094
+ const base = withoutTrailingSlashes(options.endpoint);
31095
+ const url2 = (route) => `${base}${route}`;
31096
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
31097
+ return {
31098
+ async ingestEvents(batch) {
31099
+ const response = await send({
31100
+ ...common,
31101
+ method: "POST",
31102
+ url: url2(ROUTES.events),
31103
+ body: JSON.stringify(batch)
31104
+ });
31105
+ return parsed(IngestAck, okBody(response), ROUTES.events);
31106
+ },
31107
+ async ingestInventory(context) {
31108
+ const response = await send({
31109
+ ...common,
31110
+ method: "POST",
31111
+ url: url2(ROUTES.inventory),
31112
+ body: JSON.stringify(context)
31113
+ });
31114
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
31115
+ },
31116
+ async recordAuditEvent(event) {
31117
+ const validated = RecordAuditEventRequest.safeParse(event);
31118
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
31119
+ const submission = validated.data;
31120
+ const response = await send({
31121
+ ...common,
31122
+ method: "POST",
31123
+ url: url2(ROUTES.auditEvents),
31124
+ body: JSON.stringify(submission)
31125
+ });
31126
+ okBody(response);
31127
+ },
31128
+ async reportStorePosture(snapshot) {
31129
+ const response = await send({
31130
+ ...common,
31131
+ method: "POST",
31132
+ url: url2(ROUTES.storePosture),
31133
+ body: JSON.stringify(snapshot)
31134
+ });
31135
+ okBody(response);
31136
+ },
31137
+ async getPolicyBundle(etag) {
31138
+ const response = await send({
31139
+ ...common,
31140
+ method: "GET",
31141
+ url: url2(ROUTES.policyBundle),
31142
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
31143
+ });
31144
+ if (response.status === 304) {
31145
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
31146
+ }
31147
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
31148
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
31149
+ },
31150
+ async whoami() {
31151
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
31152
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
31153
+ }
31154
+ };
31155
+ }
31156
+
31157
+ // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
31158
+ var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
31159
+ function createPostureReporter(deps) {
31160
+ async function prepare() {
31161
+ try {
31162
+ const state = await withTimeout(deps.store.read(), REQUEST_TIMEOUT_MS);
31163
+ if (state === null) return null;
31164
+ const nowMs = deps.now();
31165
+ const elapsed = nowMs - state.lastAttemptedAtMs;
31166
+ if (elapsed >= 0 && elapsed < POSTURE_REPORT_INTERVAL_MS) return null;
31167
+ try {
31168
+ await withTimeout(deps.store.markAttempted(state.deviceId, nowMs), REQUEST_TIMEOUT_MS);
31169
+ } catch {
31170
+ }
31171
+ const { readError, ...measurement } = deps.readStore();
31172
+ if (readError) return null;
31173
+ let plugin;
31174
+ try {
31175
+ plugin = await deps.pluginBlock?.();
31176
+ } catch {
31177
+ plugin = void 0;
31178
+ }
31179
+ return {
31180
+ deviceId: state.deviceId,
31181
+ hostname: deps.hostname(),
31182
+ capturedAt: nowMs,
31183
+ ...measurement,
31184
+ // Omit the key rather than spread an explicit `undefined` —
31185
+ // exactOptionalPropertyTypes distinguishes the two, and the bridge in
31186
+ // factory.ts keys on presence.
31187
+ ...plugin === void 0 ? {} : { plugin }
31188
+ };
31189
+ } catch {
31190
+ return null;
31191
+ }
31192
+ }
31193
+ async function send2(snapshot) {
31194
+ try {
31195
+ await deps.report(snapshot);
31196
+ } catch {
31197
+ }
31198
+ }
31199
+ return { prepare, send: send2 };
31200
+ }
31201
+
31202
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31203
+ import { statSync as statSync9 } from "fs";
31204
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
31205
+
31206
+ // ../../packages/plugin-runtime/src/attached/action-counts.ts
31207
+ function emptyActionCounts() {
31208
+ return Object.fromEntries(ACTION_TAKEN_KEYS.map((a) => [a, 0]));
31209
+ }
31210
+ function isActionTaken(value) {
31211
+ return ACTION_TAKEN_KEYS.includes(value);
31212
+ }
31213
+
31214
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31215
+ var CAPTURE_EVENT_TYPES_SQL2 = `('prompt','response','code_change','tool_use')`;
31216
+ function isSchemaAbsent(err) {
31217
+ return err instanceof Error && /no such table/i.test(err.message);
31218
+ }
31219
+ function emptyReadout(readError = false) {
31220
+ const byAction = emptyActionCounts();
31221
+ return {
31222
+ storePresent: false,
31223
+ schemaVersion: null,
31224
+ findingsTotal: 0,
31225
+ findingsFirstAt: null,
31226
+ findingsLastAt: null,
31227
+ packs: [],
31228
+ policyCounts: { total: 0, disabled: 0, byAction },
31229
+ readError
31230
+ };
31231
+ }
31232
+ function readStorePosture(dbPath2) {
31233
+ try {
31234
+ statSync9(dbPath2);
31235
+ } catch (err) {
31236
+ const code = err.code;
31237
+ if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
31238
+ return emptyReadout(true);
31239
+ }
31240
+ let db = null;
31241
+ let version2 = null;
31242
+ let packs2 = [];
31243
+ let policyCounts = {
31244
+ total: 0,
31245
+ disabled: 0,
31246
+ byAction: emptyActionCounts()
31247
+ };
31248
+ let findingsTotal = 0;
31249
+ let findingsFirstAt = null;
31250
+ let findingsLastAt = null;
31251
+ const currentReadout = () => ({
31252
+ storePresent: true,
31253
+ schemaVersion: version2,
31254
+ findingsTotal,
31255
+ findingsFirstAt,
31256
+ findingsLastAt,
31257
+ packs: packs2,
31258
+ policyCounts,
31259
+ readError: false
31260
+ });
31261
+ try {
31262
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
31263
+ db.exec("PRAGMA busy_timeout = 2000");
31264
+ version2 = db.prepare("PRAGMA user_version").get().user_version;
31265
+ try {
31266
+ const packRows = db.prepare(
31267
+ `SELECT namespace, pack_id, version, enabled, updated_at FROM installed_packs ORDER BY namespace, pack_id`
31268
+ ).all();
31269
+ packs2 = packRows.map((r) => ({
31270
+ packId: `${r.namespace}/${r.pack_id}`,
31271
+ version: r.version,
31272
+ enabled: r.enabled !== 0,
31273
+ updatedAt: r.updated_at == null ? null : String(r.updated_at)
31274
+ }));
31275
+ } catch (err) {
31276
+ if (!isSchemaAbsent(err)) throw err;
31277
+ }
31278
+ try {
31279
+ const policyRows = db.prepare(`SELECT action, enabled FROM policies`).all();
31280
+ const byAction = emptyActionCounts();
31281
+ let disabled = 0;
31282
+ for (const row of policyRows) {
31283
+ if (row.enabled === 0) disabled += 1;
31284
+ if (isActionTaken(row.action)) byAction[row.action] += 1;
31285
+ }
31286
+ policyCounts = { total: policyRows.length, disabled, byAction };
31287
+ } catch (err) {
31288
+ if (!isSchemaAbsent(err)) throw err;
31289
+ }
31290
+ try {
31291
+ const agg = db.prepare(
31292
+ `SELECT count(*) AS n, min(f.first_detected_at) AS firstAt, max(f.first_detected_at) AS lastAt
31293
+ FROM inspection_findings f JOIN audit_events e ON e.id = f.audit_event_id
31294
+ WHERE e.event_type IN ${CAPTURE_EVENT_TYPES_SQL2}`
31295
+ ).get();
31296
+ findingsTotal = agg.n;
31297
+ findingsFirstAt = agg.firstAt;
31298
+ findingsLastAt = agg.lastAt;
31299
+ } catch (err) {
31300
+ if (!isSchemaAbsent(err)) throw err;
31301
+ }
31302
+ return currentReadout();
31303
+ } catch {
31304
+ return emptyReadout(true);
31305
+ } finally {
31306
+ try {
31307
+ db?.close();
31308
+ } catch {
31309
+ }
31310
+ }
31311
+ }
31312
+
31313
+ // ../../packages/plugin-runtime/src/attached/posture-store.ts
31314
+ import { randomUUID as randomUUID17 } from "crypto";
31315
+ import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
31316
+ import { join as join20 } from "path";
31317
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
31318
+ function createPostureStore(dir = settingsDir(), legacyDir) {
31319
+ const file2 = join20(dir, "posture-state.json");
31320
+ const legacyFile = legacyDir === void 0 ? null : join20(legacyDir, "posture-state.json");
31321
+ async function persist(state) {
31322
+ await ensureDataDir(dir);
31323
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
31324
+ try {
31325
+ await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
31326
+ await publishByRename(tmp, file2);
31327
+ } catch (err) {
31328
+ await rm2(tmp, { force: true }).catch(() => void 0);
31329
+ throw err;
31330
+ }
31331
+ }
31332
+ async function readFrom(path) {
31333
+ let raw;
31334
+ try {
31335
+ raw = await readFile3(path, "utf8");
31336
+ } catch (err) {
31337
+ const code = err.code;
31338
+ if (code === "ENOENT" || code === "ENOTDIR") return null;
31339
+ throw err;
31340
+ }
31341
+ try {
31342
+ const parsed2 = JSON.parse(raw);
31343
+ if (typeof parsed2 === "object" && parsed2 !== null) {
31344
+ const record2 = parsed2;
31345
+ if (typeof record2.deviceId === "string" && UUID_RE.test(record2.deviceId)) {
31346
+ const stamp = typeof record2.lastAttemptedAtMs === "number" ? record2.lastAttemptedAtMs : typeof record2.lastReportedAtMs === "number" ? record2.lastReportedAtMs : 0;
31347
+ return { deviceId: record2.deviceId, lastAttemptedAtMs: stamp };
31348
+ }
31349
+ }
31350
+ } catch {
31351
+ }
31352
+ return null;
31353
+ }
31354
+ async function read() {
31355
+ const current = await readFrom(file2);
31356
+ if (current) return current;
31357
+ const legacy = legacyFile === null || legacyFile === file2 ? null : await readFrom(legacyFile).catch(() => null);
31358
+ if (legacy) {
31359
+ try {
31360
+ await persist(legacy);
31361
+ } catch {
31362
+ }
31363
+ return legacy;
31364
+ }
31365
+ const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
31366
+ try {
31367
+ await ensureDataDir(dir);
31368
+ if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
31369
+ } catch {
31370
+ return null;
31371
+ }
31372
+ const winner = await readFrom(file2).catch(() => null);
31373
+ if (winner) return winner;
31374
+ try {
31375
+ await persist(fresh);
31376
+ } catch {
31377
+ return null;
31378
+ }
31379
+ return fresh;
31380
+ }
31381
+ async function markAttempted(deviceId, atMs) {
31382
+ await persist({ deviceId, lastAttemptedAtMs: atMs });
31383
+ }
31384
+ return { read, markAttempted, file: file2 };
31385
+ }
31386
+
31387
+ // ../../packages/plugin-runtime/src/attached/sync-state.ts
31388
+ import { readFileSync as readFileSync13 } from "fs";
31389
+ import { join as join21 } from "path";
31390
+
31391
+ // ../../packages/plugin-runtime/src/attached/status.ts
31392
+ var REFUSAL_LINES = {
31393
+ unauthorized: "KEY REJECTED \u2014 re-attach with a valid plugin key",
31394
+ forbidden: "ACCESS REFUSED \u2014 key is valid but not permitted; ask your org admin"
31395
+ };
31396
+ var OUTCOME_LINES = {
31397
+ ok: "policy synced",
31398
+ "not-modified": "policy up to date",
31399
+ unauthorized: REFUSAL_LINES.unauthorized,
31400
+ forbidden: REFUSAL_LINES.forbidden,
31401
+ unreachable: "control plane unreachable at last attempt",
31402
+ "invalid-bundle": "control plane sent a policy bundle this build cannot read"
31403
+ };
31404
+
31405
+ // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
31406
+ import { spawn } from "child_process";
31407
+ import { fileURLToPath as fileURLToPath2 } from "url";
31408
+ var SYNC_MARKER_NAME = "sync-last-attempt";
31409
+ var SYNC_SCRIPT_NAME = "sync.js";
31410
+ var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
31411
+ function triggerPolicySync(config2, deps = {}) {
31412
+ try {
31413
+ if (!isAttached(config2.settings)) return;
31414
+ const connection = config2.settings.controlPlane;
31415
+ if (connection === void 0) return;
31416
+ if (!readControlPlaneCredentialState(config2.settingsDir, connection).usable) return;
31417
+ const isThrottled = deps.isThrottled ?? ((dir) => throttled(dir, SYNC_MARKER_NAME, SYNC_THROTTLE_MS));
31418
+ if (isThrottled(config2.dataDir)) return;
31419
+ const scriptPath = fileURLToPath2(deps.scriptUrl ?? new URL(SYNC_SCRIPT_NAME, import.meta.url));
31420
+ (deps.spawnChild ?? spawnDetached)(scriptPath);
31421
+ } catch {
31422
+ }
31423
+ }
31424
+ function spawnDetached(scriptPath) {
31425
+ const child = spawn(process.execPath, [scriptPath], { detached: true, stdio: "ignore" });
31426
+ child.on("error", () => {
31427
+ });
31428
+ child.unref();
31429
+ }
31430
+
31431
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31432
+ import { hostname as hostname5 } from "os";
31433
+
31434
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
31435
+ import { randomUUID as randomUUID18 } from "crypto";
31436
+
31437
+ // ../../packages/plugin-runtime/src/recorder.ts
31438
+ var PLUGIN_RECORDER_BINARY = "plugin";
31439
+ function pluginRecordedBy(version2) {
31440
+ return `${PLUGIN_RECORDER_BINARY}@${version2}`;
31441
+ }
31442
+
31443
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
31444
+ var StandaloneDataGateway = class {
31445
+ db;
31446
+ // Kept for the fingerprint key lookup (exception.key lives beside the store).
31447
+ dataDir;
31448
+ // One notice per gateway — see warnRulesetDiscarded.
31449
+ warnedRulesetDiscarded = false;
31450
+ constructor(dataDir2, detections = [], meta3) {
31451
+ this.db = openLocalDatabase(dataDir2);
31452
+ this.dataDir = dataDir2;
31453
+ this.db.installedPacks.recordInventory(detections, meta3);
31454
+ }
31455
+ recordCapture(record2) {
29911
31456
  this.db.recordCapture(record2.event, record2.findings);
29912
31457
  return Promise.resolve();
29913
31458
  }
@@ -29931,12 +31476,12 @@ var StandaloneDataGateway = class {
29931
31476
  // reconciler drops the whole pass and recovers it idempotently on the next read.
29932
31477
  recordLlmCalls(inputs) {
29933
31478
  if (inputs.length === 0) return Promise.resolve();
29934
- return new Promise((resolve, reject) => {
31479
+ return new Promise((resolve2, reject) => {
29935
31480
  try {
29936
31481
  this.db.auditEvents.runInTransaction(() => {
29937
31482
  for (const input of inputs) this.db.auditEvents.insertLlmCall(input);
29938
31483
  });
29939
- resolve();
31484
+ resolve2();
29940
31485
  } catch (err) {
29941
31486
  reject(err instanceof Error ? err : new Error(String(err)));
29942
31487
  }
@@ -29948,12 +31493,12 @@ var StandaloneDataGateway = class {
29948
31493
  // drops the whole pass and recovers it idempotently next time.
29949
31494
  recordToolCalls(inputs) {
29950
31495
  if (inputs.length === 0) return Promise.resolve();
29951
- return new Promise((resolve, reject) => {
31496
+ return new Promise((resolve2, reject) => {
29952
31497
  try {
29953
31498
  this.db.auditEvents.runInTransaction(() => {
29954
31499
  for (const input of inputs) this.writeToolCall(input);
29955
31500
  });
29956
- resolve();
31501
+ resolve2();
29957
31502
  } catch (err) {
29958
31503
  reject(err instanceof Error ? err : new Error(String(err)));
29959
31504
  }
@@ -30095,7 +31640,7 @@ var StandaloneDataGateway = class {
30095
31640
  const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
30096
31641
  const installed = this.installedScanRules();
30097
31642
  const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
30098
- id: randomUUID15(),
31643
+ id: randomUUID18(),
30099
31644
  scope: "global",
30100
31645
  target: { ruleId },
30101
31646
  action,
@@ -30249,15 +31794,61 @@ var StandaloneDataGateway = class {
30249
31794
  }
30250
31795
  };
30251
31796
 
31797
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31798
+ function resolveGatewayForConfig(config2, meta3) {
31799
+ const local = new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
31800
+ try {
31801
+ if (!isAttached(config2.settings)) return local;
31802
+ const connection = config2.settings.controlPlane;
31803
+ if (connection === void 0) return local;
31804
+ const state = readControlPlaneCredentialState(config2.settingsDir, connection);
31805
+ if (!state.usable) return local;
31806
+ const client = createRemoteClient({
31807
+ endpoint: connection.endpoint,
31808
+ apiKey: state.credential.apiKey
31809
+ });
31810
+ const store = createPolicyStore(config2.dataDir);
31811
+ const postureStore = createPostureStore(config2.settingsDir, config2.dataDir);
31812
+ const forward = createForwardPolicy({ dir: config2.dataDir });
31813
+ return new AttachedDataGateway({
31814
+ local,
31815
+ client,
31816
+ dataDir: config2.dataDir,
31817
+ readCachedBundle: () => store.read().then((cached2) => cached2?.bundle ?? null),
31818
+ forward,
31819
+ posture: createPostureReporter({
31820
+ // THROUGH THE BREAKER, and wrapped HERE rather than around
31821
+ // `PostureReporter.send`. The reporter swallows every error by
31822
+ // contract, so a wrap outside it would hand `forward.run` a resolved
31823
+ // promise for a send that failed — recording a SUCCESS, clearing
31824
+ // `consecutiveFailures` and `lastFailure`, and telling `aka status` the
31825
+ // forward recovered when nothing did. Wrapping the raw client call puts
31826
+ // the breaker above the swallow, where it can see the truth.
31827
+ //
31828
+ // What it buys: once the breaker is open — the plane already confirmed
31829
+ // down by the gateway's own writes — this stops paying a request
31830
+ // timeout per throttle interval to re-learn it.
31831
+ report: (snapshot) => forward.run(() => client.reportStorePosture(snapshot)).then(() => void 0),
31832
+ store: postureStore,
31833
+ readStore: () => readStorePosture(config2.dbPath),
31834
+ hostname: () => hostname5(),
31835
+ now: () => Date.now()
31836
+ })
31837
+ });
31838
+ } catch {
31839
+ return local;
31840
+ }
31841
+ }
31842
+
30252
31843
  // ../../packages/plugin-runtime/src/resolve.ts
30253
- var standaloneGatewayFactory = (config2, meta3) => new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
30254
- var defaultGatewayFactory = standaloneGatewayFactory;
31844
+ var configuredGatewayFactory = (config2, meta3) => resolveGatewayForConfig(config2, meta3);
31845
+ var defaultGatewayFactory = configuredGatewayFactory;
30255
31846
  function resolveDataGateway(config2, meta3, gatewayFactory = defaultGatewayFactory) {
30256
31847
  return gatewayFactory(config2, meta3);
30257
31848
  }
30258
31849
 
30259
31850
  // ../../packages/plugin-runtime/src/handle-session-start.ts
30260
- import { randomUUID as randomUUID16 } from "crypto";
31851
+ import { randomUUID as randomUUID19 } from "crypto";
30261
31852
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
30262
31853
  async function handleSessionStart(input, config2 = loadConfig()) {
30263
31854
  const silent = { staleBinaryNotice: null };
@@ -30321,6 +31912,7 @@ async function handleSessionStart(input, config2 = loadConfig()) {
30321
31912
  } catch {
30322
31913
  }
30323
31914
  }
31915
+ triggerPolicySync(config2);
30324
31916
  if (input.harnessVersion !== void 0 && offersMaintenance(gateway, "staleBinaryNotice")) {
30325
31917
  return { staleBinaryNotice: gateway.staleBinaryNotice(input.harnessVersion) };
30326
31918
  }
@@ -30346,7 +31938,7 @@ async function recordConfigInventory(gateway, sessionId, cwd, homeDir) {
30346
31938
  }
30347
31939
  function buildConfigScanEvent(sessionId, scan2) {
30348
31940
  return {
30349
- id: randomUUID16(),
31941
+ id: randomUUID19(),
30350
31942
  eventType: "config_scan",
30351
31943
  startedAt: scan2.scannedAt,
30352
31944
  parentId: sessionId,
@@ -30395,9 +31987,9 @@ function buildSessionRoot(sessionId, input, ctx, resolved, provider, branch) {
30395
31987
  }
30396
31988
 
30397
31989
  // src/history/reconcile-trigger.ts
30398
- import { spawn } from "child_process";
30399
- import { dirname as dirname4, join as join16 } from "path";
30400
- import { fileURLToPath as fileURLToPath2 } from "url";
31990
+ import { spawn as spawn2 } from "child_process";
31991
+ import { dirname as dirname5, join as join23 } from "path";
31992
+ import { fileURLToPath as fileURLToPath3 } from "url";
30401
31993
 
30402
31994
  // src/history/tail.ts
30403
31995
  import { createHash as createHash5 } from "crypto";
@@ -30406,11 +31998,11 @@ import {
30406
31998
  fstatSync,
30407
31999
  mkdirSync as mkdirSync4,
30408
32000
  openSync as openSync2,
30409
- readFileSync as readFileSync10,
32001
+ readFileSync as readFileSync14,
30410
32002
  readSync,
30411
32003
  writeFileSync as writeFileSync7
30412
32004
  } from "fs";
30413
- import { join as join15 } from "path";
32005
+ import { join as join22 } from "path";
30414
32006
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
30415
32007
  function safeSessionId(sessionId) {
30416
32008
  if (SAFE_SESSION_ID.test(sessionId) && sessionId !== "." && sessionId !== "..") {
@@ -30426,8 +32018,8 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
30426
32018
  try {
30427
32019
  const marker = `${RECONCILE_MARKER_PREFIX}-${safeSessionId(sessionId)}`;
30428
32020
  if (throttled(dataDir2, marker, RECONCILE_THROTTLE_MS)) return;
30429
- const here = dirname4(fileURLToPath2(import.meta.url));
30430
- const child = spawn(process.execPath, [join16(here, "reconcile.js"), sessionId, transcriptPath], {
32021
+ const here = dirname5(fileURLToPath3(import.meta.url));
32022
+ const child = spawn2(process.execPath, [join23(here, "reconcile.js"), sessionId, transcriptPath], {
30431
32023
  detached: true,
30432
32024
  stdio: "ignore"
30433
32025
  });
@@ -30439,7 +32031,7 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
30439
32031
  // src/hooks/shared.ts
30440
32032
  var WATCHDOG_MS = 8e3;
30441
32033
  async function readStdin() {
30442
- return new Promise((resolve) => {
32034
+ return new Promise((resolve2) => {
30443
32035
  let data = "";
30444
32036
  let settled = false;
30445
32037
  const finish = () => {
@@ -30448,7 +32040,7 @@ async function readStdin() {
30448
32040
  clearTimeout(timer);
30449
32041
  process.stdin.removeListener("data", onData);
30450
32042
  process.stdin.removeListener("end", finish);
30451
- resolve(data);
32043
+ resolve2(data);
30452
32044
  };
30453
32045
  const onData = (chunk) => {
30454
32046
  data += chunk;
@@ -30462,8 +32054,8 @@ async function readStdin() {
30462
32054
  }
30463
32055
  function parseJson(raw) {
30464
32056
  try {
30465
- const parsed = JSON.parse(raw);
30466
- return typeof parsed === "object" && parsed !== null ? parsed : null;
32057
+ const parsed2 = JSON.parse(raw);
32058
+ return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
30467
32059
  } catch {
30468
32060
  return null;
30469
32061
  }
@@ -30481,12 +32073,12 @@ function primaryWorkspacePath(input) {
30481
32073
  return void 0;
30482
32074
  }
30483
32075
  function emit(output) {
30484
- return new Promise((resolve) => {
32076
+ return new Promise((resolve2) => {
30485
32077
  let settled = false;
30486
32078
  const finish = () => {
30487
32079
  if (settled) return;
30488
32080
  settled = true;
30489
- resolve();
32081
+ resolve2();
30490
32082
  };
30491
32083
  process.stdout.on("error", finish);
30492
32084
  process.stdout.write(JSON.stringify(output), finish);
@@ -30498,9 +32090,9 @@ async function runHookFailOpen(main2, failOpen, watchdogMs = WATCHDOG_MS) {
30498
32090
  try {
30499
32091
  const decided = await Promise.race([
30500
32092
  main2(),
30501
- new Promise((resolve) => {
32093
+ new Promise((resolve2) => {
30502
32094
  watchdog = setTimeout(() => {
30503
- resolve(void 0);
32095
+ resolve2(void 0);
30504
32096
  }, watchdogMs);
30505
32097
  })
30506
32098
  ]);
@@ -30516,13 +32108,72 @@ async function runHookFailOpen(main2, failOpen, watchdogMs = WATCHDOG_MS) {
30516
32108
  process.exit(0);
30517
32109
  }
30518
32110
 
32111
+ // src/hooks/store-health.ts
32112
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync15, writeFileSync as writeFileSync8 } from "fs";
32113
+ import { dirname as dirname6, join as join24 } from "path";
32114
+ var STORE_REDIRECT_MARKER = "store-redirect-last-session";
32115
+ function markerDirs(dataDir2) {
32116
+ return [dataDir2, dirname6(dataDir2)];
32117
+ }
32118
+ function alreadyClaimed(dirs, marker, sessionId) {
32119
+ return dirs.some((dir) => {
32120
+ try {
32121
+ return readFileSync15(join24(dir, marker), "utf8") === sessionId;
32122
+ } catch {
32123
+ return false;
32124
+ }
32125
+ });
32126
+ }
32127
+ function recordClaim(dirs, marker, sessionId) {
32128
+ for (const dir of dirs) {
32129
+ try {
32130
+ mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
32131
+ writeFileSync8(join24(dir, marker), sessionId, { mode: DATA_FILE_MODE });
32132
+ return;
32133
+ } catch {
32134
+ }
32135
+ }
32136
+ }
32137
+ function storeRedirectedMessage(paths, platform2 = process.platform) {
32138
+ const where = paths.map(({ path, target, holds, missing, mode }) => {
32139
+ if (missing) return `${path} -> ${target} (which does not exist; ${holds} cannot land there)`;
32140
+ const loose = mode !== void 0 && (mode & 63) !== 0 ? ", NOT owner-only" : "";
32141
+ const inherited = mode === void 0 ? "" : ` (${formatMode(mode)}${loose})`;
32142
+ return `${path} -> ${target}${inherited}, holding ${holds}`;
32143
+ }).join("; ");
32144
+ const subject = paths.length === 1 ? "a store path is a symlink" : `${String(paths.length)} store paths are symlinks`;
32145
+ const anyResolves = paths.some(({ missing }) => !missing);
32146
+ const lead = anyResolves ? `${subject}, so AKA is writing into the target instead: ${where}. ` : `${subject} resolving nowhere, so AKA cannot write there: ${where}. `;
32147
+ const kept = anyResolves && platform2 !== "win32" ? "Permissions are never changed through a symlink, so the store keeps whatever the target already had. " : "";
32148
+ return `[aka] ${lead}${kept}If you did not create that link, treat it as untrusted and run \`aka init\` for the full report.
32149
+ `;
32150
+ }
32151
+ function formatMode(mode) {
32152
+ return `0${mode.toString(8).padStart(3, "0")}`;
32153
+ }
32154
+ function warnIfStoreRedirected(config2, sessionId, write = (message2) => void process.stderr.write(message2)) {
32155
+ try {
32156
+ const paths = symlinkedStorePaths(dirname6(config2.dataDir));
32157
+ if (paths.length === 0) return;
32158
+ if (!sessionId) {
32159
+ write(storeRedirectedMessage(paths));
32160
+ return;
32161
+ }
32162
+ const dirs = markerDirs(config2.dataDir);
32163
+ if (alreadyClaimed(dirs, STORE_REDIRECT_MARKER, sessionId)) return;
32164
+ write(storeRedirectedMessage(paths));
32165
+ recordClaim(dirs, STORE_REDIRECT_MARKER, sessionId);
32166
+ } catch {
32167
+ }
32168
+ }
32169
+
30519
32170
  // src/hooks/pre-invocation.ts
30520
32171
  var CARRY_ON = {};
30521
32172
  function harnessVersion() {
30522
32173
  const manifestPath = process.argv[2];
30523
32174
  if (!manifestPath) return void 0;
30524
32175
  try {
30525
- const manifest = JSON.parse(readFileSync11(manifestPath, "utf8"));
32176
+ const manifest = JSON.parse(readFileSync16(manifestPath, "utf8"));
30526
32177
  return typeof manifest.version === "string" ? manifest.version : void 0;
30527
32178
  } catch {
30528
32179
  return void 0;
@@ -30534,6 +32185,7 @@ async function main() {
30534
32185
  const cwd = (input ? primaryWorkspacePath(input) : void 0) ?? process.cwd();
30535
32186
  const transcriptPath = input ? getString(input, "transcriptPath") : void 0;
30536
32187
  const config2 = loadConfig(void 0, resolveAntigravityProvider);
32188
+ warnIfStoreRedirected(config2, sessionId);
30537
32189
  const result = await handleSessionStart(
30538
32190
  {
30539
32191
  sessionId,