opencode-commit-guard 1.0.3 → 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 +33 -8
- package/dist/index.js +394 -42
- package/package.json +1 -1
- package/src/capture.ts +250 -0
- package/src/config.ts +3 -10
- package/src/plugin.ts +180 -9
- package/src/shell.ts +32 -4
- package/src/types.ts +3 -2
- package/src/validator.ts +5 -12
package/README.md
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
# opencode-commit-guard
|
|
2
2
|
|
|
3
3
|
OpenCode V2 plugin that enforces git commit message format rules during agent sessions.
|
|
4
|
+
Capture Git context before your first commit in each session and checkout.
|
|
4
5
|
|
|
5
6
|
## Overview
|
|
6
7
|
|
|
7
8
|
`opencode-commit-guard` intercepts `shell` and `bash` tool execution before it runs.
|
|
8
9
|
When an agent attempts a `git commit`, the plugin inspects the command line and inline message content.
|
|
9
10
|
If the commit violates configured formatting standards, the plugin rejects the tool call through OpenCode's typed tool-error channel.
|
|
11
|
+
The plugin requires a valid Git signing baseline for the exact checkout before it allows a commit.
|
|
10
12
|
|
|
11
13
|
### Why this approach fits
|
|
12
14
|
|
|
@@ -39,8 +41,7 @@ You can also specify custom configuration options:
|
|
|
39
41
|
"options": {
|
|
40
42
|
"requireScope": true,
|
|
41
43
|
"allowedScopes": ["kernel", "releasetools", "build", "ui"],
|
|
42
|
-
"maxLineLength": 72
|
|
43
|
-
"requireSignoff": true
|
|
44
|
+
"maxLineLength": 72
|
|
44
45
|
}
|
|
45
46
|
}
|
|
46
47
|
]
|
|
@@ -54,7 +55,22 @@ You can also specify custom configuration options:
|
|
|
54
55
|
| `requireScope` | `boolean` | `true` | Requires the first line to match `<scope>: <subject>`. |
|
|
55
56
|
| `allowedScopes` | `string[]` | `undefined` | Restricts allowed scope identifiers to a specified list. |
|
|
56
57
|
| `maxLineLength` | `number` | `72` | Limits every line in the subject and body to this length. Set to `0` to disable. |
|
|
57
|
-
|
|
58
|
+
|
|
59
|
+
## Capture commit context
|
|
60
|
+
|
|
61
|
+
Call `commit_context` before your first commit in each session and worktree.
|
|
62
|
+
Run the returned command through the foreground `shell` tool with the indicated workdir.
|
|
63
|
+
Call `commit_context` again to read concise guidance.
|
|
64
|
+
If the shell result lacks a verified successful process exit, capture again instead of using a partial baseline.
|
|
65
|
+
The command writes full historical messages to a private file and prints only a fixed receipt.
|
|
66
|
+
The plugin does not put complete historical messages into tool results or model context.
|
|
67
|
+
Set `refresh: true` after a branch switch, a signing setting change, or a change to commit instructions.
|
|
68
|
+
A failed refresh does not restore the previous baseline.
|
|
69
|
+
An external Git configuration change or checkout replacement at the same path is not detected until you refresh.
|
|
70
|
+
Remote workspaces are unsupported.
|
|
71
|
+
Historical scopes are observations, not allowed scopes or policy.
|
|
72
|
+
The guard enforces configured scope syntax, allowed scopes, line length, inline message input, and conditional signoff.
|
|
73
|
+
It does not enforce every writing convention in `AGENTS.md` or verify a cryptographic signature.
|
|
58
74
|
|
|
59
75
|
## Formatting rules
|
|
60
76
|
|
|
@@ -84,19 +100,28 @@ For conventional commits such as `feat(parser): ...`, the plugin accepts either
|
|
|
84
100
|
No line in the commit subject or body may exceed the configured character limit (default 72 characters).
|
|
85
101
|
When a line exceeds this limit, the error identifies the exact line number, current character length, and offending text.
|
|
86
102
|
|
|
87
|
-
### 4. Signoff
|
|
103
|
+
### 4. Signoff
|
|
88
104
|
|
|
89
|
-
|
|
105
|
+
When the captured effective `commit.gpgsign` is `true`, every commit with a supplied message must include a signoff indicator.
|
|
106
|
+
When it is `false` or unset, signoff is not required.
|
|
107
|
+
An invalid or missing signing snapshot blocks the commit until you capture context again.
|
|
90
108
|
You can provide this either via flags or directly in the message body:
|
|
91
109
|
|
|
92
110
|
- Pass `-s` or `--signoff` in the git command.
|
|
93
111
|
- Or include a trailer matching `Signed-off-by: Full Name <email@example.com>` in the message body.
|
|
94
112
|
|
|
113
|
+
Signoff identifies the author of a contribution.
|
|
114
|
+
It does not cryptographically sign the commit.
|
|
115
|
+
Git signing settings and your signing key remain separate from signoff.
|
|
116
|
+
|
|
95
117
|
### 5. Amend commits (`--amend`)
|
|
96
118
|
|
|
97
|
-
|
|
98
|
-
The plugin
|
|
99
|
-
|
|
119
|
+
Use `git commit --amend --no-edit` to keep the existing message unchanged.
|
|
120
|
+
The plugin does not read or revalidate that message, so a message created outside this guard may not meet its format rules.
|
|
121
|
+
Provide `-m` when you change the message; the plugin validates the supplied text in the captured checkout.
|
|
122
|
+
Use a direct Git command in that checkout.
|
|
123
|
+
The guard rejects `git -C`, Git directory and worktree flags, Git environment overrides, and directory-changing wrappers because they can select another target.
|
|
124
|
+
The guard also rejects earlier shell environment mutations such as `export`, `typeset`, `declare`, `source`, `.`, `eval`, `set`, and assignment-only commands before a commit.
|
|
100
125
|
|
|
101
126
|
### Message input
|
|
102
127
|
|
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",
|
|
@@ -543,6 +746,7 @@ function extractInvocation(words, commandStart) {
|
|
|
543
746
|
return;
|
|
544
747
|
wordIndex++;
|
|
545
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;
|
|
546
750
|
while (wordIndex < words.length) {
|
|
547
751
|
const argument = words[wordIndex];
|
|
548
752
|
if (argument === undefined)
|
|
@@ -553,14 +757,21 @@ function extractInvocation(words, commandStart) {
|
|
|
553
757
|
break;
|
|
554
758
|
}
|
|
555
759
|
if (gitGlobalOptionsWithArg.has(argument)) {
|
|
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.";
|
|
762
|
+
}
|
|
556
763
|
wordIndex += 2;
|
|
557
764
|
continue;
|
|
558
765
|
}
|
|
559
|
-
if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || 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
|
+
}
|
|
560
770
|
wordIndex++;
|
|
561
771
|
continue;
|
|
562
772
|
}
|
|
563
773
|
if (argument.startsWith("-C")) {
|
|
774
|
+
targetError = "git -C can change the commit target. Run git commit directly in the captured workdir.";
|
|
564
775
|
wordIndex++;
|
|
565
776
|
continue;
|
|
566
777
|
}
|
|
@@ -664,20 +875,25 @@ function extractInvocation(words, commandStart) {
|
|
|
664
875
|
isAmend,
|
|
665
876
|
hasNoEdit,
|
|
666
877
|
isFixup,
|
|
667
|
-
isHelp
|
|
878
|
+
isHelp,
|
|
879
|
+
targetError
|
|
668
880
|
};
|
|
669
881
|
}
|
|
670
|
-
function extractGitCommits(command) {
|
|
882
|
+
function extractGitCommits(command, inheritedDirectoryChange = false) {
|
|
671
883
|
const tokens = tokenizeShell(command);
|
|
672
884
|
const invocations = [];
|
|
885
|
+
let changedDirectory = inheritedDirectoryChange;
|
|
673
886
|
for (const simple of splitSimpleCommands(tokens)) {
|
|
674
887
|
const commandTokens = simple.tokens;
|
|
675
888
|
const words = extractCommandWords(commandTokens);
|
|
676
889
|
const commandStart = findCommandStart(words);
|
|
677
890
|
const invocation = extractInvocation(words, commandStart);
|
|
891
|
+
if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment))
|
|
892
|
+
changedDirectory = true;
|
|
678
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;
|
|
679
895
|
if (!invocation.filePaths.includes("-")) {
|
|
680
|
-
invocations.push(
|
|
896
|
+
invocations.push(target);
|
|
681
897
|
continue;
|
|
682
898
|
}
|
|
683
899
|
const heredocs = commandTokens.filter((token) => token.type === "redirect" && /^\d*<<$/.test(token.value));
|
|
@@ -697,7 +913,7 @@ function extractGitCommits(command) {
|
|
|
697
913
|
stdinError = "Use a complete quoted heredoc delimiter, for example: git commit -s -F - <<'EOF'.";
|
|
698
914
|
}
|
|
699
915
|
invocations.push({
|
|
700
|
-
...
|
|
916
|
+
...target,
|
|
701
917
|
stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined,
|
|
702
918
|
stdinError
|
|
703
919
|
});
|
|
@@ -705,7 +921,7 @@ function extractGitCommits(command) {
|
|
|
705
921
|
}
|
|
706
922
|
for (const token of tokens) {
|
|
707
923
|
for (const substitution of token.substitutions ?? []) {
|
|
708
|
-
invocations.push(...extractGitCommits(substitution));
|
|
924
|
+
invocations.push(...extractGitCommits(substitution, changedDirectory));
|
|
709
925
|
}
|
|
710
926
|
}
|
|
711
927
|
return invocations;
|
|
@@ -756,10 +972,6 @@ function validateGitCommits(invocations, config, originalCommand) {
|
|
|
756
972
|
continue;
|
|
757
973
|
}
|
|
758
974
|
const collectedMessages = [...invocation.messages];
|
|
759
|
-
if (invocation.isAmend && invocation.hasNoEdit === true && invocation.messages.length === 0) {
|
|
760
|
-
allViolations.push('Cannot validate --amend --no-edit before shell permissions run because it would read the existing commit. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".');
|
|
761
|
-
continue;
|
|
762
|
-
}
|
|
763
975
|
const filePath = invocation.filePaths.at(-1);
|
|
764
976
|
if (filePath !== undefined) {
|
|
765
977
|
if (filePath !== "-" || invocation.filePaths.length !== 1) {
|
|
@@ -773,6 +985,9 @@ function validateGitCommits(invocations, config, originalCommand) {
|
|
|
773
985
|
collectedMessages.push(invocation.stdinMessage);
|
|
774
986
|
}
|
|
775
987
|
if (collectedMessages.length === 0) {
|
|
988
|
+
if (invocation.isAmend && invocation.hasNoEdit === true) {
|
|
989
|
+
continue;
|
|
990
|
+
}
|
|
776
991
|
if (invocation.isFixup === true) {
|
|
777
992
|
continue;
|
|
778
993
|
}
|
|
@@ -826,7 +1041,7 @@ function validateGitCommits(invocations, config, originalCommand) {
|
|
|
826
1041
|
${details}`);
|
|
827
1042
|
}
|
|
828
1043
|
}
|
|
829
|
-
if (config.
|
|
1044
|
+
if (config.enforceSignoff) {
|
|
830
1045
|
const hasSignoff = invocation.hasSignoffFlag || hasSignoffTrailer(lines);
|
|
831
1046
|
if (!hasSignoff) {
|
|
832
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.");
|
|
@@ -841,32 +1056,169 @@ ${details}`);
|
|
|
841
1056
|
// src/plugin.ts
|
|
842
1057
|
var plugin = Plugin.define({
|
|
843
1058
|
id: "opencode-commit-guard",
|
|
844
|
-
effect: (ctx) =>
|
|
845
|
-
const config = yield*
|
|
1059
|
+
effect: (ctx) => Effect2.gen(function* () {
|
|
1060
|
+
const config = yield* Effect2.sync(() => {
|
|
846
1061
|
return parseConfig(ctx.options);
|
|
847
1062
|
});
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
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." };
|
|
852
1083
|
}
|
|
853
|
-
const
|
|
854
|
-
if (
|
|
855
|
-
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;
|
|
856
1132
|
}
|
|
857
|
-
|
|
858
|
-
|
|
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)
|
|
859
1200
|
return;
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
if (invocations.length === 0) {
|
|
1201
|
+
const metadata = event.result.metadata;
|
|
1202
|
+
if (!isRecord(metadata))
|
|
863
1203
|
return;
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
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)))
|
|
1205
|
+
return;
|
|
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));
|
|
870
1222
|
}));
|
|
871
1223
|
})
|
|
872
1224
|
});
|
package/package.json
CHANGED
package/src/capture.ts
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
2
|
+
import { closeSync, constants, fstatSync, mkdtempSync, openSync, readSync, rmSync } from "node:fs"
|
|
3
|
+
import { tmpdir } from "node:os"
|
|
4
|
+
import { join, relative } from "node:path"
|
|
5
|
+
import type { Plugin } from "@opencode/plugin/effect"
|
|
6
|
+
import { Effect, Semaphore } from "effect"
|
|
7
|
+
import { isJSONString, isRecord } from "./types.js"
|
|
8
|
+
import type { CommitGuardConfig, JsonValue } from "./types.js"
|
|
9
|
+
|
|
10
|
+
const version = 1
|
|
11
|
+
|
|
12
|
+
const maxBytes = 262144
|
|
13
|
+
|
|
14
|
+
export const captureTimeout = 20000
|
|
15
|
+
|
|
16
|
+
const policy = "commit-guard-context-v1"
|
|
17
|
+
|
|
18
|
+
const storageLock = Semaphore.makeUnsafe(1)
|
|
19
|
+
|
|
20
|
+
type Context = Parameters<Plugin.Plugin["effect"]>[0]
|
|
21
|
+
|
|
22
|
+
export interface Baseline {
|
|
23
|
+
readonly directory: string
|
|
24
|
+
readonly workdir: string
|
|
25
|
+
readonly gitDir: string
|
|
26
|
+
readonly commonDir: string
|
|
27
|
+
readonly branch: string | null
|
|
28
|
+
readonly head: string | null
|
|
29
|
+
readonly messages: readonly string[]
|
|
30
|
+
readonly gpgsign: "true" | "false" | "unset" | "error"
|
|
31
|
+
readonly signingkey: string | null | "error"
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface Pending {
|
|
35
|
+
readonly scope: string
|
|
36
|
+
readonly command: string
|
|
37
|
+
readonly directory: string
|
|
38
|
+
readonly workdir: string
|
|
39
|
+
readonly fd: number
|
|
40
|
+
readonly identity: { dev: number; ino: number; uid: number }
|
|
41
|
+
expires: number
|
|
42
|
+
readonly counter: number
|
|
43
|
+
readonly agent: string
|
|
44
|
+
readonly sessionID: string
|
|
45
|
+
claimed?: { messageID: string; id: string }
|
|
46
|
+
closed?: boolean
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function digest(text: string): string {
|
|
50
|
+
return createHash("sha256").update(text).digest("hex")
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function scopeFor(ctx: Context, sessionID: string, config: CommitGuardConfig): string {
|
|
54
|
+
const location = ctx.location
|
|
55
|
+
|
|
56
|
+
return digest(JSON.stringify([version, location.project.id, sessionID, location.directory, location.workspaceID ?? null,
|
|
57
|
+
policy, config.requireScope, config.allowedScopes ?? null, config.maxLineLength]))
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function counterKey(scope: string): string { return `counter/${scope}` }
|
|
61
|
+
|
|
62
|
+
function prefix(scope: string): string { return `snap/${scope}/` }
|
|
63
|
+
|
|
64
|
+
export function counter(ctx: Context, scope: string): Effect.Effect<number> {
|
|
65
|
+
return Effect.gen(function*() {
|
|
66
|
+
const value = yield* ctx.storage.get(counterKey(scope))
|
|
67
|
+
|
|
68
|
+
if (value === undefined) return 0
|
|
69
|
+
|
|
70
|
+
return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : -1
|
|
71
|
+
})
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function invalidate(ctx: Context, scope: string): Effect.Effect<void> {
|
|
75
|
+
return storageLock.withPermits(1)(Effect.gen(function*() {
|
|
76
|
+
const previous = yield* counter(ctx, scope)
|
|
77
|
+
|
|
78
|
+
yield* ctx.storage.set(counterKey(scope), previous < 0 ? 1 : previous + 1)
|
|
79
|
+
}))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function validBaseline(value: JsonValue | undefined): value is Baseline & Record<string, JsonValue> {
|
|
83
|
+
if (!isRecord(value)) return false
|
|
84
|
+
|
|
85
|
+
return ["directory", "workdir", "gitDir", "commonDir"].every((key) => isJSONString(value[key])) &&
|
|
86
|
+
(value["branch"] === null || isJSONString(value["branch"])) &&
|
|
87
|
+
(value["head"] === null || /^[0-9a-f]{40,64}$/.test(String(value["head"]))) &&
|
|
88
|
+
Array.isArray(value["messages"]) && value["messages"].length <= 10 &&
|
|
89
|
+
value["messages"].every((message: JsonValue) => isJSONString(message)) &&
|
|
90
|
+
["true", "false", "unset", "error"].includes(String(value["gpgsign"])) &&
|
|
91
|
+
(value["signingkey"] === null || value["signingkey"] === "error" || isJSONString(value["signingkey"]))
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function load(ctx: Context, scope: string): Effect.Effect<Baseline | undefined> {
|
|
95
|
+
return storageLock.withPermits(1)(Effect.gen(function*() {
|
|
96
|
+
const current = yield* counter(ctx, scope)
|
|
97
|
+
|
|
98
|
+
if (current < 0) return undefined
|
|
99
|
+
let after: string | undefined
|
|
100
|
+
let newest: { sequence: string; baseline: Baseline } | undefined
|
|
101
|
+
|
|
102
|
+
do {
|
|
103
|
+
const page = yield* ctx.storage.scan({ prefix: prefix(scope), after, limit: 100 })
|
|
104
|
+
|
|
105
|
+
for (const record of page.entries) {
|
|
106
|
+
// SAFETY: Storage returns arbitrary JSON that is checked before reading any entry fields.
|
|
107
|
+
const raw = record.value as JsonValue
|
|
108
|
+
|
|
109
|
+
if (!isRecord(raw) || raw["schema"] !== version || raw["scope"] !== scope || raw["counter"] !== current ||
|
|
110
|
+
!isJSONString(raw["generation"]) || !isJSONString(raw["sequence"]) || !isJSONString(raw["checksum"]) ||
|
|
111
|
+
!validBaseline(raw["baseline"])) continue
|
|
112
|
+
const baseline = raw["baseline"]
|
|
113
|
+
|
|
114
|
+
if (digest(JSON.stringify([version, scope, current, raw["generation"], raw["sequence"], baseline])) !== raw["checksum"]) continue
|
|
115
|
+
|
|
116
|
+
if (newest === undefined || raw["sequence"] > newest.sequence) newest = { sequence: raw["sequence"], baseline }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
after = page.next
|
|
120
|
+
} while (after !== undefined)
|
|
121
|
+
|
|
122
|
+
return newest?.baseline
|
|
123
|
+
}))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Each line is a base64-encoded Git result. No Git output enters the shell result.
|
|
127
|
+
function captureCommand(path: string): string {
|
|
128
|
+
const quoted = `'${path.replaceAll("'", "'\\''")}'`
|
|
129
|
+
|
|
130
|
+
return `timeout 15s bash -c 'set -euo pipefail
|
|
131
|
+
ulimit -f 256
|
|
132
|
+
out=$1
|
|
133
|
+
printf "CTX1\\n" > "$out"
|
|
134
|
+
field() { "$@" 2>/dev/null | base64 -w0 >> "$out"; printf "\\n" >> "$out"; }
|
|
135
|
+
field git rev-parse --show-toplevel
|
|
136
|
+
field git rev-parse --absolute-git-dir
|
|
137
|
+
field git rev-parse --path-format=absolute --git-common-dir
|
|
138
|
+
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
|
|
139
|
+
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
|
|
140
|
+
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
|
|
141
|
+
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
|
|
142
|
+
printf "END\\n" >> "$out"
|
|
143
|
+
printf "RECEIPT_OK\\n"' bash ${quoted} 2>/dev/null`
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function createPending(scope: string, sessionID: string, agent: string, counterValue: number, workdir: string): Pending {
|
|
147
|
+
const directory = mkdtempSync(join(tmpdir(), "commit-context-"))
|
|
148
|
+
|
|
149
|
+
try {
|
|
150
|
+
const file = join(directory, randomUUID())
|
|
151
|
+
const fd = openSync(file, constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_RDWR, 0o600)
|
|
152
|
+
const stat = fstatSync(fd)
|
|
153
|
+
|
|
154
|
+
return { scope, sessionID, agent, counter: counterValue, directory, workdir, fd,
|
|
155
|
+
identity: { dev: stat.dev, ino: stat.ino, uid: stat.uid }, expires: Date.now() + captureTimeout,
|
|
156
|
+
command: captureCommand(file) }
|
|
157
|
+
} catch (error) {
|
|
158
|
+
rmSync(directory, { recursive: true, force: true })
|
|
159
|
+
throw error
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function cleanup(pending: Pending): void {
|
|
164
|
+
if (pending.closed === true) return
|
|
165
|
+
|
|
166
|
+
pending.closed = true
|
|
167
|
+
closeSync(pending.fd)
|
|
168
|
+
rmSync(pending.directory, { recursive: true, force: true })
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function decode(line: string): string {
|
|
172
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(line)) throw new Error("Invalid capture framing")
|
|
173
|
+
|
|
174
|
+
return Buffer.from(line, "base64").toString("utf8")
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function importCapture(pending: Pending): Baseline {
|
|
178
|
+
const stat = fstatSync(pending.fd)
|
|
179
|
+
|
|
180
|
+
if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino ||
|
|
181
|
+
stat.uid !== pending.identity.uid || (stat.mode & 0o777) !== 0o600 || stat.size > maxBytes || stat.size === 0) {
|
|
182
|
+
throw new Error("Invalid private capture artifact")
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const bytes = Buffer.alloc(stat.size)
|
|
186
|
+
|
|
187
|
+
if (readSync(pending.fd, bytes, 0, stat.size, 0) !== stat.size) throw new Error("Incomplete private capture artifact")
|
|
188
|
+
|
|
189
|
+
const completed = fstatSync(pending.fd)
|
|
190
|
+
|
|
191
|
+
if (completed.size !== stat.size || completed.dev !== stat.dev || completed.ino !== stat.ino) throw new Error("Capture changed during import")
|
|
192
|
+
|
|
193
|
+
const fields = bytes.toString("utf8").split("\n")
|
|
194
|
+
|
|
195
|
+
if (fields.length !== 15 || fields[0] !== "CTX1" || fields[13] !== "END" || fields[14] !== "") throw new Error("Incomplete capture")
|
|
196
|
+
const root = decode(fields[1]!).trimEnd()
|
|
197
|
+
const gitDir = decode(fields[2]!).trimEnd()
|
|
198
|
+
const commonDir = decode(fields[3]!).trimEnd()
|
|
199
|
+
const branch = fields[4] === "branch" ? decode(fields[5]!).trimEnd() : null
|
|
200
|
+
const head = fields[6] === "head" ? decode(fields[7]!).trim() : null
|
|
201
|
+
const rawLog = decode(fields[8]!)
|
|
202
|
+
const messages = head === null ? [] : rawLog.split("\0\0").filter((message) => message.length > 0)
|
|
203
|
+
|
|
204
|
+
if (!root.startsWith("/") || !gitDir.startsWith("/") || !commonDir.startsWith("/") ||
|
|
205
|
+
relative(root, pending.workdir).startsWith("..") ||
|
|
206
|
+
!["branch", "detached"].includes(fields[4]!) || !["head", "unborn"].includes(fields[6]!) ||
|
|
207
|
+
(head !== null && !/^[a-f0-9]{40,64}$/.test(head)) ||
|
|
208
|
+
(head === null && rawLog !== "") || (head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\0\0")))) throw new Error("Invalid Git baseline")
|
|
209
|
+
const configState = fields[9]
|
|
210
|
+
const value = decode(fields[10]!).trim()
|
|
211
|
+
|
|
212
|
+
const gpgsign = configState === "set" && (value === "true" || value === "false") ? value :
|
|
213
|
+
configState === "unset" ? "unset" : "error"
|
|
214
|
+
|
|
215
|
+
const signingkey = fields[11] === "set" ? decode(fields[12]!).trim() : fields[11] === "unset" ? null : "error"
|
|
216
|
+
|
|
217
|
+
return { directory: root, workdir: pending.workdir, gitDir, commonDir, branch, head, messages, gpgsign, signingkey }
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function publish(ctx: Context, pending: Pending, generation: string, baseline: Baseline): Effect.Effect<boolean> {
|
|
221
|
+
return storageLock.withPermits(1)(Effect.gen(function*() {
|
|
222
|
+
if ((yield* counter(ctx, pending.scope)) !== pending.counter) return false
|
|
223
|
+
const sequence = `${Date.now().toString().padStart(15, "0")}-${randomUUID()}`
|
|
224
|
+
const checksum = digest(JSON.stringify([version, pending.scope, pending.counter, generation, sequence, baseline]))
|
|
225
|
+
|
|
226
|
+
yield* ctx.storage.set(prefix(pending.scope) + sequence, {
|
|
227
|
+
schema: version,
|
|
228
|
+
scope: pending.scope,
|
|
229
|
+
counter: pending.counter,
|
|
230
|
+
generation,
|
|
231
|
+
sequence,
|
|
232
|
+
checksum,
|
|
233
|
+
baseline: { ...baseline, messages: [...baseline.messages] },
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
let after: string | undefined
|
|
237
|
+
|
|
238
|
+
do {
|
|
239
|
+
const page = yield* ctx.storage.scan({ prefix: prefix(pending.scope), after, limit: 100 })
|
|
240
|
+
|
|
241
|
+
for (const record of page.entries) {
|
|
242
|
+
if (record.key < prefix(pending.scope) + sequence) yield* ctx.storage.remove(record.key)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
after = page.next
|
|
246
|
+
} while (after !== undefined)
|
|
247
|
+
|
|
248
|
+
return true
|
|
249
|
+
}))
|
|
250
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -60,21 +60,14 @@ export function parseConfig(options: JsonValue | undefined): CommitGuardConfig {
|
|
|
60
60
|
maxLineLength = rawMaxLineLength as number
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (rawRequireSignoff !== undefined) {
|
|
67
|
-
if (!isJSONBoolean(rawRequireSignoff)) {
|
|
68
|
-
throw new Error("Invalid plugin option requireSignoff; expected a boolean.")
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
requireSignoff = rawRequireSignoff
|
|
63
|
+
if (options["requireSignoff"] !== undefined) {
|
|
64
|
+
throw new Error("Plugin option requireSignoff has been removed; signoff follows the captured effective commit.gpgsign value.")
|
|
72
65
|
}
|
|
73
66
|
|
|
74
67
|
return {
|
|
75
68
|
requireScope,
|
|
76
69
|
allowedScopes,
|
|
77
70
|
maxLineLength,
|
|
78
|
-
|
|
71
|
+
enforceSignoff: defaultConfig.enforceSignoff,
|
|
79
72
|
}
|
|
80
73
|
}
|
package/src/plugin.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { Plugin } from "@opencode/plugin/effect"
|
|
2
2
|
import { Tool } from "@opencode/schema/tool"
|
|
3
3
|
import { Effect } from "effect"
|
|
4
|
+
import { randomUUID } from "node:crypto"
|
|
5
|
+
import { captureTimeout, cleanup, createPending, importCapture, invalidate, publish, scopeFor, counter, load } from "./capture.js"
|
|
6
|
+
import type { Pending } from "./capture.js"
|
|
4
7
|
import { parseConfig } from "./config.js"
|
|
5
8
|
import { extractGitCommits } from "./shell.js"
|
|
6
9
|
import { isJSONString, isRecord } from "./types.js"
|
|
@@ -15,8 +18,92 @@ export const plugin = Plugin.define({
|
|
|
15
18
|
return parseConfig(ctx.options as JsonValue | undefined)
|
|
16
19
|
})
|
|
17
20
|
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
const generation = randomUUID()
|
|
22
|
+
const pending = new Map<string, Pending>()
|
|
23
|
+
const preparing = new Set<string>()
|
|
24
|
+
|
|
25
|
+
yield* Effect.addFinalizer(() => Effect.gen(function*() {
|
|
26
|
+
for (const attempt of pending.values()) {
|
|
27
|
+
cleanup(attempt)
|
|
28
|
+
yield* invalidate(ctx, attempt.scope)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
pending.clear()
|
|
32
|
+
}))
|
|
33
|
+
|
|
34
|
+
yield* ctx.tool.transform((editor) => editor.add({
|
|
35
|
+
name: "commit_context",
|
|
36
|
+
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.",
|
|
37
|
+
input: { type: "object", properties: { refresh: { type: "boolean" } }, additionalProperties: false },
|
|
38
|
+
execute: (input, toolContext) => Effect.gen(function*() {
|
|
39
|
+
if (ctx.location.workspaceID !== undefined) return { content: "Commit context capture is unavailable for remote workspaces." }
|
|
40
|
+
|
|
41
|
+
const session = yield* ctx.session.get({ sessionID: toolContext.sessionID })
|
|
42
|
+
|
|
43
|
+
if (session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID) {
|
|
44
|
+
return { content: "The session moved to another worktree. Call commit_context from its new location." }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const scope = scopeFor(ctx, toolContext.sessionID, config)
|
|
48
|
+
|
|
49
|
+
if (preparing.has(scope)) return { content: "A commit context capture is preparing for this session. Call commit_context again." }
|
|
50
|
+
|
|
51
|
+
preparing.add(scope)
|
|
52
|
+
|
|
53
|
+
return yield* Effect.gen(function*() {
|
|
54
|
+
// SAFETY: The tool input schema permits only a refresh boolean.
|
|
55
|
+
const request = input as { refresh?: boolean }
|
|
56
|
+
const previous = pending.get(scope)
|
|
57
|
+
|
|
58
|
+
if (previous !== undefined) {
|
|
59
|
+
if (Date.now() < previous.expires && request.refresh !== true) return { content: `Run this shell command with workdir ${ctx.location.directory} and background:false, then call commit_context again:\n${previous.command}` }
|
|
60
|
+
pending.delete(scope)
|
|
61
|
+
cleanup(previous)
|
|
62
|
+
yield* invalidate(ctx, scope)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (request.refresh !== true) {
|
|
66
|
+
const baseline = yield* load(ctx, scope)
|
|
67
|
+
|
|
68
|
+
if (baseline !== undefined && baseline.workdir === ctx.location.directory && baseline.gpgsign !== "error" && baseline.signingkey !== "error") {
|
|
69
|
+
const observed = [...new Set(baseline.messages.map((message) => message.split("\n")[0]?.match(/^([a-zA-Z0-9_./-]{1,40}): /)?.[1]).filter((value) => value !== undefined))].slice(0, 3)
|
|
70
|
+
const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.\n` : ""
|
|
71
|
+
|
|
72
|
+
const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." :
|
|
73
|
+
`Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`
|
|
74
|
+
|
|
75
|
+
return { content: `Frozen commit baseline for ${ctx.location.directory}.\n` +
|
|
76
|
+
`Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.\n` +
|
|
77
|
+
`${scopes}\n${examples}` +
|
|
78
|
+
`Effective commit.gpgsign: ${baseline.gpgsign}. Signoff ${baseline.gpgsign === "true" ? "required" : "not required"}; ` +
|
|
79
|
+
`signoff is not a cryptographic signature. user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}.\n` +
|
|
80
|
+
"Set refresh:true after a branch switch, changed signing settings, or changed commit instructions." }
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (request.refresh === true) yield* invalidate(ctx, scope)
|
|
85
|
+
const count = yield* counter(ctx, scope)
|
|
86
|
+
const attempt = yield* Effect.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, ctx.location.directory))
|
|
87
|
+
pending.set(scope, attempt)
|
|
88
|
+
|
|
89
|
+
return { content: `Run this shell command with workdir ${ctx.location.directory} and background:false, then call commit_context again:\n${attempt.command}` }
|
|
90
|
+
}).pipe(Effect.ensuring(Effect.sync(() => { preparing.delete(scope) })))
|
|
91
|
+
}).pipe(Effect.mapError(() => new Tool.Error({
|
|
92
|
+
message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout.",
|
|
93
|
+
}))),
|
|
94
|
+
}))
|
|
95
|
+
|
|
96
|
+
yield* ctx.shell.hook("create.before", (event) => Effect.sync(() => {
|
|
97
|
+
for (const attempt of pending.values()) {
|
|
98
|
+
if (attempt.claimed !== undefined && event.command === attempt.command && event.cwd === attempt.workdir) {
|
|
99
|
+
attempt.expires = Date.now() + captureTimeout
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}))
|
|
103
|
+
|
|
104
|
+
yield* ctx.tool.hook("execute.before", (event) => Effect.gen(function*() {
|
|
105
|
+
const parsed = yield* Effect.try({
|
|
106
|
+
try: () => {
|
|
20
107
|
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
21
108
|
return
|
|
22
109
|
}
|
|
@@ -34,19 +121,103 @@ export const plugin = Plugin.define({
|
|
|
34
121
|
return
|
|
35
122
|
}
|
|
36
123
|
|
|
124
|
+
for (const attempt of pending.values()) {
|
|
125
|
+
if (command !== attempt.command) continue
|
|
126
|
+
|
|
127
|
+
if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent ||
|
|
128
|
+
(rawInput["workdir"] !== ctx.location.directory ||
|
|
129
|
+
rawInput["background"] === true) || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
|
|
130
|
+
throw new Error("[commit-guard] Capture must use its exact foreground shell command in the original session and workdir. Call commit_context to refresh.")
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
attempt.claimed = { messageID: event.messageID, id: event.id }
|
|
134
|
+
attempt.expires = Date.now() + captureTimeout
|
|
135
|
+
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
|
|
37
139
|
const invocations = extractGitCommits(command)
|
|
38
140
|
|
|
39
141
|
if (invocations.length === 0) {
|
|
40
142
|
return
|
|
41
143
|
}
|
|
42
144
|
|
|
43
|
-
validateGitCommits(invocations, config, command)
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
: "[commit-guard] Git commit validation failed.",
|
|
49
|
-
|
|
145
|
+
validateGitCommits(invocations, { ...config, enforceSignoff: false }, command)
|
|
146
|
+
|
|
147
|
+
return { invocations, command, rawInput }
|
|
148
|
+
},
|
|
149
|
+
catch: (error) => new Tool.Error({
|
|
150
|
+
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
|
|
151
|
+
}),
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
if (parsed === undefined) return
|
|
155
|
+
|
|
156
|
+
if (ctx.location.workspaceID !== undefined) return yield* Effect.fail(new Tool.Error({
|
|
157
|
+
message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout.",
|
|
158
|
+
}))
|
|
159
|
+
|
|
160
|
+
const session = yield* ctx.session.get({ sessionID: event.sessionID })
|
|
161
|
+
|
|
162
|
+
if (session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID ||
|
|
163
|
+
parsed.rawInput["workdir"] !== undefined && parsed.rawInput["workdir"] !== ctx.location.directory ||
|
|
164
|
+
parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
|
|
165
|
+
return yield* Effect.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." }))
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const baseline = yield* load(ctx, scopeFor(ctx, event.sessionID, config))
|
|
169
|
+
|
|
170
|
+
if (baseline === undefined || baseline.workdir !== ctx.location.directory || baseline.gpgsign === "error" || baseline.signingkey === "error") {
|
|
171
|
+
return yield* Effect.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." }))
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
yield* Effect.try({
|
|
175
|
+
try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
|
|
176
|
+
catch: (error) => new Tool.Error({ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed." }),
|
|
177
|
+
})
|
|
178
|
+
}).pipe(Effect.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
|
|
179
|
+
message: "[commit-guard] Could not verify the commit target or signing baseline. Call commit_context from this checkout.",
|
|
180
|
+
}))))
|
|
181
|
+
|
|
182
|
+
yield* ctx.tool.hook("execute.after", (event) => Effect.gen(function*() {
|
|
183
|
+
if (event.tool !== "shell") return
|
|
184
|
+
|
|
185
|
+
const attempt = [...pending.values()].find((item) => item.claimed?.id === event.id &&
|
|
186
|
+
item.claimed?.messageID === event.messageID && item.sessionID === event.sessionID && item.agent === event.agent)
|
|
187
|
+
|
|
188
|
+
if (attempt === undefined) return
|
|
189
|
+
|
|
190
|
+
let published = false
|
|
191
|
+
|
|
192
|
+
yield* Effect.gen(function*() {
|
|
193
|
+
if (event.status !== "completed" || Date.now() >= attempt.expires ||
|
|
194
|
+
(yield* counter(ctx, attempt.scope)) !== attempt.counter) return
|
|
195
|
+
// SAFETY: Tool result metadata is untrusted JSON; verify every required field before import.
|
|
196
|
+
const metadata = event.result.metadata as JsonValue | undefined
|
|
197
|
+
|
|
198
|
+
if (!isRecord(metadata)) return
|
|
199
|
+
|
|
200
|
+
// OpenCode's shell tool reports completed/exit:0 after a foreground process exits.
|
|
201
|
+
// Continued jobs report running/shellID; timeouts report timeout:true without an exit.
|
|
202
|
+
if (metadata["status"] !== "completed" || metadata["exit"] !== 0 || metadata["truncated"] !== false ||
|
|
203
|
+
metadata["timeout"] !== undefined && metadata["timeout"] !== false || metadata["shellID"] !== undefined ||
|
|
204
|
+
Object.keys(metadata).some((key) => !["status", "exit", "truncated", "timeout"].includes(key))) return
|
|
205
|
+
|
|
206
|
+
const session = yield* Effect.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => undefined)
|
|
207
|
+
|
|
208
|
+
if (session === undefined || session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID) return
|
|
209
|
+
|
|
210
|
+
const baseline = yield* Effect.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") })
|
|
211
|
+
|
|
212
|
+
if (baseline.workdir !== ctx.location.directory || ctx.location.workspaceID !== undefined) return
|
|
213
|
+
published = yield* publish(ctx, attempt, generation, baseline)
|
|
214
|
+
}).pipe(Effect.onExit(() => Effect.gen(function*() {
|
|
215
|
+
if (pending.get(attempt.scope) === attempt) pending.delete(attempt.scope)
|
|
216
|
+
|
|
217
|
+
if (!published) yield* invalidate(ctx, attempt.scope)
|
|
218
|
+
|
|
219
|
+
yield* Effect.sync(() => cleanup(attempt))
|
|
220
|
+
})), Effect.catchCause(() => Effect.void))
|
|
50
221
|
}))
|
|
51
222
|
}),
|
|
52
223
|
})
|
package/src/shell.ts
CHANGED
|
@@ -8,6 +8,7 @@ const gitGlobalOptionsWithArg = new Set([
|
|
|
8
8
|
"--namespace",
|
|
9
9
|
"--exec-path",
|
|
10
10
|
"--super-prefix",
|
|
11
|
+
"--config-env",
|
|
11
12
|
])
|
|
12
13
|
|
|
13
14
|
const commandPrefixes = new Set([
|
|
@@ -22,6 +23,11 @@ const commandPrefixes = new Set([
|
|
|
22
23
|
"while",
|
|
23
24
|
])
|
|
24
25
|
|
|
26
|
+
const targetMutators = new Set([
|
|
27
|
+
"cd", "pushd", "popd", "chdir", "export", "typeset", "declare", "source", ".", "eval",
|
|
28
|
+
"set", "unset", "readonly", "local", "setenv",
|
|
29
|
+
])
|
|
30
|
+
|
|
25
31
|
const commitLongOptionsWithArg = new Set([
|
|
26
32
|
"--author",
|
|
27
33
|
"--cleanup",
|
|
@@ -570,6 +576,10 @@ function extractInvocation(
|
|
|
570
576
|
wordIndex++
|
|
571
577
|
let subcommand: string | undefined
|
|
572
578
|
|
|
579
|
+
let targetError = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word) || word === "export")
|
|
580
|
+
? "Environment or wrapper changes can redirect a Git commit target. Use a direct git commit in the captured workdir."
|
|
581
|
+
: undefined
|
|
582
|
+
|
|
573
583
|
while (wordIndex < words.length) {
|
|
574
584
|
const argument = words[wordIndex]
|
|
575
585
|
|
|
@@ -582,6 +592,10 @@ function extractInvocation(
|
|
|
582
592
|
}
|
|
583
593
|
|
|
584
594
|
if (gitGlobalOptionsWithArg.has(argument)) {
|
|
595
|
+
if (argument === "-C" || argument === "--git-dir" || argument === "--work-tree" || argument === "-c" || argument === "--config-env") {
|
|
596
|
+
targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir."
|
|
597
|
+
}
|
|
598
|
+
|
|
585
599
|
wordIndex += 2
|
|
586
600
|
continue
|
|
587
601
|
}
|
|
@@ -592,13 +606,19 @@ function extractInvocation(
|
|
|
592
606
|
argument.startsWith("--namespace=") ||
|
|
593
607
|
argument.startsWith("--exec-path=") ||
|
|
594
608
|
argument.startsWith("--super-prefix=") ||
|
|
609
|
+
argument.startsWith("--config-env=") ||
|
|
595
610
|
argument.startsWith("-c")
|
|
596
611
|
) {
|
|
612
|
+
if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
|
|
613
|
+
targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir."
|
|
614
|
+
}
|
|
615
|
+
|
|
597
616
|
wordIndex++
|
|
598
617
|
continue
|
|
599
618
|
}
|
|
600
619
|
|
|
601
620
|
if (argument.startsWith("-C")) {
|
|
621
|
+
targetError = "git -C can change the commit target. Run git commit directly in the captured workdir."
|
|
602
622
|
wordIndex++
|
|
603
623
|
continue
|
|
604
624
|
}
|
|
@@ -711,12 +731,14 @@ function extractInvocation(
|
|
|
711
731
|
hasNoEdit,
|
|
712
732
|
isFixup,
|
|
713
733
|
isHelp,
|
|
734
|
+
targetError,
|
|
714
735
|
}
|
|
715
736
|
}
|
|
716
737
|
|
|
717
|
-
export function extractGitCommits(command: string): GitCommitInvocation[] {
|
|
738
|
+
export function extractGitCommits(command: string, inheritedDirectoryChange = false): GitCommitInvocation[] {
|
|
718
739
|
const tokens = tokenizeShell(command)
|
|
719
740
|
const invocations: GitCommitInvocation[] = []
|
|
741
|
+
let changedDirectory = inheritedDirectoryChange
|
|
720
742
|
|
|
721
743
|
for (const simple of splitSimpleCommands(tokens)) {
|
|
722
744
|
const commandTokens = simple.tokens
|
|
@@ -724,9 +746,15 @@ export function extractGitCommits(command: string): GitCommitInvocation[] {
|
|
|
724
746
|
const commandStart = findCommandStart(words)
|
|
725
747
|
const invocation = extractInvocation(words, commandStart)
|
|
726
748
|
|
|
749
|
+
if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment)) changedDirectory = true
|
|
750
|
+
|
|
727
751
|
if (invocation !== undefined) {
|
|
752
|
+
const target = changedDirectory
|
|
753
|
+
? { ...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." }
|
|
754
|
+
: invocation
|
|
755
|
+
|
|
728
756
|
if (!invocation.filePaths.includes("-")) {
|
|
729
|
-
invocations.push(
|
|
757
|
+
invocations.push(target)
|
|
730
758
|
continue
|
|
731
759
|
}
|
|
732
760
|
|
|
@@ -751,7 +779,7 @@ export function extractGitCommits(command: string): GitCommitInvocation[] {
|
|
|
751
779
|
}
|
|
752
780
|
|
|
753
781
|
invocations.push({
|
|
754
|
-
...
|
|
782
|
+
...target,
|
|
755
783
|
stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined,
|
|
756
784
|
stdinError,
|
|
757
785
|
})
|
|
@@ -760,7 +788,7 @@ export function extractGitCommits(command: string): GitCommitInvocation[] {
|
|
|
760
788
|
|
|
761
789
|
for (const token of tokens) {
|
|
762
790
|
for (const substitution of token.substitutions ?? []) {
|
|
763
|
-
invocations.push(...extractGitCommits(substitution))
|
|
791
|
+
invocations.push(...extractGitCommits(substitution, changedDirectory))
|
|
764
792
|
}
|
|
765
793
|
}
|
|
766
794
|
|
package/src/types.ts
CHANGED
|
@@ -25,14 +25,14 @@ export interface CommitGuardConfig {
|
|
|
25
25
|
readonly requireScope: boolean
|
|
26
26
|
readonly allowedScopes?: readonly string[]
|
|
27
27
|
readonly maxLineLength: number
|
|
28
|
-
readonly
|
|
28
|
+
readonly enforceSignoff: boolean
|
|
29
29
|
}
|
|
30
30
|
|
|
31
31
|
export const defaultConfig: CommitGuardConfig = {
|
|
32
32
|
requireScope: true,
|
|
33
33
|
allowedScopes: undefined,
|
|
34
34
|
maxLineLength: 72,
|
|
35
|
-
|
|
35
|
+
enforceSignoff: true,
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
export type ShellTokenType = "word" | "operator" | "redirect"
|
|
@@ -54,6 +54,7 @@ export interface GitCommitInvocation {
|
|
|
54
54
|
readonly hasNoEdit?: boolean
|
|
55
55
|
readonly isFixup?: boolean
|
|
56
56
|
readonly isHelp: boolean
|
|
57
|
+
readonly targetError?: string
|
|
57
58
|
}
|
|
58
59
|
|
|
59
60
|
export interface OverlongLine {
|
package/src/validator.ts
CHANGED
|
@@ -65,17 +65,6 @@ export function validateGitCommits(
|
|
|
65
65
|
|
|
66
66
|
const collectedMessages: string[] = [...invocation.messages]
|
|
67
67
|
|
|
68
|
-
if (
|
|
69
|
-
invocation.isAmend &&
|
|
70
|
-
invocation.hasNoEdit === true &&
|
|
71
|
-
invocation.messages.length === 0
|
|
72
|
-
) {
|
|
73
|
-
allViolations.push(
|
|
74
|
-
'Cannot validate --amend --no-edit before shell permissions run because it would read the existing commit. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".',
|
|
75
|
-
)
|
|
76
|
-
continue
|
|
77
|
-
}
|
|
78
|
-
|
|
79
68
|
const filePath = invocation.filePaths.at(-1)
|
|
80
69
|
|
|
81
70
|
if (filePath !== undefined) {
|
|
@@ -97,6 +86,10 @@ export function validateGitCommits(
|
|
|
97
86
|
}
|
|
98
87
|
|
|
99
88
|
if (collectedMessages.length === 0) {
|
|
89
|
+
if (invocation.isAmend && invocation.hasNoEdit === true) {
|
|
90
|
+
continue
|
|
91
|
+
}
|
|
92
|
+
|
|
100
93
|
if (invocation.isFixup === true) {
|
|
101
94
|
continue
|
|
102
95
|
}
|
|
@@ -179,7 +172,7 @@ export function validateGitCommits(
|
|
|
179
172
|
}
|
|
180
173
|
}
|
|
181
174
|
|
|
182
|
-
if (config.
|
|
175
|
+
if (config.enforceSignoff) {
|
|
183
176
|
const hasSignoff = invocation.hasSignoffFlag || hasSignoffTrailer(lines)
|
|
184
177
|
|
|
185
178
|
if (!hasSignoff) {
|