@modootoday/pmcp 0.22.7 → 0.22.9

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 (77) 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-UYCLP5AL.js → apply-W5ZX5D5X.js} +10 -10
  6. package/dist/{chunk-6FFGGATI.js → chunk-2M3ECRPV.js} +5 -5
  7. package/dist/{chunk-XERIEIQ3.js → chunk-37Q7OYQX.js} +12 -12
  8. package/dist/{chunk-667C72QC.js → chunk-3TXTIBGH.js} +3 -3
  9. package/dist/{chunk-2R3FVI6M.js → chunk-4K6DXQOQ.js} +2 -2
  10. package/dist/{chunk-5NPDVKX5.js → chunk-65TTHA3K.js} +5 -5
  11. package/dist/{chunk-DYAOLBWZ.js → chunk-7GD2RXEX.js} +1081 -328
  12. package/dist/{chunk-GTZ5R2ER.js → chunk-ANFQ3A24.js} +2 -2
  13. package/dist/{chunk-7DYWCQVB.js → chunk-ARXCYFFZ.js} +1 -1
  14. package/dist/{chunk-NK5CAYET.js → chunk-D2P5GPVS.js} +2 -2
  15. package/dist/{chunk-565QGUAV.js → chunk-GHLTACBM.js} +2 -2
  16. package/dist/{chunk-4GBK5M5C.js → chunk-IRS5ZBET.js} +2 -2
  17. package/dist/{chunk-NVNC3JY5.js → chunk-JFXYSTPA.js} +3 -3
  18. package/dist/{chunk-CILQCERV.js → chunk-KPKMEUUH.js} +2 -2
  19. package/dist/{chunk-CBGY3ELI.js → chunk-L5S342S2.js} +2 -2
  20. package/dist/{chunk-QRTA5NGD.js → chunk-MDNLT3YR.js} +3 -3
  21. package/dist/chunk-NKR54YAW.js +7 -0
  22. package/dist/{chunk-JX5G2USM.js → chunk-SXOTPXCE.js} +3 -3
  23. package/dist/{chunk-CFSYEB4U.js → chunk-UYBWUOLR.js} +15 -2
  24. package/dist/{chunk-EKW2TQA3.js → chunk-YADCUUD4.js} +2 -2
  25. package/dist/{chunk-AOWWLVFL.js → chunk-ZPG5UPKH.js} +5 -5
  26. package/dist/{chunk-5EZKGPWY.js → chunk-ZRDQHCXB.js} +2 -2
  27. package/dist/{chunk-HABVHASY.js → chunk-ZUD2Q4SN.js} +2 -2
  28. package/dist/{cli-DKVUBOMX.js → cli-ZTYST4U5.js} +4 -4
  29. package/dist/cli.js +3 -3
  30. package/dist/{completion-5WIKJUXU.js → completion-P4Q5WEGQ.js} +2 -2
  31. package/dist/{diagnostics-6EKKP4FS.js → diagnostics-EENJZXVK.js} +5 -5
  32. package/dist/{doctor-XOUT6HJU.js → doctor-Y6N7JLTY.js} +11 -11
  33. package/dist/{entry-7THS4LUN.js → entry-3QQHN3DS.js} +9 -9
  34. package/dist/{exec-mcp-V4VMYZBN.js → exec-mcp-MSKMOFFR.js} +7 -7
  35. package/dist/{harness-3DFGRL57.js → harness-QMFQR45M.js} +3 -3
  36. package/dist/harness-launch-gate.js +3 -3
  37. package/dist/harness-worker.js +5 -5
  38. package/dist/hook-body.js +1265 -475
  39. package/dist/{hooks-QGH3RRZH.js → hooks-OJX3NOA5.js} +3 -3
  40. package/dist/{host-64MTQRJZ.js → host-I5LBMDRG.js} +6 -6
  41. package/dist/{host-AWCM6O5R.js → host-XKEUZRJK.js} +9 -9
  42. package/dist/{host-run-NCHMUCWE.js → host-run-NID7HYEA.js} +4 -4
  43. package/dist/http.js +1 -1
  44. package/dist/{import-mcp-WFDAOCTO.js → import-mcp-BEVPZARX.js} +6 -6
  45. package/dist/index.d.ts +1 -1
  46. package/dist/index.js +10 -10
  47. package/dist/{init-GXSUWZC7.js → init-RRF5WOZO.js} +2 -2
  48. package/dist/{invoke-5FOYWZKY.js → invoke-FOEHGZCL.js} +7 -7
  49. package/dist/{list-FOVH6DDM.js → list-HPICQV6B.js} +8 -8
  50. package/dist/{logout-BV4Z36EL.js → logout-CLP7DUYF.js} +7 -7
  51. package/dist/{mainline-VOEDBDZE.js → mainline-SQSAUOMQ.js} +5 -3
  52. package/dist/{mcp-VQGNYSEO.js → mcp-AKFNEMLA.js} +2 -2
  53. package/dist/{project-4YGFV3OU.js → project-NKQKVT7K.js} +4 -4
  54. package/dist/{run-JP4CIL5Z.js → run-AV2IEFAH.js} +4 -4
  55. package/dist/{run-JLZ5SCX6.js → run-TCQ7QY63.js} +6 -6
  56. package/dist/{serve-RYHXWUTT.js → serve-TBB3GQHM.js} +3 -3
  57. package/dist/{smoke-UA7VVDKD.js → smoke-2FI5D74B.js} +3 -3
  58. package/dist/{start-login-LXP4FVGX.js → start-login-ZIIZUDN2.js} +7 -7
  59. package/dist/{status-6TXNV2GA.js → status-AVMKB63P.js} +7 -7
  60. package/dist/{status-EBD7PGZZ.js → status-K5RQYXPU.js} +8 -8
  61. package/dist/stdio.js +2 -2
  62. package/dist/{test-56CNS2LD.js → test-NDE4VQ4N.js} +30 -22
  63. package/dist/{tui-6JJOARKG.js → tui-FFZEB25B.js} +4 -4
  64. package/dist/{worker-A3ZT5TTF.js → worker-EEOWWPAM.js} +7 -7
  65. package/dist/{worktree-sync-JS7ZSCKX.js → worktree-sync-DGNHSQ64.js} +2 -2
  66. package/docs/hooks.md +13 -3
  67. package/docs/upgrading.md +8 -0
  68. package/gemini-extension.json +2 -2
  69. package/mcp.json +1 -1
  70. package/package.json +5 -5
  71. package/plugin.json +1 -1
  72. package/plugins/pmcp/.claude-plugin/plugin.json +1 -1
  73. package/plugins/pmcp/.mcp.json +1 -1
  74. package/plugins/pmcp/gemini-extension.json +2 -2
  75. package/plugins/pmcp/mcp.json +1 -1
  76. package/plugins/pmcp/plugin.json +1 -1
  77. package/dist/chunk-7GL2BXSP.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 };
