@modootoday/pmcp 0.22.8 → 0.22.10

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 (75) 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-T26VVWOZ.js → apply-U3ZXKI7A.js} +9 -9
  6. package/dist/{chunk-AY2JWFTO.js → chunk-5S7YW764.js} +2 -2
  7. package/dist/{chunk-7GVHEUCI.js → chunk-6HQYDPF4.js} +5 -5
  8. package/dist/{chunk-XHBWMWZM.js → chunk-6J7QS6OU.js} +2 -2
  9. package/dist/{chunk-2C7YCZCU.js → chunk-7O5PZMMZ.js} +5 -5
  10. package/dist/{chunk-H7UCINE3.js → chunk-ACBTBCCP.js} +2 -2
  11. package/dist/{chunk-HJRD7R3L.js → chunk-AHTWOXRM.js} +3 -3
  12. package/dist/{chunk-7DYWCQVB.js → chunk-ARXCYFFZ.js} +1 -1
  13. package/dist/{chunk-7MC2ECUI.js → chunk-ASEPCCIF.js} +12 -12
  14. package/dist/{chunk-ZWRMK5TZ.js → chunk-AYAYA26J.js} +3 -3
  15. package/dist/{chunk-4LB4665T.js → chunk-DMBXFSBT.js} +3 -3
  16. package/dist/chunk-EWVCW475.js +7 -0
  17. package/dist/{chunk-HVCBG4MT.js → chunk-IEHSW5KZ.js} +2 -2
  18. package/dist/{chunk-6N7YO2MJ.js → chunk-IYRCOMJ3.js} +1080 -327
  19. package/dist/{chunk-MBWFCWBY.js → chunk-KENKFUKQ.js} +2 -2
  20. package/dist/{chunk-CILQCERV.js → chunk-KPKMEUUH.js} +2 -2
  21. package/dist/{chunk-UVHL7DOT.js → chunk-PKLW5B6F.js} +2 -2
  22. package/dist/{chunk-PAXVHM4E.js → chunk-SDKM5XLY.js} +5 -5
  23. package/dist/{chunk-WEOSWF6Q.js → chunk-V36R56EC.js} +3 -3
  24. package/dist/{chunk-LYMX6G4B.js → chunk-WHGWUGUE.js} +2 -2
  25. package/dist/{chunk-QW6PHF5K.js → chunk-X5BNN7WH.js} +2 -2
  26. package/dist/{chunk-HRZ44RLZ.js → chunk-YGX4YPJ4.js} +2 -2
  27. package/dist/{cli-ZTYST4U5.js → cli-JXPJFHUA.js} +3 -3
  28. package/dist/cli.js +3 -3
  29. package/dist/{completion-BNGZXFIX.js → completion-YRHYNNQJ.js} +2 -2
  30. package/dist/{diagnostics-EDOHR27L.js → diagnostics-HF664XER.js} +5 -5
  31. package/dist/{doctor-QENZSTX4.js → doctor-AA7KSFSZ.js} +10 -10
  32. package/dist/{entry-KQQ2WVS3.js → entry-SVJKWWRX.js} +9 -9
  33. package/dist/{exec-mcp-7J6I2TFN.js → exec-mcp-REREJQZS.js} +6 -6
  34. package/dist/{harness-5V7C7W4X.js → harness-5J2QPEAG.js} +3 -3
  35. package/dist/harness-launch-gate.js +3 -3
  36. package/dist/harness-worker.js +5 -5
  37. package/dist/hook-body.js +1253 -476
  38. package/dist/{hooks-YH27BJNA.js → hooks-F235VOD5.js} +3 -3
  39. package/dist/{host-LDKQLXZK.js → host-6RMVD7WT.js} +6 -6
  40. package/dist/{host-BPL4QYTV.js → host-G63ENESI.js} +8 -8
  41. package/dist/{host-run-JQQRBC3B.js → host-run-6QLLKBXA.js} +4 -4
  42. package/dist/http.js +1 -1
  43. package/dist/{import-mcp-ECOJNVES.js → import-mcp-XCATZ4FG.js} +5 -5
  44. package/dist/index.d.ts +1 -1
  45. package/dist/index.js +9 -9
  46. package/dist/{init-SFD2AD55.js → init-7S7YIUTV.js} +2 -2
  47. package/dist/{invoke-XKDBJWZR.js → invoke-YNRYQRAS.js} +7 -7
  48. package/dist/{list-YQMLWGDZ.js → list-XXQXZWDF.js} +7 -7
  49. package/dist/{logout-ULJ7Y5GJ.js → logout-QUTGV2WF.js} +6 -6
  50. package/dist/{mainline-SQSAUOMQ.js → mainline-74WCH4T4.js} +21 -7
  51. package/dist/{mcp-AWSPXJ5K.js → mcp-J7FQGJT2.js} +2 -2
  52. package/dist/{project-XWAGF3LG.js → project-RAB5YUJG.js} +4 -4
  53. package/dist/{run-VUIMTTUN.js → run-ZCTDZTZG.js} +5 -5
  54. package/dist/{run-ESKEMSV6.js → run-ZKVZSZZD.js} +4 -4
  55. package/dist/{serve-N3QMQTFP.js → serve-A3T73BAD.js} +3 -3
  56. package/dist/{smoke-UA7VVDKD.js → smoke-2FI5D74B.js} +3 -3
  57. package/dist/{start-login-OAG3OUDP.js → start-login-UFWY6IE7.js} +6 -6
  58. package/dist/{status-XULZJ677.js → status-BHC34INJ.js} +6 -6
  59. package/dist/{status-OKH3ZY6V.js → status-JBCQDSVM.js} +7 -7
  60. package/dist/stdio.js +2 -2
  61. package/dist/{test-MP634HCP.js → test-XJJSVALB.js} +29 -21
  62. package/dist/{tui-TKV3C3XM.js → tui-WQ6J5AXI.js} +4 -4
  63. package/dist/{worker-53EP7EUT.js → worker-3BAZVDL5.js} +7 -7
  64. package/docs/hooks.md +13 -3
  65. package/docs/upgrading.md +8 -0
  66. package/gemini-extension.json +2 -2
  67. package/mcp.json +1 -1
  68. package/package.json +5 -5
  69. package/plugin.json +1 -1
  70. package/plugins/pmcp/.claude-plugin/plugin.json +1 -1
  71. package/plugins/pmcp/.mcp.json +1 -1
  72. package/plugins/pmcp/gemini-extension.json +2 -2
  73. package/plugins/pmcp/mcp.json +1 -1
  74. package/plugins/pmcp/plugin.json +1 -1
  75. package/dist/chunk-Y7F4EY35.js +0 -7
package/dist/hook-body.js CHANGED
@@ -297,186 +297,841 @@ function expandPath(base, path) {
297
297
  return isAbsolute(path) ? path : resolve2(mainCheckoutBase(base), path);
298
298
  }
299
299
 
300
- // src/hooks/dispatch/emergency.ts
301
- var READ_ONLY = /* @__PURE__ */ new Set([
302
- "cat",
303
- "ls",
304
- "stat",
305
- "test",
306
- "[",
307
- "head",
308
- "tail",
309
- "wc",
310
- "file"
311
- ]);
312
- var REASON = "The emergency off switch belongs to the operator; agents may not create, change or delete it.";
313
- function emergencyActive(root, file2) {
314
- return file2 !== void 0 && existsSync(expandPath(root, file2));
315
- }
316
- function protectOffFile(input, file2) {
317
- const tool = input.tool;
318
- if (!file2 || input.event !== "before_tool" || !tool) return {};
319
- const target = expandPath(input.projectRoot, file2);
320
- if (tool.kind === "edit") {
321
- return tool.paths.some((path) => resolve3(path) === target) ? { verdict: "deny", reason: REASON } : {};
322
- }
323
- if (tool.kind !== "shell") return {};
324
- if (!tool.steps) {
325
- return (tool.command ?? "").includes(file2) ? { verdict: "deny", reason: REASON } : {};
326
- }
327
- const names3 = tool.steps.some(
328
- (step) => !READ_ONLY.has(step.argv[0] ?? "") && step.raw.some(
329
- (word) => word === file2 || expandPath(resolve3(input.cwd, step.dir), word) === target
330
- )
331
- );
332
- return names3 ? { verdict: "deny", reason: REASON } : {};
333
- }
300
+ // src/hooks/shell/commands.ts
301
+ import { homedir as homedir2 } from "node:os";
302
+ import { isAbsolute as isAbsolute2, join as join4 } from "node:path";
334
303
 
