opencode-commit-guard 1.1.1 → 1.2.0

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 +78 -148
  2. package/dist/index.js +1053 -227
  3. package/package.json +11 -9
package/README.md CHANGED
@@ -1,198 +1,128 @@
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, across POSIX shells and PowerShell 7 (`pwsh`).
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
+ On Windows, context capture and command inspection target PowerShell 7 (`pwsh`).
14
15
 
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.
16
+ The plugin does not change Git hooks or repository configuration.
19
17
 
20
18
  ## Installation
21
19
 
22
- Add the plugin to your `opencode.json` configuration file:
20
+ Add the package to your `opencode.json` or `opencode.jsonc` file:
23
21
 
24
- ```json
22
+ ```jsonc
25
23
  {
24
+ "$schema": "https://opencode.ai/config.json",
26
25
  "plugins": [
27
26
  {
28
- "package": "opencode-commit-guard"
29
- }
30
- ]
27
+ "package": "opencode-commit-guard",
28
+ },
29
+ ],
31
30
  }
32
31
  ```
33
32
 
34
- You can also specify custom configuration options:
33
+ Set options on the plugin entry:
35
34
 
36
- ```json
35
+ ```jsonc
37
36
  {
38
37
  "plugins": [
39
38
  {
40
39
  "package": "opencode-commit-guard",
41
40
  "options": {
42
41
  "requireScope": true,
43
- "allowedScopes": ["kernel", "releasetools", "build", "ui"],
44
- "maxLineLength": 72
45
- }
46
- }
47
- ]
42
+ "allowedScopes": ["kernel", "build", "ui"],
43
+ "maxLineLength": 72,
44
+ },
45
+ },
46
+ ],
48
47
  }
49
48
  ```
50
49
 
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`)
50
+ | Option | Default | Allowed values |
51
+ | --------------- | ------- | ---------------------------------------------------------------------------------- |
52
+ | `requireScope` | `true` | Boolean. Requires a `<scope>: <subject>` first line. |
53
+ | `allowedScopes` | none | Array of non-empty scope names. An empty array allows any scope. |
54
+ | `maxLineLength` | `72` | Integer of 0 or more. Limits each subject and body line. Set `0` to remove limits. |
95
55
 
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:
56
+ The plugin rejects unknown options, including `requireSignoff`.
98
57
 
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`
58
+ ## Quick start
103
59
 
104
- The plugin rejects subject lines that omit the colon, leave the scope empty, or omit the space after the colon:
60
+ 1. Call `commit_context` before your first commit in a session and checkout.
61
+ Set `workdir` if the repository is not the session directory, for example `commit_context({ workdir: "my-repo" })`.
62
+ 2. Run the returned command immediately and unchanged through the `shell` tool, in the foreground, with that workdir.
63
+ Do not run it in the background, wrap it, or chain another command onto it.
64
+ 3. Commit only after the shell result reports `Frozen commit baseline`.
65
+ That report also lists the commit rules for the checkout.
66
+ If the report is missing, call `commit_context` again with the same workdir for status and next steps.
105
67
 
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`
68
+ `RECEIPT_OK` in the shell output confirms only that the capture file was written.
69
+ It does not authorize a commit.
109
70
 
110
- ### 2. Allowed scopes (`allowedScopes`)
71
+ Call `commit_context` with `refresh: true` after you switch branches, change signing settings, or change commit instructions.
111
72
 
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.
73
+ In `full_codemode`, call both tools from one `execute` script:
118
74
 
119
- ### 3. Maximum line length (`maxLineLength`)
120
-
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.
125
-
126
- ### 4. Signoff
75
+ ```js
76
+ const text = await tools.commit_context({ workdir: "my-repo" });
77
+ if (!text.includes("Run this shell command")) return text;
78
+ const command = text.split("\n").slice(1).join("\n");
79
+ const result = await tools.shell({ command, workdir: "my-repo" });
80
+ return result.output;
81
+ ```
127
82
 
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:
83
+ If `commit_context` returns status or baseline guidance without a command, the script returns that text.
84
+ Otherwise, the returned `result.output` text includes the `Frozen commit baseline` report.
135
85
 
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.
86
+ ## Formatting rules
138
87
 
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.
88
+ - **Scope**: The first line uses `<scope>: <subject>`, for example `kernel: fix race` or `feat(parser): add subshells`.
89
+ - **Allowed scopes**: If `allowedScopes` has entries, the scope must match one of them.
90
+ - **Line length**: No subject or body line exceeds `maxLineLength`.
91
+ - **Signoff**: If the captured `commit.gpgsign` is `true`, add `-s` or a `Signed-off-by:` trailer.
92
+ Signoff is not a cryptographic signature.
93
+ - **Literal messages**: Supply messages with `-m`, `--message`, one quoted heredoc on POSIX standard input, or a single literal here-string pipeline in PowerShell 7.
94
+ The plugin rejects message files, shell expansion in messages, and `--trailer`.
95
+ - **Direct target**: Run `git commit` directly in the captured checkout.
96
+ The plugin rejects `git -C`, Git directory flags, Git environment overrides, and directory-changing wrappers.
142
97
 
143
- ### 5. Amend commits (`--amend`)
98
+ In POSIX shells, use real newlines inside `$'...'` for a message body:
144
99
 
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.
100
+ ```bash
101
+ git commit -s -m $'kernel: Fix race in thermal driver\n\nHold the lock while the sensor list changes.'
102
+ ```
151
103
 
152
- ### Message input
104
+ In PowerShell 7 (`pwsh`), use single quotes or pipe a literal here-string to `git commit -F -`:
153
105
 
154
- Provide commit messages inline with `-m` or `--message`, or use one quoted heredoc directly on standard input:
106
+ ```powershell
107
+ @'
108
+ kernel: Fix race in thermal driver
155
109
 
156
- ```bash
157
- git commit -s -F - <<'EOF'
158
- kernel: fix race
159
- EOF
110
+ Hold the lock while the sensor list changes.
111
+ '@ | git commit -s -F -
160
112
  ```
161
113
 
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.
114
+ `git commit --help` and `git commit -h` do not need a baseline.
187
115
 
188
116
  ## Development
189
117
 
190
- Use Bun for all repository operations.
118
+ Use Bun 1.4 or newer; the test suite runs tests concurrently.
191
119
 
192
- ```bash
120
+ ```sh
193
121
  bun install
194
- bun test
195
- bun run typecheck
196
- bun run lint
197
- bun run build
122
+ bun run check # lint, format check, typecheck, and tests
123
+ bun test # unit tests and real OpenCode host tests
124
+ bun run typecheck # TypeScript type checking
125
+ bun run build # build dist/
198
126
  ```
127
+
128
+ Other scripts: `bun run lint` and `bun run format`.