opencode-commit-guard 1.1.1 → 1.1.2

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.
Files changed (3) hide show
  1. package/README.md +69 -150
  2. package/dist/index.js +23 -18
  3. package/package.json +7 -6
package/README.md CHANGED
@@ -1,198 +1,117 @@
1
1
  # opencode-commit-guard
2
2
 
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.
3
+ This OpenCode V2 plugin checks Git commit messages before an agent runs `git commit`.
4
+ It requires `@opencode/plugin` 2.4.1 or newer.
5
5
 
6
6
  ## Overview
7
7
 
8
- `opencode-commit-guard` intercepts `shell` and `bash` tool execution before it runs.
9
- When an agent attempts a `git commit`, the plugin inspects the command line and inline message content.
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.
8
+ The plugin inspects every `shell` and `bash` tool call before it runs.
9
+ If a `git commit` breaks a formatting rule, the plugin rejects the tool call with an error.
10
+ The error lists each violation and shows a conforming example, so the agent can fix the message and retry.
12
11
 
13
- ### Why this approach fits
12
+ Before the first commit in each session and checkout, the agent captures a Git baseline with the `commit_context` tool.
13
+ The baseline records the effective `commit.gpgsign` setting, which determines whether a commit needs a signoff.
14
14
 
15
- - Operates strictly inside OpenCode agent sessions.
16
- - Leaves system git hooks, Gerrit Change-Id hooks, and repository configuration untouched.
17
- - Gives the agent an immediate error explaining the rule violation and providing a conforming example.
18
- - Allows the agent to correct the message and retry without corrupting repository state.
15
+ The plugin does not change Git hooks or repository configuration.
19
16
 
20
17
  ## Installation
21
18
 
22
- Add the plugin to your `opencode.json` configuration file:
19
+ Add the package to your `opencode.json` or `opencode.jsonc` file:
23
20
 
24
- ```json
21
+ ```jsonc
25
22
  {
23
+ "$schema": "https://opencode.ai/config.json",
26
24
  "plugins": [
27
25
  {
28
- "package": "opencode-commit-guard"
29
- }
30
- ]
26
+ "package": "opencode-commit-guard",
27
+ },
28
+ ],
31
29
  }
32
30
  ```
33
31
 
34
- You can also specify custom configuration options:
32
+ Set options on the plugin entry:
35
33
 
36
- ```json
34
+ ```jsonc
37
35
  {
38
36
  "plugins": [
39
37
  {
40
38
  "package": "opencode-commit-guard",
41
39
  "options": {
42
40
  "requireScope": true,
43
- "allowedScopes": ["kernel", "releasetools", "build", "ui"],
44
- "maxLineLength": 72
45
- }
46
- }
47
- ]
41
+ "allowedScopes": ["kernel", "build", "ui"],
42
+ "maxLineLength": 72,
43
+ },
44
+ },
45
+ ],
48
46
  }
49
47
  ```
50
48
 
