opencode-commit-guard 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,7 +2,17 @@
2
2
  // src/plugin.ts
3
3
  import { Plugin } from "@opencode/plugin/effect";
4
4
  import { Tool } from "@opencode/schema/tool";
5
- import { Effect } from "effect";
5
+ import { Effect as Effect2 } from "effect";
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";
9
+
10
+ // src/capture.ts
11
+ import { createHash, randomUUID } from "crypto";
12
+ import { closeSync, constants, existsSync, fstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync, statSync } from "fs";
13
+ import { tmpdir } from "os";
14
+ import { dirname, join, relative, resolve } from "path";
15
+ import { Effect, Semaphore } from "effect";
6
16
 
7
17
  // src/types.ts
8
18
  function isJSONString(value) {
@@ -21,9 +31,280 @@ var defaultConfig = {
21
31
  requireScope: true,
22
32
  allowedScopes: undefined,
23
33
  maxLineLength: 72,
24
- requireSignoff: true
34
+ enforceSignoff: true
25
35
  };
26
36
 
37
+ // src/capture.ts
38
+ var version = 1;
39
+ var maxBytes = 262144;
40
+ var captureTimeout = 20000;
41
+ var policy = "commit-guard-context-v1";
42
+ var storageLock = Semaphore.makeUnsafe(1);
43
+ function digest(text) {
44
+ return createHash("sha256").update(text).digest("hex");
45
+ }
46
+ function scopeFor(ctx, sessionID, config, targetDir) {
47
+ const location = ctx.location;
48
+ return digest(JSON.stringify([
49
+ version,
50
+ location.project.id,
51
+ sessionID,
52
+ targetDir ?? location.directory,
53
+ location.workspaceID ?? null,
54
+ policy,
55
+ config.requireScope,
56
+ config.allowedScopes ?? null,
57
+ config.maxLineLength
58
+ ]));
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
+ }
149
+ function counterKey(scope) {
150
+ return `counter/${scope}`;
151
+ }
152
+ function prefix(scope) {
153
+ return `snap/${scope}/`;
154
+ }
155
+ function counter(ctx, scope) {
156
+ return Effect.gen(function* () {
157
+ const value = yield* ctx.storage.get(counterKey(scope));
158
+ if (value === undefined)
159
+ return 0;
160
+ return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : -1;
161
+ });
162
+ }
163
+ function invalidate(ctx, scope) {
164
+ return storageLock.withPermits(1)(Effect.gen(function* () {
165
+ const previous = yield* counter(ctx, scope);
166
+ yield* ctx.storage.set(counterKey(scope), previous < 0 ? 1 : previous + 1);
167
+ }));
168
+ }
169
+ function validBaseline(value) {
170
+ if (!isRecord(value))
171
+ return false;
172
+ return ["directory", "workdir", "gitDir", "commonDir"].every((key) => isJSONString(value[key])) && (value["branch"] === null || isJSONString(value["branch"])) && (value["head"] === null || /^[0-9a-f]{40,64}$/.test(String(value["head"]))) && Array.isArray(value["messages"]) && value["messages"].length <= 10 && value["messages"].every((message) => isJSONString(message)) && ["true", "false", "unset", "error"].includes(String(value["gpgsign"])) && (value["signingkey"] === null || value["signingkey"] === "error" || isJSONString(value["signingkey"]));
173
+ }
174
+ function load(ctx, scope) {
175
+ return storageLock.withPermits(1)(Effect.gen(function* () {
176
+ const current = yield* counter(ctx, scope);
177
+ if (current < 0)
178
+ return;
179
+ let after;
180
+ let newest;
181
+ do {
182
+ const page = yield* ctx.storage.scan({ prefix: prefix(scope), after, limit: 100 });
183
+ for (const record of page.entries) {
184
+ const raw = record.value;
185
+ if (!isRecord(raw) || raw["schema"] !== version || raw["scope"] !== scope || raw["counter"] !== current || !isJSONString(raw["generation"]) || !isJSONString(raw["sequence"]) || !isJSONString(raw["checksum"]) || !validBaseline(raw["baseline"]))
186
+ continue;
187
+ const baseline = raw["baseline"];
188
+ if (digest(JSON.stringify([version, scope, current, raw["generation"], raw["sequence"], baseline])) !== raw["checksum"])
189
+ continue;
190
+ if (newest === undefined || raw["sequence"] > newest.sequence)
191
+ newest = { sequence: raw["sequence"], baseline };
192
+ }
193
+ after = page.next;
194
+ } while (after !== undefined);
195
+ return newest?.baseline;
196
+ }));
197
+ }
198
+ function captureCommand(path) {
199
+ const quoted = `'${path.replaceAll("'", "'\\''")}'`;
200
+ return `timeout 15s bash -c 'set -euo pipefail
201
+ ulimit -f 256
202
+ out=$1
203
+ printf "CTX1\\n" > "$out"
204
+ field() { "$@" 2>/dev/null | base64 -w0 >> "$out"; printf "\\n" >> "$out"; }
205
+ field git rev-parse --show-toplevel
206
+ field git rev-parse --absolute-git-dir
207
+ field git rev-parse --path-format=absolute --git-common-dir
208
+ if git symbolic-ref -q --short HEAD >/dev/null 2>&1; then printf "branch\\n" >> "$out"; field git symbolic-ref -q --short HEAD; else status=$?; if [ "$status" -ne 1 ]; then exit "$status"; fi; printf "detached\\n\\n" >> "$out"; fi
209
+ if git rev-parse --verify HEAD >/dev/null 2>&1; then printf "head\\n" >> "$out"; field git rev-parse --verify HEAD; field git log -10 -z --format=%B%x00; else status=$?; if [ "$status" -ne 128 ] || ! git symbolic-ref -q HEAD >/dev/null 2>&1 || ! git status --porcelain >/dev/null 2>&1; then exit 1; fi; printf "unborn\\n\\n\\n" >> "$out"; fi
210
+ if git config --type=bool --get commit.gpgsign >/dev/null 2>&1; then printf "set\\n" >> "$out"; field git config --type=bool --get commit.gpgsign; else status=$?; if [ "$status" -eq 1 ]; then printf "unset\\n\\n" >> "$out"; else printf "error\\n\\n" >> "$out"; fi; fi
211
+ if git config --get user.signingkey >/dev/null 2>&1; then printf "set\\n" >> "$out"; field git config --get user.signingkey; else status=$?; if [ "$status" -eq 1 ]; then printf "unset\\n\\n" >> "$out"; else printf "error\\n\\n" >> "$out"; fi; fi
212
+ printf "END\\n" >> "$out"
213
+ printf "RECEIPT_OK\\n"' bash ${quoted} 2>/dev/null`;
214
+ }
215
+ function createPending(scope, sessionID, agent, counterValue, workdir) {
216
+ const directory = mkdtempSync(join(tmpdir(), "commit-context-"));
217
+ try {
218
+ const file = join(directory, randomUUID());
219
+ const fd = openSync(file, constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_RDWR, 384);
220
+ const stat = fstatSync(fd);
221
+ return {
222
+ scope,
223
+ sessionID,
224
+ agent,
225
+ counter: counterValue,
226
+ directory,
227
+ workdir,
228
+ fd,
229
+ identity: { dev: stat.dev, ino: stat.ino, uid: stat.uid },
230
+ expires: Date.now() + captureTimeout,
231
+ command: captureCommand(file)
232
+ };
233
+ } catch (error) {
234
+ rmSync(directory, { recursive: true, force: true });
235
+ throw error;
236
+ }
237
+ }
238
+ function cleanup(pending) {
239
+ if (pending.closed === true)
240
+ return;
241
+ pending.closed = true;
242
+ closeSync(pending.fd);
243
+ rmSync(pending.directory, { recursive: true, force: true });
244
+ }
245
+ function decode(line) {
246
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(line))
247
+ throw new Error("Invalid capture framing");
248
+ return Buffer.from(line, "base64").toString("utf8");
249
+ }
250
+ function importCapture(pending) {
251
+ const stat = fstatSync(pending.fd);
252
+ if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino || stat.uid !== pending.identity.uid || (stat.mode & 511) !== 384 || stat.size > maxBytes || stat.size === 0) {
253
+ throw new Error("Invalid private capture artifact");
254
+ }
255
+ const bytes = Buffer.alloc(stat.size);
256
+ if (readSync(pending.fd, bytes, 0, stat.size, 0) !== stat.size)
257
+ throw new Error("Incomplete private capture artifact");
258
+ const completed = fstatSync(pending.fd);
259
+ if (completed.size !== stat.size || completed.dev !== stat.dev || completed.ino !== stat.ino)
260
+ throw new Error("Capture changed during import");
261
+ const fields = bytes.toString("utf8").split(`
262
+ `);
263
+ if (fields.length !== 15 || fields[0] !== "CTX1" || fields[13] !== "END" || fields[14] !== "")
264
+ throw new Error("Incomplete capture");
265
+ const root = decode(fields[1]).trimEnd();
266
+ const gitDir = decode(fields[2]).trimEnd();
267
+ const commonDir = decode(fields[3]).trimEnd();
268
+ const branch = fields[4] === "branch" ? decode(fields[5]).trimEnd() : null;
269
+ const head = fields[6] === "head" ? decode(fields[7]).trim() : null;
270
+ const rawLog = decode(fields[8]);
271
+ const messages = head === null ? [] : rawLog.split("\x00\x00").filter((message) => message.length > 0);
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")))
273
+ throw new Error("Invalid Git baseline");
274
+ const configState = fields[9];
275
+ const value = decode(fields[10]).trim();
276
+ const gpgsign = configState === "set" && (value === "true" || value === "false") ? value : configState === "unset" ? "unset" : "error";
277
+ const signingkey = fields[11] === "set" ? decode(fields[12]).trim() : fields[11] === "unset" ? null : "error";
278
+ return { directory: root, workdir: pending.workdir, gitDir, commonDir, branch, head, messages, gpgsign, signingkey };
279
+ }
280
+ function publish(ctx, pending, generation, baseline) {
281
+ return storageLock.withPermits(1)(Effect.gen(function* () {
282
+ if ((yield* counter(ctx, pending.scope)) !== pending.counter)
283
+ return false;
284
+ const sequence = `${Date.now().toString().padStart(15, "0")}-${randomUUID()}`;
285
+ const checksum = digest(JSON.stringify([version, pending.scope, pending.counter, generation, sequence, baseline]));
286
+ yield* ctx.storage.set(prefix(pending.scope) + sequence, {
287
+ schema: version,
288
+ scope: pending.scope,
289
+ counter: pending.counter,
290
+ generation,
291
+ sequence,
292
+ checksum,
293
+ baseline: { ...baseline, messages: [...baseline.messages] }
294
+ });
295
+ let after;
296
+ do {
297
+ const page = yield* ctx.storage.scan({ prefix: prefix(pending.scope), after, limit: 100 });
298
+ for (const record of page.entries) {
299
+ if (record.key < prefix(pending.scope) + sequence)
300
+ yield* ctx.storage.remove(record.key);
301
+ }
302
+ after = page.next;
303
+ } while (after !== undefined);
304
+ return true;
305
+ }));
306
+ }
307
+
27
308
  // src/config.ts
