@modootoday/pmcp 0.18.4 → 0.19.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.
Files changed (103) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.mcp.json +1 -1
  5. package/dist/{apply-75UWIUVQ.js → apply-IPTASVRS.js} +16 -17
  6. package/dist/{broadcast-CBMVOV3G.js → broadcast-56NPEJWM.js} +3 -4
  7. package/dist/{chunk-ARA4VDHD.js → chunk-2DAC45ZT.js} +2 -2
  8. package/dist/{chunk-JS5RTH4I.js → chunk-2Q6MNGU5.js} +2 -2
  9. package/dist/{chunk-ZWLUH3F2.js → chunk-2W6CEJD7.js} +2 -2
  10. package/dist/{chunk-YRGDWUFY.js → chunk-3BLHIEAK.js} +2 -2
  11. package/dist/{chunk-R26RWSFW.js → chunk-3CLLHFP7.js} +2 -2
  12. package/dist/{chunk-HE2C2S5A.js → chunk-3H5FZCKX.js} +3 -3
  13. package/dist/{chunk-TFRJ5QOS.js → chunk-7FAA32PB.js} +3 -3
  14. package/dist/{chunk-DCU2EXQV.js → chunk-D5D3V6RU.js} +4 -4
  15. package/dist/{chunk-LTZH5E3G.js → chunk-DHAPQUEF.js} +235 -30
  16. package/dist/{chunk-LBXO4VPG.js → chunk-E4FJOLPJ.js} +6 -3
  17. package/dist/{chunk-OPYFEHKG.js → chunk-G7JONWL4.js} +29 -1
  18. package/dist/{chunk-4JUSGIMX.js → chunk-G7NN23YK.js} +2 -2
  19. package/dist/chunk-GPSOPGJA.js +7 -0
  20. package/dist/{chunk-LGO2SZAS.js → chunk-IKJOXDCF.js} +2 -2
  21. package/dist/{chunk-QEW4J3IZ.js → chunk-ISNRDHSD.js} +2 -2
  22. package/dist/{chunk-S3PIAMXV.js → chunk-J5XQW2CM.js} +68 -8
  23. package/dist/{chunk-LFR245MZ.js → chunk-JAICIL6H.js} +5 -5
  24. package/dist/{chunk-GZHHEHKY.js → chunk-JJBSYUSQ.js} +19 -7
  25. package/dist/{chunk-YSUINA5Q.js → chunk-MB72PZH7.js} +8 -8
  26. package/dist/{chunk-3CA3NNVH.js → chunk-MFPQDXUQ.js} +5 -5
  27. package/dist/{chunk-VQ2HEGWH.js → chunk-OKW7VKNQ.js} +2 -2
  28. package/dist/{chunk-6UXJ62XJ.js → chunk-OWW5VY4D.js} +3 -3
  29. package/dist/{chunk-OB3P5RMN.js → chunk-U2FPMGEM.js} +2 -2
  30. package/dist/{chunk-XELAZAIM.js → chunk-UD3BEEBQ.js} +54 -12
  31. package/dist/{chunk-EAWPJHJ7.js → chunk-UGODVKBJ.js} +2 -2
  32. package/dist/{chunk-MSOZPOPX.js → chunk-UOLV2AWA.js} +7 -3
  33. package/dist/{chunk-FBIDDE3N.js → chunk-XKGS2FNF.js} +71 -51
  34. package/dist/{chunk-XMXBE5IQ.js → chunk-XS2QM6AT.js} +5 -5
  35. package/dist/{chunk-45Y3KZ3Q.js → chunk-Y65MO2SS.js} +87 -20
  36. package/dist/{chunk-DAR6RGRN.js → chunk-YTSJRA4Z.js} +2 -2
  37. package/dist/{chunk-QBJC4DRP.js → chunk-ZYMJV7YX.js} +14 -14
  38. package/dist/{cli-ZN7ZVDEZ.js → cli-MUP2NSXT.js} +10 -9
  39. package/dist/{cli-MI4ZCAZ3.js → cli-T5LHBUY2.js} +8 -8
  40. package/dist/cli.js +3 -3
  41. package/dist/{completion-WYJAKJE4.js → completion-ZY5P443T.js} +2 -2
  42. package/dist/{diagnostics-ADIVFSBW.js → diagnostics-KUNS6LCZ.js} +12 -12
  43. package/dist/{doctor-BBCS4DF5.js → doctor-UH7KEOSO.js} +18 -19
  44. package/dist/{entry-DMOTX4SS.js → entry-DOUDMRO2.js} +10 -10
  45. package/dist/{exec-mcp-OBUM3DVW.js → exec-mcp-TGW6FXGC.js} +13 -14
  46. package/dist/{harness-6AUE3I4Q.js → harness-7HC6UR2D.js} +3 -3
  47. package/dist/harness-launch-gate.js +4 -4
  48. package/dist/harness-worker.js +6 -6
  49. package/dist/hook-body.js +446 -278
  50. package/dist/{hook-spec-C5fWTSCH.d.ts → hook-spec-0aGt29Pg.d.ts} +22 -2
  51. package/dist/{hooks-HLPQPVRY.js → hooks-L2MKB75Z.js} +3 -3
  52. package/dist/{host-5Q3X6OY7.js → host-OAQZTYII.js} +15 -16
  53. package/dist/{host-LGSWU3PJ.js → host-QSBXKTWT.js} +7 -7
  54. package/dist/{host-run-4NMQQASQ.js → host-run-HFOADX32.js} +10 -6
  55. package/dist/http.js +1 -1
  56. package/dist/{import-mcp-WU7TO2RT.js → import-mcp-BCYXJAIU.js} +11 -12
  57. package/dist/index.d.ts +2 -2
  58. package/dist/index.js +17 -18
  59. package/dist/{init-XA6XXLGA.js → init-NVJVNZOD.js} +2 -2
  60. package/dist/{invoke-CYQZYU5T.js → invoke-KVTEPXSC.js} +8 -8
  61. package/dist/{list-FNGXY5D7.js → list-2VRPMASP.js} +13 -14
  62. package/dist/{logout-N753FBZP.js → logout-6T5ZDLHQ.js} +12 -13
  63. package/dist/{logs-TBUA4UWU.js → logs-H3RPKNTE.js} +3 -4
  64. package/dist/{mailbox-BMTZOSZ7.js → mailbox-O3MX6QPF.js} +3 -4
  65. package/dist/{mainline-KAD2ERLP.js → mainline-DG75NLBS.js} +306 -57
  66. package/dist/{mcp-GR4VXKTG.js → mcp-7UKG5TD3.js} +2 -2
  67. package/dist/{pause-7LILUVGL.js → pause-2HQ7CKMR.js} +3 -4
  68. package/dist/project/hook-adapter.d.ts +1 -1
  69. package/dist/{project-OEBACWEX.js → project-BPKQOSKQ.js} +4 -4
  70. package/dist/{resume-26VFAAMH.js → resume-ETFTR5V3.js} +3 -4
  71. package/dist/{run-MDRUOEFL.js → run-5JD62E7R.js} +11 -12
  72. package/dist/{run-7XNGPU2I.js → run-WGIRM6Z7.js} +4 -4
  73. package/dist/{serve-HXHNWKEK.js → serve-J575WVIU.js} +3 -3
  74. package/dist/setup-T6T2PFC4.js +20 -0
  75. package/dist/{start-login-PWCEKNED.js → start-login-2AYCHWLV.js} +12 -13
  76. package/dist/{status-QFOBQ42J.js → status-2YWTJOMH.js} +20 -27
  77. package/dist/{status-54IYX2FN.js → status-425ZKIE6.js} +12 -13
  78. package/dist/{status-RO55QPKV.js → status-GPSLH4VO.js} +3 -4
  79. package/dist/stdio.js +2 -2
  80. package/dist/{sweep-35LGQTTO.js → sweep-VY2TNOO5.js} +3 -4
  81. package/dist/{test-36ZUVALT.js → test-XBLZOX52.js} +50 -15
  82. package/dist/{tui-CSRW4DN2.js → tui-WNVBHP65.js} +4 -4
  83. package/dist/{unbroadcast-5QNGAJR2.js → unbroadcast-RKTBP57G.js} +3 -4
  84. package/dist/{worker-EODWT4KK.js → worker-CGF3UIJE.js} +8 -8
  85. package/dist/{worktree-create-PZSRB7PH.js → worktree-create-NO4UOOEP.js} +2 -2
  86. package/dist/{worktree-list-JYB6VXLW.js → worktree-list-NEIDD66X.js} +4 -4
  87. package/dist/{worktree-sync-UF5CXPWV.js → worktree-sync-W4BDDLRO.js} +8 -9
  88. package/docs/commands.md +1 -1
  89. package/docs/git-workflow.md +58 -1
  90. package/docs/hooks.md +29 -0
  91. package/docs/project-configuration.md +7 -7
  92. package/gemini-extension.json +2 -2
  93. package/mcp.json +1 -1
  94. package/package.json +5 -5
  95. package/plugin.json +1 -1
  96. package/plugins/pmcp/.claude-plugin/plugin.json +1 -1
  97. package/plugins/pmcp/.mcp.json +1 -1
  98. package/plugins/pmcp/gemini-extension.json +2 -2
  99. package/plugins/pmcp/mcp.json +1 -1
  100. package/plugins/pmcp/plugin.json +1 -1
  101. package/dist/chunk-26WLNWDG.js +0 -93
  102. package/dist/chunk-MZCRCMEY.js +0 -7
  103. package/dist/setup-DTKZLZUT.js +0 -18
package/dist/hook-body.js CHANGED
@@ -1,9 +1,56 @@
1
1
  // src/hooks/entry.ts
2
- import { dirname as dirname9, resolve as resolve18 } from "node:path";
2
+ import { dirname as dirname12, resolve as resolve19 } from "node:path";
3
3
 
