opencode-commit-guard 1.0.4 → 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/README.md CHANGED
@@ -59,8 +59,12 @@ You can also specify custom configuration options:
59
59
  ## Capture commit context
60
60
 
61
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.
62
64
  Run the returned command through the foreground `shell` tool with the indicated workdir.
63
65
  Call `commit_context` again to read concise guidance.
66
+ Repeat the same `workdir` on each call when you select a repository explicitly.
67
+ An argument-free call selects the session directory when it is inside a Git repository, even after an explicit selection.
64
68
  If the shell result lacks a verified successful process exit, capture again instead of using a partial baseline.
65
69
  The command writes full historical messages to a private file and prints only a fixed receipt.
66
70
  The plugin does not put complete historical messages into tool results or model context.
package/dist/index.js CHANGED
@@ -4,12 +4,14 @@ import { Plugin } from "@opencode/plugin/effect";
4
4
  import { Tool } from "@opencode/schema/tool";
5
5
  import { Effect as Effect2 } from "effect";
6
6
  import { randomUUID as randomUUID2 } from "crypto";
7
+ import { existsSync as existsSync2, realpathSync as realpathSync2 } from "fs";
8
+ import { relative as relative2, resolve as resolve2 } from "path";
7
9
 
8
10
  // src/capture.ts
9
11
  import { createHash, randomUUID } from "crypto";
10
- import { closeSync, constants, fstatSync, mkdtempSync, openSync, readSync, rmSync } from "fs";
12
+ import { closeSync, constants, existsSync, fstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync, statSync } from "fs";
11
13
  import { tmpdir } from "os";
12
- import { join, relative } from "path";
14
+ import { dirname, join, relative, resolve } from "path";
13
15
  import { Effect, Semaphore } from "effect";
14
16
 
15
17
  // src/types.ts
@@ -41,13 +43,13 @@ var storageLock = Semaphore.makeUnsafe(1);
41
43
  function digest(text) {
42
44
  return createHash("sha256").update(text).digest("hex");
43
45
  }