51
- ## Configuration options
52
-
53
- | Option | Type | Default | Description |
54
- | --------------- | ---------- | ----------- | -------------------------------------------------------------------------------- |
55
- | `requireScope` | `boolean` | `true` | Requires the first line to match `<scope>: <subject>`. |
56
- | `allowedScopes` | `string[]` | `undefined` | Restricts allowed scope identifiers to a specified list. |
57
- | `maxLineLength` | `number` | `72` | Limits every line in the subject and body to this length. Set to `0` to disable. |
58
-
59
- ## Capture commit context
60
-
61
- Call `commit_context` before your first commit in each session and worktree.
62
- If the Git repository is in a subdirectory or differs from the project root, specify `workdir` (e.g., `commit_context({ workdir: "my-repo" })`).
63
- If `workdir` is omitted and the project root is not a Git repository, the plugin automatically selects the repository if exactly one exists, or lists available repositories if multiple are present.
64
- Run the returned command immediately, unchanged, through the foreground `shell` tool with the indicated workdir and `background:false`.
65
- Do not wrap it or chain another command onto it.
66
- Commit after the shell result reports `Frozen commit baseline` and follow its commit rules.
67
- If the result lacks that report, call `commit_context` again with the same workdir for status and next steps.
68
- A second call is optional after inline success.
69
- Repeat an explicit `workdir` when you check that checkout.
70
- An argument-free call selects the session directory when it is inside a Git repository, even after an explicit selection.
71
- If the shell result lacks a verified successful process exit, capture again instead of using a partial baseline.
72
- The command writes full historical messages to a private file and prints a fixed receipt.
73
- On Linux and macOS, capture uses Bash, portable `base64`, and a 15-second process-group watchdog.
74
- On Windows, capture uses Windows PowerShell through an encoded command that you can run from PowerShell, `pwsh`, `cmd.exe`, or Git Bash.
75
- Both capture paths limit the artifact to 256 KiB and preserve NUL-delimited Git history.
76
- The plugin appends the capture outcome and commit rules to the shell result.
77
- `RECEIPT_OK` confirms only that the artifact was written, not that the baseline was published.
78
- The next context call reports whether a capture is unclaimed, awaiting permission or execution, expired, or failed.
79
- Run an unclaimed command within 20 seconds; a claimed capture does not expire during permission approval.
80
- Expired unclaimed captures release their private files on later context or tool calls.
81
- The plugin does not put complete historical messages into tool results or model context.
82
- Set `refresh: true` after a branch switch, a signing setting change, or a change to commit instructions.
83
- A failed refresh does not restore the previous baseline.
84
- Calls from the checkout root and its subdirectories share one baseline and refresh state.
85
- Run each capture from its exact indicated workdir.
86
- An external Git configuration change or checkout replacement at the same path is not detected until you refresh.
87
- Remote workspaces are unsupported.
88
- Historical scopes are observations, not allowed scopes or policy.
89
- The guard enforces configured scope syntax, allowed scopes, line length, inline message input, and conditional signoff.
90
- It does not enforce every writing convention in `AGENTS.md` or verify a cryptographic signature.
91
-
92
- ## Formatting rules
93
-
94
- ### 1. Scope prefix (`requireScope`)
95
-
96
- The first line of the commit message must follow the `<scope>: <subject>` pattern.
97
- Both standard lowercase scopes and conventional commit formats are valid:
98
-
99
- - `kernel: add support for new thermal sensor`
100
- - `releasetools: fix ota package generation`
101
- - `feat(parser): add subshell tokenization`
102
- - `fix(ui): resolve button alignment issue`
103
-
104
- The plugin rejects subject lines that omit the colon, leave the scope empty, or omit the space after the colon:
49
+ | Option | Default | Allowed values |
50
+ | --------------- | ------- | ---------------------------------------------------------------------------------- |
51
+ | `requireScope` | `true` | Boolean. Requires a `<scope>: <subject>` first line. |
52
+ | `allowedScopes` | none | Array of non-empty scope names. An empty array allows any scope. |
53
+ | `maxLineLength` | `72` | Integer of 0 or more. Limits each subject and body line. Set `0` to remove limits. |
105
54
 
106
- - Invalid: `Add support for new thermal sensor`
107
- - Invalid: `: add support for new thermal sensor`
108
- - Invalid: `kernel:add support for new thermal sensor`
55
+ The plugin rejects unknown options, including `requireSignoff`.
109
56
 
110
- ### 2. Allowed scopes (`allowedScopes`)
57
+ ## Quick start
111
58
 