28
309
  function parseConfig(options) {
29
310
  if (options === undefined) {
@@ -63,19 +344,14 @@ function parseConfig(options) {
63
344
  }
64
345
  maxLineLength = rawMaxLineLength;
65
346
  }
66
- const rawRequireSignoff = options["requireSignoff"];
67
- let requireSignoff = defaultConfig.requireSignoff;
68
- if (rawRequireSignoff !== undefined) {
69
- if (!isJSONBoolean(rawRequireSignoff)) {
70
- throw new Error("Invalid plugin option requireSignoff; expected a boolean.");
71
- }
72
- requireSignoff = rawRequireSignoff;
347
+ if (options["requireSignoff"] !== undefined) {
348
+ throw new Error("Plugin option requireSignoff has been removed; signoff follows the captured effective commit.gpgsign value.");
73
349
  }
74
350
  return {
75
351
  requireScope,
76
352
  allowedScopes,
77
353
  maxLineLength,
78
- requireSignoff
354
+ enforceSignoff: defaultConfig.enforceSignoff
79
355
  };
80
356
  }
81
357
 
@@ -87,7 +363,8 @@ var gitGlobalOptionsWithArg = new Set([
87
363
  "--work-tree",
88
364
  "--namespace",
89
365
  "--exec-path",
90
- "--super-prefix"
366
+ "--super-prefix",
367
+ "--config-env"
91
368
  ]);
92
369
  var commandPrefixes = new Set([
93
370
  "!",
@@ -100,6 +377,23 @@ var commandPrefixes = new Set([
100
377
  "until",
101
378
  "while"
102
379
  ]);
380
+ var targetMutators = new Set([
381
+ "cd",
382
+ "pushd",
383
+ "popd",
384
+ "chdir",
385
+ "export",
386
+ "typeset",
387
+ "declare",
388
+ "source",
389
+ ".",
390
+ "eval",
391
+ "set",
392
+ "unset",
393
+ "readonly",
394
+ "local",
395
+ "setenv"
396
+ ]);
103
397
  var commitLongOptionsWithArg = new Set([
104
398
  "--author",
105
399
  "--cleanup",
@@ -543,6 +837,7 @@ function extractInvocation(words, commandStart) {
543
837
  return;
544
838
  wordIndex++;
545
839
  let subcommand;
840
+ let targetError = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word) || word === "export") ? "Environment or wrapper changes can redirect a Git commit target. Use a direct git commit in the captured workdir." : undefined;
546
841
  while (wordIndex < words.length) {
547
842
  const argument = words[wordIndex];
548
843
  if (argument === undefined)
@@ -553,14 +848,21 @@ function extractInvocation(words, commandStart) {
553
848
  break;
554
849
  }
555
850
  if (gitGlobalOptionsWithArg.has(argument)) {
851
+ if (argument === "-C" || argument === "--git-dir" || argument === "--work-tree" || argument === "-c" || argument === "--config-env") {
852
+ targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
853
+ }
556
854
  wordIndex += 2;
557
855
  continue;
558
856
  }
559
- if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--namespace=") || argument.startsWith("--exec-path=") || argument.startsWith("--super-prefix=") || argument.startsWith("-c")) {
857
+ if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--namespace=") || argument.startsWith("--exec-path=") || argument.startsWith("--super-prefix=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
858
+ if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
859
+ targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
860
+ }
560
861
  wordIndex++;
561
862
  continue;
562
863
  }
563
864
  if (argument.startsWith("-C")) {
865
+ targetError = "git -C can change the commit target. Run git commit directly in the captured workdir.";
564
866
  wordIndex++;
565
867
  continue;
566
868
  }
@@ -664,20 +966,25 @@ function extractInvocation(words, commandStart) {
664
966
  isAmend,
665
967
  hasNoEdit,
666
968
  isFixup,
667
- isHelp
969
+ isHelp,
970
+ targetError
668
971
  };
669
972
  }
670
- function extractGitCommits(command) {
973
+ function extractGitCommits(command, inheritedDirectoryChange = false) {
671
974
  const tokens = tokenizeShell(command);
672
975
  const invocations = [];
976
+ let changedDirectory = inheritedDirectoryChange;
673
977
  for (const simple of splitSimpleCommands(tokens)) {
674
978
  const commandTokens = simple.tokens;
675
979
  const words = extractCommandWords(commandTokens);
676
980
  const commandStart = findCommandStart(words);
677
981
  const invocation = extractInvocation(words, commandStart);
982
+ if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment))
983
+ changedDirectory = true;
678
984
  if (invocation !== undefined) {
985
+ const target = changedDirectory ? { ...invocation, targetError: "A preceding directory or environment change makes the commit target ambiguous. Run git commit in a separate shell call with the captured workdir." } : invocation;
679
986
  if (!invocation.filePaths.includes("-")) {
680
- invocations.push(invocation);
987
+ invocations.push(target);
681
988
  continue;
682
989
  }
683
990
  const heredocs = commandTokens.filter((token) => token.type === "redirect" && /^\d*<<$/.test(token.value));
@@ -697,7 +1004,7 @@ function extractGitCommits(command) {
697
1004
  stdinError = "Use a complete quoted heredoc delimiter, for example: git commit -s -F - <<'EOF'.";
698
1005
  }
699
1006
  invocations.push({
700
- ...invocation,
1007
+ ...target,
701
1008
  stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined,
702
1009
  stdinError
703
1010
  });
@@ -705,7 +1012,7 @@ function extractGitCommits(command) {
705
1012
  }
706
1013
  for (const token of tokens) {
707
1014
  for (const substitution of token.substitutions ?? []) {
708
- invocations.push(...extractGitCommits(substitution));
1015
+ invocations.push(...extractGitCommits(substitution, changedDirectory));
709
1016
  }
710
1017
  }
711
1018
  return invocations;
@@ -756,10 +1063,6 @@ function validateGitCommits(invocations, config, originalCommand) {
756
1063
  continue;
757
1064
  }
758
1065
  const collectedMessages = [...invocation.messages];
759
- if (invocation.isAmend && invocation.hasNoEdit === true && invocation.messages.length === 0) {
760
- allViolations.push('Cannot validate --amend --no-edit before shell permissions run because it would read the existing commit. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".');
761
- continue;
762
- }
763
1066
  const filePath = invocation.filePaths.at(-1);
764
1067
  if (filePath !== undefined) {
765
1068
  if (filePath !== "-" || invocation.filePaths.length !== 1) {
@@ -773,6 +1076,9 @@ function validateGitCommits(invocations, config, originalCommand) {
773
1076
  collectedMessages.push(invocation.stdinMessage);
774
1077
  }
775
1078
  if (collectedMessages.length === 0) {
1079
+ if (invocation.isAmend && invocation.hasNoEdit === true) {
1080
+ continue;
1081
+ }
776
1082
  if (invocation.isFixup === true) {
777
1083
  continue;
778
1084
  }
@@ -826,7 +1132,7 @@ function validateGitCommits(invocations, config, originalCommand) {
826
1132
  ${details}`);
827
1133
  }
828
1134
  }
829
- if (config.requireSignoff) {
1135
+ if (config.enforceSignoff) {
830
1136
  const hasSignoff = invocation.hasSignoffFlag || hasSignoffTrailer(lines);
831
1137
  if (!hasSignoff) {
832
1138
  allViolations.push("Missing commit signoff. Commit must either include the '-s' or '--signoff' flag, or contain a valid 'Signed-off-by: Name <email>' trailer in the message body.");
@@ -841,32 +1147,216 @@ ${details}`);
841
1147
  // src/plugin.ts
842
1148
  var plugin = Plugin.define({
843
1149
  id: "opencode-commit-guard",
844
- effect: (ctx) => Effect.gen(function* () {
845
- const config = yield* Effect.sync(() => {
1150
+ effect: (ctx) => Effect2.gen(function* () {
1151
+ const config = yield* Effect2.sync(() => {
846
1152
  return parseConfig(ctx.options);
847
1153
  });
848
- yield* ctx.tool.hook("execute.before", (event) => Effect.try({
849
- try: () => {
850
- if (event.tool !== "shell" && event.tool !== "bash") {
851
- return;
1154
+ const generation = randomUUID2();
1155
+ const pending = new Map;
1156
+ const preparing = new Set;
1157
+ const lastSessionWorkdir = new Map;
1158
+ yield* Effect2.addFinalizer(() => Effect2.gen(function* () {
1159
+ for (const attempt of pending.values()) {
1160
+ cleanup(attempt);
1161
+ yield* invalidate(ctx, attempt.scope);
1162
+ }
1163
+ pending.clear();
1164
+ }));
1165
+ yield* ctx.tool.transform((editor) => editor.add({
1166
+ name: "commit_context",
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
+ },
1177
+ execute: (input, toolContext) => Effect2.gen(function* () {
1178
+ if (ctx.location.workspaceID !== undefined)
1179
+ return { content: "Commit context capture is unavailable for remote workspaces." };
1180
+ const session = yield* ctx.session.get({ sessionID: toolContext.sessionID });
1181
+ if (session.location.workspaceID !== ctx.location.workspaceID) {
1182
+ return { content: "Commit context capture is unavailable for remote workspaces." };
852
1183
  }
853
- const rawInput = event.input;
854
- if (!isRecord(rawInput)) {
855
- return;
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
+ }
856
1193
  }
857
- const command = rawInput["command"];
858
- if (!isJSONString(command)) {
859
- return;
1194
+ if (target.error !== undefined || target.workdir === undefined) {
1195
+ return { content: target.error ?? "Could not determine target Git repository." };
860
1196
  }
861
- const invocations = extractGitCommits(command);
862
- if (invocations.length === 0) {
863
- return;
1197
+ const targetWorkdir = target.workdir;
1198
+ lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir);
1199
+ const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir);
1200
+ if (preparing.has(scope))
1201
+ return { content: "A commit context capture is preparing for this session and checkout. Call commit_context again." };
1202
+ preparing.add(scope);
1203
+ return yield* Effect2.gen(function* () {
1204
+ const previous = pending.get(scope);
1205
+ if (previous !== undefined) {
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:
1208
+ ${previous.command}` };
1209
+ }
1210
+ pending.delete(scope);
1211
+ cleanup(previous);
1212
+ yield* invalidate(ctx, scope);
1213
+ }
1214
+ if (request.refresh !== true) {
1215
+ const baseline = yield* load(ctx, scope);
1216
+ if (baseline !== undefined && (baseline.workdir === targetWorkdir || baseline.directory === targetWorkdir) && baseline.gpgsign !== "error" && baseline.signingkey !== "error") {
1217
+ const observed = [...new Set(baseline.messages.map((message) => message.split(`
1218
+ `)[0]?.match(/^([a-zA-Z0-9_./-]{1,40}): /)?.[1]).filter((value) => value !== undefined))].slice(0, 3);
1219
+ const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
1220
+ ` : "";
1221
+ const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." : `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`;
1222
+ return { content: `Frozen commit baseline for ${targetWorkdir}.
1223
+ ` + `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.
1224
+ ` + `${scopes}
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"}.
1226
+ ` + "Set refresh:true after a branch switch, changed signing settings, or changed commit instructions." };
1227
+ }
1228
+ }
1229
+ if (request.refresh === true)
1230
+ yield* invalidate(ctx, scope);
1231
+ const count = yield* counter(ctx, scope);
1232
+ const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, targetWorkdir));
1233
+ pending.set(scope, attempt);
1234
+ return { content: `Run this shell command with workdir ${targetWorkdir} and background:false, then call commit_context again:
1235
+ ${attempt.command}` };
1236
+ }).pipe(Effect2.ensuring(Effect2.sync(() => {
1237
+ preparing.delete(scope);
1238
+ })));
1239
+ }).pipe(Effect2.mapError(() => new Tool.Error({
1240
+ message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout."
1241
+ })))
1242
+ }));
1243
+ yield* ctx.shell.hook("create.before", (event) => Effect2.sync(() => {
1244
+ for (const attempt of pending.values()) {
1245
+ if (attempt.claimed !== undefined && event.command === attempt.command && event.cwd === attempt.workdir) {
1246
+ attempt.expires = Date.now() + captureTimeout;
864
1247
  }
865
- validateGitCommits(invocations, config, command);
866
- },
867
- catch: (error) => new Tool.Error({
868
- message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
869
- })
1248
+ }
1249
+ }));
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;
1253
+ const parsed = yield* Effect2.try({
1254
+ try: () => {
1255
+ if (event.tool !== "shell" && event.tool !== "bash") {
1256
+ return;
1257
+ }
1258
+ const rawInput = event.input;
1259
+ if (!isRecord(rawInput)) {
1260
+ return;
1261
+ }
1262
+ const command = rawInput["command"];
1263
+ if (!isJSONString(command)) {
1264
+ return;
1265
+ }
1266
+ const rawWorkdir = rawInput["workdir"];
1267
+ for (const attempt of pending.values()) {
1268
+ if (command !== attempt.command)
1269
+ continue;
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) {
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.");
1273
+ }
1274
+ attempt.claimed = { messageID: event.messageID, id: event.id };
1275
+ attempt.expires = Date.now() + captureTimeout;
1276
+ return;
1277
+ }
1278
+ const invocations = extractGitCommits(command);
1279
+ if (invocations.length === 0) {
1280
+ return;
1281
+ }
1282
+ validateGitCommits(invocations, { ...config, enforceSignoff: false }, command);
1283
+ return { invocations, command, rawInput };
1284
+ },
1285
+ catch: (error) => new Tool.Error({
1286
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
1287
+ })
1288
+ });
1289
+ if (parsed === undefined)
1290
+ return;
1291
+ if (ctx.location.workspaceID !== undefined)
1292
+ return yield* Effect2.fail(new Tool.Error({
1293
+ message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."
1294
+ }));
1295
+ const session = yield* ctx.session.get({ sessionID: event.sessionID });
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
+ }));
1300
+ }
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
+ }));
1319
+ }
1320
+ yield* Effect2.try({
1321
+ try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
1322
+ catch: (error) => new Tool.Error({
1323
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
1324
+ })
1325
+ });
1326
+ }).pipe(Effect2.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
1327
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
1328
+ }))));
1329
+ yield* ctx.tool.hook("execute.after", (event) => Effect2.gen(function* () {
1330
+ if (event.tool !== "shell")
1331
+ return;
1332
+ const attempt = [...pending.values()].find((item) => item.claimed?.id === event.id && item.claimed?.messageID === event.messageID && item.sessionID === event.sessionID && item.agent === event.agent);
1333
+ if (attempt === undefined)
1334
+ return;
1335
+ let published = false;
1336
+ yield* Effect2.gen(function* () {
1337
+ if (event.status !== "completed" || Date.now() >= attempt.expires || (yield* counter(ctx, attempt.scope)) !== attempt.counter)
1338
+ return;
1339
+ const metadata = event.result.metadata;
1340
+ if (!isRecord(metadata))
1341
+ return;
1342
+ if (metadata["status"] !== "completed" || metadata["exit"] !== 0 || metadata["truncated"] !== false || metadata["timeout"] !== undefined && metadata["timeout"] !== false || metadata["shellID"] !== undefined || Object.keys(metadata).some((key) => !["status", "exit", "truncated", "timeout"].includes(key)))
1343
+ return;
1344
+ const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {
1345
+ return;
1346
+ });
1347
+ if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID)
1348
+ return;
1349
+ const baseline = yield* Effect2.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") });
1350
+ if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined)
1351
+ return;
1352
+ published = yield* publish(ctx, attempt, generation, baseline);
1353
+ }).pipe(Effect2.onExit(() => Effect2.gen(function* () {
1354
+ if (pending.get(attempt.scope) === attempt)
1355
+ pending.delete(attempt.scope);
1356
+ if (!published)
1357
+ yield* invalidate(ctx, attempt.scope);
1358
+ yield* Effect2.sync(() => cleanup(attempt));
1359
+ })), Effect2.catchCause(() => Effect2.void));
870
1360
  }));
871
1361
  })
872
1362
  });