335
- // src/hooks/shell/tokenize.ts
336
- var SEPARATORS = /* @__PURE__ */ new Set([
304
+ // src/hooks/shell/parse/scanner.ts
305
+ var ShellSyntaxError = class extends Error {
306
+ constructor(message, at) {
307
+ super(`${message} at offset ${at}`);
308
+ this.at = at;
309
+ }
310
+ };
311
+ var OPERATORS = [
312
+ ";;&",
337
313
  "&&",
338
314
  "||",
315
+ ";;",
316
+ ";&",
317
+ "|&",
339
318
  ";",
340
- "|",
341
319
  "&",
342
- "\n",
320
+ "|",
343
321
  "(",
344
322
  ")",
345
- "{",
346
- "}"
347
- ]);
348
- function quoteEnd(text9, start) {
349
- for (let index = start; index < text9.length; index += 1) {
350
- const char = text9[index];
351
- if (char === "\\") index += 1;
352
- else if (char === '"') return index;
353
- else if (text9.startsWith("$(", index)) {
354
- const close2 = closing(text9, index + 2);
355
- if (close2 < 0) return -1;
356
- index = close2;
357
- } else if (char === "`") {
358
- const close2 = text9.indexOf("`", index + 1);
359
- if (close2 < 0) return -1;
360
- index = close2;
323
+ "\n"
324
+ ];
325
+ var REDIRECTS = [
326
+ "&>>",
327
+ "<<<",
328
+ "<<-",
329
+ "&>",
330
+ ">>",
331
+ ">|",
332
+ "<>",
333
+ "<<",
334
+ ">&",
335
+ "<&",
336
+ ">",
337
+ "<"
338
+ ];
339
+ var BREAKS = /* @__PURE__ */ new Set([" ", " ", "\n", ";", "&", "|", "<", ">", "(", ")"]);
340
+ var TEST_OPERATORS = ["&&", "||", "(", ")", "<", ">"];
341
+ var ARRAY_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=$/u;
342
+ var PARAM = /\$(?:([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)\})/uy;
343
+ var ANSI_ESCAPES = {
344
+ n: "\n",
345
+ t: " ",
346
+ r: "\r",
347
+ a: "\x07",
348
+ b: "\b",
349
+ e: "\x1B",
350
+ E: "\x1B",
351
+ f: "\f",
352
+ v: "\v"
353
+ };
354
+ var Scanner = class _Scanner {
355
+ constructor(text9, pos, nested) {
356
+ this.text = text9;
357
+ this.pos = pos;
358
+ this.nested = nested;
359
+ }
360
+ pending = [];
361
+ token() {
362
+ this.blank();
363
+ const { text: text9 } = this;
364
+ const start2 = this.pos;
365
+ if (start2 >= text9.length) return { kind: "eof", start: start2 };
366
+ if (text9[start2] === "\n") {
367
+ this.pos += 1;
368
+ this.heredocs();
369
+ return { kind: "op", op: "\n", start: start2 };
370
+ }
371
+ if (!text9.startsWith("<(", start2) && !text9.startsWith(">(", start2)) {
372
+ const fd = /^\d+(?=[<>])/u.exec(text9.slice(start2, start2 + 12))?.[0] ?? "";
373
+ const at = start2 + fd.length;
374
+ const redirect = REDIRECTS.find((op2) => text9.startsWith(op2, at));
375
+ if (redirect) {
376
+ this.pos = at + redirect.length;
377
+ return { kind: "redirect", op: redirect, fd, start: start2 };
378
+ }
379
+ const op = OPERATORS.find(
380
+ (candidate) => text9.startsWith(candidate, start2)
381
+ );
382
+ if (op) {
383
+ this.pos += op.length;
384
+ return { kind: "op", op, start: start2 };
385
+ }
386
+ }
387
+ const word = this.word();
388
+ if (this.pos === start2)
389
+ throw new ShellSyntaxError(`unexpected ${text9[start2]}`, start2);
390
+ return { kind: "word", word, raw: text9.slice(start2, this.pos), start: start2 };
391
+ }
392
+ // A word inside [[ ]], where < > ( ) && || belong to the test; null at the closing ]].
393
+ testWord(regex) {
394
+ const { text: text9 } = this;
395
+ while (" \n".includes(text9[this.pos] ?? "x") || text9.startsWith("\\\n", this.pos))
396
+ this.pos += text9[this.pos] === "\\" ? 2 : 1;
397
+ const start2 = this.pos;
398
+ if (start2 >= text9.length) throw new ShellSyntaxError("unclosed [[", start2);
399
+ if (text9.startsWith("]]", start2) && this.ends(start2 + 2)) {
400
+ this.pos += 2;
401
+ return null;
361
402
  }
403
+ const op = TEST_OPERATORS.find(
404
+ (candidate) => text9.startsWith(candidate, start2)
405
+ );
406
+ if (op && !regex) {
407
+ this.pos += op.length;
408
+ return { word: { text: op, nested: [], params: [] }, raw: op };
409
+ }
410
+ const word = this.word(regex);
411
+ if (this.pos === start2)
412
+ throw new ShellSyntaxError(`unexpected ${text9[start2]}`, start2);
413
+ return { word, raw: text9.slice(start2, this.pos) };
414
+ }
415
+ // The (( ... )) starting at pos as one word, or null when the parentheses close as a subshell.
416
+ arithmetic(pos) {
417
+ const nested = [];
418
+ const end = this.arithmeticEnd(pos, nested);
419
+ if (end < 0) return null;
420
+ this.pos = end;
421
+ return { text: this.text.slice(pos + 2, end - 2), nested, params: [] };
422
+ }
423
+ heredoc(redirect, delimiter2, raw, strip) {
424
+ this.pending.push({
425
+ redirect,
426
+ delimiter: delimiter2.text,
427
+ strip,
428
+ quoted: /['"\\]/u.test(raw)
429
+ });
362
430
  }
363
- return -1;
364
- }
365
- function closing(text9, start) {
366
- let depth = 1;
367
- for (let index = start; index < text9.length; index += 1) {
368
- const char = text9[index];
369
- let skipTo = index;
370
- if (char === "\\") skipTo = index + 1;
371
- if (char === "'") skipTo = text9.indexOf("'", index + 1);
372
- if (char === "`") skipTo = text9.indexOf("`", index + 1);
373
- if (char === '"') skipTo = quoteEnd(text9, index + 1);
374
- if (skipTo < 0) return -1;
375
- if (skipTo !== index) {
376
- index = skipTo;
377
- continue;
431
+ ends(at) {
432
+ const char = this.text[at];
433
+ return char === void 0 || BREAKS.has(char);
434
+ }
435
+ blank() {
436
+ const { text: text9 } = this;
437
+ for (; ; ) {
438
+ const char = text9[this.pos];
439
+ if (char === " " || char === " ") this.pos += 1;
440
+ else if (text9.startsWith("\\\n", this.pos)) this.pos += 2;
441
+ else if (char === "#") {
442
+ const end = text9.indexOf("\n", this.pos);
443
+ this.pos = end < 0 ? text9.length : end;
444
+ } else return;
378
445
  }
379
- if (char === "(") depth += 1;
380
- if (char === ")") depth -= 1;
381
- if (depth === 0) return index;
382
- }
383
- return -1;
384
- }
385
- function tokenize(script) {
386
- const tokens = [];
387
- const nested = [];
388
- let word = "";
389
- let started = false;
390
- const flush = () => {
391
- if (started) tokens.push(word);
392
- word = "";
393
- started = false;
394
- };
395
- for (let index = 0; index < script.length; index += 1) {
396
- const char = script[index];
397
- const pair = script.slice(index, index + 2);
398
- if (char === "'") {
399
- const end = script.indexOf("'", index + 1);
400
- if (end < 0) return null;
401
- word += script.slice(index + 1, end);
402
- started = true;
403
- index = end;
404
- continue;
446
+ }
447
+ word(regex = false) {
448
+ const { text: text9 } = this;
449
+ const start2 = this.pos;
450
+ const nested = [];
451
+ const params = [];
452
+ let out = "";
453
+ let depth = 0;
454
+ while (this.pos < text9.length) {
455
+ const char = text9[this.pos];
456
+ const next = text9[this.pos + 1];
457
+ if ((char === "<" || char === ">") && next === "(") {
458
+ const inner = this.nested.at(text9, this.pos + 2);
459
+ nested.push(inner.list);
460
+ this.pos = inner.end;
461
+ out += "$()";
462
+ continue;
463
+ }
464
+ if (char === "(" && !regex && ARRAY_ASSIGNMENT.test(text9.slice(start2, this.pos))) {
465
+ out += this.array(nested);
466
+ continue;
467
+ }
468
+ if (regex && char === "(") depth += 1;
469
+ if (regex && char === ")" && depth > 0) depth -= 1;
470
+ const inRegex = regex && ("()|".includes(char) || depth > 0 && char === " ");
471
+ if (BREAKS.has(char) && !inRegex) break;
472
+ if (char === "\\") {
473
+ if (next !== "\n") out += next ?? "";
474
+ this.pos += 2;
475
+ continue;
476
+ }
477
+ if (char === "'") {
478
+ const end = text9.indexOf("'", this.pos + 1);
479
+ if (end < 0) throw new ShellSyntaxError("unclosed '", this.pos);
480
+ out += text9.slice(this.pos + 1, end);
481
+ this.pos = end + 1;
482
+ continue;
483
+ }
484
+ if (char === "$" && next === "'") {
485
+ out += this.ansi();
486
+ continue;
487
+ }
488
+ if (char === "$" && next === '"') {
489
+ this.pos += 1;
490
+ continue;
491
+ }
492
+ if (char === '"') {
493
+ this.pos += 1;
494
+ out += this.quoted('"', nested, { params, base: out.length });
495
+ continue;
496
+ }
497
+ const expansion = this.expansion(nested, { params, base: out.length });
498
+ if (expansion !== null) {
499
+ out += expansion;
500
+ continue;
501
+ }
502
+ out += char;
503
+ this.pos += 1;
405
504
  }
406
- if (char === '"' || char === "`") {
407
- let end = index + 1;
408
- let text9 = "";
409
- while (end < script.length && script[end] !== char) {
410
- if (script[end] === "\\" && char === '"') {
411
- text9 += script[end + 1] ?? "";
412
- end += 2;
413
- continue;
414
- }
415
- if (char === '"' && script.startsWith("$(", end)) {
416
- const close2 = closing(script, end + 2);
417
- if (close2 < 0) return null;
418
- nested.push(script.slice(end + 2, close2));
419
- end = close2 + 1;
420
- continue;
421
- }
422
- if (char === '"' && script[end] === "`") {
423
- const close2 = script.indexOf("`", end + 1);
424
- if (close2 < 0) return null;
425
- nested.push(script.slice(end + 1, close2));
426
- end = close2 + 1;
427
- continue;
428
- }
429
- text9 += script[end];
430
- end += 1;
505
+ return { text: out, nested, params };
506
+ }
507
+ // Double-quoted text up to close, or to the end for a here-document body (close null).
508
+ quoted(close2, nested, sink) {
509
+ const { text: text9 } = this;
510
+ let out = "";
511
+ while (this.pos < text9.length) {
512
+ const char = text9[this.pos];
513
+ if (char === close2) {
514
+ this.pos += 1;
515
+ return out;
431
516
  }
432
- if (end >= script.length) return null;
433
- if (char === "`") nested.push(text9);
434
- if (char === '"') word += text9;
435
- started = true;
436
- index = end;
437
- continue;
517
+ if (char === "\\") {
518
+ const next = text9[this.pos + 1] ?? "";
519
+ if (next !== "\n") out += '$`"\\'.includes(next) ? next : `\\${next}`;
520
+ this.pos += 2;
521
+ continue;
522
+ }
523
+ const expansion = this.expansion(
524
+ nested,
525
+ sink && { params: sink.params, base: sink.base + out.length }
526
+ );
527
+ if (expansion !== null) {
528
+ out += expansion;
529
+ continue;
530
+ }
531
+ out += char;
532
+ this.pos += 1;
438
533
  }
439
- if (pair === "$(") {
440
- const close2 = closing(script, index + 2);
441
- if (close2 < 0) return null;
442
- nested.push(script.slice(index + 2, close2));
443
- word += "$()";
444
- started = true;
445
- index = close2;
446
- continue;
534
+ if (close2 !== null)
535
+ throw new ShellSyntaxError(`unclosed ${close2}`, this.pos);
536
+ return out;
537
+ }
538
+ expansion(nested, sink) {
539
+ const { text: text9 } = this;
540
+ const at = this.pos;
541
+ PARAM.lastIndex = at;
542
+ const param = PARAM.exec(text9);
543
+ if (param) {
544
+ this.pos = PARAM.lastIndex;
545
+ sink?.params.push({
546
+ name: param[1] ?? param[2],
547
+ start: sink.base,
548
+ end: sink.base + param[0].length
549
+ });
550
+ return param[0];
447
551
  }
448
- if (char === "\\") {
449
- word += script[index + 1] ?? "";
450
- started = true;
552
+ if (text9.startsWith("$((", at)) {
553
+ const end = this.arithmeticEnd(at + 1, nested);
554
+ if (end >= 0) {
555
+ this.pos = end;
556
+ return text9.slice(at, end);
557
+ }
558
+ }
559
+ if (text9.startsWith("$(", at)) {
560
+ const inner = this.nested.at(text9, at + 2);
561
+ nested.push(inner.list);
562
+ this.pos = inner.end;
563
+ return "$()";
564
+ }
565
+ if (text9.startsWith("${", at)) {
566
+ this.pos = this.braceEnd(at + 2, nested);
567
+ return text9.slice(at, this.pos);
568
+ }
569
+ if (text9[at] === "`") {
570
+ nested.push(this.backtick());
571
+ return "$()";
572
+ }
573
+ return null;
574
+ }
575
+ // Index just past the )) closing the (( at open, or -1 when a lone ) closes it first.
576
+ arithmeticEnd(open2, nested) {
577
+ const { text: text9 } = this;
578
+ const found = [];
579
+ let depth = 0;
580
+ let index = open2 + 2;
581
+ while (index < text9.length) {
582
+ const char = text9[index];
583
+ if (char === "\\") {
584
+ index += 2;
585
+ continue;
586
+ }
587
+ if (text9.startsWith("$(", index) && !text9.startsWith("$((", index)) {
588
+ const inner = this.nested.at(text9, index + 2);
589
+ found.push(inner.list);
590
+ index = inner.end;
591
+ continue;
592
+ }
593
+ if (char === "(") depth += 1;
594
+ if (char === ")") {
595
+ if (depth === 0) {
596
+ if (text9[index + 1] !== ")") return -1;
597
+ nested.push(...found);
598
+ return index + 2;
599
+ }
600
+ depth -= 1;
601
+ }
451
602
  index += 1;
452
- continue;
453
603
  }
454
- if (char === "#" && !started) {
455
- const end = script.indexOf("\n", index);
456
- index = end < 0 ? script.length : end - 1;
457
- continue;
604
+ return -1;
605
+ }
606
+ // Index just past the } closing a ${ whose body starts at from.
607
+ braceEnd(from, nested) {
608
+ const { text: text9 } = this;
609
+ let depth = 1;
610
+ this.pos = from;
611
+ while (this.pos < text9.length) {
612
+ const char = text9[this.pos];
613
+ if (char === "\\") {
614
+ this.pos += 2;
615
+ continue;
616
+ }
617
+ if (char === "'") {
618
+ const end = text9.indexOf("'", this.pos + 1);
619
+ if (end < 0) throw new ShellSyntaxError("unclosed '", this.pos);
620
+ this.pos = end + 1;
621
+ continue;
622
+ }
623
+ if (char === '"') {
624
+ this.pos += 1;
625
+ this.quoted('"', nested);
626
+ continue;
627
+ }
628
+ if (text9.startsWith("${", this.pos)) {
629
+ depth += 1;
630
+ this.pos += 2;
631
+ continue;
632
+ }
633
+ if (char === "}") {
634
+ depth -= 1;
635
+ this.pos += 1;
636
+ if (depth === 0) return this.pos;
637
+ continue;
638
+ }
639
+ if (this.expansion(nested) === null) this.pos += 1;
458
640
  }
459
- if (pair === "&&" || pair === "||") {
460
- flush();
461
- tokens.push(pair);
641
+ throw new ShellSyntaxError("unclosed ${", from);
642
+ }
643
+ backtick() {
644
+ const { text: text9 } = this;
645
+ let inner = "";
646
+ let index = this.pos + 1;
647
+ while (index < text9.length && text9[index] !== "`") {
648
+ const next = text9[index + 1] ?? "";
649
+ if (text9[index] === "\\" && "$`\\".includes(next)) {
650
+ inner += next;
651
+ index += 2;
652
+ continue;
653
+ }
654
+ inner += text9[index];
462
655
  index += 1;
463
- continue;
464
656
  }
465
- if (SEPARATORS.has(char)) {
466
- flush();
467
- tokens.push(char);
468
- continue;
657
+ if (index >= text9.length)
658
+ throw new ShellSyntaxError("unclosed `", this.pos);
659
+ this.pos = index + 1;
660
+ return this.nested.whole(inner);
661
+ }
662
+ ansi() {
663
+ const { text: text9 } = this;
664
+ let out = "";
665
+ let index = this.pos + 2;
666
+ while (index < text9.length && text9[index] !== "'") {
667
+ if (text9[index] === "\\") {
668
+ const next = text9[index + 1] ?? "";
669
+ out += ANSI_ESCAPES[next] ?? next;
670
+ index += 2;
671
+ continue;
672
+ }
673
+ out += text9[index];
674
+ index += 1;
469
675
  }
470
- if (char === " " || char === " ") {
471
- flush();
472
- continue;
676
+ if (index >= text9.length)
677
+ throw new ShellSyntaxError("unclosed $'", this.pos);
678
+ this.pos = index + 1;
679
+ return out;
680
+ }
681
+ // The (...) of name=(...), its elements as words.
682
+ array(nested) {
683
+ const { text: text9 } = this;
684
+ const elements = [];
685
+ this.pos += 1;
686
+ for (; ; ) {
687
+ while (" \n".includes(text9[this.pos] ?? "x")) this.pos += 1;
688
+ if (text9[this.pos] === "#") this.blank();
689
+ if (this.pos >= text9.length)
690
+ throw new ShellSyntaxError("unclosed (", this.pos);
691
+ if (text9[this.pos] === ")") {
692
+ this.pos += 1;
693
+ return `(${elements.join(" ")})`;
694
+ }
695
+ const start2 = this.pos;
696
+ const element = this.word();
697
+ if (this.pos === start2)
698
+ throw new ShellSyntaxError(`unexpected ${text9[start2]}`, start2);
699
+ nested.push(...element.nested);
700
+ elements.push(element.text);
473
701
  }
474
- word += char;
475
- started = true;
476
702
  }
477
- flush();
478
- return { tokens, nested };
479
- }
703
+ heredocs() {
704
+ const { text: text9 } = this;
705
+ const pending = this.pending;
706
+ this.pending = [];
707
+ for (const doc of pending) {
708
+ let body = "";
709
+ while (this.pos < text9.length) {
710
+ const end = text9.indexOf("\n", this.pos);
711
+ const stop = end < 0 ? text9.length : end;
712
+ const line = text9.slice(this.pos, stop);
713
+ this.pos = end < 0 ? stop : end + 1;
714
+ if ((doc.strip ? line.replace(/^\t+/u, "") : line) === doc.delimiter)
715
+ break;
716
+ body += `${line}
717
+ `;
718
+ }
719
+ doc.redirect.body = doc.quoted ? { text: body, nested: [], params: [] } : this.expanded(body);
720
+ }
721
+ }
722
+ expanded(body) {
723
+ const scanner = new _Scanner(body, 0, this.nested);
724
+ const nested = [];
725
+ return { text: scanner.quoted(null, nested), nested, params: [] };
726
+ }
727
+ };
728
+
729
+ // src/hooks/shell/parse/parser.ts
730
+ var LIST_END_OPERATORS = /* @__PURE__ */ new Set([")", ";;", ";&", ";;&"]);
731
+ var CASE_ENDS = /* @__PURE__ */ new Set([";;", ";&", ";;&"]);
732
+ var NO_KEYWORDS = /* @__PURE__ */ new Set();
733
+ var ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=/u;
734
+ var ARRAY = /^[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=\(/u;
735
+ var DECLARES = /* @__PURE__ */ new Set(["declare", "local", "export", "readonly", "typeset"]);
736
+ var CONTINUATIONS = /* @__PURE__ */ new Set([
737
+ "then",
738
+ "elif",
739
+ "else",
740
+ "fi",
741
+ "do",
742
+ "done",
743
+ "esac",
744
+ "}",
745
+ // ! negates a whole pipeline, so it cannot follow a |.
746
+ "!"
747
+ ]);
748
+ var NESTED = {
749
+ at(text9, pos) {
750
+ const parser = new Parser(text9, pos);
751
+ const list = parser.list(NO_KEYWORDS);
752
+ parser.op(")");
753
+ return { list, end: parser.position() };
754
+ },
755
+ whole: runnable
756
+ };
757
+ function runnable(text9) {
758
+ try {
759
+ return parseScript(text9);
760
+ } catch (error) {
761
+ if (!(error instanceof ShellSyntaxError)) throw error;
762
+ const line = lineStart(text9, error.at);
763
+ return line === 0 ? [] : runnable(text9.slice(0, line));
764
+ }
765
+ }
766
+ function lineStart(text9, at) {
767
+ let newline = text9.lastIndexOf("\n", Math.min(at, text9.length - 1) - 1);
768
+ while (newline >= 0 && continued(text9, newline)) {
769
+ newline = text9.lastIndexOf("\n", newline - 1);
770
+ }
771
+ return newline + 1;
772
+ }
773
+ function continued(text9, newline) {
774
+ let slashes = 0;
775
+ while (text9[newline - 1 - slashes] === "\\") slashes += 1;
776
+ return slashes % 2 === 1;
777
+ }
778
+ function parseScript(text9) {
779
+ const parser = new Parser(text9, 0);
780
+ const list = parser.list(NO_KEYWORDS);
781
+ parser.end();
782
+ return list;
783
+ }
784
+ function describe(token) {
785
+ if (token.kind === "eof") return "end of input";
786
+ if (token.kind === "word") return token.raw;
787
+ return token.op === "\n" ? "newline" : token.op;
788
+ }
789
+ var Parser = class {
790
+ scan;
791
+ ahead;
792
+ constructor(text9, pos) {
793
+ this.scan = new Scanner(text9, pos, NESTED);
794
+ }
795
+ position() {
796
+ return this.scan.pos;
797
+ }
798
+ end() {
799
+ const token = this.peek();
800
+ if (token.kind !== "eof") this.fail(token);
801
+ }
802
+ op(op) {
803
+ const token = this.next();
804
+ if (token.kind !== "op" || token.op !== op) this.fail(token, op);
805
+ }
806
+ // Items until a token that closes the enclosing construct: ), ;;, the end, or a keyword in ends.
807
+ list(ends) {
808
+ const items = [];
809
+ for (; ; ) {
810
+ this.newlines();
811
+ const token = this.peek();
812
+ if (token.kind === "eof") return items;
813
+ if (token.kind === "op" && LIST_END_OPERATORS.has(token.op)) return items;
814
+ if (token.kind === "word" && ends.has(token.raw)) return items;
815
+ const { pipelines, operators } = this.andOr();
816
+ const after = this.peek();
817
+ const separator = after.kind === "op" && [";", "&", "\n"].includes(after.op) ? after.op : "";
818
+ items.push({ pipelines, operators, background: separator === "&" });
819
+ if (!separator) return items;
820
+ this.next();
821
+ }
822
+ }
823
+ peek() {
824
+ this.ahead ??= this.scan.token();
825
+ return this.ahead;
826
+ }
827
+ next() {
828
+ const token = this.peek();
829
+ this.ahead = void 0;
830
+ return token;
831
+ }
832
+ fail(token, expected) {
833
+ const found = describe(token);
834
+ throw new ShellSyntaxError(
835
+ expected ? `expected ${expected}, found ${found}` : `unexpected ${found}`,
836
+ token.start
837
+ );
838
+ }
839
+ isWord(token, raw) {
840
+ return token.kind === "word" && token.raw === raw;
841
+ }
842
+ keyword(raw) {
843
+ const token = this.next();
844
+ if (!this.isWord(token, raw)) this.fail(token, raw);
845
+ }
846
+ word() {
847
+ const token = this.next();
848
+ if (token.kind !== "word") this.fail(token, "a word");
849
+ return { word: token.word, raw: token.raw };
850
+ }
851
+ newlines() {
852
+ for (; ; ) {
853
+ const token = this.peek();
854
+ if (token.kind !== "op" || token.op !== "\n") return;
855
+ this.next();
856
+ }
857
+ }
858
+ andOr() {
859
+ const pipelines = [this.pipeline()];
860
+ const operators = [];
861
+ for (; ; ) {
862
+ const token = this.peek();
863
+ if (token.kind !== "op" || token.op !== "&&" && token.op !== "||")
864
+ return { pipelines, operators };
865
+ this.next();
866
+ operators.push(token.op);
867
+ this.newlines();
868
+ pipelines.push(this.pipeline());
869
+ }
870
+ }
871
+ pipeline() {
872
+ let negated = false;
873
+ let prefixed = false;
874
+ for (; ; ) {
875
+ const token = this.peek();
876
+ if (this.isWord(token, "time")) {
877
+ this.next();
878
+ if (this.isWord(this.peek(), "-p")) this.next();
879
+ } else if (this.isWord(token, "!")) {
880
+ this.next();
881
+ negated = !negated;
882
+ } else break;
883
+ prefixed = true;
884
+ }
885
+ const next = this.peek();
886
+ const ends = next.kind === "eof" || next.kind === "op" && (next.op === ";" || next.op === "\n");
887
+ if (prefixed && ends) return { negated, commands: [] };
888
+ const commands = [this.command()];
889
+ for (; ; ) {
890
+ const token = this.peek();
891
+ if (token.kind !== "op" || token.op !== "|" && token.op !== "|&")
892
+ return { negated, commands };
893
+ this.next();
894
+ this.newlines();
895
+ commands.push(this.command());
896
+ }
897
+ }
898
+ command() {
899
+ const token = this.peek();
900
+ if (token.kind === "op" && token.op === "(")
901
+ return this.parenthesized(token);
902
+ if (token.kind !== "word") return this.simple();
903
+ switch (token.raw) {
904
+ case "{": {
905
+ this.next();
906
+ const body = this.filled(/* @__PURE__ */ new Set(["}"]));
907
+ this.keyword("}");
908
+ return { kind: "group", body, redirects: this.redirects() };
909
+ }
910
+ case "if":
911
+ return this.ifCommand();
912
+ case "while":
913
+ case "until":
914
+ return this.loop(token.raw);
915
+ case "for":
916
+ case "select":
917
+ return this.forCommand(token.raw);
918
+ case "case":
919
+ return this.caseCommand();
920
+ case "[[":
921
+ return this.test();
922
+ case "function":
923
+ return this.functionKeyword();
924
+ default:
925
+ if (CONTINUATIONS.has(token.raw)) this.fail(token);
926
+ return this.simple();
927
+ }
928
+ }
929
+ parenthesized(token) {
930
+ this.ahead = void 0;
931
+ if (this.scan.text[token.start + 1] === "(") {
932
+ const word = this.scan.arithmetic(token.start);
933
+ if (word)
934
+ return this.closed({
935
+ kind: "compound",
936
+ keyword: "((",
937
+ parts: [],
938
+ words: [word],
939
+ redirects: this.redirects()
940
+ });
941
+ this.scan.pos = token.start + 1;
942
+ }
943
+ const body = this.filled(NO_KEYWORDS);
944
+ this.op(")");
945
+ return { kind: "subshell", body, redirects: this.redirects() };
946
+ }
947
+ // The list of a construct the shell refuses to leave empty.
948
+ filled(ends) {
949
+ const list = this.list(ends);
950
+ if (list.length === 0) this.fail(this.peek());
951
+ return list;
952
+ }
953
+ ifCommand() {
954
+ const parts = [];
955
+ this.keyword("if");
956
+ for (; ; ) {
957
+ parts.push(this.filled(/* @__PURE__ */ new Set(["then"])));
958
+ this.keyword("then");
959
+ parts.push(this.filled(/* @__PURE__ */ new Set(["elif", "else", "fi"])));
960
+ const token = this.next();
961
+ if (this.isWord(token, "elif")) continue;
962
+ if (this.isWord(token, "else")) {
963
+ parts.push(this.filled(/* @__PURE__ */ new Set(["fi"])));
964
+ this.keyword("fi");
965
+ } else if (!this.isWord(token, "fi")) this.fail(token, "fi");
966
+ return this.compound("if", parts, []);
967
+ }
968
+ }
969
+ loop(keyword) {
970
+ this.next();
971
+ const condition = this.filled(/* @__PURE__ */ new Set(["do"]));
972
+ return this.compound(keyword, [condition, this.doBody()], []);
973
+ }
974
+ doBody() {
975
+ this.newlines();
976
+ this.keyword("do");
977
+ const body = this.filled(/* @__PURE__ */ new Set(["done"]));
978
+ this.keyword("done");
979
+ return body;
980
+ }
981
+ forCommand(keyword) {
982
+ const start2 = this.next();
983
+ const words = [];
984
+ let variable;
985
+ const token = this.peek();
986
+ if (token.kind === "op" && token.op === "(" && this.scan.text[token.start + 1] === "(") {
987
+ this.ahead = void 0;
988
+ const header = this.scan.arithmetic(token.start);
989
+ if (!header) this.fail(start2, "((");
990
+ words.push(header);
991
+ } else {
992
+ variable = this.word().raw;
993
+ this.newlines();
994
+ if (this.isWord(this.peek(), "in")) {
995
+ this.next();
996
+ for (; ; ) {
997
+ const item = this.peek();
998
+ if (item.kind !== "word") break;
999
+ words.push(this.word().word);
1000
+ }
1001
+ }
1002
+ }
1003
+ const separator = this.peek();
1004
+ if (separator.kind === "op" && (separator.op === ";" || separator.op === "\n"))
1005
+ this.next();
1006
+ return this.compound(keyword, [this.doBody()], words, variable);
1007
+ }
1008
+ caseCommand() {
1009
+ this.next();
1010
+ const words = [this.word().word];
1011
+ this.newlines();
1012
+ this.keyword("in");
1013
+ const parts = [];
1014
+ for (; ; ) {
1015
+ this.newlines();
1016
+ if (this.isWord(this.peek(), "esac")) {
1017
+ this.next();
1018
+ return this.compound("case", parts, words);
1019
+ }
1020
+ const open2 = this.peek();
1021
+ if (open2.kind === "op" && open2.op === "(") this.next();
1022
+ words.push(this.word().word);
1023
+ for (; ; ) {
1024
+ const token = this.next();
1025
+ if (token.kind === "op" && token.op === ")") break;
1026
+ if (token.kind !== "op" || token.op !== "|") this.fail(token, ")");
1027
+ words.push(this.word().word);
1028
+ }
1029
+ parts.push(this.list(/* @__PURE__ */ new Set(["esac"])));
1030
+ const end = this.peek();
1031
+ if (end.kind === "op" && CASE_ENDS.has(end.op)) this.next();
1032
+ else if (!this.isWord(end, "esac")) this.fail(end, ";;");
1033
+ }
1034
+ }
1035
+ test() {
1036
+ this.next();
1037
+ const words = [];
1038
+ let previous = "";
1039
+ for (; ; ) {
1040
+ const item = this.scan.testWord(previous === "=~");
1041
+ if (!item) return this.closed(this.compound("[[", [], words));
1042
+ words.push(item.word);
1043
+ previous = item.raw;
1044
+ }
1045
+ }
1046
+ // The shell reads (( )) and [[ ]] like a simple command, so a word right after one is no
1047
+ // reserved word: "{ (( n )) }" leaves the brace group open.
1048
+ closed(command6) {
1049
+ const token = this.peek();
1050
+ if (token.kind === "word") this.fail(token);
1051
+ return command6;
1052
+ }
1053
+ functionKeyword() {
1054
+ this.next();
1055
+ const { raw } = this.word();
1056
+ const token = this.peek();
1057
+ if (token.kind === "op" && token.op === "(" && this.scan.text[token.start + 1] !== "(") {
1058
+ this.next();
1059
+ this.op(")");
1060
+ }
1061
+ return { kind: "function", name: raw, body: this.functionBody() };
1062
+ }
1063
+ // A function body is a compound command: { }, ( ), if, while, until, for, case, [[ ]] or (( )).
1064
+ functionBody() {
1065
+ this.newlines();
1066
+ const start2 = this.peek();
1067
+ const body = this.command();
1068
+ if (body.kind === "simple" || body.kind === "function") this.fail(start2);
1069
+ return body;
1070
+ }
1071
+ compound(keyword, parts, words, variable) {
1072
+ return {
1073
+ kind: "compound",
1074
+ keyword,
1075
+ ...variable ? { variable } : {},
1076
+ parts,
1077
+ words,
1078
+ redirects: this.redirects()
1079
+ };
1080
+ }
1081
+ redirects() {
1082
+ const redirects = [];
1083
+ while (this.peek().kind === "redirect") redirects.push(this.redirect());
1084
+ return redirects;
1085
+ }
1086
+ redirect() {
1087
+ const token = this.next();
1088
+ if (token.kind !== "redirect") this.fail(token, "a redirection");
1089
+ const { word, raw } = this.word();
1090
+ const redirect = {
1091
+ op: token.op,
1092
+ fd: token.fd,
1093
+ target: word,
1094
+ body: void 0
1095
+ };
1096
+ if (token.op === "<<" || token.op === "<<-")
1097
+ this.scan.heredoc(redirect, word, raw, token.op === "<<-");
1098
+ return redirect;
1099
+ }
1100
+ simple() {
1101
+ const assigns = [];
1102
+ const words = [];
1103
+ const redirects = [];
1104
+ let first = "";
1105
+ let redirectedAfterAssign = false;
1106
+ for (; ; ) {
1107
+ const token = this.peek();
1108
+ if (token.kind === "redirect") {
1109
+ redirects.push(this.redirect());
1110
+ if (assigns.length > 0) redirectedAfterAssign = true;
1111
+ continue;
1112
+ }
1113
+ if (token.kind !== "word") break;
1114
+ this.next();
1115
+ if (words.length === 0 && ASSIGNMENT.test(token.raw)) {
1116
+ if (redirectedAfterAssign && ARRAY.test(token.raw)) this.fail(token);
1117
+ assigns.push(token.word);
1118
+ continue;
1119
+ }
1120
+ if (ARRAY.test(token.raw) && !DECLARES.has(first)) this.fail(token);
1121
+ if (words.length === 0) first = token.raw;
1122
+ words.push(token.word);
1123
+ const after = this.peek();
1124
+ if (words.length === 1 && assigns.length === 0 && redirects.length === 0 && after.kind === "op" && after.op === "(") {
1125
+ this.next();
1126
+ this.op(")");
1127
+ return { kind: "function", name: token.raw, body: this.functionBody() };
1128
+ }
1129
+ }
1130
+ if (assigns.length + words.length + redirects.length === 0)
1131
+ this.fail(this.peek());
1132
+ return { kind: "simple", assigns, words, redirects };
1133
+ }
1134
+ };
480
1135
 
481
1136
  // src/hooks/shell/vocabulary.ts
482
1137
  var WRAPPERS = /* @__PURE__ */ new Set([
@@ -556,12 +1211,13 @@ var WRANGLER_MUTATING = /* @__PURE__ */ new Set([
556
1211
  ]);
557
1212
 
558
1213
  // src/hooks/shell/commands.ts
559
- var ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/u;
1214
+ var ASSIGNMENT2 = /^[A-Za-z_][A-Za-z0-9_]*=/u;
1215
+ var MAX_DEPTH = 4;
560
1216
  function unwrap(words) {
561
1217
  const assigned = [];
562
1218
  let rest = [...words];
563
1219
  for (; ; ) {
564
- if (rest.length > 0 && ASSIGNMENT.test(rest[0])) {
1220
+ if (rest.length > 0 && ASSIGNMENT2.test(rest[0])) {
565
1221
  assigned.push(rest[0].split("=")[0]);
566
1222
  rest = rest.slice(1);
567
1223
  continue;
@@ -576,56 +1232,196 @@ function unwrap(words) {
576
1232
  return { assigned, words: rest };
577
1233
  }
578
1234
  }
579
- function commandsOf(script, depth = 0) {
580
- if (depth > 4) return null;
581
- const parsed = tokenize(script);
582
- if (!parsed) return null;
583
- const found = [];
584
- let dir = "";
585
- let current = [];
586
- const close2 = () => {
587
- if (current.length === 0) return true;
588
- const raw = current;
589
- const { assigned, words } = unwrap(current);
590
- current = [];
1235
+ var DECLARES2 = /* @__PURE__ */ new Set(["export", "declare", "local", "readonly", "typeset"]);
1236
+ function start() {
1237
+ return {
1238
+ dir: "",
1239
+ previous: "",
1240
+ stack: [],
1241
+ vars: /* @__PURE__ */ new Map([["HOME", homedir2()]]),
1242
+ exported: /* @__PURE__ */ new Set(["HOME"])
1243
+ };
1244
+ }
1245
+ function fork(place) {
1246
+ return {
1247
+ ...place,
1248
+ stack: [...place.stack],
1249
+ vars: new Map(place.vars),
1250
+ exported: new Set(place.exported)
1251
+ };
1252
+ }
1253
+ function child(place, prefix) {
1254
+ const next = fork(place);
1255
+ next.stack = [];
1256
+ for (const name of next.vars.keys())
1257
+ if (!next.exported.has(name)) next.vars.delete(name);
1258
+ assign(next, prefix, true);
1259
+ return next;
1260
+ }
1261
+ function expanded(word, vars) {
1262
+ let text9 = word.text;
1263
+ for (const param of [...word.params].reverse()) {
1264
+ const value = vars.get(param.name);
1265
+ if (value !== void 0)
1266
+ text9 = text9.slice(0, param.start) + value + text9.slice(param.end);
1267
+ }
1268
+ return text9;
1269
+ }
1270
+ function changeDir(place, target) {
1271
+ if (target === void 0 || target === "~") return homedir2();
1272
+ if (target.startsWith("~/")) return join4(homedir2(), target.slice(2));
1273
+ if (isAbsolute2(target) || place.dir === "") return target;
1274
+ return join4(place.dir, target);
1275
+ }
1276
+ function assign(place, assigns, exporting) {
1277
+ for (const word of assigns) {
1278
+ const name = /^([A-Za-z_][A-Za-z0-9_]*)=/u.exec(word.text)?.[1];
1279
+ if (!name) continue;
1280
+ if (exporting) place.exported.add(name);
1281
+ const value = expanded(word, place.vars).slice(name.length + 1);
1282
+ const known = word.nested.length === 0 && word.params.every((param) => place.vars.has(param.name)) && !value.includes("$");
1283
+ if (known) place.vars.set(name, value);
1284
+ else place.vars.delete(name);
1285
+ }
1286
+ }
1287
+ function go(place, dir) {
1288
+ place.previous = place.dir;
1289
+ place.dir = dir;
1290
+ }
1291
+ function move(place, argv) {
1292
+ const args = argv.slice(1).filter((word) => !/^-[LPe@]+$/u.test(word));
1293
+ const target = args[0] === "--" ? args[1] : args[0];
1294
+ if (argv[0] === "popd") {
1295
+ const back = place.stack.pop();
1296
+ if (back !== void 0) go(place, back);
1297
+ return;
1298
+ }
1299
+ if (argv[0] === "pushd") {
1300
+ if (target === void 0) return;
1301
+ place.stack.push(place.dir);
1302
+ }
1303
+ go(place, target === "-" ? place.previous : changeDir(place, target));
1304
+ }
1305
+ var Walk = class _Walk {
1306
+ found = [];
1307
+ redirects = [];
1308
+ list(items, place, depth) {
1309
+ for (const item of items) {
1310
+ const here = item.background ? fork(place) : place;
1311
+ for (const pipeline of item.pipelines) {
1312
+ const alone = pipeline.commands.length === 1;
1313
+ for (const command6 of pipeline.commands)
1314
+ this.command(command6, alone ? here : fork(here), depth);
1315
+ }
1316
+ }
1317
+ }
1318
+ command(command6, place, depth) {
1319
+ switch (command6.kind) {
1320
+ case "simple":
1321
+ this.simple(command6, place, depth);
1322
+ return;
1323
+ case "group":
1324
+ this.list(command6.body, place, depth);
1325
+ this.redirected(command6.redirects, place, depth);
1326
+ return;
1327
+ case "subshell":
1328
+ this.list(command6.body, fork(place), depth);
1329
+ this.redirected(command6.redirects, place, depth);
1330
+ return;
1331
+ case "compound":
1332
+ this.expansions(command6.words, place, depth);
1333
+ if (command6.variable) place.vars.delete(command6.variable);
1334
+ for (const part of command6.parts) this.list(part, place, depth);
1335
+ this.redirected(command6.redirects, place, depth);
1336
+ return;
1337
+ case "function":
1338
+ this.command(command6.body, fork(place), depth);
1339
+ }
1340
+ }
1341
+ redirected(redirects, place, depth) {
1342
+ this.expansions(redirectWords(redirects), place, depth);
1343
+ const plain = redirects.map(({ op, fd, target }) => ({
1344
+ op,
1345
+ fd,
1346
+ target: expanded(target, place.vars)
1347
+ }));
1348
+ this.redirects.push(...plain);
1349
+ return plain;
1350
+ }
1351
+ // What a simple command does to this shell's variables.
1352
+ settle(command6, place) {
1353
+ if (command6.words.length === 0) {
1354
+ assign(place, command6.assigns, false);
1355
+ return;
1356
+ }
1357
+ const [name, ...args] = command6.words.map((word) => word.text);
1358
+ if (DECLARES2.has(name)) {
1359
+ const exporting = name === "export";
1360
+ assign(place, command6.words.slice(1), exporting);
1361
+ if (exporting) {
1362
+ for (const arg of args)
1363
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/u.test(arg)) place.exported.add(arg);
1364
+ }
1365
+ }
1366
+ if (name === "read") {
1367
+ for (const arg of args)
1368
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/u.test(arg)) place.vars.delete(arg);
1369
+ }
1370
+ }
1371
+ // Substitutions run in subshells that start where the command is.
1372
+ expansions(words, place, depth) {
1373
+ for (const word of words)
1374
+ for (const nested of word.nested) this.list(nested, fork(place), depth);
1375
+ }
1376
+ simple(command6, place, depth) {
1377
+ const written = [...command6.assigns, ...command6.words];
1378
+ this.expansions(written, place, depth);
1379
+ const redirects = this.redirected(command6.redirects, place, depth);
1380
+ if (written.length === 0) return;
1381
+ const raw = written.map((word) => expanded(word, place.vars));
1382
+ this.settle(command6, place);
1383
+ const { assigned, words } = unwrap(raw);
591
1384
  if (words.length === 0) {
592
- found.push({ argv: [], raw, assigned, dir });
593
- return true;
1385
+ this.found.push({ argv: [], raw, assigned, dir: place.dir, redirects });
1386
+ return;
594
1387
  }
595
- if (words[0] === "cd") {
596
- dir = words[1] ?? "";
597
- return true;
1388
+ if (["cd", "pushd", "popd"].includes(words[0])) {
1389
+ move(place, words);
1390
+ return;
598
1391
  }
599
1392
  const scriptAt = SHELLS.has(words[0]) ? words.findIndex((word) => /^-[a-z]*c$/u.test(word)) : -1;
600
1393
  if (scriptAt > 0 || words[0] === "eval") {
1394
+ if (depth >= MAX_DEPTH)
1395
+ throw new ShellSyntaxError("shell nested too deep", 0);
601
1396
  const source = words[0] === "eval" ? words.slice(1).join(" ") : words[scriptAt + 1] ?? "";
602
- const inner = commandsOf(source, depth + 1);
603
- if (!inner) return false;
604
- found.push(
605
- ...inner.map((step) => ({
1397
+ const inner = new _Walk();
1398
+ inner.list(parseScript(source), child(place, command6.assigns), depth + 1);
1399
+ this.redirects.push(...inner.redirects);
1400
+ this.found.push(
1401
+ ...inner.found.map((step) => ({
606
1402
  ...step,
607
1403
  assigned: [...assigned, ...step.assigned]
608
1404
  }))
609
1405
  );
610
- return true;
611
- }
612
- found.push({ argv: words, raw, assigned, dir });
613
- return true;
614
- };
615
- for (const token of parsed.tokens) {
616
- if (!SEPARATORS.has(token)) {
617
- current.push(token);
618
- continue;
1406
+ return;
619
1407
  }
620
- if (!close2()) return null;
1408
+ this.found.push({ argv: words, raw, assigned, dir: place.dir, redirects });
621
1409
  }
622
- if (!close2()) return null;
623
- for (const nested of parsed.nested) {
624
- const inner = commandsOf(nested, depth + 1);
625
- if (!inner) return null;
626
- found.push(...inner);
1410
+ };
1411
+ function redirectWords(redirects) {
1412
+ return redirects.flatMap(
1413
+ (redirect) => redirect.body ? [redirect.target, redirect.body] : [redirect.target]
1414
+ );
1415
+ }
1416
+ function readScript(script) {
1417
+ const walk = new Walk();
1418
+ try {
1419
+ walk.list(parseScript(script), start(), 0);
1420
+ } catch (error) {
1421
+ if (error instanceof ShellSyntaxError) return { error: error.message };
1422
+ throw error;
627
1423
  }
628
- return found;
1424
+ return { steps: walk.found, redirects: walk.redirects };
629
1425
  }
630
1426
  function gitCall(words) {
631
1427
  let index = 1;
@@ -690,17 +1486,84 @@ function mutates(words, rules = DEFAULT_MUTATING_RULES) {
690
1486
  );
691
1487
  }
692
1488
 
1489
+ // src/hooks/dispatch/emergency.ts
1490
+ var READ_ONLY = /* @__PURE__ */ new Set([
1491
+ "cat",
1492
+ "ls",
1493
+ "stat",
1494
+ "test",
1495
+ "[",
1496
+ "head",
1497
+ "tail",
1498
+ "wc",
1499
+ "file"
1500
+ ]);
1501
+ var REASON = "The emergency off switch belongs to the operator; agents may not create, change or delete it.";
1502
+ function emergencyActive(root, file2) {
1503
+ return file2 !== void 0 && existsSync(expandPath(root, file2));
1504
+ }
1505
+ function protectOffFile(input, file2) {
1506
+ const tool = input.tool;
1507
+ if (!file2 || input.event !== "before_tool" || !tool) return {};
1508
+ const target = expandPath(input.projectRoot, file2);
1509
+ if (tool.kind === "edit") {
1510
+ return tool.paths.some((path) => resolve3(path) === target) ? { verdict: "deny", reason: REASON } : {};
1511
+ }
1512
+ if (tool.kind !== "shell") return {};
1513
+ const read4 = tool.steps ? { steps: tool.steps } : readScript(tool.command ?? "");
1514
+ if ("error" in read4)
1515
+ return {
1516
+ verdict: "deny",
1517
+ reason: `${REASON} (not shell syntax: ${read4.error})`
1518
+ };
1519
+ const names3 = read4.steps.some((step) => {
1520
+ const at = (word) => word === file2 || expandPath(resolve3(input.cwd, step.dir), word) === target;
1521
+ if (step.redirects.some((redirect) => at(redirect.target))) return true;
1522
+ return !READ_ONLY.has(step.argv[0] ?? "") && step.raw.some(at);
1523
+ });
1524
+ return names3 ? { verdict: "deny", reason: REASON } : {};
1525
+ }
1526
+
693
1527
  // src/hooks/dispatch/enrich.ts
694
1528
  function withSteps(input) {
695
1529
  const tool = input.tool;
696
1530
  if (tool?.kind !== "shell" || !tool.command) return input;
697
- const steps = commandsOf(tool.command);
698
- if (!steps) return input;
699
- return { ...input, tool: { ...tool, steps } };
1531
+ const read4 = readScript(tool.command);
1532
+ if ("error" in read4)
1533
+ return { ...input, tool: { ...tool, syntaxError: read4.error } };
1534
+ return {
1535
+ ...input,
1536
+ tool: { ...tool, steps: read4.steps, redirects: read4.redirects }
1537
+ };
1538
+ }
1539
+
1540
+ // src/hooks/policies/_shared.ts
1541
+ var UnreadableCommand = class extends Error {
1542
+ constructor(reason2) {
1543
+ super(`not shell syntax: ${reason2}`);
1544
+ }
1545
+ };
1546
+ function shellCall(input) {
1547
+ if (input.tool?.kind !== "shell") return null;
1548
+ const command6 = input.tool.command ?? "";
1549
+ if (command6.trim() === "") return null;
1550
+ const { steps, redirects, syntaxError } = input.tool;
1551
+ if (steps) return { command: command6, steps, redirects: redirects ?? [] };
1552
+ const read4 = readScript(command6);
1553
+ if ("error" in read4) throw new UnreadableCommand(syntaxError ?? read4.error);
1554
+ return { command: command6, steps: read4.steps, redirects: read4.redirects };
1555
+ }
1556
+ function program(word) {
1557
+ if (!word) return "";
1558
+ const slash = word.lastIndexOf("/");
1559
+ return slash < 0 ? word : word.slice(slash + 1);
1560
+ }
1561
+ function realSteps(steps) {
1562
+ return steps.filter((step) => step.argv.length > 0);
700
1563
  }
701
1564
 
702
1565
  // src/hooks/dispatch/failure.ts
703
- import { isAbsolute as isAbsolute2, relative as relative2, resolve as resolve4 } from "node:path";
1566
+ import { isAbsolute as isAbsolute3, relative as relative2, resolve as resolve4 } from "node:path";
704
1567
  var PASS_KINDS = ["read", "edit-own-worktree"];
705
1568
  function ownWorktree(input) {
706
1569
  const checkout = checkoutOf(input.cwd);
@@ -708,7 +1571,7 @@ function ownWorktree(input) {
708
1571
  const paths = input.tool?.paths ?? [];
709
1572
  return paths.length > 0 && paths.every((path) => {
710
1573
  const rest = relative2(checkout.root, resolve4(input.cwd, path));
711
- return rest !== "" && !rest.startsWith("..") && !isAbsolute2(rest);
1574
+ return rest !== "" && !rest.startsWith("..") && !isAbsolute3(rest);
712
1575
  });
713
1576
  }
714
1577
  function passes(input, pass2) {
@@ -798,7 +1661,7 @@ async function runPolicy(selected, input, deps) {
798
1661
  }
799
1662
  return finish({
800
1663
  verdict: "deny",
801
- reason: `pmcp ${policy.id} failed, refusing to be safe`
1664
+ reason: error instanceof UnreadableCommand ? `pmcp ${policy.id} refuses a command that is ${error.message}` : `pmcp ${policy.id} failed, refusing to be safe`
802
1665
  });
803
1666
  }
804
1667
  }
@@ -806,22 +1669,6 @@ async function runPolicy(selected, input, deps) {
806
1669
  // src/hooks/policies/git/forced-branch-move.ts
807
1670
  import { resolve as resolve5 } from "node:path";
808
1671
 
809
- // src/hooks/policies/_shared.ts
810
- function shellCall(input) {
811
- if (input.tool?.kind !== "shell") return null;
812
- const command6 = input.tool.command ?? "";
813
- if (command6.trim() === "") return null;
814
- return { command: command6, steps: input.tool.steps };
815
- }
816
- function program(word) {
817
- if (!word) return "";
818
- const slash = word.lastIndexOf("/");
819
- return slash < 0 ? word : word.slice(slash + 1);
820
- }
821
- function realSteps(steps) {
822
- return steps.filter((step) => step.argv.length > 0);
823
- }
824
-
825
1672
  // src/hooks/policies/types.ts
826
1673
  var pass = {};
827
1674
  function noOptions(raw) {
@@ -844,7 +1691,6 @@ function onlyKeys(raw, keys) {
844
1691
 
845
1692
  // src/hooks/policies/git/forced-branch-move.ts
846
1693
  var FORCE = /* @__PURE__ */ new Set(["-f", "-M", "--force"]);
847
- var FALLBACK = /\bgit\b[^|;&\n]*\sbranch\b[^|;&\n]*\s(?:-f|-M|--force)(?:\s|$)/u;
848
1694
  function forcedTarget(argv) {
849
1695
  if (program(argv[0]) !== "git") return null;
850
1696
  const call = gitCall(argv);
@@ -869,13 +1715,6 @@ var forcedBranchMove = {
869
1715
  evaluate(input, ctx) {
870
1716
  const call = shellCall(input);
871
1717
  if (!call) return pass;
872
- if (!call.steps) {
873
- if (!FALLBACK.test(call.command)) return pass;
874
- return {
875
- verdict: "deny",
876
- reason: "A forced branch move could not be read."
877
- };
878
- }
879
1718
  for (const step of realSteps(call.steps)) {
880
1719
  const target = forcedTarget(step.argv);
881
1720
  if (!target) continue;
@@ -892,9 +1731,6 @@ var forcedBranchMove = {
892
1731
 
893
1732
  // src/hooks/policies/git/gate-bypass-env.ts
894
1733
  var REASON2 = "This takes a way around the gate that only the operator may take. Fix what the gate reports, or ask the operator.";
895
- function escape(text9) {
896
- return text9.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
897
- }
898
1734
  function bypasses(step, options2) {
899
1735
  if (step.assigned.some((name2) => options2.variables.includes(name2)))
900
1736
  return true;
@@ -906,14 +1742,6 @@ function bypasses(step, options2) {
906
1742
  }
907
1743
  return options2.noVerify && name === "git" && step.argv.includes("--no-verify");
908
1744
  }
909
- function fallback(command6, options2) {
910
- const names3 = options2.variables.map(escape);
911
- if (options2.noVerify) names3.push("--no-verify");
912
- if (names3.length === 0) return false;
913
- return new RegExp(`(?:^|[^\\w-])(?:${names3.join("|")})\\b`, "u").test(
914
- command6
915
- );
916
- }
917
1745
  var gateBypassEnv = {
918
1746
  id: "git.gate_bypass_env",
919
1747
  events: ["before_tool"],
@@ -930,13 +1758,12 @@ var gateBypassEnv = {
930
1758
  evaluate(input, ctx) {
931
1759
  const call = shellCall(input);
932
1760
  if (!call) return pass;
933
- const hit2 = call.steps ? call.steps.some((step) => bypasses(step, ctx.options)) : fallback(call.command, ctx.options);
1761
+ const hit2 = call.steps.some((step) => bypasses(step, ctx.options));
934
1762
  return hit2 ? { verdict: "deny", reason: REASON2 } : pass;
935
1763
  }
936
1764
  };
937
1765
 
938
1766
  // src/hooks/policies/git/push-without-verify.ts
939
- var FALLBACK2 = /\bgit\b[^|;&\n]*\spush\b[^|;&\n]*\s--no-verify(?:\s|$)/u;
940
1767
  var REASON3 = "Pushing with verification disabled skips every pre-push check at once, including the ones that catch what a person cannot review by eye. Fix the failing check instead of waiving all of them.";
941
1768
  function skipsVerify(argv) {
942
1769
  if (program(argv[0]) !== "git") return false;
@@ -954,7 +1781,7 @@ var pushWithoutVerify = {
954
1781
  evaluate(input) {
955
1782
  const call = shellCall(input);
956
1783
  if (!call) return pass;
957
- const hit2 = call.steps ? realSteps(call.steps).some((step) => skipsVerify(step.argv)) : FALLBACK2.test(call.command);
1784
+ const hit2 = realSteps(call.steps).some((step) => skipsVerify(step.argv));
958
1785
  return hit2 ? { verdict: "deny", reason: REASON3 } : pass;
959
1786
  }
960
1787
  };
@@ -977,7 +1804,6 @@ var COMMIT_VALUES = /* @__PURE__ */ new Set([
977
1804
  ]);
978
1805
  var SHORT_VALUES = /* @__PURE__ */ new Set(["m", "F", "C", "c", "t"]);
979
1806
  var ROOT_PATHS = /* @__PURE__ */ new Set([".", "./", ":/", ":(top)", ":(top)."]);
980
- var NAMES_GIT = /(?:^|[^\w.-])git(?![\w.-])/u;
981
1807
  function stagesAll(args, commit) {
982
1808
  let paths = false;
983
1809
  for (let index = 0; index < args.length; index += 1) {
@@ -1028,8 +1854,7 @@ var stageAll = {
1028
1854
  evaluate(input) {
1029
1855
  const call = shellCall(input);
1030
1856
  if (!call) return pass;
1031
- if (!call.steps && !NAMES_GIT.test(call.command)) return pass;
1032
- if (call.steps && !realSteps(call.steps).some((step) => stagesEverything(step.argv)))
1857
+ if (!realSteps(call.steps).some((step) => stagesEverything(step.argv)))
1033
1858
  return pass;
1034
1859
  return {
1035
1860
  verdict: "deny",
@@ -1081,7 +1906,7 @@ function runCheck(command6, root, timeout) {
1081
1906
  }
1082
1907
 
1083
1908
  // src/hooks/checks/options.ts
1084
- import { isAbsolute as isAbsolute3 } from "node:path";
1909
+ import { isAbsolute as isAbsolute4 } from "node:path";
1085
1910
  function report(raw) {
1086
1911
  if (raw["report"] !== void 0 && raw["report"] !== "context")
1087
1912
  throw new Error("report must be context");
@@ -1092,7 +1917,7 @@ function afterEditOptions(raw) {
1092
1917
  const glob2 = raw["validator_glob"];
1093
1918
  const command6 = raw["command"];
1094
1919
  const seconds = raw["debounce_seconds"] ?? 60;
1095
- if (typeof glob2 !== "string" || !glob2 || isAbsolute3(glob2) || glob2.split("/").includes(".."))
1920
+ if (typeof glob2 !== "string" || !glob2 || isAbsolute4(glob2) || glob2.split("/").includes(".."))
1096
1921
  throw new Error("validator_glob must stay inside the project");
1097
1922
  if (!Array.isArray(command6) || command6.length === 0 || !command6.every(
1098
1923
  (part) => typeof part === "string" && part.length > 0 && !part.includes("\0")
@@ -1116,10 +1941,10 @@ function stopOptions(raw) {
1116
1941
  }
1117
1942
 
1118
1943
  // src/hooks/checks/validators.ts
1119
- import { dirname as dirname3, isAbsolute as isAbsolute4, relative as relative3, resolve as resolve6, sep } from "node:path";
1944
+ import { dirname as dirname3, isAbsolute as isAbsolute5, relative as relative3, resolve as resolve6, sep } from "node:path";
1120
1945
  function contains(root, target) {
1121
1946
  const rest = relative3(root, target);
1122
- return !isAbsolute4(rest) && rest !== ".." && !rest.startsWith(`..${sep}`);
1947
+ return !isAbsolute5(rest) && rest !== ".." && !rest.startsWith(`..${sep}`);
1123
1948
  }
1124
1949
  function owner(validator) {
1125
1950
  const parts = validator.split(sep);
@@ -1196,10 +2021,10 @@ var afterEdit = {
1196
2021
  };
1197
2022
 
1198
2023
  // src/hooks/checks/projection.ts
1199
- import { join as join5 } from "node:path";
2024
+ import { join as join6 } from "node:path";
1200
2025
 
1201
2026
  // src/sessions/projector-cli.ts
1202
- import { delimiter, join as join4 } from "node:path";
2027
+ import { delimiter, join as join5 } from "node:path";
1203
2028
  var PROJECTOR_FILE = "projector.json";
1204
2029
  function readJson(path) {
1205
2030
  try {
@@ -1209,17 +2034,17 @@ function readJson(path) {
1209
2034
  }
1210
2035
  }
1211
2036
  function localCli(root) {
1212
- const own = join4(root, "node_modules/@modootoday/pmcp/dist/cli.js");
2037
+ const own = join5(root, "node_modules/@modootoday/pmcp/dist/cli.js");
1213
2038
  if (existsSync(own)) return own;
1214
2039
  try {
1215
- const target = realpathSync(join4(root, "node_modules/.bin/pmcp"));
2040
+ const target = realpathSync(join5(root, "node_modules/.bin/pmcp"));
1216
2041
  return /\.[cm]?js$/u.test(target) ? target : null;
1217
2042
  } catch {
1218
2043
  return null;
1219
2044
  }
1220
2045
  }
1221
2046
  function recordedCli(root, stateDir) {
1222
- const known = readJson(join4(stateDir, PROJECTOR_FILE));
2047
+ const known = readJson(join5(stateDir, PROJECTOR_FILE));
1223
2048
  let checkout;
1224
2049
  try {
1225
2050
  checkout = realpathSync(root);
@@ -1236,7 +2061,7 @@ function projectingCli(root, stateDir) {
1236
2061
  function pathPmcp(path) {
1237
2062
  for (const dir of (path ?? "").split(delimiter).filter(Boolean)) {
1238
2063
  try {
1239
- return realpathSync(join4(dir, "pmcp"));
2064
+ return realpathSync(join5(dir, "pmcp"));
1240
2065
  } catch {
1241
2066
  continue;
1242
2067
  }
@@ -1280,7 +2105,7 @@ function findProjector(root, stateDir, deadline) {
1280
2105
  const cli = localCli(root) ?? recordedCli(root, stateDir);
1281
2106
  if (!cli || !existsSync(cli))
1282
2107
  return { missing: cli ?? "no local or recorded pmcp" };
1283
- const expected = readJson2(join5(root, "pmcp.lock"))?.[LOCK_VERSION_KEY];
2108
+ const expected = readJson2(join6(root, "pmcp.lock"))?.[LOCK_VERSION_KEY];
1284
2109
  const answer = run([process.execPath, cli, "--version"], root, deadline);
1285
2110
  if (answer.error || answer.stdout.trim() !== expected)
1286
2111
  return { missing: cli };
@@ -1426,9 +2251,7 @@ function startsWith(argv, prefix) {
1426
2251
  (word, at) => at === 0 ? program(argv[0]) === word : argv[at] === word
1427
2252
  );
1428
2253
  }
1429
- function blocked(steps, command6, rule) {
1430
- if (!steps)
1431
- return rule.blocks.some((prefix) => command6.includes(prefix.join(" ")));
2254
+ function blocked(steps, rule) {
1432
2255
  return realSteps(steps).some(
1433
2256
  (step) => rule.blocks.some((prefix) => startsWith(step.argv, prefix))
1434
2257
  );
@@ -1456,7 +2279,7 @@ var leases = {
1456
2279
  const call = shellCall(input);
1457
2280
  if (!call) return pass;
1458
2281
  for (const rule of ctx.options) {
1459
- if (!blocked(call.steps, call.command, rule)) continue;
2282
+ if (!blocked(call.steps, rule)) continue;
1460
2283
  const lease = ctx.store.leases.read(rule.name);
1461
2284
  if (!lease) continue;
1462
2285
  return {
@@ -1629,9 +2452,9 @@ function alive(pid) {
1629
2452
  return error.code === "EPERM";
1630
2453
  }
1631
2454
  }
1632
- function ancestors(start = process.ppid, limit = 12) {
2455
+ function ancestors(start2 = process.ppid, limit = 12) {
1633
2456
  const chain = [];
1634
- let pid = start;
2457
+ let pid = start2;
1635
2458
  while (pid > 1 && chain.length < limit) {
1636
2459
  chain.push(pid);
1637
2460
  const info = stat2(pid);
@@ -1667,8 +2490,8 @@ function darwinTable() {
1667
2490
  }
1668
2491
  return darwin;
1669
2492
  }
1670
- function runtimePid(start = process.ppid) {
1671
- let pid = start;
2493
+ function runtimePid(start2 = process.ppid) {
2494
+ let pid = start2;
1672
2495
  for (let hop = 0; hop < 3; hop += 1) {
1673
2496
  const info = stat2(pid);
1674
2497
  if (!info || !SHELLS2.has(info.name) || info.parent <= 1) return pid;
@@ -1777,21 +2600,11 @@ var mailbox = {
1777
2600
  };
1778
2601
 
1779
2602
  // src/hooks/policies/sessions/pause.ts
1780
- var BUILT_IN = /\b(git\s+(commit|push|merge|rebase|reset|checkout|switch|cherry-pick|revert|am|stash|tag|clean|restore|rm|mv|worktree\s+(add|remove|move))|bun\s+(install|i|add|remove|rm|update|link)\b|(npm|pnpm|yarn)\s+(install|i|add|remove|publish|ci)\b)\b/u;
1781
- var escape2 = (word) => word.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
1782
2603
  function changes(input, options2) {
1783
- const tool = input.tool;
1784
- if (tool?.kind === "edit") return true;
1785
- if (tool?.kind !== "shell") return false;
1786
- if (!tool.steps) {
1787
- const command6 = tool.command ?? "";
1788
- return BUILT_IN.test(command6) || options2.commands.some(
1789
- (prefix) => new RegExp(`\\b${prefix.map(escape2).join("\\s+")}\\b`, "u").test(
1790
- command6
1791
- )
1792
- ) || options2.scripts.some((s) => s.test(command6));
1793
- }
1794
- return realSteps(tool.steps).some((step) => mutates(step.argv, options2));
2604
+ if (input.tool?.kind === "edit") return true;
2605
+ const call = shellCall(input);
2606
+ if (!call) return false;
2607
+ return realSteps(call.steps).some((step) => mutates(step.argv, options2));
1795
2608
  }
1796
2609
  function patterns(raw, key) {
1797
2610
  const list = stringList(raw, key);
@@ -2032,7 +2845,6 @@ var VERB_VALUE_FLAGS = {
2032
2845
  down: /* @__PURE__ */ new Set(["-t", "--timeout", "--rmi"])
2033
2846
  };
2034
2847
  var SCOPED_VERBS = /* @__PURE__ */ new Set(["stop", "rm", "kill"]);
2035
- var FALLBACK3 = /\b(?:docker[ \t]+compose|docker-compose)\b[^|;&]*\b(?:down|stop|rm|kill)\b/u;
2036
2848
  function firstArgument(words, valueFlags) {
2037
2849
  for (let index = 0; index < words.length; index += 1) {
2038
2850
  const word = words[index];
@@ -2069,13 +2881,6 @@ var composeTeardown = {
2069
2881
  evaluate(input) {
2070
2882
  const call = shellCall(input);
2071
2883
  if (!call) return pass;
2072
- if (!call.steps) {
2073
- if (!FALLBACK3.test(call.command)) return pass;
2074
- return {
2075
- verdict: "deny",
2076
- reason: "A docker compose teardown could not be read."
2077
- };
2078
- }
2079
2884
  for (const step of realSteps(call.steps)) {
2080
2885
  const reason2 = teardownReason(step.argv);
2081
2886
  if (reason2) return { verdict: "deny", reason: reason2 };
@@ -2085,32 +2890,8 @@ var composeTeardown = {
2085
2890
  };
2086
2891
 
2087
2892
  // src/hooks/policies/shell/heredoc.ts
2088
- var HEREDOC = /<<(?!<)-?[ \t]*(['"\\]?)[A-Za-z_][A-Za-z0-9_]*\1/u;
2089
- var HERESTRING = /<<</u;
2893
+ var HERE = /* @__PURE__ */ new Set(["<<", "<<-", "<<<"]);
2090
2894
  var REASON4 = "Heredocs and here-strings are refused: the shell expands and truncates their body silently. Write the file with the editor tool, then run it, or pass the content as an argument.";
2091
- function maskQuotes(command6) {
2092
- let out = "";
2093
- for (let index = 0; index < command6.length; index += 1) {
2094
- const char = command6[index];
2095
- if (char === "\\") {
2096
- out += command6.slice(index, index + 2);
2097
- index += 1;
2098
- continue;
2099
- }
2100
- if (char !== "'" && char !== '"') {
2101
- out += char;
2102
- continue;
2103
- }
2104
- let end = index + 1;
2105
- while (end < command6.length && command6[end] !== char) {
2106
- end += char === '"' && command6[end] === "\\" ? 2 : 1;
2107
- }
2108
- if (end >= command6.length) return null;
2109
- out += "Q";
2110
- index = end;
2111
- }
2112
- return out;
2113
- }
2114
2895
  var heredoc = {
2115
2896
  id: "shell.heredoc",
2116
2897
  events: ["before_tool"],
@@ -2121,18 +2902,13 @@ var heredoc = {
2121
2902
  evaluate(input) {
2122
2903
  const call = shellCall(input);
2123
2904
  if (!call) return pass;
2124
- const text9 = maskQuotes(call.command) ?? call.command;
2125
- if (HEREDOC.test(text9) || HERESTRING.test(text9)) {
2126
- return { verdict: "deny", reason: REASON4 };
2127
- }
2128
- return pass;
2905
+ return call.redirects.some((redirect) => HERE.has(redirect.op)) ? { verdict: "deny", reason: REASON4 } : pass;
2129
2906
  }
2130
2907
  };
2131
2908
 
2132
2909
  // src/hooks/policies/shell/host-approval.ts
2133
2910
  var APPROVALS = "host-approvals";
2134
2911
  var VERB = ["host", "approve"];
2135
- var FALLBACK4 = /\bhost\s+approve\b|host-approvals/u;
2136
2912
  var REASON5 = "Approving the pmcp-pty host policy is the operator's step: run pmcp harness host approve in your own terminal, not from an agent.";
2137
2913
  function approves(argv) {
2138
2914
  const at = argv.indexOf(VERB[0]);
@@ -2144,7 +2920,8 @@ function hit(input) {
2144
2920
  return tool.paths.some((path) => path.includes(`/${APPROVALS}`));
2145
2921
  const call = shellCall(input);
2146
2922
  if (!call) return false;
2147
- if (!call.steps) return FALLBACK4.test(call.command);
2923
+ if (call.redirects.some((redirect) => redirect.target.includes(APPROVALS)))
2924
+ return true;
2148
2925
  return realSteps(call.steps).some(
2149
2926
  (step) => approves(step.argv) || step.argv.some((word) => word.includes(APPROVALS))
2150
2927
  );
@@ -2163,7 +2940,6 @@ var hostApproval = {
2163
2940
 
2164
2941
  // src/hooks/policies/shell/in-place-edit.ts
2165
2942
  var EDITORS = /* @__PURE__ */ new Set(["sed", "perl", "awk", "gawk"]);
2166
- var FALLBACK5 = /(^|[;&|\n]|&&)[ \t]*(?:[A-Za-z_][A-Za-z0-9_]*=\S*[ \t]+)*(sed|perl|gawk|awk)\b[^\n]*?\s(-i\b|--in-place\b|-i\S+)/u;
2167
2943
  var REASON6 = "In-place stream edits (sed -i, perl -i, awk -i) rewrite files without showing a diff and succeed on the first match rather than the intended one. Use the editor tool instead.";
2168
2944
  function inPlace(argv) {
2169
2945
  const name = program(argv[0]);
@@ -2181,7 +2957,7 @@ var inPlaceEdit = {
2181
2957
  evaluate(input) {
2182
2958
  const call = shellCall(input);
2183
2959
  if (!call) return pass;
2184
- const hit2 = call.steps ? realSteps(call.steps).some((step) => inPlace(step.argv)) : FALLBACK5.test(call.command);
2960
+ const hit2 = realSteps(call.steps).some((step) => inPlace(step.argv));
2185
2961
  return hit2 ? { verdict: "deny", reason: REASON6 } : pass;
2186
2962
  }
2187
2963
  };
@@ -2240,8 +3016,8 @@ function repeats(pattern, at) {
2240
3016
  if (char === "*" || char === "+") return true;
2241
3017
  return char === "{" && /^\{\d*,\}/u.test(pattern.slice(at));
2242
3018
  }
2243
- function classEnd(pattern, start) {
2244
- let at = start + 1;
3019
+ function classEnd(pattern, start2) {
3020
+ let at = start2 + 1;
2245
3021
  if (pattern[at] === "^") at += 1;
2246
3022
  if (pattern[at] === "]") at += 1;
2247
3023
  for (; at < pattern.length; at += 1) {
@@ -2299,9 +3075,9 @@ var FLAVOR_LONG = {
2299
3075
  "fixed-strings": "fixed",
2300
3076
  "basic-regexp": "basic"
2301
3077
  };
2302
- function readGrep(args, start) {
3078
+ function readGrep(args, start2) {
2303
3079
  const patterns2 = [];
2304
- let flavor = start;
3080
+ let flavor = start2;
2305
3081
  let onlyMatching = false;
2306
3082
  let operand;
2307
3083
  let fromFile = false;
@@ -2361,14 +3137,14 @@ function costOf(step, options2) {
2361
3137
  return null;
2362
3138
  }
2363
3139
  var reason = (why, threshold) => `This grep can keep a CPU core busy for minutes: ${why}. Find the line with grep -n and no -o or large count, then print a window around it with sed -n 'N,+K p' FILE; or use rg, which matches in linear time; or bring the count to ${threshold} or below; or bound the run with timeout 20 grep \u2026.`;
2364
- function integer(raw, key, fallback3) {
2365
- const value = raw[key] ?? fallback3;
3140
+ function integer(raw, key, fallback) {
3141
+ const value = raw[key] ?? fallback;
2366
3142
  if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 32767)
2367
3143
  throw new Error(`${key} must be an integer from 1 to 32767`);
2368
3144
  return value;
2369
3145
  }
2370
- function bool(raw, key, fallback3) {
2371
- const value = raw[key] ?? fallback3;
3146
+ function bool(raw, key, fallback) {
3147
+ const value = raw[key] ?? fallback;
2372
3148
  if (typeof value !== "boolean")
2373
3149
  throw new Error(`${key} must be true or false`);
2374
3150
  return value;
@@ -2389,8 +3165,9 @@ var runawayRegex = {
2389
3165
  },
2390
3166
  // Unreadable shell syntax passes: a wrong refusal here costs more than a slow grep.
2391
3167
  evaluate(input, ctx) {
3168
+ if (input.tool?.syntaxError) return pass;
2392
3169
  const call = shellCall(input);
2393
- if (!call?.steps) return pass;
3170
+ if (!call) return pass;
2394
3171
  for (const step of realSteps(call.steps)) {
2395
3172
  const why = costOf(step, ctx.options);
2396
3173
  if (why)
@@ -2533,8 +3310,6 @@ var ENV_DUMPS = [
2533
3310
  ["export", "-p"],
2534
3311
  ["declare", "-x"]
2535
3312
  ];
2536
- var FALLBACK_PATH = /(?:^|[^\w.-])\.env(?![.\w-])|\.dev\.vars(?:\.json)?\b/u;
2537
- var FALLBACK_USE = /(?:^|[;&|(]|&&)\s*(?:sudo\s+)?(?:cat|head|tail|less|grep|rg|jq|base64|cp|curl|wget|nc|scp|rsync)\b/u;
2538
3313
  var NO_VALUES = "Use metadata verbs instead (ls, stat, wc, find), or a command that names keys without resolving values.";
2539
3314
  function names(word, options2) {
2540
3315
  if (PATTERN.test(word)) return false;
@@ -2585,6 +3360,9 @@ function operandsOf(argv) {
2585
3360
  }
2586
3361
  return operands;
2587
3362
  }
3363
+ function inputFiles(step) {
3364
+ return step.redirects.filter((redirect) => redirect.op === "<" || redirect.op === "<>").map((redirect) => redirect.target);
3365
+ }
2588
3366
  function severity(steps, options2) {
2589
3367
  const wire = steps.some((step) => step.raw.some(isWire));
2590
3368
  const real4 = realSteps(steps);
@@ -2594,16 +3372,14 @@ function severity(steps, options2) {
2594
3372
  return wire ? "exfil" : "read";
2595
3373
  if (steps.some(dumpsEnvironment)) return wire ? "exfil" : "read";
2596
3374
  const touched = real4.filter(
2597
- (step) => operandsOf(step.argv).some((word) => names(word, options2))
3375
+ (step) => [...operandsOf(step.argv), ...inputFiles(step)].some(
3376
+ (word) => names(word, options2)
3377
+ )
2598
3378
  );
2599
3379
  if (touched.some((step) => isWire(step.argv[0]))) return "exfil";
2600
3380
  if (!touched.some((step) => READERS.has(program(step.argv[0])))) return null;
2601
3381
  return wire ? "exfil" : "read";
2602
3382
  }
2603
- function fallbackSeverity(command6) {
2604
- if (!FALLBACK_PATH.test(command6) || !FALLBACK_USE.test(command6)) return null;
2605
- return /\b(?:curl|wget|nc|scp|rsync)\b|https?:\/\//u.test(command6) ? "exfil" : "read";
2606
- }
2607
3383
  function verbsOf(table, key) {
2608
3384
  return (stringList(table, key) ?? []).map((verb) => verb.split(/\s+/u));
2609
3385
  }
@@ -2645,7 +3421,7 @@ var secretExfiltration = {
2645
3421
  evaluate(input, ctx) {
2646
3422
  const call = shellCall(input);
2647
3423
  if (!call) return pass;
2648
- const found = call.steps ? severity(call.steps, ctx.options) : fallbackSeverity(call.command);
3424
+ const found = severity(call.steps, ctx.options);
2649
3425
  if (found === "exfil") {
2650
3426
  return {
2651
3427
  verdict: "deny",
@@ -2664,34 +3440,15 @@ var secretExfiltration = {
2664
3440
 
2665
3441
  // src/hooks/policies/shell/stdin-interpreter.ts
2666
3442
  var PYTHON = /^i?python[23]?(\.\d+)?$/u;
2667
- var FALLBACK6 = /(?:^|[;&|(]|&&|\|\|)[ \t]*(?:sudo[ \t]+)?i?python[23]?(?:\.\d+)?\b([^;&|)]*)/gu;
2668
3443
  var REASON7 = "This interpreter reads its program from stdin, so the command text does not contain it and whatever fed the pipe already expanded it. Write the script with the editor tool, then run it.";
2669
3444
  var INFORMATIONAL = /^(?:-V+|--version|-h|-\?|--help(?:-[a-z]+)?)$/u;
2670
- var REDIRECT = /^\d*(?:<|>>?|&>)(.*)$/u;
2671
- function withoutRedirects(args) {
2672
- const kept = [];
2673
- for (let at = 0; at < args.length; at += 1) {
2674
- const match = REDIRECT.exec(args[at]);
2675
- if (!match) kept.push(args[at]);
2676
- else if (match[1] === "") at += 1;
2677
- }
2678
- return kept;
2679
- }
2680
- function programFromStdin(words) {
2681
- const args = withoutRedirects(words);
3445
+ function programFromStdin(args) {
2682
3446
  if (args.includes("-")) return true;
2683
3447
  if (args.some((arg) => INFORMATIONAL.test(arg))) return false;
2684
3448
  return !args.some(
2685
3449
  (arg) => arg === "-c" || arg === "-m" || !arg.startsWith("-")
2686
3450
  );
2687
3451
  }
2688
- function fallback2(command6) {
2689
- for (const match of command6.matchAll(FALLBACK6)) {
2690
- const args = (match[1] ?? "").trim().split(/\s+/u).filter(Boolean);
2691
- if (programFromStdin(args)) return true;
2692
- }
2693
- return false;
2694
- }
2695
3452
  var stdinInterpreter = {
2696
3453
  id: "shell.stdin_interpreter",
2697
3454
  events: ["before_tool"],
@@ -2702,9 +3459,9 @@ var stdinInterpreter = {
2702
3459
  evaluate(input) {
2703
3460
  const call = shellCall(input);
2704
3461
  if (!call) return pass;
2705
- const hit2 = call.steps ? realSteps(call.steps).some(
3462
+ const hit2 = realSteps(call.steps).some(
2706
3463
  (step) => PYTHON.test(program(step.argv[0])) && programFromStdin(step.argv.slice(1))
2707
- ) : fallback2(call.command);
3464
+ );
2708
3465
  return hit2 ? { verdict: "deny", reason: REASON7 } : pass;
2709
3466
  }
2710
3467
  };
@@ -2723,12 +3480,12 @@ function claimantNotice(root, names3) {
2723
3480
  }
2724
3481
 
2725
3482
  // src/hooks/policies/workspace/leftovers.ts
2726
- import { isAbsolute as isAbsolute5, relative as relative5, resolve as resolve8 } from "node:path";
3483
+ import { isAbsolute as isAbsolute6, relative as relative5, resolve as resolve8 } from "node:path";
2727
3484
  var TOUCHED_KEPT = 50;
2728
3485
  function addTouched(touched, root, target) {
2729
3486
  const path = relative5(
2730
3487
  root,
2731
- isAbsolute5(target) ? target : resolve8(root, target)
3488
+ isAbsolute6(target) ? target : resolve8(root, target)
2732
3489
  );
2733
3490
  if (!path || path.startsWith("..") || touched.some((entry) => entry.path === path))
2734
3491
  return [...touched];
@@ -2974,7 +3731,6 @@ function detect(cwd, prefs = {}) {
2974
3731
  }
2975
3732
 
2976
3733
  // src/hooks/policies/workspace/mainline-deliver.ts
2977
- var PUSH = /\bgit\b[^|;&\n]*\spush\b/u;
2978
3734
  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 branches, other remotes and other repositories push as usual.";
2979
3735
  var VALUE_OPTIONS = /* @__PURE__ */ new Set([
2980
3736
  "--repo",
@@ -3071,10 +3827,6 @@ var mainlineDeliver = {
3071
3827
  const call = shellCall(input);
3072
3828
  const project6 = checkoutOf(input.projectRoot);
3073
3829
  if (!call || !project6) return pass;
3074
- if (!call.steps) {
3075
- const hit2 = PUSH.test(call.command) && sameRepository(input.cwd, project6.commonDir);
3076
- return hit2 ? { verdict: "deny", reason: REASON8 } : pass;
3077
- }
3078
3830
  for (const step of realSteps(call.steps)) {
3079
3831
  if (program(step.argv[0]) !== "git") continue;
3080
3832
  const git2 = gitCall(step.argv);
@@ -3092,7 +3844,7 @@ var mainlineDeliver = {
3092
3844
  import { relative as relative6, resolve as resolve11 } from "node:path";
3093
3845
 
3094
3846
  // src/git/modes.ts
3095
- import { join as join6 } from "node:path";
3847
+ import { join as join7 } from "node:path";
3096
3848
  function withUmask(mask, run3) {
3097
3849
  if (mask === void 0) return run3();
3098
3850
  let before2;
@@ -3127,7 +3879,7 @@ function restoreModes(root, from, to) {
3127
3879
  const want = INDEX_MODES[entry.slice(0, 6)];
3128
3880
  if (want === void 0) continue;
3129
3881
  const path = entry.slice(tab + 1);
3130
- const file2 = join6(root, path);
3882
+ const file2 = join7(root, path);
3131
3883
  let mode;
3132
3884
  try {
3133
3885
  const stat3 = lstatSync(file2);
@@ -3157,7 +3909,7 @@ function restoreSubmoduleModes(root, from, to) {
3157
3909
  const match = GITLINK.exec(line);
3158
3910
  if (!match) continue;
3159
3911
  const [, before2, after, path] = match;
3160
- const dir = join6(root, path);
3912
+ const dir = join7(root, path);
3161
3913
  if (gitText(dir, ["rev-parse", "HEAD"]) !== after) continue;
3162
3914
  const old = /^0+$/u.test(before2) ? null : before2;
3163
3915
  for (const file2 of restoreModes(dir, old, after))
@@ -3175,12 +3927,12 @@ function reportModes(report2, fixed) {
3175
3927
  }
3176
3928
 
3177
3929
  // src/git/install.ts
3178
- import { dirname as dirname6, join as join7 } from "node:path";
3930
+ import { dirname as dirname6, join as join8 } from "node:path";
3179
3931
  function lockHash(root, paths) {
3180
3932
  const hash = createHash("sha256");
3181
3933
  let found = false;
3182
3934
  for (const path of paths) {
3183
- const file2 = join7(root, path);
3935
+ const file2 = join8(root, path);
3184
3936
  if (!existsSync(file2)) continue;
3185
3937
  found = true;
3186
3938
  hash.update(`${path}\0`).update(readFileSync(file2));
@@ -3190,7 +3942,7 @@ function lockHash(root, paths) {
3190
3942
  }
3191
3943
  function installedHash(root, spec) {
3192
3944
  if (spec.stamp?.hash !== "plain") return lockHash(root, spec.when);
3193
- const file2 = join7(root, spec.when[0] ?? "");
3945
+ const file2 = join8(root, spec.when[0] ?? "");
3194
3946
  if (!existsSync(file2)) return null;
3195
3947
  return createHash("sha256").update(readFileSync(file2)).digest("hex");
3196
3948
  }
@@ -3200,7 +3952,7 @@ function stampFile(root, spec) {
3200
3952
  return spec.stamp.path.replace("${git_dir}", gitDir);
3201
3953
  }
3202
3954
  const key = createHash("sha256").update([root, ...spec.when].join("\0")).digest("hex");
3203
- return join7(spec.stateDir, "installed", key);
3955
+ return join8(spec.stateDir, "installed", key);
3204
3956
  }
3205
3957
  function readStamp(path) {
3206
3958
  if (!existsSync(path)) return null;
@@ -3225,17 +3977,17 @@ function installIfStale(root, spec, report2) {
3225
3977
  }
3226
3978
 
3227
3979
  // src/git/superseded.ts
3228
- import { join as join8 } from "node:path";
3980
+ import { join as join9 } from "node:path";
3229
3981
  var GITLINK2 = /^:160000 160000 [0-9a-f]{40} ([0-9a-f]{40}) M$/u;
3230
3982
  function submoduleRepo(cwd, path) {
3231
- const checkout = join8(cwd, path);
3232
- if (existsSync(join8(checkout, ".git"))) return checkout;
3983
+ const checkout = join9(cwd, path);
3984
+ if (existsSync(join9(checkout, ".git"))) return checkout;
3233
3985
  const common = gitText(cwd, [
3234
3986
  "rev-parse",
3235
3987
  "--path-format=absolute",
3236
3988
  "--git-common-dir"
3237
3989
  ]);
3238
- const kept = common ? join8(common, "modules", path) : "";
3990
+ const kept = common ? join9(common, "modules", path) : "";
3239
3991
  return kept && existsSync(kept) ? kept : null;
3240
3992
  }
3241
3993
  function pinsSuperseded(cwd, upstream, sha) {
@@ -3308,7 +4060,7 @@ function distance(cwd, upstream) {
3308
4060
  }
3309
4061
 
3310
4062
  // src/git/added-submodules.ts
3311
- import { dirname as dirname7, join as join9 } from "node:path";
4063
+ import { dirname as dirname7, join as join10 } from "node:path";
3312
4064
  var ADDED_GITLINK = /^:\d{6} 160000 [0-9a-f]{40} ([0-9a-f]{40}) [AT]\t(.+)$/u;
3313
4065
  function initAddedSubmodules(root, from, to) {
3314
4066
  const raw = gitText(root, [
@@ -3329,8 +4081,8 @@ function initAddedSubmodules(root, from, to) {
3329
4081
  return lines;
3330
4082
  }
3331
4083
  function initOne(root, path, pin, from) {
3332
- const dir = join9(root, path);
3333
- if (existsSync(join9(dir, ".git"))) return followLeftCheckout(root, path, pin);
4084
+ const dir = join10(root, path);
4085
+ if (existsSync(join10(dir, ".git"))) return followLeftCheckout(root, path, pin);
3334
4086
  let displaced = "";
3335
4087
  if (existsSync(dir) && readdirSync(dir).length > 0) {
3336
4088
  if (unignoredFiles(root, path, from).length > 0)
@@ -3344,7 +4096,7 @@ function initOne(root, path, pin, from) {
3344
4096
  return `new submodule checked out at ${pin.slice(0, 10)}${aside}`;
3345
4097
  }
3346
4098
  function followLeftCheckout(root, path, pin) {
3347
- const dir = join9(root, path);
4099
+ const dir = join10(root, path);
3348
4100
  const head = git(dir, ["rev-parse", "HEAD"]);
3349
4101
  if (head.status === 0 && head.stdout.trim() === pin)
3350
4102
  return "already checked out";
@@ -3364,7 +4116,7 @@ function unignoredFiles(root, path, from) {
3364
4116
  let level = [path];
3365
4117
  while (level.length > 0) {
3366
4118
  const entries = level.flatMap(
3367
- (dir) => readdirSync(join9(root, dir), { withFileTypes: true }).map((entry) => ({
4119
+ (dir) => readdirSync(join10(root, dir), { withFileTypes: true }).map((entry) => ({
3368
4120
  path: `${dir}/${entry.name}`,
3369
4121
  dir: entry.isDirectory()
3370
4122
  }))
@@ -3384,7 +4136,7 @@ function unignoredFiles(root, path, from) {
3384
4136
  level = open2.filter((entry) => entry.dir).map((entry) => entry.path);
3385
4137
  }
3386
4138
  } finally {
3387
- for (const file2 of restored) rmSync(join9(root, file2));
4139
+ for (const file2 of restored) rmSync(join10(root, file2));
3388
4140
  }
3389
4141
  return kept;
3390
4142
  }
@@ -3402,7 +4154,7 @@ function restoreIgnoreFiles(root, path, from) {
3402
4154
  const restored = [];
3403
4155
  for (const file2 of listed.stdout.split("\0")) {
3404
4156
  if (!file2.endsWith("/.gitignore")) continue;
3405
- const target = join9(root, file2);
4157
+ const target = join10(root, file2);
3406
4158
  if (existsSync(target) || !existsSync(dirname7(target))) continue;
3407
4159
  const body = git(root, ["show", `${from}:${file2}`]);
3408
4160
  if (body.status !== 0) continue;
@@ -3414,14 +4166,14 @@ function restoreIgnoreFiles(root, path, from) {
3414
4166
  function displace(root, path) {
3415
4167
  const gitDir = gitText(root, ["rev-parse", "--absolute-git-dir"]);
3416
4168
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/gu, "-");
3417
- const target = join9(gitDir, "pmcp-displaced", stamp, path);
4169
+ const target = join10(gitDir, "pmcp-displaced", stamp, path);
3418
4170
  mkdirSync(dirname7(target), { recursive: true });
3419
- renameSync(join9(root, path), target);
4171
+ renameSync(join10(root, path), target);
3420
4172
  return target;
3421
4173
  }
3422
4174
 
3423
4175
  // src/git/submodules.ts
3424
- import { join as join10 } from "node:path";
4176
+ import { join as join11 } from "node:path";
3425
4177
  function clean(dir) {
3426
4178
  return git(dir, ["status", "--porcelain"]).stdout.trim() === "";
3427
4179
  }
@@ -3431,8 +4183,8 @@ function hasCommit(dir, sha) {
3431
4183
  function movableSubmodules(root) {
3432
4184
  const listed = git(root, ["submodule", "status"]).stdout;
3433
4185
  return listed.split("\n").filter((line) => /^[ +]/u.test(line)).map((line) => line.trim().split(/\s+/u)[1] ?? "").filter((path) => {
3434
- const dir = join10(root, path);
3435
- if (!path || !existsSync(join10(dir, ".git"))) return false;
4186
+ const dir = join11(root, path);
4187
+ if (!path || !existsSync(join11(dir, ".git"))) return false;
3436
4188
  const local = gitText(dir, [
3437
4189
  "rev-list",
3438
4190
  "--count",
@@ -3447,7 +4199,7 @@ function updateToPins(root, paths) {
3447
4199
  const lines = [];
3448
4200
  for (const path of paths) {
3449
4201
  const pin = gitText(root, ["rev-parse", `HEAD:${path}`]);
3450
- const dir = join10(root, path);
4202
+ const dir = join11(root, path);
3451
4203
  if (!pin || !hasCommit(dir, pin)) {
3452
4204
  lines.push(
3453
4205
  `${path}: left alone, ${pin.slice(0, 10) || "its pin"} is not in its checkout`
@@ -3575,7 +4327,7 @@ function changed(root, from, paths, to = "HEAD") {
3575
4327
  return gitText(root, ["diff", "--name-only", from, to, "--", ...paths]).split("\n").filter(Boolean);
3576
4328
  }
3577
4329
  function backgroundInstall(root, command6, umask) {
3578
- const child = withUmask(
4330
+ const child2 = withUmask(
3579
4331
  umask,
3580
4332
  () => spawn(command6[0], command6.slice(1), {
3581
4333
  cwd: root,
@@ -3583,10 +4335,10 @@ function backgroundInstall(root, command6, umask) {
3583
4335
  stdio: "ignore"
3584
4336
  })
3585
4337
  );
3586
- child.on("error", () => void 0);
3587
- child.unref();
4338
+ child2.on("error", () => void 0);
4339
+ child2.unref();
3588
4340
  }
3589
- function move(input, ctx, git2) {
4341
+ function move2(input, ctx, git2) {
3590
4342
  const opts = ctx.options;
3591
4343
  const lines = [];
3592
4344
  const report2 = {
@@ -3645,13 +4397,13 @@ var worktreeSync = {
3645
4397
  const reason2 = blocked2(input, ctx);
3646
4398
  if (reason2)
3647
4399
  return input.event === "session_start" ? { context: [`Worktree ${git2.root} was not moved: ${reason2}.`] } : pass;
3648
- const lines = move(input, ctx, git2);
4400
+ const lines = move2(input, ctx, git2);
3649
4401
  return lines.length > 0 ? { context: lines } : pass;
3650
4402
  }
3651
4403
  };
3652
4404
 
3653
4405
  // src/hooks/policies/custom.ts
3654
- import { isAbsolute as isAbsolute6, relative as relative7, resolve as resolve12 } from "node:path";
4406
+ import { isAbsolute as isAbsolute7, relative as relative7, resolve as resolve12 } from "node:path";
3655
4407
  var FAILED = "Guard failed validation or execution";
3656
4408
  var GUARD_PROTOCOL = "pmcp.guard.v1";
3657
4409
  var MAX_FINDINGS = 20;
@@ -3669,7 +4421,7 @@ function customMode(entry) {
3669
4421
  }
3670
4422
  function inside(base, path) {
3671
4423
  const rest = relative7(base, path);
3672
- return rest !== "" && !rest.startsWith("..") && !isAbsolute6(rest);
4424
+ return rest !== "" && !rest.startsWith("..") && !isAbsolute7(rest);
3673
4425
  }
3674
4426
  function guardScript(root, command6) {
3675
4427
  const script = command6[0]?.startsWith(".agents/guards/") ? command6[0] : command6[1];
@@ -3732,6 +4484,9 @@ function request(entry, input) {
3732
4484
  ...entry.event === "prompt" ? { prompt: input.prompt ?? "" } : {}
3733
4485
  });
3734
4486
  }
4487
+ function failedToRun(error) {
4488
+ return error !== void 0 && error.code !== "EPIPE";
4489
+ }
3735
4490
  function run2(entry, input, log) {
3736
4491
  const root = input.projectRoot;
3737
4492
  if (entry.guardSha256 !== void 0 && guardHash(root, entry.command) !== entry.guardSha256) {
@@ -3752,7 +4507,7 @@ function run2(entry, input, log) {
3752
4507
  killSignal: "SIGKILL",
3753
4508
  maxBuffer: 65536
3754
4509
  });
3755
- if (result.status !== 0 || result.error)
4510
+ if (result.status !== 0 || failedToRun(result.error))
3756
4511
  return { verdict: "deny", reason: FAILED };
3757
4512
  const response = JSON.parse(result.stdout);
3758
4513
  const extra = Object.keys(response).some(
@@ -3964,7 +4719,7 @@ function verdict(stdout) {
3964
4719
  }
3965
4720
 
3966
4721
  // src/hooks/runtimes/antigravity/payload.ts
3967
- import { isAbsolute as isAbsolute7, resolve as resolve13 } from "node:path";
4722
+ import { isAbsolute as isAbsolute8, resolve as resolve13 } from "node:path";
3968
4723
  function object(value) {
3969
4724
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
3970
4725
  }
@@ -3990,7 +4745,7 @@ function normalize(nativeEvent, payload, projectRoot) {
3990
4745
  const name = text3(call["name"]);
3991
4746
  const kind = name ? toolKind(name) : void 0;
3992
4747
  const target = text3(args["TargetFile"]);
3993
- const paths = target ? [isAbsolute7(target) ? target : resolve13(cwd, target)] : [];
4748
+ const paths = target ? [isAbsolute8(target) ? target : resolve13(cwd, target)] : [];
3994
4749
  return {
3995
4750
  contract: 2,
3996
4751
  runtime: "antigravity",
@@ -4011,9 +4766,9 @@ function normalize(nativeEvent, payload, projectRoot) {
4011
4766
  }
4012
4767
 
4013
4768
  // src/hooks/runtimes/climb.ts
4014
- function climbCommand(run3, missing, start) {
4769
+ function climbCommand(run3, missing, start2) {
4015
4770
  const skip = `echo "pmcp: no pmcp.toml at or above $(pwd -P); hook skipped" >&2`;
4016
- const from = start ? `cd ${start} 2>/dev/null; ` : "";
4771
+ const from = start2 ? `cd ${start2} 2>/dev/null; ` : "";
4017
4772
  return `${from}cd "$(pwd -P)" && while [ ! -f pmcp.toml ] && [ "$(pwd)" != / ]; do cd ..; done; if [ -f pmcp.toml ]; then exec ${run3}; fi; ${skip}` + (missing ? `; ${missing}` : "");
4018
4773
  }
4019
4774
  var HOOK_PATH = ".agents/pmcp-hooks/hook.mjs";
@@ -4195,7 +4950,7 @@ function verdict2(stdout) {
4195
4950
  }
4196
4951
 
4197
4952
  // src/hooks/runtimes/claude/payload.ts
4198
- import { isAbsolute as isAbsolute8, resolve as resolve14 } from "node:path";
4953
+ import { isAbsolute as isAbsolute9, resolve as resolve14 } from "node:path";
4199
4954
  function object2(value) {
4200
4955
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
4201
4956
  }
@@ -4212,7 +4967,7 @@ function normalize2(nativeEvent, payload, projectRoot) {
4212
4967
  toolInput["file_path"],
4213
4968
  toolInput["notebook_path"],
4214
4969
  kind === "read" ? toolInput["path"] : void 0
4215
- ].filter((value) => typeof value === "string" && !!value).map((path) => isAbsolute8(path) ? path : resolve14(cwd, path));
4970
+ ].filter((value) => typeof value === "string" && !!value).map((path) => isAbsolute9(path) ? path : resolve14(cwd, path));
4216
4971
  const agentType = text4(raw["agent_type"]);
4217
4972
  const turnId = text4(raw["prompt_id"]);
4218
4973
  const lastMessage = text4(raw["last_assistant_message"]);
@@ -4453,7 +5208,7 @@ function verdict3(stdout) {
4453
5208
  }
4454
5209
 
4455
5210
  // src/hooks/runtimes/codex/payload.ts
4456
- import { isAbsolute as isAbsolute9, resolve as resolve15 } from "node:path";
5211
+ import { isAbsolute as isAbsolute10, resolve as resolve15 } from "node:path";
4457
5212
  var PATCH_HEADER = /^\*\*\* (?:Update File|Add File|Delete File|Move to): (.+)$/gmu;
4458
5213
  function object3(value) {
4459
5214
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -4471,7 +5226,7 @@ function normalize3(nativeEvent, payload, projectRoot) {
4471
5226
  const toolInput = object3(raw["tool_input"]);
4472
5227
  const kind = name ? toolKind3(name) : void 0;
4473
5228
  const body = text5(toolInput["command"]) ?? "";
4474
- const paths = (kind === "edit" ? patchPaths(body) : []).filter(Boolean).map((path) => isAbsolute9(path) ? path : resolve15(cwd, path));
5229
+ const paths = (kind === "edit" ? patchPaths(body) : []).filter(Boolean).map((path) => isAbsolute10(path) ? path : resolve15(cwd, path));
4475
5230
  const turnId = text5(raw["turn_id"]);
4476
5231
  const lastMessage = text5(raw["last_assistant_message"]);
4477
5232
  const prompt = text5(raw["prompt"]);
@@ -4670,7 +5425,7 @@ function verdict4(stdout) {
4670
5425
  }
4671
5426
 
4672
5427
  // src/hooks/runtimes/gemini/payload.ts
4673
- import { isAbsolute as isAbsolute10, resolve as resolve16 } from "node:path";
5428
+ import { isAbsolute as isAbsolute11, resolve as resolve16 } from "node:path";
4674
5429
  function object4(value) {
4675
5430
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
4676
5431
  }
@@ -4683,7 +5438,7 @@ function normalize4(nativeEvent, payload, projectRoot) {
4683
5438
  const name = text6(raw["tool_name"]);
4684
5439
  const input = object4(raw["tool_input"]);
4685
5440
  const kind = name ? toolKind4(name) : void 0;
4686
- const paths = [input["file_path"], input["absolute_path"], input["path"]].filter((value) => typeof value === "string" && !!value).map((path) => isAbsolute10(path) ? path : resolve16(cwd, path));
5441
+ const paths = [input["file_path"], input["absolute_path"], input["path"]].filter((value) => typeof value === "string" && !!value).map((path) => isAbsolute11(path) ? path : resolve16(cwd, path));
4687
5442
  const prompt = text6(raw["prompt"]);
4688
5443
  const lastMessage = text6(raw["prompt_response"]);
4689
5444
  return {
@@ -4869,7 +5624,7 @@ function verdict5(stdout) {
4869
5624
  }
4870
5625
 
4871
5626
  // src/hooks/runtimes/grok/payload.ts
4872
- import { isAbsolute as isAbsolute11, resolve as resolve17 } from "node:path";
5627
+ import { isAbsolute as isAbsolute12, resolve as resolve17 } from "node:path";
4873
5628
  function object5(value) {
4874
5629
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
4875
5630
  }
@@ -4887,7 +5642,7 @@ function normalize5(nativeEvent, payload, projectRoot) {
4887
5642
  const input = object5(raw["toolInput"] ?? raw["tool_input"]);
4888
5643
  const kind = name ? toolKind5(name) : void 0;
4889
5644
  const path = text7(input["file_path"]);
4890
- const paths = path ? [isAbsolute11(path) ? path : resolve17(cwd, path)] : [];
5645
+ const paths = path ? [isAbsolute12(path) ? path : resolve17(cwd, path)] : [];
4891
5646
  const turnId = text7(raw["promptId"]);
4892
5647
  const prompt = text7(raw["prompt"]);
4893
5648
  const lastMessage = text7(raw["lastAssistantMessage"]);
@@ -5069,7 +5824,7 @@ function verdict6(stdout) {
5069
5824
  }
5070
5825
 
5071
5826
  // src/hooks/runtimes/opencode/payload.ts
5072
- import { isAbsolute as isAbsolute12, resolve as resolve18 } from "node:path";
5827
+ import { isAbsolute as isAbsolute13, resolve as resolve18 } from "node:path";
5073
5828
  function object6(value) {
5074
5829
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
5075
5830
  }
@@ -5085,7 +5840,7 @@ function normalize6(nativeEvent, payload, projectRoot) {
5085
5840
  const args = object6(raw["args"] ?? input["args"]);
5086
5841
  const kind = name ? toolKind6(name) : void 0;
5087
5842
  const path = text8(args["filePath"]);
5088
- const paths = path ? [isAbsolute12(path) ? path : resolve18(cwd, path)] : [];
5843
+ const paths = path ? [isAbsolute13(path) ? path : resolve18(cwd, path)] : [];
5089
5844
  const session = text8(input["sessionID"]) ?? text8(properties["sessionID"]) ?? "";
5090
5845
  return {
5091
5846
  contract: 2,
@@ -5299,8 +6054,8 @@ async function dispatch(raw, compiled, deps) {
5299
6054
  compose([protect, ...decisions]),
5300
6055
  compiled.lowering[input.runtime]
5301
6056
  );
5302
- const continued = input.event === "stop" && input.stop?.active === true;
5303
- const delivers = continued ? [] : RUNTIMES[input.runtime].capabilities.context;
6057
+ const continued2 = input.event === "stop" && input.stop?.active === true;
6058
+ const delivers = continued2 ? [] : RUNTIMES[input.runtime].capabilities.context;
5304
6059
  return deferContext(
5305
6060
  input,
5306
6061
  quietRepeatedStop(input, composed),
@@ -5310,18 +6065,18 @@ async function dispatch(raw, compiled, deps) {
5310
6065
  }
5311
6066
 
5312
6067
  // src/hooks/entry/fail-closed.ts
5313
- import { join as join13 } from "node:path";
6068
+ import { join as join14 } from "node:path";
5314
6069
 
5315
6070
  // src/hooks/compiled.ts
5316
- import { join as join12 } from "node:path";
6071
+ import { join as join13 } from "node:path";
5317
6072
 
5318
6073
  // src/hooks/integrity-cache.ts
5319
- import { homedir as homedir2 } from "node:os";
5320
- import { dirname as dirname8, join as join11 } from "node:path";
6074
+ import { homedir as homedir3 } from "node:os";
6075
+ import { dirname as dirname8, join as join12 } from "node:path";
5321
6076
  var LIMIT = 64;
5322
6077
  function cacheFile() {
5323
- const base = process.env["XDG_CACHE_HOME"] || join11(homedir2(), ".cache");
5324
- return join11(base, "pmcp", "hook-verified.json");
6078
+ const base = process.env["XDG_CACHE_HOME"] || join12(homedir3(), ".cache");
6079
+ return join12(base, "pmcp", "hook-verified.json");
5325
6080
  }
5326
6081
  function readCache() {
5327
6082
  try {
@@ -5391,8 +6146,8 @@ function readLockFile(path) {
5391
6146
  }
5392
6147
  }
5393
6148
  function readCompiled(root) {
5394
- const policyPath = join12(root, POLICY_FILE);
5395
- const files2 = [policyPath, join12(root, LOCK_FILE)];
6149
+ const policyPath = join13(root, POLICY_FILE);
6150
+ const files2 = [policyPath, join13(root, LOCK_FILE)];
5396
6151
  const before2 = stampOf(files2);
5397
6152
  const text9 = readFileSync(policyPath, "utf8");
5398
6153
  const lock = readLockFile(files2[1]);
@@ -5415,7 +6170,7 @@ function readCompiled(root) {
5415
6170
  var FAILED_CLOSED = "pmcp hook could not evaluate this call and refused it";
5416
6171
  function rawFailure(root) {
5417
6172
  try {
5418
- const raw = JSON.parse(readFileSync(join13(root, POLICY_FILE), "utf8"))["failure"];
6173
+ const raw = JSON.parse(readFileSync(join14(root, POLICY_FILE), "utf8"))["failure"];
5419
6174
  if (!raw || typeof raw.timeoutMs !== "number" || typeof raw.retry !== "number" || !Array.isArray(raw.pass) || !raw.pass.every(
5420
6175
  (kind) => PASS_KINDS.includes(kind)
5421
6176
  ))
@@ -5450,32 +6205,54 @@ function failClosed(adapter, event, root, error, stated = false) {
5450
6205
  }
5451
6206
 
5452
6207
  // src/hooks/entry/lock-repair.ts
5453
- import { join as join14, resolve as resolve19 } from "node:path";
5454
- var REV = String.raw`[\w./~^@{}-]+`;
5455
- var LOCK = String.raw`(?:\./)?pmcp\.lock`;
5456
- var REPAIRS = [
5457
- new RegExp(String.raw`^git show ${REV}:${LOCK} > ${LOCK}$`, "u"),
5458
- new RegExp(
5459
- String.raw`^git checkout (?:(?:--ours|--theirs|${REV}) )?(?:-- )?${LOCK}$`,
5460
- "u"
5461
- ),
5462
- new RegExp(
5463
- String.raw`^git restore (?:(?:--source=${REV}|--staged|--worktree|--ours|--theirs|-[SW]+) )*(?:-- )?${LOCK}$`,
5464
- "u"
5465
- )
5466
- ];
6208
+ import { join as join15, resolve as resolve19 } from "node:path";
6209
+ var REV = /^[\w./~^@{}][\w./~^@{}-]*$/u;
6210
+ var LOCK_PATHS = /* @__PURE__ */ new Set([LOCK_FILE, `./${LOCK_FILE}`]);
6211
+ var RESTORE_OPTIONS = /* @__PURE__ */ new Set([
6212
+ "--staged",
6213
+ "--worktree",
6214
+ "--ours",
6215
+ "--theirs"
6216
+ ]);
6217
+ var isLock = (word) => word !== void 0 && LOCK_PATHS.has(word);
6218
+ function showsLock(args, step) {
6219
+ const [spec, ...rest] = args;
6220
+ const colon = spec?.indexOf(":") ?? -1;
6221
+ const [into, ...more] = step.redirects;
6222
+ return rest.length === 0 && colon > 0 && REV.test(spec.slice(0, colon)) && isLock(spec.slice(colon + 1)) && more.length === 0 && into?.op === ">" && into.fd === "" && isLock(into.target);
6223
+ }
6224
+ function checksOutLock(sub, args) {
6225
+ if (!isLock(args.at(-1))) return false;
6226
+ let options2 = args.slice(0, -1);
6227
+ if (options2.at(-1) === "--") options2 = options2.slice(0, -1);
6228
+ if (sub === "checkout")
6229
+ return options2.length === 0 || options2.length === 1 && (options2[0] === "--ours" || options2[0] === "--theirs" || REV.test(options2[0]));
6230
+ if (sub === "restore")
6231
+ return options2.every(
6232
+ (option) => RESTORE_OPTIONS.has(option) || /^-[SW]+$/u.test(option) || option.startsWith("--source=") && REV.test(option.slice("--source=".length))
6233
+ );
6234
+ return false;
6235
+ }
6236
+ function restoresLock(command6) {
6237
+ const read4 = readScript(command6);
6238
+ if ("error" in read4 || read4.steps.length !== 1) return false;
6239
+ const step = read4.steps[0];
6240
+ if (step.assigned.length > 0 || read4.redirects.length !== step.redirects.length)
6241
+ return false;
6242
+ const [git2, sub = "", ...args] = step.argv;
6243
+ if (git2 !== "git") return false;
6244
+ if (sub === "show") return showsLock(args, step);
6245
+ return step.redirects.length === 0 && checksOutLock(sub, args);
6246
+ }
5467
6247
  function repairsLock(input, root) {
5468
6248
  const tool = input.tool;
5469
6249
  if (!tool) return false;
5470
6250
  if (tool.kind === "read") return true;
5471
6251
  if (tool.kind === "edit") {
5472
- const lock = join14(root, LOCK_FILE);
6252
+ const lock = join15(root, LOCK_FILE);
5473
6253
  return tool.paths.length > 0 && tool.paths.every((path) => resolve19(input.cwd, path) === lock);
5474
6254
  }
5475
- if (tool.kind === "shell") {
5476
- const command6 = (tool.command ?? "").trim().replace(/\s+/gu, " ");
5477
- return REPAIRS.some((pattern) => pattern.test(command6));
5478
- }
6255
+ if (tool.kind === "shell") return restoresLock(tool.command ?? "");
5479
6256
  return false;
5480
6257
  }
5481
6258
  function lockRepair(adapter, event, root, input, error) {
@@ -5490,7 +6267,7 @@ function lockRepair(adapter, event, root, input, error) {
5490
6267
  }
5491
6268
 
5492
6269
  // src/hooks/entry/logger.ts
5493
- import { dirname as dirname9, join as join17 } from "node:path";
6270
+ import { dirname as dirname9, join as join18 } from "node:path";
5494
6271
 
5495
6272
  // src/logging/levels.ts
5496
6273
  var LEVEL_RANK = {
@@ -5614,11 +6391,11 @@ var silentLogger = createLogger(() => {
5614
6391
  });
5615
6392
 
5616
6393
  // src/logging/sinks/file.ts
5617
- import { join as join15 } from "node:path";
6394
+ import { join as join16 } from "node:path";
5618
6395
  var FILE = /^pmcp-(\d{8})(?:\.\d+)?\.jsonl$/u;
5619
6396
  function dailyLogFile(dir, now = /* @__PURE__ */ new Date()) {
5620
6397
  const day = now.toISOString().slice(0, 10).replaceAll("-", "");
5621
- return join15(dir, `pmcp-${day}.jsonl`);
6398
+ return join16(dir, `pmcp-${day}.jsonl`);
5622
6399
  }
5623
6400
  function roll(file2) {
5624
6401
  let index = 1;
@@ -5649,7 +6426,7 @@ function logFiles(dir) {
5649
6426
  const part = (name) => Number(/\.(\d+)\.jsonl$/u.exec(name)?.[1] ?? Number.MAX_SAFE_INTEGER);
5650
6427
  return names3.sort(
5651
6428
  (a, b) => a.slice(5, 13).localeCompare(b.slice(5, 13)) || part(a) - part(b)
5652
- ).map((name) => join15(dir, name));
6429
+ ).map((name) => join16(dir, name));
5653
6430
  }
5654
6431
  function pruneLogs(dir, keepDays, now = /* @__PURE__ */ new Date()) {
5655
6432
  const cutoff = new Date(now.getTime() - keepDays * 864e5).toISOString().slice(0, 10).replaceAll("-", "");
@@ -5664,14 +6441,14 @@ function pruneLogs(dir, keepDays, now = /* @__PURE__ */ new Date()) {
5664
6441
  }
5665
6442
 
5666
6443
  // src/sessions/state-dir.ts
5667
- import { homedir as homedir3 } from "node:os";
5668
- import { join as join16 } from "node:path";
6444
+ import { homedir as homedir4 } from "node:os";
6445
+ import { join as join17 } from "node:path";
5669
6446
  function projectStateDir(root, override, env = process.env) {
5670
6447
  if (override) return expandPath(root, override);
5671
6448
  const anchor = gitCommonDir(root) ?? realpathSync(root);
5672
6449
  const id = createHash("sha256").update(anchor).digest("hex").slice(0, 16);
5673
- const base = env["XDG_STATE_HOME"] || join16(homedir3(), ".local", "state");
5674
- return join16(base, "pmcp", "projects", id);
6450
+ const base = env["XDG_STATE_HOME"] || join17(homedir4(), ".local", "state");
6451
+ return join17(base, "pmcp", "projects", id);
5675
6452
  }
5676
6453
 
5677
6454
  // src/hooks/entry/logger.ts
@@ -5686,7 +6463,7 @@ function hookLogger(root, compiled, runtime2, event) {
5686
6463
  process.env["PMCP_LOG"]
5687
6464
  );
5688
6465
  const file2 = compiled?.logFile ? expandPath(root, compiled.logFile) : void 0;
5689
- const dir = file2 ? dirname9(file2) : join17(projectStateDir(root, compiled?.stateDir), "logs");
6466
+ const dir = file2 ? dirname9(file2) : join18(projectStateDir(root, compiled?.stateDir), "logs");
5690
6467
  const sink = fileSink({
5691
6468
  dir,
5692
6469
  ...file2 ? { file: file2 } : {},
@@ -5702,18 +6479,18 @@ function hookLogger(root, compiled, runtime2, event) {
5702
6479
  }
5703
6480
 
5704
6481
  // src/hooks/entry/state-dir.ts
5705
- import { join as join19 } from "node:path";
6482
+ import { join as join20 } from "node:path";
5706
6483
 
5707
6484
  // src/sessions/lease-files.ts
5708
- import { dirname as dirname10, isAbsolute as isAbsolute13, join as join18 } from "node:path";
6485
+ import { dirname as dirname10, isAbsolute as isAbsolute14, join as join19 } from "node:path";
5709
6486
  var GATE_DIR = "${gate_dir}/";
5710
6487
  function gateTree(root, stateDir, gate, env) {
5711
6488
  const override = gate.treeEnv ? env[gate.treeEnv] : void 0;
5712
6489
  if (override) return override;
5713
- return gate.tree ? expandPath(root, gate.tree) : join18(stateDir, "gate", "tree");
6490
+ return gate.tree ? expandPath(root, gate.tree) : join19(stateDir, "gate", "tree");
5714
6491
  }
5715
6492
  function atGateDir(path, gateDir) {
5716
- return path.startsWith(GATE_DIR) ? join18(gateDir, path.slice(GATE_DIR.length)) : path;
6493
+ return path.startsWith(GATE_DIR) ? join19(gateDir, path.slice(GATE_DIR.length)) : path;
5717
6494
  }
5718
6495
  function resolvePauseFile(file2, gateDir) {
5719
6496
  return file2 === void 0 ? void 0 : atGateDir(file2, gateDir);
@@ -5768,7 +6545,7 @@ function pauseFileAnswer(root) {
5768
6545
  compiled?.sessions.gate,
5769
6546
  process.env
5770
6547
  );
5771
- return `${file2 ?? join19(stateDir, STATE_FILES.pause)}
6548
+ return `${file2 ?? join20(stateDir, STATE_FILES.pause)}
5772
6549
  `;
5773
6550
  }
5774
6551
 
@@ -5806,7 +6583,7 @@ var gitProbe = {
5806
6583
  };
5807
6584
 
5808
6585
  // src/sessions/files/broadcast.ts
5809
- import { join as join20 } from "node:path";
6586
+ import { join as join21 } from "node:path";
5810
6587
 
5811
6588
  // src/sessions/files/json.ts
5812
6589
  import { dirname as dirname11 } from "node:path";
@@ -5853,8 +6630,8 @@ function writeLines(path, values) {
5853
6630
 
5854
6631
  // src/sessions/files/broadcast.ts
5855
6632
  function filesBroadcast(dir, keep, registry2) {
5856
- const latestPath = join20(dir, STATE_FILES.broadcast);
5857
- const historyPath = join20(dir, STATE_FILES.history);
6633
+ const latestPath = join21(dir, STATE_FILES.broadcast);
6634
+ const historyPath = join21(dir, STATE_FILES.history);
5858
6635
  const list = () => {
5859
6636
  const latest = asBroadcast(readJson3(latestPath));
5860
6637
  if (!latest) return [];
@@ -5898,9 +6675,9 @@ function filesBroadcast(dir, keep, registry2) {
5898
6675
  }
5899
6676
 
5900
6677
  // src/sessions/files/leases.ts
5901
- import { dirname as dirname12, join as join21 } from "node:path";
6678
+ import { dirname as dirname12, join as join22 } from "node:path";
5902
6679
  function filesLeases(dir, files2 = {}) {
5903
- const leasePath = (name) => files2[name]?.file ?? join21(dir, leaseFile(name));
6680
+ const leasePath = (name) => files2[name]?.file ?? join22(dir, leaseFile(name));
5904
6681
  const read4 = (name) => {
5905
6682
  const lease = asLease(readJson3(leasePath(name)));
5906
6683
  if (!lease || !alive(lease.pid)) return null;
@@ -5950,28 +6727,28 @@ function filesLeases(dir, files2 = {}) {
5950
6727
  }
5951
6728
 
5952
6729
  // src/sessions/files/mailbox.ts
5953
- import { join as join22 } from "node:path";
6730
+ import { join as join23 } from "node:path";
5954
6731
  var ID = /^\d{13}-[0-9a-f]{8}$/u;
5955
6732
  var SAFE_KEY = /^@?[\w.-]+$/u;
5956
6733
  function filesMailbox(dir, settings) {
5957
- const messages = join22(dir, "messages");
5958
- const inbox = join22(dir, "inbox");
5959
- const pathOf = (id) => join22(messages, `${id}.json`);
6734
+ const messages = join23(dir, "messages");
6735
+ const inbox = join23(dir, "inbox");
6736
+ const pathOf = (id) => join23(messages, `${id}.json`);
5960
6737
  const marker = (key, id, kind) => {
5961
6738
  if (!SAFE_KEY.test(key) || !ID.test(id))
5962
6739
  throw new Error(`invalid mailbox key ${key} or id ${id}`);
5963
- return join22(inbox, key, `${id}.${kind}`);
6740
+ return join23(inbox, key, `${id}.${kind}`);
5964
6741
  };
5965
6742
  const audit = (event, fields2) => {
5966
6743
  if (!settings.audit) return;
5967
6744
  const line = { at: (/* @__PURE__ */ new Date()).toISOString(), event, ...fields2 };
5968
- appendFileSync(join22(dir, "messages.jsonl"), `${JSON.stringify(line)}
6745
+ appendFileSync(join23(dir, "messages.jsonl"), `${JSON.stringify(line)}
5969
6746
  `, {
5970
6747
  mode: 384
5971
6748
  });
5972
6749
  };
5973
6750
  const touch = (path) => {
5974
- mkdirSync(join22(path, ".."), { recursive: true, mode: 448 });
6751
+ mkdirSync(join23(path, ".."), { recursive: true, mode: 448 });
5975
6752
  try {
5976
6753
  writeFileSync(path, "", { flag: "wx", mode: 384 });
5977
6754
  return true;
@@ -5988,7 +6765,7 @@ function filesMailbox(dir, settings) {
5988
6765
  if (existsSync(inbox))
5989
6766
  for (const key of readdirSync(inbox))
5990
6767
  for (const kind of ["ack", "delivered"])
5991
- rmSync(join22(inbox, key, `${message.id}.${kind}`), { force: true });
6768
+ rmSync(join23(inbox, key, `${message.id}.${kind}`), { force: true });
5992
6769
  audit(event, { id: message.id });
5993
6770
  };
5994
6771
  return {
@@ -6064,9 +6841,9 @@ function filesMailbox(dir, settings) {
6064
6841
  }
6065
6842
 
6066
6843
  // src/sessions/files/pause.ts
6067
- import { join as join23 } from "node:path";
6844
+ import { join as join24 } from "node:path";
6068
6845
  function filesPause(dir, file2) {
6069
- const path = file2 ?? join23(dir, STATE_FILES.pause);
6846
+ const path = file2 ?? join24(dir, STATE_FILES.pause);
6070
6847
  return {
6071
6848
  read: () => asPause(readJson3(path)),
6072
6849
  write(pause2) {
@@ -6084,12 +6861,12 @@ function filesPause(dir, file2) {
6084
6861
  }
6085
6862
 
6086
6863
  // src/sessions/files/registry.ts
6087
- import { join as join24 } from "node:path";
6864
+ import { join as join25 } from "node:path";
6088
6865
  var SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/u;
6089
6866
  function filesRegistry(dir, staleMs) {
6090
- const records = join24(dir, STATE_FILES.records);
6091
- const dirs = [records, join24(dir, STATE_FILES.legacyRecords)];
6092
- const pathsOf = (session) => dirs.map((records2) => join24(records2, `${session}.json`));
6867
+ const records = join25(dir, STATE_FILES.records);
6868
+ const dirs = [records, join25(dir, STATE_FILES.legacyRecords)];
6869
+ const pathsOf = (session) => dirs.map((records2) => join25(records2, `${session}.json`));
6093
6870
  const get = (session) => {
6094
6871
  if (!SESSION_ID.test(session)) return null;
6095
6872
  return latestRecord(
@@ -6108,7 +6885,7 @@ function filesRegistry(dir, staleMs) {
6108
6885
  for (const name of names3)
6109
6886
  found.set(name, [
6110
6887
  ...found.get(name) ?? [],
6111
- asRecord(readJson3(join24(folder, name)))
6888
+ asRecord(readJson3(join25(folder, name)))
6112
6889
  ]);
6113
6890
  }
6114
6891
  return [...found.values()].map(latestRecord).filter((record) => record !== null).map((record) => ({ ...record, live: isLive(record, now, staleMs) }));
@@ -6135,7 +6912,7 @@ function filesRegistry(dir, staleMs) {
6135
6912
  next["worktree"] = checkout?.root ?? "";
6136
6913
  next["branch"] = checkout?.branch ?? "";
6137
6914
  }
6138
- writeJson(join24(records, `${session}.json`), next);
6915
+ writeJson(join25(records, `${session}.json`), next);
6139
6916
  return next;
6140
6917
  },
6141
6918
  sweep(now = Date.now()) {