112
- When `allowedScopes` contains values, the extracted scope must match an entry in the list.
113
- Set `allowedScopes: []` to disable the scope allowlist.
114
- The plugin normalizes the empty array to `undefined`.
115
- The plugin rejects unknown option keys and lists the valid options: `requireScope`, `allowedScopes`, and `maxLineLength`.
116
- For conventional commits such as `feat(parser): ...`, the plugin accepts either the inner scope (`parser`), the full scope token (`feat(parser)`), or the type prefix (`feat`).
117
- Each configured entry must match the scope syntax; spaces and characters such as `@` are invalid.
59
+ 1. Call `commit_context` before your first commit in a session and checkout.
60
+ Set `workdir` if the repository is not the session directory, for example `commit_context({ workdir: "my-repo" })`.
61
+ 2. Run the returned command immediately and unchanged through the `shell` tool, in the foreground, with that workdir.
62
+ Do not run it in the background, wrap it, or chain another command onto it.
63
+ 3. Commit only after the shell result reports `Frozen commit baseline`.
64
+ That report also lists the commit rules for the checkout.
65
+ If the report is missing, call `commit_context` again with the same workdir for status and next steps.
118
66
 
119
- ### 3. Maximum line length (`maxLineLength`)
67
+ `RECEIPT_OK` in the shell output confirms only that the capture file was written.
68
+ It does not authorize a commit.
120
69
 
121
- No line in the commit subject or body may exceed the configured character limit (default 72 characters).
122
- When a line exceeds this limit, the error identifies the exact line number, current character length, and offending text.
123
- Each `-m` supplies a paragraph, not automatic line wrapping.
124
- Wrap with real newlines inside `$'...'`; `"\n"` inside double quotes remains literal.
70
+ Call `commit_context` with `refresh: true` after you switch branches, change signing settings, or change commit instructions.
125
71
 
126
- ### 4. Signoff
72
+ In `full_codemode`, call both tools from one `execute` script:
127
73
 
128
- When the captured effective `commit.gpgsign` is `true`, every commit with a supplied message must include a signoff indicator.
129
- When it is `false` or unset, signoff is not required.
130
- A missing signing snapshot blocks the commit until you capture context.
131
- An invalid signing setting requires a configuration repair, not repeated capture.
132
- Inspect it with `git config --show-origin --get-all commit.gpgsign` (or `user.signingkey`).
133
- Fix the value without changing the intended signing policy, then call `commit_context({ refresh: true })`.
134
- You can provide this either via flags or directly in the message body:
135
-
136
- - Pass `-s` or `--signoff` in the git command.
137
- - Or include a trailer matching `Signed-off-by: Full Name <email@example.com>` in the message body.
138
-
139
- Signoff identifies the author of a contribution.
140
- It does not cryptographically sign the commit.
141
- Git signing settings and your signing key remain separate from signoff.
74
+ ```js
75
+ const text = await tools.commit_context({ workdir: "my-repo" });
76
+ if (!text.includes("Run this shell command")) return text;
77
+ const command = text.split("\n").slice(1).join("\n");
78
+ const result = await tools.shell({ command, workdir: "my-repo" });
79
+ return result.output;
80
+ ```
142
81
 
143
- ### 5. Amend commits (`--amend`)
82
+ If `commit_context` returns status or baseline guidance without a command, the script returns that text.
83
+ Otherwise, the returned `result.output` text includes the `Frozen commit baseline` report.
144
84
 
145
- Use `git commit --amend --no-edit` to keep the existing message unchanged.
146
- The plugin does not read or revalidate that message, so a message created outside this guard may not meet its format rules.
147
- Provide `-m` when you change the message; the plugin validates the supplied text in the captured checkout.
148
- Use a direct Git command in that checkout.
149
- The guard rejects `git -C`, Git directory and worktree flags, Git environment overrides, and directory-changing wrappers because they can select another target.
150
- The guard also rejects earlier shell environment mutations such as `export`, `typeset`, `declare`, `source`, `.`, `eval`, `set`, and assignment-only commands before a commit.
85
+ ## Formatting rules
151
86
 
152
- ### Message input
87
+ - **Scope**: The first line uses `<scope>: <subject>`, for example `kernel: fix race` or `feat(parser): add subshells`.
88
+ - **Allowed scopes**: If `allowedScopes` has entries, the scope must match one of them.
89
+ - **Line length**: No subject or body line exceeds `maxLineLength`.
90
+ - **Signoff**: If the captured `commit.gpgsign` is `true`, add `-s` or a `Signed-off-by:` trailer.
91
+ Signoff is not a cryptographic signature.
92
+ - **Literal messages**: Supply messages with `-m`, `--message`, or one quoted heredoc on standard input.
93
+ The plugin rejects message files, shell expansion in messages, and `--trailer`.
94
+ - **Direct target**: Run `git commit` directly in the captured checkout.
95
+ The plugin rejects `git -C`, Git directory flags, Git environment overrides, and directory-changing wrappers.
153
96
 
