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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-commit-guard",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
4
4
|
"description": "OpenCode V2 plugin enforcing git commit format rules",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -21,15 +21,15 @@
|
|
|
21
21
|
"prepack": "bun run build"
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@opencode/plugin": "2.0.
|
|
25
|
-
"@opencode/schema": "2.0.
|
|
24
|
+
"@opencode/plugin": "2.0.15",
|
|
25
|
+
"@opencode/schema": "2.0.15",
|
|
26
26
|
"effect": "4.0.0-rc.112"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
|
-
"@oxlint/plugins": "1.
|
|
30
|
-
"@types/bun": "
|
|
31
|
-
"oxlint": "1.
|
|
32
|
-
"typescript": "
|
|
29
|
+
"@oxlint/plugins": "1.85.0",
|
|
30
|
+
"@types/bun": "1.4.2",
|
|
31
|
+
"oxlint": "1.85.0",
|
|
32
|
+
"typescript": "7.0.2"
|
|
33
33
|
},
|
|
34
34
|
"engines": {
|
|
35
35
|
"bun": ">=1.2.0"
|
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,11 +1,14 @@
|
|
|
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"
|
|
7
10
|
import type { JsonValue } from "./types.js"
|
|
8
|
-
import {
|
|
11
|
+
import { validateGitCommits } from "./validator.js"
|
|
9
12
|
|
|
10
13
|
export const plugin = Plugin.define({
|
|
11
14
|
id: "opencode-commit-guard",
|
|
@@ -15,11 +18,92 @@ export const plugin = Plugin.define({
|
|
|
15
18
|
return parseConfig(ctx.options as JsonValue | undefined)
|
|
16
19
|
})
|
|
17
20
|
|
|
18
|
-
const
|
|
19
|
-
const
|
|
21
|
+
const generation = randomUUID()
|
|
22
|
+
const pending = new Map<string, Pending>()
|
|
23
|
+
const preparing = new Set<string>()
|
|
20
24
|
|
|
21
|
-
yield*
|
|
22
|
-
|
|
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: () => {
|
|
23
107
|
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
24
108
|
return
|
|
25
109
|
}
|
|
@@ -37,7 +121,18 @@ export const plugin = Plugin.define({
|
|
|
37
121
|
return
|
|
38
122
|
}
|
|
39
123
|
|
|
40
|
-
|
|
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
|
+
|
|
41
136
|
return
|
|
42
137
|
}
|
|
43
138
|
|
|
@@ -47,22 +142,82 @@ export const plugin = Plugin.define({
|
|
|
47
142
|
return
|
|
48
143
|
}
|
|
49
144
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
message:
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
})
|
|
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))
|
|
66
221
|
}))
|
|
67
222
|
}),
|
|
68
223
|
})
|