opencode-commit-guard 1.0.4 → 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 +31 -4
- package/dist/index.js +491 -131
- package/package.json +7 -7
- package/src/capture.ts +172 -7
- package/src/config.ts +5 -0
- package/src/plugin.ts +285 -92
- 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
|
@@ -4,12 +4,14 @@ import { Plugin } from "@opencode/plugin/effect";
|
|
|
4
4
|
import { Tool } from "@opencode/schema/tool";
|
|
5
5
|
import { Effect as Effect2 } from "effect";
|
|
6
6
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
7
|
+
import { existsSync as existsSync2, realpathSync as realpathSync2 } from "fs";
|
|
8
|
+
import { relative as relative2, resolve as resolve2 } from "path";
|
|
7
9
|
|
|
8
10
|
// src/capture.ts
|
|
9
11
|
import { createHash, randomUUID } from "crypto";
|
|
10
|
-
import { closeSync, constants, fstatSync, mkdtempSync, openSync, readSync, rmSync } from "fs";
|
|
12
|
+
import { closeSync, constants, existsSync, fstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync, statSync } from "fs";
|
|
11
13
|
import { tmpdir } from "os";
|
|
12
|
-
import { join, relative } from "path";
|
|
14
|
+
import { dirname, join, relative, resolve } from "path";
|
|
13
15
|
import { Effect, Semaphore } from "effect";
|
|
14
16
|
|
|
15
17
|
// src/types.ts
|
|
@@ -41,13 +43,15 @@ var storageLock = Semaphore.makeUnsafe(1);
|
|
|
41
43
|
function digest(text) {
|
|
42
44
|
return createHash("sha256").update(text).digest("hex");
|
|
43
45
|
}
|
|
44
|
-
function scopeFor(ctx, sessionID, config) {
|
|
46
|
+
function scopeFor(ctx, sessionID, config, targetDir) {
|
|
45
47
|
const location = ctx.location;
|
|
48
|
+
const directory = targetDir ?? location.directory;
|
|
49
|
+
const root = findGitRoot(directory) ?? realpathSync(directory);
|
|
46
50
|
return digest(JSON.stringify([
|
|
47
51
|
version,
|
|
48
52
|
location.project.id,
|
|
49
53
|
sessionID,
|
|
50
|
-
|
|
54
|
+
root,
|
|
51
55
|
location.workspaceID ?? null,
|
|
52
56
|
policy,
|
|
53
57
|
config.requireScope,
|
|
@@ -55,6 +59,95 @@ function scopeFor(ctx, sessionID, config) {
|
|
|
55
59
|
config.maxLineLength
|
|
56
60
|
]));
|
|
57
61
|
}
|
|
62
|
+
function isGitDirectory(dir) {
|
|
63
|
+
try {
|
|
64
|
+
return existsSync(join(dir, ".git"));
|
|
65
|
+
} catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function findGitRoot(startDir) {
|
|
70
|
+
let current;
|
|
71
|
+
try {
|
|
72
|
+
current = realpathSync(startDir);
|
|
73
|
+
} catch {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
while (true) {
|
|
77
|
+
if (isGitDirectory(current)) {
|
|
78
|
+
return current;
|
|
79
|
+
}
|
|
80
|
+
const parent = dirname(current);
|
|
81
|
+
if (parent === current) {
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
current = parent;
|
|
85
|
+
}
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
function findSubRepos(dir, maxDepth = 2) {
|
|
89
|
+
const repos = [];
|
|
90
|
+
function search(currentDir, currentDepth) {
|
|
91
|
+
if (currentDepth > maxDepth)
|
|
92
|
+
return;
|
|
93
|
+
try {
|
|
94
|
+
const entries = readdirSync(currentDir, { withFileTypes: true });
|
|
95
|
+
for (const entry of entries) {
|
|
96
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink())
|
|
97
|
+
continue;
|
|
98
|
+
if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist")
|
|
99
|
+
continue;
|
|
100
|
+
const fullPath = join(currentDir, entry.name);
|
|
101
|
+
if (isGitDirectory(fullPath)) {
|
|
102
|
+
repos.push(fullPath);
|
|
103
|
+
} else if (currentDepth < maxDepth) {
|
|
104
|
+
search(fullPath, currentDepth + 1);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
} catch {}
|
|
108
|
+
}
|
|
109
|
+
search(dir, 1);
|
|
110
|
+
return repos;
|
|
111
|
+
}
|
|
112
|
+
function resolveTargetWorkdir(baseDir, requestedDir) {
|
|
113
|
+
if (requestedDir !== undefined) {
|
|
114
|
+
const resolvedDir = resolve(baseDir, requestedDir);
|
|
115
|
+
if (!existsSync(resolvedDir)) {
|
|
116
|
+
return { error: `Directory "${requestedDir}" does not exist.` };
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
if (!statSync(resolvedDir).isDirectory()) {
|
|
120
|
+
return { error: `Path "${requestedDir}" is not a directory.` };
|
|
121
|
+
}
|
|
122
|
+
} catch {
|
|
123
|
+
return { error: `Could not access directory "${requestedDir}".` };
|
|
124
|
+
}
|
|
125
|
+
const gitRoot = findGitRoot(resolvedDir);
|
|
126
|
+
if (gitRoot === undefined) {
|
|
127
|
+
return { error: `Directory "${requestedDir}" is not a Git repository or inside one.` };
|
|
128
|
+
}
|
|
129
|
+
return { workdir: realpathSync(resolvedDir) };
|
|
130
|
+
}
|
|
131
|
+
const currentGitRoot = findGitRoot(baseDir);
|
|
132
|
+
if (currentGitRoot !== undefined) {
|
|
133
|
+
return { workdir: realpathSync(baseDir) };
|
|
134
|
+
}
|
|
135
|
+
const subRepos = findSubRepos(baseDir);
|
|
136
|
+
if (subRepos.length === 1) {
|
|
137
|
+
return { workdir: realpathSync(subRepos[0]) };
|
|
138
|
+
}
|
|
139
|
+
if (subRepos.length === 0) {
|
|
140
|
+
return {
|
|
141
|
+
error: `No Git repository found in ${baseDir}. Specify the repository directory with the 'workdir' option, for example: commit_context({ workdir: "path/to/repo" }).`
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const repoList = subRepos.map((repo) => relative(baseDir, repo)).join(", ");
|
|
145
|
+
return {
|
|
146
|
+
error: `The directory ${baseDir} is not a Git repository. Multiple Git repositories were found: ${repoList}.
|
|
147
|
+
Specify which repository to target with the 'workdir' option, for example:
|
|
148
|
+
commit_context({ workdir: "${relative(baseDir, subRepos[0])}" })`
|
|
149
|
+
};
|
|
150
|
+
}
|
|
58
151
|
function counterKey(scope) {
|
|
59
152
|
return `counter/${scope}`;
|
|
60
153
|
}
|
|
@@ -72,9 +165,39 @@ function counter(ctx, scope) {
|
|
|
72
165
|
function invalidate(ctx, scope) {
|
|
73
166
|
return storageLock.withPermits(1)(Effect.gen(function* () {
|
|
74
167
|
const previous = yield* counter(ctx, scope);
|
|
75
|
-
|
|
168
|
+
const next = previous < 0 ? 1 : previous + 1;
|
|
169
|
+
yield* ctx.storage.set(counterKey(scope), next);
|
|
170
|
+
return next;
|
|
171
|
+
}));
|
|
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) });
|
|
76
185
|
}));
|
|
77
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
|
+
}
|
|
78
201
|
function validBaseline(value) {
|
|
79
202
|
if (!isRecord(value))
|
|
80
203
|
return false;
|
|
@@ -178,7 +301,7 @@ function importCapture(pending) {
|
|
|
178
301
|
const head = fields[6] === "head" ? decode(fields[7]).trim() : null;
|
|
179
302
|
const rawLog = decode(fields[8]);
|
|
180
303
|
const messages = head === null ? [] : rawLog.split("\x00\x00").filter((message) => message.length > 0);
|
|
181
|
-
if (!root.startsWith("/") || !gitDir.startsWith("/") || !commonDir.startsWith("/") ||
|
|
304
|
+
if (!root.startsWith("/") || !gitDir.startsWith("/") || !commonDir.startsWith("/") || root !== findGitRoot(pending.workdir) || !["branch", "detached"].includes(fields[4]) || !["head", "unborn"].includes(fields[6]) || head !== null && !/^[a-f0-9]{40,64}$/.test(head) || head === null && rawLog !== "" || head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\x00\x00")))
|
|
182
305
|
throw new Error("Invalid Git baseline");
|
|
183
306
|
const configState = fields[9];
|
|
184
307
|
const value = decode(fields[10]).trim();
|
|
@@ -214,6 +337,9 @@ function publish(ctx, pending, generation, baseline) {
|
|
|
214
337
|
}));
|
|
215
338
|
}
|
|
216
339
|
|
|
340
|
+
// src/scope.ts
|
|
341
|
+
var scopePattern = /^([a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(.+)$/;
|
|
342
|
+
|
|
217
343
|
// src/config.ts
|
|
218
344
|
function parseConfig(options) {
|
|
219
345
|
if (options === undefined) {
|
|
@@ -241,6 +367,9 @@ function parseConfig(options) {
|
|
|
241
367
|
if (!isJSONString(item) || item.trim().length === 0) {
|
|
242
368
|
throw new Error("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
|
|
243
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
|
+
}
|
|
244
373
|
scopes.push(item.trim());
|
|
245
374
|
}
|
|
246
375
|
allowedScopes = scopes.length > 0 ? scopes : undefined;
|
|
@@ -312,14 +441,15 @@ var commitLongOptionsWithArg = new Set([
|
|
|
312
441
|
"--reedit-message",
|
|
313
442
|
"--reuse-message",
|
|
314
443
|
"--squash",
|
|
315
|
-
"--template"
|
|
316
|
-
"--trailer"
|
|
444
|
+
"--template"
|
|
317
445
|
]);
|
|
318
446
|
function isWordSeparator(character) {
|
|
319
447
|
return character === " " || character === "\t" || character === "\r" || character === `
|
|
320
448
|
` || character === ";" || character === "&" || character === "|" || character === "(" || character === ")" || character === "{" || character === "}";
|
|
321
449
|
}
|
|
322
|
-
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.");
|
|
323
453
|
let depth = 1;
|
|
324
454
|
let quote;
|
|
325
455
|
let i = start + 2;
|
|
@@ -341,7 +471,7 @@ function consumeCommandSubstitution(command, start) {
|
|
|
341
471
|
quote = undefined;
|
|
342
472
|
i++;
|
|
343
473
|
} else if (character === "$" && command[i + 1] === "(") {
|
|
344
|
-
i = consumeCommandSubstitution(command, i).end;
|
|
474
|
+
i = consumeCommandSubstitution(command, i, nesting + 1).end;
|
|
345
475
|
} else {
|
|
346
476
|
i++;
|
|
347
477
|
}
|
|
@@ -373,7 +503,7 @@ function consumeCommandSubstitution(command, start) {
|
|
|
373
503
|
continue;
|
|
374
504
|
}
|
|
375
505
|
if (character === "$" && command[i + 1] === "(") {
|
|
376
|
-
i = consumeCommandSubstitution(command, i).end;
|
|
506
|
+
i = consumeCommandSubstitution(command, i, nesting + 1).end;
|
|
377
507
|
atWordStart = false;
|
|
378
508
|
continue;
|
|
379
509
|
}
|
|
@@ -396,14 +526,46 @@ function consumeCommandSubstitution(command, start) {
|
|
|
396
526
|
atWordStart = false;
|
|
397
527
|
i++;
|
|
398
528
|
}
|
|
399
|
-
|
|
529
|
+
throw new Error("Cannot parse shell substitution reliably. Run git commit directly.");
|
|
400
530
|
}
|
|
401
|
-
function
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
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];
|
|
406
539
|
}
|
|
540
|
+
throw new Error("Cannot parse backtick substitution reliably. Run git commit directly.");
|
|
541
|
+
}
|
|
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 };
|
|
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);
|
|
407
569
|
}
|
|
408
570
|
function heredocSubstitutions(body) {
|
|
409
571
|
const substitutions = [];
|
|
@@ -450,7 +612,7 @@ function tokenizeShell(command) {
|
|
|
450
612
|
i += 2;
|
|
451
613
|
continue;
|
|
452
614
|
}
|
|
453
|
-
if (character === "|" || character === ";" || character === "&" || character === `
|
|
615
|
+
if (character === "|" || character === ";" || character === "&" && command[i + 1] !== ">" || character === `
|
|
454
616
|
` || character === "(" || character === ")" || character === "{" || character === "}") {
|
|
455
617
|
tokens.push({ type: "operator", value: character });
|
|
456
618
|
i++;
|
|
@@ -465,9 +627,10 @@ function tokenizeShell(command) {
|
|
|
465
627
|
const end = lineEnd < 0 ? command.length : lineEnd;
|
|
466
628
|
const line = command.slice(i, end);
|
|
467
629
|
i = lineEnd < 0 ? end : end + 1;
|
|
468
|
-
if (line === heredoc.delimiter) {
|
|
630
|
+
if ((heredoc.stripTabs ? line.replace(/^\t+/, "") : line) === heredoc.delimiter) {
|
|
469
631
|
complete = true;
|
|
470
|
-
const
|
|
632
|
+
const rawBody = command.slice(bodyStart, i - (line.length + (lineEnd < 0 ? 0 : 1)));
|
|
633
|
+
const body = heredoc.stripTabs ? rawBody.replace(/^\t+/gm, "") : rawBody;
|
|
471
634
|
tokens[heredoc.index] = {
|
|
472
635
|
...tokens[heredoc.index],
|
|
473
636
|
heredoc: { body, quoted: heredoc.quoted },
|
|
@@ -484,17 +647,19 @@ function tokenizeShell(command) {
|
|
|
484
647
|
}
|
|
485
648
|
continue;
|
|
486
649
|
}
|
|
487
|
-
const redirectMatch = command.slice(i).match(/^(
|
|
650
|
+
const redirectMatch = command.slice(i).match(/^(?:\d+)?(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)|^&>>?/);
|
|
488
651
|
if (redirectMatch !== null && redirectMatch[0] !== undefined) {
|
|
489
652
|
tokens.push({ type: "redirect", value: redirectMatch[0] });
|
|
490
|
-
if (/^\d
|
|
653
|
+
if (/^\d*<<-?$/.test(redirectMatch[0]))
|
|
491
654
|
pendingDelimiter = tokens.length - 1;
|
|
492
655
|
i += redirectMatch[0].length;
|
|
493
656
|
continue;
|
|
494
657
|
}
|
|
495
658
|
let value = "";
|
|
659
|
+
const wordBytes = [];
|
|
496
660
|
let quoted = false;
|
|
497
661
|
let unsupportedDelimiter = false;
|
|
662
|
+
let expansion = false;
|
|
498
663
|
const substitutions = [];
|
|
499
664
|
while (i < command.length) {
|
|
500
665
|
const current = command[i];
|
|
@@ -517,40 +682,36 @@ function tokenizeShell(command) {
|
|
|
517
682
|
continue;
|
|
518
683
|
}
|
|
519
684
|
if (current === "$" && command[i + 1] === "'") {
|
|
685
|
+
wordBytes.push(...Buffer.from(value));
|
|
686
|
+
value = "";
|
|
520
687
|
quoted = true;
|
|
521
688
|
unsupportedDelimiter = true;
|
|
522
689
|
i += 2;
|
|
690
|
+
const bytes = [];
|
|
691
|
+
let complete = false;
|
|
523
692
|
while (i < command.length) {
|
|
524
693
|
const ansiCharacter = command[i];
|
|
525
694
|
if (ansiCharacter === undefined)
|
|
526
695
|
break;
|
|
527
696
|
if (ansiCharacter === "'") {
|
|
528
697
|
i++;
|
|
698
|
+
complete = true;
|
|
529
699
|
break;
|
|
530
700
|
}
|
|
531
701
|
if (ansiCharacter === "\\" && i + 1 < command.length) {
|
|
532
|
-
const escaped = command
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
`;
|
|
536
|
-
else if (escaped === "t")
|
|
537
|
-
value += "\t";
|
|
538
|
-
else if (escaped === "r")
|
|
539
|
-
value += "\r";
|
|
540
|
-
else if (escaped === "\\")
|
|
541
|
-
value += "\\";
|
|
542
|
-
else if (escaped === "'")
|
|
543
|
-
value += "'";
|
|
544
|
-
else if (escaped === '"')
|
|
545
|
-
value += '"';
|
|
546
|
-
else
|
|
547
|
-
value += escaped;
|
|
548
|
-
i += 2;
|
|
702
|
+
const escaped = ansiEscape(command, i);
|
|
703
|
+
bytes.push(...escaped.byte === undefined ? Buffer.from(escaped.content) : [escaped.byte]);
|
|
704
|
+
i = escaped.end;
|
|
549
705
|
} else {
|
|
550
|
-
|
|
551
|
-
|
|
706
|
+
const literal = String.fromCodePoint(command.codePointAt(i));
|
|
707
|
+
bytes.push(...Buffer.from(literal));
|
|
708
|
+
i += literal.length;
|
|
552
709
|
}
|
|
553
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));
|
|
554
715
|
continue;
|
|
555
716
|
}
|
|
556
717
|
if (current === "'") {
|
|
@@ -560,8 +721,9 @@ function tokenizeShell(command) {
|
|
|
560
721
|
value += command[i];
|
|
561
722
|
i++;
|
|
562
723
|
}
|
|
563
|
-
if (command[i]
|
|
564
|
-
|
|
724
|
+
if (command[i] !== "'")
|
|
725
|
+
throw new Error("Cannot parse shell quotes reliably. Run git commit directly.");
|
|
726
|
+
i++;
|
|
565
727
|
continue;
|
|
566
728
|
}
|
|
567
729
|
if (current === '"') {
|
|
@@ -587,35 +749,58 @@ function tokenizeShell(command) {
|
|
|
587
749
|
const substitution = consumeCommandSubstitution(command, i);
|
|
588
750
|
value += command.slice(i, substitution.end);
|
|
589
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;
|
|
590
759
|
i = substitution.end;
|
|
591
760
|
} else {
|
|
761
|
+
if (quotedCharacter === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? ""))
|
|
762
|
+
expansion = true;
|
|
592
763
|
value += quotedCharacter;
|
|
593
764
|
i++;
|
|
594
765
|
}
|
|
595
766
|
}
|
|
596
|
-
if (command[i]
|
|
597
|
-
|
|
767
|
+
if (command[i] !== '"')
|
|
768
|
+
throw new Error("Cannot parse shell quotes reliably. Run git commit directly.");
|
|
769
|
+
i++;
|
|
598
770
|
continue;
|
|
599
771
|
}
|
|
600
772
|
if (current === "$" && command[i + 1] === "(") {
|
|
601
773
|
const substitution = consumeCommandSubstitution(command, i);
|
|
602
774
|
value += command.slice(i, substitution.end);
|
|
603
775
|
substitutions.push(substitution.content);
|
|
776
|
+
expansion = true;
|
|
604
777
|
i = substitution.end;
|
|
605
778
|
continue;
|
|
606
779
|
}
|
|
607
|
-
|
|
780
|
+
if (current === "`") {
|
|
781
|
+
const substitution = consumeBackticks(command, i);
|
|
782
|
+
value += command.slice(i, substitution.end);
|
|
783
|
+
substitutions.push(substitution.content);
|
|
784
|
+
expansion = true;
|
|
785
|
+
i = substitution.end;
|
|
786
|
+
continue;
|
|
787
|
+
}
|
|
788
|
+
if (current === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? ""))
|
|
789
|
+
expansion = true;
|
|
790
|
+
const nextRedirect = command.slice(i).match(/^(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)/);
|
|
608
791
|
if (nextRedirect !== null)
|
|
609
792
|
break;
|
|
610
793
|
value += current;
|
|
611
794
|
i++;
|
|
612
795
|
}
|
|
613
|
-
|
|
796
|
+
if (wordBytes.length > 0)
|
|
797
|
+
value = Buffer.from([...wordBytes, ...Buffer.from(value)]).toString("utf8");
|
|
798
|
+
pushWord(tokens, value, substitutions, expansion);
|
|
614
799
|
if (pendingDelimiter !== undefined) {
|
|
615
800
|
if (unsupportedDelimiter) {
|
|
616
801
|
throw new Error("Cannot validate an ANSI-C quoted heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.");
|
|
617
802
|
}
|
|
618
|
-
pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted });
|
|
803
|
+
pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted, stripTabs: tokens[pendingDelimiter]?.value.endsWith("-") === true });
|
|
619
804
|
pendingDelimiter = undefined;
|
|
620
805
|
}
|
|
621
806
|
}
|
|
@@ -651,14 +836,14 @@ function extractCommandWords(tokens) {
|
|
|
651
836
|
if (token === undefined)
|
|
652
837
|
break;
|
|
653
838
|
if (token.type === "redirect") {
|
|
654
|
-
if (
|
|
839
|
+
if (tokens[i + 1]?.type === "word")
|
|
655
840
|
i += 2;
|
|
656
841
|
else
|
|
657
842
|
i++;
|
|
658
843
|
continue;
|
|
659
844
|
}
|
|
660
845
|
if (token.type === "word") {
|
|
661
|
-
words.push(token
|
|
846
|
+
words.push(token);
|
|
662
847
|
}
|
|
663
848
|
i++;
|
|
664
849
|
}
|
|
@@ -739,7 +924,7 @@ function findCommandStart(words) {
|
|
|
739
924
|
}
|
|
740
925
|
return index;
|
|
741
926
|
}
|
|
742
|
-
function extractInvocation(words, commandStart) {
|
|
927
|
+
function extractInvocation(words, commandStart, wordTokens) {
|
|
743
928
|
let wordIndex = commandStart;
|
|
744
929
|
const executable = words[wordIndex];
|
|
745
930
|
if (executable === undefined || executable !== "git" && !executable.endsWith("/git"))
|
|
@@ -792,6 +977,8 @@ function extractInvocation(words, commandStart) {
|
|
|
792
977
|
let hasNoEdit = false;
|
|
793
978
|
let isFixup = false;
|
|
794
979
|
let isHelp = false;
|
|
980
|
+
let messageExpansion = false;
|
|
981
|
+
let hasTrailer = false;
|
|
795
982
|
const collectMessage = (word) => {
|
|
796
983
|
if (word === undefined)
|
|
797
984
|
return;
|
|
@@ -824,8 +1011,10 @@ function extractInvocation(words, commandStart) {
|
|
|
824
1011
|
hasSignoffFlag = false;
|
|
825
1012
|
} else if (argument === "-m" || argument === "--message") {
|
|
826
1013
|
index++;
|
|
1014
|
+
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
827
1015
|
collectMessage(words[index]);
|
|
828
1016
|
} else if (argument.startsWith("--message=")) {
|
|
1017
|
+
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
829
1018
|
collectMessage(argument.slice("--message=".length));
|
|
830
1019
|
} else if (argument === "-F" || argument === "--file") {
|
|
831
1020
|
index++;
|
|
@@ -836,6 +1025,10 @@ function extractInvocation(words, commandStart) {
|
|
|
836
1025
|
isFixup = true;
|
|
837
1026
|
if (equalsIndex < 0)
|
|
838
1027
|
index++;
|
|
1028
|
+
} else if (longOptionName === "--trailer") {
|
|
1029
|
+
hasTrailer = true;
|
|
1030
|
+
if (equalsIndex < 0)
|
|
1031
|
+
index++;
|
|
839
1032
|
} else if (commitLongOptionsWithArg.has(longOptionName)) {
|
|
840
1033
|
if (equalsIndex < 0)
|
|
841
1034
|
index++;
|
|
@@ -851,9 +1044,10 @@ function extractInvocation(words, commandStart) {
|
|
|
851
1044
|
} else if (option === "m" || option === "F") {
|
|
852
1045
|
const attached = argument.slice(characterIndex + 1);
|
|
853
1046
|
const input = attached.length > 0 ? attached : words[++index];
|
|
854
|
-
if (option === "m")
|
|
1047
|
+
if (option === "m") {
|
|
1048
|
+
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
855
1049
|
collectMessage(input);
|
|
856
|
-
else
|
|
1050
|
+
} else
|
|
857
1051
|
collectFile(input);
|
|
858
1052
|
break;
|
|
859
1053
|
} else if (option === "S") {
|
|
@@ -876,18 +1070,52 @@ function extractInvocation(words, commandStart) {
|
|
|
876
1070
|
hasNoEdit,
|
|
877
1071
|
isFixup,
|
|
878
1072
|
isHelp,
|
|
879
|
-
targetError
|
|
1073
|
+
targetError,
|
|
1074
|
+
messageExpansion,
|
|
1075
|
+
hasTrailer
|
|
880
1076
|
};
|
|
881
1077
|
}
|
|
882
|
-
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.");
|
|
883
1081
|
const tokens = tokenizeShell(command);
|
|
884
1082
|
const invocations = [];
|
|
885
1083
|
let changedDirectory = inheritedDirectoryChange;
|
|
886
1084
|
for (const simple of splitSimpleCommands(tokens)) {
|
|
887
1085
|
const commandTokens = simple.tokens;
|
|
888
|
-
const
|
|
1086
|
+
const wordTokens = extractCommandWords(commandTokens);
|
|
1087
|
+
const words = wordTokens.map((token) => token.value);
|
|
889
1088
|
const commandStart = findCommandStart(words);
|
|
890
|
-
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
|
+
}
|
|
891
1119
|
if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment))
|
|
892
1120
|
changedDirectory = true;
|
|
893
1121
|
if (invocation !== undefined) {
|
|
@@ -921,14 +1149,13 @@ function extractGitCommits(command, inheritedDirectoryChange = false) {
|
|
|
921
1149
|
}
|
|
922
1150
|
for (const token of tokens) {
|
|
923
1151
|
for (const substitution of token.substitutions ?? []) {
|
|
924
|
-
invocations.push(...extractGitCommits(substitution, changedDirectory));
|
|
1152
|
+
invocations.push(...extractGitCommits(substitution, changedDirectory, depth + 1));
|
|
925
1153
|
}
|
|
926
1154
|
}
|
|
927
1155
|
return invocations;
|
|
928
1156
|
}
|
|
929
1157
|
|
|
930
1158
|
// src/validator.ts
|
|
931
|
-
var scopePattern = /^([a-zA-Z0-9_\-./]+(?:\([a-zA-Z0-9_\-./]+\))?):\s+(.+)$/;
|
|
932
1159
|
var signoffPattern = /^\s*Signed-off-by:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/i;
|
|
933
1160
|
function hasSignoffTrailer(lines) {
|
|
934
1161
|
const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
|
|
@@ -943,43 +1170,45 @@ function validateAllowedScope(rawScope, allowedScopes) {
|
|
|
943
1170
|
return;
|
|
944
1171
|
return `Scope "${rawScope}" is not in the allowed scopes list. Allowed scopes: ${allowedScopes.join(", ")}.`;
|
|
945
1172
|
}
|
|
946
|
-
function createCommitGuardError(violations,
|
|
1173
|
+
function createCommitGuardError(violations, config) {
|
|
947
1174
|
const header = "[commit-guard] Git commit rejected: commit message format rules violated.";
|
|
948
1175
|
const violationText = violations.map((v, i) => `${i + 1}. ${v}`).join(`
|
|
949
1176
|
|
|
950
1177
|
`);
|
|
951
|
-
const
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
' git commit -m "feat(parser): add subshell support" -m "Signed-off-by: Developer <dev@example.com>"'
|
|
956
|
-
].join(`
|
|
957
|
-
`);
|
|
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.'`;
|
|
958
1182
|
return new Error(`${header}
|
|
959
1183
|
|
|
960
1184
|
Violations:
|
|
961
1185
|
${violationText}
|
|
962
1186
|
|
|
963
|
-
${examples}
|
|
964
|
-
|
|
965
|
-
Command attempted:
|
|
966
|
-
${originalCommand}`);
|
|
1187
|
+
${examples}`);
|
|
967
1188
|
}
|
|
968
|
-
function validateGitCommits(invocations, config,
|
|
1189
|
+
function validateGitCommits(invocations, config, _originalCommand) {
|
|
969
1190
|
const allViolations = [];
|
|
970
1191
|
for (const invocation of invocations) {
|
|
971
1192
|
if (invocation.isHelp) {
|
|
972
1193
|
continue;
|
|
973
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
|
+
}
|
|
974
1203
|
const collectedMessages = [...invocation.messages];
|
|
975
1204
|
const filePath = invocation.filePaths.at(-1);
|
|
976
1205
|
if (filePath !== undefined) {
|
|
977
1206
|
if (filePath !== "-" || invocation.filePaths.length !== 1) {
|
|
978
|
-
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.");
|
|
979
1208
|
continue;
|
|
980
1209
|
}
|
|
981
1210
|
if (invocation.stdinError !== undefined || invocation.stdinMessage === undefined || collectedMessages.length > 0) {
|
|
982
|
-
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.`);
|
|
983
1212
|
continue;
|
|
984
1213
|
}
|
|
985
1214
|
collectedMessages.push(invocation.stdinMessage);
|
|
@@ -1022,7 +1251,7 @@ function validateGitCommits(invocations, config, originalCommand) {
|
|
|
1022
1251
|
} else if (/^[^:]+:\s*$/.test(effectiveSubject)) {
|
|
1023
1252
|
allViolations.push(`Subject text after colon is empty in "${subjectLine}". Expected format: "<scope>: <subject>".`);
|
|
1024
1253
|
} else {
|
|
1025
|
-
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.`);
|
|
1026
1255
|
}
|
|
1027
1256
|
}
|
|
1028
1257
|
}
|
|
@@ -1038,7 +1267,8 @@ function validateGitCommits(invocations, config, originalCommand) {
|
|
|
1038
1267
|
const details = overlongLines.map((l) => ` - Line ${l.lineNumber} (${l.length} chars, max ${config.maxLineLength}): "${l.text}"`).join(`
|
|
1039
1268
|
`);
|
|
1040
1269
|
allViolations.push(`Commit message exceeds maximum line length of ${config.maxLineLength} characters:
|
|
1041
|
-
${details}
|
|
1270
|
+
${details}
|
|
1271
|
+
Each -m becomes one paragraph line. Wrap with real newlines inside $'...'; "\\n" inside double quotes stays literal.`);
|
|
1042
1272
|
}
|
|
1043
1273
|
}
|
|
1044
1274
|
if (config.enforceSignoff) {
|
|
@@ -1049,7 +1279,7 @@ ${details}`);
|
|
|
1049
1279
|
}
|
|
1050
1280
|
}
|
|
1051
1281
|
if (allViolations.length > 0) {
|
|
1052
|
-
throw createCommitGuardError(allViolations,
|
|
1282
|
+
throw createCommitGuardError(allViolations.slice(0, 10).map((text) => text.slice(0, 2048)), config);
|
|
1053
1283
|
}
|
|
1054
1284
|
}
|
|
1055
1285
|
|
|
@@ -1063,61 +1293,111 @@ var plugin = Plugin.define({
|
|
|
1063
1293
|
const generation = randomUUID2();
|
|
1064
1294
|
const pending = new Map;
|
|
1065
1295
|
const preparing = new Set;
|
|
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
|
+
});
|
|
1066
1315
|
yield* Effect2.addFinalizer(() => Effect2.gen(function* () {
|
|
1067
1316
|
for (const attempt of pending.values()) {
|
|
1068
1317
|
cleanup(attempt);
|
|
1069
|
-
yield*
|
|
1318
|
+
yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication");
|
|
1319
|
+
yield* invalidateOwned(ctx, attempt);
|
|
1070
1320
|
}
|
|
1071
1321
|
pending.clear();
|
|
1072
1322
|
}));
|
|
1073
1323
|
yield* ctx.tool.transform((editor) => editor.add({
|
|
1074
1324
|
name: "commit_context",
|
|
1075
|
-
description:
|
|
1076
|
-
|
|
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.`,
|
|
1339
|
+
input: {
|
|
1340
|
+
type: "object",
|
|
1341
|
+
properties: {
|
|
1342
|
+
refresh: { type: "boolean" },
|
|
1343
|
+
workdir: { type: "string", description: "Working directory of the Git repository relative to the session directory or absolute." },
|
|
1344
|
+
directory: { type: "string", description: "Path to the Git repository checkout (alias for workdir)." }
|
|
1345
|
+
},
|
|
1346
|
+
additionalProperties: false
|
|
1347
|
+
},
|
|
1077
1348
|
execute: (input, toolContext) => Effect2.gen(function* () {
|
|
1349
|
+
yield* sweep();
|
|
1078
1350
|
if (ctx.location.workspaceID !== undefined)
|
|
1079
1351
|
return { content: "Commit context capture is unavailable for remote workspaces." };
|
|
1080
1352
|
const session = yield* ctx.session.get({ sessionID: toolContext.sessionID });
|
|
1081
|
-
if (session.location.
|
|
1082
|
-
return { content: "
|
|
1353
|
+
if (session.location.workspaceID !== ctx.location.workspaceID) {
|
|
1354
|
+
return { content: "Commit context capture is unavailable for remote workspaces." };
|
|
1083
1355
|
}
|
|
1084
|
-
const
|
|
1356
|
+
const request = input;
|
|
1357
|
+
const requestedDir = isJSONString(request.workdir) ? request.workdir : isJSONString(request.directory) ? request.directory : undefined;
|
|
1358
|
+
const sessionDirectory = session.location.directory ?? ctx.location.directory;
|
|
1359
|
+
let target = resolveTargetWorkdir(sessionDirectory, requestedDir);
|
|
1360
|
+
if (target.workdir === undefined && requestedDir === undefined) {
|
|
1361
|
+
const remembered = lastSessionWorkdir.get(toolContext.sessionID);
|
|
1362
|
+
if (remembered !== undefined && existsSync2(remembered) && findGitRoot(remembered) !== undefined) {
|
|
1363
|
+
target = { workdir: remembered };
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
if (target.error !== undefined || target.workdir === undefined) {
|
|
1367
|
+
return { content: target.error ?? "Could not determine target Git repository." };
|
|
1368
|
+
}
|
|
1369
|
+
const targetWorkdir = target.workdir;
|
|
1370
|
+
lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir);
|
|
1371
|
+
const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir);
|
|
1085
1372
|
if (preparing.has(scope))
|
|
1086
|
-
return { content: "A commit context capture is preparing for this session.
|
|
1373
|
+
return { content: "A commit context capture is preparing for this session and checkout. Wait for its command, then follow its instructions." };
|
|
1087
1374
|
preparing.add(scope);
|
|
1088
1375
|
return yield* Effect2.gen(function* () {
|
|
1089
|
-
const request = input;
|
|
1090
1376
|
const previous = pending.get(scope);
|
|
1091
1377
|
if (previous !== undefined) {
|
|
1092
|
-
if (
|
|
1093
|
-
return { content:
|
|
1094
|
-
|
|
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. ") };
|
|
1383
|
+
}
|
|
1095
1384
|
pending.delete(scope);
|
|
1096
1385
|
cleanup(previous);
|
|
1097
|
-
yield*
|
|
1386
|
+
yield* recordState(ctx, previous, "failed", "capture replaced by refresh");
|
|
1387
|
+
yield* invalidateOwned(ctx, previous);
|
|
1098
1388
|
}
|
|
1099
1389
|
if (request.refresh !== true) {
|
|
1100
1390
|
const baseline = yield* load(ctx, scope);
|
|
1101
|
-
if (baseline !== undefined && baseline.
|
|
1102
|
-
|
|
1103
|
-
`)[0]?.match(/^([a-zA-Z0-9_./-]{1,40}): /)?.[1]).filter((value) => value !== undefined))].slice(0, 3);
|
|
1104
|
-
const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
|
|
1105
|
-
` : "";
|
|
1106
|
-
const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." : `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`;
|
|
1107
|
-
return { content: `Frozen commit baseline for ${ctx.location.directory}.
|
|
1108
|
-
` + `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.
|
|
1109
|
-
` + `${scopes}
|
|
1110
|
-
${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"}.
|
|
1111
|
-
` + "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) };
|
|
1112
1393
|
}
|
|
1113
1394
|
}
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
const count = yield* counter(ctx, scope);
|
|
1117
|
-
const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, ctx.location.directory));
|
|
1395
|
+
const count = yield* invalidate(ctx, scope);
|
|
1396
|
+
const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, targetWorkdir));
|
|
1118
1397
|
pending.set(scope, attempt);
|
|
1119
|
-
|
|
1120
|
-
|
|
1398
|
+
const status = failures.get(scope) ?? (yield* captureStatus(ctx, scope));
|
|
1399
|
+
yield* recordState(ctx, attempt, "prepared");
|
|
1400
|
+
return { content: captureInstructions(attempt, status) };
|
|
1121
1401
|
}).pipe(Effect2.ensuring(Effect2.sync(() => {
|
|
1122
1402
|
preparing.delete(scope);
|
|
1123
1403
|
})));
|
|
@@ -1125,14 +1405,10 @@ ${attempt.command}` };
|
|
|
1125
1405
|
message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout."
|
|
1126
1406
|
})))
|
|
1127
1407
|
}));
|
|
1128
|
-
yield* ctx.shell.hook("create.before", (event) => Effect2.sync(() => {
|
|
1129
|
-
for (const attempt of pending.values()) {
|
|
1130
|
-
if (attempt.claimed !== undefined && event.command === attempt.command && event.cwd === attempt.workdir) {
|
|
1131
|
-
attempt.expires = Date.now() + captureTimeout;
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
|
-
}));
|
|
1135
1408
|
yield* ctx.tool.hook("execute.before", (event) => Effect2.gen(function* () {
|
|
1409
|
+
yield* sweep();
|
|
1410
|
+
const captureSession = event.tool === "shell" || event.tool === "bash" ? yield* ctx.session.get({ sessionID: event.sessionID }) : undefined;
|
|
1411
|
+
const captureSessionDirectory = captureSession?.location.directory ?? ctx.location.directory;
|
|
1136
1412
|
const parsed = yield* Effect2.try({
|
|
1137
1413
|
try: () => {
|
|
1138
1414
|
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
@@ -1146,47 +1422,70 @@ ${attempt.command}` };
|
|
|
1146
1422
|
if (!isJSONString(command)) {
|
|
1147
1423
|
return;
|
|
1148
1424
|
}
|
|
1425
|
+
const rawWorkdir = rawInput["workdir"];
|
|
1149
1426
|
for (const attempt of pending.values()) {
|
|
1150
1427
|
if (command !== attempt.command)
|
|
1151
1428
|
continue;
|
|
1152
|
-
|
|
1429
|
+
const matchesWorkdir = rawWorkdir === attempt.workdir || isJSONString(rawWorkdir) && resolve2(captureSessionDirectory, rawWorkdir) === attempt.workdir || rawWorkdir === undefined && captureSessionDirectory === attempt.workdir;
|
|
1430
|
+
if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || !matchesWorkdir || rawInput["background"] === true || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
|
|
1153
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.");
|
|
1154
1432
|
}
|
|
1155
1433
|
attempt.claimed = { messageID: event.messageID, id: event.id };
|
|
1156
|
-
attempt.expires = Date.now() + captureTimeout;
|
|
1157
1434
|
return;
|
|
1158
1435
|
}
|
|
1159
1436
|
const invocations = extractGitCommits(command);
|
|
1160
1437
|
if (invocations.length === 0) {
|
|
1161
1438
|
return;
|
|
1162
1439
|
}
|
|
1163
|
-
validateGitCommits(invocations, { ...config, enforceSignoff: false }, command);
|
|
1164
1440
|
return { invocations, command, rawInput };
|
|
1165
1441
|
},
|
|
1166
1442
|
catch: (error) => new Tool.Error({
|
|
1167
1443
|
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
|
|
1168
1444
|
})
|
|
1169
1445
|
});
|
|
1170
|
-
|
|
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))
|
|
1171
1451
|
return;
|
|
1172
1452
|
if (ctx.location.workspaceID !== undefined)
|
|
1173
1453
|
return yield* Effect2.fail(new Tool.Error({
|
|
1174
1454
|
message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."
|
|
1175
1455
|
}));
|
|
1176
1456
|
const session = yield* ctx.session.get({ sessionID: event.sessionID });
|
|
1177
|
-
if (session.location.
|
|
1178
|
-
return yield* Effect2.fail(new Tool.Error({
|
|
1457
|
+
if (session.location.workspaceID !== ctx.location.workspaceID || parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
|
|
1458
|
+
return yield* Effect2.fail(new Tool.Error({
|
|
1459
|
+
message: "[commit-guard] Commit target is ambiguous. Use a direct git commit without -C, Git directory/configuration flags, environment overrides, or cd wrappers. Set shell workdir to the captured checkout and call commit_context there."
|
|
1460
|
+
}));
|
|
1179
1461
|
}
|
|
1180
|
-
const
|
|
1181
|
-
|
|
1182
|
-
|
|
1462
|
+
const sessionDirectory = session.location.directory ?? ctx.location.directory;
|
|
1463
|
+
const rawWorkdir = parsed.rawInput["workdir"];
|
|
1464
|
+
const effectiveWorkdir = yield* Effect2.try(() => realpathSync2(isJSONString(rawWorkdir) ? resolve2(sessionDirectory, rawWorkdir) : sessionDirectory));
|
|
1465
|
+
const targetGitRoot = findGitRoot(effectiveWorkdir);
|
|
1466
|
+
const scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir);
|
|
1467
|
+
const baseline = yield* load(ctx, scope);
|
|
1468
|
+
const expectedDir = targetGitRoot ?? effectiveWorkdir;
|
|
1469
|
+
const baselineValid = baseline !== undefined && targetGitRoot !== undefined && baseline.directory === targetGitRoot && baseline.directory === expectedDir;
|
|
1470
|
+
if (!baselineValid || baseline === undefined) {
|
|
1471
|
+
const relWorkdir = relative2(sessionDirectory, expectedDir);
|
|
1472
|
+
const workdirHint = JSON.stringify(relWorkdir.length > 0 ? relWorkdir : ".");
|
|
1473
|
+
return yield* Effect2.fail(new Tool.Error({
|
|
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.`
|
|
1475
|
+
}));
|
|
1183
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
|
+
}));
|
|
1184
1481
|
yield* Effect2.try({
|
|
1185
1482
|
try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
|
|
1186
|
-
catch: (error) => new Tool.Error({
|
|
1483
|
+
catch: (error) => new Tool.Error({
|
|
1484
|
+
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
|
|
1485
|
+
})
|
|
1187
1486
|
});
|
|
1188
1487
|
}).pipe(Effect2.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
|
|
1189
|
-
message: "[commit-guard]
|
|
1488
|
+
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
|
|
1190
1489
|
}))));
|
|
1191
1490
|
yield* ctx.tool.hook("execute.after", (event) => Effect2.gen(function* () {
|
|
1192
1491
|
if (event.tool !== "shell")
|
|
@@ -1195,10 +1494,17 @@ ${attempt.command}` };
|
|
|
1195
1494
|
if (attempt === undefined)
|
|
1196
1495
|
return;
|
|
1197
1496
|
let published = false;
|
|
1497
|
+
let captured;
|
|
1498
|
+
let reason = "capture import or storage failed";
|
|
1198
1499
|
yield* Effect2.gen(function* () {
|
|
1199
|
-
|
|
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)
|
|
1200
1505
|
return;
|
|
1201
1506
|
const metadata = event.result.metadata;
|
|
1507
|
+
reason = "shell result lacks verified foreground completion metadata";
|
|
1202
1508
|
if (!isRecord(metadata))
|
|
1203
1509
|
return;
|
|
1204
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)))
|
|
@@ -1206,23 +1512,77 @@ ${attempt.command}` };
|
|
|
1206
1512
|
const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {
|
|
1207
1513
|
return;
|
|
1208
1514
|
});
|
|
1209
|
-
|
|
1515
|
+
reason = "capture session or workspace no longer matches";
|
|
1516
|
+
if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID)
|
|
1210
1517
|
return;
|
|
1518
|
+
reason = "private artifact is invalid or incomplete (END required)";
|
|
1211
1519
|
const baseline = yield* Effect2.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") });
|
|
1212
|
-
if (baseline.workdir !==
|
|
1520
|
+
if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined)
|
|
1213
1521
|
return;
|
|
1522
|
+
reason = "capture storage failed or its counter changed";
|
|
1214
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
|
+
}
|
|
1215
1529
|
}).pipe(Effect2.onExit(() => Effect2.gen(function* () {
|
|
1216
1530
|
if (pending.get(attempt.scope) === attempt)
|
|
1217
1531
|
pending.delete(attempt.scope);
|
|
1218
|
-
if (!published)
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
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);
|
|
1222
1547
|
}));
|
|
1223
1548
|
})
|
|
1224
1549
|
});
|
|
1225
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
|
+
}
|
|
1226
1586
|
export {
|
|
1227
1587
|
plugin_default as default
|
|
1228
1588
|
};
|