opencode-commit-guard 1.0.3 → 1.0.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-commit-guard",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "OpenCode V2 plugin enforcing git commit format rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -21,14 +21,14 @@
21
21
  "prepack": "bun run build"
22
22
  },
23
23
  "dependencies": {
24
- "@opencode/plugin": "2.0.15",
25
- "@opencode/schema": "2.0.15",
24
+ "@opencode/plugin": "2.0.21",
25
+ "@opencode/schema": "2.0.21",
26
26
  "effect": "4.0.0-rc.112"
27
27
  },
28
28
  "devDependencies": {
29
- "@oxlint/plugins": "1.85.0",
29
+ "@oxlint/plugins": "1.86.0",
30
30
  "@types/bun": "1.4.2",
31
- "oxlint": "1.85.0",
31
+ "oxlint": "1.86.0",
32
32
  "typescript": "7.0.2"
33
33
  },
34
34
  "engines": {
package/src/capture.ts ADDED
@@ -0,0 +1,374 @@
1
+ import { createHash, randomUUID } from "node:crypto"
2
+ import { closeSync, constants, existsSync, fstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync, statSync } from "node:fs"
3
+ import { tmpdir } from "node:os"
4
+ import { dirname, join, relative, resolve } 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, targetDir?: string): string {
54
+ const location = ctx.location
55
+
56
+ return digest(JSON.stringify([version, location.project.id, sessionID, targetDir ?? location.directory, location.workspaceID ?? null,
57
+ policy, config.requireScope, config.allowedScopes ?? null, config.maxLineLength]))
58
+ }
59
+
60
+ export function isGitDirectory(dir: string): boolean {
61
+ try {
62
+ return existsSync(join(dir, ".git"))
63
+ } catch {
64
+ return false
65
+ }
66
+ }
67
+
68
+ export function findGitRoot(startDir: string): string | undefined {
69
+ let current: string
70
+
71
+ try {
72
+ current = realpathSync(startDir)
73
+ } catch {
74
+ return undefined
75
+ }
76
+
77
+ while (true) {
78
+ if (isGitDirectory(current)) {
79
+ return current
80
+ }
81
+
82
+ const parent = dirname(current)
83
+
84
+ if (parent === current) {
85
+ break
86
+ }
87
+
88
+ current = parent
89
+ }
90
+
91
+ return undefined
92
+ }
93
+
94
+ export interface ResolvedTargetWorkdir {
95
+ readonly workdir?: string
96
+ readonly error?: string
97
+ }
98
+
99
+ export function findSubRepos(dir: string, maxDepth = 2): string[] {
100
+ const repos: string[] = []
101
+
102
+ function search(currentDir: string, currentDepth: number): void {
103
+ if (currentDepth > maxDepth) return
104
+
105
+ try {
106
+ const entries = readdirSync(currentDir, { withFileTypes: true })
107
+
108
+ for (const entry of entries) {
109
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
110
+
111
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist") continue
112
+
113
+ const fullPath = join(currentDir, entry.name)
114
+
115
+ if (isGitDirectory(fullPath)) {
116
+ repos.push(fullPath)
117
+ } else if (currentDepth < maxDepth) {
118
+ search(fullPath, currentDepth + 1)
119
+ }
120
+ }
121
+ } catch {
122
+ // Inaccessible directory
123
+ }
124
+ }
125
+
126
+ search(dir, 1)
127
+
128
+ return repos
129
+ }
130
+
131
+ export function resolveTargetWorkdir(
132
+ baseDir: string,
133
+ requestedDir?: string,
134
+ ): ResolvedTargetWorkdir {
135
+ if (requestedDir !== undefined) {
136
+ const resolvedDir = resolve(baseDir, requestedDir)
137
+
138
+ if (!existsSync(resolvedDir)) {
139
+ return { error: `Directory "${requestedDir}" does not exist.` }
140
+ }
141
+
142
+ try {
143
+ if (!statSync(resolvedDir).isDirectory()) {
144
+ return { error: `Path "${requestedDir}" is not a directory.` }
145
+ }
146
+ } catch {
147
+ return { error: `Could not access directory "${requestedDir}".` }
148
+ }
149
+
150
+ const gitRoot = findGitRoot(resolvedDir)
151
+
152
+ if (gitRoot === undefined) {
153
+ return { error: `Directory "${requestedDir}" is not a Git repository or inside one.` }
154
+ }
155
+
156
+ return { workdir: realpathSync(resolvedDir) }
157
+ }
158
+
159
+ const currentGitRoot = findGitRoot(baseDir)
160
+
161
+ if (currentGitRoot !== undefined) {
162
+ return { workdir: realpathSync(baseDir) }
163
+ }
164
+
165
+ const subRepos = findSubRepos(baseDir)
166
+
167
+ if (subRepos.length === 1) {
168
+ return { workdir: realpathSync(subRepos[0]!) }
169
+ }
170
+
171
+ if (subRepos.length === 0) {
172
+ return {
173
+ error: `No Git repository found in ${baseDir}. Specify the repository directory with the 'workdir' option, for example: commit_context({ workdir: "path/to/repo" }).`,
174
+ }
175
+ }
176
+
177
+ const repoList = subRepos.map((repo) => relative(baseDir, repo)).join(", ")
178
+
179
+ return {
180
+ error: `The directory ${baseDir} is not a Git repository. Multiple Git repositories were found: ${repoList}.\nSpecify which repository to target with the 'workdir' option, for example:\ncommit_context({ workdir: "${relative(baseDir, subRepos[0]!)}" })`,
181
+ }
182
+ }
183
+
184
+ function counterKey(scope: string): string { return `counter/${scope}` }
185
+
186
+ function prefix(scope: string): string { return `snap/${scope}/` }
187
+
188
+ export function counter(ctx: Context, scope: string): Effect.Effect<number> {
189
+ return Effect.gen(function*() {
190
+ const value = yield* ctx.storage.get(counterKey(scope))
191
+
192
+ if (value === undefined) return 0
193
+
194
+ return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : -1
195
+ })
196
+ }
197
+
198
+ export function invalidate(ctx: Context, scope: string): Effect.Effect<void> {
199
+ return storageLock.withPermits(1)(Effect.gen(function*() {
200
+ const previous = yield* counter(ctx, scope)
201
+
202
+ yield* ctx.storage.set(counterKey(scope), previous < 0 ? 1 : previous + 1)
203
+ }))
204
+ }
205
+
206
+ function validBaseline(value: JsonValue | undefined): value is Baseline & Record<string, JsonValue> {
207
+ if (!isRecord(value)) return false
208
+
209
+ return ["directory", "workdir", "gitDir", "commonDir"].every((key) => isJSONString(value[key])) &&
210
+ (value["branch"] === null || isJSONString(value["branch"])) &&
211
+ (value["head"] === null || /^[0-9a-f]{40,64}$/.test(String(value["head"]))) &&
212
+ Array.isArray(value["messages"]) && value["messages"].length <= 10 &&
213
+ value["messages"].every((message: JsonValue) => isJSONString(message)) &&
214
+ ["true", "false", "unset", "error"].includes(String(value["gpgsign"])) &&
215
+ (value["signingkey"] === null || value["signingkey"] === "error" || isJSONString(value["signingkey"]))
216
+ }
217
+
218
+ export function load(ctx: Context, scope: string): Effect.Effect<Baseline | undefined> {
219
+ return storageLock.withPermits(1)(Effect.gen(function*() {
220
+ const current = yield* counter(ctx, scope)
221
+
222
+ if (current < 0) return undefined
223
+ let after: string | undefined
224
+ let newest: { sequence: string; baseline: Baseline } | undefined
225
+
226
+ do {
227
+ const page = yield* ctx.storage.scan({ prefix: prefix(scope), after, limit: 100 })
228
+
229
+ for (const record of page.entries) {
230
+ // SAFETY: Storage returns arbitrary JSON that is checked before reading any entry fields.
231
+ const raw = record.value as JsonValue
232
+
233
+ if (!isRecord(raw) || raw["schema"] !== version || raw["scope"] !== scope || raw["counter"] !== current ||
234
+ !isJSONString(raw["generation"]) || !isJSONString(raw["sequence"]) || !isJSONString(raw["checksum"]) ||
235
+ !validBaseline(raw["baseline"])) continue
236
+ const baseline = raw["baseline"]
237
+
238
+ if (digest(JSON.stringify([version, scope, current, raw["generation"], raw["sequence"], baseline])) !== raw["checksum"]) continue
239
+
240
+ if (newest === undefined || raw["sequence"] > newest.sequence) newest = { sequence: raw["sequence"], baseline }
241
+ }
242
+
243
+ after = page.next
244
+ } while (after !== undefined)
245
+
246
+ return newest?.baseline
247
+ }))
248
+ }
249
+
250
+ // Each line is a base64-encoded Git result. No Git output enters the shell result.
251
+ function captureCommand(path: string): string {
252
+ const quoted = `'${path.replaceAll("'", "'\\''")}'`
253
+
254
+ return `timeout 15s bash -c 'set -euo pipefail
255
+ ulimit -f 256
256
+ out=$1
257
+ printf "CTX1\\n" > "$out"
258
+ field() { "$@" 2>/dev/null | base64 -w0 >> "$out"; printf "\\n" >> "$out"; }
259
+ field git rev-parse --show-toplevel
260
+ field git rev-parse --absolute-git-dir
261
+ field git rev-parse --path-format=absolute --git-common-dir
262
+ 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
263
+ 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
264
+ 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
265
+ 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
266
+ printf "END\\n" >> "$out"
267
+ printf "RECEIPT_OK\\n"' bash ${quoted} 2>/dev/null`
268
+ }
269
+
270
+ export function createPending(scope: string, sessionID: string, agent: string, counterValue: number, workdir: string): Pending {
271
+ const directory = mkdtempSync(join(tmpdir(), "commit-context-"))
272
+
273
+ try {
274
+ const file = join(directory, randomUUID())
275
+ const fd = openSync(file, constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_RDWR, 0o600)
276
+ const stat = fstatSync(fd)
277
+
278
+ return { scope, sessionID, agent, counter: counterValue, directory, workdir, fd,
279
+ identity: { dev: stat.dev, ino: stat.ino, uid: stat.uid }, expires: Date.now() + captureTimeout,
280
+ command: captureCommand(file) }
281
+ } catch (error) {
282
+ rmSync(directory, { recursive: true, force: true })
283
+ throw error
284
+ }
285
+ }
286
+
287
+ export function cleanup(pending: Pending): void {
288
+ if (pending.closed === true) return
289
+
290
+ pending.closed = true
291
+ closeSync(pending.fd)
292
+ rmSync(pending.directory, { recursive: true, force: true })
293
+ }
294
+
295
+ function decode(line: string): string {
296
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(line)) throw new Error("Invalid capture framing")
297
+
298
+ return Buffer.from(line, "base64").toString("utf8")
299
+ }
300
+
301
+ export function importCapture(pending: Pending): Baseline {
302
+ const stat = fstatSync(pending.fd)
303
+
304
+ if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino ||
305
+ stat.uid !== pending.identity.uid || (stat.mode & 0o777) !== 0o600 || stat.size > maxBytes || stat.size === 0) {
306
+ throw new Error("Invalid private capture artifact")
307
+ }
308
+
309
+ const bytes = Buffer.alloc(stat.size)
310
+
311
+ if (readSync(pending.fd, bytes, 0, stat.size, 0) !== stat.size) throw new Error("Incomplete private capture artifact")
312
+
313
+ const completed = fstatSync(pending.fd)
314
+
315
+ if (completed.size !== stat.size || completed.dev !== stat.dev || completed.ino !== stat.ino) throw new Error("Capture changed during import")
316
+
317
+ const fields = bytes.toString("utf8").split("\n")
318
+
319
+ if (fields.length !== 15 || fields[0] !== "CTX1" || fields[13] !== "END" || fields[14] !== "") throw new Error("Incomplete capture")
320
+ const root = decode(fields[1]!).trimEnd()
321
+ const gitDir = decode(fields[2]!).trimEnd()
322
+ const commonDir = decode(fields[3]!).trimEnd()
323
+ const branch = fields[4] === "branch" ? decode(fields[5]!).trimEnd() : null
324
+ const head = fields[6] === "head" ? decode(fields[7]!).trim() : null
325
+ const rawLog = decode(fields[8]!)
326
+ const messages = head === null ? [] : rawLog.split("\0\0").filter((message) => message.length > 0)
327
+
328
+ if (!root.startsWith("/") || !gitDir.startsWith("/") || !commonDir.startsWith("/") ||
329
+ root !== findGitRoot(pending.workdir) ||
330
+ !["branch", "detached"].includes(fields[4]!) || !["head", "unborn"].includes(fields[6]!) ||
331
+ (head !== null && !/^[a-f0-9]{40,64}$/.test(head)) ||
332
+ (head === null && rawLog !== "") || (head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\0\0")))) throw new Error("Invalid Git baseline")
333
+ const configState = fields[9]
334
+ const value = decode(fields[10]!).trim()
335
+
336
+ const gpgsign = configState === "set" && (value === "true" || value === "false") ? value :
337
+ configState === "unset" ? "unset" : "error"
338
+
339
+ const signingkey = fields[11] === "set" ? decode(fields[12]!).trim() : fields[11] === "unset" ? null : "error"
340
+
341
+ return { directory: root, workdir: pending.workdir, gitDir, commonDir, branch, head, messages, gpgsign, signingkey }
342
+ }
343
+
344
+ export function publish(ctx: Context, pending: Pending, generation: string, baseline: Baseline): Effect.Effect<boolean> {
345
+ return storageLock.withPermits(1)(Effect.gen(function*() {
346
+ if ((yield* counter(ctx, pending.scope)) !== pending.counter) return false
347
+ const sequence = `${Date.now().toString().padStart(15, "0")}-${randomUUID()}`
348
+ const checksum = digest(JSON.stringify([version, pending.scope, pending.counter, generation, sequence, baseline]))
349
+
350
+ yield* ctx.storage.set(prefix(pending.scope) + sequence, {
351
+ schema: version,
352
+ scope: pending.scope,
353
+ counter: pending.counter,
354
+ generation,
355
+ sequence,
356
+ checksum,
357
+ baseline: { ...baseline, messages: [...baseline.messages] },
358
+ })
359
+
360
+ let after: string | undefined
361
+
362
+ do {
363
+ const page = yield* ctx.storage.scan({ prefix: prefix(pending.scope), after, limit: 100 })
364
+
365
+ for (const record of page.entries) {
366
+ if (record.key < prefix(pending.scope) + sequence) yield* ctx.storage.remove(record.key)
367
+ }
368
+
369
+ after = page.next
370
+ } while (after !== undefined)
371
+
372
+ return true
373
+ }))
374
+ }
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
- const rawRequireSignoff = options["requireSignoff"]
64
- let requireSignoff = defaultConfig.requireSignoff
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
- requireSignoff,
71
+ enforceSignoff: defaultConfig.enforceSignoff,
79
72
  }
80
73
  }