opencode-commit-guard 1.0.2 → 1.0.4
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 +43 -12
- package/dist/index.js +499 -154
- package/package.json +7 -7
- package/src/capture.ts +250 -0
- package/src/config.ts +3 -10
- package/src/plugin.ts +177 -22
- package/src/shell.ts +155 -57
- package/src/types.ts +6 -5
- package/src/validator.ts +11 -105
package/dist/index.js
CHANGED
|
@@ -2,7 +2,15 @@
|
|
|
2
2
|
// src/plugin.ts
|
|
3
3
|
import { Plugin } from "@opencode/plugin/effect";
|
|
4
4
|
import { Tool } from "@opencode/schema/tool";
|
|
5
|
-
import { Effect } from "effect";
|
|
5
|
+
import { Effect as Effect2 } from "effect";
|
|
6
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
7
|
+
|
|
8
|
+
// src/capture.ts
|
|
9
|
+
import { createHash, randomUUID } from "crypto";
|
|
10
|
+
import { closeSync, constants, fstatSync, mkdtempSync, openSync, readSync, rmSync } from "fs";
|
|
11
|
+
import { tmpdir } from "os";
|
|
12
|
+
import { join, relative } from "path";
|
|
13
|
+
import { Effect, Semaphore } from "effect";
|
|
6
14
|
|
|
7
15
|
// src/types.ts
|
|
8
16
|
function isJSONString(value) {
|
|
@@ -21,9 +29,191 @@ var defaultConfig = {
|
|
|
21
29
|
requireScope: true,
|
|
22
30
|
allowedScopes: undefined,
|
|
23
31
|
maxLineLength: 72,
|
|
24
|
-
|
|
32
|
+
enforceSignoff: true
|
|
25
33
|
};
|
|
26
34
|
|
|
35
|
+
// src/capture.ts
|
|
36
|
+
var version = 1;
|
|
37
|
+
var maxBytes = 262144;
|
|
38
|
+
var captureTimeout = 20000;
|
|
39
|
+
var policy = "commit-guard-context-v1";
|
|
40
|
+
var storageLock = Semaphore.makeUnsafe(1);
|
|
41
|
+
function digest(text) {
|
|
42
|
+
return createHash("sha256").update(text).digest("hex");
|
|
43
|
+
}
|
|
44
|
+
function scopeFor(ctx, sessionID, config) {
|
|
45
|
+
const location = ctx.location;
|
|
46
|
+
return digest(JSON.stringify([
|
|
47
|
+
version,
|
|
48
|
+
location.project.id,
|
|
49
|
+
sessionID,
|
|
50
|
+
location.directory,
|
|
51
|
+
location.workspaceID ?? null,
|
|
52
|
+
policy,
|
|
53
|
+
config.requireScope,
|
|
54
|
+
config.allowedScopes ?? null,
|
|
55
|
+
config.maxLineLength
|
|
56
|
+
]));
|
|
57
|
+
}
|
|
58
|
+
function counterKey(scope) {
|
|
59
|
+
return `counter/${scope}`;
|
|
60
|
+
}
|
|
61
|
+
function prefix(scope) {
|
|
62
|
+
return `snap/${scope}/`;
|
|
63
|
+
}
|
|
64
|
+
function counter(ctx, scope) {
|
|
65
|
+
return Effect.gen(function* () {
|
|
66
|
+
const value = yield* ctx.storage.get(counterKey(scope));
|
|
67
|
+
if (value === undefined)
|
|
68
|
+
return 0;
|
|
69
|
+
return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : -1;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function invalidate(ctx, scope) {
|
|
73
|
+
return storageLock.withPermits(1)(Effect.gen(function* () {
|
|
74
|
+
const previous = yield* counter(ctx, scope);
|
|
75
|
+
yield* ctx.storage.set(counterKey(scope), previous < 0 ? 1 : previous + 1);
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
function validBaseline(value) {
|
|
79
|
+
if (!isRecord(value))
|
|
80
|
+
return false;
|
|
81
|
+
return ["directory", "workdir", "gitDir", "commonDir"].every((key) => isJSONString(value[key])) && (value["branch"] === null || isJSONString(value["branch"])) && (value["head"] === null || /^[0-9a-f]{40,64}$/.test(String(value["head"]))) && Array.isArray(value["messages"]) && value["messages"].length <= 10 && value["messages"].every((message) => isJSONString(message)) && ["true", "false", "unset", "error"].includes(String(value["gpgsign"])) && (value["signingkey"] === null || value["signingkey"] === "error" || isJSONString(value["signingkey"]));
|
|
82
|
+
}
|
|
83
|
+
function load(ctx, scope) {
|
|
84
|
+
return storageLock.withPermits(1)(Effect.gen(function* () {
|
|
85
|
+
const current = yield* counter(ctx, scope);
|
|
86
|
+
if (current < 0)
|
|
87
|
+
return;
|
|
88
|
+
let after;
|
|
89
|
+
let newest;
|
|
90
|
+
do {
|
|
91
|
+
const page = yield* ctx.storage.scan({ prefix: prefix(scope), after, limit: 100 });
|
|
92
|
+
for (const record of page.entries) {
|
|
93
|
+
const raw = record.value;
|
|
94
|
+
if (!isRecord(raw) || raw["schema"] !== version || raw["scope"] !== scope || raw["counter"] !== current || !isJSONString(raw["generation"]) || !isJSONString(raw["sequence"]) || !isJSONString(raw["checksum"]) || !validBaseline(raw["baseline"]))
|
|
95
|
+
continue;
|
|
96
|
+
const baseline = raw["baseline"];
|
|
97
|
+
if (digest(JSON.stringify([version, scope, current, raw["generation"], raw["sequence"], baseline])) !== raw["checksum"])
|
|
98
|
+
continue;
|
|
99
|
+
if (newest === undefined || raw["sequence"] > newest.sequence)
|
|
100
|
+
newest = { sequence: raw["sequence"], baseline };
|
|
101
|
+
}
|
|
102
|
+
after = page.next;
|
|
103
|
+
} while (after !== undefined);
|
|
104
|
+
return newest?.baseline;
|
|
105
|
+
}));
|
|
106
|
+
}
|
|
107
|
+
function captureCommand(path) {
|
|
108
|
+
const quoted = `'${path.replaceAll("'", "'\\''")}'`;
|
|
109
|
+
return `timeout 15s bash -c 'set -euo pipefail
|
|
110
|
+
ulimit -f 256
|
|
111
|
+
out=$1
|
|
112
|
+
printf "CTX1\\n" > "$out"
|
|
113
|
+
field() { "$@" 2>/dev/null | base64 -w0 >> "$out"; printf "\\n" >> "$out"; }
|
|
114
|
+
field git rev-parse --show-toplevel
|
|
115
|
+
field git rev-parse --absolute-git-dir
|
|
116
|
+
field git rev-parse --path-format=absolute --git-common-dir
|
|
117
|
+
if git symbolic-ref -q --short HEAD >/dev/null 2>&1; then printf "branch\\n" >> "$out"; field git symbolic-ref -q --short HEAD; else status=$?; if [ "$status" -ne 1 ]; then exit "$status"; fi; printf "detached\\n\\n" >> "$out"; fi
|
|
118
|
+
if git rev-parse --verify HEAD >/dev/null 2>&1; then printf "head\\n" >> "$out"; field git rev-parse --verify HEAD; field git log -10 -z --format=%B%x00; else status=$?; if [ "$status" -ne 128 ] || ! git symbolic-ref -q HEAD >/dev/null 2>&1 || ! git status --porcelain >/dev/null 2>&1; then exit 1; fi; printf "unborn\\n\\n\\n" >> "$out"; fi
|
|
119
|
+
if git config --type=bool --get commit.gpgsign >/dev/null 2>&1; then printf "set\\n" >> "$out"; field git config --type=bool --get commit.gpgsign; else status=$?; if [ "$status" -eq 1 ]; then printf "unset\\n\\n" >> "$out"; else printf "error\\n\\n" >> "$out"; fi; fi
|
|
120
|
+
if git config --get user.signingkey >/dev/null 2>&1; then printf "set\\n" >> "$out"; field git config --get user.signingkey; else status=$?; if [ "$status" -eq 1 ]; then printf "unset\\n\\n" >> "$out"; else printf "error\\n\\n" >> "$out"; fi; fi
|
|
121
|
+
printf "END\\n" >> "$out"
|
|
122
|
+
printf "RECEIPT_OK\\n"' bash ${quoted} 2>/dev/null`;
|
|
123
|
+
}
|
|
124
|
+
function createPending(scope, sessionID, agent, counterValue, workdir) {
|
|
125
|
+
const directory = mkdtempSync(join(tmpdir(), "commit-context-"));
|
|
126
|
+
try {
|
|
127
|
+
const file = join(directory, randomUUID());
|
|
128
|
+
const fd = openSync(file, constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_RDWR, 384);
|
|
129
|
+
const stat = fstatSync(fd);
|
|
130
|
+
return {
|
|
131
|
+
scope,
|
|
132
|
+
sessionID,
|
|
133
|
+
agent,
|
|
134
|
+
counter: counterValue,
|
|
135
|
+
directory,
|
|
136
|
+
workdir,
|
|
137
|
+
fd,
|
|
138
|
+
identity: { dev: stat.dev, ino: stat.ino, uid: stat.uid },
|
|
139
|
+
expires: Date.now() + captureTimeout,
|
|
140
|
+
command: captureCommand(file)
|
|
141
|
+
};
|
|
142
|
+
} catch (error) {
|
|
143
|
+
rmSync(directory, { recursive: true, force: true });
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function cleanup(pending) {
|
|
148
|
+
if (pending.closed === true)
|
|
149
|
+
return;
|
|
150
|
+
pending.closed = true;
|
|
151
|
+
closeSync(pending.fd);
|
|
152
|
+
rmSync(pending.directory, { recursive: true, force: true });
|
|
153
|
+
}
|
|
154
|
+
function decode(line) {
|
|
155
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(line))
|
|
156
|
+
throw new Error("Invalid capture framing");
|
|
157
|
+
return Buffer.from(line, "base64").toString("utf8");
|
|
158
|
+
}
|
|
159
|
+
function importCapture(pending) {
|
|
160
|
+
const stat = fstatSync(pending.fd);
|
|
161
|
+
if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino || stat.uid !== pending.identity.uid || (stat.mode & 511) !== 384 || stat.size > maxBytes || stat.size === 0) {
|
|
162
|
+
throw new Error("Invalid private capture artifact");
|
|
163
|
+
}
|
|
164
|
+
const bytes = Buffer.alloc(stat.size);
|
|
165
|
+
if (readSync(pending.fd, bytes, 0, stat.size, 0) !== stat.size)
|
|
166
|
+
throw new Error("Incomplete private capture artifact");
|
|
167
|
+
const completed = fstatSync(pending.fd);
|
|
168
|
+
if (completed.size !== stat.size || completed.dev !== stat.dev || completed.ino !== stat.ino)
|
|
169
|
+
throw new Error("Capture changed during import");
|
|
170
|
+
const fields = bytes.toString("utf8").split(`
|
|
171
|
+
`);
|
|
172
|
+
if (fields.length !== 15 || fields[0] !== "CTX1" || fields[13] !== "END" || fields[14] !== "")
|
|
173
|
+
throw new Error("Incomplete capture");
|
|
174
|
+
const root = decode(fields[1]).trimEnd();
|
|
175
|
+
const gitDir = decode(fields[2]).trimEnd();
|
|
176
|
+
const commonDir = decode(fields[3]).trimEnd();
|
|
177
|
+
const branch = fields[4] === "branch" ? decode(fields[5]).trimEnd() : null;
|
|
178
|
+
const head = fields[6] === "head" ? decode(fields[7]).trim() : null;
|
|
179
|
+
const rawLog = decode(fields[8]);
|
|
180
|
+
const messages = head === null ? [] : rawLog.split("\x00\x00").filter((message) => message.length > 0);
|
|
181
|
+
if (!root.startsWith("/") || !gitDir.startsWith("/") || !commonDir.startsWith("/") || relative(root, pending.workdir).startsWith("..") || !["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
|
+
throw new Error("Invalid Git baseline");
|
|
183
|
+
const configState = fields[9];
|
|
184
|
+
const value = decode(fields[10]).trim();
|
|
185
|
+
const gpgsign = configState === "set" && (value === "true" || value === "false") ? value : configState === "unset" ? "unset" : "error";
|
|
186
|
+
const signingkey = fields[11] === "set" ? decode(fields[12]).trim() : fields[11] === "unset" ? null : "error";
|
|
187
|
+
return { directory: root, workdir: pending.workdir, gitDir, commonDir, branch, head, messages, gpgsign, signingkey };
|
|
188
|
+
}
|
|
189
|
+
function publish(ctx, pending, generation, baseline) {
|
|
190
|
+
return storageLock.withPermits(1)(Effect.gen(function* () {
|
|
191
|
+
if ((yield* counter(ctx, pending.scope)) !== pending.counter)
|
|
192
|
+
return false;
|
|
193
|
+
const sequence = `${Date.now().toString().padStart(15, "0")}-${randomUUID()}`;
|
|
194
|
+
const checksum = digest(JSON.stringify([version, pending.scope, pending.counter, generation, sequence, baseline]));
|
|
195
|
+
yield* ctx.storage.set(prefix(pending.scope) + sequence, {
|
|
196
|
+
schema: version,
|
|
197
|
+
scope: pending.scope,
|
|
198
|
+
counter: pending.counter,
|
|
199
|
+
generation,
|
|
200
|
+
sequence,
|
|
201
|
+
checksum,
|
|
202
|
+
baseline: { ...baseline, messages: [...baseline.messages] }
|
|
203
|
+
});
|
|
204
|
+
let after;
|
|
205
|
+
do {
|
|
206
|
+
const page = yield* ctx.storage.scan({ prefix: prefix(pending.scope), after, limit: 100 });
|
|
207
|
+
for (const record of page.entries) {
|
|
208
|
+
if (record.key < prefix(pending.scope) + sequence)
|
|
209
|
+
yield* ctx.storage.remove(record.key);
|
|
210
|
+
}
|
|
211
|
+
after = page.next;
|
|
212
|
+
} while (after !== undefined);
|
|
213
|
+
return true;
|
|
214
|
+
}));
|
|
215
|
+
}
|
|
216
|
+
|
|
27
217
|
// src/config.ts
|
|
28
218
|
function parseConfig(options) {
|
|
29
219
|
if (options === undefined) {
|
|
@@ -63,19 +253,14 @@ function parseConfig(options) {
|
|
|
63
253
|
}
|
|
64
254
|
maxLineLength = rawMaxLineLength;
|
|
65
255
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
if (rawRequireSignoff !== undefined) {
|
|
69
|
-
if (!isJSONBoolean(rawRequireSignoff)) {
|
|
70
|
-
throw new Error("Invalid plugin option requireSignoff; expected a boolean.");
|
|
71
|
-
}
|
|
72
|
-
requireSignoff = rawRequireSignoff;
|
|
256
|
+
if (options["requireSignoff"] !== undefined) {
|
|
257
|
+
throw new Error("Plugin option requireSignoff has been removed; signoff follows the captured effective commit.gpgsign value.");
|
|
73
258
|
}
|
|
74
259
|
return {
|
|
75
260
|
requireScope,
|
|
76
261
|
allowedScopes,
|
|
77
262
|
maxLineLength,
|
|
78
|
-
|
|
263
|
+
enforceSignoff: defaultConfig.enforceSignoff
|
|
79
264
|
};
|
|
80
265
|
}
|
|
81
266
|
|
|
@@ -87,7 +272,8 @@ var gitGlobalOptionsWithArg = new Set([
|
|
|
87
272
|
"--work-tree",
|
|
88
273
|
"--namespace",
|
|
89
274
|
"--exec-path",
|
|
90
|
-
"--super-prefix"
|
|
275
|
+
"--super-prefix",
|
|
276
|
+
"--config-env"
|
|
91
277
|
]);
|
|
92
278
|
var commandPrefixes = new Set([
|
|
93
279
|
"!",
|
|
@@ -100,6 +286,23 @@ var commandPrefixes = new Set([
|
|
|
100
286
|
"until",
|
|
101
287
|
"while"
|
|
102
288
|
]);
|
|
289
|
+
var targetMutators = new Set([
|
|
290
|
+
"cd",
|
|
291
|
+
"pushd",
|
|
292
|
+
"popd",
|
|
293
|
+
"chdir",
|
|
294
|
+
"export",
|
|
295
|
+
"typeset",
|
|
296
|
+
"declare",
|
|
297
|
+
"source",
|
|
298
|
+
".",
|
|
299
|
+
"eval",
|
|
300
|
+
"set",
|
|
301
|
+
"unset",
|
|
302
|
+
"readonly",
|
|
303
|
+
"local",
|
|
304
|
+
"setenv"
|
|
305
|
+
]);
|
|
103
306
|
var commitLongOptionsWithArg = new Set([
|
|
104
307
|
"--author",
|
|
105
308
|
"--cleanup",
|
|
@@ -202,8 +405,25 @@ function pushWord(tokens, value, substitutions) {
|
|
|
202
405
|
tokens.push({ type: "word", value });
|
|
203
406
|
}
|
|
204
407
|
}
|
|
408
|
+
function heredocSubstitutions(body) {
|
|
409
|
+
const substitutions = [];
|
|
410
|
+
for (let i = 0;i < body.length; i++) {
|
|
411
|
+
if (body[i] === "\\" && (body[i + 1] === "$" || body[i + 1] === "`")) {
|
|
412
|
+
i++;
|
|
413
|
+
} else if (body[i] === "`") {
|
|
414
|
+
throw new Error("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.");
|
|
415
|
+
} else if (body[i] === "$" && body[i + 1] === "(") {
|
|
416
|
+
const substitution = consumeCommandSubstitution(body, i);
|
|
417
|
+
substitutions.push(substitution.content);
|
|
418
|
+
i = substitution.end - 1;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return substitutions;
|
|
422
|
+
}
|
|
205
423
|
function tokenizeShell(command) {
|
|
206
424
|
const tokens = [];
|
|
425
|
+
const pendingHeredocs = [];
|
|
426
|
+
let pendingDelimiter;
|
|
207
427
|
let i = 0;
|
|
208
428
|
while (i < command.length) {
|
|
209
429
|
const character = command[i];
|
|
@@ -234,15 +454,47 @@ function tokenizeShell(command) {
|
|
|
234
454
|
` || character === "(" || character === ")" || character === "{" || character === "}") {
|
|
235
455
|
tokens.push({ type: "operator", value: character });
|
|
236
456
|
i++;
|
|
457
|
+
if (character === `
|
|
458
|
+
` && pendingHeredocs.length > 0) {
|
|
459
|
+
for (const heredoc of pendingHeredocs) {
|
|
460
|
+
const bodyStart = i;
|
|
461
|
+
let complete = false;
|
|
462
|
+
while (i < command.length) {
|
|
463
|
+
const lineEnd = command.indexOf(`
|
|
464
|
+
`, i);
|
|
465
|
+
const end = lineEnd < 0 ? command.length : lineEnd;
|
|
466
|
+
const line = command.slice(i, end);
|
|
467
|
+
i = lineEnd < 0 ? end : end + 1;
|
|
468
|
+
if (line === heredoc.delimiter) {
|
|
469
|
+
complete = true;
|
|
470
|
+
const body = command.slice(bodyStart, i - (line.length + (lineEnd < 0 ? 0 : 1)));
|
|
471
|
+
tokens[heredoc.index] = {
|
|
472
|
+
...tokens[heredoc.index],
|
|
473
|
+
heredoc: { body, quoted: heredoc.quoted },
|
|
474
|
+
substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body)
|
|
475
|
+
};
|
|
476
|
+
break;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (!complete) {
|
|
480
|
+
throw new Error("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.");
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
pendingHeredocs.length = 0;
|
|
484
|
+
}
|
|
237
485
|
continue;
|
|
238
486
|
}
|
|
239
487
|
const redirectMatch = command.slice(i).match(/^(\d+)?(<<<|>>|<<|>&|<&|>\||>|<)(?:-|\d+)?/);
|
|
240
488
|
if (redirectMatch !== null && redirectMatch[0] !== undefined) {
|
|
241
489
|
tokens.push({ type: "redirect", value: redirectMatch[0] });
|
|
490
|
+
if (/^\d*<<$/.test(redirectMatch[0]))
|
|
491
|
+
pendingDelimiter = tokens.length - 1;
|
|
242
492
|
i += redirectMatch[0].length;
|
|
243
493
|
continue;
|
|
244
494
|
}
|
|
245
495
|
let value = "";
|
|
496
|
+
let quoted = false;
|
|
497
|
+
let unsupportedDelimiter = false;
|
|
246
498
|
const substitutions = [];
|
|
247
499
|
while (i < command.length) {
|
|
248
500
|
const current = command[i];
|
|
@@ -254,6 +506,7 @@ function tokenizeShell(command) {
|
|
|
254
506
|
continue;
|
|
255
507
|
}
|
|
256
508
|
if (current === "\\") {
|
|
509
|
+
quoted = true;
|
|
257
510
|
if (i + 1 < command.length) {
|
|
258
511
|
value += command[i + 1];
|
|
259
512
|
i += 2;
|
|
@@ -264,6 +517,8 @@ function tokenizeShell(command) {
|
|
|
264
517
|
continue;
|
|
265
518
|
}
|
|
266
519
|
if (current === "$" && command[i + 1] === "'") {
|
|
520
|
+
quoted = true;
|
|
521
|
+
unsupportedDelimiter = true;
|
|
267
522
|
i += 2;
|
|
268
523
|
while (i < command.length) {
|
|
269
524
|
const ansiCharacter = command[i];
|
|
@@ -299,6 +554,7 @@ function tokenizeShell(command) {
|
|
|
299
554
|
continue;
|
|
300
555
|
}
|
|
301
556
|
if (current === "'") {
|
|
557
|
+
quoted = true;
|
|
302
558
|
i++;
|
|
303
559
|
while (i < command.length && command[i] !== "'") {
|
|
304
560
|
value += command[i];
|
|
@@ -309,6 +565,7 @@ function tokenizeShell(command) {
|
|
|
309
565
|
continue;
|
|
310
566
|
}
|
|
311
567
|
if (current === '"') {
|
|
568
|
+
quoted = true;
|
|
312
569
|
i++;
|
|
313
570
|
while (i < command.length && command[i] !== '"') {
|
|
314
571
|
const quotedCharacter = command[i];
|
|
@@ -354,23 +611,36 @@ function tokenizeShell(command) {
|
|
|
354
611
|
i++;
|
|
355
612
|
}
|
|
356
613
|
pushWord(tokens, value, substitutions);
|
|
614
|
+
if (pendingDelimiter !== undefined) {
|
|
615
|
+
if (unsupportedDelimiter) {
|
|
616
|
+
throw new Error("Cannot validate an ANSI-C quoted heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.");
|
|
617
|
+
}
|
|
618
|
+
pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted });
|
|
619
|
+
pendingDelimiter = undefined;
|
|
620
|
+
}
|
|
357
621
|
}
|
|
358
622
|
return tokens;
|
|
359
623
|
}
|
|
360
624
|
function splitSimpleCommands(tokens) {
|
|
361
625
|
const commands = [];
|
|
362
626
|
let current = [];
|
|
627
|
+
let precedingPipeline = false;
|
|
363
628
|
for (const token of tokens) {
|
|
364
629
|
if (token.type === "operator") {
|
|
365
|
-
|
|
366
|
-
|
|
630
|
+
const isPipeline = token.value === "|" || token.value === "|&";
|
|
631
|
+
const hasCommand = current.length > 0;
|
|
632
|
+
if (hasCommand)
|
|
633
|
+
commands.push({ tokens: current, pipeline: precedingPipeline || isPipeline });
|
|
367
634
|
current = [];
|
|
635
|
+
if (hasCommand || token.value !== `
|
|
636
|
+
`)
|
|
637
|
+
precedingPipeline = isPipeline;
|
|
368
638
|
} else {
|
|
369
639
|
current.push(token);
|
|
370
640
|
}
|
|
371
641
|
}
|
|
372
642
|
if (current.length > 0)
|
|
373
|
-
commands.push(current);
|
|
643
|
+
commands.push({ tokens: current, pipeline: precedingPipeline });
|
|
374
644
|
return commands;
|
|
375
645
|
}
|
|
376
646
|
function extractCommandWords(tokens) {
|
|
@@ -405,7 +675,6 @@ function skipAssignments(words, start) {
|
|
|
405
675
|
}
|
|
406
676
|
function findCommandStart(words) {
|
|
407
677
|
let index = skipAssignments(words, 0);
|
|
408
|
-
const directoryChanges = [];
|
|
409
678
|
while (index < words.length) {
|
|
410
679
|
const word = words[index];
|
|
411
680
|
if (word !== undefined && commandPrefixes.has(word)) {
|
|
@@ -425,16 +694,8 @@ function findCommandStart(words) {
|
|
|
425
694
|
if (argument === "-u" || argument === "--unset") {
|
|
426
695
|
index += 2;
|
|
427
696
|
} else if (argument === "-C" || argument === "--chdir") {
|
|
428
|
-
const directory = words[index + 1];
|
|
429
|
-
if (directory !== undefined) {
|
|
430
|
-
directoryChanges.push(directory);
|
|
431
|
-
}
|
|
432
697
|
index += 2;
|
|
433
|
-
} else if (argument.startsWith("--chdir=")) {
|
|
434
|
-
directoryChanges.push(argument.slice("--chdir=".length));
|
|
435
|
-
index++;
|
|
436
|
-
} else if (/^-C.+/.test(argument)) {
|
|
437
|
-
directoryChanges.push(argument.slice(2));
|
|
698
|
+
} else if (argument.startsWith("--chdir=") || /^-C.+/.test(argument)) {
|
|
438
699
|
index++;
|
|
439
700
|
} else if (argument.startsWith("--unset=") || /^-u.+/.test(argument)) {
|
|
440
701
|
index++;
|
|
@@ -476,18 +737,16 @@ function findCommandStart(words) {
|
|
|
476
737
|
}
|
|
477
738
|
break;
|
|
478
739
|
}
|
|
479
|
-
return
|
|
740
|
+
return index;
|
|
480
741
|
}
|
|
481
742
|
function extractInvocation(words, commandStart) {
|
|
482
|
-
let wordIndex = commandStart
|
|
743
|
+
let wordIndex = commandStart;
|
|
483
744
|
const executable = words[wordIndex];
|
|
484
745
|
if (executable === undefined || executable !== "git" && !executable.endsWith("/git"))
|
|
485
746
|
return;
|
|
486
747
|
wordIndex++;
|
|
487
|
-
const directoryChanges = [...commandStart.directoryChanges];
|
|
488
|
-
let gitDir;
|
|
489
|
-
let workTree;
|
|
490
748
|
let subcommand;
|
|
749
|
+
let targetError = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word) || word === "export") ? "Environment or wrapper changes can redirect a Git commit target. Use a direct git commit in the captured workdir." : undefined;
|
|
491
750
|
while (wordIndex < words.length) {
|
|
492
751
|
const argument = words[wordIndex];
|
|
493
752
|
if (argument === undefined)
|
|
@@ -498,33 +757,21 @@ function extractInvocation(words, commandStart) {
|
|
|
498
757
|
break;
|
|
499
758
|
}
|
|
500
759
|
if (gitGlobalOptionsWithArg.has(argument)) {
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
directoryChanges.push(optionValue);
|
|
504
|
-
} else if (argument === "--git-dir" && optionValue !== undefined) {
|
|
505
|
-
gitDir = optionValue;
|
|
506
|
-
} else if (argument === "--work-tree" && optionValue !== undefined) {
|
|
507
|
-
workTree = optionValue;
|
|
760
|
+
if (argument === "-C" || argument === "--git-dir" || argument === "--work-tree" || argument === "-c" || argument === "--config-env") {
|
|
761
|
+
targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
|
|
508
762
|
}
|
|
509
763
|
wordIndex += 2;
|
|
510
764
|
continue;
|
|
511
765
|
}
|
|
512
|
-
if (argument.startsWith("--git-dir=")) {
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
}
|
|
517
|
-
if (argument.startsWith("--work-tree=")) {
|
|
518
|
-
workTree = argument.slice("--work-tree=".length);
|
|
519
|
-
wordIndex++;
|
|
520
|
-
continue;
|
|
521
|
-
}
|
|
522
|
-
if (argument.startsWith("--namespace=") || argument.startsWith("--exec-path=") || argument.startsWith("--super-prefix=") || argument.startsWith("-c")) {
|
|
766
|
+
if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--namespace=") || argument.startsWith("--exec-path=") || argument.startsWith("--super-prefix=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
|
|
767
|
+
if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
|
|
768
|
+
targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
|
|
769
|
+
}
|
|
523
770
|
wordIndex++;
|
|
524
771
|
continue;
|
|
525
772
|
}
|
|
526
773
|
if (argument.startsWith("-C")) {
|
|
527
|
-
|
|
774
|
+
targetError = "git -C can change the commit target. Run git commit directly in the captured workdir.";
|
|
528
775
|
wordIndex++;
|
|
529
776
|
continue;
|
|
530
777
|
}
|
|
@@ -629,63 +876,60 @@ function extractInvocation(words, commandStart) {
|
|
|
629
876
|
hasNoEdit,
|
|
630
877
|
isFixup,
|
|
631
878
|
isHelp,
|
|
632
|
-
|
|
633
|
-
gitDir,
|
|
634
|
-
workTree
|
|
879
|
+
targetError
|
|
635
880
|
};
|
|
636
881
|
}
|
|
637
|
-
function extractGitCommits(command) {
|
|
882
|
+
function extractGitCommits(command, inheritedDirectoryChange = false) {
|
|
638
883
|
const tokens = tokenizeShell(command);
|
|
639
884
|
const invocations = [];
|
|
640
|
-
|
|
885
|
+
let changedDirectory = inheritedDirectoryChange;
|
|
886
|
+
for (const simple of splitSimpleCommands(tokens)) {
|
|
887
|
+
const commandTokens = simple.tokens;
|
|
641
888
|
const words = extractCommandWords(commandTokens);
|
|
642
889
|
const commandStart = findCommandStart(words);
|
|
643
890
|
const invocation = extractInvocation(words, commandStart);
|
|
644
|
-
if (
|
|
645
|
-
|
|
891
|
+
if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment))
|
|
892
|
+
changedDirectory = true;
|
|
893
|
+
if (invocation !== undefined) {
|
|
894
|
+
const target = changedDirectory ? { ...invocation, targetError: "A preceding directory or environment change makes the commit target ambiguous. Run git commit in a separate shell call with the captured workdir." } : invocation;
|
|
895
|
+
if (!invocation.filePaths.includes("-")) {
|
|
896
|
+
invocations.push(target);
|
|
897
|
+
continue;
|
|
898
|
+
}
|
|
899
|
+
const heredocs = commandTokens.filter((token) => token.type === "redirect" && /^\d*<<$/.test(token.value));
|
|
900
|
+
const stdinRedirects = commandTokens.filter((token) => {
|
|
901
|
+
if (token.type !== "redirect")
|
|
902
|
+
return false;
|
|
903
|
+
const match = token.value.match(/^(\d*)([<>])/);
|
|
904
|
+
return match !== null && (match[1] === "" ? match[2] === "<" : Number(match[1]) === 0);
|
|
905
|
+
});
|
|
906
|
+
const heredoc = heredocs[0];
|
|
907
|
+
let stdinError;
|
|
908
|
+
if (simple.pipeline)
|
|
909
|
+
stdinError = "Pipelines cannot supply a validated commit message.";
|
|
910
|
+
else if (heredocs.length !== 1 || stdinRedirects.length !== 1 || heredoc?.value !== "<<" && heredoc?.value !== "0<<") {
|
|
911
|
+
stdinError = "Use exactly one quoted stdin heredoc on git commit -F -, with no other stdin redirects.";
|
|
912
|
+
} else if (heredoc.heredoc?.quoted !== true) {
|
|
913
|
+
stdinError = "Use a complete quoted heredoc delimiter, for example: git commit -s -F - <<'EOF'.";
|
|
914
|
+
}
|
|
915
|
+
invocations.push({
|
|
916
|
+
...target,
|
|
917
|
+
stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined,
|
|
918
|
+
stdinError
|
|
919
|
+
});
|
|
920
|
+
}
|
|
646
921
|
}
|
|
647
922
|
for (const token of tokens) {
|
|
648
923
|
for (const substitution of token.substitutions ?? []) {
|
|
649
|
-
invocations.push(...extractGitCommits(substitution));
|
|
924
|
+
invocations.push(...extractGitCommits(substitution, changedDirectory));
|
|
650
925
|
}
|
|
651
926
|
}
|
|
652
927
|
return invocations;
|
|
653
928
|
}
|
|
654
929
|
|
|
655
930
|
// src/validator.ts
|
|
656
|
-
import { spawnSync } from "child_process";
|
|
657
|
-
import { homedir } from "os";
|
|
658
|
-
import { join, resolve } from "path";
|
|
659
931
|
var scopePattern = /^([a-zA-Z0-9_\-./]+(?:\([a-zA-Z0-9_\-./]+\))?):\s+(.+)$/;
|
|
660
932
|
var signoffPattern = /^\s*Signed-off-by:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/i;
|
|
661
|
-
function normalizeWindowsShellPath(inputPath) {
|
|
662
|
-
if (process.platform !== "win32")
|
|
663
|
-
return inputPath;
|
|
664
|
-
const patterns = [
|
|
665
|
-
/^\/([a-zA-Z]):(?:[\\/]|$)/,
|
|
666
|
-
/^\/([a-zA-Z])(?:\/|$)/,
|
|
667
|
-
/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,
|
|
668
|
-
/^\/mnt\/([a-zA-Z])(?:\/|$)/
|
|
669
|
-
];
|
|
670
|
-
for (const pattern of patterns) {
|
|
671
|
-
const match = inputPath.match(pattern);
|
|
672
|
-
const drive = match?.[1];
|
|
673
|
-
if (match?.[0] !== undefined && drive !== undefined) {
|
|
674
|
-
return `${drive.toUpperCase()}:/${inputPath.slice(match[0].length)}`;
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
return inputPath;
|
|
678
|
-
}
|
|
679
|
-
function resolveLocationPath(baseDirectory, inputPath) {
|
|
680
|
-
const homeDirectory = process.env.OPENCODE_TEST_HOME ?? homedir();
|
|
681
|
-
const normalizedInput = normalizeWindowsShellPath(inputPath);
|
|
682
|
-
if (normalizedInput === "~")
|
|
683
|
-
return homeDirectory;
|
|
684
|
-
if (normalizedInput.startsWith("~/") || process.platform === "win32" && normalizedInput.startsWith("~\\")) {
|
|
685
|
-
return join(homeDirectory, normalizedInput.slice(2));
|
|
686
|
-
}
|
|
687
|
-
return resolve(baseDirectory, normalizedInput);
|
|
688
|
-
}
|
|
689
933
|
function hasSignoffTrailer(lines) {
|
|
690
934
|
const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
|
|
691
935
|
return subjectIndex >= 0 && lines.slice(subjectIndex + 1).some((line) => signoffPattern.test(line));
|
|
@@ -721,59 +965,29 @@ ${examples}
|
|
|
721
965
|
Command attempted:
|
|
722
966
|
${originalCommand}`);
|
|
723
967
|
}
|
|
724
|
-
function validateGitCommits(invocations, config, originalCommand
|
|
968
|
+
function validateGitCommits(invocations, config, originalCommand) {
|
|
725
969
|
const allViolations = [];
|
|
726
970
|
for (const invocation of invocations) {
|
|
727
971
|
if (invocation.isHelp) {
|
|
728
972
|
continue;
|
|
729
973
|
}
|
|
730
974
|
const collectedMessages = [...invocation.messages];
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
if (invocation.isAmend && invocation.hasNoEdit === true && invocation.messages.length === 0 && invocation.filePaths.length === 0) {
|
|
736
|
-
const hasAmbiguousHomeChange = invocation.directoryChanges?.some((directoryChange) => directoryChange === "~" || directoryChange.startsWith("~/") || process.platform === "win32" && directoryChange.startsWith("~\\")) === true;
|
|
737
|
-
if (hasAmbiguousHomeChange) {
|
|
738
|
-
allViolations.push('Cannot validate an existing commit through a shell directory change that starts with "~". Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".');
|
|
739
|
-
continue;
|
|
740
|
-
}
|
|
741
|
-
if (!canReadLocalRepository) {
|
|
742
|
-
allViolations.push('Cannot validate the existing commit in a workspace-backed location. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".');
|
|
743
|
-
continue;
|
|
744
|
-
}
|
|
745
|
-
if (invocation.gitDir !== undefined || invocation.workTree !== undefined) {
|
|
746
|
-
allViolations.push('Cannot validate an existing commit through --git-dir or --work-tree before shell permissions run. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".');
|
|
747
|
-
continue;
|
|
748
|
-
}
|
|
749
|
-
const result = spawnSync("git", ["log", "-1", "--format=%B", "HEAD"], {
|
|
750
|
-
cwd: messageDirectory,
|
|
751
|
-
encoding: "utf-8",
|
|
752
|
-
stdio: ["ignore", "pipe", "pipe"]
|
|
753
|
-
});
|
|
754
|
-
if (result.error !== undefined) {
|
|
755
|
-
allViolations.push(`Failed to read the existing HEAD commit message: ${result.error.message}`);
|
|
756
|
-
continue;
|
|
757
|
-
}
|
|
758
|
-
if (result.status !== 0) {
|
|
759
|
-
const detail = result.stderr.trim();
|
|
760
|
-
const suffix = detail.length > 0 ? `: ${detail}` : ".";
|
|
761
|
-
allViolations.push(`Failed to read the existing HEAD commit message${suffix}`);
|
|
975
|
+
const filePath = invocation.filePaths.at(-1);
|
|
976
|
+
if (filePath !== undefined) {
|
|
977
|
+
if (filePath !== "-" || invocation.filePaths.length !== 1) {
|
|
978
|
+
allViolations.push(`Cannot validate a commit message from file "${filePath}" before shell permissions run. Use an inline message, for example: git commit -s -m "kernel: add support for foo".`);
|
|
762
979
|
continue;
|
|
763
980
|
}
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
allViolations.push("The existing HEAD commit message is empty.");
|
|
981
|
+
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 directly on git commit -s -F - <<'EOF', or use -m "kernel: add support for foo".`);
|
|
767
983
|
continue;
|
|
768
984
|
}
|
|
769
|
-
collectedMessages.push(
|
|
770
|
-
}
|
|
771
|
-
const filePath = invocation.filePaths.at(-1);
|
|
772
|
-
if (filePath !== undefined) {
|
|
773
|
-
allViolations.push(`Cannot validate a commit message from ${filePath === "-" ? "standard input" : `file "${filePath}"`} before shell permissions run. Use an inline message, for example: git commit -s -m "kernel: add support for foo".`);
|
|
774
|
-
continue;
|
|
985
|
+
collectedMessages.push(invocation.stdinMessage);
|
|
775
986
|
}
|
|
776
987
|
if (collectedMessages.length === 0) {
|
|
988
|
+
if (invocation.isAmend && invocation.hasNoEdit === true) {
|
|
989
|
+
continue;
|
|
990
|
+
}
|
|
777
991
|
if (invocation.isFixup === true) {
|
|
778
992
|
continue;
|
|
779
993
|
}
|
|
@@ -827,7 +1041,7 @@ function validateGitCommits(invocations, config, originalCommand, workingDirecto
|
|
|
827
1041
|
${details}`);
|
|
828
1042
|
}
|
|
829
1043
|
}
|
|
830
|
-
if (config.
|
|
1044
|
+
if (config.enforceSignoff) {
|
|
831
1045
|
const hasSignoff = invocation.hasSignoffFlag || hasSignoffTrailer(lines);
|
|
832
1046
|
if (!hasSignoff) {
|
|
833
1047
|
allViolations.push("Missing commit signoff. Commit must either include the '-s' or '--signoff' flag, or contain a valid 'Signed-off-by: Name <email>' trailer in the message body.");
|
|
@@ -842,38 +1056,169 @@ ${details}`);
|
|
|
842
1056
|
// src/plugin.ts
|
|
843
1057
|
var plugin = Plugin.define({
|
|
844
1058
|
id: "opencode-commit-guard",
|
|
845
|
-
effect: (ctx) =>
|
|
846
|
-
const config = yield*
|
|
1059
|
+
effect: (ctx) => Effect2.gen(function* () {
|
|
1060
|
+
const config = yield* Effect2.sync(() => {
|
|
847
1061
|
return parseConfig(ctx.options);
|
|
848
1062
|
});
|
|
849
|
-
const
|
|
850
|
-
const
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
1063
|
+
const generation = randomUUID2();
|
|
1064
|
+
const pending = new Map;
|
|
1065
|
+
const preparing = new Set;
|
|
1066
|
+
yield* Effect2.addFinalizer(() => Effect2.gen(function* () {
|
|
1067
|
+
for (const attempt of pending.values()) {
|
|
1068
|
+
cleanup(attempt);
|
|
1069
|
+
yield* invalidate(ctx, attempt.scope);
|
|
1070
|
+
}
|
|
1071
|
+
pending.clear();
|
|
1072
|
+
}));
|
|
1073
|
+
yield* ctx.tool.transform((editor) => editor.add({
|
|
1074
|
+
name: "commit_context",
|
|
1075
|
+
description: "Prepare a private, permission-checked Git baseline. Run the returned shell command in the foreground, then call this tool again. Set refresh to replace a frozen baseline.",
|
|
1076
|
+
input: { type: "object", properties: { refresh: { type: "boolean" } }, additionalProperties: false },
|
|
1077
|
+
execute: (input, toolContext) => Effect2.gen(function* () {
|
|
1078
|
+
if (ctx.location.workspaceID !== undefined)
|
|
1079
|
+
return { content: "Commit context capture is unavailable for remote workspaces." };
|
|
1080
|
+
const session = yield* ctx.session.get({ sessionID: toolContext.sessionID });
|
|
1081
|
+
if (session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID) {
|
|
1082
|
+
return { content: "The session moved to another worktree. Call commit_context from its new location." };
|
|
855
1083
|
}
|
|
856
|
-
const
|
|
857
|
-
if (
|
|
858
|
-
return;
|
|
1084
|
+
const scope = scopeFor(ctx, toolContext.sessionID, config);
|
|
1085
|
+
if (preparing.has(scope))
|
|
1086
|
+
return { content: "A commit context capture is preparing for this session. Call commit_context again." };
|
|
1087
|
+
preparing.add(scope);
|
|
1088
|
+
return yield* Effect2.gen(function* () {
|
|
1089
|
+
const request = input;
|
|
1090
|
+
const previous = pending.get(scope);
|
|
1091
|
+
if (previous !== undefined) {
|
|
1092
|
+
if (Date.now() < previous.expires && request.refresh !== true)
|
|
1093
|
+
return { content: `Run this shell command with workdir ${ctx.location.directory} and background:false, then call commit_context again:
|
|
1094
|
+
${previous.command}` };
|
|
1095
|
+
pending.delete(scope);
|
|
1096
|
+
cleanup(previous);
|
|
1097
|
+
yield* invalidate(ctx, scope);
|
|
1098
|
+
}
|
|
1099
|
+
if (request.refresh !== true) {
|
|
1100
|
+
const baseline = yield* load(ctx, scope);
|
|
1101
|
+
if (baseline !== undefined && baseline.workdir === ctx.location.directory && baseline.gpgsign !== "error" && baseline.signingkey !== "error") {
|
|
1102
|
+
const observed = [...new Set(baseline.messages.map((message) => message.split(`
|
|
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." };
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
if (request.refresh === true)
|
|
1115
|
+
yield* invalidate(ctx, scope);
|
|
1116
|
+
const count = yield* counter(ctx, scope);
|
|
1117
|
+
const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, ctx.location.directory));
|
|
1118
|
+
pending.set(scope, attempt);
|
|
1119
|
+
return { content: `Run this shell command with workdir ${ctx.location.directory} and background:false, then call commit_context again:
|
|
1120
|
+
${attempt.command}` };
|
|
1121
|
+
}).pipe(Effect2.ensuring(Effect2.sync(() => {
|
|
1122
|
+
preparing.delete(scope);
|
|
1123
|
+
})));
|
|
1124
|
+
}).pipe(Effect2.mapError(() => new Tool.Error({
|
|
1125
|
+
message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout."
|
|
1126
|
+
})))
|
|
1127
|
+
}));
|
|
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;
|
|
859
1132
|
}
|
|
860
|
-
|
|
861
|
-
|
|
1133
|
+
}
|
|
1134
|
+
}));
|
|
1135
|
+
yield* ctx.tool.hook("execute.before", (event) => Effect2.gen(function* () {
|
|
1136
|
+
const parsed = yield* Effect2.try({
|
|
1137
|
+
try: () => {
|
|
1138
|
+
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
const rawInput = event.input;
|
|
1142
|
+
if (!isRecord(rawInput)) {
|
|
1143
|
+
return;
|
|
1144
|
+
}
|
|
1145
|
+
const command = rawInput["command"];
|
|
1146
|
+
if (!isJSONString(command)) {
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
for (const attempt of pending.values()) {
|
|
1150
|
+
if (command !== attempt.command)
|
|
1151
|
+
continue;
|
|
1152
|
+
if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || (rawInput["workdir"] !== ctx.location.directory || rawInput["background"] === true) || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
|
|
1153
|
+
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
|
+
}
|
|
1155
|
+
attempt.claimed = { messageID: event.messageID, id: event.id };
|
|
1156
|
+
attempt.expires = Date.now() + captureTimeout;
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
const invocations = extractGitCommits(command);
|
|
1160
|
+
if (invocations.length === 0) {
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1163
|
+
validateGitCommits(invocations, { ...config, enforceSignoff: false }, command);
|
|
1164
|
+
return { invocations, command, rawInput };
|
|
1165
|
+
},
|
|
1166
|
+
catch: (error) => new Tool.Error({
|
|
1167
|
+
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
|
|
1168
|
+
})
|
|
1169
|
+
});
|
|
1170
|
+
if (parsed === undefined)
|
|
1171
|
+
return;
|
|
1172
|
+
if (ctx.location.workspaceID !== undefined)
|
|
1173
|
+
return yield* Effect2.fail(new Tool.Error({
|
|
1174
|
+
message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."
|
|
1175
|
+
}));
|
|
1176
|
+
const session = yield* ctx.session.get({ sessionID: event.sessionID });
|
|
1177
|
+
if (session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID || parsed.rawInput["workdir"] !== undefined && parsed.rawInput["workdir"] !== ctx.location.directory || parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
|
|
1178
|
+
return yield* Effect2.fail(new Tool.Error({ 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." }));
|
|
1179
|
+
}
|
|
1180
|
+
const baseline = yield* load(ctx, scopeFor(ctx, event.sessionID, config));
|
|
1181
|
+
if (baseline === undefined || baseline.workdir !== ctx.location.directory || baseline.gpgsign === "error" || baseline.signingkey === "error") {
|
|
1182
|
+
return yield* Effect2.fail(new Tool.Error({ message: "[commit-guard] No valid signing baseline for this checkout. Call commit_context, run its authorized foreground shell command, then call commit_context again before committing." }));
|
|
1183
|
+
}
|
|
1184
|
+
yield* Effect2.try({
|
|
1185
|
+
try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
|
|
1186
|
+
catch: (error) => new Tool.Error({ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed." })
|
|
1187
|
+
});
|
|
1188
|
+
}).pipe(Effect2.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
|
|
1189
|
+
message: "[commit-guard] Could not verify the commit target or signing baseline. Call commit_context from this checkout."
|
|
1190
|
+
}))));
|
|
1191
|
+
yield* ctx.tool.hook("execute.after", (event) => Effect2.gen(function* () {
|
|
1192
|
+
if (event.tool !== "shell")
|
|
1193
|
+
return;
|
|
1194
|
+
const attempt = [...pending.values()].find((item) => item.claimed?.id === event.id && item.claimed?.messageID === event.messageID && item.sessionID === event.sessionID && item.agent === event.agent);
|
|
1195
|
+
if (attempt === undefined)
|
|
1196
|
+
return;
|
|
1197
|
+
let published = false;
|
|
1198
|
+
yield* Effect2.gen(function* () {
|
|
1199
|
+
if (event.status !== "completed" || Date.now() >= attempt.expires || (yield* counter(ctx, attempt.scope)) !== attempt.counter)
|
|
862
1200
|
return;
|
|
863
|
-
|
|
864
|
-
if (!
|
|
1201
|
+
const metadata = event.result.metadata;
|
|
1202
|
+
if (!isRecord(metadata))
|
|
865
1203
|
return;
|
|
866
|
-
|
|
867
|
-
const invocations = extractGitCommits(command);
|
|
868
|
-
if (invocations.length === 0) {
|
|
1204
|
+
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)))
|
|
869
1205
|
return;
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
1206
|
+
const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {
|
|
1207
|
+
return;
|
|
1208
|
+
});
|
|
1209
|
+
if (session === undefined || session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID)
|
|
1210
|
+
return;
|
|
1211
|
+
const baseline = yield* Effect2.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") });
|
|
1212
|
+
if (baseline.workdir !== ctx.location.directory || ctx.location.workspaceID !== undefined)
|
|
1213
|
+
return;
|
|
1214
|
+
published = yield* publish(ctx, attempt, generation, baseline);
|
|
1215
|
+
}).pipe(Effect2.onExit(() => Effect2.gen(function* () {
|
|
1216
|
+
if (pending.get(attempt.scope) === attempt)
|
|
1217
|
+
pending.delete(attempt.scope);
|
|
1218
|
+
if (!published)
|
|
1219
|
+
yield* invalidate(ctx, attempt.scope);
|
|
1220
|
+
yield* Effect2.sync(() => cleanup(attempt));
|
|
1221
|
+
})), Effect2.catchCause(() => Effect2.void));
|
|
877
1222
|
}));
|
|
878
1223
|
})
|
|
879
1224
|
});
|