154
- Provide commit messages inline with `-m` or `--message`, or use one quoted heredoc directly on standard input:
97
+ Use real newlines inside `$'...'` for a message body:
155
98
 
156
99
  ```bash
157
- git commit -s -F - <<'EOF'
158
- kernel: fix race
159
- EOF
100
+ git commit -s -m $'kernel: Fix race in thermal driver\n\nHold the lock while the sensor list changes.'
160
101
  ```
161
102
 
162
- The plugin rejects file-backed `-F` or `--file` messages without reading the files.
163
- It also rejects unquoted or ambiguous standard-input sources.
164
- Supply the final message literally; message words containing shell expansion are rejected without evaluation.
165
- Single quotes and ANSI-C quotes (`$'...'`) supply literal text.
166
- The parser inspects commits inside command substitutions, backticks, and literal `bash`, `sh`, or `zsh` `-c` bodies.
167
- Double-quoted parameters support nested defaults and quotes, such as `"${VAR:-"default"}"`, but remain expansions rather than literal message text.
168
- Run command substitutions and backticks outside these parameters; the parser rejects executable substitutions inside them.
169
- Command substitutions support command-position `case` branches, optional leading pattern parentheses, and `;;`, `;&`, and `;;&` terminators.
170
- The guard also validates commits inside those branches.
171
- Run function and `coproc` declarations outside command substitutions; their compound bodies are rejected there.
172
- Use `bash -c` or `zsh -c` instead of `sh -c` for bodies containing `$'` quoting; the guard rejects this nonportable syntax under `sh`.
173
- Unquoted heredoc delimiters match after backslash-newline continuations are removed; quote the delimiter to preserve literal body text.
174
- Use a literal shell body if expansion can change its executable words.
175
- Both `bash -c "$SCRIPT"` and `bash -c "FOO=$BAR pytest"` fail closed because expansion can introduce executable commands.
176
- Parser failures identify pre-execution shell inspection with a `[commit-guard]` prefix.
177
- Simplify unsupported syntax or quote literal text; run Git directly when committing.
178
- Put trailers in the literal message body or use `-s`; `--trailer` is rejected.
179
- The guard resolves the signing baseline before reporting message-format violations.
180
- `git commit --help` and `git commit -h` do not require a baseline.
181
-
182
- ### Code Mode boundary
183
-
184
- The `commit_context` tool remains available through Code Mode.
185
- The OC-1 proposal to exclude it with `codemode: false` is deferred and is not implemented.
186
- Require the same verified foreground shell result and `Frozen commit baseline` report regardless of how you call the tool.
103
+ `git commit --help` and `git commit -h` do not need a baseline.
187
104
 
188
105
  ## Development
189
106
 
190
- Use Bun for all repository operations.
107
+ Use Bun 1.3 or newer; the test suite runs tests concurrently.
191
108
 
192
- ```bash
109
+ ```sh
193
110
  bun install
194
- bun test
195
- bun run typecheck
196
- bun run lint
197
- bun run build
111
+ bun test # unit tests and real OpenCode host tests
112
+ bun run typecheck # TypeScript type checking
113
+ bun run check # lint and format check
114
+ bun run build # build dist/
198
115
  ```
116
+
117
+ Other scripts: `bun run lint` and `bun run format`.
package/dist/index.js CHANGED
@@ -1662,7 +1662,7 @@ ${examples}Effective commit.gpgsign: ${baseline.gpgsign}. ${signoff}
1662
1662
  ` + `A second commit_context call is optional.
1663
1663
  Set refresh:true after a branch switch, changed signing settings, or changed commit instructions.`;
