opencode-commit-guard 1.0.5 → 1.0.7

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.
package/dist/index.js CHANGED
@@ -45,11 +45,13 @@ function digest(text) {
45
45
  }
46
46
  function scopeFor(ctx, sessionID, config, targetDir) {
47
47
  const location = ctx.location;
48
+ const directory = targetDir ?? location.directory;
49
+ const root = findGitRoot(directory) ?? realpathSync(directory);
48
50
  return digest(JSON.stringify([
49
51
  version,
50
52
  location.project.id,
51
53
  sessionID,
52
- targetDir ?? location.directory,
54
+ root,
53
55
  location.workspaceID ?? null,
54
56
  policy,
55
57
  config.requireScope,
@@ -163,9 +165,39 @@ function counter(ctx, scope) {
163
165
  function invalidate(ctx, scope) {
164
166
  return storageLock.withPermits(1)(Effect.gen(function* () {
165
167
  const previous = yield* counter(ctx, scope);
166
- yield* ctx.storage.set(counterKey(scope), previous < 0 ? 1 : previous + 1);
168
+ const next = previous < 0 ? 1 : previous + 1;
169
+ yield* ctx.storage.set(counterKey(scope), next);
170
+ return next;
167
171
  }));
168
172
  }
173
+ function invalidateOwned(ctx, attempt) {
174
+ return storageLock.withPermits(1)(Effect.gen(function* () {
175
+ if ((yield* counter(ctx, attempt.scope)) === attempt.counter) {
176
+ yield* ctx.storage.set(counterKey(attempt.scope), attempt.counter + 1);
177
+ }
178
+ }));
179
+ }
180
+ function recordState(ctx, attempt, state, reason = "") {
181
+ return storageLock.withPermits(1)(Effect.gen(function* () {
182
+ if ((yield* counter(ctx, attempt.scope)) !== attempt.counter)
183
+ return;
184
+ yield* ctx.storage.set(`state/${attempt.scope}`, { state, reason: reason.slice(0, 256) });
185
+ }));
186
+ }
187
+ function captureStatus(ctx, scope) {
188
+ return Effect.gen(function* () {
189
+ const value = yield* ctx.storage.get(`state/${scope}`);
190
+ if (!isRecord(value))
191
+ return "";
192
+ if (value["state"] === "expired")
193
+ return "The previous capture expired before its command was claimed; no matching shell result was observed. ";
194
+ if (value["state"] === "failed" && isJSONString(value["reason"]))
195
+ return `The previous capture failed: ${value["reason"]}. `;
196
+ if (value["state"] === "prepared" || value["state"] === "claimed")
197
+ return "The previous capture was interrupted before publication. ";
198
+ return "";
199
+ });
200
+ }
169
201
  function validBaseline(value) {
170
202
  if (!isRecord(value))
171
203
  return false;
@@ -305,6 +337,9 @@ function publish(ctx, pending, generation, baseline) {
305
337
  }));
306
338
  }
307
339
 
340
+ // src/scope.ts
341
+ var scopePattern = /^([a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(.+)$/;
342
+
308
343
  // src/config.ts
309
344
  function parseConfig(options) {
310
345
  if (options === undefined) {
@@ -332,6 +367,9 @@ function parseConfig(options) {
332
367
  if (!isJSONString(item) || item.trim().length === 0) {
333
368
  throw new Error("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
334
369
  }
370
+ if (scopePattern.exec(`${item.trim()}: Subject`)?.[1] !== item.trim()) {
371
+ throw new Error(`Invalid plugin option allowedScopes; scope ${JSON.stringify(item)} cannot match the commit scope syntax.`);
372
+ }
335
373
  scopes.push(item.trim());
336
374
  }
337
375
  allowedScopes = scopes.length > 0 ? scopes : undefined;
@@ -403,22 +441,37 @@ var commitLongOptionsWithArg = new Set([
403
441
  "--reedit-message",
404
442
  "--reuse-message",
405
443
  "--squash",
406
- "--template",
407
- "--trailer"
444
+ "--template"
408
445
  ]);
409
446
  function isWordSeparator(character) {
410
447
  return character === " " || character === "\t" || character === "\r" || character === `
411
- ` || character === ";" || character === "&" || character === "|" || character === "(" || character === ")" || character === "{" || character === "}";
448
+ ` || character === ";" || character === "&" || character === "|" || character === "(" || character === ")";
412
449
  }
413
- function consumeCommandSubstitution(command, start) {
450
+ function consumeCommandSubstitution(command, start, nesting = 0) {
451
+ if (nesting > 12)
452
+ throw new Error("Shell parsing limit exceeded. Run git commit directly.");
414
453
  let depth = 1;
415
454
  let quote;
416
455
  let i = start + 2;
417
456
  let atWordStart = true;
457
+ let atCommandStart = true;
458
+ let timeOption = false;
459
+ let arithmeticDepth = command[start + 2] === "(" ? 1 : undefined;
460
+ const pendingHeredocs = [];
418
461
  while (i < command.length) {
419
462
  const character = command[i];
420
463
  if (character === undefined)
421
464
  break;
465
+ if (quote === "$'") {
466
+ if (character === "'")
467
+ quote = undefined;
468
+ else if (character === "\\") {
469
+ i = ansiEscape(command, i).end;
470
+ continue;
471
+ }
472
+ i++;
473
+ continue;
474
+ }
422
475
  if (quote === "'") {
423
476
  if (character === "'")
424
477
  quote = undefined;
@@ -432,7 +485,11 @@ function consumeCommandSubstitution(command, start) {
432
485
  quote = undefined;
433
486
  i++;
434
487
  } else if (character === "$" && command[i + 1] === "(") {
435
- i = consumeCommandSubstitution(command, i).end;
488
+ i = consumeCommandSubstitution(command, i, nesting + 1).end;
489
+ } else if (character === "$" && command[i + 1] === "{") {
490
+ i = consumeQuotedParameter(command, i);
491
+ } else if (character === "`") {
492
+ i = consumeBackticks(command, i, true).end;
436
493
  } else {
437
494
  i++;
438
495
  }
@@ -440,11 +497,65 @@ function consumeCommandSubstitution(command, start) {
440
497
  }
441
498
  if (character === "\\") {
442
499
  if (command[i + 1] !== `
443
- `)
500
+ `) {
444
501
  atWordStart = false;
502
+ atCommandStart = false;
503
+ }
445
504
  i += i + 1 < command.length ? 2 : 1;
446
505
  continue;
447
506
  }
507
+ if (arithmeticDepth === undefined && character === "<" && command[i + 1] === "<") {
508
+ if (command[i + 2] === "<") {
509
+ i += 3;
510
+ } else {
511
+ const parsed = tokenizeShellInput(command, i, true, nesting + 1);
512
+ if (parsed.delimiter === undefined)
513
+ throw incompleteHeredoc();
514
+ pendingHeredocs.push(parsed.delimiter);
515
+ i = parsed.end;
516
+ }
517
+ atWordStart = true;
518
+ continue;
519
+ }
520
+ if (character === `
521
+ ` && pendingHeredocs.length > 0) {
522
+ i++;
523
+ for (const heredoc of pendingHeredocs)
524
+ i = consumeHeredoc(command, i, heredoc).end;
525
+ pendingHeredocs.length = 0;
526
+ atWordStart = true;
527
+ atCommandStart = true;
528
+ timeOption = false;
529
+ continue;
530
+ }
531
+ if (atCommandStart && atWordStart && !isWordSeparator(character) && character !== "#") {
532
+ let word = "";
533
+ for (let end = i;end < command.length; end++) {
534
+ const next = command[end];
535
+ if (next === "\\" && command[end + 1] === `
536
+ `) {
537
+ end++;
538
+ continue;
539
+ }
540
+ if (isWordSeparator(next))
541
+ break;
542
+ word += next;
543
+ }
544
+ if (word === "case") {
545
+ throw new Error("Cannot parse case patterns inside a command substitution. Run the case command separately or run git commit directly.");
546
+ }
547
+ if (word === "function" || word === "coproc") {
548
+ throw new Error("Cannot parse function or coproc declarations inside a command substitution. Run the declaration separately or run git commit directly.");
549
+ }
550
+ atCommandStart = timeOption && (word === "-p" || word === "--") || commandPrefixes.has(word) || word === "{";
551
+ timeOption = word === "time" || timeOption && word === "-p";
552
+ }
553
+ if (character === "$" && command[i + 1] === "'") {
554
+ quote = "$'";
555
+ atWordStart = false;
556
+ i += 2;
557
+ continue;
558
+ }
448
559
  if (character === "'") {
449
560
  quote = "'";
450
561
  atWordStart = false;
@@ -464,42 +575,104 @@ function consumeCommandSubstitution(command, start) {
464
575
  continue;
465
576
  }
466
577
  if (character === "$" && command[i + 1] === "(") {
467
- i = consumeCommandSubstitution(command, i).end;
578
+ i = consumeCommandSubstitution(command, i, nesting + 1).end;
579
+ atWordStart = false;
580
+ continue;
581
+ }
582
+ if (character === "`") {
583
+ i = consumeBackticks(command, i).end;
468
584
  atWordStart = false;
469
585
  continue;
470
586
  }
471
587
  if (character === "(") {
588
+ if (arithmeticDepth === undefined && atCommandStart && command[i + 1] === "(")
589
+ arithmeticDepth = depth;
472
590
  depth++;
473
591
  i++;
474
592
  atWordStart = true;
593
+ atCommandStart = true;
475
594
  continue;
476
595
  }
477
596
  if (character === ")") {
478
597
  depth--;
598
+ if (depth === arithmeticDepth)
599
+ arithmeticDepth = undefined;
479
600
  if (depth === 0) {
601
+ if (pendingHeredocs.length > 0)
602
+ throw incompleteHeredoc();
480
603
  return { content: command.slice(start + 2, i), end: i + 1 };
481
604
  }
482
605
  atWordStart = true;
483
606
  }
607
+ if ([";", "&", "|", `
608
+ `, ")"].includes(character)) {
609
+ atCommandStart = true;
610
+ timeOption = false;
611
+ }
484
612
  if (isWordSeparator(character))
485
613
  atWordStart = true;
486
614
  else
487
615
  atWordStart = false;
488
616
  i++;
489
617
  }
490
- return { content: command.slice(start + 2), end: command.length };
618
+ if (pendingHeredocs.length > 0)
619
+ throw incompleteHeredoc();
620
+ throw new Error(`Unterminated $( substitution starting at character ${start + 1}. Close it with ) or use single quotes for literal text.`);
491
621
  }
492
- function pushWord(tokens, value, substitutions) {
493
- if (substitutions.length > 0) {
494
- tokens.push({ type: "word", value, substitutions });
495
- } else {
496
- tokens.push({ type: "word", value });
622
+ function consumeBackticks(command, start, doubleQuoted = false) {
623
+ let content = "";
624
+ for (let i = start + 1;i < command.length; i++) {
625
+ if (command[i] === "`")
626
+ return { content, end: i + 1 };
627
+ if (command[i] === "\\" && (["$", "`", "\\"].includes(command[i + 1] ?? "") || doubleQuoted && command[i + 1] === '"'))
628
+ i++;
629
+ content += command[i];
497
630
  }
631
+ throw new Error(`Unterminated backtick substitution starting at character ${start + 1}. Close it, escape a literal backtick as \\\`, or use single quotes.`);
632
+ }
633
+ function consumeQuotedParameter(command, start) {
634
+ for (let i = start + 2;i < command.length; i++) {
635
+ const character = command[i];
636
+ if (character === "}")
637
+ return i + 1;
638
+ if (["'", '"', "\\", "`", "$", "{"].includes(character))
639
+ break;
640
+ }
641
+ throw new Error('Cannot parse nested quoting or expansions in a double-quoted parameter expansion. Use a simple parameter such as "${HOME}" or run git commit directly.');
642
+ }
643
+ function ansiEscape(command, start) {
644
+ const escaped = command[start + 1] ?? "";
645
+ const simple = new Map(Object.entries({ a: "\x07", b: "\b", e: "\x1B", E: "\x1B", f: "\f", n: `
646
+ `, r: "\r", t: "\t", v: "\v", "\\": "\\", "'": "'", '"': '"', "?": "?" }));
647
+ const literal = simple.get(escaped);
648
+ if (literal !== undefined)
649
+ return { content: literal, end: start + 2 };
650
+ if (escaped === "c" && command[start + 2] !== undefined && command[start + 2] !== "'") {
651
+ const character = command[start + 2];
652
+ const end = start + (character === "\\" && command[start + 3] === "\\" ? 4 : 3);
653
+ return { content: String.fromCharCode(character === "?" ? 127 : character.toUpperCase().charCodeAt(0) & 31), end };
654
+ }
655
+ const count = escaped === "x" ? 2 : escaped === "u" ? 4 : escaped === "U" ? 8 : 0;
656
+ const digits = count > 0 ? command.slice(start + 2).match(new RegExp(`^[0-9a-fA-F]{1,${count}}`))?.[0] : command.slice(start + 1).match(/^[0-7]{1,3}/)?.[0];
657
+ if (digits !== undefined) {
658
+ const code = Number.parseInt(digits, count > 0 ? 16 : 8);
659
+ if (code > 1114111)
660
+ throw new Error("Cannot validate this ANSI-C escape. Supply the message literally.");
661
+ const end = start + (count > 0 ? 2 : 1) + digits.length;
662
+ if (count === 0 || escaped === "x")
663
+ return { content: "", byte: code & 255, end };
664
+ return { content: String.fromCodePoint(code), end };
665
+ }
666
+ return { content: `\\${escaped}`, end: start + 2 };
667
+ }
668
+ function pushWord(tokens, value, substitutions, expansion) {
669
+ const token = substitutions.length > 0 ? { type: "word", value, substitutions } : { type: "word", value };
670
+ tokens.push(expansion ? { ...token, expansion: true } : token);
498
671
  }
499
672
  function heredocSubstitutions(body) {
500
673
  const substitutions = [];
501
674
  for (let i = 0;i < body.length; i++) {
502
- if (body[i] === "\\" && (body[i + 1] === "$" || body[i + 1] === "`")) {
675
+ if (body[i] === "\\" && ["\\", "$", "`"].includes(body[i + 1] ?? "")) {
503
676
  i++;
504
677
  } else if (body[i] === "`") {
505
678
  throw new Error("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.");
@@ -511,11 +684,47 @@ function heredocSubstitutions(body) {
511
684
  }
512
685
  return substitutions;
513
686
  }
687
+ function incompleteHeredoc() {
688
+ return new Error("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.");
689
+ }
690
+ function consumeHeredoc(command, start, heredoc) {
691
+ let i = start;
692
+ let body = "";
693
+ while (i < command.length) {
694
+ let line = "";
695
+ let newline = false;
696
+ while (i < command.length) {
697
+ const lineEnd = command.indexOf(`
698
+ `, i);
699
+ const end = lineEnd < 0 ? command.length : lineEnd;
700
+ const physicalLine = command.slice(i, end);
701
+ const backslashes = physicalLine.match(/\\+$/)?.[0].length ?? 0;
702
+ newline = lineEnd >= 0;
703
+ i = newline ? end + 1 : end;
704
+ if (!heredoc.quoted && newline && backslashes % 2 === 1) {
705
+ line += physicalLine.slice(0, -1);
706
+ continue;
707
+ }
708
+ line += physicalLine;
709
+ break;
710
+ }
711
+ if (heredoc.stripTabs)
712
+ line = line.replace(/^\t+/, "");
713
+ if (line === heredoc.delimiter)
714
+ return { content: body, end: i };
715
+ body += line + (newline ? `
716
+ ` : "");
717
+ }
718
+ throw incompleteHeredoc();
719
+ }
514
720
  function tokenizeShell(command) {
721
+ return tokenizeShellInput(command).tokens;
722
+ }
723
+ function tokenizeShellInput(command, start = 0, delimiterOnly = false, nesting = 0) {
515
724
  const tokens = [];
516
725
  const pendingHeredocs = [];
517
726
  let pendingDelimiter;
518
- let i = 0;
727
+ let i = start;
519
728
  while (i < command.length) {
520
729
  const character = command[i];
521
730
  if (character === undefined)
@@ -536,56 +745,75 @@ function tokenizeShell(command) {
536
745
  continue;
537
746
  }
538
747
  const twoCharacters = command.slice(i, i + 2);
748
+ let standaloneBrace = false;
749
+ if (delimiterOnly && pendingDelimiter !== undefined && (isWordSeparator(character) || character === "<" || character === ">")) {
750
+ throw incompleteHeredoc();
751
+ }
752
+ if (character === "{" || character === "}") {
753
+ let commandPosition = true;
754
+ for (let index = tokens.length - 1;index >= 0; index--) {
755
+ const token = tokens[index];
756
+ if (token.type === "operator")
757
+ break;
758
+ if (token.type === "word") {
759
+ const precedingWord = tokens[index - 1]?.type === "word" ? tokens[index - 1]?.value : undefined;
760
+ if (index === tokens.length - 1 && token.value === "coproc")
761
+ continue;
762
+ if (token.value === "--" && (precedingWord === "time" || precedingWord === "-p" && tokens[index - 2]?.type === "word" && tokens[index - 2]?.value === "time"))
763
+ continue;
764
+ if (index === tokens.length - 1 && (precedingWord === "function" || precedingWord === "coproc") || precedingWord === "time" && token.value === "-p") {
765
+ index--;
766
+ continue;
767
+ }
768
+ }
769
+ if (token.type !== "word" || !commandPrefixes.has(token.value)) {
770
+ commandPosition = false;
771
+ break;
772
+ }
773
+ }
774
+ let braceEnd = i + 1;
775
+ while (command[braceEnd] === "\\" && command[braceEnd + 1] === `
776
+ `)
777
+ braceEnd += 2;
778
+ standaloneBrace = commandPosition && (command[braceEnd] === undefined || isWordSeparator(command[braceEnd]) || command[braceEnd] === "<" || command[braceEnd] === ">");
779
+ }
539
780
  if (twoCharacters === "&&" || twoCharacters === "||" || twoCharacters === "|&" || twoCharacters === ";;") {
540
781
  tokens.push({ type: "operator", value: twoCharacters });
541
782
  i += 2;
542
783
  continue;
543
784
  }
544
- if (character === "|" || character === ";" || character === "&" || character === `
545
- ` || character === "(" || character === ")" || character === "{" || character === "}") {
785
+ if (character === "|" || character === ";" || character === "&" && command[i + 1] !== ">" || character === `
786
+ ` || character === "(" || character === ")" || standaloneBrace) {
546
787
  tokens.push({ type: "operator", value: character });
547
788
  i++;
548
789
  if (character === `
549
790
  ` && pendingHeredocs.length > 0) {
550
791
  for (const heredoc of pendingHeredocs) {
551
- const bodyStart = i;
552
- let complete = false;
553
- while (i < command.length) {
554
- const lineEnd = command.indexOf(`
555
- `, i);
556
- const end = lineEnd < 0 ? command.length : lineEnd;
557
- const line = command.slice(i, end);
558
- i = lineEnd < 0 ? end : end + 1;
559
- if (line === heredoc.delimiter) {
560
- complete = true;
561
- const body = command.slice(bodyStart, i - (line.length + (lineEnd < 0 ? 0 : 1)));
562
- tokens[heredoc.index] = {
563
- ...tokens[heredoc.index],
564
- heredoc: { body, quoted: heredoc.quoted },
565
- substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body)
566
- };
567
- break;
568
- }
569
- }
570
- if (!complete) {
571
- throw new Error("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.");
572
- }
792
+ const body = consumeHeredoc(command, i, heredoc);
793
+ i = body.end;
794
+ tokens[heredoc.index] = {
795
+ ...tokens[heredoc.index],
796
+ heredoc: { body: body.content, quoted: heredoc.quoted },
797
+ substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body.content)
798
+ };
573
799
  }
574
800
  pendingHeredocs.length = 0;
575
801
  }
576
802
  continue;
577
803
  }
578
- const redirectMatch = command.slice(i).match(/^(\d+)?(<<<|>>|<<|>&|<&|>\||>|<)(?:-|\d+)?/);
804
+ const redirectMatch = command.slice(i).match(/^(?:\d+)?(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)|^&>>?/);
579
805
  if (redirectMatch !== null && redirectMatch[0] !== undefined) {
580
806
  tokens.push({ type: "redirect", value: redirectMatch[0] });
581
- if (/^\d*<<$/.test(redirectMatch[0]))
807
+ if (/^\d*<<-?$/.test(redirectMatch[0]))
582
808
  pendingDelimiter = tokens.length - 1;
583
809
  i += redirectMatch[0].length;
584
810
  continue;
585
811
  }
586
812
  let value = "";
813
+ const wordBytes = [];
587
814
  let quoted = false;
588
- let unsupportedDelimiter = false;
815
+ let unsupportedDelimiter;
816
+ let expansion = false;
589
817
  const substitutions = [];
590
818
  while (i < command.length) {
591
819
  const current = command[i];
@@ -607,55 +835,65 @@ function tokenizeShell(command) {
607
835
  }
608
836
  continue;
609
837
  }
838
+ if (current === "$") {
839
+ let quoteStart = i + 1;
840
+ while (command[quoteStart] === "\\" && command[quoteStart + 1] === `
841
+ `)
842
+ quoteStart += 2;
843
+ if (command[quoteStart] === '"')
844
+ unsupportedDelimiter = "locale-quoted";
845
+ else if (command[quoteStart] === "'")
846
+ unsupportedDelimiter = "ANSI-C quoted";
847
+ }
610
848
  if (current === "$" && command[i + 1] === "'") {
849
+ const quoteStart = i;
850
+ wordBytes.push(...Buffer.from(value));
851
+ value = "";
611
852
  quoted = true;
612
- unsupportedDelimiter = true;
853
+ unsupportedDelimiter = "ANSI-C quoted";
613
854
  i += 2;
855
+ const bytes = [];
856
+ let complete = false;
614
857
  while (i < command.length) {
615
858
  const ansiCharacter = command[i];
616
859
  if (ansiCharacter === undefined)
617
860
  break;
618
861
  if (ansiCharacter === "'") {
619
862
  i++;
863
+ complete = true;
620
864
  break;
621
865
  }
622
866
  if (ansiCharacter === "\\" && i + 1 < command.length) {
623
- const escaped = command[i + 1];
624
- if (escaped === "n")
625
- value += `
626
- `;
627
- else if (escaped === "t")
628
- value += "\t";
629
- else if (escaped === "r")
630
- value += "\r";
631
- else if (escaped === "\\")
632
- value += "\\";
633
- else if (escaped === "'")
634
- value += "'";
635
- else if (escaped === '"')
636
- value += '"';
637
- else
638
- value += escaped;
639
- i += 2;
867
+ const escaped = ansiEscape(command, i);
868
+ bytes.push(...escaped.byte === undefined ? Buffer.from(escaped.content) : [escaped.byte]);
869
+ i = escaped.end;
640
870
  } else {
641
- value += ansiCharacter;
642
- i++;
871
+ const literal = String.fromCodePoint(command.codePointAt(i));
872
+ bytes.push(...Buffer.from(literal));
873
+ i += literal.length;
643
874
  }
644
875
  }
876
+ if (!complete)
877
+ throw new Error(`Unterminated ANSI-C quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
878
+ const nul = bytes.indexOf(0);
879
+ wordBytes.push(...nul < 0 ? bytes : bytes.slice(0, nul));
645
880
  continue;
646
881
  }
647
882
  if (current === "'") {
883
+ const quoteStart = i;
648
884
  quoted = true;
649
885
  i++;
650
886
  while (i < command.length && command[i] !== "'") {
651
887
  value += command[i];
652
888
  i++;
653
889
  }
654
- if (command[i] === "'")
655
- i++;
890
+ if (command[i] !== "'")
891
+ throw new Error(`Unterminated single quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
892
+ i++;
656
893
  continue;
657
894
  }
658
895
  if (current === '"') {
896
+ const quoteStart = i;
659
897
  quoted = true;
660
898
  i++;
661
899
  while (i < command.length && command[i] !== '"') {
@@ -675,42 +913,73 @@ function tokenizeShell(command) {
675
913
  i += 2;
676
914
  }
677
915
  } else if (quotedCharacter === "$" && command[i + 1] === "(") {
678
- const substitution = consumeCommandSubstitution(command, i);
916
+ const substitution = consumeCommandSubstitution(command, i, nesting);
679
917
  value += command.slice(i, substitution.end);
680
918
  substitutions.push(substitution.content);
919
+ expansion = true;
920
+ i = substitution.end;
921
+ } else if (quotedCharacter === "$" && command[i + 1] === "{") {
922
+ const end = consumeQuotedParameter(command, i);
923
+ value += command.slice(i, end);
924
+ expansion = true;
925
+ i = end;
926
+ } else if (quotedCharacter === "`") {
927
+ const substitution = consumeBackticks(command, i, true);
928
+ value += command.slice(i, substitution.end);
929
+ substitutions.push(substitution.content);
930
+ expansion = true;
681
931
  i = substitution.end;
682
932
  } else {
933
+ if (quotedCharacter === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? ""))
934
+ expansion = true;
683
935
  value += quotedCharacter;
684
936
  i++;
685
937
  }
686
938
  }
687
- if (command[i] === '"')
688
- i++;
939
+ if (command[i] !== '"')
940
+ throw new Error(`Unterminated double quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
941
+ i++;
689
942
  continue;
690
943
  }
691
944
  if (current === "$" && command[i + 1] === "(") {
692
- const substitution = consumeCommandSubstitution(command, i);
945
+ const substitution = consumeCommandSubstitution(command, i, nesting);
693
946
  value += command.slice(i, substitution.end);
694
947
  substitutions.push(substitution.content);
948
+ expansion = true;
695
949
  i = substitution.end;
696
950
  continue;
697
951
  }
698
- const nextRedirect = command.slice(i).match(/^(\d+)?(<<<|>>|<<|>&|<&|>\||>|<)(?:-|\d+)?/);
952
+ if (current === "`") {
953
+ const substitution = consumeBackticks(command, i);
954
+ value += command.slice(i, substitution.end);
955
+ substitutions.push(substitution.content);
956
+ expansion = true;
957
+ i = substitution.end;
958
+ continue;
959
+ }
960
+ if (current === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? ""))
961
+ expansion = true;
962
+ const nextRedirect = command.slice(i).match(/^(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)/);
699
963
  if (nextRedirect !== null)
700
964
  break;
701
965
  value += current;
702
966
  i++;
703
967
  }
704
- pushWord(tokens, value, substitutions);
968
+ if (wordBytes.length > 0)
969
+ value = Buffer.from([...wordBytes, ...Buffer.from(value)]).toString("utf8");
970
+ pushWord(tokens, value, substitutions, expansion);
705
971
  if (pendingDelimiter !== undefined) {
706
- if (unsupportedDelimiter) {
707
- throw new Error("Cannot validate an ANSI-C quoted heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.");
972
+ if (unsupportedDelimiter !== undefined) {
973
+ throw new Error(`Cannot validate this ${unsupportedDelimiter} heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.`);
708
974
  }
709
- pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted });
975
+ const delimiter = { delimiter: value, quoted, stripTabs: tokens[pendingDelimiter]?.value.endsWith("-") === true };
976
+ if (delimiterOnly)
977
+ return { tokens, end: i, delimiter };
978
+ pendingHeredocs.push({ index: pendingDelimiter, ...delimiter });
710
979
  pendingDelimiter = undefined;
711
980
  }
712
981
  }
713
- return tokens;
982
+ return { tokens, end: i };
714
983
  }
715
984
  function splitSimpleCommands(tokens) {
716
985
  const commands = [];
@@ -742,14 +1011,14 @@ function extractCommandWords(tokens) {
742
1011
  if (token === undefined)
743
1012
  break;
744
1013
  if (token.type === "redirect") {
745
- if (!token.value.includes("&") && tokens[i + 1]?.type === "word")
1014
+ if (tokens[i + 1]?.type === "word")
746
1015
  i += 2;
747
1016
  else
748
1017
  i++;
749
1018
  continue;
750
1019
  }
751
1020
  if (token.type === "word") {
752
- words.push(token.value);
1021
+ words.push(token);
753
1022
  }
754
1023
  i++;
755
1024
  }
@@ -830,7 +1099,7 @@ function findCommandStart(words) {
830
1099
  }
831
1100
  return index;
832
1101
  }
833
- function extractInvocation(words, commandStart) {
1102
+ function extractInvocation(words, commandStart, wordTokens) {
834
1103
  let wordIndex = commandStart;
835
1104
  const executable = words[wordIndex];
836
1105
  if (executable === undefined || executable !== "git" && !executable.endsWith("/git"))
@@ -883,6 +1152,8 @@ function extractInvocation(words, commandStart) {
883
1152
  let hasNoEdit = false;
884
1153
  let isFixup = false;
885
1154
  let isHelp = false;
1155
+ let messageExpansion = false;
1156
+ let hasTrailer = false;
886
1157
  const collectMessage = (word) => {
887
1158
  if (word === undefined)
888
1159
  return;
@@ -915,8 +1186,10 @@ function extractInvocation(words, commandStart) {
915
1186
  hasSignoffFlag = false;
916
1187
  } else if (argument === "-m" || argument === "--message") {
917
1188
  index++;
1189
+ messageExpansion ||= wordTokens[index]?.expansion === true;
918
1190
  collectMessage(words[index]);
919
1191
  } else if (argument.startsWith("--message=")) {
1192
+ messageExpansion ||= wordTokens[index]?.expansion === true;
920
1193
  collectMessage(argument.slice("--message=".length));
921
1194
  } else if (argument === "-F" || argument === "--file") {
922
1195
  index++;
@@ -927,6 +1200,10 @@ function extractInvocation(words, commandStart) {
927
1200
  isFixup = true;
928
1201
  if (equalsIndex < 0)
929
1202
  index++;
1203
+ } else if (longOptionName === "--trailer") {
1204
+ hasTrailer = true;
1205
+ if (equalsIndex < 0)
1206
+ index++;
930
1207
  } else if (commitLongOptionsWithArg.has(longOptionName)) {
931
1208
  if (equalsIndex < 0)
932
1209
  index++;
@@ -942,9 +1219,10 @@ function extractInvocation(words, commandStart) {
942
1219
  } else if (option === "m" || option === "F") {
943
1220
  const attached = argument.slice(characterIndex + 1);
944
1221
  const input = attached.length > 0 ? attached : words[++index];
945
- if (option === "m")
1222
+ if (option === "m") {
1223
+ messageExpansion ||= wordTokens[index]?.expansion === true;
946
1224
  collectMessage(input);
947
- else
1225
+ } else
948
1226
  collectFile(input);
949
1227
  break;
950
1228
  } else if (option === "S") {
@@ -967,18 +1245,55 @@ function extractInvocation(words, commandStart) {
967
1245
  hasNoEdit,
968
1246
  isFixup,
969
1247
  isHelp,
970
- targetError
1248
+ targetError,
1249
+ messageExpansion,
1250
+ hasTrailer
971
1251
  };
972
1252
  }
973
- function extractGitCommits(command, inheritedDirectoryChange = false) {
1253
+ function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0) {
1254
+ if (depth > 12 || command.length > 262144)
1255
+ throw new Error("Shell parsing limit exceeded. Run git commit directly.");
974
1256
  const tokens = tokenizeShell(command);
975
1257
  const invocations = [];
976
1258
  let changedDirectory = inheritedDirectoryChange;
977
1259
  for (const simple of splitSimpleCommands(tokens)) {
978
1260
  const commandTokens = simple.tokens;
979
- const words = extractCommandWords(commandTokens);
1261
+ const wordTokens = extractCommandWords(commandTokens);
1262
+ const words = wordTokens.map((token) => token.value);
980
1263
  const commandStart = findCommandStart(words);
981
- const invocation = extractInvocation(words, commandStart);
1264
+ const invocation = extractInvocation(words, commandStart, wordTokens);
1265
+ if (/^(?:.*\/)?(?:bash|sh|zsh)$/.test(words[commandStart] ?? "")) {
1266
+ let bodyIndex = commandStart + 1;
1267
+ let executeString = false;
1268
+ while (bodyIndex < words.length) {
1269
+ const option = words[bodyIndex];
1270
+ if (option === "--") {
1271
+ bodyIndex++;
1272
+ break;
1273
+ }
1274
+ if (!option.startsWith("-") && !option.startsWith("+"))
1275
+ break;
1276
+ if (/^-[a-zA-Z]*c[a-zA-Z]*$/.test(option))
1277
+ executeString = true;
1278
+ const shortOptions = /^[+-][a-zA-Z]+$/.test(option);
1279
+ if (shortOptions && /[oO]/.test(option) && !/[oO]$/.test(option)) {
1280
+ throw new Error("Cannot parse shell options reliably. Run git commit directly.");
1281
+ }
1282
+ const next = words[bodyIndex + 1];
1283
+ const optionName = next !== undefined && !/^[+-]/.test(next);
1284
+ bodyIndex += shortOptions && /[oO]$/.test(option) && optionName || ["--rcfile", "--init-file"].includes(option) ? 2 : 1;
1285
+ }
1286
+ if (executeString) {
1287
+ const body = wordTokens[bodyIndex];
1288
+ if (body === undefined || body.expansion)
1289
+ throw new Error("Cannot parse shell -c body reliably. Run git commit directly.");
1290
+ if (/^(?:.*\/)?sh$/.test(words[commandStart] ?? "") && body.value.includes("$'")) {
1291
+ throw new Error("Cannot parse $' quoting portably in sh -c. Use a literal bash -c or zsh -c body, or run git commit directly.");
1292
+ }
1293
+ const wrapperChange = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word));
1294
+ invocations.push(...extractGitCommits(body.value, changedDirectory || wrapperChange, depth + 1));
1295
+ }
1296
+ }
982
1297
  if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment))
983
1298
  changedDirectory = true;
984
1299
  if (invocation !== undefined) {
@@ -1012,14 +1327,13 @@ function extractGitCommits(command, inheritedDirectoryChange = false) {
1012
1327
  }
1013
1328
  for (const token of tokens) {
1014
1329
  for (const substitution of token.substitutions ?? []) {
1015
- invocations.push(...extractGitCommits(substitution, changedDirectory));
1330
+ invocations.push(...extractGitCommits(substitution, changedDirectory, depth + 1));
1016
1331
  }
1017
1332
  }
1018
1333
  return invocations;
1019
1334
  }
1020
1335
 
1021
1336
  // src/validator.ts
1022
- var scopePattern = /^([a-zA-Z0-9_\-./]+(?:\([a-zA-Z0-9_\-./]+\))?):\s+(.+)$/;
1023
1337
  var signoffPattern = /^\s*Signed-off-by:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/i;
1024
1338
  function hasSignoffTrailer(lines) {
1025
1339
  const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
@@ -1034,43 +1348,45 @@ function validateAllowedScope(rawScope, allowedScopes) {
1034
1348
  return;
1035
1349
  return `Scope "${rawScope}" is not in the allowed scopes list. Allowed scopes: ${allowedScopes.join(", ")}.`;
1036
1350
  }
1037
- function createCommitGuardError(violations, originalCommand) {
1351
+ function createCommitGuardError(violations, config) {
1038
1352
  const header = "[commit-guard] Git commit rejected: commit message format rules violated.";
1039
1353
  const violationText = violations.map((v, i) => `${i + 1}. ${v}`).join(`
1040
1354
 
1041
1355
  `);
1042
- const examples = [
1043
- "Example of a correctly formatted git commit:",
1044
- ' git commit -s -m "kernel: add support for foo"',
1045
- ' git commit -s -m "releasetools: fix ota generation" -m "Detailed explanation of why this fix is needed."',
1046
- ' git commit -m "feat(parser): add subshell support" -m "Signed-off-by: Developer <dev@example.com>"'
1047
- ].join(`
1048
- `);
1356
+ const scope = config.allowedScopes?.[0] ?? "scope";
1357
+ const examples = `Signoff ${config.enforceSignoff ? "required: captured commit.gpgsign=true. Keep -s." : "not required: captured commit.gpgsign=false|unset."}
1358
+ ` + `Example:
1359
+ git commit${config.enforceSignoff ? " -s" : ""} -m $'${scope}: Subject\\n\\nBody line one.\\nBody line two.'`;
1049
1360
  return new Error(`${header}
1050
1361
 
1051
1362
  Violations:
1052
1363
  ${violationText}
1053
1364
 
1054
- ${examples}
1055
-
1056
- Command attempted:
1057
- ${originalCommand}`);
1365
+ ${examples}`);
1058
1366
  }
1059
- function validateGitCommits(invocations, config, originalCommand) {
1367
+ function validateGitCommits(invocations, config, _originalCommand) {
1060
1368
  const allViolations = [];
1061
1369
  for (const invocation of invocations) {
1062
1370
  if (invocation.isHelp) {
1063
1371
  continue;
1064
1372
  }
1373
+ if (invocation.messageExpansion) {
1374
+ allViolations.push("Cannot validate a message containing shell expansion. Supply the final message literally.");
1375
+ continue;
1376
+ }
1377
+ if (invocation.hasTrailer) {
1378
+ allViolations.push("Cannot validate --trailer. Put the trailer in the literal message body or use -s.");
1379
+ continue;
1380
+ }
1065
1381
  const collectedMessages = [...invocation.messages];
1066
1382
  const filePath = invocation.filePaths.at(-1);
1067
1383
  if (filePath !== undefined) {
1068
1384
  if (filePath !== "-" || invocation.filePaths.length !== 1) {
1069
- allViolations.push(`Cannot validate a commit message from file "${filePath}" before shell permissions run. Use an inline message, for example: git commit -s -m "kernel: add support for foo".`);
1385
+ allViolations.push("Cannot validate a commit message from -F/--file before permission approval. Use an inline $'...' message or one quoted stdin heredoc.");
1070
1386
  continue;
1071
1387
  }
1072
1388
  if (invocation.stdinError !== undefined || invocation.stdinMessage === undefined || collectedMessages.length > 0) {
1073
- allViolations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} Use one quoted heredoc directly on git commit -s -F - <<'EOF', or use -m "kernel: add support for foo".`);
1389
+ allViolations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} Use one quoted stdin heredoc or an inline $'...' message.`);
1074
1390
  continue;
1075
1391
  }
1076
1392
  collectedMessages.push(invocation.stdinMessage);
@@ -1113,7 +1429,7 @@ function validateGitCommits(invocations, config, originalCommand) {
1113
1429
  } else if (/^[^:]+:\s*$/.test(effectiveSubject)) {
1114
1430
  allViolations.push(`Subject text after colon is empty in "${subjectLine}". Expected format: "<scope>: <subject>".`);
1115
1431
  } else {
1116
- allViolations.push(`Missing scope in subject line "${subjectLine}". First line must follow "<scope>: <subject>" format (e.g., "kernel: add support for foo" or "feat(parser): add subshell support").`);
1432
+ allViolations.push(`Missing scope in subject line "${subjectLine}". First line must follow "<scope>: <subject>" format.`);
1117
1433
  }
1118
1434
  }
1119
1435
  }
@@ -1129,7 +1445,8 @@ function validateGitCommits(invocations, config, originalCommand) {
1129
1445
  const details = overlongLines.map((l) => ` - Line ${l.lineNumber} (${l.length} chars, max ${config.maxLineLength}): "${l.text}"`).join(`
1130
1446
  `);
1131
1447
  allViolations.push(`Commit message exceeds maximum line length of ${config.maxLineLength} characters:
1132
- ${details}`);
1448
+ ${details}
1449
+ Each -m becomes one paragraph line. Wrap with real newlines inside $'...'; "\\n" inside double quotes stays literal.`);
1133
1450
  }
1134
1451
  }
1135
1452
  if (config.enforceSignoff) {
@@ -1140,7 +1457,7 @@ ${details}`);
1140
1457
  }
1141
1458
  }
1142
1459
  if (allViolations.length > 0) {
1143
- throw createCommitGuardError(allViolations, originalCommand);
1460
+ throw createCommitGuardError(allViolations.slice(0, 10).map((text) => text.slice(0, 2048)), config);
1144
1461
  }
1145
1462
  }
1146
1463
 
@@ -1155,16 +1472,48 @@ var plugin = Plugin.define({
1155
1472
  const pending = new Map;
1156
1473
  const preparing = new Set;
1157
1474
  const lastSessionWorkdir = new Map;
1475
+ const failures = new Map;
1476
+ const rememberFailure = (scope, reason) => {
1477
+ failures.delete(scope);
1478
+ failures.set(scope, `The previous capture failed: ${reason.slice(0, 256)}. `);
1479
+ if (failures.size > 128)
1480
+ failures.delete(failures.keys().next().value);
1481
+ };
1482
+ const sweep = () => Effect2.gen(function* () {
1483
+ for (const attempt of [...pending.values()].slice(0, 32)) {
1484
+ pending.delete(attempt.scope);
1485
+ if (attempt.claimed === undefined && Date.now() >= attempt.expires) {
1486
+ cleanup(attempt);
1487
+ yield* recordState(ctx, attempt, "expired");
1488
+ yield* invalidateOwned(ctx, attempt);
1489
+ } else
1490
+ pending.set(attempt.scope, attempt);
1491
+ }
1492
+ });
1158
1493
  yield* Effect2.addFinalizer(() => Effect2.gen(function* () {
1159
1494
  for (const attempt of pending.values()) {
1160
1495
  cleanup(attempt);
1161
- yield* invalidate(ctx, attempt.scope);
1496
+ yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication");
1497
+ yield* invalidateOwned(ctx, attempt);
1162
1498
  }
1163
1499
  pending.clear();
1164
1500
  }));
1165
1501
  yield* ctx.tool.transform((editor) => editor.add({
1166
1502
  name: "commit_context",
1167
- description: "Prepare a private, permission-checked Git baseline. Run the returned shell command in the foreground, then call this tool again. Specify workdir if the Git repository is in a subdirectory or differs from the project directory. Set refresh to replace a frozen baseline.",
1503
+ description: String.raw`Prepare a Git baseline. Run the returned command unchanged in the foreground; require "Frozen commit baseline".
1504
+ Call before your first commit in each session and checkout.
1505
+ Set workdir when targeting another repository.
1506
+ Run the returned command immediately, unchanged, with the indicated workdir and background:false.
1507
+ Do not wrap it or chain another command onto it.
1508
+ Commit only after the shell result or this tool reports "Frozen commit baseline".
1509
+ RECEIPT_OK alone is insufficient.
1510
+ The shell result includes commit rules; a second call is optional.
1511
+ Repeat an explicit workdir when checking that checkout.
1512
+ Set refresh:true after switching branches, changing signing settings, or changing commit instructions.
1513
+ Use literal message text and real body newlines.
1514
+ Example: git commit -m $'scope: Subject\n\nBody line one.\nBody line two.'
1515
+ Replace scope and follow the returned line-length and signoff rules.
1516
+ Add -s only when the returned policy or repository instructions require it.`,
1168
1517
  input: {
1169
1518
  type: "object",
1170
1519
  properties: {
@@ -1175,6 +1524,7 @@ var plugin = Plugin.define({
1175
1524
  additionalProperties: false
1176
1525
  },
1177
1526
  execute: (input, toolContext) => Effect2.gen(function* () {
1527
+ yield* sweep();
1178
1528
  if (ctx.location.workspaceID !== undefined)
1179
1529
  return { content: "Commit context capture is unavailable for remote workspaces." };
1180
1530
  const session = yield* ctx.session.get({ sessionID: toolContext.sessionID });
@@ -1198,41 +1548,34 @@ var plugin = Plugin.define({
1198
1548
  lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir);
1199
1549
  const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir);
1200
1550
  if (preparing.has(scope))
1201
- return { content: "A commit context capture is preparing for this session and checkout. Call commit_context again." };
1551
+ return { content: "A commit context capture is preparing for this session and checkout. Wait for its command, then follow its instructions." };
1202
1552
  preparing.add(scope);
1203
1553
  return yield* Effect2.gen(function* () {
1204
1554
  const previous = pending.get(scope);
1205
1555
  if (previous !== undefined) {
1206
- if (Date.now() < previous.expires && request.refresh !== true) {
1207
- return { content: `Run this shell command with workdir ${previous.workdir} and background:false, then call commit_context again:
1208
- ${previous.command}` };
1556
+ if (previous.claimed !== undefined && request.refresh !== true) {
1557
+ return { content: 'Capture claimed; permission approval or execution is pending. Wait for its foreground shell result. Commit after it reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing. RECEIPT_OK confirms only that the artifact was written, not that the baseline was published.' };
1558
+ }
1559
+ if (request.refresh !== true) {
1560
+ return { content: captureInstructions(previous, "Capture still pending and unclaimed. ") };
1209
1561
  }
1210
1562
  pending.delete(scope);
1211
1563
  cleanup(previous);
1212
- yield* invalidate(ctx, scope);
1564
+ yield* recordState(ctx, previous, "failed", "capture replaced by refresh");
1565
+ yield* invalidateOwned(ctx, previous);
1213
1566
  }
1214
1567
  if (request.refresh !== true) {
1215
1568
  const baseline = yield* load(ctx, scope);
1216
- if (baseline !== undefined && (baseline.workdir === targetWorkdir || baseline.directory === targetWorkdir) && baseline.gpgsign !== "error" && baseline.signingkey !== "error") {
1217
- const observed = [...new Set(baseline.messages.map((message) => message.split(`
1218
- `)[0]?.match(/^([a-zA-Z0-9_./-]{1,40}): /)?.[1]).filter((value) => value !== undefined))].slice(0, 3);
1219
- const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
1220
- ` : "";
1221
- const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." : `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`;
1222
- return { content: `Frozen commit baseline for ${targetWorkdir}.
1223
- ` + `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.
1224
- ` + `${scopes}
1225
- ${examples}` + `Effective commit.gpgsign: ${baseline.gpgsign}. Signoff ${baseline.gpgsign === "true" ? "required" : "not required"}; ` + `signoff is not a cryptographic signature. user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}.
1226
- ` + "Set refresh:true after a branch switch, changed signing settings, or changed commit instructions." };
1569
+ if (baseline !== undefined && baseline.directory === findGitRoot(targetWorkdir)) {
1570
+ return { content: baselineGuidance(baseline, config) };
1227
1571
  }
1228
1572
  }
1229
- if (request.refresh === true)
1230
- yield* invalidate(ctx, scope);
1231
- const count = yield* counter(ctx, scope);
1573
+ const count = yield* invalidate(ctx, scope);
1232
1574
  const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, targetWorkdir));
1233
1575
  pending.set(scope, attempt);
1234
- return { content: `Run this shell command with workdir ${targetWorkdir} and background:false, then call commit_context again:
1235
- ${attempt.command}` };
1576
+ const status = failures.get(scope) ?? (yield* captureStatus(ctx, scope));
1577
+ yield* recordState(ctx, attempt, "prepared");
1578
+ return { content: captureInstructions(attempt, status) };
1236
1579
  }).pipe(Effect2.ensuring(Effect2.sync(() => {
1237
1580
  preparing.delete(scope);
1238
1581
  })));
@@ -1240,14 +1583,8 @@ ${attempt.command}` };
1240
1583
  message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout."
1241
1584
  })))
1242
1585
  }));
1243
- yield* ctx.shell.hook("create.before", (event) => Effect2.sync(() => {
1244
- for (const attempt of pending.values()) {
1245
- if (attempt.claimed !== undefined && event.command === attempt.command && event.cwd === attempt.workdir) {
1246
- attempt.expires = Date.now() + captureTimeout;
1247
- }
1248
- }
1249
- }));
1250
1586
  yield* ctx.tool.hook("execute.before", (event) => Effect2.gen(function* () {
1587
+ yield* sweep();
1251
1588
  const captureSession = event.tool === "shell" || event.tool === "bash" ? yield* ctx.session.get({ sessionID: event.sessionID }) : undefined;
1252
1589
  const captureSessionDirectory = captureSession?.location.directory ?? ctx.location.directory;
1253
1590
  const parsed = yield* Effect2.try({
@@ -1272,21 +1609,23 @@ ${attempt.command}` };
1272
1609
  throw new Error("[commit-guard] Capture must use its exact foreground shell command in the original session and workdir. Call commit_context to refresh.");
1273
1610
  }
1274
1611
  attempt.claimed = { messageID: event.messageID, id: event.id };
1275
- attempt.expires = Date.now() + captureTimeout;
1276
1612
  return;
1277
1613
  }
1278
1614
  const invocations = extractGitCommits(command);
1279
1615
  if (invocations.length === 0) {
1280
1616
  return;
1281
1617
  }
1282
- validateGitCommits(invocations, { ...config, enforceSignoff: false }, command);
1283
1618
  return { invocations, command, rawInput };
1284
1619
  },
1285
1620
  catch: (error) => new Tool.Error({
1286
1621
  message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
1287
1622
  })
1288
1623
  });
