opencode-commit-guard 1.0.4 → 1.0.6

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
@@ -2,12 +2,28 @@ import { Plugin } from "@opencode/plugin/effect"
2
2
  import { Tool } from "@opencode/schema/tool"
3
3
  import { Effect } from "effect"
4
4
  import { randomUUID } from "node:crypto"
5
- import { captureTimeout, cleanup, createPending, importCapture, invalidate, publish, scopeFor, counter, load } from "./capture.js"
6
- import type { Pending } from "./capture.js"
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"
7
23
  import { parseConfig } from "./config.js"
8
24
  import { extractGitCommits } from "./shell.js"
9
25
  import { isJSONString, isRecord } from "./types.js"
10
- import type { JsonValue } from "./types.js"
26
+ import type { CommitGuardConfig, JsonValue } from "./types.js"
11
27
  import { validateGitCommits } from "./validator.js"
12
28
 
13
29
  export const plugin = Plugin.define({
@@ -21,11 +37,33 @@ export const plugin = Plugin.define({
21
37
  const generation = randomUUID()
22
38
  const pending = new Map<string, Pending>()
23
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
+ })
24
61
 
25
62
  yield* Effect.addFinalizer(() => Effect.gen(function*() {
26
63
  for (const attempt of pending.values()) {
27
64
  cleanup(attempt)
28
- yield* invalidate(ctx, attempt.scope)
65
+ yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication")
66
+ yield* invalidateOwned(ctx, attempt)
29
67
  }
30
68
 
31
69
  pending.clear()
@@ -33,125 +71,179 @@ export const plugin = Plugin.define({
33
71
 
34
72
  yield* ctx.tool.transform((editor) => editor.add({
35
73
  name: "commit_context",
36
- description: "Prepare a private, permission-checked Git baseline. Run the returned shell command in the foreground, then call this tool again. Set refresh to replace a frozen baseline.",
37
- input: { type: "object", properties: { refresh: { type: "boolean" } }, additionalProperties: false },
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
+ },
38
97
  execute: (input, toolContext) => Effect.gen(function*() {
98
+ yield* sweep()
99
+
39
100
  if (ctx.location.workspaceID !== undefined) return { content: "Commit context capture is unavailable for remote workspaces." }
40
101
 
41
102
  const session = yield* ctx.session.get({ sessionID: toolContext.sessionID })
42
103
 
43
- if (session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID) {
44
- return { content: "The session moved to another worktree. Call commit_context from its new location." }
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." }
45
127
  }
46
128
 
47
- const scope = scopeFor(ctx, toolContext.sessionID, config)
129
+ const targetWorkdir = target.workdir
48
130
 
49
- if (preparing.has(scope)) return { content: "A commit context capture is preparing for this session. Call commit_context again." }
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." }
50
136
 
51
137
  preparing.add(scope)
52
138
 
53
139
  return yield* Effect.gen(function*() {
54
- // SAFETY: The tool input schema permits only a refresh boolean.
55
- const request = input as { refresh?: boolean }
56
- const previous = pending.get(scope)
57
-
58
- if (previous !== undefined) {
59
- if (Date.now() < previous.expires && request.refresh !== true) return { content: `Run this shell command with workdir ${ctx.location.directory} and background:false, then call commit_context again:\n${previous.command}` }
60
- pending.delete(scope)
61
- cleanup(previous)
62
- yield* invalidate(ctx, scope)
63
- }
140
+ const previous = pending.get(scope)
64
141
 
65
- if (request.refresh !== true) {
66
- const baseline = yield* load(ctx, scope)
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
+ }
67
146
 
68
- if (baseline !== undefined && baseline.workdir === ctx.location.directory && baseline.gpgsign !== "error" && baseline.signingkey !== "error") {
69
- 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)
70
- const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.\n` : ""
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
+ }
71
156
 
72
- const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." :
73
- `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`
157
+ if (request.refresh !== true) {
158
+ const baseline = yield* load(ctx, scope)
74
159
 
75
- return { content: `Frozen commit baseline for ${ctx.location.directory}.\n` +
76
- `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.\n` +
77
- `${scopes}\n${examples}` +
78
- `Effective commit.gpgsign: ${baseline.gpgsign}. Signoff ${baseline.gpgsign === "true" ? "required" : "not required"}; ` +
79
- `signoff is not a cryptographic signature. user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}.\n` +
80
- "Set refresh:true after a branch switch, changed signing settings, or changed commit instructions." }
160
+ if (baseline !== undefined && baseline.directory === findGitRoot(targetWorkdir)) {
161
+ return { content: baselineGuidance(baseline, config) }
162
+ }
81
163
  }
82
- }
83
164
 
84
- if (request.refresh === true) yield* invalidate(ctx, scope)
85
- const count = yield* counter(ctx, scope)
86
- const attempt = yield* Effect.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, ctx.location.directory))
87
- pending.set(scope, attempt)
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")
88
173
 
89
- return { content: `Run this shell command with workdir ${ctx.location.directory} and background:false, then call commit_context again:\n${attempt.command}` }
174
+ return { content: captureInstructions(attempt, status) }
90
175
  }).pipe(Effect.ensuring(Effect.sync(() => { preparing.delete(scope) })))
91
176
  }).pipe(Effect.mapError(() => new Tool.Error({
92
177
  message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout.",
93
178
  }))),
94
179
  }))
95
180
 
96
- yield* ctx.shell.hook("create.before", (event) => Effect.sync(() => {
97
- for (const attempt of pending.values()) {
98
- if (attempt.claimed !== undefined && event.command === attempt.command && event.cwd === attempt.workdir) {
99
- attempt.expires = Date.now() + captureTimeout
100
- }
101
- }
102
- }))
103
-
104
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
+
105
189
  const parsed = yield* Effect.try({
106
190
  try: () => {
107
- if (event.tool !== "shell" && event.tool !== "bash") {
108
- return
109
- }
191
+ if (event.tool !== "shell" && event.tool !== "bash") {
192
+ return
193
+ }
110
194
 
111
- // SAFETY: event.input is an unvalidated tool input payload from OpenCode runtime.
112
- const rawInput = event.input as JsonValue | undefined
195
+ // SAFETY: event.input is an unvalidated tool input payload from OpenCode runtime.
196
+ const rawInput = event.input as JsonValue | undefined
113
197
 
114
- if (!isRecord(rawInput)) {
115
- return
116
- }
198
+ if (!isRecord(rawInput)) {
199
+ return
200
+ }
117
201
 
118
- const command = rawInput["command"]
202
+ const command = rawInput["command"]
119
203
 
120
- if (!isJSONString(command)) {
121
- return
122
- }
204
+ if (!isJSONString(command)) {
205
+ return
206
+ }
123
207
 
124
- for (const attempt of pending.values()) {
125
- if (command !== attempt.command) continue
208
+ const rawWorkdir = rawInput["workdir"]
126
209
 
127
- if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent ||
128
- (rawInput["workdir"] !== ctx.location.directory ||
129
- rawInput["background"] === true) || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
130
- throw new Error("[commit-guard] Capture must use its exact foreground shell command in the original session and workdir. Call commit_context to refresh.")
131
- }
210
+ for (const attempt of pending.values()) {
211
+ if (command !== attempt.command) continue
132
212
 
133
- attempt.claimed = { messageID: event.messageID, id: event.id }
134
- attempt.expires = Date.now() + captureTimeout
213
+ const matchesWorkdir = rawWorkdir === attempt.workdir ||
214
+ (isJSONString(rawWorkdir) && resolve(captureSessionDirectory, rawWorkdir) === attempt.workdir) ||
215
+ (rawWorkdir === undefined && captureSessionDirectory === attempt.workdir)
135
216
 
136
- return
137
- }
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
+ }
138
222
 
139
- const invocations = extractGitCommits(command)
223
+ attempt.claimed = { messageID: event.messageID, id: event.id }
140
224
 
141
- if (invocations.length === 0) {
142
- return
143
- }
225
+ return
226
+ }
227
+
228
+ const invocations = extractGitCommits(command)
144
229
 
145
- validateGitCommits(invocations, { ...config, enforceSignoff: false }, command)
230
+ if (invocations.length === 0) {
231
+ return
232
+ }
146
233
 
147
- return { invocations, command, rawInput }
234
+ return { invocations, command, rawInput }
148
235
  },
149
236
  catch: (error) => new Tool.Error({
150
237
  message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
151
238
  }),
152
239
  })
153
240
 
154
- if (parsed === undefined) return
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
155
247
 
156
248
  if (ctx.location.workspaceID !== undefined) return yield* Effect.fail(new Tool.Error({
157
249
  message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout.",
@@ -159,24 +251,51 @@ export const plugin = Plugin.define({
159
251
 
160
252
  const session = yield* ctx.session.get({ sessionID: event.sessionID })
161
253
 
162
- if (session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID ||
163
- parsed.rawInput["workdir"] !== undefined && parsed.rawInput["workdir"] !== ctx.location.directory ||
254
+ if (session.location.workspaceID !== ctx.location.workspaceID ||
164
255
  parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
165
- return yield* Effect.fail(new Tool.Error({ 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." }))
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
+ }))
166
259
  }
167
260
 
168
- const baseline = yield* load(ctx, scopeFor(ctx, event.sessionID, config))
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)
169
271
 
170
- if (baseline === undefined || baseline.workdir !== ctx.location.directory || baseline.gpgsign === "error" || baseline.signingkey === "error") {
171
- return yield* Effect.fail(new Tool.Error({ message: "[commit-guard] No valid signing baseline for this checkout. Call commit_context, run its authorized foreground shell command, then call commit_context again before committing." }))
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
+ }))
172
285
  }
173
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
+
174
291
  yield* Effect.try({
175
292
  try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
176
- catch: (error) => new Tool.Error({ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed." }),
293
+ catch: (error) => new Tool.Error({
294
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
295
+ }),
177
296
  })
178
297
  }).pipe(Effect.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
179
- message: "[commit-guard] Could not verify the commit target or signing baseline. Call commit_context from this checkout.",
298
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
180
299
  }))))
181
300
 
182
301
  yield* ctx.tool.hook("execute.after", (event) => Effect.gen(function*() {
@@ -188,13 +307,21 @@ export const plugin = Plugin.define({
188
307
  if (attempt === undefined) return
189
308
 
190
309
  let published = false
310
+ let captured: Baseline | undefined
311
+ let reason = "capture import or storage failed"
191
312
 
192
313
  yield* Effect.gen(function*() {
193
- if (event.status !== "completed" || Date.now() >= attempt.expires ||
194
- (yield* counter(ctx, attempt.scope)) !== attempt.counter) return
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
195
320
  // SAFETY: Tool result metadata is untrusted JSON; verify every required field before import.
196
321
  const metadata = event.result.metadata as JsonValue | undefined
197
322
 
323
+ reason = "shell result lacks verified foreground completion metadata"
324
+
198
325
  if (!isRecord(metadata)) return
199
326
 
200
327
  // OpenCode's shell tool reports completed/exit:0 after a foreground process exits.
@@ -205,21 +332,87 @@ export const plugin = Plugin.define({
205
332
 
206
333
  const session = yield* Effect.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => undefined)
207
334
 
208
- if (session === undefined || session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID) return
335
+ reason = "capture session or workspace no longer matches"
209
336
 
337
+ if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID) return
338
+
339
+ reason = "private artifact is invalid or incomplete (END required)"
210
340
  const baseline = yield* Effect.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") })
211
341
 
212
- if (baseline.workdir !== ctx.location.directory || ctx.location.workspaceID !== undefined) return
342
+ if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined) return
343
+ reason = "capture storage failed or its counter changed"
213
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
+ }
214
351
  }).pipe(Effect.onExit(() => Effect.gen(function*() {
215
352
  if (pending.get(attempt.scope) === attempt) pending.delete(attempt.scope)
216
353
 
217
- if (!published) yield* invalidate(ctx, attempt.scope)
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."
218
365
 
219
- yield* Effect.sync(() => cleanup(attempt))
220
- })), Effect.catchCause(() => Effect.void))
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)
221
369
  }))
222
370
  }),
223
371
  })
224
372
 
225
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 ADDED
@@ -0,0 +1 @@
1
+ export const scopePattern = /^([a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(.+)$/