4
- // src/hooks/lazy/crypto.ts
5
- var real = () => process.getBuiltinModule("node:crypto");
6
- var createHash = ((...args) => real().createHash(...args));
4
+ // src/hooks/contract.ts
5
+ var NEUTRAL_EVENTS = [
6
+ "session_start",
7
+ "prompt",
8
+ "before_tool",
9
+ "after_tool",
10
+ "stop",
11
+ "session_end",
12
+ "notification"
13
+ ];
14
+
15
+ // src/hooks/dispatch/compose.ts
16
+ var RANK = { allow: 0, ask: 1, deny: 2 };
17
+ function applyMode(id, decision, mode) {
18
+ if (!decision.verdict || decision.verdict === "allow") return decision;
19
+ if (mode === "off") return {};
20
+ if (mode === "graded") return decision;
21
+ if (mode === "warn") {
22
+ const note = `pmcp ${id}: ${decision.reason ?? "would refuse this call"}`;
23
+ return { context: [...decision.context ?? [], note] };
24
+ }
25
+ return { ...decision, verdict: mode };
26
+ }
27
+ function compose(decisions) {
28
+ let winner = {};
29
+ const context = [];
30
+ const feedback = [];
31
+ for (const decision of decisions) {
32
+ context.push(...decision.context ?? []);
33
+ if (decision.feedback) feedback.push(decision.feedback);
34
+ if (!decision.verdict) continue;
35
+ if (!winner.verdict || RANK[decision.verdict] > RANK[winner.verdict])
36
+ winner = decision;
37
+ }
38
+ return {
39
+ ...winner.verdict ? { verdict: winner.verdict } : {},
40
+ ...winner.reason ? { reason: winner.reason } : {},
41
+ ...context.length > 0 ? { context } : {},
42
+ ...feedback.length > 0 ? { feedback: feedback.join("\n\n") } : {}
43
+ };
44
+ }
45
+ function lower(decision, lowering) {
46
+ if (decision.verdict !== "ask" || !lowering) return decision;
47
+ if (lowering.ask === "deny") return { ...decision, verdict: "deny" };
48
+ const { verdict: _verdict, reason, ...rest } = decision;
49
+ return {
50
+ ...rest,
51
+ context: [...decision.context ?? [], `pmcp: ${reason ?? "would ask"}`]
52
+ };
53
+ }
7
54
 
8
55
  // builtin-fs:node:fs
9
56
  var fs = process.getBuiltinModule("node:fs");
@@ -109,143 +156,11 @@ var W_OK = fs.W_OK;
109
156
  var X_OK = fs.X_OK;
110
157
  var constants = fs.constants;
111
158
 
112
- // src/hooks/compiled.ts
113
- import { join as join2 } from "node:path";
114
-
115
- // src/hooks/integrity-cache.ts
116
- import { homedir } from "node:os";
117
- import { dirname, join } from "node:path";
118
- var LIMIT = 64;
119
- function cacheFile() {
120
- const base = process.env["XDG_CACHE_HOME"] || join(homedir(), ".cache");
121
- return join(base, "pmcp", "hook-verified.json");
122
- }
123
- function readCache() {
124
- try {
125
- return JSON.parse(readFileSync(cacheFile(), "utf8"));
126
- } catch {
127
- return {};
128
- }
129
- }
130
- function stampOf(paths) {
131
- try {
132
- return paths.map((path) => {
133
- const stat3 = statSync(path, { bigint: true });
134
- return `${stat3.ino}:${stat3.size}:${stat3.ctimeNs}`;
135
- }).join("|");
136
- } catch {
137
- return null;
138
- }
139
- }
140
- function verifiedBefore(key, stamp, sha) {
141
- const entry = readCache()[key];
142
- return entry?.stamp === stamp && entry.sha === sha;
143
- }
144
- function rememberVerified(key, stamp, sha) {
145
- try {
146
- const kept = Object.entries(readCache()).filter(([path]) => path !== key);
147
- const cache = Object.fromEntries([
148
- ...kept.slice(-(LIMIT - 1)),
149
- [key, { stamp, sha }]
150
- ]);
151
- const file2 = cacheFile();
152
- mkdirSync(dirname(file2), { recursive: true });
153
- const temporary = `${file2}.${process.pid}.tmp`;
154
- writeFileSync(temporary, JSON.stringify(cache), { mode: 384 });
155
- renameSync(temporary, file2);
156
- } catch {
157
- }
158
- }
159
-
160
- // src/hooks/compiled.ts
161
- var HOOK_DIRECTORY = ".agents/pmcp-hooks";
162
- var POLICY_FILE = `${HOOK_DIRECTORY}/policy.json`;
163
- var HOOK_FILE = `${HOOK_DIRECTORY}/hook.mjs`;
164
- var HOOK_BODY_FILE = `${HOOK_DIRECTORY}/hook-body.mjs`;
165
- var LOCK_FILE = "pmcp.lock";
166
- function sha256(text9) {
167
- return createHash("sha256").update(text9).digest("hex");
168
- }
169
- var PolicyIntegrityError = class extends Error {
170
- };
171
- var MISMATCH = "policy.json does not match pmcp.lock; review the change and run pmcp project";
172
- function readCompiled(root) {
173
- const policyPath = join2(root, POLICY_FILE);
174
- const files2 = [policyPath, join2(root, LOCK_FILE)];
175
- const before2 = stampOf(files2);
176
- const text9 = readFileSync(policyPath, "utf8");
177
- const lock = JSON.parse(readFileSync(files2[1], "utf8"));
178
- const entry = lock.outputs?.find((output) => output.path === POLICY_FILE);
179
- const expected = typeof entry?.sha256 === "string" ? entry.sha256 : null;
180
- if (expected === null) throw new PolicyIntegrityError(MISMATCH);
181
- const stamp = before2 !== null && before2 === stampOf(files2) ? before2 : null;
182
- const cached = stamp !== null && verifiedBefore(policyPath, stamp, expected);
183
- if (!cached) {
184
- if (expected !== sha256(text9)) throw new PolicyIntegrityError(MISMATCH);
185
- if (stamp !== null) rememberVerified(policyPath, stamp, expected);
186
- }
187
- const compiled = JSON.parse(text9);
188
- if (compiled.contract !== 2)
189
- throw new PolicyIntegrityError("Unknown policy.json contract");
190
- return { ...compiled, policySha256: expected };
191
- }
192
-
193
- // src/hooks/contract.ts
194
- var NEUTRAL_EVENTS = [
195
- "session_start",
196
- "prompt",
197
- "before_tool",
198
- "after_tool",
199
- "stop",
200
- "session_end",
201
- "notification"
202
- ];
203
-
204
- // src/hooks/dispatch/compose.ts
205
- var RANK = { allow: 0, ask: 1, deny: 2 };
206
- function applyMode(id, decision, mode) {
207
- if (!decision.verdict || decision.verdict === "allow") return decision;
208
- if (mode === "off") return {};
209
- if (mode === "graded") return decision;
210
- if (mode === "warn") {
211
- const note = `pmcp ${id}: ${decision.reason ?? "would refuse this call"}`;
212
- return { context: [...decision.context ?? [], note] };
213
- }
214
- return { ...decision, verdict: mode };
215
- }
216
- function compose(decisions) {
217
- let winner = {};
218
- const context = [];
219
- const feedback = [];
220
- for (const decision of decisions) {
221
- context.push(...decision.context ?? []);
222
- if (decision.feedback) feedback.push(decision.feedback);
223
- if (!decision.verdict) continue;
224
- if (!winner.verdict || RANK[decision.verdict] > RANK[winner.verdict])
225
- winner = decision;
226
- }
227
- return {
228
- ...winner.verdict ? { verdict: winner.verdict } : {},
229
- ...winner.reason ? { reason: winner.reason } : {},
230
- ...context.length > 0 ? { context } : {},
231
- ...feedback.length > 0 ? { feedback: feedback.join("\n\n") } : {}
232
- };
233
- }
234
- function lower(decision, lowering) {
235
- if (decision.verdict !== "ask" || !lowering) return decision;
236
- if (lowering.ask === "deny") return { ...decision, verdict: "deny" };
237
- const { verdict: _verdict, reason, ...rest } = decision;
238
- return {
239
- ...rest,
240
- context: [...decision.context ?? [], `pmcp: ${reason ?? "would ask"}`]
241
- };
242
- }
243
-
244
159
  // src/hooks/dispatch/defer.ts
245
- import { join as join3 } from "node:path";
160
+ import { join } from "node:path";
246
161
  var SAFE = /[^A-Za-z0-9_-]/gu;