1664
1664
  };
1665
- var captureInstructions = (attempt, status) => `${status}Run this shell command immediately, unchanged, in the foreground with workdir ${attempt.workdir} and background:false. ` + `Do not wrap it or chain another command onto it. ${publicationGuidance} ${receiptGuidance}
1665
+ var captureInstructions = (attempt, status) => `${status}Run this shell command immediately, unchanged, in the foreground with workdir ${attempt.workdir} (do not run it in the background). ` + `Do not wrap it or chain another command onto it. ${publicationGuidance} ${receiptGuidance}
1666
1666
  ${attempt.command}`;
1667
1667
  var sweep = (state) => Effect2.gen(function* sweepPending() {
1668
1668
  for (const attempt of [...state.pending.values()].slice(0, 32)) {
@@ -1803,7 +1803,7 @@ var verifyBaselineAndValidate = (state, event, input, command, invocations) => E
1803
1803
  if (baseline === undefined || root === undefined || baseline.directory !== root) {
1804
1804
  const expected = root ?? workdir;
1805
1805
  const hint = JSON.stringify(relative2(sessionDirectory, expected) || ".");
1806
- return yield* Effect2.fail(new Error(`[commit-guard] No published baseline for ${expected}. Call commit_context({ workdir: ${hint} }), 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. ${publicationGuidance} RECEIPT_OK alone is insufficient.`));
1806
+ return yield* Effect2.fail(new Error(`[commit-guard] No published baseline for ${expected}. Call commit_context({ workdir: ${hint} }), then run the returned command immediately, unchanged, in the foreground with that workdir (do not run it in the background). Do not wrap it or chain another command onto it. ${publicationGuidance} RECEIPT_OK alone is insufficient.`));
1807
1807
  }
1808
1808
  if (baseline.gpgsign === "error" || baseline.signingkey === "error") {
1809
1809
  return yield* Effect2.fail(new Error(signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")));
@@ -1837,6 +1837,9 @@ var handleBeforeExecute = (state, event) => Effect2.gen(function* before() {
1837
1837
  var isVerifiedShellMetadata = (metadata) => isRecord(metadata) && metadata.status === "completed" && metadata.exit === 0 && metadata.truncated === false && (metadata.timeout === undefined || metadata.timeout === false) && Object.keys(metadata).every((key) => ["status", "exit", "truncated", "timeout"].includes(key));
1838
1838
  var publishCapturedAttempt = (state, event, attempt) => Effect2.gen(function* publishAttempt() {
1839
1839
  const { ctx } = state;
1840
+ if (!isRecord(event.input) || event.input.command !== attempt.command) {
1841
+ return "claimed capture command was modified before execution";
1842
+ }
1840
1843
  if (event.status !== "completed") {
1841
1844
  return "shell result did not complete successfully";
1842
1845
  }
@@ -1886,32 +1889,34 @@ var rememberFailure = (state, scope, reason) => {
1886
1889
  }
1887
1890
  }
1888
1891
  };
1889
- var handleAfterExecute = (state, event) => Effect2.gen(function* after() {
1890
- if (event.tool !== "shell") {
1891
- return;
1892
+ var finalizeAttempt = (state, attempt, outcome) => Effect2.gen(function* finalize() {
1893
+ if (state.pending.get(attempt.scope) === attempt) {
1894
+ state.pending.delete(attempt.scope);
1895
+ }
1896
+ if (isJSONString(outcome)) {
1897
+ rememberFailure(state, attempt.scope, outcome);
1898
+ yield* recordState(state.ctx, attempt, "failed", outcome).pipe(Effect2.catchCause(() => Effect2.void));
1899
+ yield* invalidateOwned(state.ctx, attempt);
1892
1900
  }
1901
+ }).pipe(Effect2.ensuring(Effect2.sync(() => {
1902
+ cleanup(attempt);
1903
+ })), Effect2.catchCause(() => Effect2.void));
1904
+ var handleAfterExecute = (state, event) => Effect2.gen(function* after() {
1893
1905
  const attempt = [...state.pending.values()].find((item) => item.claimed?.id === event.id && item.claimed?.messageID === event.messageID && item.sessionID === event.sessionID && item.agent === event.agent);
1894
1906
  if (attempt === undefined) {
1895
1907
  return;
1896
1908
  }
1909
+ if (event.tool !== "shell") {
1910
+ yield* finalizeAttempt(state, attempt, "claimed capture tool was renamed away from shell");
1911
+ return;
1912
+ }
1897
1913
  let outcome = "capture import or storage failed";
1898
1914
  yield* Effect2.gen(function* publishing() {
1899
1915
  outcome = yield* publishCapturedAttempt(state, event, attempt);
1900
1916
  if (!isJSONString(outcome)) {
1901
1917
  yield* recordState(state.ctx, attempt, "published");
1902
1918
  }
1903
- }).pipe(Effect2.onExit(() => Effect2.gen(function* finalize() {
1904
- if (state.pending.get(attempt.scope) === attempt) {
1905
- state.pending.delete(attempt.scope);
1906
- }
1907
- if (isJSONString(outcome)) {
1908
- rememberFailure(state, attempt.scope, outcome);
1909
- yield* recordState(state.ctx, attempt, "failed", outcome).pipe(Effect2.catchCause(() => Effect2.void));
1910
- yield* invalidateOwned(state.ctx, attempt);
1911
- }
1912
- }).pipe(Effect2.ensuring(Effect2.sync(() => {
1913
- cleanup(attempt);
1914
- })), Effect2.catchCause(() => Effect2.void))), Effect2.catchCause(() => Effect2.void));
1919
+ }).pipe(Effect2.onExit(() => finalizeAttempt(state, attempt, outcome)), Effect2.catchCause(() => Effect2.void));
1915
1920
  const note = isJSONString(outcome) ? `[commit-guard] This capture did not publish a usable baseline: ${outcome.slice(0, 256)}.
