@agenttrail/cli 0.1.0 → 0.2.1

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.
@@ -1944,7 +1944,7 @@ function createCompiledLabelMatcher(pattern) {
1944
1944
  compiledLabelCache.set(pattern, matcher);
1945
1945
  }
1946
1946
  const cached = matcher;
1947
- return (label) => cached(label);
1947
+ return (label2) => cached(label2);
1948
1948
  }
1949
1949
  function createCompiledDetailMatcher(pattern) {
1950
1950
  let compiled = compiledDetailCache.get(pattern);
@@ -2149,6 +2149,9 @@ function strongestVerdict(matches) {
2149
2149
  return { verdict: "allow", policyId: null };
2150
2150
  }
2151
2151
 
2152
+ // ../shared/src/agent-feedback.ts
2153
+ var AGENT_GUIDANCE_MAX_CHARS = 500;
2154
+
2152
2155
  // src/cursor/detect.ts
2153
2156
  var CURSOR_EVENT_NAMES = /* @__PURE__ */ new Set([
2154
2157
  // guard's list
@@ -2637,8 +2640,8 @@ function credentialsPath(homeDir, agent = "claude") {
2637
2640
  function noCredentialFor(agent) {
2638
2641
  throw new Error(`AgentTrail has no credential file for the agent ${JSON.stringify(agent)}.`);
2639
2642
  }
2640
- function readCredentials(homeDir, io = {}, agent = "claude") {
2641
- const read = io.readFile ?? ((p) => readFileSync3(p, "utf8"));
2643
+ function readCredentials(homeDir, io2 = {}, agent = "claude") {
2644
+ const read = io2.readFile ?? ((p) => readFileSync3(p, "utf8"));
2642
2645
  try {
2643
2646
  const parsed = JSON.parse(read(credentialsPath(homeDir, agent)));
2644
2647
  if (!isCredentials(parsed)) return null;
@@ -2696,12 +2699,12 @@ function queueFolderFor(home, projectKey) {
2696
2699
  }
2697
2700
 
2698
2701
  // src/cursor/enforcement-record.ts
2699
- function readEnforcementRecord(home, io = nodeCaptureFileIO) {
2702
+ function readEnforcementRecord(home, io2 = nodeCaptureFileIO) {
2700
2703
  let value;
2701
2704
  try {
2702
2705
  const path = cursorPaths(home).enforcement;
2703
- if (!io.exists(path)) return void 0;
2704
- value = JSON.parse(io.readFile(path).toString("utf8"));
2706
+ if (!io2.exists(path)) return void 0;
2707
+ value = JSON.parse(io2.readFile(path).toString("utf8"));
2705
2708
  } catch {
2706
2709
  return void 0;
2707
2710
  }
@@ -2751,11 +2754,11 @@ var EMPTY_REGISTRY = Object.freeze({
2751
2754
  v: 1,
2752
2755
  projects: Object.freeze({})
2753
2756
  });
2754
- function readRegistryAt(path, isProjectRecord2, io = nodeCaptureFileIO) {
2757
+ function readRegistryAt(path, isProjectRecord2, io2 = nodeCaptureFileIO) {
2755
2758
  let text;
2756
2759
  try {
2757
- if (!io.exists(path)) return { kind: "missing" };
2758
- text = io.readFile(path).toString("utf8");
2760
+ if (!io2.exists(path)) return { kind: "missing" };
2761
+ text = io2.readFile(path).toString("utf8");
2759
2762
  } catch {
2760
2763
  return { kind: "unreadable" };
2761
2764
  }
@@ -2823,8 +2826,8 @@ function isProjectRecord(key, value) {
2823
2826
  if (!isRecord3(value)) return false;
2824
2827
  return value.projectKey === key && isString2(value.root) && isString2(value.transcriptFolder) && isString2(value.orgId) && isString2(value.projectSlug) && isString2(value.projectId) && PROJECT_SOURCES.has(value.projectSource) && typeof value.projectLabel === "string" && (value.developerId === void 0 || typeof value.developerId === "string") && typeof value.captureContent === "boolean" && isInstall(value.install) && isString2(value.registeredAt) && (value.subfolders === void 0 || Array.isArray(value.subfolders) && value.subfolders.every(isSubfolder));
2825
2828
  }
2826
- function readRegistry(home, io = nodeCaptureFileIO) {
2827
- return readRegistryAt(cursorPaths(home).projects, isProjectRecord, io);
2829
+ function readRegistry(home, io2 = nodeCaptureFileIO) {
2830
+ return readRegistryAt(cursorPaths(home).projects, isProjectRecord, io2);
2828
2831
  }
2829
2832
  function findProjectForWorkspace2(registry, workspaceRoots, projectDirEnv) {
2830
2833
  return findProjectForWorkspace(registry, workspaceRoots, projectDirEnv);
@@ -2880,8 +2883,8 @@ function cursorScopeFor(record, agentId) {
2880
2883
  vendor: CURSOR_VENDOR_SLUG
2881
2884
  };
2882
2885
  }
2883
- function resolveCursorPepConfig(home, io, credentialsIO) {
2884
- const record = readEnforcementRecord(home, io ?? nodeCaptureFileIO);
2886
+ function resolveCursorPepConfig(home, io2, credentialsIO) {
2887
+ const record = readEnforcementRecord(home, io2 ?? nodeCaptureFileIO);
2885
2888
  if (record === void 0 || !record.enabled) return void 0;
2886
2889
  const creds = readCredentials(home, credentialsIO, "cursor");
2887
2890
  const token = creds?.ingest_token;
@@ -3032,6 +3035,13 @@ async function evaluateViaPdp(args, fetchFn) {
3032
3035
  if (res.status === 401) return { kind: "unauthorized" };
3033
3036
  throw new PdpUnreachableError(`unexpected status ${res.status}`);
3034
3037
  }
3038
+ function agentDenialOf(body) {
3039
+ if (typeof body !== "object" || body === null) return null;
3040
+ const o = body;
3041
+ if (o.outcome !== "denied" || !("decided_by_name" in o)) return null;
3042
+ const reason = typeof o.reason === "string" ? o.reason.trim() : "";
3043
+ return reason.startsWith("Denied by ") ? reason : null;
3044
+ }
3035
3045
  async function holdForApproval(args, fetchFn) {
3036
3046
  const res = await boundedFetch(
3037
3047
  fetchFn,
@@ -3060,14 +3070,14 @@ async function holdForApproval(args, fetchFn) {
3060
3070
  } catch {
3061
3071
  throw new PdpUnreachableError("hold 200 with unparseable body");
3062
3072
  }
3063
- const outcome = parsed.outcome;
3073
+ const outcome = parsed?.outcome;
3064
3074
  if (outcome === "approved" || outcome === "denied" || outcome === "unanswered") {
3065
- return outcome;
3075
+ return { outcome, denial: agentDenialOf(parsed) };
3066
3076
  }
3067
3077
  throw new PdpUnreachableError("hold 200 with malformed outcome");
3068
3078
  }
3069
- function readCachedSnapshot(path, io = {}) {
3070
- const read = io.readFile ?? ((p) => readFileSync4(p, "utf8"));
3079
+ function readCachedSnapshot(path, io2 = {}) {
3080
+ const read = io2.readFile ?? ((p) => readFileSync4(p, "utf8"));
3071
3081
  try {
3072
3082
  const parsed = JSON.parse(read(path));
3073
3083
  return isCompiledSnapshot(parsed) ? parsed : null;
@@ -3105,7 +3115,7 @@ async function holdCursorApproval(input) {
3105
3115
  const windowSeconds = holdWindowSeconds(input.elapsedMs);
3106
3116
  input.extendDeadline?.(holdWatchdogDelayMs(input.elapsedMs));
3107
3117
  try {
3108
- const outcome = await holdForApproval(
3118
+ const held = await holdForApproval(
3109
3119
  {
3110
3120
  url: cfg.holdUrl,
3111
3121
  token: cfg.token,
@@ -3116,10 +3126,10 @@ async function holdCursorApproval(input) {
3116
3126
  },
3117
3127
  input.fetchFn
3118
3128
  );
3119
- if (outcome === "tier-disabled") {
3129
+ if (held === "tier-disabled") {
3120
3130
  return { outcome: "forbidden", windowSeconds, correlationId };
3121
3131
  }
3122
- return { outcome, windowSeconds, correlationId };
3132
+ return { outcome: held.outcome, windowSeconds, correlationId, denial: held.denial };
3123
3133
  } catch (err) {
3124
3134
  if (err instanceof PdpUnreachableError) {
3125
3135
  return { outcome: "unreachable", windowSeconds, correlationId };
@@ -3137,10 +3147,10 @@ function argsHashFor(args, key) {
3137
3147
  const digest = createHmac("sha256", key).update(sortedJson(args), "utf8").digest("hex");
3138
3148
  return `${ARGS_HASH_PREFIX}${digest.slice(0, ARGS_HASH_HEX)}`;
3139
3149
  }
3140
- function readCaptureQueueKey(home, stateDir, io = nodeCaptureFileIO) {
3150
+ function readCaptureQueueKey(home, stateDir, io2 = nodeCaptureFileIO) {
3141
3151
  let bytes;
3142
3152
  try {
3143
- bytes = io.readFile(capturePaths(home, stateDir).queueKey);
3153
+ bytes = io2.readFile(capturePaths(home, stateDir).queueKey);
3144
3154
  } catch {
3145
3155
  return void 0;
3146
3156
  }
@@ -3152,8 +3162,8 @@ function argsHashForCall(vendorTool, firstCandidateArgs, toolInput, key) {
3152
3162
  const args = isCursorMcpCall(vendorTool) ? { full_command: serializeMcpInput(toolInput) } : firstCandidateArgs;
3153
3163
  return argsHashFor(args, key);
3154
3164
  }
3155
- function readQueueKey(home, io = nodeCaptureFileIO) {
3156
- return readCaptureQueueKey(home, CURSOR_STATE_DIR, io);
3165
+ function readQueueKey(home, io2 = nodeCaptureFileIO) {
3166
+ return readCaptureQueueKey(home, CURSOR_STATE_DIR, io2);
3157
3167
  }
3158
3168
 
3159
3169
  // src/backfill/content.ts
@@ -3307,7 +3317,7 @@ var SCRUB_PATTERNS = [
3307
3317
  tier: "standard",
3308
3318
  regex: AWS_SECRET_ACCESS_KEY,
3309
3319
  // Preserve the key name (group 1) + the original separator (group 2, incl. the
3310
- // value's opening quote); redact only the 40-char value (group 3). TEC-904:
3320
+ // value's opening quote); redact only the 40-char value (group 3). Why:
3311
3321
  // emitting g[2] instead of a hard-coded `=` keeps `key: "val"` from being
3312
3322
  // rewritten to `key="val` (dangling quote) and preserves `=`-form output.
3313
3323
  placeholder: (g) => `${g[1]}${g[2]}${redacted("secret:aws-secret")}`
@@ -3320,9 +3330,9 @@ var SCRUB_PATTERNS = [
3320
3330
  tier: "standard",
3321
3331
  regex: ENV_SECRET_ASSIGNMENT,
3322
3332
  // Preserve the key name (group 1) + the original separator (group 2); redact
3323
- // only the value (group 4/6/7). TEC-904: emitting g[2] instead of a hard-coded
3333
+ // only the value (group 4/6/7). Why: emitting g[2] instead of a hard-coded
3324
3334
  // `=` keeps `key: value` from being rewritten to `key=value`.
3325
- // TEC-534: the match also consumes the value's quotes, so re-emit them around
3335
+ // Quotes: the match also consumes the value's quotes, so re-emit them around
3326
3336
  // the placeholder — g[3]/g[5] is the opening quote for the double-/single-
3327
3337
  // quoted branch, and empty for an unquoted value. Without this the output is
3328
3338
  // not valid JSON or YAML (see the exact-output tests).
@@ -3571,9 +3581,9 @@ function scrubAttributes(attributes, resolved, options = {}) {
3571
3581
  // src/capture/queue-record.ts
3572
3582
  var CONTENT_VALUE_CAP = 8192;
3573
3583
  var QUEUE_ENTRY_CAP = 1e4;
3574
- function queueEntryCount(io, folder) {
3584
+ function queueEntryCount(io2, folder) {
3575
3585
  try {
3576
- return io.readdir(folder).filter((name) => name.endsWith(".json")).length;
3586
+ return io2.readdir(folder).filter((name) => name.endsWith(".json")).length;
3577
3587
  } catch {
3578
3588
  return 0;
3579
3589
  }
@@ -3721,11 +3731,11 @@ function parseQueueEntry(text) {
3721
3731
  var SHELL_JOIN_WINDOW_MS = 3e4;
3722
3732
  var MCP_OBSERVED_WINDOW_MS = 6e4;
3723
3733
  function recentDecisions(query, windowMs) {
3724
- const io = query.io ?? nodeCaptureFileIO;
3734
+ const io2 = query.io ?? nodeCaptureFileIO;
3725
3735
  const folder = queueFolderFor(query.home, query.projectKey);
3726
3736
  let names;
3727
3737
  try {
3728
- names = io.readdir(folder);
3738
+ names = io2.readdir(folder);
3729
3739
  } catch {
3730
3740
  return [];
3731
3741
  }
@@ -3742,7 +3752,7 @@ function recentDecisions(query, windowMs) {
3742
3752
  for (const { name } of inWindow) {
3743
3753
  let text;
3744
3754
  try {
3745
- text = io.readFile(`${folder}/${name}`).toString("utf8");
3755
+ text = io2.readFile(`${folder}/${name}`).toString("utf8");
3746
3756
  } catch {
3747
3757
  continue;
3748
3758
  }
@@ -3770,17 +3780,17 @@ function readShellJoin(query) {
3770
3780
  return answer ?? { kind: "miss", liveHandoff };
3771
3781
  }
3772
3782
  function joinQueryFor(input) {
3773
- const io = input.io ?? nodeCaptureFileIO;
3774
- const key = readQueueKey(input.home, io);
3775
- const label = input.vendorTool ?? input.normalized?.vendorTool;
3783
+ const io2 = input.io ?? nodeCaptureFileIO;
3784
+ const key = readQueueKey(input.home, io2);
3785
+ const label2 = input.vendorTool ?? input.normalized?.vendorTool;
3776
3786
  const first = input.normalized?.candidates[0];
3777
3787
  return {
3778
3788
  home: input.home,
3779
- io,
3789
+ io: io2,
3780
3790
  projectKey: input.projectKey,
3781
3791
  conversationId: input.conversationId,
3782
3792
  generationId: input.generationId,
3783
- argsHash: key === void 0 || label === void 0 ? null : argsHashForCall(label, first?.args ?? {}, input.toolInput, key),
3793
+ argsHash: key === void 0 || label2 === void 0 ? null : argsHashForCall(label2, first?.args ?? {}, input.toolInput, key),
3784
3794
  nowMs: input.nowMs
3785
3795
  };
3786
3796
  }
@@ -3876,6 +3886,178 @@ function withScope(requests, scope) {
3876
3886
  return requests.map((request) => ({ ...request, scope }));
3877
3887
  }
3878
3888
 
3889
+ // src/pep/pending-decisions.ts
3890
+ import { randomUUID } from "crypto";
3891
+ import { mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync5, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
3892
+ import { dirname as dirname4, join as join7 } from "path";
3893
+
3894
+ // ../policy-engine/src/action-shape.ts
3895
+ import { createHash as createHash3 } from "crypto";
3896
+ var ACTION_SHAPE_MAX_LENGTH = 512;
3897
+ var MAX_TOKENS = 24;
3898
+ var ARG = "<arg>";
3899
+ var SUBCOMMAND_DEPTH = {
3900
+ git: 1,
3901
+ docker: 1,
3902
+ kubectl: 1,
3903
+ npm: 1,
3904
+ pnpm: 1,
3905
+ yarn: 1,
3906
+ terraform: 1,
3907
+ aws: 2,
3908
+ gcloud: 2,
3909
+ gh: 2,
3910
+ helm: 1
3911
+ };
3912
+ var SECOND_LEVEL_AFTER = {
3913
+ docker: /* @__PURE__ */ new Set(["volume", "network", "image", "container", "compose", "system", "builder"])
3914
+ };
3915
+ var SYSTEM_BIN = /^\/(usr\/(local\/)?)?s?bin\/|^\/opt\/homebrew\/bin\//;
3916
+ var SUBCOMMAND_WORD = /^[a-z][a-z0-9-]{0,31}$/;
3917
+ var PROGRAM_WORD = /^[A-Za-z0-9._+-]{1,64}$/;
3918
+ function shapeFlag(token) {
3919
+ const eq = token.indexOf("=");
3920
+ const name = eq === -1 ? token : token.slice(0, eq);
3921
+ if (name.startsWith("--")) {
3922
+ return /^--[a-z0-9][a-z0-9-]{0,40}$/i.test(name) ? `${name}${eq === -1 ? "" : `=${ARG}`}` : ARG;
3923
+ }
3924
+ if (/^-[A-Za-z]{1,2}$/.test(name)) return name;
3925
+ if (/^-[A-Za-z]/.test(name)) return `${name.slice(0, 2)}${ARG}`;
3926
+ return ARG;
3927
+ }
3928
+ function shapeProgram(token) {
3929
+ if (token.includes("/")) {
3930
+ if (!SYSTEM_BIN.test(token)) return ARG;
3931
+ const base = token.slice(token.lastIndexOf("/") + 1);
3932
+ return PROGRAM_WORD.test(base) ? base.toLowerCase() : ARG;
3933
+ }
3934
+ return PROGRAM_WORD.test(token) ? token.toLowerCase() : ARG;
3935
+ }
3936
+ function firstCommand(command) {
3937
+ const head = command.split(/&&|\|\||;|\||\n/)[0] ?? "";
3938
+ const tokens = head.trim().split(/\s+/).filter(Boolean);
3939
+ let i = 0;
3940
+ while (i < tokens.length) {
3941
+ const t = tokens[i] ?? "";
3942
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t)) {
3943
+ i++;
3944
+ continue;
3945
+ }
3946
+ if (t === "sudo" || t === "env" || t === "command" || t === "exec" || t === "time") {
3947
+ i++;
3948
+ continue;
3949
+ }
3950
+ break;
3951
+ }
3952
+ return tokens.slice(i, i + MAX_TOKENS);
3953
+ }
3954
+ function shapeCommand(command) {
3955
+ const stripped = command.replace(/^\s*cd\s+\S+\s*(&&|;)\s*/, "");
3956
+ const tokens = firstCommand(stripped);
3957
+ if (tokens.length === 0) return null;
3958
+ const program = shapeProgram(tokens[0] ?? "");
3959
+ const out = [program];
3960
+ let subcommandsLeft = SUBCOMMAND_DEPTH[program] ?? 0;
3961
+ const secondLevel = SECOND_LEVEL_AFTER[program];
3962
+ for (const token of tokens.slice(1)) {
3963
+ if (token.startsWith("-") && token.length > 1) {
3964
+ out.push(shapeFlag(token));
3965
+ subcommandsLeft = 0;
3966
+ continue;
3967
+ }
3968
+ if (subcommandsLeft > 0 && SUBCOMMAND_WORD.test(token)) {
3969
+ out.push(token);
3970
+ subcommandsLeft--;
3971
+ if (subcommandsLeft === 0 && secondLevel?.has(token) && out.length === 2) {
3972
+ subcommandsLeft = 1;
3973
+ }
3974
+ continue;
3975
+ }
3976
+ subcommandsLeft = 0;
3977
+ out.push(ARG);
3978
+ }
3979
+ return clamp(out.join(" "));
3980
+ }
3981
+ function clamp(shape) {
3982
+ if (shape.length <= ACTION_SHAPE_MAX_LENGTH) return shape;
3983
+ const cut = shape.slice(0, ACTION_SHAPE_MAX_LENGTH);
3984
+ return cut.slice(0, cut.lastIndexOf(" "));
3985
+ }
3986
+ function redactedActionShape(tool, args) {
3987
+ if (tool.startsWith("mcp__")) return null;
3988
+ const command = args.full_command ?? args.detail;
3989
+ if (typeof command === "string" && command.trim() !== "") {
3990
+ if (tool === "WebSearch") return null;
3991
+ return shapeCommand(command);
3992
+ }
3993
+ if (typeof args.file_path === "string" && args.file_path !== "") return "<path>";
3994
+ return null;
3995
+ }
3996
+
3997
+ // src/pep/pending-decisions.ts
3998
+ var PENDING_DECISIONS_CAP = 500;
3999
+ var DIR_MODE = 448;
4000
+ var FILE_MODE = 384;
4001
+ var LABEL_MAX = 255;
4002
+ var realIO = {
4003
+ mkdir: (p, mode) => mkdirSync4(p, { recursive: true, mode }),
4004
+ writeFile: (p, content, mode) => writeFileSync3(p, content, { mode }),
4005
+ readDir: (p) => readdirSync2(p),
4006
+ readFile: (p) => readFileSync5(p, "utf8"),
4007
+ remove: (p) => rmSync2(p, { force: true })
4008
+ };
4009
+ function io(over) {
4010
+ return { ...realIO, ...over ?? {} };
4011
+ }
4012
+ function pendingDecisionsDir(snapshotPath) {
4013
+ return join7(dirname4(snapshotPath), "pending-decisions");
4014
+ }
4015
+ function label(v) {
4016
+ return typeof v === "string" && v.length > 0 && v.length <= LABEL_MAX ? v : void 0;
4017
+ }
4018
+ function shapeOnlyArgs(tool, args) {
4019
+ const shape = redactedActionShape(tool, args);
4020
+ if (shape === null) return {};
4021
+ if (shape === "<path>" && args.full_command === void 0) return { file_path: shape };
4022
+ return { full_command: shape };
4023
+ }
4024
+ function toUploadItem(d, now = /* @__PURE__ */ new Date(), id = randomUUID()) {
4025
+ const correlationId = label(d.request.correlation_id);
4026
+ const sessionId = label(d.request.session_id);
4027
+ return {
4028
+ id,
4029
+ policy_id: d.policyId,
4030
+ verdict: d.verdict,
4031
+ tool: d.request.tool.slice(0, LABEL_MAX),
4032
+ args: shapeOnlyArgs(d.request.tool, d.request.args),
4033
+ ...d.request.kind !== void 0 ? { kind: d.request.kind } : {},
4034
+ ...d.request.scope !== void 0 ? { scope: d.request.scope } : {},
4035
+ ...sessionId !== void 0 ? { session_id: sessionId } : {},
4036
+ ...correlationId !== void 0 ? { correlation_id: correlationId } : {},
4037
+ decided_at: now.toISOString()
4038
+ };
4039
+ }
4040
+ function queueOfflineDecision(snapshotPath, d, opts = {}) {
4041
+ try {
4042
+ const fs = io(opts.io);
4043
+ const dir = pendingDecisionsDir(snapshotPath);
4044
+ fs.mkdir(dir, DIR_MODE);
4045
+ let count = 0;
4046
+ try {
4047
+ count = fs.readDir(dir).filter((f) => f.endsWith(".json")).length;
4048
+ } catch {
4049
+ count = 0;
4050
+ }
4051
+ if (count >= PENDING_DECISIONS_CAP) return false;
4052
+ const item = toUploadItem(d, opts.now);
4053
+ const stamp = String(Date.parse(item.decided_at)).padStart(15, "0");
4054
+ fs.writeFile(join7(dir, `${stamp}-${item.id}.json`), JSON.stringify(item), FILE_MODE);
4055
+ return true;
4056
+ } catch {
4057
+ return false;
4058
+ }
4059
+ }
4060
+
3879
4061
  // src/pep/hook-shim.ts
3880
4062
  var HOOK_OUTCOMES = Object.keys({
3881
4063
  deny: 0,
@@ -3883,6 +4065,7 @@ var HOOK_OUTCOMES = Object.keys({
3883
4065
  warn: 0,
3884
4066
  none: 0
3885
4067
  });
4068
+ var REVIEWER_DENIED = "Denied by an AgentTrail reviewer.";
3886
4069
  var NO_DECISION = { decision: "none", reason: "" };
3887
4070
  var MAX_DETAIL_LEN = 8192;
3888
4071
  var PEP_VENDOR = "claude-code";
@@ -3916,7 +4099,7 @@ var handleApproval = async (payload, verdict, ctx) => {
3916
4099
  }
3917
4100
  ctx.extendDeadline?.(PEP_HOLD_WATCHDOG_MS);
3918
4101
  try {
3919
- const outcome = await holdForApproval(
4102
+ const held = await holdForApproval(
3920
4103
  {
3921
4104
  url: ctx.cfg.holdUrl,
3922
4105
  token: ctx.cfg.token,
@@ -3927,14 +4110,14 @@ var handleApproval = async (payload, verdict, ctx) => {
3927
4110
  },
3928
4111
  ctx.fetchFn
3929
4112
  );
3930
- if (outcome === "tier-disabled") {
4113
+ if (held === "tier-disabled") {
3931
4114
  return NO_DECISION;
3932
4115
  }
3933
- if (outcome === "approved") {
4116
+ if (held.outcome === "approved") {
3934
4117
  return NO_DECISION;
3935
4118
  }
3936
- if (outcome === "denied") {
3937
- return { decision: "deny", reason: "Denied by an AgentTrail reviewer." };
4119
+ if (held.outcome === "denied") {
4120
+ return { decision: "deny", reason: held.denial ?? REVIEWER_DENIED };
3938
4121
  }
3939
4122
  return {
3940
4123
  decision: "ask",
@@ -3987,6 +4170,8 @@ function buildPdpRequest(payload, scope) {
3987
4170
  }
3988
4171
  const agentId = scope?.agent_id;
3989
4172
  const projectId = scope?.project_id;
4173
+ const correlationId = pdpLabel(payload.tool_use_id);
4174
+ const sessionId = pdpLabel(payload.session_id);
3990
4175
  return {
3991
4176
  tool,
3992
4177
  args,
@@ -3994,9 +4179,14 @@ function buildPdpRequest(payload, scope) {
3994
4179
  ...agentId !== void 0 ? { agent_id: agentId } : {},
3995
4180
  ...projectId !== void 0 ? { project_id: projectId } : {},
3996
4181
  vendor: PEP_VENDOR
3997
- }
4182
+ },
4183
+ ...correlationId !== void 0 ? { correlation_id: correlationId } : {},
4184
+ ...sessionId !== void 0 ? { session_id: sessionId } : {}
3998
4185
  };
3999
4186
  }
4187
+ function pdpLabel(value) {
4188
+ return typeof value === "string" && value.length > 0 && value.length <= 255 ? value : void 0;
4189
+ }
4000
4190
  async function mapVerdict(payload, response, cfg, deps) {
4001
4191
  switch (response.verdict) {
4002
4192
  case "allow": {
@@ -4021,17 +4211,34 @@ function failClosedViaSnapshot(_payload, request, cfg, deps) {
4021
4211
  reason: "AgentTrail PDP is unreachable and no local policy snapshot is cached; failing closed."
4022
4212
  };
4023
4213
  }
4024
- const { verdict, decidingName } = evaluateLocally(snapshot, request, cfg.orgId);
4214
+ const { verdict, decidingName, decidingPolicyId, decidingGuidance } = evaluateLocally(
4215
+ snapshot,
4216
+ request,
4217
+ cfg.orgId
4218
+ );
4219
+ if ((verdict === "deny" || verdict === "require_approval") && decidingPolicyId) {
4220
+ (deps.queueOffline ?? queueOfflineDecision)(cfg.snapshotPath, {
4221
+ policyId: decidingPolicyId,
4222
+ verdict,
4223
+ request
4224
+ });
4225
+ }
4025
4226
  if (verdict === "deny") {
4026
4227
  return {
4027
4228
  decision: "deny",
4028
- reason: `Blocked by local AgentTrail policy${quoted(decidingName)} (PDP unreachable; evaluated against the cached snapshot).`
4229
+ reason: withGuidance(
4230
+ `Blocked by local AgentTrail policy${quoted(decidingName)} (PDP unreachable; evaluated against the cached snapshot).`,
4231
+ decidingGuidance
4232
+ )
4029
4233
  };
4030
4234
  }
4031
4235
  if (verdict === "require_approval") {
4032
4236
  return {
4033
4237
  decision: "ask",
4034
- reason: `Approval required by local AgentTrail policy${quoted(decidingName)} (PDP unreachable; deferring to you).`
4238
+ reason: withGuidance(
4239
+ `Approval required by local AgentTrail policy${quoted(decidingName)} (PDP unreachable; deferring to you).`,
4240
+ decidingGuidance
4241
+ )
4035
4242
  };
4036
4243
  }
4037
4244
  return NO_DECISION;
@@ -4039,6 +4246,17 @@ function failClosedViaSnapshot(_payload, request, cfg, deps) {
4039
4246
  function quoted(name) {
4040
4247
  return name ? ` "${name}"` : "";
4041
4248
  }
4249
+ function guidanceOf(entry) {
4250
+ const raw = entry.agent_guidance;
4251
+ if (typeof raw !== "string") return null;
4252
+ const trimmed2 = raw.trim();
4253
+ if (trimmed2 === "") return null;
4254
+ const chars = [...trimmed2];
4255
+ return chars.length <= AGENT_GUIDANCE_MAX_CHARS ? trimmed2 : chars.slice(0, AGENT_GUIDANCE_MAX_CHARS).join("");
4256
+ }
4257
+ function withGuidance(sentence, guidance) {
4258
+ return guidance ? `${sentence} ${guidance}` : sentence;
4259
+ }
4042
4260
  function evaluateLocally(snapshot, request, orgId) {
4043
4261
  const ctx = buildEvaluationContext(request, orgId ?? NIL_ORG_ID);
4044
4262
  const matches = [];
@@ -4057,12 +4275,20 @@ function evaluateLocally(snapshot, request, orgId) {
4057
4275
  }
4058
4276
  const { verdict, policyId } = strongestVerdict(matches);
4059
4277
  const names = {};
4060
- for (const [id, entry] of byId) names[id] = entry.name;
4278
+ const guidance = {};
4279
+ for (const [id, entry] of byId) {
4280
+ names[id] = entry.name;
4281
+ const g = guidanceOf(entry);
4282
+ if (g !== null) guidance[id] = g;
4283
+ }
4061
4284
  return {
4062
4285
  verdict,
4063
4286
  decidingName: policyId ? byId.get(policyId)?.name ?? null : null,
4287
+ decidingPolicyId: policyId,
4288
+ decidingGuidance: policyId ? guidance[policyId] ?? null : null,
4064
4289
  matches,
4065
- names
4290
+ names,
4291
+ guidance
4066
4292
  };
4067
4293
  }
4068
4294
  async function decide(payload, cfg, deps) {
@@ -4072,7 +4298,7 @@ async function decide(payload, cfg, deps) {
4072
4298
  if (!cfg.url || !cfg.token) {
4073
4299
  return {
4074
4300
  decision: "deny",
4075
- reason: "AgentTrail enforcement is enabled but misconfigured (missing PDP URL or token); failing closed. Re-run `npx -y @agenttrail/cli@latest setup --agent claude`."
4301
+ 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."
4076
4302
  };
4077
4303
  }
4078
4304
  const request = buildPdpRequest(payload, cfg.scope);
@@ -4308,9 +4534,12 @@ function matchesOf(response) {
4308
4534
  }
4309
4535
  return { matches, names };
4310
4536
  }
4311
- function cursorReason(verdict, name) {
4537
+ function cursorReason(verdict, name, guidance = null) {
4312
4538
  const named = name === null ? "" : ` "${name}"`;
4313
- return verdict === "deny" ? `Blocked by AgentTrail policy${named}.` : `Approval required by AgentTrail policy${named}.`;
4539
+ return withGuidance(
4540
+ verdict === "deny" ? `Blocked by AgentTrail policy${named}.` : `Approval required by AgentTrail policy${named}.`,
4541
+ guidance
4542
+ );
4314
4543
  }
4315
4544
  async function decideCursorCandidates(requests, cfg, deps) {
4316
4545
  const settled = await Promise.all(
@@ -4374,7 +4603,15 @@ function outcomeOf(perCandidate, via) {
4374
4603
  }
4375
4604
  const names = Object.assign({}, ...perCandidate.map((result) => result.names));
4376
4605
  const name = combined.policyId === null ? null : names[combined.policyId] ?? null;
4377
- const message = cursorReason(combined.verdict, name);
4606
+ const guidance = Object.assign(
4607
+ {},
4608
+ ...perCandidate.map((result) => result.guidance ?? {})
4609
+ );
4610
+ const message = cursorReason(
4611
+ combined.verdict,
4612
+ name,
4613
+ combined.policyId === null ? null : guidance[combined.policyId] ?? null
4614
+ );
4378
4615
  if (combined.verdict === "deny") {
4379
4616
  return {
4380
4617
  outcome: { kind: "deny", message },
@@ -4392,12 +4629,12 @@ function outcomeOf(perCandidate, via) {
4392
4629
  via
4393
4630
  };
4394
4631
  }
4395
- function decideCursorShell(join7, cfg, deps, request) {
4396
- if (join7.kind === "handoff") {
4632
+ function decideCursorShell(join8, cfg, deps, request) {
4633
+ if (join8.kind === "handoff") {
4397
4634
  return { kind: "approval", message: "AgentTrail is waiting for approval of this command." };
4398
4635
  }
4399
- if (join7.kind === "decided") return { kind: "none" };
4400
- if (join7.liveHandoff) {
4636
+ if (join8.kind === "decided") return { kind: "none" };
4637
+ if (join8.liveHandoff) {
4401
4638
  return { kind: "approval", message: "AgentTrail is waiting for approval in this turn." };
4402
4639
  }
4403
4640
  const snapshot = readCachedSnapshot(cfg.snapshotPath, deps.snapshotIO);
@@ -4406,14 +4643,17 @@ function decideCursorShell(join7, cfg, deps, request) {
4406
4643
  }
4407
4644
  const local = evaluateLocally(snapshot, request, cfg.orgId);
4408
4645
  if (local.verdict === "allow") return { kind: "none" };
4409
- return { kind: "approval", message: cursorReason(local.verdict, local.decidingName) };
4646
+ return {
4647
+ kind: "approval",
4648
+ message: cursorReason(local.verdict, local.decidingName, local.decidingGuidance)
4649
+ };
4410
4650
  }
4411
4651
  function outcomeOfHold(result) {
4412
4652
  switch (result.outcome) {
4413
4653
  case "approved":
4414
4654
  return { kind: "none" };
4415
4655
  case "denied":
4416
- return { kind: "deny", message: "Denied by an AgentTrail reviewer." };
4656
+ return { kind: "deny", message: result.denial ?? REVIEWER_DENIED };
4417
4657
  case "forbidden":
4418
4658
  return { kind: "none" };
4419
4659
  case "unreachable":
@@ -4515,7 +4755,7 @@ async function answerCursor(deps, startedAtMs) {
4515
4755
  }
4516
4756
  if (event === "beforeShellExecution") {
4517
4757
  const request = normalized?.candidates[0];
4518
- const join7 = (deps.shellJoin ?? readShellJoin)(
4758
+ const join8 = (deps.shellJoin ?? readShellJoin)(
4519
4759
  joinQueryFor({
4520
4760
  home: deps.home,
4521
4761
  io: deps.io,
@@ -4529,7 +4769,7 @@ async function answerCursor(deps, startedAtMs) {
4529
4769
  })
4530
4770
  );
4531
4771
  const outcome = decideCursorShell(
4532
- join7,
4772
+ join8,
4533
4773
  cfg,
4534
4774
  deps,
4535
4775
  request === void 0 ? void 0 : { tool: request.tool, args: { ...request.args } }
@@ -4538,17 +4778,17 @@ async function answerCursor(deps, startedAtMs) {
4538
4778
  verdict: verdictOf(outcome),
4539
4779
  // This checkpoint asks no one: it answers from the queue, or from the cached rules
4540
4780
  // when the queue has nothing to say.
4541
- via: join7.kind === "miss" ? "cached-rules" : "pdp"
4781
+ via: join8.kind === "miss" ? "cached-rules" : "pdp"
4542
4782
  });
4543
4783
  }
4544
4784
  const requests = buildCursorPdpRequest(payload);
4545
4785
  if (requests === void 0 || normalized === void 0) {
4546
- const label = cursorVendorTool(payload);
4547
- const mcp = label?.startsWith(CURSOR_MCP_PREFIX);
4786
+ const label2 = cursorVendorTool(payload);
4787
+ const mcp = label2?.startsWith(CURSOR_MCP_PREFIX);
4548
4788
  return record(CURSOR_NO_OPINION, {
4549
4789
  verdict: "observed",
4550
4790
  via: "pdp",
4551
- ...mcp === true && label !== void 0 ? { vendorTool: label, toolUseId: correlationIdFor(payload.tool_use_id) } : (
4791
+ ...mcp === true && label2 !== void 0 ? { vendorTool: label2, toolUseId: correlationIdFor(payload.tool_use_id) } : (
4552
4792
  // Not an MCP call and not mappable: nothing to record it under, and nothing
4553
4793
  // will look for it.
4554
4794
  {}
@@ -4682,6 +4922,7 @@ export {
4682
4922
  decide,
4683
4923
  dispatchHookRun,
4684
4924
  evaluateLocally,
4925
+ guidanceOf,
4685
4926
  handleApproval,
4686
4927
  parsePayload,
4687
4928
  runCodexShim,