247
162
  function file(store, session) {
248
- return join3(
163
+ return join(
249
164
  store.dir,
250
165
  "pending-context",
251
166
  `${session.replace(SAFE, "_")}.json`
@@ -260,7 +175,7 @@ function read2(path) {
260
175
  }
261
176
  }
262
177
  function write2(path, notes) {
263
- mkdirSync(join3(path, ".."), { recursive: true });
178
+ mkdirSync(join(path, ".."), { recursive: true });
264
179
  const temporary = `${path}.${process.pid}.tmp`;
265
180
  writeFileSync(temporary, JSON.stringify(notes));
266
181
  renameSync(temporary, path);
@@ -285,38 +200,38 @@ function deferContext(input, decision, delivers, store) {
285
200
  import { resolve as resolve3 } from "node:path";
286
201
 
287
202
  // src/sessions/paths.ts
288
- import { homedir as homedir2 } from "node:os";
203
+ import { homedir } from "node:os";
289
204
  import {
290
205
  basename,
291
- dirname as dirname3,
206
+ dirname as dirname2,
292
207
  isAbsolute,
293
- join as join5,
208
+ join as join3,
294
209
  relative,
295
210
  resolve as resolve2
296
211
  } from "node:path";
297
212
 
298
213
  // src/sessions/checkout.ts
299
- import { dirname as dirname2, join as join4, resolve } from "node:path";
214
+ import { dirname, join as join2, resolve } from "node:path";
300
215
  function gitDirOf(root) {
301
- const dotGit = join4(root, ".git");
216
+ const dotGit = join2(root, ".git");
302
217
  if (statSync(dotGit).isDirectory()) return realpathSync(dotGit);
303
218
  const pointer = /^gitdir:\s*(.+)$/mu.exec(readFileSync(dotGit, "utf8"))?.[1]?.trim();
304
219
  return pointer ? realpathSync(resolve(root, pointer)) : null;
305
220
  }
306
221
  function commonDirOf(gitDir) {
307
- const file2 = join4(gitDir, "commondir");
222
+ const file2 = join2(gitDir, "commondir");
308
223
  if (!existsSync(file2)) return gitDir;
309
224
  return realpathSync(resolve(gitDir, readFileSync(file2, "utf8").trim()));
310
225
  }
311
226
  function branchOf(gitDir) {
312
- const head = readFileSync(join4(gitDir, "HEAD"), "utf8").trim();
227
+ const head = readFileSync(join2(gitDir, "HEAD"), "utf8").trim();
313
228
  return head.startsWith("ref: refs/heads/") ? head.slice("ref: refs/heads/".length) : "";
314
229
  }
315
230
  function checkoutOf(path) {
316
231
  let dir = resolve(path);
317
232
  for (; ; ) {
318
233
  try {
319
- if (existsSync(join4(dir, ".git"))) {
234
+ if (existsSync(join2(dir, ".git"))) {
320
235
  const gitDir = gitDirOf(dir);
321
236
  if (!gitDir) return null;
322
237
  const commonDir = commonDirOf(gitDir);
@@ -331,7 +246,7 @@ function checkoutOf(path) {
331
246
  } catch {
332
247
  return null;
333
248
  }
334
- const parent = dirname2(dir);
249
+ const parent = dirname(dir);
335
250
  if (parent === dir) return null;
336
251
  dir = parent;
337
252
  }
@@ -341,19 +256,19 @@ function gitCommonDir(root) {
341
256
  }
342
257
  function worktreesOf(checkout) {
343
258
  const found = [
344
- { path: dirname2(checkout.commonDir), branch: branchOf(checkout.commonDir) }
259
+ { path: dirname(checkout.commonDir), branch: branchOf(checkout.commonDir) }
345
260
  ];
346
261
  let names2 = [];
347
262
  try {
348
- names2 = readdirSync(join4(checkout.commonDir, "worktrees"));
263
+ names2 = readdirSync(join2(checkout.commonDir, "worktrees"));
349
264
  } catch {
350
265
  return found;
351
266
  }
352
267
  for (const name of names2) {
353
- const admin = join4(checkout.commonDir, "worktrees", name);
268
+ const admin = join2(checkout.commonDir, "worktrees", name);
354
269
  try {
355
- const dotGit = readFileSync(join4(admin, "gitdir"), "utf8").trim();
356
- found.push({ path: dirname2(dotGit), branch: branchOf(admin) });
270
+ const dotGit = readFileSync(join2(admin, "gitdir"), "utf8").trim();
271
+ found.push({ path: dirname(dotGit), branch: branchOf(admin) });
357
272
  } catch {
358
273
  }
359
274
  }
@@ -361,7 +276,7 @@ function worktreesOf(checkout) {
361
276
  }
362
277
  function hasLinkedWorktrees(checkout) {
363
278
  try {
364
- return readdirSync(join4(checkout.commonDir, "worktrees")).length > 0;
279
+ return readdirSync(join2(checkout.commonDir, "worktrees")).length > 0;
365
280
  } catch {
366
281
  return false;
367
282
  }
@@ -372,12 +287,12 @@ function mainCheckoutBase(dir) {
372
287
  const checkout = checkoutOf(dir);
373
288
  if (!checkout || basename(checkout.commonDir) !== ".git") return dir;
374
289
  const inside2 = relative(checkout.root, resolve2(dir));
375
- return join5(dirname3(checkout.commonDir), inside2);
290
+ return join3(dirname2(checkout.commonDir), inside2);
376
291
  }
377
292
  function expandPath(base, path) {
378
- if (path === "~") return homedir2();
379
- if (path.startsWith("~/")) return join5(homedir2(), path.slice(2));
380
- if (path.startsWith("$HOME/")) return join5(homedir2(), path.slice(6));
293
+ if (path === "~") return homedir();
294
+ if (path.startsWith("~/")) return join3(homedir(), path.slice(2));
295
+ if (path.startsWith("$HOME/")) return join3(homedir(), path.slice(6));
381
296
  return isAbsolute(path) ? path : resolve2(mainCheckoutBase(base), path);
382
297
  }
383
298
 
@@ -766,7 +681,44 @@ function withSteps(input) {
766
681
  return { ...input, tool: { ...tool, steps } };
767
682
  }
768
683
 
684
+ // src/hooks/dispatch/failure.ts
685
+ import { isAbsolute as isAbsolute2, relative as relative2, resolve as resolve4 } from "node:path";
686
+ var PASS_KINDS = ["read", "edit-own-worktree"];
687
+ function ownWorktree(input) {
688
+ const checkout = checkoutOf(input.cwd);
689
+ if (!checkout || checkout.main) return false;
690
+ const paths = input.tool?.paths ?? [];
691
+ return paths.length > 0 && paths.every((path) => {
692
+ const rest = relative2(checkout.root, resolve4(input.cwd, path));
693
+ return rest !== "" && !rest.startsWith("..") && !isAbsolute2(rest);
694
+ });
695
+ }
696
+ function passes(input, pass2) {
697
+ const kind = input.tool?.kind;
698
+ if (kind === "read") return pass2.includes("read");
699
+ if (kind === "edit")
700
+ return pass2.includes("edit-own-worktree") && ownWorktree(input);
701
+ return false;
702
+ }
703
+ function afterFailure(policy, cause, input, failure) {
704
+ const head = `pmcp hooks: ${policy} failed (${cause})`;
705
+ if (passes(input, failure.pass))
706
+ return { context: [`${head}; passed with a warning`] };
707
+ return { verdict: "deny", reason: `${head}; refused` };
708
+ }
709
+
769
710
  // src/hooks/dispatch/run-policy.ts
711
+ var Timeout = class extends Error {
712
+ };
713
+ function within(work, ms) {
714
+ if (ms === void 0) return work;
715
+ let timer;
716
+ const late = new Promise((_, reject) => {
717
+ timer = setTimeout(() => reject(new Timeout(`timeout ${ms} ms`)), ms);
718
+ timer.unref?.();
719
+ });
720
+ return Promise.race([work, late]).finally(() => clearTimeout(timer));
721
+ }
770
722
  async function runPolicy(selected, input, deps) {
771
723
  const { policy, mode } = selected;
772
724
  const log = deps.log.child({ policy: policy.id });
@@ -791,7 +743,22 @@ async function runPolicy(selected, input, deps) {
791
743
  now: deps.now,
792
744
  ...deps.policySha256 ? { policySha256: deps.policySha256 } : {}
793
745
  };
794
- const raw = await (deps.evaluate ? deps.evaluate(selected, input, context) : policy.evaluate(input, context));
746
+ const evaluate = () => Promise.resolve(
747
+ deps.evaluate ? deps.evaluate(selected, input, context) : policy.evaluate(input, context)
748
+ );
749
+ const tries = (deps.failure?.retry ?? 0) + 1;
750
+ let raw;
751
+ for (let attempt = 1; ; attempt += 1) {
752
+ try {
753
+ raw = await within(evaluate(), deps.failure?.timeoutMs);
754
+ break;
755
+ } catch (error) {
756
+ if (attempt >= tries) throw error;
757
+ log.warn("policy failed; trying again", {
758
+ error: error instanceof Error ? error.message : String(error)
759
+ });
760
+ }
761
+ }
795
762
  const decision = applyMode(policy.id, raw, mode);
796
763
  log.debug("policy", {
797
764
  verdict: decision.verdict,
@@ -803,6 +770,10 @@ async function runPolicy(selected, input, deps) {
803
770
  error: error instanceof Error ? error.message : String(error)
804
771
  });
805
772
  if (policy.fail === "open") return finish({});
773
+ if (deps.failure) {
774
+ const cause = error instanceof Timeout ? error.message : `error: ${(error instanceof Error ? error.message : String(error)).split("\n")[0]}`;
775
+ return finish(afterFailure(policy.id, cause, input, deps.failure));
776
+ }
806
777
  return finish({
807
778
  verdict: "deny",
808
779
  reason: `pmcp ${policy.id} failed, refusing to be safe`
@@ -811,7 +782,7 @@ async function runPolicy(selected, input, deps) {
811
782
  }
812
783
 
813
784
  // src/hooks/policies/git/forced-branch-move.ts
814
- import { resolve as resolve4 } from "node:path";
785
+ import { resolve as resolve5 } from "node:path";
815
786
 
816
787
  // src/hooks/policies/_shared.ts
817
788
  function shellCall(input) {
@@ -886,7 +857,7 @@ var forcedBranchMove = {
886
857
  for (const step of realSteps(call.steps)) {
887
858
  const target = forcedTarget(step.argv);
888
859
  if (!target) continue;
889
- const cwd = resolve4(input.cwd, step.dir, target.dir);
860
+ const cwd = resolve5(input.cwd, step.dir, target.dir);
890
861
  if (!checkedOutElsewhere(ctx.git, cwd, target.branch)) continue;
891
862
  return {
892
863
  verdict: "deny",
@@ -1045,8 +1016,12 @@ var stageAll = {
1045
1016
  }
1046
1017
  };
1047
1018
 
1019
+ // src/hooks/lazy/crypto.ts
1020
+ var real = () => process.getBuiltinModule("node:crypto");
1021
+ var createHash = ((...args) => real().createHash(...args));
1022
+
1048
1023
  // src/hooks/checks/after-edit.ts
1049
- import { relative as relative3 } from "node:path";
1024
+ import { relative as relative4 } from "node:path";
1050
1025
 
1051
1026
  // src/hooks/checks/_shared.ts
1052
1027
  function readState(input, ctx) {
@@ -1084,7 +1059,7 @@ function runCheck(command6, root, timeout) {
1084
1059
  }
1085
1060
 
1086
1061
  // src/hooks/checks/options.ts
1087
- import { isAbsolute as isAbsolute2 } from "node:path";
1062
+ import { isAbsolute as isAbsolute3 } from "node:path";
1088
1063
  function report(raw) {
1089
1064
  if (raw["report"] !== void 0 && raw["report"] !== "context")
1090
1065
  throw new Error("report must be context");
@@ -1095,7 +1070,7 @@ function afterEditOptions(raw) {
1095
1070
  const glob2 = raw["validator_glob"];
1096
1071
  const command6 = raw["command"];
1097
1072
  const seconds = raw["debounce_seconds"] ?? 60;
1098
- if (typeof glob2 !== "string" || !glob2 || isAbsolute2(glob2) || glob2.split("/").includes(".."))
1073
+ if (typeof glob2 !== "string" || !glob2 || isAbsolute3(glob2) || glob2.split("/").includes(".."))
1099
1074
  throw new Error("validator_glob must stay inside the project");
1100
1075
  if (!Array.isArray(command6) || command6.length === 0 || !command6.every(
1101
1076
  (part) => typeof part === "string" && part.length > 0 && !part.includes("\0")
@@ -1119,26 +1094,26 @@ function stopOptions(raw) {
1119
1094
  }
1120
1095
 
1121
1096
  // src/hooks/checks/validators.ts
1122
- import { dirname as dirname4, isAbsolute as isAbsolute3, relative as relative2, resolve as resolve5, sep } from "node:path";
1097
+ import { dirname as dirname3, isAbsolute as isAbsolute4, relative as relative3, resolve as resolve6, sep } from "node:path";
1123
1098
  function contains(root, target) {
1124
- const rest = relative2(root, target);
1125
- return !isAbsolute3(rest) && rest !== ".." && !rest.startsWith(`..${sep}`);
1099
+ const rest = relative3(root, target);
1100
+ return !isAbsolute4(rest) && rest !== ".." && !rest.startsWith(`..${sep}`);
1126
1101
  }
1127
1102
  function owner(validator) {
1128
1103
  const parts = validator.split(sep);
1129
1104
  const at = parts.findIndex((part) => part === ".agents" || part === ".agent");
1130
- return at < 0 ? dirname4(validator) : parts.slice(0, at).join(sep) || sep;
1105
+ return at < 0 ? dirname3(validator) : parts.slice(0, at).join(sep) || sep;
1131
1106
  }
1132
1107
  function validators(root, pattern, paths) {
1133
1108
  const realRoot = realpathSync(root);
1134
- const edits = paths.map((path) => resolve5(path)).filter((path) => contains(root, path));
1109
+ const edits = paths.map((path) => resolve6(path)).filter((path) => contains(root, path));
1135
1110
  if (edits.length === 0) return [];
1136
1111
  const candidates = [
1137
1112
  ...globSync(pattern, {
1138
1113
  cwd: root,
1139
1114
  exclude: ["**/node_modules/**", "**/.git/**"]
1140
1115
  })
1141
- ].map((path) => resolve5(root, path)).filter((path) => {
1116
+ ].map((path) => resolve6(root, path)).filter((path) => {
1142
1117
  if (!contains(realRoot, realpathSync(path)) || !statSync(path).isFile())
1143
1118
  return false;
1144
1119
  return edits.some((edit) => contains(owner(path), edit));
@@ -1187,11 +1162,11 @@ var afterEdit = {
1187
1162
  writeState(input, ctx, { validators: Object.fromEntries(kept) });
1188
1163
  if (runCheck(command6, input.projectRoot, deadline - Date.now())) continue;
1189
1164
  ctx.log.error("validator check failed", {
1190
- validator: relative3(input.projectRoot, validator)
1165
+ validator: relative4(input.projectRoot, validator)
1191
1166
  });
1192
1167
  if (context.length < 20)
1193
1168
  context.push(
1194
- `pmcp after_edit: validation failed for ${relative3(input.projectRoot, validator)}; run the configured validator to inspect its output.`
1169
+ `pmcp after_edit: validation failed for ${relative4(input.projectRoot, validator)}; run the configured validator to inspect its output.`
1195
1170
  );
1196
1171
  }
1197
1172
  return context.length ? { context } : pass;
@@ -1199,10 +1174,10 @@ var afterEdit = {
1199
1174
  };
1200
1175
 
1201
1176
  // src/hooks/checks/projection.ts
1202
- import { join as join7 } from "node:path";
1177
+ import { join as join5 } from "node:path";
1203
1178
 
1204
1179
  // src/sessions/projector-cli.ts
1205
- import { delimiter, join as join6 } from "node:path";
1180
+ import { delimiter, join as join4 } from "node:path";
1206
1181
  var PROJECTOR_FILE = "projector.json";
1207
1182
  function readJson(path) {
1208
1183
  try {
@@ -1212,17 +1187,17 @@ function readJson(path) {
1212
1187
  }
1213
1188
  }
1214
1189
  function localCli(root) {
1215
- const own = join6(root, "node_modules/@modootoday/pmcp/dist/cli.js");
1190
+ const own = join4(root, "node_modules/@modootoday/pmcp/dist/cli.js");
1216
1191
  if (existsSync(own)) return own;
1217
1192
  try {
1218
- const target = realpathSync(join6(root, "node_modules/.bin/pmcp"));
1193
+ const target = realpathSync(join4(root, "node_modules/.bin/pmcp"));
1219
1194
  return /\.[cm]?js$/u.test(target) ? target : null;
1220
1195
  } catch {
1221
1196
  return null;
1222
1197
  }
1223
1198
  }
1224
1199
  function recordedCli(root, stateDir) {
1225
- const known = readJson(join6(stateDir, PROJECTOR_FILE));
1200
+ const known = readJson(join4(stateDir, PROJECTOR_FILE));
1226
1201
  let checkout;
1227
1202
  try {
1228
1203
  checkout = realpathSync(root);
@@ -1239,7 +1214,7 @@ function projectingCli(root, stateDir) {
1239
1214
  function pathPmcp(path) {
1240
1215
  for (const dir of (path ?? "").split(delimiter).filter(Boolean)) {
1241
1216
  try {
1242
- return realpathSync(join6(dir, "pmcp"));
1217
+ return realpathSync(join4(dir, "pmcp"));
1243
1218
  } catch {
1244
1219
  continue;
1245
1220
  }
@@ -1283,7 +1258,7 @@ function findProjector(root, stateDir, deadline) {
1283
1258
  const cli = localCli(root) ?? recordedCli(root, stateDir);
1284
1259
  if (!cli || !existsSync(cli))
1285
1260
  return { missing: cli ?? "no local or recorded pmcp" };
1286
- const expected = readJson2(join7(root, "pmcp.lock"))?.[LOCK_VERSION_KEY];
1261
+ const expected = readJson2(join5(root, "pmcp.lock"))?.[LOCK_VERSION_KEY];
1287
1262
  const answer = run([process.execPath, cli, "--version"], root, deadline);
1288
1263
  if (answer.error || answer.stdout.trim() !== expected)
1289
1264
  return { missing: cli };
@@ -1445,7 +1420,7 @@ var leases = {
1445
1420
  options(raw) {
1446
1421
  return Object.entries(raw).map(([name, value]) => {
1447
1422
  const table = value ?? {};
1448
- onlyKeys(table, ["path", "blocks"]);
1423
+ onlyKeys(table, ["path", "blocks", "file", "events"]);
1449
1424
  if (table["path"] !== void 0 && typeof table["path"] !== "string")
1450
1425
  throw new Error(`${name}.path must be a string`);
1451
1426
  return {
@@ -1512,7 +1487,7 @@ function noticeOf(fresh, earlier, limit, session, pmcp = "pmcp") {
1512
1487
  }
1513
1488
 
1514
1489
  // src/sessions/mailbox/select.ts
1515
- import { basename as basename2, resolve as resolve6 } from "node:path";
1490
+ import { basename as basename2, resolve as resolve7 } from "node:path";
1516
1491
  var isWorktree = (kind) => kind === "worktree" || kind === "desk";
1517
1492
  function splitSelector(selector) {
1518
1493
  const at = selector.indexOf(":");
@@ -2439,7 +2414,7 @@ var stdinInterpreter = {
2439
2414
  };
2440
2415
 
2441
2416
  // src/hooks/policies/workspace/shared-checkout.ts
2442
- import { dirname as dirname5 } from "node:path";
2417
+ import { dirname as dirname4 } from "node:path";
2443
2418
 
2444
2419
  // src/hooks/policies/workspace/claimants.ts
2445
2420
  function claimants(store, session, root) {
@@ -2452,12 +2427,12 @@ function claimantNotice(root, names2) {
2452
2427
  }
2453
2428
 
2454
2429
  // src/hooks/policies/workspace/leftovers.ts
2455
- import { isAbsolute as isAbsolute4, relative as relative4, resolve as resolve7 } from "node:path";
2430
+ import { isAbsolute as isAbsolute5, relative as relative5, resolve as resolve8 } from "node:path";
2456
2431
  var TOUCHED_KEPT = 50;
2457
2432
  function addTouched(touched, root, target) {
2458
- const path = relative4(
2433
+ const path = relative5(
2459
2434
  root,
2460
- isAbsolute4(target) ? target : resolve7(root, target)
2435
+ isAbsolute5(target) ? target : resolve8(root, target)
2461
2436
  );
2462
2437
  if (!path || path.startsWith("..") || touched.some((entry) => entry.path === path))
2463
2438
  return [...touched];
@@ -2540,7 +2515,7 @@ function leftovers(input, ctx) {
2540
2515
  }
2541
2516
  function onEdit(input, ctx) {
2542
2517
  const target = input.tool?.paths[0];
2543
- const checkout = target ? checkoutOf(dirname5(target)) : null;
2518
+ const checkout = target ? checkoutOf(dirname4(target)) : null;
2544
2519
  if (!target || !checkout) return [];
2545
2520
  const lines = [];
2546
2521
  const others = ctx.options.warnClaimants ? claimants(ctx.store, input.session.id, checkout.root) : [];
@@ -2596,7 +2571,7 @@ var sharedCheckout = {
2596
2571
  };
2597
2572
 
2598
2573
  // src/hooks/policies/workspace/mainline-deliver.ts
2599
- import { resolve as resolve8 } from "node:path";
2574
+ import { resolve as resolve9 } from "node:path";
2600
2575
  var PUSH = /\bgit\b[^|;&\n]*\spush\b/u;
2601
2576
  var REASON8 = "This repository's mainline moves only through pmcp git deliver, which replays, gates and pushes one delivery at a time. Commit, then run pmcp git deliver; other repositories push from their own directory.";
2602
2577
  function sameRepository(dir, commonDir) {
@@ -2624,7 +2599,7 @@ var mainlineDeliver = {
2624
2599
  if (program(step.argv[0]) !== "git") continue;
2625
2600
  const git2 = gitCall(step.argv);
2626
2601
  if (git2.sub !== "push") continue;
2627
- const dir = resolve8(input.cwd, step.dir, git2.dir);
2602
+ const dir = resolve9(input.cwd, step.dir, git2.dir);
2628
2603
  if (sameRepository(dir, project6.commonDir))
2629
2604
  return { verdict: "deny", reason: REASON8 };
2630
2605
  }
@@ -2633,10 +2608,10 @@ var mainlineDeliver = {
2633
2608
  };
2634
2609
 
2635
2610
  // src/hooks/policies/workspace/worktree-sync.ts
2636
- import { relative as relative5, resolve as resolve10 } from "node:path";
2611
+ import { relative as relative6, resolve as resolve11 } from "node:path";
2637
2612
 
2638
2613
  // src/git/detect.ts
2639
- import { dirname as dirname6, resolve as resolve9 } from "node:path";
2614
+ import { dirname as dirname5, resolve as resolve10 } from "node:path";
2640
2615
 
2641
2616
  // src/git/exec.ts
2642
2617
  var LOCAL_ENV = [
@@ -2716,11 +2691,11 @@ function detect(cwd, prefs = {}) {
2716
2691
  const remote = defaultRemote(root, prefs.remote);
2717
2692
  const mainline = defaultMainline(root, remote, prefs.mainline);
2718
2693
  return {
2719
- root: resolve9(root),
2720
- gitDir: resolve9(gitDir),
2721
- commonDir: resolve9(commonDir),
2722
- mainRoot: dirname6(resolve9(commonDir)),
2723
- linked: resolve9(gitDir) !== resolve9(commonDir),
2694
+ root: resolve10(root),
2695
+ gitDir: resolve10(gitDir),
2696
+ commonDir: resolve10(commonDir),
2697
+ mainRoot: dirname5(resolve10(commonDir)),
2698
+ linked: resolve10(gitDir) !== resolve10(commonDir),
2724
2699
  remote,
2725
2700
  mainline,
2726
2701
  upstream: `${remote}/${mainline}`,
@@ -2729,12 +2704,12 @@ function detect(cwd, prefs = {}) {
2729
2704
  }
2730
2705
 
2731
2706
  // src/git/install.ts
2732
- import { join as join8 } from "node:path";
2707
+ import { dirname as dirname6, join as join6 } from "node:path";
2733
2708
  function lockHash(root, paths) {
2734
2709
  const hash = createHash("sha256");
2735
2710
  let found = false;
2736
2711
  for (const path of paths) {
2737
- const file2 = join8(root, path);
2712
+ const file2 = join6(root, path);
2738
2713
  if (!existsSync(file2)) continue;
2739
2714
  found = true;
2740
2715
  hash.update(`${path}\0`).update(readFileSync(file2));
@@ -2742,16 +2717,26 @@ function lockHash(root, paths) {
2742
2717
  if (!found) return null;
2743
2718
  return hash.digest("hex");
2744
2719
  }
2720
+ function installedHash(root, spec) {
2721
+ if (spec.stamp?.hash !== "plain") return lockHash(root, spec.when);
2722
+ const file2 = join6(root, spec.when[0] ?? "");
2723
+ if (!existsSync(file2)) return null;
2724
+ return createHash("sha256").update(readFileSync(file2)).digest("hex");
2725
+ }
2745
2726
  function stampFile(root, spec) {
2727
+ if (spec.stamp) {
2728
+ const gitDir = gitText(root, ["rev-parse", "--absolute-git-dir"]);
2729
+ return spec.stamp.path.replace("${git_dir}", gitDir);
2730
+ }
2746
2731
  const key = createHash("sha256").update([root, ...spec.when].join("\0")).digest("hex");
2747
- return join8(spec.stateDir, "installed", key);
2732
+ return join6(spec.stateDir, "installed", key);
2748
2733
  }
2749
2734
  function readStamp(path) {
2750
2735
  if (!existsSync(path)) return null;
2751
2736
  return readFileSync(path, "utf8").trim() || null;
2752
2737
  }
2753
2738
  function installIfStale(root, spec, report2) {
2754
- const hash = lockHash(root, spec.when);
2739
+ const hash = installedHash(root, spec);
2755
2740
  const stamp = stampFile(root, spec);
2756
2741
  if (hash === null || readStamp(stamp) === hash) return null;
2757
2742
  report2.info(
@@ -2762,7 +2747,7 @@ function installIfStale(root, spec, report2) {
2762
2747
  report2.warn(`the install exited ${status}; the next sync runs it again`);
2763
2748
  return status;
2764
2749
  }
2765
- mkdirSync(join8(spec.stateDir, "installed"), { recursive: true });
2750
+ mkdirSync(dirname6(stamp), { recursive: true });
2766
2751
  writeFileSync(stamp, `${hash}
2767
2752
  `);
2768
2753
  return 0;
@@ -2792,7 +2777,7 @@ function distance(cwd, upstream) {
2792
2777
  }
2793
2778
 
2794
2779
  // src/git/submodules.ts
2795
- import { join as join9 } from "node:path";
2780
+ import { join as join7 } from "node:path";
2796
2781
  function clean(dir) {
2797
2782
  return git(dir, ["status", "--porcelain"]).stdout.trim() === "";
2798
2783
  }
@@ -2802,8 +2787,8 @@ function hasCommit(dir, sha) {
2802
2787
  function movableSubmodules(root) {
2803
2788
  const listed = git(root, ["submodule", "status"]).stdout;
2804
2789
  return listed.split("\n").filter((line) => /^[ +]/u.test(line)).map((line) => line.trim().split(/\s+/u)[1] ?? "").filter((path) => {
2805
- const dir = join9(root, path);
2806
- if (!path || !existsSync(join9(dir, ".git"))) return false;
2790
+ const dir = join7(root, path);
2791
+ if (!path || !existsSync(join7(dir, ".git"))) return false;
2807
2792
  const local = gitText(dir, [
2808
2793
  "rev-list",
2809
2794
  "--count",
@@ -2818,7 +2803,7 @@ function updateToPins(root, paths) {
2818
2803
  const lines = [];
2819
2804
  for (const path of paths) {
2820
2805
  const pin = gitText(root, ["rev-parse", `HEAD:${path}`]);
2821
- const dir = join9(root, path);
2806
+ const dir = join7(root, path);
2822
2807
  if (!pin || !hasCommit(dir, pin)) {
2823
2808
  lines.push(
2824
2809
  `${path}: left alone, ${pin.slice(0, 10) || "its pin"} is not in its checkout`
@@ -2902,8 +2887,8 @@ function options(raw) {
2902
2887
  function desk(input, opts) {
2903
2888
  const checkout = checkoutOf(input.cwd);
2904
2889
  if (!checkout || checkout.main) return null;
2905
- const desks = resolve10(checkout.commonDir, "..", opts.root);
2906
- const inside2 = relative5(desks, checkout.root);
2890
+ const desks = resolve11(checkout.commonDir, "..", opts.root);
2891
+ const inside2 = relative6(desks, checkout.root);
2907
2892
  if (!inside2 || inside2.startsWith("..")) return null;
2908
2893
  return detect(checkout.root, {
2909
2894
  ...opts.remote ? { remote: opts.remote } : {},
@@ -2994,23 +2979,23 @@ var worktreeSync = {
2994
2979
  };
2995
2980
 
2996
2981
  // src/hooks/policies/custom.ts
2997
- import { isAbsolute as isAbsolute5, relative as relative6, resolve as resolve11 } from "node:path";
2982
+ import { isAbsolute as isAbsolute6, relative as relative7, resolve as resolve12 } from "node:path";
2998
2983
  var FAILED = "Guard failed validation or execution";
2999
2984
  function inside(base, path) {
3000
- const rest = relative6(base, path);
3001
- return rest !== "" && !rest.startsWith("..") && !isAbsolute5(rest);
2985
+ const rest = relative7(base, path);
2986
+ return rest !== "" && !rest.startsWith("..") && !isAbsolute6(rest);
3002
2987
  }
3003
2988
  function guardScript(root, command6) {
3004
2989
  const script = command6[0]?.startsWith(".agents/guards/") ? command6[0] : command6[1];
3005
2990
  if (!script?.startsWith(".agents/guards/")) {
3006
2991
  throw new Error("Hook command must execute a script under .agents/guards/");
3007
2992
  }
3008
- const base = resolve11(root, ".agents/guards");
3009
- if (!inside(base, resolve11(root, script)))
2993
+ const base = resolve12(root, ".agents/guards");
2994
+ if (!inside(base, resolve12(root, script)))
3010
2995
  throw new Error("Hook guard must stay under .agents/guards/");
3011
- if (!existsSync(resolve11(root, script)))
2996
+ if (!existsSync(resolve12(root, script)))
3012
2997
  throw new Error("Hook guard script must exist");
3013
- const real4 = realpathSync(resolve11(root, script));
2998
+ const real4 = realpathSync(resolve12(root, script));
3014
2999
  if (!inside(realpathSync(base), real4))
3015
3000
  throw new Error("Hook guard cannot resolve outside .agents/guards/");
3016
3001
  return real4;
@@ -3033,7 +3018,7 @@ function run2(entry, input) {
3033
3018
  };
3034
3019
  }
3035
3020
  const args = entry.command.map(
3036
- (part) => part.startsWith(".agents/guards/") ? resolve11(root, part) : part
3021
+ (part) => part.startsWith(".agents/guards/") ? resolve12(root, part) : part
3037
3022
  );
3038
3023
  const result = spawnSync(args[0], args.slice(1), {
3039
3024
  cwd: root,
@@ -3227,7 +3212,7 @@ function render(input, decision) {
3227
3212
  }
3228
3213
 
3229
3214
  // src/hooks/runtimes/antigravity/payload.ts
3230
- import { isAbsolute as isAbsolute6, resolve as resolve12 } from "node:path";
3215
+ import { isAbsolute as isAbsolute7, resolve as resolve13 } from "node:path";
3231
3216
  function object(value) {
3232
3217
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
3233
3218
  }
@@ -3253,7 +3238,7 @@ function normalize(nativeEvent, payload, projectRoot) {
3253
3238
  const name = text3(call["name"]);
3254
3239
  const kind = name ? toolKind(name) : void 0;
3255
3240
  const target = text3(args["TargetFile"]);
3256
- const paths = target ? [isAbsolute6(target) ? target : resolve12(cwd, target)] : [];
3241
+ const paths = target ? [isAbsolute7(target) ? target : resolve13(cwd, target)] : [];
3257
3242
  return {
3258
3243
  contract: 2,
3259
3244
  runtime: "antigravity",
@@ -3451,7 +3436,7 @@ function shape(input, decision, parts) {
3451
3436
  }
3452
3437
 
3453
3438
  // src/hooks/runtimes/claude/payload.ts
3454
- import { isAbsolute as isAbsolute7, resolve as resolve13 } from "node:path";
3439
+ import { isAbsolute as isAbsolute8, resolve as resolve14 } from "node:path";
3455
3440
  function object2(value) {
3456
3441
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
3457
3442
  }
@@ -3468,7 +3453,7 @@ function normalize2(nativeEvent, payload, projectRoot) {
3468
3453
  toolInput["file_path"],
3469
3454
  toolInput["notebook_path"],
3470
3455
  kind === "read" ? toolInput["path"] : void 0
3471
- ].filter((value) => typeof value === "string" && !!value).map((path) => isAbsolute7(path) ? path : resolve13(cwd, path));
3456
+ ].filter((value) => typeof value === "string" && !!value).map((path) => isAbsolute8(path) ? path : resolve14(cwd, path));
3472
3457
  const agentType = text4(raw["agent_type"]);
3473
3458
  const turnId = text4(raw["prompt_id"]);
3474
3459
  const lastMessage = text4(raw["last_assistant_message"]);
@@ -3702,7 +3687,7 @@ function shape2(input, decision, parts) {
3702
3687
  }
3703
3688
 
3704
3689
  // src/hooks/runtimes/codex/payload.ts
3705
- import { isAbsolute as isAbsolute8, resolve as resolve14 } from "node:path";
3690
+ import { isAbsolute as isAbsolute9, resolve as resolve15 } from "node:path";
3706
3691
  var PATCH_HEADER = /^\*\*\* (?:Update File|Add File|Delete File|Move to): (.+)$/gmu;
3707
3692
  function object3(value) {
3708
3693
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -3720,7 +3705,7 @@ function normalize3(nativeEvent, payload, projectRoot) {
3720
3705
  const toolInput = object3(raw["tool_input"]);
3721
3706
  const kind = name ? toolKind3(name) : void 0;
3722
3707
  const body = text5(toolInput["command"]) ?? "";
3723
- const paths = (kind === "edit" ? patchPaths(body) : []).filter(Boolean).map((path) => isAbsolute8(path) ? path : resolve14(cwd, path));
3708
+ const paths = (kind === "edit" ? patchPaths(body) : []).filter(Boolean).map((path) => isAbsolute9(path) ? path : resolve15(cwd, path));
3724
3709
  const turnId = text5(raw["turn_id"]);
3725
3710
  const lastMessage = text5(raw["last_assistant_message"]);
3726
3711
  const prompt = text5(raw["prompt"]);
@@ -3912,7 +3897,7 @@ function render4(input, decision) {
3912
3897
  }
3913
3898
 
3914
3899
  // src/hooks/runtimes/gemini/payload.ts
3915
- import { isAbsolute as isAbsolute9, resolve as resolve15 } from "node:path";
3900
+ import { isAbsolute as isAbsolute10, resolve as resolve16 } from "node:path";
3916
3901
  function object4(value) {
3917
3902
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
3918
3903
  }
@@ -3925,7 +3910,7 @@ function normalize4(nativeEvent, payload, projectRoot) {
3925
3910
  const name = text6(raw["tool_name"]);
3926
3911
  const input = object4(raw["tool_input"]);
3927
3912
  const kind = name ? toolKind4(name) : void 0;
3928
- const paths = [input["file_path"], input["absolute_path"], input["path"]].filter((value) => typeof value === "string" && !!value).map((path) => isAbsolute9(path) ? path : resolve15(cwd, path));
3913
+ const paths = [input["file_path"], input["absolute_path"], input["path"]].filter((value) => typeof value === "string" && !!value).map((path) => isAbsolute10(path) ? path : resolve16(cwd, path));
3929
3914
  const prompt = text6(raw["prompt"]);
3930
3915
  const lastMessage = text6(raw["prompt_response"]);
3931
3916
  return {
@@ -4104,7 +4089,7 @@ function render5(input, decision) {
4104
4089
  }
4105
4090
 
4106
4091
  // src/hooks/runtimes/grok/payload.ts
4107
- import { isAbsolute as isAbsolute10, resolve as resolve16 } from "node:path";
4092
+ import { isAbsolute as isAbsolute11, resolve as resolve17 } from "node:path";
4108
4093
  function object5(value) {
4109
4094
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
4110
4095
  }
@@ -4122,7 +4107,7 @@ function normalize5(nativeEvent, payload, projectRoot) {
4122
4107
  const input = object5(raw["toolInput"] ?? raw["tool_input"]);
4123
4108
  const kind = name ? toolKind5(name) : void 0;
4124
4109
  const path = text7(input["file_path"]);
4125
- const paths = path ? [isAbsolute10(path) ? path : resolve16(cwd, path)] : [];
4110
+ const paths = path ? [isAbsolute11(path) ? path : resolve17(cwd, path)] : [];
4126
4111
  const turnId = text7(raw["promptId"]);
4127
4112
  const prompt = text7(raw["prompt"]);
4128
4113
  const lastMessage = text7(raw["lastAssistantMessage"]);
@@ -4300,7 +4285,7 @@ function render6(input, decision) {
4300
4285
  }
4301
4286
 
4302
4287
  // src/hooks/runtimes/opencode/payload.ts
4303
- import { isAbsolute as isAbsolute11, resolve as resolve17 } from "node:path";
4288
+ import { isAbsolute as isAbsolute12, resolve as resolve18 } from "node:path";
4304
4289
  function object6(value) {
4305
4290
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
4306
4291
  }
@@ -4316,7 +4301,7 @@ function normalize6(nativeEvent, payload, projectRoot) {
4316
4301
  const args = object6(raw["args"] ?? input["args"]);
4317
4302
  const kind = name ? toolKind6(name) : void 0;
4318
4303
  const path = text8(args["filePath"]);
4319
- const paths = path ? [isAbsolute11(path) ? path : resolve17(cwd, path)] : [];
4304
+ const paths = path ? [isAbsolute12(path) ? path : resolve18(cwd, path)] : [];
4320
4305
  const session = text8(input["sessionID"]) ?? text8(properties["sessionID"]) ?? "";
4321
4306
  return {
4322
4307
  contract: 2,
@@ -4518,7 +4503,12 @@ async function dispatch(raw, compiled, deps) {
4518
4503
  const selected = off ? [] : selectPolicies(compiled, input);
4519
4504
  if (off) deps.log.warn("emergency off file present; guards pass");
4520
4505
  const decisions = await Promise.all(
4521
- selected.map((entry) => runPolicy(entry, input, deps))
4506
+ selected.map(
4507
+ (entry) => runPolicy(entry, input, {
4508
+ ...deps,
4509
+ ...compiled.failure ? { failure: compiled.failure } : {}
4510
+ })
4511
+ )
4522
4512
  );
4523
4513
  const composed = lower(
4524
4514
  compose([protect, ...decisions]),
@@ -4534,11 +4524,117 @@ async function dispatch(raw, compiled, deps) {
4534
4524
  );
4535
4525
  }
4536
4526
 
4527
+ // src/hooks/entry/fail-closed.ts
4528
+ import { join as join10 } from "node:path";
4529
+
4530
+ // src/hooks/compiled.ts
4531
+ import { join as join9 } from "node:path";
4532
+
4533
+ // src/hooks/integrity-cache.ts
4534
+ import { homedir as homedir2 } from "node:os";
4535
+ import { dirname as dirname7, join as join8 } from "node:path";
4536
+ var LIMIT = 64;
4537
+ function cacheFile() {
4538
+ const base = process.env["XDG_CACHE_HOME"] || join8(homedir2(), ".cache");
4539
+ return join8(base, "pmcp", "hook-verified.json");
4540
+ }
4541
+ function readCache() {
4542
+ try {
4543
+ return JSON.parse(readFileSync(cacheFile(), "utf8"));
4544
+ } catch {
4545
+ return {};
4546
+ }
4547
+ }
4548
+ function stampOf(paths) {
4549
+ try {
4550
+ return paths.map((path) => {
4551
+ const stat3 = statSync(path, { bigint: true });
4552
+ return `${stat3.ino}:${stat3.size}:${stat3.ctimeNs}`;
4553
+ }).join("|");
4554
+ } catch {
4555
+ return null;
4556
+ }
4557
+ }
4558
+ function verifiedBefore(key, stamp, sha) {
4559
+ const entry = readCache()[key];
4560
+ return entry?.stamp === stamp && entry.sha === sha;
4561
+ }
4562
+ function rememberVerified(key, stamp, sha) {
4563
+ try {
4564
+ const kept = Object.entries(readCache()).filter(([path]) => path !== key);
4565
+ const cache = Object.fromEntries([
4566
+ ...kept.slice(-(LIMIT - 1)),
4567
+ [key, { stamp, sha }]
4568
+ ]);
4569
+ const file2 = cacheFile();
4570
+ mkdirSync(dirname7(file2), { recursive: true });
4571
+ const temporary = `${file2}.${process.pid}.tmp`;
4572
+ writeFileSync(temporary, JSON.stringify(cache), { mode: 384 });
4573
+ renameSync(temporary, file2);
4574
+ } catch {
4575
+ }
4576
+ }
4577
+
4578
+ // src/hooks/compiled.ts
4579
+ var HOOK_DIRECTORY = ".agents/pmcp-hooks";
4580
+ var POLICY_FILE = `${HOOK_DIRECTORY}/policy.json`;
4581
+ var HOOK_FILE = `${HOOK_DIRECTORY}/hook.mjs`;
4582
+ var HOOK_BODY_FILE = `${HOOK_DIRECTORY}/hook-body.mjs`;
4583
+ var LOCK_FILE = "pmcp.lock";
4584
+ function sha256(text9) {
4585
+ return createHash("sha256").update(text9).digest("hex");
4586
+ }
4587
+ var PolicyIntegrityError = class extends Error {
4588
+ };
4589
+ var MISMATCH = "policy.json does not match pmcp.lock; review the change and run pmcp project";
4590
+ function readCompiled(root) {
4591
+ const policyPath = join9(root, POLICY_FILE);
4592
+ const files2 = [policyPath, join9(root, LOCK_FILE)];
4593
+ const before2 = stampOf(files2);
4594
+ const text9 = readFileSync(policyPath, "utf8");
4595
+ const lock = JSON.parse(readFileSync(files2[1], "utf8"));
4596
+ const entry = lock.outputs?.find((output) => output.path === POLICY_FILE);
4597
+ const expected = typeof entry?.sha256 === "string" ? entry.sha256 : null;
4598
+ if (expected === null) throw new PolicyIntegrityError(MISMATCH);
4599
+ const stamp = before2 !== null && before2 === stampOf(files2) ? before2 : null;
4600
+ const cached = stamp !== null && verifiedBefore(policyPath, stamp, expected);
4601
+ if (!cached) {
4602
+ if (expected !== sha256(text9)) throw new PolicyIntegrityError(MISMATCH);
4603
+ if (stamp !== null) rememberVerified(policyPath, stamp, expected);
4604
+ }
4605
+ const compiled = JSON.parse(text9);
4606
+ if (compiled.contract !== 2)
4607
+ throw new PolicyIntegrityError("Unknown policy.json contract");
4608
+ return { ...compiled, policySha256: expected };
4609
+ }
4610
+
4537
4611
  // src/hooks/entry/fail-closed.ts
4538
4612
  var FAILED_CLOSED = "pmcp hook could not evaluate this call and refused it";
4539
- function failClosed(adapter, event, root, error) {
4613
+ function rawFailure(root) {
4614
+ try {
4615
+ const raw = JSON.parse(readFileSync(join10(root, POLICY_FILE), "utf8"))["failure"];
4616
+ if (!raw || typeof raw.timeoutMs !== "number" || typeof raw.retry !== "number" || !Array.isArray(raw.pass) || !raw.pass.every(
4617
+ (kind) => PASS_KINDS.includes(kind)
4618
+ ))
4619
+ return void 0;
4620
+ return { timeoutMs: raw.timeoutMs, retry: raw.retry, pass: raw.pass };
4621
+ } catch {
4622
+ return void 0;
4623
+ }
4624
+ }
4625
+ function failedEntry(adapter, event, root, input, failure, error) {
4626
+ if (event !== "before_tool") return "";
4627
+ const cause = `error: ${(error instanceof Error ? error.message : String(error)).split("\n")[0]}`;
4628
+ const head = `pmcp hooks: the hook failed (${cause})`;
4629
+ if (input && passes(input, failure.pass))
4630
+ return adapter.render(input, {
4631
+ context: [`${head}; passed with a warning`]
4632
+ }).stdout;
4633
+ return failClosed(adapter, event, root, new Error(`${head}; refused`), true);
4634
+ }
4635
+ function failClosed(adapter, event, root, error, stated = false) {
4540
4636
  if (event !== "before_tool") return "";
4541
- const reason = error instanceof PolicyIntegrityError ? error.message : FAILED_CLOSED;
4637
+ const reason = error instanceof PolicyIntegrityError || stated && error instanceof Error ? error.message : FAILED_CLOSED;
4542
4638
  const input = {
4543
4639
  contract: 2,
4544
4640
  runtime: adapter.id,
@@ -4551,7 +4647,7 @@ function failClosed(adapter, event, root, error) {
4551
4647
  }
4552
4648
 
4553
4649
  // src/hooks/entry/logger.ts
4554
- import { dirname as dirname7, join as join12 } from "node:path";
4650
+ import { dirname as dirname8, join as join13 } from "node:path";
4555
4651
 
4556
4652
  // src/logging/levels.ts
4557
4653
  var LEVEL_RANK = {
@@ -4675,11 +4771,11 @@ var silentLogger = createLogger(() => {
4675
4771
  });
4676
4772
 
4677
4773
  // src/logging/sinks/file.ts
4678
- import { join as join10 } from "node:path";
4774
+ import { join as join11 } from "node:path";
4679
4775
  var FILE = /^pmcp-(\d{8})(?:\.\d+)?\.jsonl$/u;
4680
4776
  function dailyLogFile(dir, now = /* @__PURE__ */ new Date()) {
4681
4777
  const day = now.toISOString().slice(0, 10).replaceAll("-", "");
4682
- return join10(dir, `pmcp-${day}.jsonl`);
4778
+ return join11(dir, `pmcp-${day}.jsonl`);
4683
4779
  }
4684
4780
  function roll(file2) {
4685
4781
  let index = 1;
@@ -4710,7 +4806,7 @@ function logFiles(dir) {
4710
4806
  const part = (name) => Number(/\.(\d+)\.jsonl$/u.exec(name)?.[1] ?? Number.MAX_SAFE_INTEGER);
4711
4807
  return names2.sort(
4712
4808
  (a, b) => a.slice(5, 13).localeCompare(b.slice(5, 13)) || part(a) - part(b)
4713
- ).map((name) => join10(dir, name));
4809
+ ).map((name) => join11(dir, name));
4714
4810
  }
4715
4811
  function pruneLogs(dir, keepDays, now = /* @__PURE__ */ new Date()) {
4716
4812
  const cutoff = new Date(now.getTime() - keepDays * 864e5).toISOString().slice(0, 10).replaceAll("-", "");
@@ -4726,13 +4822,13 @@ function pruneLogs(dir, keepDays, now = /* @__PURE__ */ new Date()) {
4726
4822
 
4727
4823
  // src/sessions/state-dir.ts
4728
4824
  import { homedir as homedir3 } from "node:os";
4729
- import { join as join11 } from "node:path";
4825
+ import { join as join12 } from "node:path";
4730
4826
  function projectStateDir(root, override, env = process.env) {
4731
4827
  if (override) return expandPath(root, override);
4732
4828
  const anchor = gitCommonDir(root) ?? realpathSync(root);
4733
4829
  const id = createHash("sha256").update(anchor).digest("hex").slice(0, 16);
4734
- const base = env["XDG_STATE_HOME"] || join11(homedir3(), ".local", "state");
4735
- return join11(base, "pmcp", "projects", id);
4830
+ const base = env["XDG_STATE_HOME"] || join12(homedir3(), ".local", "state");
4831
+ return join12(base, "pmcp", "projects", id);
4736
4832
  }
4737
4833
 
4738
4834
  // src/hooks/entry/logger.ts
@@ -4747,7 +4843,7 @@ function hookLogger(root, compiled, runtime2, event) {
4747
4843
  process.env["PMCP_LOG"]
4748
4844
  );
4749
4845
  const file2 = compiled?.logFile ? expandPath(root, compiled.logFile) : void 0;
4750
- const dir = file2 ? dirname7(file2) : join12(projectStateDir(root, compiled?.stateDir), "logs");
4846
+ const dir = file2 ? dirname8(file2) : join13(projectStateDir(root, compiled?.stateDir), "logs");
4751
4847
  const sink = fileSink({
4752
4848
  dir,
4753
4849
  ...file2 ? { file: file2 } : {},
@@ -4807,10 +4903,10 @@ var gitProbe = {
4807
4903
  };
4808
4904
 
4809
4905
  // src/sessions/files/broadcast.ts
4810
- import { join as join13 } from "node:path";
4906
+ import { join as join14 } from "node:path";
4811
4907
 
4812
4908
  // src/sessions/files/json.ts
4813
- import { dirname as dirname8 } from "node:path";
4909
+ import { dirname as dirname9 } from "node:path";
4814
4910
  function readJson3(path) {
4815
4911
  try {
4816
4912
  return JSON.parse(readFileSync(path, "utf8"));
@@ -4819,7 +4915,7 @@ function readJson3(path) {
4819
4915
  }
4820
4916
  }
4821
4917
  function writeJson(path, value) {
4822
- mkdirSync(dirname8(path), { recursive: true, mode: 448 });
4918
+ mkdirSync(dirname9(path), { recursive: true, mode: 448 });
4823
4919
  const temporary = `${path}.${process.pid}.tmp`;
4824
4920
  writeFileSync(temporary, `${JSON.stringify(value, null, 2)}
4825
4921
  `, {
@@ -4843,7 +4939,7 @@ function readLines(path) {
4843
4939
  });
4844
4940
  }
4845
4941
  function writeLines(path, values) {
4846
- mkdirSync(dirname8(path), { recursive: true, mode: 448 });
4942
+ mkdirSync(dirname9(path), { recursive: true, mode: 448 });
4847
4943
  writeFileSync(
4848
4944
  path,
4849
4945
  `${values.map((value) => JSON.stringify(value)).join("\n")}
@@ -4854,8 +4950,8 @@ function writeLines(path, values) {
4854
4950
 
4855
4951
  // src/sessions/files/broadcast.ts
4856
4952
  function filesBroadcast(dir, keep, registry2) {
4857
- const latestPath = join13(dir, STATE_FILES.broadcast);
4858
- const historyPath = join13(dir, STATE_FILES.history);
4953
+ const latestPath = join14(dir, STATE_FILES.broadcast);
4954
+ const historyPath = join14(dir, STATE_FILES.history);
4859
4955
  const list = () => {
4860
4956
  const latest = asBroadcast(readJson3(latestPath));
4861
4957
  if (!latest) return [];
@@ -4899,60 +4995,80 @@ function filesBroadcast(dir, keep, registry2) {
4899
4995
  }
4900
4996
 
4901
4997
  // src/sessions/files/leases.ts
4902
- import { join as join14 } from "node:path";
4903
- var leasePath = (dir, name) => join14(dir, leaseFile(name));
4904
- function filesLeases(dir) {
4998
+ import { dirname as dirname10, join as join15 } from "node:path";
4999
+ function filesLeases(dir, files2 = {}) {
5000
+ const leasePath = (name) => files2[name]?.file ?? join15(dir, leaseFile(name));
4905
5001
  const read3 = (name) => {
4906
- const lease = asLease(readJson3(leasePath(dir, name)));
5002
+ const lease = asLease(readJson3(leasePath(name)));
4907
5003
  if (!lease || !alive(lease.pid)) return null;
4908
5004
  return lease;
4909
5005
  };
4910
5006
  return {
4911
5007
  read: read3,
5008
+ // Atomic against another process taking the same file (another tool may share it): the
5009
+ // record is linked into place, and a dead holder's record is replaced and then re-read, so
5010
+ // of two takers replacing it at once only the one whose record stays holds the lease.
4912
5011
  take(name, lease) {
4913
- const held = read3(name);
5012
+ const path = leasePath(name);
4914
5013
  const pid = lease.pid ?? process.pid;
4915
- if (held && held.pid !== pid) return false;
4916
- writeJson(leasePath(dir, name), {
5014
+ const record = {
4917
5015
  pid,
4918
5016
  subject: lease.subject,
4919
5017
  ...lease.cwd ? { cwd: lease.cwd } : {},
4920
5018
  since: (/* @__PURE__ */ new Date()).toISOString()
4921
- });
4922
- return true;
5019
+ };
5020
+ mkdirSync(dirname10(path), { recursive: true });
5021
+ const temp = `${path}.${process.pid}.${Date.now()}.tmp`;
5022
+ writeFileSync(temp, `${JSON.stringify(record)}
5023
+ `);
5024
+ try {
5025
+ try {
5026
+ linkSync(temp, path);
5027
+ return true;
5028
+ } catch (error) {
5029
+ if (error.code !== "EEXIST") throw error;
5030
+ }
5031
+ const held = read3(name);
5032
+ if (held && held.pid !== pid) return false;
5033
+ renameSync(temp, path);
5034
+ return asLease(readJson3(path))?.pid === pid;
5035
+ } finally {
5036
+ rmSync(temp, { force: true });
5037
+ }
4923
5038
  },
4924
5039
  release(name, pid = process.pid) {
4925
- const held = asLease(readJson3(leasePath(dir, name)));
5040
+ const path = leasePath(name);
5041
+ const held = asLease(readJson3(path));
4926
5042
  if (!held || held.pid === pid || !alive(held.pid)) {
4927
- rmSync(leasePath(dir, name), { force: true });
5043
+ rmSync(path, { force: true });
4928
5044
  }
4929
5045
  }
4930
5046
  };
4931
5047
  }
4932
5048
 
4933
5049
  // src/sessions/files/mailbox.ts
4934
- import { join as join15 } from "node:path";
5050
+ import { join as join16 } from "node:path";
4935
5051
  var ID = /^\d{13}-[0-9a-f]{8}$/u;
4936
5052
  var SAFE_KEY = /^@?[\w.-]+$/u;
4937
5053
  function filesMailbox(dir, settings) {
4938
- const messages = join15(dir, "messages");
4939
- const inbox = join15(dir, "inbox");
4940
- const pathOf = (id) => join15(messages, `${id}.json`);
5054
+ const messages = join16(dir, "messages");
5055
+ const inbox = join16(dir, "inbox");
5056
+ const pathOf = (id) => join16(messages, `${id}.json`);
4941
5057
  const marker = (key, id, kind) => {
4942
5058
  if (!SAFE_KEY.test(key) || !ID.test(id))
4943
5059
  throw new Error(`invalid mailbox key ${key} or id ${id}`);
4944
- return join15(inbox, key, `${id}.${kind}`);
5060
+ return join16(inbox, key, `${id}.${kind}`);
4945
5061
  };
4946
5062
  const audit = (event, fields2) => {
4947
5063
  if (!settings.audit) return;
4948
5064
  const line = { at: (/* @__PURE__ */ new Date()).toISOString(), event, ...fields2 };
4949
- appendFileSync(join15(dir, "messages.jsonl"), `${JSON.stringify(line)}
5065
+ appendFileSync(join16(dir, "messages.jsonl"), `${JSON.stringify(line)}
4950
5066
  `, {
4951
5067
  mode: 384
4952
5068
  });
4953
5069
  };
4954
5070
  const touch = (path) => {
4955
- mkdirSync(join15(path, ".."), { recursive: true, mode: 448 });
5071
+ mkdirSync(join16(path, ".."), { recursive: true, mode: 448 });
4956
5072
  try {
4957
5073
  writeFileSync(path, "", { flag: "wx", mode: 384 });
4958
5074
  return true;
@@ -4969,7 +5085,7 @@ function filesMailbox(dir, settings) {
4969
5085
  if (existsSync(inbox))
4970
5086
  for (const key of readdirSync(inbox))
4971
5087
  for (const kind of ["ack", "delivered"])
4972
- rmSync(join15(inbox, key, `${message.id}.${kind}`), { force: true });
5088
+ rmSync(join16(inbox, key, `${message.id}.${kind}`), { force: true });
4973
5089
  audit(event, { id: message.id });
4974
5090
  };
4975
5091
  return {
@@ -5045,9 +5161,9 @@ function filesMailbox(dir, settings) {
5045
5161
  }
5046
5162
 
5047
5163
  // src/sessions/files/pause.ts
5048
- import { join as join16 } from "node:path";
5164
+ import { join as join17 } from "node:path";
5049
5165
  function filesPause(dir) {
5050
- const path = join16(dir, STATE_FILES.pause);
5166
+ const path = join17(dir, STATE_FILES.pause);
5051
5167
  return {
5052
5168
  read: () => asPause(readJson3(path)),
5053
5169
  write(pause2) {
@@ -5065,11 +5181,11 @@ function filesPause(dir) {
5065
5181
  }
5066
5182
 
5067
5183
  // src/sessions/files/registry.ts
5068
- import { join as join17 } from "node:path";
5184
+ import { join as join18 } from "node:path";
5069
5185
  var SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/u;
5070
5186
  function filesRegistry(dir, staleMs) {
5071
- const fleetDir = join17(dir, STATE_FILES.records);
5072
- const pathOf = (session) => join17(fleetDir, `${session}.json`);
5187
+ const fleetDir = join18(dir, STATE_FILES.records);
5188
+ const pathOf = (session) => join18(fleetDir, `${session}.json`);
5073
5189
  const get = (session) => SESSION_ID.test(session) ? asRecord(readJson3(pathOf(session))) : null;
5074
5190
  const list = (now = Date.now()) => {
5075
5191
  let names2 = [];
@@ -5078,7 +5194,7 @@ function filesRegistry(dir, staleMs) {
5078
5194
  } catch {
5079
5195
  return [];
5080
5196
  }
5081
- return names2.map((name) => asRecord(readJson3(join17(fleetDir, name)))).filter((record) => record !== null).map((record) => ({ ...record, live: isLive(record, now, staleMs) }));
5197
+ return names2.map((name) => asRecord(readJson3(join18(fleetDir, name)))).filter((record) => record !== null).map((record) => ({ ...record, live: isLive(record, now, staleMs) }));
5082
5198
  };
5083
5199
  const remove = (session) => {
5084
5200
  if (SESSION_ID.test(session)) rmSync(pathOf(session), { force: true });
@@ -5127,7 +5243,7 @@ function createFilesStore(dir, options2 = {}) {
5127
5243
  dir,
5128
5244
  registry: registry2,
5129
5245
  pause: filesPause(dir),
5130
- leases: filesLeases(dir),
5246
+ leases: filesLeases(dir, options2.leaseFiles),
5131
5247
  // With the mailbox on, a broadcast is also a message to all, which the mailbox delivers;
5132
5248
  // broadcast.json stays the record status, snapshot and the Claude band read.
5133
5249
  broadcast: !mailbox2.settings.enabled ? broadcast2 : {
@@ -5151,6 +5267,35 @@ function createFilesStore(dir, options2 = {}) {
5151
5267
  };
5152
5268
  }
5153
5269
 
5270
+ // src/sessions/lease-files.ts
5271
+ import { dirname as dirname11, isAbsolute as isAbsolute13, join as join19 } from "node:path";
5272
+ var GATE_DIR = "${gate_dir}/";
5273
+ function gateTree(root, stateDir, gate, env) {
5274
+ const override = gate.treeEnv ? env[gate.treeEnv] : void 0;
5275
+ if (override) return override;
5276
+ return gate.tree ? expandPath(root, gate.tree) : join19(stateDir, "gate", "tree");
5277
+ }
5278
+ function resolveLeaseFiles(files2, gateDir) {
5279
+ const resolve20 = (path) => path?.startsWith(GATE_DIR) ? join19(gateDir, path.slice(GATE_DIR.length)) : path;
5280
+ return Object.fromEntries(
5281
+ Object.entries(files2 ?? {}).map(([name, f]) => {
5282
+ const file2 = resolve20(f.file);
5283
+ const events2 = resolve20(f.events);
5284
+ return [
5285
+ name,
5286
+ { ...file2 ? { file: file2 } : {}, ...events2 ? { events: events2 } : {} }
5287
+ ];
5288
+ })
5289
+ );
5290
+ }
5291
+ function leaseFilesFor(root, stateDir, files2, gate, env) {
5292
+ if (!files2 || Object.keys(files2).length === 0) return {};
5293
+ return resolveLeaseFiles(
5294
+ files2,
5295
+ dirname11(gateTree(root, stateDir, gate ?? {}, env))
5296
+ );
5297
+ }
5298
+
5154
5299
  // src/hooks/entry.ts
5155
5300
  async function main(argv, root) {
5156
5301
  if (argv[0] === "--state-dir") {
@@ -5170,20 +5315,30 @@ async function main(argv, root) {
5170
5315
  if (adapter.silent) writeStdout(adapter.silent(event));
5171
5316
  return 0;
5172
5317
  };
5318
+ let compiled = null;
5319
+ let payload = null;
5320
+ let input = null;
5173
5321
  try {
5174
- const compiled = readCompiled(root);
5175
- const payload = JSON.parse(readStdin() || "{}");
5322
+ compiled = readCompiled(root);
5323
+ payload = JSON.parse(readStdin() || "{}");
5176
5324
  adapter = guestFor(projected, payload, compiled.targets);
5177
5325
  log = hookLogger(root, compiled, adapter.id, event);
5178
5326
  if (!compiled.targets.includes(adapter.id)) return pass2();
5179
5327
  const native = adapter.nativeEvent(event);
5180
- const input = native ? adapter.normalize(native, payload, root) : null;
5328
+ input = native ? adapter.normalize(native, payload, root) : null;
5181
5329
  if (!input) return pass2();
5182
5330
  const run3 = log.child({ session: input.session.id });
5183
- const store = createFilesStore(
5184
- projectStateDir(root, compiled.stateDir),
5185
- compiled.sessions
5186
- );
5331
+ const stateDir = projectStateDir(root, compiled.stateDir);
5332
+ const store = createFilesStore(stateDir, {
5333
+ ...compiled.sessions,
5334
+ leaseFiles: leaseFilesFor(
5335
+ root,
5336
+ stateDir,
5337
+ compiled.sessions.leaseFiles,
5338
+ compiled.sessions.gate,
5339
+ process.env
5340
+ )
5341
+ });
5187
5342
  const decision = await dispatch(input, compiled, {
5188
5343
  log: run3,
5189
5344
  git: gitProbe,
@@ -5205,15 +5360,28 @@ async function main(argv, root) {
5205
5360
  log.error("hook failed", {
5206
5361
  error: error instanceof Error ? error.message : String(error)
5207
5362
  });
5363
+ const failure = error instanceof PolicyIntegrityError ? void 0 : compiled?.failure ?? rawFailure(root);
5364
+ if (failure) {
5365
+ if (!input && payload !== null) {
5366
+ try {
5367
+ const native = adapter.nativeEvent(event);
5368
+ input = native ? adapter.normalize(native, payload, root) : null;
5369
+ } catch {
5370
+ input = null;
5371
+ }
5372
+ }
5373
+ writeStdout(failedEntry(adapter, event, root, input, failure, error));
5374
+ return 0;
5375
+ }
5208
5376
  writeStdout(failClosed(adapter, event, root, error));
5209
5377
  return 0;
5210
5378
  }
5211
5379
  }
5212
5380
  var self = import.meta.filename;
5213
- if (process.argv[1] && resolve18(process.argv[1]) === self) {
5381
+ if (process.argv[1] && resolve19(process.argv[1]) === self) {
5214
5382
  process.exitCode = await main(
5215
5383
  process.argv.slice(2),
5216
- resolve18(dirname9(self), "../..")
5384
+ resolve19(dirname12(self), "../..")
5217
5385
  );
5218
5386
  }
5219
5387
  export {