1289
- if (parsed === undefined)
1624
+ for (const attempt of pending.values()) {
1625
+ if (attempt.claimed?.messageID === event.messageID && attempt.claimed.id === event.id && attempt.sessionID === event.sessionID && attempt.agent === event.agent)
1626
+ yield* recordState(ctx, attempt, "claimed");
1627
+ }
1628
+ if (parsed === undefined || parsed.invocations.every((invocation) => invocation.isHelp))
1290
1629
  return;
1291
1630
  if (ctx.location.workspaceID !== undefined)
1292
1631
  return yield* Effect2.fail(new Tool.Error({
@@ -1302,21 +1641,21 @@ ${attempt.command}` };
1302
1641
  const rawWorkdir = parsed.rawInput["workdir"];
1303
1642
  const effectiveWorkdir = yield* Effect2.try(() => realpathSync2(isJSONString(rawWorkdir) ? resolve2(sessionDirectory, rawWorkdir) : sessionDirectory));
1304
1643
  const targetGitRoot = findGitRoot(effectiveWorkdir);
1305
- let scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir);
1306
- let baseline = yield* load(ctx, scope);
1307
- if (baseline === undefined && targetGitRoot !== undefined && targetGitRoot !== effectiveWorkdir) {
1308
- scope = scopeFor(ctx, event.sessionID, config, targetGitRoot);
1309
- baseline = yield* load(ctx, scope);
1310
- }
1644
+ const scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir);
1645
+ const baseline = yield* load(ctx, scope);
1311
1646
  const expectedDir = targetGitRoot ?? effectiveWorkdir;
1312
- const baselineValid = baseline !== undefined && targetGitRoot !== undefined && baseline.directory === targetGitRoot && (baseline.workdir === effectiveWorkdir || baseline.directory === expectedDir) && baseline.gpgsign !== "error" && baseline.signingkey !== "error";
1647
+ const baselineValid = baseline !== undefined && targetGitRoot !== undefined && baseline.directory === targetGitRoot && baseline.directory === expectedDir;
1313
1648
  if (!baselineValid || baseline === undefined) {
1314
1649
  const relWorkdir = relative2(sessionDirectory, expectedDir);
1315
- const workdirHint = relWorkdir.length > 0 && !relWorkdir.startsWith("..") ? `{ workdir: "${relWorkdir}" }` : "";
1650
+ const workdirHint = JSON.stringify(relWorkdir.length > 0 ? relWorkdir : ".");
1316
1651
  return yield* Effect2.fail(new Tool.Error({
1317
- message: `[commit-guard] No valid signing baseline for this checkout. Call commit_context(${workdirHint}), run its authorized foreground shell command, then call commit_context again before committing.`
1652
+ message: `[commit-guard] No published baseline for ${expectedDir}. Call commit_context({ workdir: ${workdirHint} }), then run the returned command immediately, unchanged, in the foreground with that workdir and background:false. Do not wrap it or chain another command onto it. Commit after the shell result reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing. RECEIPT_OK alone is insufficient.`
1318
1653
  }));
1319
1654
  }
1655
+ if (baseline.gpgsign === "error" || baseline.signingkey === "error")
1656
+ return yield* Effect2.fail(new Tool.Error({
1657
+ message: signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")
1658
+ }));
1320
1659
  yield* Effect2.try({
1321
1660
  try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
1322
1661
  catch: (error) => new Tool.Error({
@@ -1333,10 +1672,17 @@ ${attempt.command}` };
1333
1672
  if (attempt === undefined)
1334
1673
  return;
1335
1674
  let published = false;
1675
+ let captured;
1676
+ let reason = "capture import or storage failed";
1336
1677
  yield* Effect2.gen(function* () {
1337
- if (event.status !== "completed" || Date.now() >= attempt.expires || (yield* counter(ctx, attempt.scope)) !== attempt.counter)
1678
+ reason = "shell result did not complete successfully";
1679
+ if (event.status !== "completed")
1680
+ return;
1681
+ reason = "capture was superseded by a refresh";
1682
+ if ((yield* counter(ctx, attempt.scope)) !== attempt.counter)
1338
1683
  return;
1339
1684
  const metadata = event.result.metadata;
1685
+ reason = "shell result lacks verified foreground completion metadata";
1340
1686
  if (!isRecord(metadata))
1341
1687
  return;
1342
1688
  if (metadata["status"] !== "completed" || metadata["exit"] !== 0 || metadata["truncated"] !== false || metadata["timeout"] !== undefined && metadata["timeout"] !== false || metadata["shellID"] !== undefined || Object.keys(metadata).some((key) => !["status", "exit", "truncated", "timeout"].includes(key)))
@@ -1344,23 +1690,77 @@ ${attempt.command}` };
1344
1690
  const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {
1345
1691
  return;
1346
1692
  });
1693
+ reason = "capture session or workspace no longer matches";
1347
1694
  if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID)
1348
1695
  return;
1696
+ reason = "private artifact is invalid or incomplete (END required)";
1349
1697
  const baseline = yield* Effect2.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") });
1350
1698
  if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined)
1351
1699
  return;
1700
+ reason = "capture storage failed or its counter changed";
1352
1701
  published = yield* publish(ctx, attempt, generation, baseline);
1702
+ if (published) {
1703
+ captured = baseline;
1704
+ failures.delete(attempt.scope);
1705
+ yield* recordState(ctx, attempt, "published");
1706
+ }
1353
1707
  }).pipe(Effect2.onExit(() => Effect2.gen(function* () {
1354
1708
  if (pending.get(attempt.scope) === attempt)
1355
1709
  pending.delete(attempt.scope);
1356
- if (!published)
1357
- yield* invalidate(ctx, attempt.scope);
1358
- yield* Effect2.sync(() => cleanup(attempt));
1359
- })), Effect2.catchCause(() => Effect2.void));
1710
+ if (!published) {
1711
+ rememberFailure(attempt.scope, reason);
1712
+ yield* recordState(ctx, attempt, "failed", reason).pipe(Effect2.catchCause(() => Effect2.void));
1713
+ yield* invalidateOwned(ctx, attempt);
1714
+ }
1715
+ }).pipe(Effect2.ensuring(Effect2.sync(() => cleanup(attempt))))), Effect2.catchCause(() => Effect2.void));
1716
+ const note = published && captured !== undefined ? baselineGuidance(captured, config) : `[commit-guard] This capture did not publish a usable baseline: ${reason.slice(0, 256)}.
1717
+ ` + `RECEIPT_OK alone does not authorize a commit.
1718
+ ` + "Call commit_context with the same workdir for status and next steps.";
1719
+ if (event.status === "error") {
1720
+ event.error = new Tool.Error({ message: `${event.error.message}
1721
+
1722
+ ${note}` });
1723
+ } else
1724
+ event.result = appendCaptureNote(event.result, note);
1360
1725
  }));
1361
1726
  })
1362
1727
  });
1363
1728
  var plugin_default = plugin;
1729
+ function captureInstructions(attempt, status) {
1730
+ return `${status}Run this shell command immediately, unchanged, in the foreground with workdir ${attempt.workdir} and background:false. ` + 'Do not wrap it or chain another command onto it. Commit after the shell result reports "Frozen commit baseline"; ' + "otherwise call commit_context again with the same workdir before committing. " + `RECEIPT_OK confirms only that the artifact was written, not that the baseline was published:
1731
+ ${attempt.command}`;
1732
+ }
1733
+ function baselineGuidance(baseline, config) {
1734
+ if (baseline.gpgsign === "error" || baseline.signingkey === "error")
1735
+ return signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey");
1736
+ const observed = [...new Set(baseline.messages.map((message) => message.split(`
1737
+ `)[0]?.match(/^([a-zA-Z0-9_./-]{1,40}): /)?.[1]).filter((value) => value !== undefined))].slice(0, 3);
1738
+ const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
1739
+ ` : "";
1740
+ const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." : `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`;
1741
+ const signoff = baseline.gpgsign === "true" ? "Add -s or --signoff." : "Signoff is not required; add it only if repository instructions require it.";
1742
+ return `[commit-guard] Frozen commit baseline for ${baseline.directory.slice(0, 4096)}.
1743
+ ` + `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.
1744
+ ` + `${scopes}
1745
+ ${examples}Effective commit.gpgsign: ${baseline.gpgsign}. ${signoff}
1746
+ ` + `user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}. Signoff is not a cryptographic signature.
1747
+ ` + `A second commit_context call is optional.
1748
+ ` + "Set refresh:true after a branch switch, changed signing settings, or changed commit instructions.";
1749
+ }
1750
+ function appendCaptureNote(result, note) {
1751
+ const content = Array.isArray(result.content) ? result.content : result.content === undefined ? [] : [{ type: "text", text: String(result.content) }];
1752
+ const output = result.output;
1753
+ const annotated = { ...result, content: [...content, { type: "text", text: note }] };
1754
+ if (isRecord(output) && isJSONString(output["output"])) {
1755
+ return { ...annotated, output: { ...output, output: `${output["output"]}
1756
+
1757
+ ${note}` } };
1758
+ }
1759
+ return annotated;
1760
+ }
1761
+ function signingError(setting) {
1762
+ return `[commit-guard] Git could not read ${setting} as valid. Repeating the capture will not fix it. Inspect with git config --show-origin --get-all ${setting}; fix the value without changing the intended signing policy, then call commit_context with refresh:true.`;
1763
+ }
1364
1764
  export {
1365
1765
  plugin_default as default
1366
1766
  };