opencode-commit-guard 1.0.5 → 1.0.6
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/README.md +28 -5
- package/dist/index.js +342 -120
- package/package.json +7 -7
- package/src/capture.ts +44 -3
- package/src/config.ts +5 -0
- package/src/plugin.ts +156 -54
- package/src/scope.ts +1 -0
- package/src/shell.ts +177 -41
- package/src/types.ts +3 -0
- package/src/validator.ts +23 -15
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
|
-
|
|
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
|
-
|
|
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,14 +441,15 @@ 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
448
|
` || character === ";" || character === "&" || 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;
|
|
@@ -432,7 +471,7 @@ function consumeCommandSubstitution(command, start) {
|
|
|
432
471
|
quote = undefined;
|
|
433
472
|
i++;
|
|
434
473
|
} else if (character === "$" && command[i + 1] === "(") {
|
|
435
|
-
i = consumeCommandSubstitution(command, i).end;
|
|
474
|
+
i = consumeCommandSubstitution(command, i, nesting + 1).end;
|
|
436
475
|
} else {
|
|
437
476
|
i++;
|
|
438
477
|
}
|
|
@@ -464,7 +503,7 @@ function consumeCommandSubstitution(command, start) {
|
|
|
464
503
|
continue;
|
|
465
504
|
}
|
|
466
505
|
if (character === "$" && command[i + 1] === "(") {
|
|
467
|
-
i = consumeCommandSubstitution(command, i).end;
|
|
506
|
+
i = consumeCommandSubstitution(command, i, nesting + 1).end;
|
|
468
507
|
atWordStart = false;
|
|
469
508
|
continue;
|
|
470
509
|
}
|
|
@@ -487,14 +526,46 @@ function consumeCommandSubstitution(command, start) {
|
|
|
487
526
|
atWordStart = false;
|
|
488
527
|
i++;
|
|
489
528
|
}
|
|
490
|
-
|
|
529
|
+
throw new Error("Cannot parse shell substitution reliably. Run git commit directly.");
|
|
530
|
+
}
|
|
531
|
+
function consumeBackticks(command, start) {
|
|
532
|
+
let content = "";
|
|
533
|
+
for (let i = start + 1;i < command.length; i++) {
|
|
534
|
+
if (command[i] === "`")
|
|
535
|
+
return { content, end: i + 1 };
|
|
536
|
+
if (command[i] === "\\" && ["$", "`", "\\"].includes(command[i + 1] ?? ""))
|
|
537
|
+
i++;
|
|
538
|
+
content += command[i];
|
|
539
|
+
}
|
|
540
|
+
throw new Error("Cannot parse backtick substitution reliably. Run git commit directly.");
|
|
491
541
|
}
|
|
492
|
-
function
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
542
|
+
function ansiEscape(command, start) {
|
|
543
|
+
const escaped = command[start + 1] ?? "";
|
|
544
|
+
const simple = new Map(Object.entries({ a: "\x07", b: "\b", e: "\x1B", E: "\x1B", f: "\f", n: `
|
|
545
|
+
`, r: "\r", t: "\t", v: "\v", "\\": "\\", "'": "'", '"': '"', "?": "?" }));
|
|
546
|
+
const literal = simple.get(escaped);
|
|
547
|
+
if (literal !== undefined)
|
|
548
|
+
return { content: literal, end: start + 2 };
|
|
549
|
+
if (escaped === "c" && command[start + 2] !== undefined) {
|
|
550
|
+
const character = command[start + 2];
|
|
551
|
+
return { content: String.fromCharCode(character === "?" ? 127 : character.toUpperCase().charCodeAt(0) & 31), end: start + 3 };
|
|
552
|
+
}
|
|
553
|
+
const count = escaped === "x" ? 2 : escaped === "u" ? 4 : escaped === "U" ? 8 : 0;
|
|
554
|
+
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];
|
|
555
|
+
if (digits !== undefined) {
|
|
556
|
+
const code = Number.parseInt(digits, count > 0 ? 16 : 8);
|
|
557
|
+
if (code > 1114111)
|
|
558
|
+
throw new Error("Cannot validate this ANSI-C escape. Supply the message literally.");
|
|
559
|
+
const end = start + (count > 0 ? 2 : 1) + digits.length;
|
|
560
|
+
if (count === 0 || escaped === "x")
|
|
561
|
+
return { content: "", byte: code & 255, end };
|
|
562
|
+
return { content: String.fromCodePoint(code), end };
|
|
497
563
|
}
|
|
564
|
+
return { content: `\\${escaped}`, end: start + 2 };
|
|
565
|
+
}
|
|
566
|
+
function pushWord(tokens, value, substitutions, expansion) {
|
|
567
|
+
const token = substitutions.length > 0 ? { type: "word", value, substitutions } : { type: "word", value };
|
|
568
|
+
tokens.push(expansion ? { ...token, expansion: true } : token);
|
|
498
569
|
}
|
|
499
570
|
function heredocSubstitutions(body) {
|
|
500
571
|
const substitutions = [];
|
|
@@ -541,7 +612,7 @@ function tokenizeShell(command) {
|
|
|
541
612
|
i += 2;
|
|
542
613
|
continue;
|
|
543
614
|
}
|
|
544
|
-
if (character === "|" || character === ";" || character === "&" || character === `
|
|
615
|
+
if (character === "|" || character === ";" || character === "&" && command[i + 1] !== ">" || character === `
|
|
545
616
|
` || character === "(" || character === ")" || character === "{" || character === "}") {
|
|
546
617
|
tokens.push({ type: "operator", value: character });
|
|
547
618
|
i++;
|
|
@@ -556,9 +627,10 @@ function tokenizeShell(command) {
|
|
|
556
627
|
const end = lineEnd < 0 ? command.length : lineEnd;
|
|
557
628
|
const line = command.slice(i, end);
|
|
558
629
|
i = lineEnd < 0 ? end : end + 1;
|
|
559
|
-
if (line === heredoc.delimiter) {
|
|
630
|
+
if ((heredoc.stripTabs ? line.replace(/^\t+/, "") : line) === heredoc.delimiter) {
|
|
560
631
|
complete = true;
|
|
561
|
-
const
|
|
632
|
+
const rawBody = command.slice(bodyStart, i - (line.length + (lineEnd < 0 ? 0 : 1)));
|
|
633
|
+
const body = heredoc.stripTabs ? rawBody.replace(/^\t+/gm, "") : rawBody;
|
|
562
634
|
tokens[heredoc.index] = {
|
|
563
635
|
...tokens[heredoc.index],
|
|
564
636
|
heredoc: { body, quoted: heredoc.quoted },
|
|
@@ -575,17 +647,19 @@ function tokenizeShell(command) {
|
|
|
575
647
|
}
|
|
576
648
|
continue;
|
|
577
649
|
}
|
|
578
|
-
const redirectMatch = command.slice(i).match(/^(
|
|
650
|
+
const redirectMatch = command.slice(i).match(/^(?:\d+)?(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)|^&>>?/);
|
|
579
651
|
if (redirectMatch !== null && redirectMatch[0] !== undefined) {
|
|
580
652
|
tokens.push({ type: "redirect", value: redirectMatch[0] });
|
|
581
|
-
if (/^\d
|
|
653
|
+
if (/^\d*<<-?$/.test(redirectMatch[0]))
|
|
582
654
|
pendingDelimiter = tokens.length - 1;
|
|
583
655
|
i += redirectMatch[0].length;
|
|
584
656
|
continue;
|
|
585
657
|
}
|
|
586
658
|
let value = "";
|
|
659
|
+
const wordBytes = [];
|
|
587
660
|
let quoted = false;
|
|
588
661
|
let unsupportedDelimiter = false;
|
|
662
|
+
let expansion = false;
|
|
589
663
|
const substitutions = [];
|
|
590
664
|
while (i < command.length) {
|
|
591
665
|
const current = command[i];
|
|
@@ -608,40 +682,36 @@ function tokenizeShell(command) {
|
|
|
608
682
|
continue;
|
|
609
683
|
}
|
|
610
684
|
if (current === "$" && command[i + 1] === "'") {
|
|
685
|
+
wordBytes.push(...Buffer.from(value));
|
|
686
|
+
value = "";
|
|
611
687
|
quoted = true;
|
|
612
688
|
unsupportedDelimiter = true;
|
|
613
689
|
i += 2;
|
|
690
|
+
const bytes = [];
|
|
691
|
+
let complete = false;
|
|
614
692
|
while (i < command.length) {
|
|
615
693
|
const ansiCharacter = command[i];
|
|
616
694
|
if (ansiCharacter === undefined)
|
|
617
695
|
break;
|
|
618
696
|
if (ansiCharacter === "'") {
|
|
619
697
|
i++;
|
|
698
|
+
complete = true;
|
|
620
699
|
break;
|
|
621
700
|
}
|
|
622
701
|
if (ansiCharacter === "\\" && i + 1 < command.length) {
|
|
623
|
-
const escaped = command
|
|
624
|
-
|
|
625
|
-
|
|
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;
|
|
702
|
+
const escaped = ansiEscape(command, i);
|
|
703
|
+
bytes.push(...escaped.byte === undefined ? Buffer.from(escaped.content) : [escaped.byte]);
|
|
704
|
+
i = escaped.end;
|
|
640
705
|
} else {
|
|
641
|
-
|
|
642
|
-
|
|
706
|
+
const literal = String.fromCodePoint(command.codePointAt(i));
|
|
707
|
+
bytes.push(...Buffer.from(literal));
|
|
708
|
+
i += literal.length;
|
|
643
709
|
}
|
|
644
710
|
}
|
|
711
|
+
if (!complete)
|
|
712
|
+
throw new Error("Cannot parse shell quotes reliably. Run git commit directly.");
|
|
713
|
+
const nul = bytes.indexOf(0);
|
|
714
|
+
wordBytes.push(...nul < 0 ? bytes : bytes.slice(0, nul));
|
|
645
715
|
continue;
|
|
646
716
|
}
|
|
647
717
|
if (current === "'") {
|
|
@@ -651,8 +721,9 @@ function tokenizeShell(command) {
|
|
|
651
721
|
value += command[i];
|
|
652
722
|
i++;
|
|
653
723
|
}
|
|
654
|
-
if (command[i]
|
|
655
|
-
|
|
724
|
+
if (command[i] !== "'")
|
|
725
|
+
throw new Error("Cannot parse shell quotes reliably. Run git commit directly.");
|
|
726
|
+
i++;
|
|
656
727
|
continue;
|
|
657
728
|
}
|
|
658
729
|
if (current === '"') {
|
|
@@ -678,35 +749,58 @@ function tokenizeShell(command) {
|
|
|
678
749
|
const substitution = consumeCommandSubstitution(command, i);
|
|
679
750
|
value += command.slice(i, substitution.end);
|
|
680
751
|
substitutions.push(substitution.content);
|
|
752
|
+
expansion = true;
|
|
753
|
+
i = substitution.end;
|
|
754
|
+
} else if (quotedCharacter === "`") {
|
|
755
|
+
const substitution = consumeBackticks(command, i);
|
|
756
|
+
value += command.slice(i, substitution.end);
|
|
757
|
+
substitutions.push(substitution.content);
|
|
758
|
+
expansion = true;
|
|
681
759
|
i = substitution.end;
|
|
682
760
|
} else {
|
|
761
|
+
if (quotedCharacter === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? ""))
|
|
762
|
+
expansion = true;
|
|
683
763
|
value += quotedCharacter;
|
|
684
764
|
i++;
|
|
685
765
|
}
|
|
686
766
|
}
|
|
687
|
-
if (command[i]
|
|
688
|
-
|
|
767
|
+
if (command[i] !== '"')
|
|
768
|
+
throw new Error("Cannot parse shell quotes reliably. Run git commit directly.");
|
|
769
|
+
i++;
|
|
689
770
|
continue;
|
|
690
771
|
}
|
|
691
772
|
if (current === "$" && command[i + 1] === "(") {
|
|
692
773
|
const substitution = consumeCommandSubstitution(command, i);
|
|
693
774
|
value += command.slice(i, substitution.end);
|
|
694
775
|
substitutions.push(substitution.content);
|
|
776
|
+
expansion = true;
|
|
777
|
+
i = substitution.end;
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
if (current === "`") {
|
|
781
|
+
const substitution = consumeBackticks(command, i);
|
|
782
|
+
value += command.slice(i, substitution.end);
|
|
783
|
+
substitutions.push(substitution.content);
|
|
784
|
+
expansion = true;
|
|
695
785
|
i = substitution.end;
|
|
696
786
|
continue;
|
|
697
787
|
}
|
|
698
|
-
|
|
788
|
+
if (current === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? ""))
|
|
789
|
+
expansion = true;
|
|
790
|
+
const nextRedirect = command.slice(i).match(/^(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)/);
|
|
699
791
|
if (nextRedirect !== null)
|
|
700
792
|
break;
|
|
701
793
|
value += current;
|
|
702
794
|
i++;
|
|
703
795
|
}
|
|
704
|
-
|
|
796
|
+
if (wordBytes.length > 0)
|
|
797
|
+
value = Buffer.from([...wordBytes, ...Buffer.from(value)]).toString("utf8");
|
|
798
|
+
pushWord(tokens, value, substitutions, expansion);
|
|
705
799
|
if (pendingDelimiter !== undefined) {
|
|
706
800
|
if (unsupportedDelimiter) {
|
|
707
801
|
throw new Error("Cannot validate an ANSI-C quoted heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.");
|
|
708
802
|
}
|
|
709
|
-
pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted });
|
|
803
|
+
pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted, stripTabs: tokens[pendingDelimiter]?.value.endsWith("-") === true });
|
|
710
804
|
pendingDelimiter = undefined;
|
|
711
805
|
}
|
|
712
806
|
}
|
|
@@ -742,14 +836,14 @@ function extractCommandWords(tokens) {
|
|
|
742
836
|
if (token === undefined)
|
|
743
837
|
break;
|
|
744
838
|
if (token.type === "redirect") {
|
|
745
|
-
if (
|
|
839
|
+
if (tokens[i + 1]?.type === "word")
|
|
746
840
|
i += 2;
|
|
747
841
|
else
|
|
748
842
|
i++;
|
|
749
843
|
continue;
|
|
750
844
|
}
|
|
751
845
|
if (token.type === "word") {
|
|
752
|
-
words.push(token
|
|
846
|
+
words.push(token);
|
|
753
847
|
}
|
|
754
848
|
i++;
|
|
755
849
|
}
|
|
@@ -830,7 +924,7 @@ function findCommandStart(words) {
|
|
|
830
924
|
}
|
|
831
925
|
return index;
|
|
832
926
|
}
|
|
833
|
-
function extractInvocation(words, commandStart) {
|
|
927
|
+
function extractInvocation(words, commandStart, wordTokens) {
|
|
834
928
|
let wordIndex = commandStart;
|
|
835
929
|
const executable = words[wordIndex];
|
|
836
930
|
if (executable === undefined || executable !== "git" && !executable.endsWith("/git"))
|
|
@@ -883,6 +977,8 @@ function extractInvocation(words, commandStart) {
|
|
|
883
977
|
let hasNoEdit = false;
|
|
884
978
|
let isFixup = false;
|
|
885
979
|
let isHelp = false;
|
|
980
|
+
let messageExpansion = false;
|
|
981
|
+
let hasTrailer = false;
|
|
886
982
|
const collectMessage = (word) => {
|
|
887
983
|
if (word === undefined)
|
|
888
984
|
return;
|
|
@@ -915,8 +1011,10 @@ function extractInvocation(words, commandStart) {
|
|
|
915
1011
|
hasSignoffFlag = false;
|
|
916
1012
|
} else if (argument === "-m" || argument === "--message") {
|
|
917
1013
|
index++;
|
|
1014
|
+
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
918
1015
|
collectMessage(words[index]);
|
|
919
1016
|
} else if (argument.startsWith("--message=")) {
|
|
1017
|
+
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
920
1018
|
collectMessage(argument.slice("--message=".length));
|
|
921
1019
|
} else if (argument === "-F" || argument === "--file") {
|
|
922
1020
|
index++;
|
|
@@ -927,6 +1025,10 @@ function extractInvocation(words, commandStart) {
|
|
|
927
1025
|
isFixup = true;
|
|
928
1026
|
if (equalsIndex < 0)
|
|
929
1027
|
index++;
|
|
1028
|
+
} else if (longOptionName === "--trailer") {
|
|
1029
|
+
hasTrailer = true;
|
|
1030
|
+
if (equalsIndex < 0)
|
|
1031
|
+
index++;
|
|
930
1032
|
} else if (commitLongOptionsWithArg.has(longOptionName)) {
|
|
931
1033
|
if (equalsIndex < 0)
|
|
932
1034
|
index++;
|
|
@@ -942,9 +1044,10 @@ function extractInvocation(words, commandStart) {
|
|
|
942
1044
|
} else if (option === "m" || option === "F") {
|
|
943
1045
|
const attached = argument.slice(characterIndex + 1);
|
|
944
1046
|
const input = attached.length > 0 ? attached : words[++index];
|
|
945
|
-
if (option === "m")
|
|
1047
|
+
if (option === "m") {
|
|
1048
|
+
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
946
1049
|
collectMessage(input);
|
|
947
|
-
else
|
|
1050
|
+
} else
|
|
948
1051
|
collectFile(input);
|
|
949
1052
|
break;
|
|
950
1053
|
} else if (option === "S") {
|
|
@@ -967,18 +1070,52 @@ function extractInvocation(words, commandStart) {
|
|
|
967
1070
|
hasNoEdit,
|
|
968
1071
|
isFixup,
|
|
969
1072
|
isHelp,
|
|
970
|
-
targetError
|
|
1073
|
+
targetError,
|
|
1074
|
+
messageExpansion,
|
|
1075
|
+
hasTrailer
|
|
971
1076
|
};
|
|
972
1077
|
}
|
|
973
|
-
function extractGitCommits(command, inheritedDirectoryChange = false) {
|
|
1078
|
+
function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0) {
|
|
1079
|
+
if (depth > 12 || command.length > 262144)
|
|
1080
|
+
throw new Error("Shell parsing limit exceeded. Run git commit directly.");
|
|
974
1081
|
const tokens = tokenizeShell(command);
|
|
975
1082
|
const invocations = [];
|
|
976
1083
|
let changedDirectory = inheritedDirectoryChange;
|
|
977
1084
|
for (const simple of splitSimpleCommands(tokens)) {
|
|
978
1085
|
const commandTokens = simple.tokens;
|
|
979
|
-
const
|
|
1086
|
+
const wordTokens = extractCommandWords(commandTokens);
|
|
1087
|
+
const words = wordTokens.map((token) => token.value);
|
|
980
1088
|
const commandStart = findCommandStart(words);
|
|
981
|
-
const invocation = extractInvocation(words, commandStart);
|
|
1089
|
+
const invocation = extractInvocation(words, commandStart, wordTokens);
|
|
1090
|
+
if (/^(?:.*\/)?(?:bash|sh|zsh)$/.test(words[commandStart] ?? "")) {
|
|
1091
|
+
let bodyIndex = commandStart + 1;
|
|
1092
|
+
let executeString = false;
|
|
1093
|
+
while (bodyIndex < words.length) {
|
|
1094
|
+
const option = words[bodyIndex];
|
|
1095
|
+
if (option === "--") {
|
|
1096
|
+
bodyIndex++;
|
|
1097
|
+
break;
|
|
1098
|
+
}
|
|
1099
|
+
if (!option.startsWith("-") && !option.startsWith("+"))
|
|
1100
|
+
break;
|
|
1101
|
+
if (/^-[a-zA-Z]*c[a-zA-Z]*$/.test(option))
|
|
1102
|
+
executeString = true;
|
|
1103
|
+
const shortOptions = /^[+-][a-zA-Z]+$/.test(option);
|
|
1104
|
+
if (shortOptions && /[oO]/.test(option) && !/[oO]$/.test(option)) {
|
|
1105
|
+
throw new Error("Cannot parse shell options reliably. Run git commit directly.");
|
|
1106
|
+
}
|
|
1107
|
+
const next = words[bodyIndex + 1];
|
|
1108
|
+
const optionName = next !== undefined && !/^[+-]/.test(next);
|
|
1109
|
+
bodyIndex += shortOptions && /[oO]$/.test(option) && optionName || ["--rcfile", "--init-file"].includes(option) ? 2 : 1;
|
|
1110
|
+
}
|
|
1111
|
+
if (executeString) {
|
|
1112
|
+
const body = wordTokens[bodyIndex];
|
|
1113
|
+
if (body === undefined || body.expansion)
|
|
1114
|
+
throw new Error("Cannot parse shell -c body reliably. Run git commit directly.");
|
|
1115
|
+
const wrapperChange = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word));
|
|
1116
|
+
invocations.push(...extractGitCommits(body.value, changedDirectory || wrapperChange, depth + 1));
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
982
1119
|
if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment))
|
|
983
1120
|
changedDirectory = true;
|
|
984
1121
|
if (invocation !== undefined) {
|
|
@@ -1012,14 +1149,13 @@ function extractGitCommits(command, inheritedDirectoryChange = false) {
|
|
|
1012
1149
|
}
|
|
1013
1150
|
for (const token of tokens) {
|
|
1014
1151
|
for (const substitution of token.substitutions ?? []) {
|
|
1015
|
-
invocations.push(...extractGitCommits(substitution, changedDirectory));
|
|
1152
|
+
invocations.push(...extractGitCommits(substitution, changedDirectory, depth + 1));
|
|
1016
1153
|
}
|
|
1017
1154
|
}
|
|
1018
1155
|
return invocations;
|
|
1019
1156
|
}
|
|
1020
1157
|
|
|
1021
1158
|
// src/validator.ts
|
|
1022
|
-
var scopePattern = /^([a-zA-Z0-9_\-./]+(?:\([a-zA-Z0-9_\-./]+\))?):\s+(.+)$/;
|
|
1023
1159
|
var signoffPattern = /^\s*Signed-off-by:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/i;
|
|
1024
1160
|
function hasSignoffTrailer(lines) {
|
|
1025
1161
|
const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
|
|
@@ -1034,43 +1170,45 @@ function validateAllowedScope(rawScope, allowedScopes) {
|
|
|
1034
1170
|
return;
|
|
1035
1171
|
return `Scope "${rawScope}" is not in the allowed scopes list. Allowed scopes: ${allowedScopes.join(", ")}.`;
|
|
1036
1172
|
}
|
|
1037
|
-
function createCommitGuardError(violations,
|
|
1173
|
+
function createCommitGuardError(violations, config) {
|
|
1038
1174
|
const header = "[commit-guard] Git commit rejected: commit message format rules violated.";
|
|
1039
1175
|
const violationText = violations.map((v, i) => `${i + 1}. ${v}`).join(`
|
|
1040
1176
|
|
|
1041
1177
|
`);
|
|
1042
|
-
const
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
' git commit -m "feat(parser): add subshell support" -m "Signed-off-by: Developer <dev@example.com>"'
|
|
1047
|
-
].join(`
|
|
1048
|
-
`);
|
|
1178
|
+
const scope = config.allowedScopes?.[0] ?? "scope";
|
|
1179
|
+
const examples = `Signoff ${config.enforceSignoff ? "required: captured commit.gpgsign=true. Keep -s." : "not required: captured commit.gpgsign=false|unset."}
|
|
1180
|
+
` + `Example:
|
|
1181
|
+
git commit${config.enforceSignoff ? " -s" : ""} -m $'${scope}: Subject\\n\\nBody line one.\\nBody line two.'`;
|
|
1049
1182
|
return new Error(`${header}
|
|
1050
1183
|
|
|
1051
1184
|
Violations:
|
|
1052
1185
|
${violationText}
|
|
1053
1186
|
|
|
1054
|
-
${examples}
|
|
1055
|
-
|
|
1056
|
-
Command attempted:
|
|
1057
|
-
${originalCommand}`);
|
|
1187
|
+
${examples}`);
|
|
1058
1188
|
}
|
|
1059
|
-
function validateGitCommits(invocations, config,
|
|
1189
|
+
function validateGitCommits(invocations, config, _originalCommand) {
|
|
1060
1190
|
const allViolations = [];
|
|
1061
1191
|
for (const invocation of invocations) {
|
|
1062
1192
|
if (invocation.isHelp) {
|
|
1063
1193
|
continue;
|
|
1064
1194
|
}
|
|
1195
|
+
if (invocation.messageExpansion) {
|
|
1196
|
+
allViolations.push("Cannot validate a message containing shell expansion. Supply the final message literally.");
|
|
1197
|
+
continue;
|
|
1198
|
+
}
|
|
1199
|
+
if (invocation.hasTrailer) {
|
|
1200
|
+
allViolations.push("Cannot validate --trailer. Put the trailer in the literal message body or use -s.");
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1065
1203
|
const collectedMessages = [...invocation.messages];
|
|
1066
1204
|
const filePath = invocation.filePaths.at(-1);
|
|
1067
1205
|
if (filePath !== undefined) {
|
|
1068
1206
|
if (filePath !== "-" || invocation.filePaths.length !== 1) {
|
|
1069
|
-
allViolations.push(
|
|
1207
|
+
allViolations.push("Cannot validate a commit message from -F/--file before permission approval. Use an inline $'...' message or one quoted stdin heredoc.");
|
|
1070
1208
|
continue;
|
|
1071
1209
|
}
|
|
1072
1210
|
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
|
|
1211
|
+
allViolations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} Use one quoted stdin heredoc or an inline $'...' message.`);
|
|
1074
1212
|
continue;
|
|
1075
1213
|
}
|
|
1076
1214
|
collectedMessages.push(invocation.stdinMessage);
|
|
@@ -1113,7 +1251,7 @@ function validateGitCommits(invocations, config, originalCommand) {
|
|
|
1113
1251
|
} else if (/^[^:]+:\s*$/.test(effectiveSubject)) {
|
|
1114
1252
|
allViolations.push(`Subject text after colon is empty in "${subjectLine}". Expected format: "<scope>: <subject>".`);
|
|
1115
1253
|
} else {
|
|
1116
|
-
allViolations.push(`Missing scope in subject line "${subjectLine}". First line must follow "<scope>: <subject>" format
|
|
1254
|
+
allViolations.push(`Missing scope in subject line "${subjectLine}". First line must follow "<scope>: <subject>" format.`);
|
|
1117
1255
|
}
|
|
1118
1256
|
}
|
|
1119
1257
|
}
|
|
@@ -1129,7 +1267,8 @@ function validateGitCommits(invocations, config, originalCommand) {
|
|
|
1129
1267
|
const details = overlongLines.map((l) => ` - Line ${l.lineNumber} (${l.length} chars, max ${config.maxLineLength}): "${l.text}"`).join(`
|
|
1130
1268
|
`);
|
|
1131
1269
|
allViolations.push(`Commit message exceeds maximum line length of ${config.maxLineLength} characters:
|
|
1132
|
-
${details}
|
|
1270
|
+
${details}
|
|
1271
|
+
Each -m becomes one paragraph line. Wrap with real newlines inside $'...'; "\\n" inside double quotes stays literal.`);
|
|
1133
1272
|
}
|
|
1134
1273
|
}
|
|
1135
1274
|
if (config.enforceSignoff) {
|
|
@@ -1140,7 +1279,7 @@ ${details}`);
|
|
|
1140
1279
|
}
|
|
1141
1280
|
}
|
|
1142
1281
|
if (allViolations.length > 0) {
|
|
1143
|
-
throw createCommitGuardError(allViolations,
|
|
1282
|
+
throw createCommitGuardError(allViolations.slice(0, 10).map((text) => text.slice(0, 2048)), config);
|
|
1144
1283
|
}
|
|
1145
1284
|
}
|
|
1146
1285
|
|
|
@@ -1155,16 +1294,48 @@ var plugin = Plugin.define({
|
|
|
1155
1294
|
const pending = new Map;
|
|
1156
1295
|
const preparing = new Set;
|
|
1157
1296
|
const lastSessionWorkdir = new Map;
|
|
1297
|
+
const failures = new Map;
|
|
1298
|
+
const rememberFailure = (scope, reason) => {
|
|
1299
|
+
failures.delete(scope);
|
|
1300
|
+
failures.set(scope, `The previous capture failed: ${reason.slice(0, 256)}. `);
|
|
1301
|
+
if (failures.size > 128)
|
|
1302
|
+
failures.delete(failures.keys().next().value);
|
|
1303
|
+
};
|
|
1304
|
+
const sweep = () => Effect2.gen(function* () {
|
|
1305
|
+
for (const attempt of [...pending.values()].slice(0, 32)) {
|
|
1306
|
+
pending.delete(attempt.scope);
|
|
1307
|
+
if (attempt.claimed === undefined && Date.now() >= attempt.expires) {
|
|
1308
|
+
cleanup(attempt);
|
|
1309
|
+
yield* recordState(ctx, attempt, "expired");
|
|
1310
|
+
yield* invalidateOwned(ctx, attempt);
|
|
1311
|
+
} else
|
|
1312
|
+
pending.set(attempt.scope, attempt);
|
|
1313
|
+
}
|
|
1314
|
+
});
|
|
1158
1315
|
yield* Effect2.addFinalizer(() => Effect2.gen(function* () {
|
|
1159
1316
|
for (const attempt of pending.values()) {
|
|
1160
1317
|
cleanup(attempt);
|
|
1161
|
-
yield*
|
|
1318
|
+
yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication");
|
|
1319
|
+
yield* invalidateOwned(ctx, attempt);
|
|
1162
1320
|
}
|
|
1163
1321
|
pending.clear();
|
|
1164
1322
|
}));
|
|
1165
1323
|
yield* ctx.tool.transform((editor) => editor.add({
|
|
1166
1324
|
name: "commit_context",
|
|
1167
|
-
description:
|
|
1325
|
+
description: String.raw`Prepare a Git baseline. Run the returned command unchanged in the foreground; require "Frozen commit baseline".
|
|
1326
|
+
Call before your first commit in each session and checkout.
|
|
1327
|
+
Set workdir when targeting another repository.
|
|
1328
|
+
Run the returned command immediately, unchanged, with the indicated workdir and background:false.
|
|
1329
|
+
Do not wrap it or chain another command onto it.
|
|
1330
|
+
Commit only after the shell result or this tool reports "Frozen commit baseline".
|
|
1331
|
+
RECEIPT_OK alone is insufficient.
|
|
1332
|
+
The shell result includes commit rules; a second call is optional.
|
|
1333
|
+
Repeat an explicit workdir when checking that checkout.
|
|
1334
|
+
Set refresh:true after switching branches, changing signing settings, or changing commit instructions.
|
|
1335
|
+
Use literal message text and real body newlines.
|
|
1336
|
+
Example: git commit -m $'scope: Subject\n\nBody line one.\nBody line two.'
|
|
1337
|
+
Replace scope and follow the returned line-length and signoff rules.
|
|
1338
|
+
Add -s only when the returned policy or repository instructions require it.`,
|
|
1168
1339
|
input: {
|
|
1169
1340
|
type: "object",
|
|
1170
1341
|
properties: {
|
|
@@ -1175,6 +1346,7 @@ var plugin = Plugin.define({
|
|
|
1175
1346
|
additionalProperties: false
|
|
1176
1347
|
},
|
|
1177
1348
|
execute: (input, toolContext) => Effect2.gen(function* () {
|
|
1349
|
+
yield* sweep();
|
|
1178
1350
|
if (ctx.location.workspaceID !== undefined)
|
|
1179
1351
|
return { content: "Commit context capture is unavailable for remote workspaces." };
|
|
1180
1352
|
const session = yield* ctx.session.get({ sessionID: toolContext.sessionID });
|
|
@@ -1198,41 +1370,34 @@ var plugin = Plugin.define({
|
|
|
1198
1370
|
lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir);
|
|
1199
1371
|
const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir);
|
|
1200
1372
|
if (preparing.has(scope))
|
|
1201
|
-
return { content: "A commit context capture is preparing for this session and checkout.
|
|
1373
|
+
return { content: "A commit context capture is preparing for this session and checkout. Wait for its command, then follow its instructions." };
|
|
1202
1374
|
preparing.add(scope);
|
|
1203
1375
|
return yield* Effect2.gen(function* () {
|
|
1204
1376
|
const previous = pending.get(scope);
|
|
1205
1377
|
if (previous !== undefined) {
|
|
1206
|
-
if (
|
|
1207
|
-
return { content:
|
|
1208
|
-
|
|
1378
|
+
if (previous.claimed !== undefined && request.refresh !== true) {
|
|
1379
|
+
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.' };
|
|
1380
|
+
}
|
|
1381
|
+
if (request.refresh !== true) {
|
|
1382
|
+
return { content: captureInstructions(previous, "Capture still pending and unclaimed. ") };
|
|
1209
1383
|
}
|
|
1210
1384
|
pending.delete(scope);
|
|
1211
1385
|
cleanup(previous);
|
|
1212
|
-
yield*
|
|
1386
|
+
yield* recordState(ctx, previous, "failed", "capture replaced by refresh");
|
|
1387
|
+
yield* invalidateOwned(ctx, previous);
|
|
1213
1388
|
}
|
|
1214
1389
|
if (request.refresh !== true) {
|
|
1215
1390
|
const baseline = yield* load(ctx, scope);
|
|
1216
|
-
if (baseline !== undefined &&
|
|
1217
|
-
|
|
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." };
|
|
1391
|
+
if (baseline !== undefined && baseline.directory === findGitRoot(targetWorkdir)) {
|
|
1392
|
+
return { content: baselineGuidance(baseline, config) };
|
|
1227
1393
|
}
|
|
1228
1394
|
}
|
|
1229
|
-
|
|
1230
|
-
yield* invalidate(ctx, scope);
|
|
1231
|
-
const count = yield* counter(ctx, scope);
|
|
1395
|
+
const count = yield* invalidate(ctx, scope);
|
|
1232
1396
|
const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, targetWorkdir));
|
|
1233
1397
|
pending.set(scope, attempt);
|
|
1234
|
-
|
|
1235
|
-
|
|
1398
|
+
const status = failures.get(scope) ?? (yield* captureStatus(ctx, scope));
|
|
1399
|
+
yield* recordState(ctx, attempt, "prepared");
|
|
1400
|
+
return { content: captureInstructions(attempt, status) };
|
|
1236
1401
|
}).pipe(Effect2.ensuring(Effect2.sync(() => {
|
|
1237
1402
|
preparing.delete(scope);
|
|
1238
1403
|
})));
|
|
@@ -1240,14 +1405,8 @@ ${attempt.command}` };
|
|
|
1240
1405
|
message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout."
|
|
1241
1406
|
})))
|
|
1242
1407
|
}));
|
|
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
1408
|
yield* ctx.tool.hook("execute.before", (event) => Effect2.gen(function* () {
|
|
1409
|
+
yield* sweep();
|
|
1251
1410
|
const captureSession = event.tool === "shell" || event.tool === "bash" ? yield* ctx.session.get({ sessionID: event.sessionID }) : undefined;
|
|
1252
1411
|
const captureSessionDirectory = captureSession?.location.directory ?? ctx.location.directory;
|
|
1253
1412
|
const parsed = yield* Effect2.try({
|
|
@@ -1272,21 +1431,23 @@ ${attempt.command}` };
|
|
|
1272
1431
|
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
1432
|
}
|
|
1274
1433
|
attempt.claimed = { messageID: event.messageID, id: event.id };
|
|
1275
|
-
attempt.expires = Date.now() + captureTimeout;
|
|
1276
1434
|
return;
|
|
1277
1435
|
}
|
|
1278
1436
|
const invocations = extractGitCommits(command);
|
|
1279
1437
|
if (invocations.length === 0) {
|
|
1280
1438
|
return;
|
|
1281
1439
|
}
|
|
1282
|
-
validateGitCommits(invocations, { ...config, enforceSignoff: false }, command);
|
|
1283
1440
|
return { invocations, command, rawInput };
|
|
1284
1441
|
},
|
|
1285
1442
|
catch: (error) => new Tool.Error({
|
|
1286
1443
|
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
|
|
1287
1444
|
})
|
|
1288
1445
|
});
|
|
1289
|
-
|
|
1446
|
+
for (const attempt of pending.values()) {
|
|
1447
|
+
if (attempt.claimed?.messageID === event.messageID && attempt.claimed.id === event.id && attempt.sessionID === event.sessionID && attempt.agent === event.agent)
|
|
1448
|
+
yield* recordState(ctx, attempt, "claimed");
|
|
1449
|
+
}
|
|
1450
|
+
if (parsed === undefined || parsed.invocations.every((invocation) => invocation.isHelp))
|
|
1290
1451
|
return;
|
|
1291
1452
|
if (ctx.location.workspaceID !== undefined)
|
|
1292
1453
|
return yield* Effect2.fail(new Tool.Error({
|
|
@@ -1302,21 +1463,21 @@ ${attempt.command}` };
|
|
|
1302
1463
|
const rawWorkdir = parsed.rawInput["workdir"];
|
|
1303
1464
|
const effectiveWorkdir = yield* Effect2.try(() => realpathSync2(isJSONString(rawWorkdir) ? resolve2(sessionDirectory, rawWorkdir) : sessionDirectory));
|
|
1304
1465
|
const targetGitRoot = findGitRoot(effectiveWorkdir);
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
if (baseline === undefined && targetGitRoot !== undefined && targetGitRoot !== effectiveWorkdir) {
|
|
1308
|
-
scope = scopeFor(ctx, event.sessionID, config, targetGitRoot);
|
|
1309
|
-
baseline = yield* load(ctx, scope);
|
|
1310
|
-
}
|
|
1466
|
+
const scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir);
|
|
1467
|
+
const baseline = yield* load(ctx, scope);
|
|
1311
1468
|
const expectedDir = targetGitRoot ?? effectiveWorkdir;
|
|
1312
|
-
const baselineValid = baseline !== undefined && targetGitRoot !== undefined && baseline.directory === targetGitRoot &&
|
|
1469
|
+
const baselineValid = baseline !== undefined && targetGitRoot !== undefined && baseline.directory === targetGitRoot && baseline.directory === expectedDir;
|
|
1313
1470
|
if (!baselineValid || baseline === undefined) {
|
|
1314
1471
|
const relWorkdir = relative2(sessionDirectory, expectedDir);
|
|
1315
|
-
const workdirHint = relWorkdir.length > 0
|
|
1472
|
+
const workdirHint = JSON.stringify(relWorkdir.length > 0 ? relWorkdir : ".");
|
|
1316
1473
|
return yield* Effect2.fail(new Tool.Error({
|
|
1317
|
-
message: `[commit-guard] No
|
|
1474
|
+
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
1475
|
}));
|
|
1319
1476
|
}
|
|
1477
|
+
if (baseline.gpgsign === "error" || baseline.signingkey === "error")
|
|
1478
|
+
return yield* Effect2.fail(new Tool.Error({
|
|
1479
|
+
message: signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")
|
|
1480
|
+
}));
|
|
1320
1481
|
yield* Effect2.try({
|
|
1321
1482
|
try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
|
|
1322
1483
|
catch: (error) => new Tool.Error({
|
|
@@ -1333,10 +1494,17 @@ ${attempt.command}` };
|
|
|
1333
1494
|
if (attempt === undefined)
|
|
1334
1495
|
return;
|
|
1335
1496
|
let published = false;
|
|
1497
|
+
let captured;
|
|
1498
|
+
let reason = "capture import or storage failed";
|
|
1336
1499
|
yield* Effect2.gen(function* () {
|
|
1337
|
-
|
|
1500
|
+
reason = "shell result did not complete successfully";
|
|
1501
|
+
if (event.status !== "completed")
|
|
1502
|
+
return;
|
|
1503
|
+
reason = "capture was superseded by a refresh";
|
|
1504
|
+
if ((yield* counter(ctx, attempt.scope)) !== attempt.counter)
|
|
1338
1505
|
return;
|
|
1339
1506
|
const metadata = event.result.metadata;
|
|
1507
|
+
reason = "shell result lacks verified foreground completion metadata";
|
|
1340
1508
|
if (!isRecord(metadata))
|
|
1341
1509
|
return;
|
|
1342
1510
|
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 +1512,77 @@ ${attempt.command}` };
|
|
|
1344
1512
|
const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {
|
|
1345
1513
|
return;
|
|
1346
1514
|
});
|
|
1515
|
+
reason = "capture session or workspace no longer matches";
|
|
1347
1516
|
if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID)
|
|
1348
1517
|
return;
|
|
1518
|
+
reason = "private artifact is invalid or incomplete (END required)";
|
|
1349
1519
|
const baseline = yield* Effect2.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") });
|
|
1350
1520
|
if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined)
|
|
1351
1521
|
return;
|
|
1522
|
+
reason = "capture storage failed or its counter changed";
|
|
1352
1523
|
published = yield* publish(ctx, attempt, generation, baseline);
|
|
1524
|
+
if (published) {
|
|
1525
|
+
captured = baseline;
|
|
1526
|
+
failures.delete(attempt.scope);
|
|
1527
|
+
yield* recordState(ctx, attempt, "published");
|
|
1528
|
+
}
|
|
1353
1529
|
}).pipe(Effect2.onExit(() => Effect2.gen(function* () {
|
|
1354
1530
|
if (pending.get(attempt.scope) === attempt)
|
|
1355
1531
|
pending.delete(attempt.scope);
|
|
1356
|
-
if (!published)
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1532
|
+
if (!published) {
|
|
1533
|
+
rememberFailure(attempt.scope, reason);
|
|
1534
|
+
yield* recordState(ctx, attempt, "failed", reason).pipe(Effect2.catchCause(() => Effect2.void));
|
|
1535
|
+
yield* invalidateOwned(ctx, attempt);
|
|
1536
|
+
}
|
|
1537
|
+
}).pipe(Effect2.ensuring(Effect2.sync(() => cleanup(attempt))))), Effect2.catchCause(() => Effect2.void));
|
|
1538
|
+
const note = published && captured !== undefined ? baselineGuidance(captured, config) : `[commit-guard] This capture did not publish a usable baseline: ${reason.slice(0, 256)}.
|
|
1539
|
+
` + `RECEIPT_OK alone does not authorize a commit.
|
|
1540
|
+
` + "Call commit_context with the same workdir for status and next steps.";
|
|
1541
|
+
if (event.status === "error") {
|
|
1542
|
+
event.error = new Tool.Error({ message: `${event.error.message}
|
|
1543
|
+
|
|
1544
|
+
${note}` });
|
|
1545
|
+
} else
|
|
1546
|
+
event.result = appendCaptureNote(event.result, note);
|
|
1360
1547
|
}));
|
|
1361
1548
|
})
|
|
1362
1549
|
});
|
|
1363
1550
|
var plugin_default = plugin;
|
|
1551
|
+
function captureInstructions(attempt, status) {
|
|
1552
|
+
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:
|
|
1553
|
+
${attempt.command}`;
|
|
1554
|
+
}
|
|
1555
|
+
function baselineGuidance(baseline, config) {
|
|
1556
|
+
if (baseline.gpgsign === "error" || baseline.signingkey === "error")
|
|
1557
|
+
return signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey");
|
|
1558
|
+
const observed = [...new Set(baseline.messages.map((message) => message.split(`
|
|
1559
|
+
`)[0]?.match(/^([a-zA-Z0-9_./-]{1,40}): /)?.[1]).filter((value) => value !== undefined))].slice(0, 3);
|
|
1560
|
+
const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
|
|
1561
|
+
` : "";
|
|
1562
|
+
const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." : `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`;
|
|
1563
|
+
const signoff = baseline.gpgsign === "true" ? "Add -s or --signoff." : "Signoff is not required; add it only if repository instructions require it.";
|
|
1564
|
+
return `[commit-guard] Frozen commit baseline for ${baseline.directory.slice(0, 4096)}.
|
|
1565
|
+
` + `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.
|
|
1566
|
+
` + `${scopes}
|
|
1567
|
+
${examples}Effective commit.gpgsign: ${baseline.gpgsign}. ${signoff}
|
|
1568
|
+
` + `user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}. Signoff is not a cryptographic signature.
|
|
1569
|
+
` + `A second commit_context call is optional.
|
|
1570
|
+
` + "Set refresh:true after a branch switch, changed signing settings, or changed commit instructions.";
|
|
1571
|
+
}
|
|
1572
|
+
function appendCaptureNote(result, note) {
|
|
1573
|
+
const content = Array.isArray(result.content) ? result.content : result.content === undefined ? [] : [{ type: "text", text: String(result.content) }];
|
|
1574
|
+
const output = result.output;
|
|
1575
|
+
const annotated = { ...result, content: [...content, { type: "text", text: note }] };
|
|
1576
|
+
if (isRecord(output) && isJSONString(output["output"])) {
|
|
1577
|
+
return { ...annotated, output: { ...output, output: `${output["output"]}
|
|
1578
|
+
|
|
1579
|
+
${note}` } };
|
|
1580
|
+
}
|
|
1581
|
+
return annotated;
|
|
1582
|
+
}
|
|
1583
|
+
function signingError(setting) {
|
|
1584
|
+
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.`;
|
|
1585
|
+
}
|
|
1364
1586
|
export {
|
|
1365
1587
|
plugin_default as default
|
|
1366
1588
|
};
|