opencode-commit-guard 1.0.7 → 1.1.1

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/src/plugin.ts DELETED
@@ -1,418 +0,0 @@
1
- import { Plugin } from "@opencode/plugin/effect"
2
- import { Tool } from "@opencode/schema/tool"
3
- import { Effect } from "effect"
4
- import { randomUUID } from "node:crypto"
5
- import { existsSync, realpathSync } from "node:fs"
6
- import { relative, resolve } from "node:path"
7
- import {
8
- captureStatus,
9
- cleanup,
10
- counter,
11
- createPending,
12
- findGitRoot,
13
- importCapture,
14
- invalidate,
15
- invalidateOwned,
16
- load,
17
- publish,
18
- recordState,
19
- resolveTargetWorkdir,
20
- scopeFor,
21
- } from "./capture.js"
22
- import type { Baseline, Pending } from "./capture.js"
23
- import { parseConfig } from "./config.js"
24
- import { extractGitCommits } from "./shell.js"
25
- import { isJSONString, isRecord } from "./types.js"
26
- import type { CommitGuardConfig, JsonValue } from "./types.js"
27
- import { validateGitCommits } from "./validator.js"
28
-
29
- export const plugin = Plugin.define({
30
- id: "opencode-commit-guard",
31
- effect: (ctx) => Effect.gen(function*() {
32
- const config = yield* Effect.sync(() => {
33
- // SAFETY: OpenCode plugin options are passed through ctx.options as JsonValue or undefined.
34
- return parseConfig(ctx.options as JsonValue | undefined)
35
- })
36
-
37
- const generation = randomUUID()
38
- const pending = new Map<string, Pending>()
39
- const preparing = new Set<string>()
40
- const lastSessionWorkdir = new Map<string, string>()
41
- const failures = new Map<string, string>()
42
-
43
- const rememberFailure = (scope: string, reason: string) => {
44
- failures.delete(scope)
45
- failures.set(scope, `The previous capture failed: ${reason.slice(0, 256)}. `)
46
-
47
- if (failures.size > 128) failures.delete(failures.keys().next().value!)
48
- }
49
-
50
- const sweep = () => Effect.gen(function*() {
51
- for (const attempt of [...pending.values()].slice(0, 32)) {
52
- pending.delete(attempt.scope)
53
-
54
- if (attempt.claimed === undefined && Date.now() >= attempt.expires) {
55
- cleanup(attempt)
56
- yield* recordState(ctx, attempt, "expired")
57
- yield* invalidateOwned(ctx, attempt)
58
- } else pending.set(attempt.scope, attempt)
59
- }
60
- })
61
-
62
- yield* Effect.addFinalizer(() => Effect.gen(function*() {
63
- for (const attempt of pending.values()) {
64
- cleanup(attempt)
65
- yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication")
66
- yield* invalidateOwned(ctx, attempt)
67
- }
68
-
69
- pending.clear()
70
- }))
71
-
72
- yield* ctx.tool.transform((editor) => editor.add({
73
- name: "commit_context",
74
- description: String.raw`Prepare a Git baseline. Run the returned command unchanged in the foreground; require "Frozen commit baseline".
75
- Call before your first commit in each session and checkout.
76
- Set workdir when targeting another repository.
77
- Run the returned command immediately, unchanged, with the indicated workdir and background:false.
78
- Do not wrap it or chain another command onto it.
79
- Commit only after the shell result or this tool reports "Frozen commit baseline".
80
- RECEIPT_OK alone is insufficient.
81
- The shell result includes commit rules; a second call is optional.
82
- Repeat an explicit workdir when checking that checkout.
83
- Set refresh:true after switching branches, changing signing settings, or changing commit instructions.
84
- Use literal message text and real body newlines.
85
- Example: git commit -m $'scope: Subject\n\nBody line one.\nBody line two.'
86
- Replace scope and follow the returned line-length and signoff rules.
87
- Add -s only when the returned policy or repository instructions require it.`,
88
- input: {
89
- type: "object",
90
- properties: {
91
- refresh: { type: "boolean" },
92
- workdir: { type: "string", description: "Working directory of the Git repository relative to the session directory or absolute." },
93
- directory: { type: "string", description: "Path to the Git repository checkout (alias for workdir)." },
94
- },
95
- additionalProperties: false,
96
- },
97
- execute: (input, toolContext) => Effect.gen(function*() {
98
- yield* sweep()
99
-
100
- if (ctx.location.workspaceID !== undefined) return { content: "Commit context capture is unavailable for remote workspaces." }
101
-
102
- const session = yield* ctx.session.get({ sessionID: toolContext.sessionID })
103
-
104
- if (session.location.workspaceID !== ctx.location.workspaceID) {
105
- return { content: "Commit context capture is unavailable for remote workspaces." }
106
- }
107
-
108
- // SAFETY: The tool input schema permits refresh, workdir, and directory.
109
- const request = input as { refresh?: boolean; workdir?: string; directory?: string }
110
-
111
- const requestedDir = isJSONString(request.workdir) ? request.workdir :
112
- isJSONString(request.directory) ? request.directory : undefined
113
-
114
- const sessionDirectory = session.location.directory ?? ctx.location.directory
115
- let target = resolveTargetWorkdir(sessionDirectory, requestedDir)
116
-
117
- if (target.workdir === undefined && requestedDir === undefined) {
118
- const remembered = lastSessionWorkdir.get(toolContext.sessionID)
119
-
120
- if (remembered !== undefined && existsSync(remembered) && findGitRoot(remembered) !== undefined) {
121
- target = { workdir: remembered }
122
- }
123
- }
124
-
125
- if (target.error !== undefined || target.workdir === undefined) {
126
- return { content: target.error ?? "Could not determine target Git repository." }
127
- }
128
-
129
- const targetWorkdir = target.workdir
130
-
131
- lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir)
132
-
133
- const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir)
134
-
135
- if (preparing.has(scope)) return { content: "A commit context capture is preparing for this session and checkout. Wait for its command, then follow its instructions." }
136
-
137
- preparing.add(scope)
138
-
139
- return yield* Effect.gen(function*() {
140
- const previous = pending.get(scope)
141
-
142
- if (previous !== undefined) {
143
- if (previous.claimed !== undefined && request.refresh !== true) {
144
- return { content: 'Capture claimed; permission approval or execution is pending. Wait for its foreground shell result. Commit after it reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing. RECEIPT_OK confirms only that the artifact was written, not that the baseline was published.' }
145
- }
146
-
147
- if (request.refresh !== true) {
148
- return { content: captureInstructions(previous, "Capture still pending and unclaimed. ") }
149
- }
150
-
151
- pending.delete(scope)
152
- cleanup(previous)
153
- yield* recordState(ctx, previous, "failed", "capture replaced by refresh")
154
- yield* invalidateOwned(ctx, previous)
155
- }
156
-
157
- if (request.refresh !== true) {
158
- const baseline = yield* load(ctx, scope)
159
-
160
- if (baseline !== undefined && baseline.directory === findGitRoot(targetWorkdir)) {
161
- return { content: baselineGuidance(baseline, config) }
162
- }
163
- }
164
-
165
- const count = yield* invalidate(ctx, scope)
166
- const attempt = yield* Effect.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, targetWorkdir))
167
-
168
- pending.set(scope, attempt)
169
-
170
- const status = failures.get(scope) ?? (yield* captureStatus(ctx, scope))
171
-
172
- yield* recordState(ctx, attempt, "prepared")
173
-
174
- return { content: captureInstructions(attempt, status) }
175
- }).pipe(Effect.ensuring(Effect.sync(() => { preparing.delete(scope) })))
176
- }).pipe(Effect.mapError(() => new Tool.Error({
177
- message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout.",
178
- }))),
179
- }))
180
-
181
- yield* ctx.tool.hook("execute.before", (event) => Effect.gen(function*() {
182
- yield* sweep()
183
-
184
- const captureSession = event.tool === "shell" || event.tool === "bash"
185
- ? yield* ctx.session.get({ sessionID: event.sessionID }) : undefined
186
-
187
- const captureSessionDirectory = captureSession?.location.directory ?? ctx.location.directory
188
-
189
- const parsed = yield* Effect.try({
190
- try: () => {
191
- if (event.tool !== "shell" && event.tool !== "bash") {
192
- return
193
- }
194
-
195
- // SAFETY: event.input is an unvalidated tool input payload from OpenCode runtime.
196
- const rawInput = event.input as JsonValue | undefined
197
-
198
- if (!isRecord(rawInput)) {
199
- return
200
- }
201
-
202
- const command = rawInput["command"]
203
-
204
- if (!isJSONString(command)) {
205
- return
206
- }
207
-
208
- const rawWorkdir = rawInput["workdir"]
209
-
210
- for (const attempt of pending.values()) {
211
- if (command !== attempt.command) continue
212
-
213
- const matchesWorkdir = rawWorkdir === attempt.workdir ||
214
- (isJSONString(rawWorkdir) && resolve(captureSessionDirectory, rawWorkdir) === attempt.workdir) ||
215
- (rawWorkdir === undefined && captureSessionDirectory === attempt.workdir)
216
-
217
- if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent ||
218
- !matchesWorkdir ||
219
- rawInput["background"] === true || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
220
- throw new Error("[commit-guard] Capture must use its exact foreground shell command in the original session and workdir. Call commit_context to refresh.")
221
- }
222
-
223
- attempt.claimed = { messageID: event.messageID, id: event.id }
224
-
225
- return
226
- }
227
-
228
- const invocations = extractGitCommits(command)
229
-
230
- if (invocations.length === 0) {
231
- return
232
- }
233
-
234
- return { invocations, command, rawInput }
235
- },
236
- catch: (error) => new Tool.Error({
237
- message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
238
- }),
239
- })
240
-
241
- for (const attempt of pending.values()) {
242
- if (attempt.claimed?.messageID === event.messageID && attempt.claimed.id === event.id &&
243
- attempt.sessionID === event.sessionID && attempt.agent === event.agent) yield* recordState(ctx, attempt, "claimed")
244
- }
245
-
246
- if (parsed === undefined || parsed.invocations.every((invocation) => invocation.isHelp)) return
247
-
248
- if (ctx.location.workspaceID !== undefined) return yield* Effect.fail(new Tool.Error({
249
- message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout.",
250
- }))
251
-
252
- const session = yield* ctx.session.get({ sessionID: event.sessionID })
253
-
254
- if (session.location.workspaceID !== ctx.location.workspaceID ||
255
- parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
256
- return yield* Effect.fail(new Tool.Error({
257
- 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.",
258
- }))
259
- }
260
-
261
- const sessionDirectory = session.location.directory ?? ctx.location.directory
262
- const rawWorkdir = parsed.rawInput["workdir"]
263
-
264
- const effectiveWorkdir = yield* Effect.try(() => realpathSync(
265
- isJSONString(rawWorkdir) ? resolve(sessionDirectory, rawWorkdir) : sessionDirectory,
266
- ))
267
-
268
- const targetGitRoot = findGitRoot(effectiveWorkdir)
269
- const scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir)
270
- const baseline = yield* load(ctx, scope)
271
-
272
- const expectedDir = targetGitRoot ?? effectiveWorkdir
273
-
274
- const baselineValid = baseline !== undefined &&
275
- targetGitRoot !== undefined && baseline.directory === targetGitRoot &&
276
- baseline.directory === expectedDir
277
-
278
- if (!baselineValid || baseline === undefined) {
279
- const relWorkdir = relative(sessionDirectory, expectedDir)
280
- const workdirHint = JSON.stringify(relWorkdir.length > 0 ? relWorkdir : ".")
281
-
282
- return yield* Effect.fail(new Tool.Error({
283
- message: `[commit-guard] No published baseline for ${expectedDir}. Call commit_context({ workdir: ${workdirHint} }), then run the returned command immediately, unchanged, in the foreground with that workdir and background:false. Do not wrap it or chain another command onto it. Commit after the shell result reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing. RECEIPT_OK alone is insufficient.`,
284
- }))
285
- }
286
-
287
- if (baseline.gpgsign === "error" || baseline.signingkey === "error") return yield* Effect.fail(new Tool.Error({
288
- message: signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey"),
289
- }))
290
-
291
- yield* Effect.try({
292
- try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
293
- catch: (error) => new Tool.Error({
294
- message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
295
- }),
296
- })
297
- }).pipe(Effect.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
298
- message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
299
- }))))
300
-
301
- yield* ctx.tool.hook("execute.after", (event) => Effect.gen(function*() {
302
- if (event.tool !== "shell") return
303
-
304
- const attempt = [...pending.values()].find((item) => item.claimed?.id === event.id &&
305
- item.claimed?.messageID === event.messageID && item.sessionID === event.sessionID && item.agent === event.agent)
306
-
307
- if (attempt === undefined) return
308
-
309
- let published = false
310
- let captured: Baseline | undefined
311
- let reason = "capture import or storage failed"
312
-
313
- yield* Effect.gen(function*() {
314
- reason = "shell result did not complete successfully"
315
-
316
- if (event.status !== "completed") return
317
- reason = "capture was superseded by a refresh"
318
-
319
- if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) return
320
- // SAFETY: Tool result metadata is untrusted JSON; verify every required field before import.
321
- const metadata = event.result.metadata as JsonValue | undefined
322
-
323
- reason = "shell result lacks verified foreground completion metadata"
324
-
325
- if (!isRecord(metadata)) return
326
-
327
- // OpenCode's shell tool reports completed/exit:0 after a foreground process exits.
328
- // Continued jobs report running/shellID; timeouts report timeout:true without an exit.
329
- if (metadata["status"] !== "completed" || metadata["exit"] !== 0 || metadata["truncated"] !== false ||
330
- metadata["timeout"] !== undefined && metadata["timeout"] !== false || metadata["shellID"] !== undefined ||
331
- Object.keys(metadata).some((key) => !["status", "exit", "truncated", "timeout"].includes(key))) return
332
-
333
- const session = yield* Effect.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => undefined)
334
-
335
- reason = "capture session or workspace no longer matches"
336
-
337
- if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID) return
338
-
339
- reason = "private artifact is invalid or incomplete (END required)"
340
- const baseline = yield* Effect.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") })
341
-
342
- if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined) return
343
- reason = "capture storage failed or its counter changed"
344
- published = yield* publish(ctx, attempt, generation, baseline)
345
-
346
- if (published) {
347
- captured = baseline
348
- failures.delete(attempt.scope)
349
- yield* recordState(ctx, attempt, "published")
350
- }
351
- }).pipe(Effect.onExit(() => Effect.gen(function*() {
352
- if (pending.get(attempt.scope) === attempt) pending.delete(attempt.scope)
353
-
354
- if (!published) {
355
- rememberFailure(attempt.scope, reason)
356
- yield* recordState(ctx, attempt, "failed", reason).pipe(Effect.catchCause(() => Effect.void))
357
- yield* invalidateOwned(ctx, attempt)
358
- }
359
- }).pipe(Effect.ensuring(Effect.sync(() => cleanup(attempt))))), Effect.catchCause(() => Effect.void))
360
-
361
- const note = published && captured !== undefined ? baselineGuidance(captured, config) :
362
- `[commit-guard] This capture did not publish a usable baseline: ${reason.slice(0, 256)}.\n` +
363
- "RECEIPT_OK alone does not authorize a commit.\n" +
364
- "Call commit_context with the same workdir for status and next steps."
365
-
366
- if (event.status === "error") {
367
- event.error = new Tool.Error({ message: `${event.error.message}\n\n${note}` })
368
- } else event.result = appendCaptureNote(event.result, note)
369
- }))
370
- }),
371
- })
372
-
373
- export default plugin
374
-
375
- function captureInstructions(attempt: Pending, status: string): string {
376
- return `${status}Run this shell command immediately, unchanged, in the foreground with workdir ${attempt.workdir} and background:false. ` +
377
- 'Do not wrap it or chain another command onto it. Commit after the shell result reports "Frozen commit baseline"; ' +
378
- "otherwise call commit_context again with the same workdir before committing. " +
379
- `RECEIPT_OK confirms only that the artifact was written, not that the baseline was published:\n${attempt.command}`
380
- }
381
-
382
- function baselineGuidance(baseline: Baseline, config: CommitGuardConfig): string {
383
- if (baseline.gpgsign === "error" || baseline.signingkey === "error") return signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")
384
- 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)
385
- const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.\n` : ""
386
-
387
- const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." :
388
- `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`
389
-
390
- const signoff = baseline.gpgsign === "true" ? "Add -s or --signoff." :
391
- "Signoff is not required; add it only if repository instructions require it."
392
-
393
- return `[commit-guard] Frozen commit baseline for ${baseline.directory.slice(0, 4096)}.\n` +
394
- `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.\n` +
395
- `${scopes}\n${examples}Effective commit.gpgsign: ${baseline.gpgsign}. ${signoff}\n` +
396
- `user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}. Signoff is not a cryptographic signature.\n` +
397
- "A second commit_context call is optional.\n" +
398
- "Set refresh:true after a branch switch, changed signing settings, or changed commit instructions."
399
- }
400
-
401
- function appendCaptureNote(result: Tool.Result, note: string): Tool.Result {
402
- const content: readonly Tool.Content[] = Array.isArray(result.content) ? result.content :
403
- result.content === undefined ? [] : [{ type: "text", text: String(result.content) }]
404
-
405
- // SAFETY: Structured tool output is untrusted JSON; check the record and output field before copying it.
406
- const output = result.output as JsonValue | undefined
407
- const annotated: Tool.Result = { ...result, content: [...content, { type: "text", text: note }] }
408
-
409
- if (isRecord(output) && isJSONString(output["output"])) {
410
- return { ...annotated, output: { ...output, output: `${output["output"]}\n\n${note}` } }
411
- }
412
-
413
- return annotated
414
- }
415
-
416
- function signingError(setting: string): string {
417
- return `[commit-guard] Git could not read ${setting} as valid. Repeating the capture will not fix it. Inspect with git config --show-origin --get-all ${setting}; fix the value without changing the intended signing policy, then call commit_context with refresh:true.`
418
- }
package/src/scope.ts DELETED
@@ -1 +0,0 @@
1
- export const scopePattern = /^([a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(.+)$/