44
- function scopeFor(ctx, sessionID, config) {
46
+ function scopeFor(ctx, sessionID, config, targetDir) {
45
47
  const location = ctx.location;
46
48
  return digest(JSON.stringify([
47
49
  version,
48
50
  location.project.id,
49
51
  sessionID,
50
- location.directory,
52
+ targetDir ?? location.directory,
51
53
  location.workspaceID ?? null,
52
54
  policy,
53
55
  config.requireScope,
@@ -55,6 +57,95 @@ function scopeFor(ctx, sessionID, config) {
55
57
  config.maxLineLength
56
58
  ]));
57
59
  }
60
+ function isGitDirectory(dir) {
61
+ try {
62
+ return existsSync(join(dir, ".git"));
63
+ } catch {
64
+ return false;
65
+ }
66
+ }
67
+ function findGitRoot(startDir) {
68
+ let current;
69
+ try {
70
+ current = realpathSync(startDir);
71
+ } catch {
72
+ return;
73
+ }
74
+ while (true) {
75
+ if (isGitDirectory(current)) {
76
+ return current;
77
+ }
78
+ const parent = dirname(current);
79
+ if (parent === current) {
80
+ break;
81
+ }
82
+ current = parent;
83
+ }
84
+ return;
85
+ }
86
+ function findSubRepos(dir, maxDepth = 2) {
87
+ const repos = [];
88
+ function search(currentDir, currentDepth) {
89
+ if (currentDepth > maxDepth)
90
+ return;
91
+ try {
92
+ const entries = readdirSync(currentDir, { withFileTypes: true });
93
+ for (const entry of entries) {
94
+ if (!entry.isDirectory() && !entry.isSymbolicLink())
95
+ continue;
96
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist")
97
+ continue;
98
+ const fullPath = join(currentDir, entry.name);
99
+ if (isGitDirectory(fullPath)) {
100
+ repos.push(fullPath);
101
+ } else if (currentDepth < maxDepth) {
102
+ search(fullPath, currentDepth + 1);
103
+ }
104
+ }
105
+ } catch {}
106
+ }
107
+ search(dir, 1);
108
+ return repos;
109
+ }
110
+ function resolveTargetWorkdir(baseDir, requestedDir) {
111
+ if (requestedDir !== undefined) {
112
+ const resolvedDir = resolve(baseDir, requestedDir);
113
+ if (!existsSync(resolvedDir)) {
114
+ return { error: `Directory "${requestedDir}" does not exist.` };
115
+ }
116
+ try {
117
+ if (!statSync(resolvedDir).isDirectory()) {
118
+ return { error: `Path "${requestedDir}" is not a directory.` };
119
+ }
120
+ } catch {
121
+ return { error: `Could not access directory "${requestedDir}".` };
122
+ }
123
+ const gitRoot = findGitRoot(resolvedDir);
124
+ if (gitRoot === undefined) {
125
+ return { error: `Directory "${requestedDir}" is not a Git repository or inside one.` };
126
+ }
127
+ return { workdir: realpathSync(resolvedDir) };
128
+ }
129
+ const currentGitRoot = findGitRoot(baseDir);
130
+ if (currentGitRoot !== undefined) {
131
+ return { workdir: realpathSync(baseDir) };
132
+ }
133
+ const subRepos = findSubRepos(baseDir);
134
+ if (subRepos.length === 1) {
135
+ return { workdir: realpathSync(subRepos[0]) };
136
+ }
137
+ if (subRepos.length === 0) {
138
+ return {
139
+ error: `No Git repository found in ${baseDir}. Specify the repository directory with the 'workdir' option, for example: commit_context({ workdir: "path/to/repo" }).`
140
+ };
141
+ }
142
+ const repoList = subRepos.map((repo) => relative(baseDir, repo)).join(", ");
143
+ return {
144
+ error: `The directory ${baseDir} is not a Git repository. Multiple Git repositories were found: ${repoList}.
145
+ Specify which repository to target with the 'workdir' option, for example:
146
+ commit_context({ workdir: "${relative(baseDir, subRepos[0])}" })`
147
+ };
148
+ }
58
149
  function counterKey(scope) {
59
150
  return `counter/${scope}`;
60
151
  }
@@ -178,7 +269,7 @@ function importCapture(pending) {
178
269
  const head = fields[6] === "head" ? decode(fields[7]).trim() : null;
179
270
  const rawLog = decode(fields[8]);
180
271
  const messages = head === null ? [] : rawLog.split("\x00\x00").filter((message) => message.length > 0);
181
- if (!root.startsWith("/") || !gitDir.startsWith("/") || !commonDir.startsWith("/") || relative(root, pending.workdir).startsWith("..") || !["branch", "detached"].includes(fields[4]) || !["head", "unborn"].includes(fields[6]) || head !== null && !/^[a-f0-9]{40,64}$/.test(head) || head === null && rawLog !== "" || head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\x00\x00")))
272
+ if (!root.startsWith("/") || !gitDir.startsWith("/") || !commonDir.startsWith("/") || root !== findGitRoot(pending.workdir) || !["branch", "detached"].includes(fields[4]) || !["head", "unborn"].includes(fields[6]) || head !== null && !/^[a-f0-9]{40,64}$/.test(head) || head === null && rawLog !== "" || head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\x00\x00")))
182
273
  throw new Error("Invalid Git baseline");
183
274
  const configState = fields[9];
184
275
  const value = decode(fields[10]).trim();
@@ -1063,6 +1154,7 @@ var plugin = Plugin.define({
1063
1154
  const generation = randomUUID2();
1064
1155
  const pending = new Map;
1065
1156
  const preparing = new Set;
1157
+ const lastSessionWorkdir = new Map;
1066
1158
  yield* Effect2.addFinalizer(() => Effect2.gen(function* () {
1067
1159
  for (const attempt of pending.values()) {
1068
1160
  cleanup(attempt);
@@ -1072,39 +1164,62 @@ var plugin = Plugin.define({
1072
1164
  }));
1073
1165
  yield* ctx.tool.transform((editor) => editor.add({
1074
1166
  name: "commit_context",
1075
- 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.",
1076
- input: { type: "object", properties: { refresh: { type: "boolean" } }, additionalProperties: false },
1167
+ 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.",
1168
+ input: {
1169
+ type: "object",
1170
+ properties: {
1171
+ refresh: { type: "boolean" },
1172
+ workdir: { type: "string", description: "Working directory of the Git repository relative to the session directory or absolute." },
1173
+ directory: { type: "string", description: "Path to the Git repository checkout (alias for workdir)." }
1174
+ },
1175
+ additionalProperties: false
1176
+ },
1077
1177
  execute: (input, toolContext) => Effect2.gen(function* () {
1078
1178
  if (ctx.location.workspaceID !== undefined)
1079
1179
  return { content: "Commit context capture is unavailable for remote workspaces." };
1080
1180
  const session = yield* ctx.session.get({ sessionID: toolContext.sessionID });
1081
- if (session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID) {
1082
- return { content: "The session moved to another worktree. Call commit_context from its new location." };
1181
+ if (session.location.workspaceID !== ctx.location.workspaceID) {
1182
+ return { content: "Commit context capture is unavailable for remote workspaces." };
1083
1183
  }
1084
- const scope = scopeFor(ctx, toolContext.sessionID, config);
1184
+ const request = input;
1185
+ const requestedDir = isJSONString(request.workdir) ? request.workdir : isJSONString(request.directory) ? request.directory : undefined;
1186
+ const sessionDirectory = session.location.directory ?? ctx.location.directory;
1187
+ let target = resolveTargetWorkdir(sessionDirectory, requestedDir);
1188
+ if (target.workdir === undefined && requestedDir === undefined) {
1189
+ const remembered = lastSessionWorkdir.get(toolContext.sessionID);
1190
+ if (remembered !== undefined && existsSync2(remembered) && findGitRoot(remembered) !== undefined) {
1191
+ target = { workdir: remembered };
1192
+ }
1193
+ }
1194
+ if (target.error !== undefined || target.workdir === undefined) {
1195
+ return { content: target.error ?? "Could not determine target Git repository." };
1196
+ }
1197
+ const targetWorkdir = target.workdir;
1198
+ lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir);
1199
+ const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir);
1085
1200
  if (preparing.has(scope))
1086
- return { content: "A commit context capture is preparing for this session. Call commit_context again." };
1201
+ return { content: "A commit context capture is preparing for this session and checkout. Call commit_context again." };
1087
1202
  preparing.add(scope);
1088
1203
  return yield* Effect2.gen(function* () {
1089
- const request = input;
1090
1204
  const previous = pending.get(scope);
1091
1205
  if (previous !== undefined) {
1092
- if (Date.now() < previous.expires && request.refresh !== true)
1093
- return { content: `Run this shell command with workdir ${ctx.location.directory} and background:false, then call commit_context again:
1206
+ if (Date.now() < previous.expires && request.refresh !== true) {
1207
+ return { content: `Run this shell command with workdir ${previous.workdir} and background:false, then call commit_context again:
1094
1208
  ${previous.command}` };
1209
+ }
1095
1210
  pending.delete(scope);
1096
1211
  cleanup(previous);
1097
1212
  yield* invalidate(ctx, scope);
1098
1213
  }
1099
1214
  if (request.refresh !== true) {
1100
1215
  const baseline = yield* load(ctx, scope);
1101
- if (baseline !== undefined && baseline.workdir === ctx.location.directory && baseline.gpgsign !== "error" && baseline.signingkey !== "error") {
1216
+ if (baseline !== undefined && (baseline.workdir === targetWorkdir || baseline.directory === targetWorkdir) && baseline.gpgsign !== "error" && baseline.signingkey !== "error") {
1102
1217
  const observed = [...new Set(baseline.messages.map((message) => message.split(`
1103
1218
  `)[0]?.match(/^([a-zA-Z0-9_./-]{1,40}): /)?.[1]).filter((value) => value !== undefined))].slice(0, 3);
1104
1219
  const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
1105
1220
  ` : "";
1106
1221
  const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." : `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`;
1107
- return { content: `Frozen commit baseline for ${ctx.location.directory}.
1222
+ return { content: `Frozen commit baseline for ${targetWorkdir}.
1108
1223
  ` + `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.
1109
1224
  ` + `${scopes}
1110
1225
  ${examples}` + `Effective commit.gpgsign: ${baseline.gpgsign}. Signoff ${baseline.gpgsign === "true" ? "required" : "not required"}; ` + `signoff is not a cryptographic signature. user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}.
@@ -1114,9 +1229,9 @@ ${examples}` + `Effective commit.gpgsign: ${baseline.gpgsign}. Signoff ${baselin
1114
1229
  if (request.refresh === true)
1115
1230
  yield* invalidate(ctx, scope);
1116
1231
  const count = yield* counter(ctx, scope);
1117
- const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, ctx.location.directory));
1232
+ const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, targetWorkdir));
1118
1233
  pending.set(scope, attempt);
1119
- return { content: `Run this shell command with workdir ${ctx.location.directory} and background:false, then call commit_context again:
1234
+ return { content: `Run this shell command with workdir ${targetWorkdir} and background:false, then call commit_context again:
1120
1235
  ${attempt.command}` };
1121
1236
  }).pipe(Effect2.ensuring(Effect2.sync(() => {
1122
1237
  preparing.delete(scope);
@@ -1133,6 +1248,8 @@ ${attempt.command}` };
1133
1248
  }
1134
1249
  }));
1135
1250
  yield* ctx.tool.hook("execute.before", (event) => Effect2.gen(function* () {
1251
+ const captureSession = event.tool === "shell" || event.tool === "bash" ? yield* ctx.session.get({ sessionID: event.sessionID }) : undefined;
1252
+ const captureSessionDirectory = captureSession?.location.directory ?? ctx.location.directory;
1136
1253
  const parsed = yield* Effect2.try({
1137
1254
  try: () => {
1138
1255
  if (event.tool !== "shell" && event.tool !== "bash") {
@@ -1146,10 +1263,12 @@ ${attempt.command}` };
1146
1263
  if (!isJSONString(command)) {
1147
1264
  return;
1148
1265
  }
1266
+ const rawWorkdir = rawInput["workdir"];
1149
1267
  for (const attempt of pending.values()) {
1150
1268
  if (command !== attempt.command)
1151
1269
  continue;
1152
- if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || (rawInput["workdir"] !== ctx.location.directory || rawInput["background"] === true) || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
1270
+ const matchesWorkdir = rawWorkdir === attempt.workdir || isJSONString(rawWorkdir) && resolve2(captureSessionDirectory, rawWorkdir) === attempt.workdir || rawWorkdir === undefined && captureSessionDirectory === attempt.workdir;
1271
+ if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || !matchesWorkdir || rawInput["background"] === true || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
1153
1272
  throw new Error("[commit-guard] Capture must use its exact foreground shell command in the original session and workdir. Call commit_context to refresh.");
1154
1273
  }
1155
1274
  attempt.claimed = { messageID: event.messageID, id: event.id };
@@ -1174,19 +1293,38 @@ ${attempt.command}` };
1174
1293
  message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."
1175
1294
  }));
1176
1295
  const session = yield* ctx.session.get({ sessionID: event.sessionID });
1177
- if (session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID || parsed.rawInput["workdir"] !== undefined && parsed.rawInput["workdir"] !== ctx.location.directory || parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
1178
- return yield* Effect2.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." }));
1296
+ if (session.location.workspaceID !== ctx.location.workspaceID || parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
1297
+ return yield* Effect2.fail(new Tool.Error({
1298
+ 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."
1299
+ }));
1179
1300
  }
1180
- const baseline = yield* load(ctx, scopeFor(ctx, event.sessionID, config));
1181
- if (baseline === undefined || baseline.workdir !== ctx.location.directory || baseline.gpgsign === "error" || baseline.signingkey === "error") {
1182
- return yield* Effect2.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." }));
1301
+ const sessionDirectory = session.location.directory ?? ctx.location.directory;
1302
+ const rawWorkdir = parsed.rawInput["workdir"];
1303
+ const effectiveWorkdir = yield* Effect2.try(() => realpathSync2(isJSONString(rawWorkdir) ? resolve2(sessionDirectory, rawWorkdir) : sessionDirectory));
1304
+ const targetGitRoot = findGitRoot(effectiveWorkdir);
1305
+ let scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir);
1306
+ let baseline = yield* load(ctx, scope);
1307
+ if (baseline === undefined && targetGitRoot !== undefined && targetGitRoot !== effectiveWorkdir) {
1308
+ scope = scopeFor(ctx, event.sessionID, config, targetGitRoot);
1309
+ baseline = yield* load(ctx, scope);
1310
+ }
1311
+ const expectedDir = targetGitRoot ?? effectiveWorkdir;
1312
+ const baselineValid = baseline !== undefined && targetGitRoot !== undefined && baseline.directory === targetGitRoot && (baseline.workdir === effectiveWorkdir || baseline.directory === expectedDir) && baseline.gpgsign !== "error" && baseline.signingkey !== "error";
1313
+ if (!baselineValid || baseline === undefined) {
1314
+ const relWorkdir = relative2(sessionDirectory, expectedDir);
1315
+ const workdirHint = relWorkdir.length > 0 && !relWorkdir.startsWith("..") ? `{ workdir: "${relWorkdir}" }` : "";
1316
+ return yield* Effect2.fail(new Tool.Error({
1317
+ 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.`
1318
+ }));
1183
1319
  }
1184
1320
  yield* Effect2.try({
1185
1321
  try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
1186
- catch: (error) => new Tool.Error({ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed." })
1322
+ catch: (error) => new Tool.Error({
1323
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
1324
+ })
1187
1325
  });
1188
1326
  }).pipe(Effect2.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
1189
- message: "[commit-guard] Could not verify the commit target or signing baseline. Call commit_context from this checkout."
1327
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
1190
1328
  }))));
1191
1329
  yield* ctx.tool.hook("execute.after", (event) => Effect2.gen(function* () {
1192
1330
  if (event.tool !== "shell")
@@ -1206,10 +1344,10 @@ ${attempt.command}` };
1206
1344
  const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {
1207
1345
  return;
1208
1346
  });
1209
- if (session === undefined || session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID)
1347
+ if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID)
1210
1348
  return;
1211
1349
  const baseline = yield* Effect2.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") });
1212
- if (baseline.workdir !== ctx.location.directory || ctx.location.workspaceID !== undefined)
1350
+ if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined)
1213
1351
  return;
1214
1352
  published = yield* publish(ctx, attempt, generation, baseline);
1215
1353
  }).pipe(Effect2.onExit(() => Effect2.gen(function* () {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-commit-guard",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "OpenCode V2 plugin enforcing git commit format rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -21,14 +21,14 @@
21
21
  "prepack": "bun run build"
22
22
  },
23
23
  "dependencies": {
24
- "@opencode/plugin": "2.0.15",
25
- "@opencode/schema": "2.0.15",
24
+ "@opencode/plugin": "2.0.21",
25
+ "@opencode/schema": "2.0.21",
26
26
  "effect": "4.0.0-rc.112"
27
27
  },
28
28
  "devDependencies": {
29
- "@oxlint/plugins": "1.85.0",
29
+ "@oxlint/plugins": "1.86.0",
30
30
  "@types/bun": "1.4.2",
31
- "oxlint": "1.85.0",
31
+ "oxlint": "1.86.0",
32
32
  "typescript": "7.0.2"
33
33
  },
34
34
  "engines": {
package/src/capture.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto"
2
- import { closeSync, constants, fstatSync, mkdtempSync, openSync, readSync, rmSync } from "node:fs"
2
+ import { closeSync, constants, existsSync, fstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync, statSync } from "node:fs"
3
3
  import { tmpdir } from "node:os"
4
- import { join, relative } from "node:path"
4
+ import { dirname, join, relative, resolve } from "node:path"
5
5
  import type { Plugin } from "@opencode/plugin/effect"
6
6
  import { Effect, Semaphore } from "effect"
7
7
  import { isJSONString, isRecord } from "./types.js"
@@ -50,13 +50,137 @@ function digest(text: string): string {
50
50
  return createHash("sha256").update(text).digest("hex")
51
51
  }
52
52
 
53
- export function scopeFor(ctx: Context, sessionID: string, config: CommitGuardConfig): string {
53
+ export function scopeFor(ctx: Context, sessionID: string, config: CommitGuardConfig, targetDir?: string): string {
54
54
  const location = ctx.location
55
55
 
56
- return digest(JSON.stringify([version, location.project.id, sessionID, location.directory, location.workspaceID ?? null,
56
+ return digest(JSON.stringify([version, location.project.id, sessionID, targetDir ?? location.directory, location.workspaceID ?? null,
57
57
  policy, config.requireScope, config.allowedScopes ?? null, config.maxLineLength]))
58
58
  }
59
59
 
60
+ export function isGitDirectory(dir: string): boolean {
61
+ try {
62
+ return existsSync(join(dir, ".git"))
63
+ } catch {
64
+ return false
65
+ }
66
+ }
67
+
68
+ export function findGitRoot(startDir: string): string | undefined {
69
+ let current: string
70
+
71
+ try {
72
+ current = realpathSync(startDir)
73
+ } catch {
74
+ return undefined
75
+ }
76
+
77
+ while (true) {
78
+ if (isGitDirectory(current)) {
79
+ return current
80
+ }
81
+
82
+ const parent = dirname(current)
83
+
84
+ if (parent === current) {
85
+ break
86
+ }
87
+
88
+ current = parent
89
+ }
90
+
91
+ return undefined
92
+ }
93
+
94
+ export interface ResolvedTargetWorkdir {
95
+ readonly workdir?: string
96
+ readonly error?: string
97
+ }
98
+
99
+ export function findSubRepos(dir: string, maxDepth = 2): string[] {
100
+ const repos: string[] = []
101
+
102
+ function search(currentDir: string, currentDepth: number): void {
103
+ if (currentDepth > maxDepth) return
104
+
105
+ try {
106
+ const entries = readdirSync(currentDir, { withFileTypes: true })
107
+
108
+ for (const entry of entries) {
109
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
110
+
111
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist") continue
112
+
113
+ const fullPath = join(currentDir, entry.name)
114
+
115
+ if (isGitDirectory(fullPath)) {
116
+ repos.push(fullPath)
117
+ } else if (currentDepth < maxDepth) {
118
+ search(fullPath, currentDepth + 1)
119
+ }
120
+ }
121
+ } catch {
122
+ // Inaccessible directory
123
+ }
124
+ }
125
+
126
+ search(dir, 1)
127
+
128
+ return repos
129
+ }
130
+
131
+ export function resolveTargetWorkdir(
132
+ baseDir: string,
133
+ requestedDir?: string,
134
+ ): ResolvedTargetWorkdir {
135
+ if (requestedDir !== undefined) {
136
+ const resolvedDir = resolve(baseDir, requestedDir)
137
+
138
+ if (!existsSync(resolvedDir)) {
139
+ return { error: `Directory "${requestedDir}" does not exist.` }
140
+ }
141
+
142
+ try {
143
+ if (!statSync(resolvedDir).isDirectory()) {
144
+ return { error: `Path "${requestedDir}" is not a directory.` }
145
+ }
146
+ } catch {
147
+ return { error: `Could not access directory "${requestedDir}".` }
148
+ }
149
+
150
+ const gitRoot = findGitRoot(resolvedDir)
151
+
152
+ if (gitRoot === undefined) {
153
+ return { error: `Directory "${requestedDir}" is not a Git repository or inside one.` }
154
+ }
155
+
156
+ return { workdir: realpathSync(resolvedDir) }
157
+ }
158
+
159
+ const currentGitRoot = findGitRoot(baseDir)
160
+
161
+ if (currentGitRoot !== undefined) {
162
+ return { workdir: realpathSync(baseDir) }
163
+ }
164
+
165
+ const subRepos = findSubRepos(baseDir)
166
+
167
+ if (subRepos.length === 1) {
168
+ return { workdir: realpathSync(subRepos[0]!) }
169
+ }
170
+
171
+ if (subRepos.length === 0) {
172
+ return {
173
+ error: `No Git repository found in ${baseDir}. Specify the repository directory with the 'workdir' option, for example: commit_context({ workdir: "path/to/repo" }).`,
174
+ }
175
+ }
176
+
177
+ const repoList = subRepos.map((repo) => relative(baseDir, repo)).join(", ")
178
+
179
+ return {
180
+ error: `The directory ${baseDir} is not a Git repository. Multiple Git repositories were found: ${repoList}.\nSpecify which repository to target with the 'workdir' option, for example:\ncommit_context({ workdir: "${relative(baseDir, subRepos[0]!)}" })`,
181
+ }
182
+ }
183
+
60
184
  function counterKey(scope: string): string { return `counter/${scope}` }
61
185
 
62
186
  function prefix(scope: string): string { return `snap/${scope}/` }
@@ -202,7 +326,7 @@ export function importCapture(pending: Pending): Baseline {
202
326
  const messages = head === null ? [] : rawLog.split("\0\0").filter((message) => message.length > 0)
203
327
 
204
328
  if (!root.startsWith("/") || !gitDir.startsWith("/") || !commonDir.startsWith("/") ||
205
- relative(root, pending.workdir).startsWith("..") ||
329
+ root !== findGitRoot(pending.workdir) ||
206
330
  !["branch", "detached"].includes(fields[4]!) || !["head", "unborn"].includes(fields[6]!) ||
207
331
  (head !== null && !/^[a-f0-9]{40,64}$/.test(head)) ||
208
332
  (head === null && rawLog !== "") || (head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\0\0")))) throw new Error("Invalid Git baseline")
package/src/plugin.ts CHANGED
@@ -2,7 +2,21 @@ 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"
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"
6
20
  import type { Pending } from "./capture.js"
7
21
  import { parseConfig } from "./config.js"
8
22
  import { extractGitCommits } from "./shell.js"
@@ -21,6 +35,7 @@ export const plugin = Plugin.define({
21
35
  const generation = randomUUID()
22
36
  const pending = new Map<string, Pending>()
23
37
  const preparing = new Set<string>()
38
+ const lastSessionWorkdir = new Map<string, string>()
24
39
 
25
40
  yield* Effect.addFinalizer(() => Effect.gen(function*() {
26
41
  for (const attempt of pending.values()) {
@@ -33,60 +48,96 @@ export const plugin = Plugin.define({
33
48
 
34
49
  yield* ctx.tool.transform((editor) => editor.add({
35
50
  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 },
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
+ },
38
61
  execute: (input, toolContext) => Effect.gen(function*() {
39
62
  if (ctx.location.workspaceID !== undefined) return { content: "Commit context capture is unavailable for remote workspaces." }
40
63
 
41
64
  const session = yield* ctx.session.get({ sessionID: toolContext.sessionID })
42
65
 
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." }
66
+ if (session.location.workspaceID !== ctx.location.workspaceID) {
67
+ return { content: "Commit context capture is unavailable for remote workspaces." }
68
+ }
69
+
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)
81
+
82
+ if (remembered !== undefined && existsSync(remembered) && findGitRoot(remembered) !== undefined) {
83
+ target = { workdir: remembered }
84
+ }
85
+ }
86
+
87
+ if (target.error !== undefined || target.workdir === undefined) {
88
+ return { content: target.error ?? "Could not determine target Git repository." }
45
89
  }
46
90
 
47
- const scope = scopeFor(ctx, toolContext.sessionID, config)
91
+ const targetWorkdir = target.workdir
92
+
93
+ lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir)
94
+
95
+ const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir)
48
96
 
49
- if (preparing.has(scope)) return { content: "A commit context capture is preparing for this session. Call commit_context again." }
97
+ if (preparing.has(scope)) return { content: "A commit context capture is preparing for this session and checkout. Call commit_context again." }
50
98
 
51
99
  preparing.add(scope)
52
100
 
53
101
  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
- }
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
+ }
64
113
 
65
- if (request.refresh !== true) {
66
- const baseline = yield* load(ctx, scope)
114
+ if (request.refresh !== true) {
115
+ const baseline = yield* load(ctx, scope)
67
116
 
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` : ""
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` : ""
71
120
 
72
- const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." :
73
- `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`
121
+ const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." :
122
+ `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`
74
123
 
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." }
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
+ }
81
131
  }
82
- }
83
132
 
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)
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))
88
137
 
89
- return { content: `Run this shell command with workdir ${ctx.location.directory} and background:false, then call commit_context again:\n${attempt.command}` }
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}` }
90
141
  }).pipe(Effect.ensuring(Effect.sync(() => { preparing.delete(scope) })))
91
142
  }).pipe(Effect.mapError(() => new Tool.Error({
92
143
  message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout.",
@@ -102,49 +153,60 @@ export const plugin = Plugin.define({
102
153
  }))
103
154
 
104
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
+
105
161
  const parsed = yield* Effect.try({
106
162
  try: () => {
107
- if (event.tool !== "shell" && event.tool !== "bash") {
108
- return
109
- }
163
+ if (event.tool !== "shell" && event.tool !== "bash") {
164
+ return
165
+ }
110
166
 
111
- // SAFETY: event.input is an unvalidated tool input payload from OpenCode runtime.
112
- const rawInput = event.input as JsonValue | undefined
167
+ // SAFETY: event.input is an unvalidated tool input payload from OpenCode runtime.
168
+ const rawInput = event.input as JsonValue | undefined
113
169
 
114
- if (!isRecord(rawInput)) {
115
- return
116
- }
170
+ if (!isRecord(rawInput)) {
171
+ return
172
+ }
117
173
 
118
- const command = rawInput["command"]
174
+ const command = rawInput["command"]
119
175
 
120
- if (!isJSONString(command)) {
121
- return
122
- }
176
+ if (!isJSONString(command)) {
177
+ return
178
+ }
123
179
 
124
- for (const attempt of pending.values()) {
125
- if (command !== attempt.command) continue
180
+ const rawWorkdir = rawInput["workdir"]
126
181
 
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
- }
182
+ for (const attempt of pending.values()) {
183
+ if (command !== attempt.command) continue
132
184
 
133
- attempt.claimed = { messageID: event.messageID, id: event.id }
134
- attempt.expires = Date.now() + captureTimeout
185
+ const matchesWorkdir = rawWorkdir === attempt.workdir ||
186
+ (isJSONString(rawWorkdir) && resolve(captureSessionDirectory, rawWorkdir) === attempt.workdir) ||
187
+ (rawWorkdir === undefined && captureSessionDirectory === attempt.workdir)
135
188
 
136
- return
137
- }
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
+ }
138
194
 
139
- const invocations = extractGitCommits(command)
195
+ attempt.claimed = { messageID: event.messageID, id: event.id }
196
+ attempt.expires = Date.now() + captureTimeout
140
197
 
141
- if (invocations.length === 0) {
142
- return
143
- }
198
+ return
199
+ }
200
+
201
+ const invocations = extractGitCommits(command)
202
+
203
+ if (invocations.length === 0) {
204
+ return
205
+ }
144
206
 
145
- validateGitCommits(invocations, { ...config, enforceSignoff: false }, command)
207
+ validateGitCommits(invocations, { ...config, enforceSignoff: false }, command)
146
208
 
147
- return { invocations, command, rawInput }
209
+ return { invocations, command, rawInput }
148
210
  },
149
211
  catch: (error) => new Tool.Error({
150
212
  message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
@@ -159,24 +221,53 @@ export const plugin = Plugin.define({
159
221
 
160
222
  const session = yield* ctx.session.get({ sessionID: event.sessionID })
161
223
 
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 ||
224
+ if (session.location.workspaceID !== ctx.location.workspaceID ||
164
225
  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." }))
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
+ }))
166
229
  }
167
230
 
168
- const baseline = yield* load(ctx, scopeFor(ctx, event.sessionID, config))
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)
169
241
 
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." }))
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
+ }))
172
261
  }
173
262
 
174
263
  yield* Effect.try({
175
264
  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." }),
265
+ catch: (error) => new Tool.Error({
266
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
267
+ }),
177
268
  })
178
269
  }).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.",
270
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed.",
180
271
  }))))
181
272
 
182
273
  yield* ctx.tool.hook("execute.after", (event) => Effect.gen(function*() {
@@ -205,11 +296,11 @@ export const plugin = Plugin.define({
205
296
 
206
297
  const session = yield* Effect.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => undefined)
207
298
 
208
- if (session === undefined || session.location.directory !== ctx.location.directory || session.location.workspaceID !== ctx.location.workspaceID) return
299
+ if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID) return
209
300
 
210
301
  const baseline = yield* Effect.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") })
211
302
 
212
- if (baseline.workdir !== ctx.location.directory || ctx.location.workspaceID !== undefined) return
303
+ if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined) return
213
304
  published = yield* publish(ctx, attempt, generation, baseline)
214
305
  }).pipe(Effect.onExit(() => Effect.gen(function*() {
215
306
  if (pending.get(attempt.scope) === attempt) pending.delete(attempt.scope)