@agenttrail/cli 0.2.12 → 0.2.26

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.
@@ -219,8 +219,8 @@ var require_constants = __commonJS({
219
219
  /**
220
220
  * Create GLOB_CHARS
221
221
  */
222
- globChars(win32) {
223
- return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
222
+ globChars(win322) {
223
+ return win322 === true ? WINDOWS_CHARS : POSIX_CHARS;
224
224
  }
225
225
  };
226
226
  }
@@ -1775,6 +1775,7 @@ var require_picomatch2 = __commonJS({
1775
1775
  });
1776
1776
 
1777
1777
  // src/pep/hook-shim.ts
1778
+ import { statSync as statSync2 } from "fs";
1778
1779
  import { homedir as homedir2 } from "os";
1779
1780
 
1780
1781
  // ../shared/src/policy-evaluate.ts
@@ -1816,7 +1817,16 @@ function buildEvaluationContext(request, orgId) {
1816
1817
  // ../policy-engine/src/matchers.ts
1817
1818
  var import_picomatch = __toESM(require_picomatch2(), 1);
1818
1819
  var DETAIL_ATTR = "detail";
1820
+ var MCP_INPUT_ATTR = "mcp_input";
1819
1821
  var FILE_PATH_ATTR = "file_path";
1822
+ function effectiveChannel(condition) {
1823
+ if (condition.channel !== void 0) return condition.channel;
1824
+ return condition.label?.toLowerCase().startsWith("mcp__") === true ? "content" : "command";
1825
+ }
1826
+ function channelText(span, channel) {
1827
+ if (channel === "content") return span.attributes[MCP_INPUT_ATTR] ?? span.attributes[DETAIL_ATTR];
1828
+ return span.attributes[DETAIL_ATTR];
1829
+ }
1820
1830
  var FILE_GLOB_OPTIONS = { dot: true, nocase: true };
1821
1831
  var LABEL_GLOB_OPTIONS = { dot: true, nocase: true };
1822
1832
  function matchKind(conditionKind, span) {
@@ -1833,8 +1843,8 @@ function matchLabel(conditionLabel, span) {
1833
1843
  reason: matched ? `label: "${conditionLabel}" matched` : `label: expected "${conditionLabel}", got "${span.label}"`
1834
1844
  };
1835
1845
  }
1836
- function matchDetailContains(requiredSubstrings, span) {
1837
- const detail = span.attributes[DETAIL_ATTR];
1846
+ function matchDetailContains(requiredSubstrings, span, channel = "command") {
1847
+ const detail = channelText(span, channel);
1838
1848
  if (detail === void 0) {
1839
1849
  return { matched: false, reason: "detail_contains: detail attribute missing" };
1840
1850
  }
@@ -1855,8 +1865,8 @@ function matchDetailContains(requiredSubstrings, span) {
1855
1865
  reason: `detail_contains: all ${requiredSubstrings.length} substring(s) found`
1856
1866
  };
1857
1867
  }
1858
- function matchDetailMatches(patterns, span) {
1859
- const detail = span.attributes[DETAIL_ATTR];
1868
+ function matchDetailMatches(patterns, span, channel = "command") {
1869
+ const detail = channelText(span, channel);
1860
1870
  if (detail === void 0) {
1861
1871
  return { matched: false, reason: "detail_matches: detail attribute missing" };
1862
1872
  }
@@ -1944,7 +1954,7 @@ function createCompiledLabelMatcher(pattern) {
1944
1954
  compiledLabelCache.set(pattern, matcher);
1945
1955
  }
1946
1956
  const cached = matcher;
1947
- return (label2) => cached(label2);
1957
+ return (label4) => cached(label4);
1948
1958
  }
1949
1959
  function createCompiledDetailMatcher(pattern) {
1950
1960
  let compiled = compiledDetailCache.get(pattern);
@@ -2029,14 +2039,22 @@ function evaluateConditionCompiled(condition, span, compiledGlobMatcher) {
2029
2039
  reasons.push(labelResult.reason);
2030
2040
  }
2031
2041
  if (condition.detail_contains !== void 0) {
2032
- const detailResult = matchDetailContains(condition.detail_contains, span);
2042
+ const detailResult = matchDetailContains(
2043
+ condition.detail_contains,
2044
+ span,
2045
+ effectiveChannel(condition)
2046
+ );
2033
2047
  if (!detailResult.matched) {
2034
2048
  return detailResult;
2035
2049
  }
2036
2050
  reasons.push(detailResult.reason);
2037
2051
  }
2038
2052
  if (condition.detail_matches !== void 0) {
2039
- const regexResult = matchDetailMatches(condition.detail_matches, span);
2053
+ const regexResult = matchDetailMatches(
2054
+ condition.detail_matches,
2055
+ span,
2056
+ effectiveChannel(condition)
2057
+ );
2040
2058
  if (!regexResult.matched) {
2041
2059
  return regexResult;
2042
2060
  }
@@ -2234,6 +2252,21 @@ var nodeCaptureFileIO = {
2234
2252
  }
2235
2253
  };
2236
2254
 
2255
+ // ../shared/src/types/agent-vendor.ts
2256
+ var AGENT_VENDORS = [
2257
+ "claude-code",
2258
+ "cursor",
2259
+ "codex",
2260
+ "replit-agent",
2261
+ "devin",
2262
+ "aider",
2263
+ "windsurf",
2264
+ "github-copilot"
2265
+ ];
2266
+ function isAgentVendor(value) {
2267
+ return typeof value === "string" && AGENT_VENDORS.includes(value);
2268
+ }
2269
+
2237
2270
  // ../shared/src/agent-attributes.ts
2238
2271
  var TOOL_VENDOR_NAME_MAX_LENGTH = 255;
2239
2272
 
@@ -2541,6 +2574,7 @@ var ENV_PEP_SNAPSHOT_PATH = "AGENTTRAIL_PEP_SNAPSHOT_PATH";
2541
2574
  var ENV_OTEL_RESOURCE_ATTRIBUTES = "OTEL_RESOURCE_ATTRIBUTES";
2542
2575
  var RESOURCE_KEY_AGENT_ID = "agenttrail.agent.id";
2543
2576
  var RESOURCE_KEY_PROJECT_ID = "agenttrail.project.id";
2577
+ var RESOURCE_KEY_ORG_ID = "agenttrail.org.id";
2544
2578
  var DEFAULT_PEP_TIMEOUT_MS = 3e3;
2545
2579
  var PEP_WATCHDOG_MS = 6e3;
2546
2580
  var PEP_HOLD_FETCH_TIMEOUT_MS = 595e3;
@@ -2550,8 +2584,11 @@ var UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$
2550
2584
  function scopeId(value) {
2551
2585
  return value !== void 0 && UUID_SHAPE.test(value) && value !== NIL_ORG_ID ? value : void 0;
2552
2586
  }
2553
- function parseResourceScope(raw) {
2554
- if (!raw) return void 0;
2587
+ function canonicalOrgId(value) {
2588
+ const lower = value?.trim().toLowerCase();
2589
+ return lower !== void 0 && UUID_SHAPE.test(lower) && lower !== NIL_ORG_ID ? lower : void 0;
2590
+ }
2591
+ function resourceValues(raw) {
2555
2592
  const values = /* @__PURE__ */ new Map();
2556
2593
  for (const entry of raw.split(",")) {
2557
2594
  const eq = entry.indexOf("=");
@@ -2563,6 +2600,15 @@ function parseResourceScope(raw) {
2563
2600
  } catch {
2564
2601
  }
2565
2602
  }
2603
+ return values;
2604
+ }
2605
+ function parseResourceOrgId(raw) {
2606
+ if (!raw) return void 0;
2607
+ return canonicalOrgId(resourceValues(raw).get(RESOURCE_KEY_ORG_ID));
2608
+ }
2609
+ function parseResourceScope(raw) {
2610
+ if (!raw) return void 0;
2611
+ const values = resourceValues(raw);
2566
2612
  const agentId = scopeId(values.get(RESOURCE_KEY_AGENT_ID));
2567
2613
  const projectId = scopeId(values.get(RESOURCE_KEY_PROJECT_ID));
2568
2614
  if (agentId === void 0 && projectId === void 0) return void 0;
@@ -2591,7 +2637,8 @@ function resolvePepConfig(env) {
2591
2637
  timeoutMs,
2592
2638
  orgId: nonEmpty2(env[ENV_PEP_ORG_ID]),
2593
2639
  snapshotPath: nonEmpty2(env[ENV_PEP_SNAPSHOT_PATH]) ?? snapshotCachePath(),
2594
- scope: parseResourceScope(env[ENV_OTEL_RESOURCE_ATTRIBUTES])
2640
+ scope: parseResourceScope(env[ENV_OTEL_RESOURCE_ATTRIBUTES]),
2641
+ outcomeOrgId: canonicalOrgId(env[ENV_PEP_ORG_ID]) ?? parseResourceOrgId(env[ENV_OTEL_RESOURCE_ATTRIBUTES])
2595
2642
  };
2596
2643
  }
2597
2644
  function pdpEvaluateUrl(apiBase) {
@@ -2855,9 +2902,9 @@ function resolveWorkspacePath(path, realpath = realpathSync2.native) {
2855
2902
  function lookupCursorWorkspace(query) {
2856
2903
  const read = readRegistry(query.home, query.io ?? nodeCaptureFileIO);
2857
2904
  if (read.kind !== "ok") return { kind: "registry-unreadable", reason: read.kind };
2858
- const resolve3 = (path) => resolveWorkspacePath(path, query.realpath);
2859
- const roots = query.workspaceRoots.filter((path) => path !== "").map(resolve3);
2860
- const projectDir = query.projectDirEnv === void 0 ? void 0 : resolve3(query.projectDirEnv);
2905
+ const resolve4 = (path) => resolveWorkspacePath(path, query.realpath);
2906
+ const roots = query.workspaceRoots.filter((path) => path !== "").map(resolve4);
2907
+ const projectDir = query.projectDirEnv === void 0 ? void 0 : resolve4(query.projectDirEnv);
2861
2908
  const record = findProjectForWorkspace2(read.registry, roots, projectDir);
2862
2909
  if (record === void 0) {
2863
2910
  const damaged = skippedRecordsForWorkspace(read.skipped, roots, projectDir);
@@ -2966,11 +3013,20 @@ function createRealCursorEmitter() {
2966
3013
  // src/pep/pdp-client.ts
2967
3014
  import { readFileSync as readFileSync4 } from "fs";
2968
3015
  var PdpUnreachableError = class extends Error {
2969
- constructor(reason) {
3016
+ kind;
3017
+ constructor(reason, kind = "unreachable") {
2970
3018
  super(`PDP unreachable: ${reason}`);
2971
3019
  this.name = "PdpUnreachableError";
3020
+ this.kind = kind;
2972
3021
  }
2973
3022
  };
3023
+ function statusKind(status) {
3024
+ if (status === 401) return "unauthorized";
3025
+ if (status === 403) return "waf_403";
3026
+ if (status === 503) return "config_unavailable";
3027
+ if (status >= 500) return "evaluator_crash";
3028
+ return "rejected_request";
3029
+ }
2974
3030
  var API_TIER_REFUSAL_MESSAGE = /^This feature requires the (Pro|Team|Business|Enterprise) plan or higher\.$/;
2975
3031
  async function isApiTierRefusal(res) {
2976
3032
  let body;
@@ -2987,7 +3043,8 @@ async function isApiTierRefusal(res) {
2987
3043
  }
2988
3044
  function foreign403(what) {
2989
3045
  return new PdpUnreachableError(
2990
- `${what} 403 did not come from the AgentTrail API (no tier-refusal body) \u2014 most likely a gateway/WAF block; failing closed`
3046
+ `${what} 403 did not come from the AgentTrail API (no tier-refusal body) \u2014 most likely a gateway/WAF block; failing closed`,
3047
+ "waf_403"
2991
3048
  );
2992
3049
  }
2993
3050
  async function boundedFetch(fetchFn, url, init, timeoutMs) {
@@ -2997,7 +3054,7 @@ async function boundedFetch(fetchFn, url, init, timeoutMs) {
2997
3054
  return await fetchFn(url, { ...init, signal: controller.signal });
2998
3055
  } catch (err) {
2999
3056
  const msg = err instanceof Error ? err.message : String(err);
3000
- throw new PdpUnreachableError(msg);
3057
+ throw new PdpUnreachableError(msg, controller.signal.aborted ? "timeout" : "unreachable");
3001
3058
  } finally {
3002
3059
  clearTimeout(timer);
3003
3060
  }
@@ -3021,10 +3078,10 @@ async function evaluateViaPdp(args, fetchFn) {
3021
3078
  try {
3022
3079
  parsed = await res.json();
3023
3080
  } catch {
3024
- throw new PdpUnreachableError("200 with unparseable JSON body");
3081
+ throw new PdpUnreachableError("200 with unparseable JSON body", "parse_error");
3025
3082
  }
3026
3083
  if (!isEvaluateResponse(parsed)) {
3027
- throw new PdpUnreachableError("200 with malformed PolicyEvaluateResponse");
3084
+ throw new PdpUnreachableError("200 with malformed PolicyEvaluateResponse", "parse_error");
3028
3085
  }
3029
3086
  return { kind: "ok", response: parsed };
3030
3087
  }
@@ -3033,7 +3090,7 @@ async function evaluateViaPdp(args, fetchFn) {
3033
3090
  throw foreign403("evaluate");
3034
3091
  }
3035
3092
  if (res.status === 401) return { kind: "unauthorized" };
3036
- throw new PdpUnreachableError(`unexpected status ${res.status}`);
3093
+ throw new PdpUnreachableError(`unexpected status ${res.status}`, statusKind(res.status));
3037
3094
  }
3038
3095
  function agentDenialOf(body) {
3039
3096
  if (typeof body !== "object" || body === null) return null;
@@ -3063,7 +3120,9 @@ async function holdForApproval(args, fetchFn) {
3063
3120
  if (await isApiTierRefusal(res)) return "tier-disabled";
3064
3121
  throw foreign403("hold");
3065
3122
  }
3066
- if (res.status !== 200) throw new PdpUnreachableError(`hold status ${res.status}`);
3123
+ if (res.status !== 200) {
3124
+ throw new PdpUnreachableError(`hold status ${res.status}`, statusKind(res.status));
3125
+ }
3067
3126
  try {
3068
3127
  args.onHeld?.();
3069
3128
  } catch {
@@ -3072,13 +3131,13 @@ async function holdForApproval(args, fetchFn) {
3072
3131
  try {
3073
3132
  parsed = JSON.parse(await res.text());
3074
3133
  } catch {
3075
- throw new PdpUnreachableError("hold 200 with unparseable body");
3134
+ throw new PdpUnreachableError("hold 200 with unparseable body", "parse_error");
3076
3135
  }
3077
3136
  const outcome = parsed?.outcome;
3078
3137
  if (outcome === "approved" || outcome === "denied" || outcome === "unanswered") {
3079
3138
  return { outcome, denial: agentDenialOf(parsed) };
3080
3139
  }
3081
- throw new PdpUnreachableError("hold 200 with malformed outcome");
3140
+ throw new PdpUnreachableError("hold 200 with malformed outcome", "parse_error");
3082
3141
  }
3083
3142
  function readCachedSnapshot(path, io2 = {}) {
3084
3143
  const read = io2.readFile ?? ((p) => readFileSync4(p, "utf8"));
@@ -3101,6 +3160,25 @@ function isCompiledSnapshot(v) {
3101
3160
  }
3102
3161
 
3103
3162
  // src/pep/cursor-hold.ts
3163
+ var CURSOR_FALLBACK_CAUSES = [
3164
+ "timeout",
3165
+ "unreachable",
3166
+ "config_unavailable",
3167
+ "evaluator_crash",
3168
+ "rejected_request",
3169
+ "waf_403",
3170
+ "parse_error"
3171
+ ];
3172
+ function fallbackCauseOf(err) {
3173
+ if (typeof err !== "object" || err === null) return void 0;
3174
+ const kind = err.kind;
3175
+ return CURSOR_FALLBACK_CAUSES.find((cause) => cause === kind);
3176
+ }
3177
+ function holdWasUnauthorized(err, status) {
3178
+ if (status === 401) return true;
3179
+ if (typeof err !== "object" || err === null) return false;
3180
+ return err.kind === "unauthorized";
3181
+ }
3104
3182
  function holdWindowSeconds(elapsedMs) {
3105
3183
  const spent = Math.floor(Math.max(0, elapsedMs) / 1e3);
3106
3184
  return Math.min(
@@ -3118,6 +3196,12 @@ async function holdCursorApproval(input) {
3118
3196
  }
3119
3197
  const windowSeconds = holdWindowSeconds(input.elapsedMs);
3120
3198
  input.extendDeadline?.(holdWatchdogDelayMs(input.elapsedMs));
3199
+ let status;
3200
+ const observedFetch = (async (...args) => {
3201
+ const res = await input.fetchFn(...args);
3202
+ status = res.status;
3203
+ return res;
3204
+ });
3121
3205
  try {
3122
3206
  const held = await holdForApproval(
3123
3207
  {
@@ -3128,7 +3212,7 @@ async function holdCursorApproval(input) {
3128
3212
  timeoutMs: PEP_HOLD_FETCH_TIMEOUT_MS,
3129
3213
  maxWindowSeconds: windowSeconds
3130
3214
  },
3131
- input.fetchFn
3215
+ observedFetch
3132
3216
  );
3133
3217
  if (held === "tier-disabled") {
3134
3218
  return { outcome: "forbidden", windowSeconds, correlationId };
@@ -3136,7 +3220,16 @@ async function holdCursorApproval(input) {
3136
3220
  return { outcome: held.outcome, windowSeconds, correlationId, denial: held.denial };
3137
3221
  } catch (err) {
3138
3222
  if (err instanceof PdpUnreachableError) {
3139
- return { outcome: "unreachable", windowSeconds, correlationId };
3223
+ if (holdWasUnauthorized(err, status)) {
3224
+ return { outcome: "unreachable", windowSeconds, correlationId, credentialRejected: true };
3225
+ }
3226
+ const fallbackCause = fallbackCauseOf(err);
3227
+ return {
3228
+ outcome: "unreachable",
3229
+ windowSeconds,
3230
+ correlationId,
3231
+ ...fallbackCause === void 0 ? {} : { fallbackCause }
3232
+ };
3140
3233
  }
3141
3234
  throw err;
3142
3235
  }
@@ -3901,9 +3994,9 @@ var GENERIC_SECRET_CANDIDATE = new RegExp(
3901
3994
  "g"
3902
3995
  );
3903
3996
  var GENERIC_SECRET_PREFILTER = new RegExp(`[A-Za-z0-9_-]{${FALLBACK_MIN_LENGTH}}`);
3904
- function aroundValue(name, separator, quote, label2) {
3997
+ function aroundValue(name, separator, quote, label4) {
3905
3998
  const q = quote ?? "";
3906
- return `${name}${separator}${q}${label2}${q}`;
3999
+ return `${name}${separator}${q}${label4}${q}`;
3907
4000
  }
3908
4001
  var EMAIL = led(String.raw`[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}\b`, "g");
3909
4002
  var SSN = led(String.raw`(?!000|666|9\d\d)\d{3}[- ](?!00)\d{2}[- ](?!0000)\d{4}\b`, "g");
@@ -4071,11 +4164,11 @@ var SCRUB_PATTERNS = [
4071
4164
  regex: CLOUD_ACCOUNT_ID,
4072
4165
  prefilter: /account|project|owner-id|arn:aws/i,
4073
4166
  placeholder: (g) => {
4074
- const label2 = redacted("pii:account");
4075
- if (g[1] !== void 0) return aroundValue(g[1], g[2] ?? "", g[3], label2);
4076
- if (g[5] !== void 0) return aroundValue(g[5], g[6] ?? "", g[7], label2);
4077
- if (g[9] !== void 0) return aroundValue(g[9], g[10] ?? "", g[11], label2);
4078
- return label2;
4167
+ const label4 = redacted("pii:account");
4168
+ if (g[1] !== void 0) return aroundValue(g[1], g[2] ?? "", g[3], label4);
4169
+ if (g[5] !== void 0) return aroundValue(g[5], g[6] ?? "", g[7], label4);
4170
+ if (g[9] !== void 0) return aroundValue(g[9], g[10] ?? "", g[11], label4);
4171
+ return label4;
4079
4172
  }
4080
4173
  },
4081
4174
  {
@@ -4277,6 +4370,54 @@ function secretManagerResultKeys(attributes, config) {
4277
4370
  return out;
4278
4371
  }
4279
4372
 
4373
+ // ../shared/src/types/decision-outcome.ts
4374
+ var DECISION_OUTCOME_UPLOAD_VIAS = ["snapshot", "none"];
4375
+ var DECISION_OUTCOME_VERDICTS = [
4376
+ "allow",
4377
+ "deny",
4378
+ "require_approval"
4379
+ ];
4380
+ var DECISION_OUTCOME_ANSWERS = ["proceed", "deny", "ask"];
4381
+ var DECISION_OUTCOME_CAUSES = [
4382
+ "pdp_refused",
4383
+ "no_snapshot",
4384
+ "credential_rejected",
4385
+ "config_blank",
4386
+ "misconfigured",
4387
+ "hold_unavailable",
4388
+ "watchdog"
4389
+ ];
4390
+ var DECISION_OUTCOME_CAUSES_WITH_FALLBACK = ["no_snapshot", "hold_unavailable"];
4391
+ var DECISION_FALLBACK_CAUSES = [
4392
+ "timeout",
4393
+ "unreachable",
4394
+ "config_unavailable",
4395
+ "evaluator_crash",
4396
+ "rejected_request",
4397
+ "waf_403",
4398
+ "parse_error"
4399
+ ];
4400
+ var CLIENT_DROP_COUNT_KEYS = [
4401
+ "writer_bound",
4402
+ "writer_timeout",
4403
+ "queue_full",
4404
+ "runtime_dir_unsafe"
4405
+ ];
4406
+ var DECISION_OUTCOME_LIMITS = {
4407
+ /** Outcomes per upload (envelope). */
4408
+ maxOutcomes: 500,
4409
+ /** Drop entries per upload (envelope). */
4410
+ maxDropDays: 31,
4411
+ /** The largest count a drop entry may carry (per entry). */
4412
+ maxDropCount: 1e5,
4413
+ /** How old an item's `decided_at` or a drop `day` may be, in days (per item or entry). */
4414
+ maxAgeDays: 30,
4415
+ /** How far ahead of the server clock a `decided_at` or a drop `day` may be, in minutes. */
4416
+ maxFutureMinutes: 5,
4417
+ /** The client prunes drop marks older than this, so a stale day is not resent forever. */
4418
+ clientDropRetentionDays: 29
4419
+ };
4420
+
4280
4421
  // ../shared/src/types/messages.ts
4281
4422
  var SSE_CHANNEL_PREFIX = "pubsub:sse:org:";
4282
4423
  var SSE_CHANNEL_PATTERN = `${SSE_CHANNEL_PREFIX}*`;
@@ -4534,7 +4675,7 @@ function readShellJoin(query) {
4534
4675
  function joinQueryFor(input) {
4535
4676
  const io2 = input.io ?? nodeCaptureFileIO;
4536
4677
  const key = readQueueKey(input.home, io2);
4537
- const label2 = input.vendorTool ?? input.normalized?.vendorTool;
4678
+ const label4 = input.vendorTool ?? input.normalized?.vendorTool;
4538
4679
  const first = input.normalized?.candidates[0];
4539
4680
  return {
4540
4681
  home: input.home,
@@ -4542,7 +4683,7 @@ function joinQueryFor(input) {
4542
4683
  projectKey: input.projectKey,
4543
4684
  conversationId: input.conversationId,
4544
4685
  generationId: input.generationId,
4545
- argsHash: key === void 0 || label2 === void 0 ? null : argsHashForCall(label2, first?.args ?? {}, input.toolInput, key),
4686
+ argsHash: key === void 0 || label4 === void 0 ? null : argsHashForCall(label4, first?.args ?? {}, input.toolInput, key),
4546
4687
  nowMs: input.nowMs
4547
4688
  };
4548
4689
  }
@@ -4591,7 +4732,12 @@ function writeDecisionRecord(input) {
4591
4732
  via: input.via,
4592
4733
  ...input.hold === void 0 ? {} : { hold: input.hold },
4593
4734
  ...input.handoff === void 0 ? {} : { handoff: input.handoff },
4594
- blocked: input.blocked
4735
+ blocked: input.blocked,
4736
+ // Written in the same synchronous write, so the hook does no new disk I/O for them.
4737
+ ...input.snapshotVersion === void 0 ? {} : { snapshotVersion: input.snapshotVersion },
4738
+ ...input.snapshotAgeSeconds === void 0 ? {} : { snapshotAgeSeconds: input.snapshotAgeSeconds },
4739
+ ...input.failMode === void 0 ? {} : { failMode: input.failMode },
4740
+ ...input.fallbackCause === void 0 ? {} : { fallbackCause: input.fallbackCause }
4595
4741
  };
4596
4742
  const folder = queueFolderFor(input.home, input.projectKey);
4597
4743
  if (queueEntryCount(input.io, folder) >= QUEUE_ENTRY_CAP) return false;
@@ -4637,6 +4783,19 @@ function buildCursorPdpRequest(payload) {
4637
4783
  function withScope(requests, scope) {
4638
4784
  return requests.map((request) => ({ ...request, scope }));
4639
4785
  }
4786
+ var CURSOR_LABEL_MAX_LENGTH = 255;
4787
+ function cursorRequestLabel(value) {
4788
+ return value !== null && value.length > 0 && value.length <= CURSOR_LABEL_MAX_LENGTH ? value : void 0;
4789
+ }
4790
+ function withLabels(requests, labels) {
4791
+ const correlationId = cursorRequestLabel(labels.correlationId);
4792
+ const sessionId = cursorRequestLabel(labels.sessionId);
4793
+ return requests.map((request) => ({
4794
+ ...request,
4795
+ ...correlationId === void 0 ? {} : { correlation_id: correlationId },
4796
+ ...sessionId === void 0 ? {} : { session_id: sessionId }
4797
+ }));
4798
+ }
4640
4799
 
4641
4800
  // src/pep/hold-upload.ts
4642
4801
  import { spawn } from "child_process";
@@ -4744,13 +4903,772 @@ function startHoldUpload(payload, env, deps = {}) {
4744
4903
  }
4745
4904
  }
4746
4905
 
4906
+ // src/pep/outcome-handoff.ts
4907
+ import { spawn as spawn2 } from "child_process";
4908
+
4909
+ // src/pep/outcome-writer.ts
4910
+ import { createHash as createHash3, randomBytes as randomBytes4, randomUUID } from "crypto";
4911
+ import { constants as FS3, promises as fsp4 } from "fs";
4912
+ import { createServer, connect as netConnect } from "net";
4913
+ import { userInfo } from "os";
4914
+ import { join as join11, resolve as resolve2 } from "path";
4915
+
4916
+ // src/pep/drop-marks.ts
4917
+ import { randomBytes as randomBytes3 } from "crypto";
4918
+ import { constants as FS2, promises as fsp3 } from "fs";
4919
+ import { join as join10 } from "path";
4920
+
4921
+ // src/pep/pending-outcomes.ts
4922
+ import { constants as FS, promises as fsp } from "fs";
4923
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join8 } from "path";
4924
+ var PENDING_OUTCOMES_CAP = 2e3;
4925
+ var PENDING_OUTCOMES_ORG_CAP = 1e3;
4926
+ var PENDING_OUTCOMES_BATCH = DECISION_OUTCOME_LIMITS.maxOutcomes;
4927
+ var OUTCOME_TMP_STALE_MS = 10 * 6e4;
4928
+ var DAY_MS = 864e5;
4929
+ var MAX_AGE_MS = DECISION_OUTCOME_LIMITS.maxAgeDays * DAY_MS;
4930
+ var MAX_FUTURE_MS = DECISION_OUTCOME_LIMITS.maxFutureMinutes * 6e4;
4931
+ var LABEL_MAX = 255;
4932
+ var SNAPSHOT_VERSION_MAX = 128;
4933
+ var DIR_MODE = 448;
4934
+ var FILE_MODE = 384;
4935
+ var O_NOFOLLOW = FS.O_NOFOLLOW ?? 0;
4936
+ var O_NONBLOCK = FS.O_NONBLOCK ?? 0;
4937
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
4938
+ var UUID_SRC = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
4939
+ var RECORD_NAME = new RegExp(`^(\\d{15})-(${UUID_SRC})-(${UUID_SRC})\\.json$`);
4940
+ var TMP_NAME = new RegExp(`^\\.tmp-(\\d{15})-(${UUID_SRC})$`);
4941
+ var realFs = {
4942
+ mkdir: (p, opts) => fsp.mkdir(p, opts),
4943
+ readdir: (p) => fsp.readdir(p),
4944
+ open: (p, flags, mode) => fsp.open(p, flags, mode),
4945
+ rename: (from, to) => fsp.rename(from, to),
4946
+ unlink: (p) => fsp.unlink(p)
4947
+ };
4948
+ function pendingOutcomesDir(snapshotPath) {
4949
+ return join8(dirname4(snapshotPath), "pending-outcomes");
4950
+ }
4951
+ function canonicalUuid(value) {
4952
+ if (typeof value !== "string") return void 0;
4953
+ const lower = value.toLowerCase();
4954
+ return UUID.test(lower) ? lower : void 0;
4955
+ }
4956
+ function label(value, max = LABEL_MAX) {
4957
+ return typeof value === "string" && value.length > 0 && value.length <= max ? value : void 0;
4958
+ }
4959
+ function oneOf(values, value) {
4960
+ return values.includes(value) ? value : void 0;
4961
+ }
4962
+ function validateOutcomeItem(raw, now = /* @__PURE__ */ new Date()) {
4963
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return void 0;
4964
+ const r = raw;
4965
+ const id = canonicalUuid(r.id);
4966
+ const orgId = canonicalUuid(r.org_id);
4967
+ const vendor = isAgentVendor(r.vendor) ? r.vendor : void 0;
4968
+ const sessionId = label(r.session_id);
4969
+ const correlationId = label(r.correlation_id);
4970
+ const toolName = label(r.tool_name);
4971
+ const via = oneOf(DECISION_OUTCOME_UPLOAD_VIAS, r.decided_via);
4972
+ const answer = oneOf(DECISION_OUTCOME_ANSWERS, r.answer);
4973
+ if (id === void 0 || orgId === void 0 || vendor === void 0 || sessionId === void 0 || correlationId === void 0 || toolName === void 0 || via === void 0 || answer === void 0) {
4974
+ return void 0;
4975
+ }
4976
+ const decidedMs = typeof r.decided_at === "string" ? Date.parse(r.decided_at) : Number.NaN;
4977
+ if (!Number.isFinite(decidedMs)) return void 0;
4978
+ const nowMs = now.getTime();
4979
+ if (decidedMs < nowMs - MAX_AGE_MS || decidedMs > nowMs + MAX_FUTURE_MS) return void 0;
4980
+ let ageSeconds;
4981
+ if (r.snapshot_age_seconds !== void 0) {
4982
+ const v = r.snapshot_age_seconds;
4983
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0) return void 0;
4984
+ ageSeconds = v;
4985
+ }
4986
+ let failMode;
4987
+ if (r.fail_mode !== void 0) {
4988
+ failMode = oneOf(["open", "closed"], r.fail_mode);
4989
+ if (failMode === void 0) return void 0;
4990
+ }
4991
+ const fallback = r.fallback_cause === void 0 ? void 0 : oneOf(DECISION_FALLBACK_CAUSES, r.fallback_cause);
4992
+ if (r.fallback_cause !== void 0 && fallback === void 0) return void 0;
4993
+ const common = {
4994
+ id,
4995
+ org_id: orgId,
4996
+ vendor,
4997
+ session_id: sessionId,
4998
+ correlation_id: correlationId,
4999
+ tool_name: toolName,
5000
+ answer,
5001
+ ...ageSeconds !== void 0 ? { snapshot_age_seconds: ageSeconds } : {},
5002
+ ...failMode !== void 0 ? { fail_mode: failMode } : {},
5003
+ decided_at: new Date(decidedMs).toISOString()
5004
+ };
5005
+ if (via === "snapshot") {
5006
+ const verdict = oneOf(DECISION_OUTCOME_VERDICTS, r.verdict);
5007
+ const version = label(r.snapshot_version, SNAPSHOT_VERSION_MAX);
5008
+ if (verdict === void 0 || version === void 0 || fallback === void 0) return void 0;
5009
+ if (r.cause !== void 0) return void 0;
5010
+ return {
5011
+ ...common,
5012
+ decided_via: via,
5013
+ verdict,
5014
+ fallback_cause: fallback,
5015
+ snapshot_version: version
5016
+ };
5017
+ }
5018
+ const cause = oneOf(DECISION_OUTCOME_CAUSES, r.cause);
5019
+ if (cause === void 0) return void 0;
5020
+ if (r.verdict !== void 0 || r.snapshot_version !== void 0) return void 0;
5021
+ const needsFallback = DECISION_OUTCOME_CAUSES_WITH_FALLBACK.includes(
5022
+ cause
5023
+ );
5024
+ if (needsFallback !== (fallback !== void 0)) return void 0;
5025
+ return {
5026
+ ...common,
5027
+ decided_via: via,
5028
+ cause,
5029
+ ...fallback !== void 0 ? { fallback_cause: fallback } : {}
5030
+ };
5031
+ }
5032
+ function outcomeFileName(item) {
5033
+ const stamp = String(Date.parse(item.decided_at)).padStart(15, "0");
5034
+ return `${stamp}-${item.org_id}-${item.id}.json`;
5035
+ }
5036
+ function parseOutcomeFileName(name) {
5037
+ const m = RECORD_NAME.exec(name);
5038
+ if (m === null) return void 0;
5039
+ return { decidedMs: Number(m[1]), orgId: m[2], id: m[3] };
5040
+ }
5041
+ async function listDir(fs, dir) {
5042
+ try {
5043
+ return await fs.readdir(dir);
5044
+ } catch {
5045
+ return void 0;
5046
+ }
5047
+ }
5048
+ async function unlinkQuietly(fs, path) {
5049
+ try {
5050
+ await fs.unlink(path);
5051
+ return true;
5052
+ } catch {
5053
+ return false;
5054
+ }
5055
+ }
5056
+ async function writeOutcomeRecord(dir, raw, opts = {}) {
5057
+ const fs = opts.fs ?? realFs;
5058
+ const now = opts.now ?? /* @__PURE__ */ new Date();
5059
+ if (!isAbsolute2(dir)) return "failed";
5060
+ const item = validateOutcomeItem(raw, now);
5061
+ if (item === void 0) return "invalid";
5062
+ let created;
5063
+ try {
5064
+ await fs.mkdir(dir, { recursive: true, mode: DIR_MODE });
5065
+ const names = await listDir(fs, dir);
5066
+ if (names === void 0) return "failed";
5067
+ let total = 0;
5068
+ let forOrg = 0;
5069
+ for (const name of names) {
5070
+ const parsed = parseOutcomeFileName(name);
5071
+ if (parsed === void 0) continue;
5072
+ total++;
5073
+ if (parsed.orgId === item.org_id) forOrg++;
5074
+ }
5075
+ if (total >= PENDING_OUTCOMES_CAP || forOrg >= PENDING_OUTCOMES_ORG_CAP) return "queue_full";
5076
+ const stamp = String(now.getTime()).padStart(15, "0");
5077
+ const tmp = join8(dir, `.tmp-${stamp}-${item.id}`);
5078
+ const handle = await fs.open(tmp, FS.O_WRONLY | FS.O_CREAT | FS.O_EXCL | O_NOFOLLOW, FILE_MODE);
5079
+ created = tmp;
5080
+ try {
5081
+ await handle.writeFile(JSON.stringify(item), "utf8");
5082
+ } finally {
5083
+ await handle.close();
5084
+ }
5085
+ await fs.rename(tmp, join8(dir, outcomeFileName(item)));
5086
+ return "queued";
5087
+ } catch {
5088
+ if (created !== void 0) await unlinkQuietly(fs, created);
5089
+ return "failed";
5090
+ }
5091
+ }
5092
+
5093
+ // src/pep/runtime-dir.ts
5094
+ import { promises as fsp2 } from "fs";
5095
+ import { tmpdir as osTmpdir } from "os";
5096
+ import { join as join9, win32 } from "path";
5097
+ var DIR_MODE2 = 448;
5098
+ var realFs2 = {
5099
+ mkdir: (p, mode) => fsp2.mkdir(p, { mode }),
5100
+ lstat: (p) => fsp2.lstat(p),
5101
+ stat: (p) => fsp2.stat(p),
5102
+ realpath: (p) => fsp2.realpath(p)
5103
+ };
5104
+ function facts(opts) {
5105
+ return {
5106
+ fs: opts.fs ?? realFs2,
5107
+ platform: opts.platform ?? process.platform,
5108
+ env: opts.env ?? process.env,
5109
+ uid: "uid" in opts ? opts.uid : process.getuid?.(),
5110
+ tmpdir: opts.tmpdir ?? osTmpdir
5111
+ };
5112
+ }
5113
+ function errCode(err) {
5114
+ return typeof err === "object" && err !== null && "code" in err ? String(err.code) : void 0;
5115
+ }
5116
+ function ownedPrivateDir(st, uid) {
5117
+ return st.isDirectory() && st.uid === uid && (st.mode & 63) === 0;
5118
+ }
5119
+ async function realDir(f, p) {
5120
+ if (p === void 0 || p === "") return void 0;
5121
+ try {
5122
+ const real = await f.fs.realpath(p);
5123
+ return (await f.fs.stat(real)).isDirectory() ? real : void 0;
5124
+ } catch {
5125
+ return void 0;
5126
+ }
5127
+ }
5128
+ async function runtimeDirLayout(opts = {}) {
5129
+ const f = facts(opts);
5130
+ if (f.platform === "win32") {
5131
+ const local = f.env.LOCALAPPDATA;
5132
+ if (local === void 0 || !win32.isAbsolute(local)) return void 0;
5133
+ return { base: local, levels: ["agenttrail", "outcome-writers"] };
5134
+ }
5135
+ const uid = f.uid;
5136
+ if (uid === void 0) return void 0;
5137
+ let base;
5138
+ if (f.platform === "linux") {
5139
+ const xdg = await realDir(f, f.env.XDG_RUNTIME_DIR);
5140
+ if (xdg !== void 0) {
5141
+ try {
5142
+ if (ownedPrivateDir(await f.fs.stat(xdg), uid)) base = xdg;
5143
+ } catch {
5144
+ }
5145
+ }
5146
+ } else if (f.platform === "darwin") {
5147
+ const t = f.env.TMPDIR;
5148
+ if (t !== void 0 && !/^\/(private\/)?tmp\/?$/.test(t)) base = await realDir(f, t);
5149
+ }
5150
+ base ??= await realDir(f, f.tmpdir()) ?? "/tmp";
5151
+ let perUser = false;
5152
+ try {
5153
+ perUser = ownedPrivateDir(await f.fs.stat(base), uid);
5154
+ } catch {
5155
+ perUser = false;
5156
+ }
5157
+ return { base, levels: [perUser ? "agenttrail" : `agenttrail-${uid}`, "outcome-writers"] };
5158
+ }
5159
+ function levelProblem(st, uid) {
5160
+ if (st.isSymbolicLink()) return "symlink";
5161
+ if (!st.isDirectory()) return "not_a_directory";
5162
+ if (uid === void 0) return void 0;
5163
+ if (st.uid !== uid) return "wrong_owner";
5164
+ if ((st.mode & 63) !== 0) return "wrong_mode";
5165
+ return void 0;
5166
+ }
5167
+ async function walk(opts, create) {
5168
+ const f = facts(opts);
5169
+ const layout = await runtimeDirLayout(opts);
5170
+ if (layout === void 0) return { kind: "unsafe", reason: "no_base" };
5171
+ const joinFn = f.platform === "win32" ? win32.join : join9;
5172
+ const uid = f.platform === "win32" ? void 0 : f.uid;
5173
+ let path = layout.base;
5174
+ for (const level of layout.levels) {
5175
+ path = joinFn(path, level);
5176
+ if (create) {
5177
+ try {
5178
+ await f.fs.mkdir(path, DIR_MODE2);
5179
+ } catch (err) {
5180
+ if (errCode(err) !== "EEXIST") return { kind: "unsafe", reason: "mkdir_failed" };
5181
+ }
5182
+ }
5183
+ let st;
5184
+ try {
5185
+ st = await f.fs.lstat(path);
5186
+ } catch (err) {
5187
+ if (!create && errCode(err) === "ENOENT") return { kind: "missing" };
5188
+ return { kind: "unsafe", reason: "lstat_failed" };
5189
+ }
5190
+ const problem = levelProblem(st, uid);
5191
+ if (problem !== void 0) return { kind: "unsafe", reason: problem };
5192
+ }
5193
+ return { kind: "ok", dir: path };
5194
+ }
5195
+ function ensureRuntimeDir(opts = {}) {
5196
+ return walk(opts, true);
5197
+ }
5198
+
5199
+ // src/pep/drop-marks.ts
5200
+ var DROP_COUNT_MAX = DECISION_OUTCOME_LIMITS.maxDropCount;
5201
+ var DROP_MARK_RETENTION_DAYS = DECISION_OUTCOME_LIMITS.clientDropRetentionDays;
5202
+ var DROP_CLAIM_ORPHAN_MS = 10 * 6e4;
5203
+ var FILE_MODE2 = 384;
5204
+ var O_NOFOLLOW2 = FS2.O_NOFOLLOW ?? 0;
5205
+ var O_NONBLOCK2 = FS2.O_NONBLOCK ?? 0;
5206
+ var UUID_SRC2 = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
5207
+ var MARK_NAME = new RegExp(
5208
+ `^(drops-(${UUID_SRC2})-(\\d{8})-(${CLIENT_DROP_COUNT_KEYS.join("|")}))(?:\\.returned-([0-9a-f]{16}-\\d{1,6})|\\.claimed-(\\d{15})-([0-9a-f]{16})-(\\d{1,6}))?(\\.count)?$`
5209
+ );
5210
+ var realFs3 = {
5211
+ readdir: (p) => fsp3.readdir(p),
5212
+ open: (p, flags, mode) => fsp3.open(p, flags, mode),
5213
+ rename: (from, to) => fsp3.rename(from, to),
5214
+ unlink: (p) => fsp3.unlink(p)
5215
+ };
5216
+ function ownerUid(opts) {
5217
+ return "uid" in opts ? opts.uid : process.getuid?.();
5218
+ }
5219
+ function errCode2(err) {
5220
+ return typeof err === "object" && err !== null && "code" in err ? String(err.code) : void 0;
5221
+ }
5222
+ function markDay(d) {
5223
+ return d.toISOString().slice(0, 10).replaceAll("-", "");
5224
+ }
5225
+ function dropMarkName(orgId, reason, now = /* @__PURE__ */ new Date()) {
5226
+ const org = canonicalUuid(orgId);
5227
+ if (org === void 0 || !CLIENT_DROP_COUNT_KEYS.includes(reason)) return void 0;
5228
+ return `drops-${org}-${markDay(now)}-${reason}`;
5229
+ }
5230
+ async function appendDropMark(dir, orgId, reason, opts = {}) {
5231
+ const fs = opts.fs ?? realFs3;
5232
+ const name = dropMarkName(orgId, reason, opts.now ?? /* @__PURE__ */ new Date());
5233
+ if (name === void 0) return "invalid";
5234
+ let handle;
5235
+ try {
5236
+ handle = await fs.open(
5237
+ join10(dir, name),
5238
+ FS2.O_WRONLY | FS2.O_APPEND | FS2.O_CREAT | O_NOFOLLOW2 | O_NONBLOCK2,
5239
+ FILE_MODE2
5240
+ );
5241
+ } catch (err) {
5242
+ const code = errCode2(err);
5243
+ return code === "ELOOP" || code === "ENXIO" ? "unsafe" : "failed";
5244
+ }
5245
+ try {
5246
+ const st = await handle.stat();
5247
+ const uid = ownerUid(opts);
5248
+ if (!st.isFile() || uid !== void 0 && st.uid !== uid) return "unsafe";
5249
+ await handle.write(Buffer.from("."));
5250
+ return "marked";
5251
+ } catch {
5252
+ return "failed";
5253
+ } finally {
5254
+ await handle.close().catch(() => {
5255
+ });
5256
+ }
5257
+ }
5258
+
5259
+ // src/pep/outcome-writer.ts
5260
+ var OUTCOME_RECORD_ENV = "AGENTTRAIL_OUTCOME_RECORD";
5261
+ var RECORD_FLAG = "--record";
5262
+ var WRITER_DEADLINE_MS = 1e4;
5263
+ var WRITER_BOUND = 4;
5264
+ var WRITER_RECOUNTS = 3;
5265
+ var RECORD_ENV_MAX = 8192;
5266
+ var PROBE_TIMEOUT_MS = 1e3;
5267
+ var MAX_ENTRIES_EXAMINED = 256;
5268
+ var UNKNOWN_TAG = "00000000";
5269
+ var ENTRY_NAME = /^h-([1-9]\d{0,9})-([0-9a-f]{8})\.sock$/;
5270
+ var PENDING_MARKER = /^pending-([0-3])-([1-9]\d{0,9})$/;
5271
+ function errCode3(err) {
5272
+ return typeof err === "object" && err !== null && "code" in err ? String(err.code) : void 0;
5273
+ }
5274
+ function parseStartTag(stat) {
5275
+ const close = stat.lastIndexOf(")");
5276
+ if (close < 0) return void 0;
5277
+ const field = stat.slice(close + 2).split(" ").at(19);
5278
+ if (field === void 0 || !/^\d{1,20}$/.test(field)) return void 0;
5279
+ const tag = (BigInt(field) % 2n ** 32n).toString(16).padStart(8, "0");
5280
+ return tag === UNKNOWN_TAG ? "00000001" : tag;
5281
+ }
5282
+ async function procStartTag(pid) {
5283
+ try {
5284
+ return parseStartTag(await fsp4.readFile(`/proc/${pid}/stat`, "utf8"));
5285
+ } catch {
5286
+ return void 0;
5287
+ }
5288
+ }
5289
+ function windowsPipeName(env) {
5290
+ let user = "";
5291
+ try {
5292
+ user = userInfo().username;
5293
+ } catch {
5294
+ user = env.USERNAME ?? "";
5295
+ }
5296
+ const hash = createHash3("sha256").update(`${user}\0${env.LOCALAPPDATA ?? ""}`).digest("hex").slice(0, 16);
5297
+ return (slot) => `\\\\.\\pipe\\agenttrail-${hash}-outcome-slot-${slot}`;
5298
+ }
5299
+ function defaultWriterDeps(env = process.env) {
5300
+ const runtime = { env };
5301
+ return {
5302
+ env,
5303
+ platform: process.platform,
5304
+ uid: process.getuid?.(),
5305
+ pid: process.pid,
5306
+ now: () => /* @__PURE__ */ new Date(),
5307
+ deadlineMs: WRITER_DEADLINE_MS,
5308
+ bindCountDelayMs: 0,
5309
+ recounts: WRITER_RECOUNTS,
5310
+ jitterMs: () => 5 + Math.floor(Math.random() * 21),
5311
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
5312
+ kill: (pid, signal) => process.kill(pid, signal),
5313
+ chdir: (dir) => process.chdir(dir),
5314
+ homeDir: () => snapshotCachePath(),
5315
+ ensureRuntime: () => ensureRuntimeDir(runtime),
5316
+ lstat: (p) => fsp4.lstat(p),
5317
+ stat: (p) => fsp4.stat(p),
5318
+ readdir: (p) => fsp4.readdir(p),
5319
+ unlink: (p) => fsp4.unlink(p),
5320
+ startTag: procStartTag,
5321
+ randomTag: () => randomBytes4(4).toString("hex"),
5322
+ newId: () => randomUUID(),
5323
+ writeRecord: (dir, item) => writeOutcomeRecord(dir, item),
5324
+ appendMark: (dir, org, reason) => appendDropMark(dir, org, reason),
5325
+ pipeName: windowsPipeName(env)
5326
+ };
5327
+ }
5328
+ function takeRecord(deps) {
5329
+ const raw = deps.env[OUTCOME_RECORD_ENV];
5330
+ delete deps.env[OUTCOME_RECORD_ENV];
5331
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > RECORD_ENV_MAX) return void 0;
5332
+ let parsed;
5333
+ try {
5334
+ parsed = JSON.parse(raw);
5335
+ } catch {
5336
+ return void 0;
5337
+ }
5338
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
5339
+ const obj = parsed;
5340
+ const withId = obj.id === void 0 ? { ...obj, id: deps.newId() } : obj;
5341
+ return validateOutcomeItem(withId, deps.now());
5342
+ }
5343
+ function pidAlive(deps, pid) {
5344
+ try {
5345
+ deps.kill(pid, 0);
5346
+ return true;
5347
+ } catch (err) {
5348
+ return errCode3(err) !== "ESRCH";
5349
+ }
5350
+ }
5351
+ function listenOn(path) {
5352
+ return new Promise((done) => {
5353
+ const server = createServer((socket) => socket.destroy());
5354
+ server.once("error", (err) => done({ code: errCode3(err) ?? "EUNKNOWN" }));
5355
+ try {
5356
+ server.listen(path, () => {
5357
+ server.removeAllListeners("error");
5358
+ server.on("error", () => {
5359
+ });
5360
+ done({ server });
5361
+ });
5362
+ } catch (err) {
5363
+ done({ code: errCode3(err) ?? "EUNKNOWN" });
5364
+ }
5365
+ });
5366
+ }
5367
+ function closeServer(server) {
5368
+ return new Promise((done) => {
5369
+ try {
5370
+ server.close(() => done());
5371
+ } catch {
5372
+ done();
5373
+ }
5374
+ });
5375
+ }
5376
+ function probe(path) {
5377
+ return new Promise((done) => {
5378
+ let settled = false;
5379
+ const finish = (result) => {
5380
+ if (settled) return;
5381
+ settled = true;
5382
+ clearTimeout(timer);
5383
+ socket.destroy();
5384
+ done(result);
5385
+ };
5386
+ const socket = netConnect({ path });
5387
+ const timer = setTimeout(() => finish("timeout"), PROBE_TIMEOUT_MS);
5388
+ socket.once("connect", () => finish("connected"));
5389
+ socket.once("error", (err) => finish(errCode3(err) ?? "EUNKNOWN"));
5390
+ });
5391
+ }
5392
+ async function entryIsDead(deps, name, pid, tag, probeFn = probe) {
5393
+ const result = await probeFn(name);
5394
+ if (result !== "ECONNREFUSED" && result !== "ENOENT") return false;
5395
+ if (!pidAlive(deps, pid)) return true;
5396
+ if (deps.platform !== "linux" || tag === UNKNOWN_TAG) return false;
5397
+ const now = await deps.startTag(pid);
5398
+ return now !== void 0 && now !== tag;
5399
+ }
5400
+ async function countLive(deps, own) {
5401
+ let names;
5402
+ try {
5403
+ names = await deps.readdir(".");
5404
+ } catch {
5405
+ return { live: Number.POSITIVE_INFINITY, timeouts: 0 };
5406
+ }
5407
+ let live = 1;
5408
+ let timeouts = 0;
5409
+ let examined = 0;
5410
+ for (const name of names) {
5411
+ if (name === own) continue;
5412
+ const m = ENTRY_NAME.exec(name);
5413
+ if (m === null) continue;
5414
+ let st;
5415
+ try {
5416
+ st = await deps.lstat(name);
5417
+ } catch {
5418
+ continue;
5419
+ }
5420
+ if (!st.isSocket() || deps.uid !== void 0 && st.uid !== deps.uid) continue;
5421
+ if (++examined > MAX_ENTRIES_EXAMINED) return { live: Number.POSITIVE_INFINITY, timeouts };
5422
+ if (await entryIsDead(deps, name, Number(m[1]), m[2])) {
5423
+ try {
5424
+ await deps.unlink(name);
5425
+ timeouts++;
5426
+ } catch {
5427
+ }
5428
+ continue;
5429
+ }
5430
+ live++;
5431
+ if (live > WRITER_BOUND) break;
5432
+ }
5433
+ return { live, timeouts };
5434
+ }
5435
+ async function book(ctx, reason) {
5436
+ try {
5437
+ await ctx.deps.appendMark(ctx.markDir, ctx.item.org_id, reason);
5438
+ } catch {
5439
+ }
5440
+ }
5441
+ async function holderWrite(ctx) {
5442
+ const { deps } = ctx;
5443
+ let item = ctx.item;
5444
+ if (item.decided_via === "snapshot" && item.snapshot_age_seconds === void 0) {
5445
+ try {
5446
+ const st = await deps.stat(ctx.snapshotPath);
5447
+ const age = Math.floor((deps.now().getTime() - st.mtimeMs) / 1e3);
5448
+ item = { ...item, snapshot_age_seconds: Math.max(0, age) };
5449
+ } catch {
5450
+ }
5451
+ }
5452
+ const result = await deps.writeRecord(ctx.queueDir, item);
5453
+ if (result === "queued") return "queued";
5454
+ if (result === "queue_full") {
5455
+ await book(ctx, "queue_full");
5456
+ return "queue_full";
5457
+ }
5458
+ return "write_failed";
5459
+ }
5460
+ async function enterFolder(deps, dir) {
5461
+ try {
5462
+ const before = await deps.lstat(dir);
5463
+ deps.chdir(dir);
5464
+ const here = await deps.stat(".");
5465
+ return here.isDirectory() && here.dev === before.dev && here.ino === before.ino && (deps.uid === void 0 || here.uid === deps.uid) && (here.mode & 63) === 0;
5466
+ } catch {
5467
+ return false;
5468
+ }
5469
+ }
5470
+ async function runUnix(ctx) {
5471
+ const { deps } = ctx;
5472
+ let tag = deps.randomTag();
5473
+ if (deps.platform === "linux") tag = await deps.startTag(deps.pid) ?? UNKNOWN_TAG;
5474
+ const own = `h-${deps.pid}-${tag}.sock`;
5475
+ for (let attempt = 0; attempt <= deps.recounts; attempt++) {
5476
+ ctx.attempts++;
5477
+ const bound = await listenOn(own);
5478
+ if (!("server" in bound)) {
5479
+ await book(ctx, "writer_bound");
5480
+ return "writer_bound";
5481
+ }
5482
+ let outcome;
5483
+ try {
5484
+ if (attempt === 0 && deps.bindCountDelayMs > 0) await deps.sleep(deps.bindCountDelayMs);
5485
+ const count = await countLive(deps, own);
5486
+ for (let i = 0; i < count.timeouts; i++) await book(ctx, "writer_timeout");
5487
+ ctx.timeouts += count.timeouts;
5488
+ if (count.live <= WRITER_BOUND) outcome = await holderWrite(ctx);
5489
+ } finally {
5490
+ await closeServer(bound.server);
5491
+ await deps.unlink(own).catch(() => {
5492
+ });
5493
+ }
5494
+ if (outcome !== void 0) return outcome;
5495
+ if (attempt < deps.recounts) await deps.sleep(deps.jitterMs());
5496
+ }
5497
+ await book(ctx, "writer_bound");
5498
+ return "writer_bound";
5499
+ }
5500
+ async function runWindows(ctx) {
5501
+ const { deps } = ctx;
5502
+ ctx.attempts++;
5503
+ let slot = -1;
5504
+ let server;
5505
+ for (let n = 0; n < WRITER_BOUND && server === void 0; n++) {
5506
+ const bound = await listenOn(deps.pipeName(n));
5507
+ if ("server" in bound) {
5508
+ server = bound.server;
5509
+ slot = n;
5510
+ }
5511
+ }
5512
+ if (server === void 0) {
5513
+ await book(ctx, "writer_bound");
5514
+ return "writer_bound";
5515
+ }
5516
+ const marker = join11(ctx.markDir, `pending-${slot}-${deps.pid}`);
5517
+ let created = false;
5518
+ try {
5519
+ for (const name of await deps.readdir(ctx.markDir).catch(() => [])) {
5520
+ const m = PENDING_MARKER.exec(name);
5521
+ if (m === null || Number(m[1]) !== slot || Number(m[2]) === deps.pid) continue;
5522
+ if (pidAlive(deps, Number(m[2]))) continue;
5523
+ try {
5524
+ await deps.unlink(join11(ctx.markDir, name));
5525
+ ctx.timeouts++;
5526
+ await book(ctx, "writer_timeout");
5527
+ } catch {
5528
+ }
5529
+ }
5530
+ try {
5531
+ const handle = await fsp4.open(marker, FS3.O_WRONLY | FS3.O_CREAT | FS3.O_EXCL, 384);
5532
+ await handle.close();
5533
+ created = true;
5534
+ } catch {
5535
+ }
5536
+ return await holderWrite(ctx);
5537
+ } finally {
5538
+ if (created) await deps.unlink(marker).catch(() => {
5539
+ });
5540
+ await closeServer(server);
5541
+ }
5542
+ }
5543
+ async function runOutcomeWriter(deps) {
5544
+ const timer = setTimeout(() => {
5545
+ try {
5546
+ deps.kill(deps.pid, "SIGKILL");
5547
+ } catch {
5548
+ }
5549
+ }, deps.deadlineMs);
5550
+ let ctx;
5551
+ try {
5552
+ const item = takeRecord(deps);
5553
+ if (item === void 0) return { outcome: "invalid_record", writerTimeouts: 0, attempts: 0 };
5554
+ const snapshotPath = resolve2(deps.env[ENV_PEP_SNAPSHOT_PATH]?.trim() || deps.homeDir());
5555
+ const checked = await deps.ensureRuntime();
5556
+ if (checked.kind !== "ok") {
5557
+ return { outcome: "runtime_dir_unsafe", writerTimeouts: 0, attempts: 0 };
5558
+ }
5559
+ ctx = {
5560
+ deps,
5561
+ item,
5562
+ snapshotPath,
5563
+ queueDir: pendingOutcomesDir(snapshotPath),
5564
+ markDir: checked.dir,
5565
+ timeouts: 0,
5566
+ attempts: 0
5567
+ };
5568
+ if (deps.platform === "win32") {
5569
+ const outcome2 = await runWindows(ctx);
5570
+ return { outcome: outcome2, writerTimeouts: ctx.timeouts, attempts: ctx.attempts };
5571
+ }
5572
+ if (!await enterFolder(deps, checked.dir)) {
5573
+ return { outcome: "runtime_dir_unsafe", writerTimeouts: 0, attempts: 0 };
5574
+ }
5575
+ ctx.markDir = ".";
5576
+ const outcome = await runUnix(ctx);
5577
+ return { outcome, writerTimeouts: ctx.timeouts, attempts: ctx.attempts };
5578
+ } catch {
5579
+ return { outcome: "error", writerTimeouts: ctx?.timeouts ?? 0, attempts: ctx?.attempts ?? 0 };
5580
+ } finally {
5581
+ clearTimeout(timer);
5582
+ }
5583
+ }
5584
+ function isRecordInvocation(argv) {
5585
+ return argv[2] === RECORD_FLAG;
5586
+ }
5587
+ async function runRecordProcess(deps = defaultWriterDeps(), exit = (code) => process.exit(code)) {
5588
+ const result = await runOutcomeWriter(deps);
5589
+ exit(0);
5590
+ return result;
5591
+ }
5592
+
5593
+ // src/pep/outcome-handoff.ts
5594
+ function answerOf(answer) {
5595
+ return answer === "deny" ? "deny" : answer === "ask" ? "ask" : "proceed";
5596
+ }
5597
+ var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
5598
+ function label2(value, max) {
5599
+ return typeof value === "string" && value.length > 0 && value.length <= max ? value : void 0;
5600
+ }
5601
+ function buildOutcomeRecord(ids, facts2, answer, now) {
5602
+ const orgId = ids.orgId !== void 0 && UUID2.test(ids.orgId) ? ids.orgId : void 0;
5603
+ const sessionId = label2(ids.payload.session_id, 255);
5604
+ const correlationId = label2(ids.payload.tool_use_id, 255);
5605
+ const toolName = label2(ids.payload.tool_name, 255);
5606
+ if (!orgId || !sessionId || !correlationId || !toolName) return void 0;
5607
+ const common = {
5608
+ org_id: orgId,
5609
+ vendor: ids.vendor,
5610
+ session_id: sessionId,
5611
+ correlation_id: correlationId,
5612
+ tool_name: toolName,
5613
+ answer: answerOf(answer),
5614
+ decided_at: now.toISOString()
5615
+ };
5616
+ if (facts2.via === "snapshot") {
5617
+ const version = label2(facts2.snapshotVersion, 128);
5618
+ if (!version) return void 0;
5619
+ return JSON.stringify({
5620
+ ...common,
5621
+ decided_via: "snapshot",
5622
+ verdict: facts2.verdict,
5623
+ fallback_cause: facts2.fallbackCause,
5624
+ snapshot_version: version,
5625
+ fail_mode: facts2.failMode
5626
+ });
5627
+ }
5628
+ return JSON.stringify({
5629
+ ...common,
5630
+ decided_via: "none",
5631
+ cause: facts2.cause,
5632
+ ...facts2.fallbackCause !== void 0 ? { fallback_cause: facts2.fallbackCause } : {}
5633
+ });
5634
+ }
5635
+ function handOffOutcome(record, deps) {
5636
+ if (!deps.bundlePath) return false;
5637
+ try {
5638
+ const child = (deps.spawn ?? spawn2)(
5639
+ deps.execPath,
5640
+ [deps.bundlePath, RECORD_FLAG],
5641
+ {
5642
+ detached: true,
5643
+ stdio: "ignore",
5644
+ windowsHide: true,
5645
+ env: { ...deps.env, [OUTCOME_RECORD_ENV]: record }
5646
+ }
5647
+ );
5648
+ child.on("error", () => {
5649
+ });
5650
+ child.unref();
5651
+ return true;
5652
+ } catch {
5653
+ return false;
5654
+ }
5655
+ }
5656
+
5657
+ // src/pep/outcome-writer-entry.ts
5658
+ function maybeRunRecordChild(argv = process.argv) {
5659
+ if (!isRecordInvocation(argv)) return false;
5660
+ void runRecordProcess();
5661
+ return true;
5662
+ }
5663
+ if (/outcome-writer-entry\.(mjs|cjs|js|ts)$/.test(process.argv[1] ?? "")) maybeRunRecordChild();
5664
+
4747
5665
  // src/pep/pending-decisions.ts
4748
- import { randomUUID } from "crypto";
5666
+ import { randomUUID as randomUUID2 } from "crypto";
4749
5667
  import { mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
4750
- import { dirname as dirname4, join as join8 } from "path";
5668
+ import { dirname as dirname5, join as join12 } from "path";
4751
5669
 
4752
5670
  // ../policy-engine/src/action-shape.ts
4753
- import { createHash as createHash3 } from "crypto";
5671
+ import { createHash as createHash4 } from "crypto";
4754
5672
  var ACTION_SHAPE_MAX_LENGTH = 512;
4755
5673
  var MAX_TOKENS = 24;
4756
5674
  var ARG = "<arg>";
@@ -4854,9 +5772,9 @@ function redactedActionShape(tool, args) {
4854
5772
 
4855
5773
  // src/pep/pending-decisions.ts
4856
5774
  var PENDING_DECISIONS_CAP = 500;
4857
- var DIR_MODE = 448;
4858
- var FILE_MODE = 384;
4859
- var LABEL_MAX = 255;
5775
+ var DIR_MODE3 = 448;
5776
+ var FILE_MODE3 = 384;
5777
+ var LABEL_MAX2 = 255;
4860
5778
  var realIO = {
4861
5779
  mkdir: (p, mode) => mkdirSync4(p, { recursive: true, mode }),
4862
5780
  writeFile: (p, content, mode) => writeFileSync3(p, content, { mode }),
@@ -4868,10 +5786,10 @@ function io(over) {
4868
5786
  return { ...realIO, ...over ?? {} };
4869
5787
  }
4870
5788
  function pendingDecisionsDir(snapshotPath) {
4871
- return join8(dirname4(snapshotPath), "pending-decisions");
5789
+ return join12(dirname5(snapshotPath), "pending-decisions");
4872
5790
  }
4873
- function label(v) {
4874
- return typeof v === "string" && v.length > 0 && v.length <= LABEL_MAX ? v : void 0;
5791
+ function label3(v) {
5792
+ return typeof v === "string" && v.length > 0 && v.length <= LABEL_MAX2 ? v : void 0;
4875
5793
  }
4876
5794
  function shapeOnlyArgs(tool, args) {
4877
5795
  const shape = redactedActionShape(tool, args);
@@ -4879,14 +5797,14 @@ function shapeOnlyArgs(tool, args) {
4879
5797
  if (shape === "<path>" && args.full_command === void 0) return { file_path: shape };
4880
5798
  return { full_command: shape };
4881
5799
  }
4882
- function toUploadItem(d, now = /* @__PURE__ */ new Date(), id = randomUUID()) {
4883
- const correlationId = label(d.request.correlation_id);
4884
- const sessionId = label(d.request.session_id);
5800
+ function toUploadItem(d, now = /* @__PURE__ */ new Date(), id = randomUUID2()) {
5801
+ const correlationId = label3(d.request.correlation_id);
5802
+ const sessionId = label3(d.request.session_id);
4885
5803
  return {
4886
5804
  id,
4887
5805
  policy_id: d.policyId,
4888
5806
  verdict: d.verdict,
4889
- tool: d.request.tool.slice(0, LABEL_MAX),
5807
+ tool: d.request.tool.slice(0, LABEL_MAX2),
4890
5808
  args: shapeOnlyArgs(d.request.tool, d.request.args),
4891
5809
  ...d.request.kind !== void 0 ? { kind: d.request.kind } : {},
4892
5810
  ...d.request.scope !== void 0 ? { scope: d.request.scope } : {},
@@ -4899,7 +5817,7 @@ function queueOfflineDecision(snapshotPath, d, opts = {}) {
4899
5817
  try {
4900
5818
  const fs = io(opts.io);
4901
5819
  const dir = pendingDecisionsDir(snapshotPath);
4902
- fs.mkdir(dir, DIR_MODE);
5820
+ fs.mkdir(dir, DIR_MODE3);
4903
5821
  let count = 0;
4904
5822
  try {
4905
5823
  count = fs.readDir(dir).filter((f) => f.endsWith(".json")).length;
@@ -4909,7 +5827,7 @@ function queueOfflineDecision(snapshotPath, d, opts = {}) {
4909
5827
  if (count >= PENDING_DECISIONS_CAP) return false;
4910
5828
  const item = toUploadItem(d, opts.now);
4911
5829
  const stamp = String(Date.parse(item.decided_at)).padStart(15, "0");
4912
- fs.writeFile(join8(dir, `${stamp}-${item.id}.json`), JSON.stringify(item), FILE_MODE);
5830
+ fs.writeFile(join12(dir, `${stamp}-${item.id}.json`), JSON.stringify(item), FILE_MODE3);
4913
5831
  return true;
4914
5832
  } catch {
4915
5833
  return false;
@@ -4918,7 +5836,7 @@ function queueOfflineDecision(snapshotPath, d, opts = {}) {
4918
5836
 
4919
5837
  // src/pep/trusted-env.ts
4920
5838
  import { readdirSync as readdirSync3, readFileSync as readFileSync7, realpathSync as realpathSync3 } from "fs";
4921
- import { dirname as dirname5, isAbsolute as isAbsolute2, join as join9, resolve as resolve2 } from "path";
5839
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join13, resolve as resolve3 } from "path";
4922
5840
  var PROJECT_IGNORED_PEP_KEYS = [
4923
5841
  ENV_PEP_URL,
4924
5842
  ENV_PEP_HOLD_URL,
@@ -4929,13 +5847,13 @@ var PROJECT_IGNORED_PEP_KEYS = [
4929
5847
  ENV_PEP_ORG_ID,
4930
5848
  ENV_PEP_ENFORCE
4931
5849
  ];
4932
- function managedSettingsFiles(platform = process.platform, listDir = (dir) => readdirSync3(dir)) {
5850
+ function managedSettingsFiles(platform = process.platform, listDir2 = (dir) => readdirSync3(dir)) {
4933
5851
  const dir = platform === "darwin" ? "/Library/Application Support/ClaudeCode" : platform === "win32" ? "C:\\Program Files\\ClaudeCode" : "/etc/claude-code";
4934
- const paths = [join9(dir, "managed-settings.json")];
5852
+ const paths = [join13(dir, "managed-settings.json")];
4935
5853
  try {
4936
- const dropIns = join9(dir, "managed-settings.d");
4937
- for (const name of listDir(dropIns).sort()) {
4938
- if (name.endsWith(".json")) paths.push(join9(dropIns, name));
5854
+ const dropIns = join13(dir, "managed-settings.d");
5855
+ for (const name of listDir2(dropIns).sort()) {
5856
+ if (name.endsWith(".json")) paths.push(join13(dropIns, name));
4939
5857
  }
4940
5858
  } catch {
4941
5859
  }
@@ -4971,7 +5889,7 @@ function safeRealpath(path, realpath) {
4971
5889
  try {
4972
5890
  return realpath(path);
4973
5891
  } catch {
4974
- return resolve2(path);
5892
+ return resolve3(path);
4975
5893
  }
4976
5894
  }
4977
5895
  function committedSettingsFolders(opts) {
@@ -4989,7 +5907,7 @@ function foldersFrom(starts, opts) {
4989
5907
  if (dir === home || seen.has(dir)) break;
4990
5908
  seen.add(dir);
4991
5909
  folders.push(dir);
4992
- const parent = dirname5(dir);
5910
+ const parent = dirname6(dir);
4993
5911
  if (parent === dir) break;
4994
5912
  dir = parent;
4995
5913
  }
@@ -5005,7 +5923,7 @@ function localRoot(opts, committed) {
5005
5923
  const realpath = opts.realpath ?? realpathSync3.native;
5006
5924
  const dir = opts.claudeProjectDir?.trim();
5007
5925
  if (dir !== void 0 && dir !== "") {
5008
- if (!isAbsolute2(dir) || setByRepo(committed, "CLAUDE_PROJECT_DIR")) return void 0;
5926
+ if (!isAbsolute3(dir) || setByRepo(committed, "CLAUDE_PROJECT_DIR")) return void 0;
5009
5927
  return safeRealpath(dir, realpath);
5010
5928
  }
5011
5929
  const first = opts.projectDirs.find((d) => d !== void 0 && d.trim() !== "");
@@ -5013,13 +5931,13 @@ function localRoot(opts, committed) {
5013
5931
  }
5014
5932
  function userSettingsFile(opts, committed) {
5015
5933
  const dir = opts.claudeConfigDir?.trim();
5016
- const trusted = dir !== void 0 && dir !== "" && isAbsolute2(dir) && !setByRepo(committed, "CLAUDE_CONFIG_DIR");
5017
- return join9(trusted ? dir : join9(opts.home, ".claude"), "settings.json");
5934
+ const trusted = dir !== void 0 && dir !== "" && isAbsolute3(dir) && !setByRepo(committed, "CLAUDE_CONFIG_DIR");
5935
+ return join13(trusted ? dir : join13(opts.home, ".claude"), "settings.json");
5018
5936
  }
5019
5937
  function trustedPepEnv(env, opts) {
5020
5938
  const read = opts.read ?? ((p) => readFileSync7(p, "utf8"));
5021
5939
  const committedPaths = committedSettingsFolders(opts).map(
5022
- (dir) => join9(dir, ".claude", "settings.json")
5940
+ (dir) => join13(dir, ".claude", "settings.json")
5023
5941
  );
5024
5942
  const committed = committedPaths.map((path) => readEnv(path, read));
5025
5943
  const anyUnparseable = committed.some((file) => file.kind === "unparseable");
@@ -5027,7 +5945,7 @@ function trustedPepEnv(env, opts) {
5027
5945
  const root = localRoot(opts, committed);
5028
5946
  const trustedFiles = [
5029
5947
  ...opts.managedPaths ?? managedSettingsFiles(),
5030
- ...root === void 0 ? [] : [join9(root, ".claude", "settings.local.json")],
5948
+ ...root === void 0 ? [] : [join13(root, ".claude", "settings.local.json")],
5031
5949
  userSettingsFile(opts, committed)
5032
5950
  ];
5033
5951
  let trusted;
@@ -5055,7 +5973,7 @@ function trustedPepEnv(env, opts) {
5055
5973
  const ownRoot = localRoot(opts, wellFormed);
5056
5974
  const files = [
5057
5975
  ...opts.managedPaths ?? managedSettingsFiles(),
5058
- ...ownRoot === void 0 ? [] : [join9(ownRoot, ".claude", "settings.local.json")],
5976
+ ...ownRoot === void 0 ? [] : [join13(ownRoot, ".claude", "settings.local.json")],
5059
5977
  userSettingsFile(opts, wellFormed)
5060
5978
  ];
5061
5979
  const own = files.map((path) => readEnv(path, read)).find((file) => file.kind === "ok" && ENV_PEP_ENFORCE in file.env);
@@ -5121,6 +6039,7 @@ var handleApproval = async (payload, verdict, ctx) => {
5121
6039
  ctx.fetchFn
5122
6040
  );
5123
6041
  if (held === "tier-disabled") {
6042
+ ctx.noteOutcome?.({ via: "none", cause: "pdp_refused" });
5124
6043
  return NO_DECISION;
5125
6044
  }
5126
6045
  if (held.outcome === "approved") {
@@ -5133,7 +6052,11 @@ var handleApproval = async (payload, verdict, ctx) => {
5133
6052
  decision: "ask",
5134
6053
  reason: "No AgentTrail reviewer answered in time; deferring the decision to you."
5135
6054
  };
5136
- } catch {
6055
+ } catch (err) {
6056
+ const kind = err instanceof PdpUnreachableError ? err.kind : "unreachable";
6057
+ ctx.noteOutcome?.(
6058
+ kind === "unauthorized" ? { via: "none", cause: "credential_rejected" } : { via: "none", cause: "hold_unavailable", fallbackCause: kind }
6059
+ );
5137
6060
  return {
5138
6061
  decision: "deny",
5139
6062
  reason: "AgentTrail approval hold was unreachable; failing closed."
@@ -5197,6 +6120,9 @@ function buildPdpRequest(payload, scope) {
5197
6120
  function pdpLabel(value) {
5198
6121
  return typeof value === "string" && value.length > 0 && value.length <= 255 ? value : void 0;
5199
6122
  }
6123
+ function fallbackOf(kind) {
6124
+ return kind === "unauthorized" ? "rejected_request" : kind;
6125
+ }
5200
6126
  async function mapVerdict(payload, response, cfg, deps) {
5201
6127
  switch (response.verdict) {
5202
6128
  case "allow": {
@@ -5213,14 +6139,17 @@ async function mapVerdict(payload, response, cfg, deps) {
5213
6139
  cfg,
5214
6140
  fetchFn: deps.fetchFn,
5215
6141
  extendDeadline: deps.extendDeadline,
5216
- ...deps.startHoldUpload ? { onHeld: () => deps.startHoldUpload?.(payload) } : {}
6142
+ ...deps.startHoldUpload ? { onHeld: () => deps.startHoldUpload?.(payload) } : {},
6143
+ ...deps.noteOutcome ? { noteOutcome: deps.noteOutcome } : {}
5217
6144
  }
5218
6145
  );
5219
6146
  }
5220
6147
  }
5221
- function failClosedViaSnapshot(_payload, request, cfg, deps) {
6148
+ function failClosedViaSnapshot(_payload, request, cfg, deps, kind = "unreachable") {
6149
+ const fallbackCause = fallbackOf(kind);
5222
6150
  const snapshot = readCachedSnapshot(cfg.snapshotPath, deps.snapshotIO);
5223
6151
  if (!snapshot) {
6152
+ deps.noteOutcome?.({ via: "none", cause: "no_snapshot", fallbackCause });
5224
6153
  return {
5225
6154
  decision: "deny",
5226
6155
  reason: "AgentTrail PDP is unreachable and no local policy snapshot is cached; failing closed."
@@ -5231,6 +6160,13 @@ function failClosedViaSnapshot(_payload, request, cfg, deps) {
5231
6160
  request,
5232
6161
  cfg.orgId
5233
6162
  );
6163
+ deps.noteOutcome?.({
6164
+ via: "snapshot",
6165
+ verdict,
6166
+ fallbackCause,
6167
+ snapshotVersion: snapshot.version,
6168
+ failMode: snapshot.fail_mode
6169
+ });
5234
6170
  if ((verdict === "deny" || verdict === "require_approval") && decidingPolicyId) {
5235
6171
  (deps.queueOffline ?? queueOfflineDecision)(cfg.snapshotPath, {
5236
6172
  policyId: decidingPolicyId,
@@ -5311,6 +6247,7 @@ async function decide(payload, cfg, deps) {
5311
6247
  return NO_DECISION;
5312
6248
  }
5313
6249
  if (!cfg.url || !cfg.token) {
6250
+ deps.noteOutcome?.({ via: "none", cause: "config_blank" });
5314
6251
  return {
5315
6252
  decision: "deny",
5316
6253
  reason: "AgentTrail enforcement is on here (AGENTTRAIL_PEP_ENFORCE=1) but has no PDP URL or token, so it fails closed. If this repo's committed .claude/settings.json sets AGENTTRAIL_PEP_ENFORCE, remove it from that file; otherwise run `npx -y @agenttrail/cli@latest setup --agent claude` in this repo."
@@ -5323,9 +6260,11 @@ async function decide(payload, cfg, deps) {
5323
6260
  deps.fetchFn
5324
6261
  );
5325
6262
  if (outcome.kind === "tier-disabled") {
6263
+ deps.noteOutcome?.({ via: "none", cause: "pdp_refused" });
5326
6264
  return NO_DECISION;
5327
6265
  }
5328
6266
  if (outcome.kind === "unauthorized") {
6267
+ deps.noteOutcome?.({ via: "none", cause: "credential_rejected" });
5329
6268
  return {
5330
6269
  decision: "deny",
5331
6270
  reason: "AgentTrail rejected the enforcement credential (401); failing closed. Re-run `npx -y @agenttrail/cli@latest setup --agent claude`."
@@ -5334,7 +6273,7 @@ async function decide(payload, cfg, deps) {
5334
6273
  return await mapVerdict(payload, outcome.response, cfg, deps);
5335
6274
  } catch (err) {
5336
6275
  if (err instanceof PdpUnreachableError) {
5337
- return failClosedViaSnapshot(payload, request, cfg, deps);
6276
+ return failClosedViaSnapshot(payload, request, cfg, deps, err.kind);
5338
6277
  }
5339
6278
  throw err;
5340
6279
  }
@@ -5367,11 +6306,16 @@ function createRealEmitter() {
5367
6306
  }, 1e3);
5368
6307
  t.unref?.();
5369
6308
  },
5370
- emitCrashDeny(reason) {
6309
+ emitCrashDeny(reason, beforeExit) {
5371
6310
  if (done) return;
5372
6311
  done = true;
6312
+ process.exitCode = 2;
5373
6313
  process.stderr.write(`${reason}
5374
6314
  `);
6315
+ try {
6316
+ beforeExit?.();
6317
+ } catch {
6318
+ }
5375
6319
  process.exit(2);
5376
6320
  }
5377
6321
  };
@@ -5408,7 +6352,24 @@ function defaultSchedule(fn, ms) {
5408
6352
  }
5409
6353
  async function runShim(deps) {
5410
6354
  const schedule = deps.schedule ?? defaultSchedule;
5411
- const fire = () => deps.emitter.emitCrashDeny("AgentTrail enforcement timed out; failing closed.");
6355
+ let ids;
6356
+ let fired = false;
6357
+ const handOff = (facts2, answer) => {
6358
+ if (ids === void 0 || deps.handOffOutcome === void 0) return;
6359
+ try {
6360
+ const record = buildOutcomeRecord(ids, facts2, answer, /* @__PURE__ */ new Date());
6361
+ if (record !== void 0) deps.handOffOutcome(record);
6362
+ } catch {
6363
+ }
6364
+ };
6365
+ const fire = () => {
6366
+ cancelWatchdog();
6367
+ deps.emitter.emitCrashDeny(
6368
+ "AgentTrail enforcement timed out; failing closed.",
6369
+ () => handOff({ via: "none", cause: "watchdog" }, "deny")
6370
+ );
6371
+ fired = true;
6372
+ };
5412
6373
  let cancelWatchdog = schedule(fire, deps.watchdogMs ?? PEP_WATCHDOG_MS);
5413
6374
  const extendDeadline = (ms) => {
5414
6375
  cancelWatchdog();
@@ -5431,25 +6392,34 @@ async function runShim(deps) {
5431
6392
  return;
5432
6393
  }
5433
6394
  const pepEnv = pepEnvFor(deps.env, payload, deps.settingsScopes);
6395
+ const cfg = resolvePepConfig(pepEnv.env);
6396
+ if (cfg.enforce) ids = { orgId: cfg.outcomeOrgId, vendor: PEP_VENDOR, payload };
5434
6397
  if (pepEnv.unreadableCommitted !== void 0) {
6398
+ ids = { orgId: resolvePepConfig(deps.env).outcomeOrgId, vendor: PEP_VENDOR, payload };
5435
6399
  cancelWatchdog();
6400
+ handOff({ via: "none", cause: "misconfigured" }, "deny");
5436
6401
  deps.emitter.emitVerdict("deny", unreadableSettingsDenyReason(pepEnv.unreadableCommitted));
5437
6402
  return;
5438
6403
  }
5439
- const cfg = resolvePepConfig(pepEnv.env);
5440
6404
  if (cfg.enforce && (!cfg.url || !cfg.token) && pepEnv.ignored.length > 0) {
5441
6405
  cancelWatchdog();
6406
+ handOff({ via: "none", cause: "config_blank" }, "deny");
5442
6407
  deps.emitter.emitVerdict("deny", repoConfigDenyReason(pepEnv.ignored));
5443
6408
  return;
5444
6409
  }
6410
+ let noted;
5445
6411
  const decision = await decide(payload, cfg, {
5446
6412
  fetchFn: deps.fetchFn,
5447
6413
  snapshotIO: deps.snapshotIO,
5448
6414
  approve: deps.approve,
5449
6415
  extendDeadline,
5450
- ...deps.startHoldUpload ? { startHoldUpload: deps.startHoldUpload } : {}
6416
+ ...deps.startHoldUpload ? { startHoldUpload: deps.startHoldUpload } : {},
6417
+ noteOutcome: (facts2) => {
6418
+ noted ??= facts2;
6419
+ }
5451
6420
  });
5452
6421
  cancelWatchdog();
6422
+ if (noted !== void 0 && !fired) handOff(noted, decision.decision);
5453
6423
  deps.emitter.emitVerdict(decision.decision, decision.reason);
5454
6424
  } catch (err) {
5455
6425
  cancelWatchdog();
@@ -5496,7 +6466,7 @@ function noDriverFor(_agent) {
5496
6466
  );
5497
6467
  process.exitCode = 2;
5498
6468
  }
5499
- if (isDirectRun()) {
6469
+ if (isDirectRun() && !maybeRunRecordChild()) {
5500
6470
  const argv = process.argv.slice(2);
5501
6471
  dispatchHookRun(argv, {
5502
6472
  cursor: () => {
@@ -5546,11 +6516,25 @@ if (isDirectRun()) {
5546
6516
  emitter,
5547
6517
  argv,
5548
6518
  settingsScopes: { home: homedir2(), processCwd: process.cwd() },
5549
- startHoldUpload: (payload) => startHoldUpload(payload, process.env)
6519
+ startHoldUpload: (payload) => startHoldUpload(payload, process.env),
6520
+ handOffOutcome: (record) => {
6521
+ handOffOutcome(record, {
6522
+ env: process.env,
6523
+ bundlePath: process.argv[1],
6524
+ execPath: process.execPath
6525
+ });
6526
+ }
5550
6527
  });
5551
6528
  }
5552
6529
  });
5553
6530
  }
6531
+ function statMtimeMs(path) {
6532
+ try {
6533
+ return statSync2(path).mtimeMs;
6534
+ } catch {
6535
+ return void 0;
6536
+ }
6537
+ }
5554
6538
  var CURSOR_BROKEN_INSTALL = "AgentTrail cannot read its project registry. Run setup again for this project.";
5555
6539
  var CURSOR_MISCONFIGURED = "AgentTrail enforcement is enabled here but misconfigured. Run setup again for this project.";
5556
6540
  var CURSOR_UNAUTHORIZED = "AgentTrail rejected the enforcement credential (401). Run login again for Cursor.";
@@ -5587,7 +6571,7 @@ function cursorReason(verdict, name, guidance = null) {
5587
6571
  guidance
5588
6572
  );
5589
6573
  }
5590
- async function decideCursorCandidates(requests, cfg, deps) {
6574
+ async function decideCursorCandidates(requests, cfg, deps, nowMs) {
5591
6575
  const settled = await Promise.all(
5592
6576
  requests.map(async (request) => {
5593
6577
  try {
@@ -5599,23 +6583,35 @@ async function decideCursorCandidates(requests, cfg, deps) {
5599
6583
  )
5600
6584
  };
5601
6585
  } catch (err) {
5602
- if (err instanceof PdpUnreachableError) return { ok: false };
6586
+ if (err instanceof PdpUnreachableError) {
6587
+ return { ok: false, fallbackCause: fallbackCauseOf(err) };
6588
+ }
5603
6589
  throw err;
5604
6590
  }
5605
6591
  })
5606
6592
  );
5607
- if (settled.some((result) => !result.ok)) {
6593
+ const failed = settled.find((result) => !result.ok);
6594
+ if (failed !== void 0 && !failed.ok) {
6595
+ const fallback = failed.fallbackCause === void 0 ? {} : { fallbackCause: failed.fallbackCause };
5608
6596
  const snapshot = readCachedSnapshot(cfg.snapshotPath, deps.snapshotIO);
5609
6597
  if (!snapshot) {
5610
6598
  return {
5611
6599
  outcome: { kind: "deny", message: CURSOR_NO_CACHE },
5612
6600
  holdCandidate: null,
5613
6601
  policyId: null,
5614
- via: "no-cache"
6602
+ via: "no-cache",
6603
+ ...fallback
5615
6604
  };
5616
6605
  }
5617
6606
  const local = requests.map((request) => evaluateLocally(snapshot, request, cfg.orgId));
5618
- return outcomeOf(local, "cached-rules");
6607
+ const mtimeMs = (deps.snapshotMtimeMs ?? statMtimeMs)(cfg.snapshotPath);
6608
+ return {
6609
+ ...outcomeOf(local, "cached-rules"),
6610
+ snapshotVersion: snapshot.version,
6611
+ failMode: snapshot.fail_mode,
6612
+ ...mtimeMs === void 0 || !Number.isFinite(mtimeMs) ? {} : { snapshotAgeSeconds: Math.max(0, Math.floor((nowMs() - mtimeMs) / 1e3)) },
6613
+ ...fallback
6614
+ };
5619
6615
  }
5620
6616
  const perCandidate = [];
5621
6617
  let refused = 0;
@@ -5675,12 +6671,12 @@ function outcomeOf(perCandidate, via) {
5675
6671
  via
5676
6672
  };
5677
6673
  }
5678
- function decideCursorShell(join10, cfg, deps, request) {
5679
- if (join10.kind === "handoff") {
6674
+ function decideCursorShell(join14, cfg, deps, request) {
6675
+ if (join14.kind === "handoff") {
5680
6676
  return { kind: "approval", message: "AgentTrail is waiting for approval of this command." };
5681
6677
  }
5682
- if (join10.kind === "decided") return { kind: "none" };
5683
- if (join10.liveHandoff) {
6678
+ if (join14.kind === "decided") return { kind: "none" };
6679
+ if (join14.liveHandoff) {
5684
6680
  return { kind: "approval", message: "AgentTrail is waiting for approval in this turn." };
5685
6681
  }
5686
6682
  const snapshot = readCachedSnapshot(cfg.snapshotPath, deps.snapshotIO);
@@ -5787,7 +6783,11 @@ async function answerCursor(deps, startedAtMs) {
5787
6783
  candidateIndex: fields.candidateIndex ?? null,
5788
6784
  via: fields.via,
5789
6785
  blocked: answerBlocks(answer2),
5790
- ...fields.hold === void 0 ? {} : { hold: fields.hold }
6786
+ ...fields.hold === void 0 ? {} : { hold: fields.hold },
6787
+ ...fields.snapshotVersion === void 0 ? {} : { snapshotVersion: fields.snapshotVersion },
6788
+ ...fields.snapshotAgeSeconds === void 0 ? {} : { snapshotAgeSeconds: fields.snapshotAgeSeconds },
6789
+ ...fields.failMode === void 0 ? {} : { failMode: fields.failMode },
6790
+ ...fields.fallbackCause === void 0 ? {} : { fallbackCause: fields.fallbackCause }
5791
6791
  });
5792
6792
  return answer2;
5793
6793
  };
@@ -5801,7 +6801,7 @@ async function answerCursor(deps, startedAtMs) {
5801
6801
  }
5802
6802
  if (event === "beforeShellExecution") {
5803
6803
  const request = normalized?.candidates[0];
5804
- const join10 = (deps.shellJoin ?? readShellJoin)(
6804
+ const join14 = (deps.shellJoin ?? readShellJoin)(
5805
6805
  joinQueryFor({
5806
6806
  home: deps.home,
5807
6807
  io: deps.io,
@@ -5815,7 +6815,7 @@ async function answerCursor(deps, startedAtMs) {
5815
6815
  })
5816
6816
  );
5817
6817
  const outcome = decideCursorShell(
5818
- join10,
6818
+ join14,
5819
6819
  cfg,
5820
6820
  deps,
5821
6821
  request === void 0 ? void 0 : { tool: request.tool, args: { ...request.args } }
@@ -5824,31 +6824,51 @@ async function answerCursor(deps, startedAtMs) {
5824
6824
  verdict: verdictOf(outcome),
5825
6825
  // This checkpoint asks no one: it answers from the queue, or from the cached rules
5826
6826
  // when the queue has nothing to say.
5827
- via: join10.kind === "miss" ? "cached-rules" : "pdp"
6827
+ via: join14.kind === "miss" ? "cached-rules" : "pdp"
5828
6828
  });
5829
6829
  }
5830
6830
  const requests = buildCursorPdpRequest(payload);
5831
6831
  if (requests === void 0 || normalized === void 0) {
5832
- const label2 = cursorVendorTool(payload);
5833
- const mcp = label2?.startsWith(CURSOR_MCP_PREFIX);
6832
+ const label4 = cursorVendorTool(payload);
6833
+ const mcp = label4?.startsWith(CURSOR_MCP_PREFIX);
5834
6834
  return record(CURSOR_NO_OPINION, {
5835
6835
  verdict: "observed",
5836
6836
  via: "pdp",
5837
- ...mcp === true && label2 !== void 0 ? { vendorTool: label2, toolUseId: correlationIdFor(payload.tool_use_id) } : (
6837
+ ...mcp === true && label4 !== void 0 ? { vendorTool: label4, toolUseId: correlationIdFor(payload.tool_use_id) } : (
5838
6838
  // Not an MCP call and not mappable: nothing to record it under, and nothing
5839
6839
  // will look for it.
5840
6840
  {}
5841
6841
  )
5842
6842
  });
5843
6843
  }
5844
- const scoped = withScope(requests, cursorScopeFor(lookup.record, cfg.agentId));
5845
- const decision = await decideCursorCandidates(scoped, cfg, deps);
6844
+ const correlationId = event === "beforeMCPExecution" ? (deps.recoverMcpCorrelationId ?? readMcpCorrelationId)(
6845
+ joinQueryFor({
6846
+ home: deps.home,
6847
+ io: deps.io,
6848
+ projectKey: lookup.record.projectKey,
6849
+ normalized,
6850
+ vendorTool: normalized.vendorTool,
6851
+ toolInput: payload.tool_input,
6852
+ conversationId: nonEmptyString(payload.conversation_id),
6853
+ generationId: nonEmptyString(payload.generation_id),
6854
+ nowMs: clock()
6855
+ })
6856
+ ) : normalized.correlationId;
6857
+ const scoped = withLabels(withScope(requests, cursorScopeFor(lookup.record, cfg.agentId)), {
6858
+ correlationId,
6859
+ sessionId: nonEmptyString(payload.conversation_id)
6860
+ });
6861
+ const decision = await decideCursorCandidates(scoped, cfg, deps, clock);
5846
6862
  const tool = normalized.vendorTool;
5847
6863
  const decided = {
5848
6864
  verdict: verdictOf(decision.outcome),
5849
6865
  via: decision.via,
5850
6866
  policyId: decision.policyId,
5851
- candidateIndex: decision.holdCandidate
6867
+ candidateIndex: decision.holdCandidate,
6868
+ ...decision.snapshotVersion === void 0 ? {} : { snapshotVersion: decision.snapshotVersion },
6869
+ ...decision.snapshotAgeSeconds === void 0 ? {} : { snapshotAgeSeconds: decision.snapshotAgeSeconds },
6870
+ ...decision.failMode === void 0 ? {} : { failMode: decision.failMode },
6871
+ ...decision.fallbackCause === void 0 ? {} : { fallbackCause: decision.fallbackCause }
5852
6872
  };
5853
6873
  if (decision.outcome.kind !== "approval") {
5854
6874
  return record(buildCursorAnswer({ event, tool, outcome: decision.outcome }), decided);
@@ -5858,19 +6878,6 @@ async function answerCursor(deps, startedAtMs) {
5858
6878
  if (held === void 0) {
5859
6879
  return record(buildCursorAnswer({ event, tool, outcome: decision.outcome }), decided);
5860
6880
  }
5861
- const correlationId = event === "beforeMCPExecution" ? (deps.recoverMcpCorrelationId ?? readMcpCorrelationId)(
5862
- joinQueryFor({
5863
- home: deps.home,
5864
- io: deps.io,
5865
- projectKey: lookup.record.projectKey,
5866
- normalized,
5867
- vendorTool: normalized.vendorTool,
5868
- toolInput: payload.tool_input,
5869
- conversationId: nonEmptyString(payload.conversation_id),
5870
- generationId: nonEmptyString(payload.generation_id),
5871
- nowMs: clock()
5872
- })
5873
- ) : normalized.correlationId;
5874
6881
  const hold = await holdCursorApproval({
5875
6882
  cfg,
5876
6883
  fetchFn: deps.fetchFn,
@@ -5880,10 +6887,14 @@ async function answerCursor(deps, startedAtMs) {
5880
6887
  extendDeadline: deps.extendDeadline
5881
6888
  });
5882
6889
  const heldFields = {
5883
- ...decided,
6890
+ ...hold.credentialRejected === true ? withoutFallbackFields(decided) : decided,
5884
6891
  ...hold.outcome === "forbidden" ? { via: "forbidden" } : {},
6892
+ ...hold.credentialRejected === true ? { via: "unauthorized" } : {},
5885
6893
  toolUseId: correlationId,
5886
6894
  toolUseIdFrom: event === "beforeMCPExecution" ? "queue" : "payload",
6895
+ // An unreachable hold after an ONLINE evaluate records the hold's own failure. A
6896
+ // `cached-rules` decision keeps the evaluate's, which is why the snapshot was used at all.
6897
+ ...hold.outcome === "unreachable" && decision.via === "pdp" && hold.fallbackCause !== void 0 ? { fallbackCause: hold.fallbackCause } : {},
5887
6898
  ...hold.outcome === "forbidden" ? {} : {
5888
6899
  hold: {
5889
6900
  correlationId: hold.correlationId ?? "",
@@ -5914,6 +6925,16 @@ async function answerCursor(deps, startedAtMs) {
5914
6925
  const answer = buildCursorAnswer({ event, tool, outcome: unanswered, handoff });
5915
6926
  return handoff ? answer : record(answer, heldFields);
5916
6927
  }
6928
+ function withoutFallbackFields(fields) {
6929
+ const {
6930
+ snapshotVersion: _version,
6931
+ snapshotAgeSeconds: _age,
6932
+ failMode: _failMode,
6933
+ fallbackCause: _cause,
6934
+ ...rest
6935
+ } = fields;
6936
+ return rest;
6937
+ }
5917
6938
  function verdictOf(outcome) {
5918
6939
  switch (outcome.kind) {
5919
6940
  case "none":