1916
1921
  RECEIPT_OK alone does not authorize a commit.
1917
1922
  Call commit_context with the same workdir for status and next steps.` : baselineGuidance(outcome, state.config);
@@ -1954,7 +1959,7 @@ var plugin = Plugin.define({
1954
1959
  description: String.raw`Prepare a Git baseline. Run the returned command unchanged in the foreground; require "Frozen commit baseline".
1955
1960
  Call before your first commit in each session and checkout.
1956
1961
  Set workdir when targeting another repository.
1957
- Run the returned command immediately, unchanged, with the indicated workdir and background:false.
1962
+ Run the returned command immediately, unchanged, in the foreground with the indicated workdir (do not run it in the background).
1958
1963
  Do not wrap it or chain another command onto it.
1959
1964
  ${publicationGuidance} ${receiptGuidance}
1960
1965
  The shell result includes commit rules; a second call is optional.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-commit-guard",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "OpenCode V2 plugin enforcing git commit format rules",
5
5
  "homepage": "https://github.com/gotenksIN/opencode-commit-guard",
6
6
  "license": "MIT",
@@ -30,17 +30,18 @@
30
30
  "prepack": "bun run build"
31
31
  },
32
32
  "devDependencies": {
33
+ "@opencode/core": "latest",
33
34
  "@opencode/plugin": "latest",
34
35
  "@types/bun": "1.4.4",
35
36
  "effect": "4.1.0",
36
- "oxfmt": "^0.78.0",
37
- "oxlint": "^1.93.0",
38
- "oxlint-tsgolint": "^7.0.2007",
37
+ "oxfmt": "latest",
38
+ "oxlint": "latest",
39
+ "oxlint-tsgolint": "latest",
39
40
  "typescript": "7.0.2",
40
- "ultracite": "^8.2.0"
41
+ "ultracite": "latest"
41
42
  },
42
43
  "peerDependencies": {
43
- "@opencode/plugin": "^2.3.0",
44
+ "@opencode/plugin": "^2.4.1",
44
45
  "effect": "^4.0.0"
45
46
  },
46
47
  "engines": {