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/src/plugin.ts CHANGED
@@ -1,6 +1,23 @@
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 { existsSync, realpathSync } from "node:fs"
6
+ import { relative, resolve } from "node:path"
7
+ import {
8
+ captureTimeout,
9
+ cleanup,
10
+ counter,
11
+ createPending,
12
+ findGitRoot,
13
+ importCapture,
14
+ invalidate,
15
+ load,
16
+ publish,
17
+ resolveTargetWorkdir,
18
+ scopeFor,
19
+ } from "./capture.js"
20
+ import type { Pending } from "./capture.js"
4
21
  import { parseConfig } from "./config.js"
5
22
  import { extractGitCommits } from "./shell.js"
6
23
  import { isJSONString, isRecord } from "./types.js"
@@ -15,38 +32,283 @@ export const plugin = Plugin.define({
15
32
  return parseConfig(ctx.options as JsonValue | undefined)
16
33
  })
17
34
 
18
- yield* ctx.tool.hook("execute.before", (event) => Effect.try({
19
- try: () => {
20
- if (event.tool !== "shell" && event.tool !== "bash") {
21
- return
22
- }
35
+ const generation = randomUUID()
36
+ const pending = new Map<string, Pending>()
37
+ const preparing = new Set<string>()
38
+ const lastSessionWorkdir = new Map<string, string>()
39
+
40
+ yield* Effect.addFinalizer(() => Effect.gen(function*() {
41
+ for (const attempt of pending.values()) {
42
+ cleanup(attempt)
43
+ yield* invalidate(ctx, attempt.scope)
44
+ }
23
45
 
24
- // SAFETY: event.input is an unvalidated tool input payload from OpenCode runtime.
25
- const rawInput = event.input as JsonValue | undefined
46
+ pending.clear()
47
+ }))
48
+
49
+ yield* ctx.tool.transform((editor) => editor.add({
50
+ name: "commit_context",
51
+ description: "Prepare a private, permission-checked Git baseline. Run the returned shell command in the foreground, then call this tool again. Specify workdir if the Git repository is in a subdirectory or differs from the project directory. Set refresh to replace a frozen baseline.",
52
+ input: {
53
+ type: "object",
54
+ properties: {
55
+ refresh: { type: "boolean" },
56
+ workdir: { type: "string", description: "Working directory of the Git repository relative to the session directory or absolute." },
57
+ directory: { type: "string", description: "Path to the Git repository checkout (alias for workdir)." },
58
+ },
59
+ additionalProperties: false,
60
+ },
61
+ execute: (input, toolContext) => Effect.gen(function*() {
62
+ if (ctx.location.workspaceID !== undefined) return { content: "Commit context capture is unavailable for remote workspaces." }
26
63
 
27
- if (!isRecord(rawInput)) {
28
- return
64
+ const session = yield* ctx.session.get({ sessionID: toolContext.sessionID })
65
+
66
+ if (session.location.workspaceID !== ctx.location.workspaceID) {
67
+ return { content: "Commit context capture is unavailable for remote workspaces." }
29
68
  }
30
69
 
31
- const command = rawInput["command"]
70
+ // SAFETY: The tool input schema permits refresh, workdir, and directory.
71
+ const request = input as { refresh?: boolean; workdir?: string; directory?: string }
72
+
73
+ const requestedDir = isJSONString(request.workdir) ? request.workdir :
74
+ isJSONString(request.directory) ? request.directory : undefined
75
+
76
+ const sessionDirectory = session.location.directory ?? ctx.location.directory
77
+ let target = resolveTargetWorkdir(sessionDirectory, requestedDir)
78
+
79
+ if (target.workdir === undefined && requestedDir === undefined) {
80
+ const remembered = lastSessionWorkdir.get(toolContext.sessionID)
32
81
 
33
- if (!isJSONString(command)) {
34
- return
82
+ if (remembered !== undefined && existsSync(remembered) && findGitRoot(remembered) !== undefined) {
83
+ target = { workdir: remembered }
84
+ }
35
85
  }
36
86
 
37
- const invocations = extractGitCommits(command)
87
+ if (target.error !== undefined || target.workdir === undefined) {
88
+ return { content: target.error ?? "Could not determine target Git repository." }
89
+ }
90
+
91
+ const targetWorkdir = target.workdir
92
+
93
+ lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir)
94
+
95
+ const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir)
96
+
97
+ if (preparing.has(scope)) return { content: "A commit context capture is preparing for this session and checkout. Call commit_context again." }
98
+
99
+ preparing.add(scope)
100
+
101
+ return yield* Effect.gen(function*() {
102
+ const previous = pending.get(scope)
103
+
104
+ if (previous !== undefined) {
105
+ if (Date.now() < previous.expires && request.refresh !== true) {
106
+ return { content: `Run this shell command with workdir ${previous.workdir} and background:false, then call commit_context again:\n${previous.command}` }
107
+ }
108
+
109
+ pending.delete(scope)
110
+ cleanup(previous)
111
+ yield* invalidate(ctx, scope)
112
+ }
38
113
 
39
- if (invocations.length === 0) {
40
- return
114
+ if (request.refresh !== true) {
115
+ const baseline = yield* load(ctx, scope)
116
+
117
+ if (baseline !== undefined && (baseline.workdir === targetWorkdir || baseline.directory === targetWorkdir) && baseline.gpgsign !== "error" && baseline.signingkey !== "error") {
118
+ 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)
119
+ const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.\n` : ""
120
+
121
+ const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." :
122
+ `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`
123
+
124
+ return { content: `Frozen commit baseline for ${targetWorkdir}.\n` +
125
+ `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.\n` +
126
+ `${scopes}\n${examples}` +
127
+ `Effective commit.gpgsign: ${baseline.gpgsign}. Signoff ${baseline.gpgsign === "true" ? "required" : "not required"}; ` +
128
+ `signoff is not a cryptographic signature. user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}.\n` +
129
+ "Set refresh:true after a branch switch, changed signing settings, or changed commit instructions." }
130
+ }
131
+ }
132
+
133
+ if (request.refresh === true) yield* invalidate(ctx, scope)
134
+
135
+ const count = yield* counter(ctx, scope)
136
+ const attempt = yield* Effect.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, targetWorkdir))
137
+
138
+ pending.set(scope, attempt)
139
+
140
+ return { content: `Run this shell command with workdir ${targetWorkdir} and background:false, then call commit_context again:\n${attempt.command}` }
141
+ }).pipe(Effect.ensuring(Effect.sync(() => { preparing.delete(scope) })))
142
+ }).pipe(Effect.mapError(() => new Tool.Error({
143
+ message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout.",
144
+ }))),
145
+ }))
146
+
147
+ yield* ctx.shell.hook("create.before", (event) => Effect.sync(() => {
148
+ for (const attempt of pending.values()) {
149
+ if (attempt.claimed !== undefined && event.command === attempt.command && event.cwd === attempt.workdir) {
150
+ attempt.expires = Date.now() + captureTimeout
41
151
  }
152
+ }
153
+ }))
42
154
 
43
- validateGitCommits(invocations, config, command)
44
- },
45
- catch: (error) => new Tool.Error({
46
- message: error instanceof Error
47
- ? error.message
48
- : "[commit-guard] Git commit validation failed.",
49
- }),
155
+ yield* ctx.tool.hook("execute.before", (event) => Effect.gen(function*() {
156
+ const captureSession = event.tool === "shell" || event.tool === "bash"
157
+ ? yield* ctx.session.get({ sessionID: event.sessionID }) : undefined
158
+
159
+ const captureSessionDirectory = captureSession?.location.directory ?? ctx.location.directory
160
+
161
+ const parsed = yield* Effect.try({
162
+ try: () => {
163
+ if (event.tool !== "shell" && event.tool !== "bash") {
164
+ return
165
+ }
166
+
167
+ // SAFETY: event.input is an unvalidated tool input payload from OpenCode runtime.
168
+ const rawInput = event.input as JsonValue | undefined
169
+
170
+ if (!isRecord(rawInput)) {
171
+ return
172
+ }
173
+
174
+ const command = rawInput["command"]
175
+
176
+ if (!isJSONString(command)) {
177
+ return
178
+ }
179
+
180
+ const rawWorkdir = rawInput["workdir"]
181
+
182
+ for (const attempt of pending.values()) {
183
+ if (command !== attempt.command) continue
184
+
185
+ const matchesWorkdir = rawWorkdir === attempt.workdir ||
186
+ (isJSONString(rawWorkdir) && resolve(captureSessionDirectory, rawWorkdir) === attempt.workdir) ||
187
+ (rawWorkdir === undefined && captureSessionDirectory === attempt.workdir)
188
+
189
+ if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent ||
190
+ !matchesWorkdir ||
191
+ rawInput["background"] === true || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
192
+ throw new Error("[commit-guard] Capture must use its exact foreground shell command in the original session and workdir. Call commit_context to refresh.")
193
+ }
194
+
195
+ attempt.claimed = { messageID: event.messageID, id: event.id }
196
+ attempt.expires = Date.now() + captureTimeout
197
+
198
+ return
199
+ }
200
+
201
+ const invocations = extractGitCommits(command)
202
+
203
+ if (invocations.length === 0) {
204
+ return
205
+ }
206
+
207
+ validateGitCommits(invocations, { ...config, enforceSignoff: false }, command)
208
+
209
+ return { invocations, command, rawInput }
210
+ },
211
+ catch: (error) => new Tool.Error({
212
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
213
+ }),
214
+ })
215
+
216
+ if (parsed === undefined) return
217
+
218
+ if (ctx.location.workspaceID !== undefined) return yield* Effect.fail(new Tool.Error({
219
+ message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout.",
220
+ }))
221
+
222
+ const session = yield* ctx.session.get({ sessionID: event.sessionID })
223
+
224
+ if (session.location.workspaceID !== ctx.location.workspaceID ||
225
+ parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
226
+ return yield* Effect.fail(new Tool.Error({
227
+ 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.",
228
+ }))
229
+ }
230
+
231
+ const sessionDirectory = session.location.directory ?? ctx.location.directory
232
+ const rawWorkdir = parsed.rawInput["workdir"]
233
+
234
+ const effectiveWorkdir = yield* Effect.try(() => realpathSync(
235
+ isJSONString(rawWorkdir) ? resolve(sessionDirectory, rawWorkdir) : sessionDirectory,
236
+ ))
237
+
238
+ const targetGitRoot = findGitRoot(effectiveWorkdir)
239
+ let scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir)
240
+ let baseline = yield* load(ctx, scope)
241
+
242
+ if (baseline === undefined && targetGitRoot !== undefined && targetGitRoot !== effectiveWorkdir) {
243
+ scope = scopeFor(ctx, event.sessionID, config, targetGitRoot)
244
+ baseline = yield* load(ctx, scope)
245
+ }
246
+
247
+ const expectedDir = targetGitRoot ?? effectiveWorkdir
248
+
249
+ const baselineValid = baseline !== undefined &&
250
+ targetGitRoot !== undefined && baseline.directory === targetGitRoot &&
251
+ (baseline.workdir === effectiveWorkdir || baseline.directory === expectedDir) &&
252
+ baseline.gpgsign !== "error" && baseline.signingkey !== "error"
253
+
254
+ if (!baselineValid || baseline === undefined) {
255
+ const relWorkdir = relative(sessionDirectory, expectedDir)
256
+ const workdirHint = relWorkdir.length > 0 && !relWorkdir.startsWith("..") ? `{ workdir: "${relWorkdir}" }` : ""
257
+
258
+ return yield* Effect.fail(new Tool.Error({
259
+ message: `[commit-guard] No valid signing baseline for this checkout. Call commit_context(${workdirHint}), run its authorized foreground shell command, then call commit_context again before committing.`,
260
+ }))
261
+ }
262
+
263
+ yield* Effect.try({
264
+ try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
265
+ catch: (error) => new Tool.Error({
266
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
267
+ }),
268
+ })
269
+ }).pipe(Effect.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
270
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
271
+ }))))
272
+
273
+ yield* ctx.tool.hook("execute.after", (event) => Effect.gen(function*() {
274
+ if (event.tool !== "shell") return
275
+
276
+ const attempt = [...pending.values()].find((item) => item.claimed?.id === event.id &&
277
+ item.claimed?.messageID === event.messageID && item.sessionID === event.sessionID && item.agent === event.agent)
278
+
279
+ if (attempt === undefined) return
280
+
281
+ let published = false
282
+
283
+ yield* Effect.gen(function*() {
284
+ if (event.status !== "completed" || Date.now() >= attempt.expires ||
285
+ (yield* counter(ctx, attempt.scope)) !== attempt.counter) return
286
+ // SAFETY: Tool result metadata is untrusted JSON; verify every required field before import.
287
+ const metadata = event.result.metadata as JsonValue | undefined
288
+
289
+ if (!isRecord(metadata)) return
290
+
291
+ // OpenCode's shell tool reports completed/exit:0 after a foreground process exits.
292
+ // Continued jobs report running/shellID; timeouts report timeout:true without an exit.
293
+ if (metadata["status"] !== "completed" || metadata["exit"] !== 0 || metadata["truncated"] !== false ||
294
+ metadata["timeout"] !== undefined && metadata["timeout"] !== false || metadata["shellID"] !== undefined ||
295
+ Object.keys(metadata).some((key) => !["status", "exit", "truncated", "timeout"].includes(key))) return
296
+
297
+ const session = yield* Effect.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => undefined)
298
+
299
+ if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID) return
300
+
301
+ const baseline = yield* Effect.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") })
302
+
303
+ if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined) return
304
+ published = yield* publish(ctx, attempt, generation, baseline)
305
+ }).pipe(Effect.onExit(() => Effect.gen(function*() {
306
+ if (pending.get(attempt.scope) === attempt) pending.delete(attempt.scope)
307
+
308
+ if (!published) yield* invalidate(ctx, attempt.scope)
309
+
310
+ yield* Effect.sync(() => cleanup(attempt))
311
+ })), Effect.catchCause(() => Effect.void))
50
312
  }))
51
313
  }),
52
314
  })
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(invocation)
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
- ...invocation,
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 requireSignoff: boolean
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
- requireSignoff: true,
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.requireSignoff) {
175
+ if (config.enforceSignoff) {
183
176
  const hasSignoff = invocation.hasSignoffFlag || hasSignoffTrailer(lines)
184
177
 
185
178
  if (!hasSignoff) {