361
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;
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 "already checked out";
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)
@@ -3343,6 +4095,19 @@ function initOne(root, path, pin, from) {
3343
4095
  return `new submodule not checked out: ${done.stderr.trim()}${aside}`;
3344
4096
  return `new submodule checked out at ${pin.slice(0, 10)}${aside}`;
3345
4097
  }
4098
+ function followLeftCheckout(root, path, pin) {
4099
+ const dir = join10(root, path);
4100
+ const head = git(dir, ["rev-parse", "HEAD"]);
4101
+ if (head.status === 0 && head.stdout.trim() === pin)
4102
+ return "already checked out";
4103
+ const status = git(dir, ["status", "--porcelain", "--ignored"]);
4104
+ if (status.status !== 0 || status.stdout.trim() !== "")
4105
+ return `new submodule not checked out: the earlier checkout in ${path} holds changes or ignored files; move it aside, then git submodule update --init ${path}`;
4106
+ const done = git(root, ["submodule", "update", "--init", "-q", "--", path]);
4107
+ if (done.status !== 0)
4108
+ return `new submodule not checked out: ${done.stderr.trim()}`;
4109
+ return `earlier checkout moved to the new pin ${pin.slice(0, 10)}`;
4110
+ }
3346
4111
  function unignoredFiles(root, path, from) {
3347
4112
  const restored = restoreIgnoreFiles(root, path, from);
3348
4113
  const own = new Set(restored);
@@ -3351,7 +4116,7 @@ function unignoredFiles(root, path, from) {
3351
4116
  let level = [path];
3352
4117
  while (level.length > 0) {
3353
4118
  const entries = level.flatMap(
3354
- (dir) => readdirSync(join9(root, dir), { withFileTypes: true }).map((entry) => ({
4119
+ (dir) => readdirSync(join10(root, dir), { withFileTypes: true }).map((entry) => ({
3355
4120
  path: `${dir}/${entry.name}`,
3356
4121
  dir: entry.isDirectory()
3357
4122
  }))
@@ -3371,7 +4136,7 @@ function unignoredFiles(root, path, from) {
3371
4136
  level = open2.filter((entry) => entry.dir).map((entry) => entry.path);
3372
4137
  }
3373
4138
  } finally {
3374
- for (const file2 of restored) rmSync(join9(root, file2));
4139
+ for (const file2 of restored) rmSync(join10(root, file2));
3375
4140
  }
3376
4141
  return kept;
3377
4142
  }
@@ -3389,7 +4154,7 @@ function restoreIgnoreFiles(root, path, from) {
3389
4154
  const restored = [];
3390
4155
  for (const file2 of listed.stdout.split("\0")) {
3391
4156
  if (!file2.endsWith("/.gitignore")) continue;
3392
- const target = join9(root, file2);
4157
+ const target = join10(root, file2);
3393
4158
  if (existsSync(target) || !existsSync(dirname7(target))) continue;
3394
4159
  const body = git(root, ["show", `${from}:${file2}`]);
3395
4160
  if (body.status !== 0) continue;
@@ -3401,14 +4166,14 @@ function restoreIgnoreFiles(root, path, from) {
3401
4166
  function displace(root, path) {
3402
4167
  const gitDir = gitText(root, ["rev-parse", "--absolute-git-dir"]);
3403
4168
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/gu, "-");
3404
- const target = join9(gitDir, "pmcp-displaced", stamp, path);
4169
+ const target = join10(gitDir, "pmcp-displaced", stamp, path);
3405
4170
  mkdirSync(dirname7(target), { recursive: true });
3406
- renameSync(join9(root, path), target);
4171
+ renameSync(join10(root, path), target);
3407
4172
  return target;
3408
4173
  }
3409
4174
 
3410
4175
  // src/git/submodules.ts
3411
- import { join as join10 } from "node:path";
4176
+ import { join as join11 } from "node:path";
3412
4177
  function clean(dir) {
3413
4178
  return git(dir, ["status", "--porcelain"]).stdout.trim() === "";
3414
4179
  }
@@ -3418,8 +4183,8 @@ function hasCommit(dir, sha) {
3418
4183
  function movableSubmodules(root) {
3419
4184
  const listed = git(root, ["submodule", "status"]).stdout;
3420
4185
  return listed.split("\n").filter((line) => /^[ +]/u.test(line)).map((line) => line.trim().split(/\s+/u)[1] ?? "").filter((path) => {
3421
- const dir = join10(root, path);
3422
- if (!path || !existsSync(join10(dir, ".git"))) return false;
4186
+ const dir = join11(root, path);
4187
+ if (!path || !existsSync(join11(dir, ".git"))) return false;
3423
4188
  const local = gitText(dir, [
3424
4189
  "rev-list",
3425
4190
  "--count",
@@ -3434,7 +4199,7 @@ function updateToPins(root, paths) {
3434
4199
  const lines = [];
3435
4200
  for (const path of paths) {
3436
4201
  const pin = gitText(root, ["rev-parse", `HEAD:${path}`]);
3437
- const dir = join10(root, path);
4202
+ const dir = join11(root, path);
3438
4203
  if (!pin || !hasCommit(dir, pin)) {
3439
4204
  lines.push(
3440
4205
  `${path}: left alone, ${pin.slice(0, 10) || "its pin"} is not in its checkout`
@@ -3562,7 +4327,7 @@ function changed(root, from, paths, to = "HEAD") {
3562
4327
  return gitText(root, ["diff", "--name-only", from, to, "--", ...paths]).split("\n").filter(Boolean);
3563
4328
  }
3564
4329
  function backgroundInstall(root, command6, umask) {
3565
- const child = withUmask(
4330
+ const child2 = withUmask(
3566
4331
  umask,
3567
4332
  () => spawn(command6[0], command6.slice(1), {
3568
4333
  cwd: root,
@@ -3570,10 +4335,10 @@ function backgroundInstall(root, command6, umask) {
3570
4335
  stdio: "ignore"
3571
4336
  })
3572
4337
  );
3573
- child.on("error", () => void 0);
3574
- child.unref();
4338
+ child2.on("error", () => void 0);
4339
+ child2.unref();
3575
4340
  }
3576
- function move(input, ctx, git2) {
4341
+ function move2(input, ctx, git2) {
3577
4342
  const opts = ctx.options;
3578
4343
  const lines = [];
3579
4344
  const report2 = {
@@ -3632,13 +4397,13 @@ var worktreeSync = {
3632
4397
  const reason2 = blocked2(input, ctx);
3633
4398
  if (reason2)
3634
4399
  return input.event === "session_start" ? { context: [`Worktree ${git2.root} was not moved: ${reason2}.`] } : pass;
3635
- const lines = move(input, ctx, git2);
4400
+ const lines = move2(input, ctx, git2);
3636
4401
  return lines.length > 0 ? { context: lines } : pass;
3637
4402
  }
3638
4403
  };
3639
4404
 
3640
4405
  // src/hooks/policies/custom.ts
3641
- 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";
3642
4407
  var FAILED = "Guard failed validation or execution";
3643
4408
  var GUARD_PROTOCOL = "pmcp.guard.v1";
3644
4409
  var MAX_FINDINGS = 20;
@@ -3656,7 +4421,7 @@ function customMode(entry) {
3656
4421
  }
3657
4422
  function inside(base, path) {
3658
4423
  const rest = relative7(base, path);
3659
- return rest !== "" && !rest.startsWith("..") && !isAbsolute6(rest);
4424
+ return rest !== "" && !rest.startsWith("..") && !isAbsolute7(rest);
3660
4425
  }
3661
4426
  function guardScript(root, command6) {
3662
4427
  const script = command6[0]?.startsWith(".agents/guards/") ? command6[0] : command6[1];
@@ -3719,6 +4484,9 @@ function request(entry, input) {
3719
4484
  ...entry.event === "prompt" ? { prompt: input.prompt ?? "" } : {}
3720
4485
  });
3721
4486
  }
4487
+ function failedToRun(error) {
4488
+ return error !== void 0 && error.code !== "EPIPE";
4489
+ }
3722
4490
  function run2(entry, input, log) {
3723
4491
  const root = input.projectRoot;
3724
4492
  if (entry.guardSha256 !== void 0 && guardHash(root, entry.command) !== entry.guardSha256) {
@@ -3739,7 +4507,7 @@ function run2(entry, input, log) {
3739
4507
  killSignal: "SIGKILL",
3740
4508
  maxBuffer: 65536
3741
4509
  });
3742
- if (result.status !== 0 || result.error)
4510
+ if (result.status !== 0 || failedToRun(result.error))
3743
4511
  return { verdict: "deny", reason: FAILED };
3744
4512
  const response = JSON.parse(result.stdout);
3745
4513
  const extra = Object.keys(response).some(
@@ -3951,7 +4719,7 @@ function verdict(stdout) {
3951
4719
  }
3952
4720
 
3953
4721
  // src/hooks/runtimes/antigravity/payload.ts
3954
- import { isAbsolute as isAbsolute7, resolve as resolve13 } from "node:path";
4722
+ import { isAbsolute as isAbsolute8, resolve as resolve13 } from "node:path";
3955
4723
  function object(value) {
3956
4724
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
3957
4725
  }
@@ -3977,7 +4745,7 @@ function normalize(nativeEvent, payload, projectRoot) {
3977
4745
  const name = text3(call["name"]);
3978
4746
  const kind = name ? toolKind(name) : void 0;
3979
4747
  const target = text3(args["TargetFile"]);
3980
- const paths = target ? [isAbsolute7(target) ? target : resolve13(cwd, target)] : [];
4748
+ const paths = target ? [isAbsolute8(target) ? target : resolve13(cwd, target)] : [];
3981
4749
  return {
3982
4750
  contract: 2,
3983
4751
  runtime: "antigravity",
@@ -3998,9 +4766,9 @@ function normalize(nativeEvent, payload, projectRoot) {
3998
4766
  }
3999
4767
 
4000
4768
  // src/hooks/runtimes/climb.ts
4001
- function climbCommand(run3, missing, start) {
4769
+ function climbCommand(run3, missing, start2) {
4002
4770
  const skip = `echo "pmcp: no pmcp.toml at or above $(pwd -P); hook skipped" >&2`;
4003
- const from = start ? `cd ${start} 2>/dev/null; ` : "";
4771
+ const from = start2 ? `cd ${start2} 2>/dev/null; ` : "";
4004
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}` : "");
4005
4773
  }
4006
4774
  var HOOK_PATH = ".agents/pmcp-hooks/hook.mjs";
@@ -4182,7 +4950,7 @@ function verdict2(stdout) {
4182
4950
  }
4183
4951
 
4184
4952
  // src/hooks/runtimes/claude/payload.ts
4185
- import { isAbsolute as isAbsolute8, resolve as resolve14 } from "node:path";
4953
+ import { isAbsolute as isAbsolute9, resolve as resolve14 } from "node:path";
4186
4954
  function object2(value) {
4187
4955
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
4188
4956
  }
@@ -4199,7 +4967,7 @@ function normalize2(nativeEvent, payload, projectRoot) {
4199
4967
  toolInput["file_path"],
4200
4968
  toolInput["notebook_path"],
4201
4969
  kind === "read" ? toolInput["path"] : void 0
4202
- ].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));
4203
4971
  const agentType = text4(raw["agent_type"]);
4204
4972
  const turnId = text4(raw["prompt_id"]);
4205
4973
  const lastMessage = text4(raw["last_assistant_message"]);
@@ -4440,7 +5208,7 @@ function verdict3(stdout) {
4440
5208
  }
4441
5209
 
4442
5210
  // src/hooks/runtimes/codex/payload.ts
4443
- import { isAbsolute as isAbsolute9, resolve as resolve15 } from "node:path";
5211
+ import { isAbsolute as isAbsolute10, resolve as resolve15 } from "node:path";
4444
5212
  var PATCH_HEADER = /^\*\*\* (?:Update File|Add File|Delete File|Move to): (.+)$/gmu;
4445
5213
  function object3(value) {
4446
5214
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -4458,7 +5226,7 @@ function normalize3(nativeEvent, payload, projectRoot) {
4458
5226
  const toolInput = object3(raw["tool_input"]);
4459
5227
  const kind = name ? toolKind3(name) : void 0;
4460
5228
  const body = text5(toolInput["command"]) ?? "";
4461
- 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));
4462
5230
  const turnId = text5(raw["turn_id"]);
4463
5231
  const lastMessage = text5(raw["last_assistant_message"]);
4464
5232
  const prompt = text5(raw["prompt"]);
@@ -4657,7 +5425,7 @@ function verdict4(stdout) {
4657
5425
  }
4658
5426
 
4659
5427
  // src/hooks/runtimes/gemini/payload.ts
4660
- import { isAbsolute as isAbsolute10, resolve as resolve16 } from "node:path";
5428
+ import { isAbsolute as isAbsolute11, resolve as resolve16 } from "node:path";
4661
5429
  function object4(value) {
4662
5430
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
4663
5431
  }
@@ -4670,7 +5438,7 @@ function normalize4(nativeEvent, payload, projectRoot) {
4670
5438
  const name = text6(raw["tool_name"]);
4671
5439
  const input = object4(raw["tool_input"]);
4672
5440
  const kind = name ? toolKind4(name) : void 0;
4673
- 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));
4674
5442
  const prompt = text6(raw["prompt"]);
4675
5443
  const lastMessage = text6(raw["prompt_response"]);
4676
5444
  return {
@@ -4856,7 +5624,7 @@ function verdict5(stdout) {
4856
5624
  }
4857
5625
 
4858
5626
  // src/hooks/runtimes/grok/payload.ts
4859
- import { isAbsolute as isAbsolute11, resolve as resolve17 } from "node:path";
5627
+ import { isAbsolute as isAbsolute12, resolve as resolve17 } from "node:path";
4860
5628
  function object5(value) {
4861
5629
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
4862
5630
  }
@@ -4874,7 +5642,7 @@ function normalize5(nativeEvent, payload, projectRoot) {
4874
5642
  const input = object5(raw["toolInput"] ?? raw["tool_input"]);
4875
5643
  const kind = name ? toolKind5(name) : void 0;
4876
5644
  const path = text7(input["file_path"]);
4877
- const paths = path ? [isAbsolute11(path) ? path : resolve17(cwd, path)] : [];
5645
+ const paths = path ? [isAbsolute12(path) ? path : resolve17(cwd, path)] : [];
4878
5646
  const turnId = text7(raw["promptId"]);
4879
5647
  const prompt = text7(raw["prompt"]);
4880
5648
  const lastMessage = text7(raw["lastAssistantMessage"]);
@@ -5056,7 +5824,7 @@ function verdict6(stdout) {
5056
5824
  }
5057
5825
 
5058
5826
  // src/hooks/runtimes/opencode/payload.ts
5059
- import { isAbsolute as isAbsolute12, resolve as resolve18 } from "node:path";
5827
+ import { isAbsolute as isAbsolute13, resolve as resolve18 } from "node:path";
5060
5828
  function object6(value) {
5061
5829
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
5062
5830
  }
@@ -5072,7 +5840,7 @@ function normalize6(nativeEvent, payload, projectRoot) {
5072
5840
  const args = object6(raw["args"] ?? input["args"]);
5073
5841
  const kind = name ? toolKind6(name) : void 0;
5074
5842
  const path = text8(args["filePath"]);
5075
- const paths = path ? [isAbsolute12(path) ? path : resolve18(cwd, path)] : [];
5843
+ const paths = path ? [isAbsolute13(path) ? path : resolve18(cwd, path)] : [];
5076
5844
  const session = text8(input["sessionID"]) ?? text8(properties["sessionID"]) ?? "";
5077
5845
  return {
5078
5846
  contract: 2,
@@ -5286,8 +6054,8 @@ async function dispatch(raw, compiled, deps) {
5286
6054
  compose([protect, ...decisions]),
5287
6055
  compiled.lowering[input.runtime]
5288
6056
  );
5289
- const continued = input.event === "stop" && input.stop?.active === true;
5290
- 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;
5291
6059
  return deferContext(
5292
6060
  input,
5293
6061
  quietRepeatedStop(input, composed),
@@ -5297,18 +6065,18 @@ async function dispatch(raw, compiled, deps) {
5297
6065
  }
5298
6066
 
5299
6067
  // src/hooks/entry/fail-closed.ts
5300
- import { join as join13 } from "node:path";
6068
+ import { join as join14 } from "node:path";
5301
6069
 
5302
6070
  // src/hooks/compiled.ts
5303
- import { join as join12 } from "node:path";
6071
+ import { join as join13 } from "node:path";
5304
6072
 
5305
6073
  // src/hooks/integrity-cache.ts
5306
- import { homedir as homedir2 } from "node:os";
5307
- 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";
5308
6076
  var LIMIT = 64;
5309
6077
  function cacheFile() {
5310
- const base = process.env["XDG_CACHE_HOME"] || join11(homedir2(), ".cache");
5311
- 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");
5312
6080
  }
5313
6081
  function readCache() {
5314
6082
  try {
@@ -5378,8 +6146,8 @@ function readLockFile(path) {
5378
6146
  }
5379
6147
  }
5380
6148
  function readCompiled(root) {
5381
- const policyPath = join12(root, POLICY_FILE);
5382
- const files2 = [policyPath, join12(root, LOCK_FILE)];
6149
+ const policyPath = join13(root, POLICY_FILE);
6150
+ const files2 = [policyPath, join13(root, LOCK_FILE)];
5383
6151
  const before2 = stampOf(files2);
5384
6152
  const text9 = readFileSync(policyPath, "utf8");
5385
6153
  const lock = readLockFile(files2[1]);
@@ -5402,7 +6170,7 @@ function readCompiled(root) {
5402
6170
  var FAILED_CLOSED = "pmcp hook could not evaluate this call and refused it";
5403
6171
  function rawFailure(root) {
5404
6172
  try {
5405
- const raw = JSON.parse(readFileSync(join13(root, POLICY_FILE), "utf8"))["failure"];
6173
+ const raw = JSON.parse(readFileSync(join14(root, POLICY_FILE), "utf8"))["failure"];
5406
6174
  if (!raw || typeof raw.timeoutMs !== "number" || typeof raw.retry !== "number" || !Array.isArray(raw.pass) || !raw.pass.every(
5407
6175
  (kind) => PASS_KINDS.includes(kind)
5408
6176
  ))
@@ -5437,32 +6205,54 @@ function failClosed(adapter, event, root, error, stated = false) {
5437
6205
  }
5438
6206
 
5439
6207
  // src/hooks/entry/lock-repair.ts
5440
- import { join as join14, resolve as resolve19 } from "node:path";
5441
- var REV = String.raw`[\w./~^@{}-]+`;
5442
- var LOCK = String.raw`(?:\./)?pmcp\.lock`;
5443
- var REPAIRS = [
5444
- new RegExp(String.raw`^git show ${REV}:${LOCK} > ${LOCK}$`, "u"),
5445
- new RegExp(
5446
- String.raw`^git checkout (?:(?:--ours|--theirs|${REV}) )?(?:-- )?${LOCK}$`,
5447
- "u"
5448
- ),
5449
- new RegExp(
5450
- String.raw`^git restore (?:(?:--source=${REV}|--staged|--worktree|--ours|--theirs|-[SW]+) )*(?:-- )?${LOCK}$`,
5451
- "u"
5452
- )
5453
- ];
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
+ }
5454
6247
  function repairsLock(input, root) {
5455
6248
  const tool = input.tool;
5456
6249
  if (!tool) return false;
5457
6250
  if (tool.kind === "read") return true;
5458
6251
  if (tool.kind === "edit") {
5459
- const lock = join14(root, LOCK_FILE);
6252
+ const lock = join15(root, LOCK_FILE);
5460
6253
  return tool.paths.length > 0 && tool.paths.every((path) => resolve19(input.cwd, path) === lock);
5461
6254
  }
5462
- if (tool.kind === "shell") {
5463
- const command6 = (tool.command ?? "").trim().replace(/\s+/gu, " ");
5464
- return REPAIRS.some((pattern) => pattern.test(command6));
5465
- }
6255
+ if (tool.kind === "shell") return restoresLock(tool.command ?? "");
5466
6256
  return false;
5467
6257
  }
5468
6258
  function lockRepair(adapter, event, root, input, error) {
@@ -5477,7 +6267,7 @@ function lockRepair(adapter, event, root, input, error) {
5477
6267
  }
5478
6268
 
5479
6269
  // src/hooks/entry/logger.ts
5480
- import { dirname as dirname9, join as join17 } from "node:path";
6270
+ import { dirname as dirname9, join as join18 } from "node:path";
5481
6271
 
5482
6272
  // src/logging/levels.ts
5483
6273
  var LEVEL_RANK = {
@@ -5601,11 +6391,11 @@ var silentLogger = createLogger(() => {
5601
6391
  });
5602
6392
 
5603
6393
  // src/logging/sinks/file.ts
5604
- import { join as join15 } from "node:path";
6394
+ import { join as join16 } from "node:path";
5605
6395
  var FILE = /^pmcp-(\d{8})(?:\.\d+)?\.jsonl$/u;
5606
6396
  function dailyLogFile(dir, now = /* @__PURE__ */ new Date()) {
5607
6397
  const day = now.toISOString().slice(0, 10).replaceAll("-", "");
5608
- return join15(dir, `pmcp-${day}.jsonl`);
6398
+ return join16(dir, `pmcp-${day}.jsonl`);
5609
6399
  }
5610
6400
  function roll(file2) {
5611
6401
  let index = 1;
@@ -5636,7 +6426,7 @@ function logFiles(dir) {
5636
6426
  const part = (name) => Number(/\.(\d+)\.jsonl$/u.exec(name)?.[1] ?? Number.MAX_SAFE_INTEGER);
5637
6427
  return names3.sort(
5638
6428
  (a, b) => a.slice(5, 13).localeCompare(b.slice(5, 13)) || part(a) - part(b)
5639
- ).map((name) => join15(dir, name));
6429
+ ).map((name) => join16(dir, name));
5640
6430
  }
5641
6431
  function pruneLogs(dir, keepDays, now = /* @__PURE__ */ new Date()) {
5642
6432
  const cutoff = new Date(now.getTime() - keepDays * 864e5).toISOString().slice(0, 10).replaceAll("-", "");
@@ -5651,14 +6441,14 @@ function pruneLogs(dir, keepDays, now = /* @__PURE__ */ new Date()) {
5651
6441
  }
5652
6442
 
5653
6443
  // src/sessions/state-dir.ts
5654
- import { homedir as homedir3 } from "node:os";
5655
- import { join as join16 } from "node:path";
6444
+ import { homedir as homedir4 } from "node:os";
6445
+ import { join as join17 } from "node:path";
5656
6446
  function projectStateDir(root, override, env = process.env) {
5657
6447
  if (override) return expandPath(root, override);
5658
6448
  const anchor = gitCommonDir(root) ?? realpathSync(root);
5659
6449
  const id = createHash("sha256").update(anchor).digest("hex").slice(0, 16);
5660
- const base = env["XDG_STATE_HOME"] || join16(homedir3(), ".local", "state");
5661
- return join16(base, "pmcp", "projects", id);
6450
+ const base = env["XDG_STATE_HOME"] || join17(homedir4(), ".local", "state");
6451
+ return join17(base, "pmcp", "projects", id);
5662
6452
  }
5663
6453
 
5664
6454
  // src/hooks/entry/logger.ts
@@ -5673,7 +6463,7 @@ function hookLogger(root, compiled, runtime2, event) {
5673
6463
  process.env["PMCP_LOG"]
5674
6464
  );
5675
6465
  const file2 = compiled?.logFile ? expandPath(root, compiled.logFile) : void 0;
5676
- const dir = file2 ? dirname9(file2) : join17(projectStateDir(root, compiled?.stateDir), "logs");
6466
+ const dir = file2 ? dirname9(file2) : join18(projectStateDir(root, compiled?.stateDir), "logs");
5677
6467
  const sink = fileSink({
5678
6468
  dir,
5679
6469
  ...file2 ? { file: file2 } : {},
@@ -5689,18 +6479,18 @@ function hookLogger(root, compiled, runtime2, event) {
5689
6479
  }
5690
6480
 
5691
6481
  // src/hooks/entry/state-dir.ts
5692
- import { join as join19 } from "node:path";
6482
+ import { join as join20 } from "node:path";
5693
6483
 
5694
6484
  // src/sessions/lease-files.ts
5695
- 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";
5696
6486
  var GATE_DIR = "${gate_dir}/";
5697
6487
  function gateTree(root, stateDir, gate, env) {
5698
6488
  const override = gate.treeEnv ? env[gate.treeEnv] : void 0;
5699
6489
  if (override) return override;
5700
- return gate.tree ? expandPath(root, gate.tree) : join18(stateDir, "gate", "tree");
6490
+ return gate.tree ? expandPath(root, gate.tree) : join19(stateDir, "gate", "tree");
5701
6491
  }
5702
6492
  function atGateDir(path, gateDir) {
5703
- 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;
5704
6494
  }
5705
6495
  function resolvePauseFile(file2, gateDir) {
5706
6496
  return file2 === void 0 ? void 0 : atGateDir(file2, gateDir);
@@ -5755,7 +6545,7 @@ function pauseFileAnswer(root) {
5755
6545
  compiled?.sessions.gate,
5756
6546
  process.env
5757
6547
  );
5758
- return `${file2 ?? join19(stateDir, STATE_FILES.pause)}
6548
+ return `${file2 ?? join20(stateDir, STATE_FILES.pause)}
5759
6549
  `;
5760
6550
  }
5761
6551
 
@@ -5793,7 +6583,7 @@ var gitProbe = {
5793
6583
  };
5794
6584
 
5795
6585
  // src/sessions/files/broadcast.ts
5796
- import { join as join20 } from "node:path";
6586
+ import { join as join21 } from "node:path";
5797
6587
 
5798
6588
  // src/sessions/files/json.ts
5799
6589
  import { dirname as dirname11 } from "node:path";
@@ -5840,8 +6630,8 @@ function writeLines(path, values) {
5840
6630
 
5841
6631
  // src/sessions/files/broadcast.ts
5842
6632
  function filesBroadcast(dir, keep, registry2) {
5843
- const latestPath = join20(dir, STATE_FILES.broadcast);
5844
- const historyPath = join20(dir, STATE_FILES.history);
6633
+ const latestPath = join21(dir, STATE_FILES.broadcast);
6634
+ const historyPath = join21(dir, STATE_FILES.history);
5845
6635
  const list = () => {
5846
6636
  const latest = asBroadcast(readJson3(latestPath));
5847
6637
  if (!latest) return [];
@@ -5885,9 +6675,9 @@ function filesBroadcast(dir, keep, registry2) {
5885
6675
  }
5886
6676
 
5887
6677
  // src/sessions/files/leases.ts
5888
- import { dirname as dirname12, join as join21 } from "node:path";
6678
+ import { dirname as dirname12, join as join22 } from "node:path";
5889
6679
  function filesLeases(dir, files2 = {}) {
5890
- const leasePath = (name) => files2[name]?.file ?? join21(dir, leaseFile(name));
6680
+ const leasePath = (name) => files2[name]?.file ?? join22(dir, leaseFile(name));
5891
6681
  const read4 = (name) => {
5892
6682
  const lease = asLease(readJson3(leasePath(name)));
5893
6683
  if (!lease || !alive(lease.pid)) return null;
@@ -5937,28 +6727,28 @@ function filesLeases(dir, files2 = {}) {
5937
6727
  }
5938
6728
 
5939
6729
  // src/sessions/files/mailbox.ts
5940
- import { join as join22 } from "node:path";
6730
+ import { join as join23 } from "node:path";
5941
6731
  var ID = /^\d{13}-[0-9a-f]{8}$/u;
5942
6732
  var SAFE_KEY = /^@?[\w.-]+$/u;
5943
6733
  function filesMailbox(dir, settings) {
5944
- const messages = join22(dir, "messages");
5945
- const inbox = join22(dir, "inbox");
5946
- 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`);
5947
6737
  const marker = (key, id, kind) => {
5948
6738
  if (!SAFE_KEY.test(key) || !ID.test(id))
5949
6739
  throw new Error(`invalid mailbox key ${key} or id ${id}`);
5950
- return join22(inbox, key, `${id}.${kind}`);
6740
+ return join23(inbox, key, `${id}.${kind}`);
5951
6741
  };
5952
6742
  const audit = (event, fields2) => {
5953
6743
  if (!settings.audit) return;
5954
6744
  const line = { at: (/* @__PURE__ */ new Date()).toISOString(), event, ...fields2 };
5955
- appendFileSync(join22(dir, "messages.jsonl"), `${JSON.stringify(line)}
6745
+ appendFileSync(join23(dir, "messages.jsonl"), `${JSON.stringify(line)}
5956
6746
  `, {
5957
6747
  mode: 384
5958
6748
  });
5959
6749
  };
5960
6750
  const touch = (path) => {
5961
- mkdirSync(join22(path, ".."), { recursive: true, mode: 448 });
6751
+ mkdirSync(join23(path, ".."), { recursive: true, mode: 448 });
5962
6752
  try {
5963
6753
  writeFileSync(path, "", { flag: "wx", mode: 384 });
5964
6754
  return true;
@@ -5975,7 +6765,7 @@ function filesMailbox(dir, settings) {
5975
6765
  if (existsSync(inbox))
5976
6766
  for (const key of readdirSync(inbox))
5977
6767
  for (const kind of ["ack", "delivered"])
5978
- rmSync(join22(inbox, key, `${message.id}.${kind}`), { force: true });
6768
+ rmSync(join23(inbox, key, `${message.id}.${kind}`), { force: true });
5979
6769
  audit(event, { id: message.id });
5980
6770
  };
5981
6771
  return {
@@ -6051,9 +6841,9 @@ function filesMailbox(dir, settings) {
6051
6841
  }
6052
6842
 
6053
6843
  // src/sessions/files/pause.ts
6054
- import { join as join23 } from "node:path";
6844
+ import { join as join24 } from "node:path";
6055
6845
  function filesPause(dir, file2) {
6056
- const path = file2 ?? join23(dir, STATE_FILES.pause);
6846
+ const path = file2 ?? join24(dir, STATE_FILES.pause);
6057
6847
  return {
6058
6848
  read: () => asPause(readJson3(path)),
6059
6849
  write(pause2) {
@@ -6071,12 +6861,12 @@ function filesPause(dir, file2) {
6071
6861
  }
6072
6862
 
6073
6863
  // src/sessions/files/registry.ts
6074
- import { join as join24 } from "node:path";
6864
+ import { join as join25 } from "node:path";
6075
6865
  var SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/u;
6076
6866
  function filesRegistry(dir, staleMs) {
6077
- const records = join24(dir, STATE_FILES.records);
6078
- const dirs = [records, join24(dir, STATE_FILES.legacyRecords)];
6079
- 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`));
6080
6870
  const get = (session) => {
6081
6871
  if (!SESSION_ID.test(session)) return null;
6082
6872
  return latestRecord(
@@ -6095,7 +6885,7 @@ function filesRegistry(dir, staleMs) {
6095
6885
  for (const name of names3)
6096
6886
  found.set(name, [
6097
6887
  ...found.get(name) ?? [],
6098
- asRecord(readJson3(join24(folder, name)))
6888
+ asRecord(readJson3(join25(folder, name)))
6099
6889
  ]);
6100
6890
  }
6101
6891
  return [...found.values()].map(latestRecord).filter((record) => record !== null).map((record) => ({ ...record, live: isLive(record, now, staleMs) }));
@@ -6122,7 +6912,7 @@ function filesRegistry(dir, staleMs) {
6122
6912
  next["worktree"] = checkout?.root ?? "";
6123
6913
  next["branch"] = checkout?.branch ?? "";
6124
6914
  }
6125
- writeJson(join24(records, `${session}.json`), next);
6915
+ writeJson(join25(records, `${session}.json`), next);
6126
6916
  return next;
6127
6917
  },
6128
6918
  sweep(now = Date.now()) {