opencode-commit-guard 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +9 -38
  2. package/dist/index.js +338 -140
  3. package/package.json +4 -4
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # opencode-commit-guard
2
2
 
3
3
  This OpenCode V2 plugin checks Git commit messages before an agent runs `git commit`.
4
- It requires `@opencode/plugin` 2.4.1 or newer.
4
+ It requires `@opencode/plugin` 2.4.1 or newer and `effect` 4.1.0 or newer.
5
5
 
6
6
  ## Overview
7
7
 
@@ -55,33 +55,18 @@ Set options on the plugin entry:
55
55
 
56
56
  The plugin rejects unknown options, including `requireSignoff`.
57
57
 
58
- ## Quick start
58
+ ## Usage
59
59
 
60
- 1. Call `commit_context` before your first commit in a session and checkout.
61
- Set `workdir` if the repository is not the session directory, for example `commit_context({ workdir: "my-repo" })`.
62
- 2. Run the returned command immediately and unchanged through the `shell` tool, in the foreground, with that workdir.
63
- Do not run it in the background, wrap it, or chain another command onto it.
64
- 3. Commit only after the shell result reports `Frozen commit baseline`.
65
- That report also lists the commit rules for the checkout.
66
- If the report is missing, call `commit_context` again with the same workdir for status and next steps.
60
+ 1. Ask your agent to commit changes in your repository.
61
+ 2. Before the first commit in a session and checkout, your agent calls `commit_context` and runs the returned capture command in the foreground shell.
62
+ Approve that shell command when OpenCode prompts you.
63
+ 3. Wait for `Frozen commit baseline` in the shell output.
64
+ That report confirms the active baseline and lists the commit rules for the checkout.
67
65
 
68
- `RECEIPT_OK` in the shell output confirms only that the capture file was written.
66
+ `RECEIPT_OK` confirms only that the shell wrote the capture file.
69
67
  It does not authorize a commit.
70
68
 
71
- Call `commit_context` with `refresh: true` after you switch branches, change signing settings, or change commit instructions.
72
-
73
- In `full_codemode`, call both tools from one `execute` script:
74
-
75
- ```js
76
- const text = await tools.commit_context({ workdir: "my-repo" });
77
- if (!text.includes("Run this shell command")) return text;
78
- const command = text.split("\n").slice(1).join("\n");
79
- const result = await tools.shell({ command, workdir: "my-repo" });
80
- return result.output;
81
- ```
82
-
83
- If `commit_context` returns status or baseline guidance without a command, the script returns that text.
84
- Otherwise, the returned `result.output` text includes the `Frozen commit baseline` report.
69
+ Ask your agent to refresh the baseline (`commit_context` with `refresh: true`) after you switch branches, change signing settings, or change commit instructions.
85
70
 
86
71
  ## Formatting rules
87
72
 
@@ -112,17 +97,3 @@ Hold the lock while the sensor list changes.
112
97
  ```
113
98
 
114
99
  `git commit --help` and `git commit -h` do not need a baseline.
115
-
116
- ## Development
117
-
118
- Use Bun 1.4 or newer; the test suite runs tests concurrently.
119
-
120
- ```sh
121
- bun install
122
- bun run check # lint, format check, typecheck, and tests
123
- bun test # unit tests and real OpenCode host tests
124
- bun run typecheck # TypeScript type checking
125
- bun run build # build dist/
126
- ```
127
-
128
- Other scripts: `bun run lint` and `bun run format`.
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { randomUUID as randomUUID2 } from "crypto";
4
4
  import { existsSync as existsSync2, realpathSync as realpathSync2 } from "fs";
5
5
  import path from "path";
6
6
  import { Plugin, Tool } from "@opencode/plugin/effect";
7
- import { Cause, Clock, Effect as Effect2 } from "effect";
7
+ import { Cause, Clock, Effect as Effect2, Exit as Exit2, Schema as Schema3, Scope as Scope2 } from "effect";
8
8
 
9
9
  // src/capture.ts
10
10
  import { createHash, randomUUID } from "crypto";
@@ -23,11 +23,19 @@ import {
23
23
  } from "fs";
24
24
  import { tmpdir } from "os";
25
25
  import nodePath from "path";
26
- import { Effect, Semaphore } from "effect";
26
+ import {
27
+ Duration,
28
+ Effect,
29
+ Exit,
30
+ Result,
31
+ Schema,
32
+ Scope,
33
+ Semaphore
34
+ } from "effect";
35
+ import { Base64 } from "effect/encoding";
27
36
 
28
37
  // src/types.ts
29
38
  var isJSONString = (value) => Object.prototype.toString.call(value) === "[object String]";
30
- var isJSONNumber = (value) => Object.prototype.toString.call(value) === "[object Number]";
31
39
  var isJSONBoolean = (value) => Object.prototype.toString.call(value) === "[object Boolean]";
32
40
  var isRecord = (value) => Object.prototype.toString.call(value) === "[object Object]";
33
41
  var defaultConfig = {
@@ -41,9 +49,15 @@ var defaultConfig = {
41
49
  var { dirname, isAbsolute, join, relative, resolve } = nodePath;
42
50
  var version = 1;
43
51
  var maxBytes = 262144;
44
- var captureTimeout = 20000;
52
+ var captureTimeout = Duration.toMillis(Duration.seconds(20));
45
53
  var policy = "commit-guard-context-v1";
46
54
  var storageLock = Semaphore.makeUnsafe(1);
55
+ var taggedError = Schema.TaggedError;
56
+
57
+ class CaptureArtifactError extends taggedError()("CaptureArtifactError", {
58
+ message: Schema.String
59
+ }) {
60
+ }
47
61
  var digest = (text) => createHash("sha256").update(text).digest("hex");
48
62
  var scopeFor = (ctx, sessionID, config, targetDir) => {
49
63
  const { location } = ctx;
@@ -183,12 +197,13 @@ var invalidateOwned = (ctx, attempt) => storageLock.withPermits(1)(Effect.gen(fu
183
197
  }));
184
198
  var recordState = (ctx, attempt, state, reason = "") => storageLock.withPermits(1)(Effect.gen(function* storeState() {
185
199
  if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) {
186
- return;
200
+ return false;
187
201
  }
188
202
  yield* ctx.storage.set(`state/${attempt.scope}`, {
189
203
  state,
190
204
  reason: reason.slice(0, 256)
191
205
  });
206
+ return true;
192
207
  }));
193
208
  var captureStatus = (ctx, scope) => Effect.gen(function* readCaptureStatus() {
194
209
  const value = yield* ctx.storage.get(`state/${scope}`);
@@ -206,12 +221,19 @@ var captureStatus = (ctx, scope) => Effect.gen(function* readCaptureStatus() {
206
221
  }
207
222
  return "";
208
223
  });
209
- var validBaseline = (value) => {
210
- if (!isRecord(value)) {
211
- return false;
212
- }
213
- return ["directory", "workdir", "gitDir", "commonDir"].every((key) => isJSONString(value[key])) && (value.branch === null || isJSONString(value.branch)) && (value.head === null || isJSONString(value.head) && /^[0-9a-f]{40,64}$/u.test(value.head)) && Array.isArray(value.messages) && value.messages.length <= 10 && value.messages.every((message) => isJSONString(message)) && isJSONString(value.gpgsign) && ["true", "false", "unset", "error"].includes(value.gpgsign) && (value.signingkey === null || value.signingkey === "error" || isJSONString(value.signingkey));
214
- };
224
+ var HeadHashSchema = Schema.String.check(Schema.isPattern(/^[0-9a-f]{40,64}$/u));
225
+ var BaselineSchema = Schema.Struct({
226
+ directory: Schema.String,
227
+ workdir: Schema.String,
228
+ gitDir: Schema.String,
229
+ commonDir: Schema.String,
230
+ branch: Schema.NullOr(Schema.String),
231
+ head: Schema.NullOr(HeadHashSchema),
232
+ messages: Schema.Array(Schema.String).check(Schema.isMaxLength(10)),
233
+ gpgsign: Schema.Literals(["true", "false", "unset", "error"]),
234
+ signingkey: Schema.NullOr(Schema.String)
235
+ });
236
+ var validBaseline = Schema.is(BaselineSchema);
215
237
  var scanStoragePrefix = (ctx, keyPrefix, visitor) => Effect.gen(function* scan() {
216
238
  let after;
217
239
  do {
@@ -353,51 +375,93 @@ try {
353
375
  $lines.Add('END')
354
376
  $bytes = [Text.Encoding]::UTF8.GetBytes(($lines -join "\`n") + "\`n")
355
377
  if ($bytes.Length -gt ${maxBytes} -or $clock.ElapsedMilliseconds -ge ${watchdogMs}) { throw 'Capture exceeds limits' }
356
- $path = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(path).toString("base64")}'))
378
+ $path = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Base64.encode(path)}'))
357
379
  $file = [IO.FileStream]::new($path, [IO.FileMode]::Truncate, [IO.FileAccess]::Write, [IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)
358
380
  try { $file.Write($bytes, 0, $bytes.Length) } finally { $file.Dispose() }
359
381
  [Console]::Write("RECEIPT_OK\`n")
360
382
  } catch { exit 1 }`;
361
- return `pwsh -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
362
- };
363
- var createPending = (scope, sessionID, agent, counterValue, workdir, watchdogSeconds = 15, platform = process.platform, now = 0) => {
364
- const directory = mkdtempSync(join(tmpdir(), "commit-context-"));
365
- try {
366
- const file = join(directory, randomUUID());
367
- const fd = openSync(file, constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_RDWR, 384);
368
- const stat = fstatSync(fd);
383
+ return `pwsh -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Base64.encode(Buffer.from(script, "utf16le"))}`;
384
+ };
385
+ var acquireCaptureArtifact = Effect.fnUntraced(function* acquireArtifact() {
386
+ const directory = yield* Effect.acquireRelease(Effect.try({
387
+ try: () => mkdtempSync(join(tmpdir(), "commit-context-")),
388
+ catch: () => new CaptureArtifactError({
389
+ message: "[commit-guard] Failed to create private capture directory."
390
+ })
391
+ }), (dir) => Effect.sync(() => {
392
+ rmSync(dir, { recursive: true, force: true });
393
+ }).pipe(Effect.catchCause(() => Effect.void)));
394
+ const file = yield* Effect.acquireRelease(Effect.try({
395
+ try: () => {
396
+ const artifactPath = join(directory, randomUUID());
397
+ const fd = openSync(artifactPath, constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_RDWR, 384);
398
+ return { artifactPath, fd };
399
+ },
400
+ catch: () => new CaptureArtifactError({
401
+ message: "[commit-guard] Failed to open private capture artifact."
402
+ })
403
+ }), (resource) => Effect.sync(() => {
404
+ closeSync(resource.fd);
405
+ }).pipe(Effect.catchCause(() => Effect.void)));
406
+ return {
407
+ directory,
408
+ artifactPath: file.artifactPath,
409
+ fd: file.fd
410
+ };
411
+ });
412
+ var withCaptureArtifact = (parentScope, use) => Effect.uninterruptibleMask((restore) => Effect.gen(function* allocate() {
413
+ if (parentScope.state._tag === "Closed") {
414
+ return yield* Effect.fail(new CaptureArtifactError({
415
+ message: "[commit-guard] Plugin unloaded before capture artifact acquisition."
416
+ }));
417
+ }
418
+ const resourceScope = yield* Scope.fork(parentScope);
419
+ return yield* Effect.gen(function* build() {
420
+ const artifact = yield* acquireCaptureArtifact().pipe(Scope.provide(resourceScope));
421
+ return yield* restore(use(artifact, resourceScope));
422
+ }).pipe(Effect.onExit((exit) => Exit.isFailure(exit) ? Scope.close(resourceScope, exit).pipe(Effect.catchCause(() => Effect.void)) : Effect.void));
423
+ }));
424
+ var createPending = Effect.fnUntraced(function* createPendingAttempt(parentScope, scope, sessionID, agent, counterValue, workdir, watchdogSeconds, platform, now) {
425
+ const resolvedWatchdog = watchdogSeconds ?? 15;
426
+ const resolvedPlatform = platform ?? process.platform;
427
+ const resolvedNow = now ?? 0;
428
+ return yield* withCaptureArtifact(parentScope, (artifact, resourceScope) => Effect.gen(function* buildAttempt() {
429
+ const stat = yield* Effect.try({
430
+ try: () => fstatSync(artifact.fd),
431
+ catch: () => new CaptureArtifactError({
432
+ message: "[commit-guard] Failed to inspect private capture artifact."
433
+ })
434
+ });
435
+ const command = yield* Effect.try({
436
+ try: () => captureCommand(artifact.artifactPath, resolvedWatchdog, resolvedPlatform),
437
+ catch: () => new CaptureArtifactError({
438
+ message: "[commit-guard] Failed to construct capture command."
439
+ })
440
+ });
369
441
  const attempt = {
370
442
  scope,
371
443
  sessionID,
372
444
  agent,
373
445
  counter: counterValue,
374
- artifactPath: file,
375
- directory,
446
+ artifactPath: artifact.artifactPath,
447
+ directory: artifact.directory,
376
448
  workdir,
377
- fd,
449
+ fd: artifact.fd,
378
450
  identity: { dev: stat.dev, ino: stat.ino, uid: stat.uid },
379
- expires: now + captureTimeout,
380
- command: captureCommand(file, watchdogSeconds, platform)
451
+ expires: resolvedNow + captureTimeout,
452
+ command,
453
+ resourceScope
381
454
  };
382
455
  return attempt;
383
- } catch (error) {
384
- rmSync(directory, { recursive: true, force: true });
385
- throw error;
386
- }
387
- };
388
- var cleanup = (pending) => {
389
- if (pending.closed === true) {
390
- return;
391
- }
392
- pending.closed = true;
393
- closeSync(pending.fd);
394
- rmSync(pending.directory, { recursive: true, force: true });
395
- };
456
+ }));
457
+ });
458
+ var releasePending = (pending) => Scope.close(pending.resourceScope, Exit.void);
396
459
  var decode = (line) => {
397
460
  if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(line)) {
398
461
  throw new Error("Invalid capture framing");
399
462
  }
400
- return Buffer.from(line, "base64").toString("utf-8");
463
+ const bytes = Result.getOrThrowWith(Base64.decode(line), () => new Error("Invalid capture framing"));
464
+ return Buffer.from(bytes).toString("utf-8");
401
465
  };
402
466
  var readCaptureArtifact = (pending, platform = process.platform) => {
403
467
  const stat = fstatSync(pending.fd);
@@ -420,8 +484,9 @@ var readCaptureArtifact = (pending, platform = process.platform) => {
420
484
  return fields;
421
485
  };
422
486
  var decodeConfigField = (state, field) => {
487
+ const value = decode(field).trim();
423
488
  if (state === "set") {
424
- return decode(field).trim();
489
+ return value;
425
490
  }
426
491
  return state === "unset" ? null : "error";
427
492
  };
@@ -460,8 +525,8 @@ var importCapture = (pending, platform = process.platform) => {
460
525
  assertBaselineIdentity(baseline, fields, rawLog);
461
526
  return baseline;
462
527
  };
463
- var publish = (ctx, pending, generation, baseline, now) => storageLock.withPermits(1)(Effect.gen(function* writeBaseline() {
464
- if ((yield* counter(ctx, pending.scope)) !== pending.counter) {
528
+ var publish = (ctx, pending, generation, baseline, now, canPublish) => storageLock.withPermits(1)(Effect.gen(function* writeBaseline() {
529
+ if ((yield* counter(ctx, pending.scope)) !== pending.counter || canPublish?.() === false) {
465
530
  return false;
466
531
  }
467
532
  const sequence = `${now.toString().padStart(15, "0")}-${randomUUID()}`;
@@ -483,10 +548,17 @@ var publish = (ctx, pending, generation, baseline, now) => storageLock.withPermi
483
548
  return true;
484
549
  }));
485
550
 
551
+ // src/config.ts
552
+ import { Result as Result2, Schema as Schema2 } from "effect";
553
+
486
554
  // src/scope.ts
487
555
  var scopePattern = /^(?<scope>[a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(?<subject>.+)$/u;
488
556
 
489
557
  // src/config.ts
558
+ var RequireScopeSchema = Schema2.Boolean;
559
+ var MaxLineLengthSchema = Schema2.Number.check(Schema2.makeFilter((value) => Number.isSafeInteger(value) && value >= 0));
560
+ var RawAllowedScopesSchema = Schema2.Array(Schema2.Unknown);
561
+ var NonEmptyStringSchema = Schema2.String.check(Schema2.makeFilter((value) => value.trim().length > 0));
490
562
  var parseConfig = (options) => {
491
563
  if (options === undefined) {
492
564
  return defaultConfig;
@@ -502,28 +574,15 @@ var parseConfig = (options) => {
502
574
  if (unknownKeys.length > 0) {
503
575
  throw new Error(`Unrecognized plugin options: ${unknownKeys.join(", ")}. Valid options: ${validOptions.join(", ")}.`);
504
576
  }
505
- const {
506
- requireScope = defaultConfig.requireScope,
507
- maxLineLength = defaultConfig.maxLineLength,
508
- allowedScopes: rawScopes
509
- } = options;
510
- if (!isJSONBoolean(requireScope)) {
511
- throw new Error("Invalid plugin option requireScope; expected a boolean.");
512
- }
513
- if (!isJSONNumber(maxLineLength) || !Number.isSafeInteger(maxLineLength) || maxLineLength < 0) {
514
- throw new Error("Invalid plugin option maxLineLength; expected an integer greater than or equal to 0.");
515
- }
577
+ const requireScope = Result2.getOrThrowWith(Schema2.decodeUnknownResult(RequireScopeSchema)(options.requireScope === undefined ? defaultConfig.requireScope : options.requireScope), () => new Error("Invalid plugin option requireScope; expected a boolean."));
578
+ const maxLineLength = Result2.getOrThrowWith(Schema2.decodeUnknownResult(MaxLineLengthSchema)(options.maxLineLength === undefined ? defaultConfig.maxLineLength : options.maxLineLength), () => new Error("Invalid plugin option maxLineLength; expected an integer greater than or equal to 0."));
516
579
  let allowedScopes;
517
- if (rawScopes !== undefined) {
518
- if (!Array.isArray(rawScopes)) {
519
- throw new TypeError("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
520
- }
580
+ if (options.allowedScopes !== undefined) {
581
+ const rawScopes = Result2.getOrThrowWith(Schema2.decodeUnknownResult(RawAllowedScopesSchema)(options.allowedScopes), () => new TypeError("Invalid plugin option allowedScopes; expected an array of non-empty strings."));
521
582
  const scopes = [];
522
583
  for (const item of rawScopes) {
523
- if (!isJSONString(item) || item.trim().length === 0) {
524
- throw new Error("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
525
- }
526
- const trimmed = item.trim();
584
+ const value = Result2.getOrThrowWith(Schema2.decodeUnknownResult(NonEmptyStringSchema)(item), () => new Error("Invalid plugin option allowedScopes; expected an array of non-empty strings."));
585
+ const trimmed = value.trim();
527
586
  if (scopePattern.exec(`${trimmed}: Subject`)?.[1] !== trimmed) {
528
587
  throw new Error(`Invalid plugin option allowedScopes; scope ${JSON.stringify(item)} cannot match the commit scope syntax.`);
529
588
  }
@@ -540,6 +599,8 @@ var parseConfig = (options) => {
540
599
  };
541
600
 
542
601
  // src/shell.ts
602
+ import { Result as Result3 } from "effect";
603
+ import { Base64 as Base642 } from "effect/encoding";
543
604
  var gitGlobalOptionsWithArg = new Set([
544
605
  "-C",
545
606
  "-c",
@@ -1958,7 +2019,11 @@ var decodePwshEncodedCommand = (encoded) => {
1958
2019
  if (encoded.length === 0 || encoded.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(encoded)) {
1959
2020
  throw inspectionError("Cannot decode invalid pwsh -EncodedCommand base64 payload.");
1960
2021
  }
1961
- const bytes = Buffer.from(encoded, "base64");
2022
+ const decoded = Base642.decode(encoded);
2023
+ if (Result3.isFailure(decoded)) {
2024
+ throw inspectionError("Cannot decode invalid pwsh -EncodedCommand base64 payload.");
2025
+ }
2026
+ const bytes = Buffer.from(decoded.success);
1962
2027
  if (bytes.length % 2 !== 0) {
1963
2028
  throw inspectionError("Cannot decode pwsh -EncodedCommand payload with odd UTF-16LE byte length.");
1964
2029
  }
@@ -2351,6 +2416,33 @@ ${example}`);
2351
2416
 
2352
2417
  // src/plugin.ts
2353
2418
  var { relative: relative2, resolve: resolve2 } = path;
2419
+ var isScopeClosed = (scope) => scope.state._tag === "Closed";
2420
+ var taggedError2 = Schema3.TaggedError;
2421
+ var GuardErrorReason = Schema3.Literals([
2422
+ "expired",
2423
+ "modified",
2424
+ "claim-mismatch",
2425
+ "ambiguous-target",
2426
+ "missing-baseline",
2427
+ "signing-config",
2428
+ "invalid-input",
2429
+ "commit-validation"
2430
+ ]);
2431
+
2432
+ class GuardError extends taggedError2()("GuardError", {
2433
+ reason: GuardErrorReason,
2434
+ message: Schema3.String
2435
+ }) {
2436
+ }
2437
+ var CommitContextInput = Schema3.Struct({
2438
+ refresh: Schema3.optionalKey(Schema3.Boolean),
2439
+ workdir: Schema3.optionalKey(Schema3.String.annotate({
2440
+ description: "Working directory of the Git repository relative to the session directory or absolute."
2441
+ })),
2442
+ directory: Schema3.optionalKey(Schema3.String.annotate({
2443
+ description: "Path to the Git repository checkout (alias for workdir)."
2444
+ }))
2445
+ });
2354
2446
  var publicationGuidance = 'Commit after the shell result reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing.';
2355
2447
  var receiptGuidance = "RECEIPT_OK confirms only that the artifact was written, not that the baseline was published.";
2356
2448
  var toToolError = (cause) => {
@@ -2359,8 +2451,7 @@ var toToolError = (cause) => {
2359
2451
  current = current.cause;
2360
2452
  }
2361
2453
  return current instanceof Tool.Error ? current : new Tool.Error({
2362
- message: current instanceof Error ? current.message : "[commit-guard] Git commit validation failed.",
2363
- error: current
2454
+ message: current instanceof Error ? current.message : "[commit-guard] Git commit validation failed."
2364
2455
  });
2365
2456
  };
2366
2457
  var signingError = (setting) => `[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.`;
@@ -2397,14 +2488,20 @@ var rememberExpired = (state, command) => {
2397
2488
  }
2398
2489
  }
2399
2490
  };
2400
- var expiredCaptureError = () => new Error("[commit-guard] This commit_context capture command expired after 20 seconds before it was claimed. Call commit_context right before committing and run the returned command immediately, unchanged, in the foreground.");
2401
- var sweep = (state) => Effect2.gen(function* sweepPending() {
2491
+ var expiredCaptureError = () => new GuardError({
2492
+ reason: "expired",
2493
+ message: "[commit-guard] This commit_context capture command expired after 20 seconds before it was claimed. Call commit_context right before committing and run the returned command immediately, unchanged, in the foreground."
2494
+ });
2495
+ var sweep = Effect2.fnUntraced(function* sweepPending(state) {
2402
2496
  const now = yield* state.clock.currentTimeMillis;
2403
2497
  for (const attempt of [...state.pending.values()].slice(0, 32)) {
2498
+ if (state.pending.get(attempt.scope) !== attempt) {
2499
+ continue;
2500
+ }
2404
2501
  state.pending.delete(attempt.scope);
2405
2502
  if (attempt.claimed === undefined && now >= attempt.expires) {
2406
2503
  rememberExpired(state, attempt.command);
2407
- cleanup(attempt);
2504
+ yield* releasePending(attempt);
2408
2505
  yield* recordState(state.ctx, attempt, "expired");
2409
2506
  yield* invalidateOwned(state.ctx, attempt);
2410
2507
  } else {
@@ -2416,26 +2513,38 @@ var resolveCanonicalWorkdir = (sessionDirectory, workdir) => {
2416
2513
  try {
2417
2514
  return realpathSync2(isJSONString(workdir) ? resolve2(sessionDirectory, workdir) : sessionDirectory);
2418
2515
  } catch {
2419
- throw new Error("[commit-guard] Cannot access the shell workdir. Supply an existing checkout directory and call commit_context there.");
2516
+ throw new GuardError({
2517
+ reason: "ambiguous-target",
2518
+ message: "[commit-guard] Cannot access the shell workdir. Supply an existing checkout directory and call commit_context there."
2519
+ });
2420
2520
  }
2421
2521
  };
2422
2522
  var validateFields = (input, fields, booleans) => {
2423
2523
  if (!isRecord(input)) {
2424
- throw new Error("[commit-guard] Cannot inspect non-object tool input. Supply literal command and workdir fields.");
2524
+ throw new GuardError({
2525
+ reason: "invalid-input",
2526
+ message: "[commit-guard] Cannot inspect non-object tool input. Supply literal command and workdir fields."
2527
+ });
2425
2528
  }
2426
2529
  for (const field of fields) {
2427
2530
  if (input[field] !== undefined && !isJSONString(input[field])) {
2428
- throw new Error(`[commit-guard] Invalid ${field}; expected a string.`);
2531
+ throw new GuardError({
2532
+ reason: "invalid-input",
2533
+ message: `[commit-guard] Invalid ${field}; expected a string.`
2534
+ });
2429
2535
  }
2430
2536
  }
2431
2537
  for (const field of booleans) {
2432
2538
  if (input[field] !== undefined && !isJSONBoolean(input[field])) {
2433
- throw new Error(`[commit-guard] Invalid ${field}; expected a boolean.`);
2539
+ throw new GuardError({
2540
+ reason: "invalid-input",
2541
+ message: `[commit-guard] Invalid ${field}; expected a boolean.`
2542
+ });
2434
2543
  }
2435
2544
  }
2436
2545
  return input;
2437
2546
  };
2438
- var prepareCapture = (state, toolContext, request, workdir, scope) => Effect2.gen(function* prepare() {
2547
+ var prepareCapture = Effect2.fnUntraced(function* prepare(state, toolContext, request, workdir, scope) {
2439
2548
  const { ctx, pending, config } = state;
2440
2549
  const now = yield* state.clock.currentTimeMillis;
2441
2550
  const previous = pending.get(scope);
@@ -2452,7 +2561,7 @@ var prepareCapture = (state, toolContext, request, workdir, scope) => Effect2.ge
2452
2561
  };
2453
2562
  }
2454
2563
  pending.delete(scope);
2455
- cleanup(previous);
2564
+ yield* releasePending(previous);
2456
2565
  yield* recordState(ctx, previous, "failed", request.refresh === true ? "capture replaced by refresh" : "capture replaced by workdir change");
2457
2566
  yield* invalidateOwned(ctx, previous);
2458
2567
  }
@@ -2462,14 +2571,41 @@ var prepareCapture = (state, toolContext, request, workdir, scope) => Effect2.ge
2462
2571
  return { content: baselineGuidance(baseline, config) };
2463
2572
  }
2464
2573
  }
2574
+ if (isScopeClosed(state.activationScope)) {
2575
+ return yield* Effect2.fail(new GuardError({
2576
+ reason: "claim-mismatch",
2577
+ message: "[commit-guard] Plugin unloaded before capture preparation."
2578
+ }));
2579
+ }
2465
2580
  const count = yield* invalidate(ctx, scope);
2466
- const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, workdir, 15, process.platform, now));
2467
- pending.set(scope, attempt);
2468
- const status = state.failures.get(scope) ?? (yield* captureStatus(ctx, scope));
2469
- yield* recordState(ctx, attempt, "prepared");
2470
- return { content: captureInstructions(attempt, status) };
2581
+ return yield* Effect2.uninterruptibleMask((restore) => Effect2.gen(function* handoffAndFinish() {
2582
+ if (isScopeClosed(state.activationScope)) {
2583
+ return yield* Effect2.fail(new GuardError({
2584
+ reason: "claim-mismatch",
2585
+ message: "[commit-guard] Plugin unloaded before capture handoff."
2586
+ }));
2587
+ }
2588
+ const attempt = yield* createPending(state.activationScope, scope, toolContext.sessionID, toolContext.agent, count, workdir, 15, process.platform, now);
2589
+ pending.set(scope, attempt);
2590
+ return yield* restore(Effect2.gen(function* finishPrepare() {
2591
+ const status = state.failures.get(scope) ?? (yield* captureStatus(ctx, scope));
2592
+ const recorded = yield* recordState(ctx, attempt, "prepared");
2593
+ if (!recorded || isScopeClosed(state.activationScope) || isScopeClosed(attempt.resourceScope) || pending.get(scope) !== attempt) {
2594
+ return yield* Effect2.fail(new GuardError({
2595
+ reason: "claim-mismatch",
2596
+ message: "[commit-guard] Capture preparation was superseded before completion. Call commit_context again."
2597
+ }));
2598
+ }
2599
+ return { content: captureInstructions(attempt, status) };
2600
+ })).pipe(Effect2.onExit((exit) => Exit2.isFailure(exit) ? Effect2.gen(function* rollbackPrepared() {
2601
+ if (pending.get(scope) === attempt) {
2602
+ pending.delete(scope);
2603
+ }
2604
+ yield* invalidateOwned(ctx, attempt).pipe(Effect2.catchCause(() => Effect2.void));
2605
+ }).pipe(Effect2.ensuring(Scope2.close(attempt.resourceScope, exit).pipe(Effect2.catchCause(() => Effect2.void)))) : Effect2.void));
2606
+ }));
2471
2607
  });
2472
- var runCommitContext = (state, input, toolContext) => Effect2.gen(function* context() {
2608
+ var runCommitContext = Effect2.fnUntraced(function* context(state, input, toolContext) {
2473
2609
  yield* sweep(state);
2474
2610
  const { ctx } = state;
2475
2611
  if (ctx.location.workspaceID !== undefined) {
@@ -2477,7 +2613,13 @@ var runCommitContext = (state, input, toolContext) => Effect2.gen(function* cont
2477
2613
  content: "Commit context capture is unavailable for remote workspaces."
2478
2614
  };
2479
2615
  }
2480
- const request = yield* Effect2.try(() => validateFields(input, ["workdir", "directory"], ["refresh"]));
2616
+ const request = yield* Effect2.try({
2617
+ try: () => validateFields(input, ["workdir", "directory"], ["refresh"]),
2618
+ catch: (error) => error instanceof GuardError ? error : new GuardError({
2619
+ reason: "invalid-input",
2620
+ message: error instanceof Error ? error.message : "[commit-guard] Invalid tool input."
2621
+ })
2622
+ });
2481
2623
  const session = yield* ctx.session.get({
2482
2624
  sessionID: toolContext.sessionID
2483
2625
  });
@@ -2513,7 +2655,7 @@ var runCommitContext = (state, input, toolContext) => Effect2.gen(function* cont
2513
2655
  return yield* prepareCapture(state, toolContext, request, workdir, scope).pipe(Effect2.ensuring(Effect2.sync(() => {
2514
2656
  state.preparing.delete(scope);
2515
2657
  })));
2516
- }).pipe(Effect2.mapError(toToolError));
2658
+ }, Effect2.mapError(toToolError));
2517
2659
  var claimMismatchReason = (event, input, attempt, sessionDirectory) => {
2518
2660
  if (event.tool !== "shell") {
2519
2661
  return `tool "${event.tool}" is not "shell"`;
@@ -2538,12 +2680,12 @@ var claimMismatchReason = (event, input, attempt, sessionDirectory) => {
2538
2680
  }
2539
2681
  return null;
2540
2682
  };
2541
- var claimCapture = (state, event, input, attempt) => Effect2.gen(function* claim() {
2683
+ var claimCapture = Effect2.fnUntraced(function* claim(state, event, input, attempt) {
2542
2684
  const now = yield* state.clock.currentTimeMillis;
2543
2685
  if (attempt.claimed === undefined && now >= attempt.expires) {
2544
2686
  state.pending.delete(attempt.scope);
2545
2687
  rememberExpired(state, attempt.command);
2546
- cleanup(attempt);
2688
+ yield* releasePending(attempt);
2547
2689
  yield* recordState(state.ctx, attempt, "expired");
2548
2690
  yield* invalidateOwned(state.ctx, attempt);
2549
2691
  yield* Effect2.fail(expiredCaptureError());
@@ -2554,14 +2696,17 @@ var claimCapture = (state, event, input, attempt) => Effect2.gen(function* claim
2554
2696
  });
2555
2697
  const sessionDirectory = session.location.directory ?? state.ctx.location.directory;
2556
2698
  const nowAfterSession = yield* state.clock.currentTimeMillis;
2557
- if (state.pending.get(attempt.scope) !== attempt) {
2558
- yield* Effect2.fail(new Error("[commit-guard] Capture is no longer active. Call commit_context with refresh: true."));
2699
+ if (isScopeClosed(state.activationScope) || isScopeClosed(attempt.resourceScope) || state.pending.get(attempt.scope) !== attempt) {
2700
+ yield* Effect2.fail(new GuardError({
2701
+ reason: "claim-mismatch",
2702
+ message: "[commit-guard] Capture is no longer active. Call commit_context with refresh: true."
2703
+ }));
2559
2704
  return;
2560
2705
  }
2561
2706
  if (attempt.claimed === undefined && nowAfterSession >= attempt.expires) {
2562
2707
  state.pending.delete(attempt.scope);
2563
2708
  rememberExpired(state, attempt.command);
2564
- cleanup(attempt);
2709
+ yield* releasePending(attempt);
2565
2710
  yield* recordState(state.ctx, attempt, "expired");
2566
2711
  yield* invalidateOwned(state.ctx, attempt);
2567
2712
  yield* Effect2.fail(expiredCaptureError());
@@ -2569,39 +2714,66 @@ var claimCapture = (state, event, input, attempt) => Effect2.gen(function* claim
2569
2714
  }
2570
2715
  const reason = claimMismatchReason(event, input, attempt, sessionDirectory);
2571
2716
  if (reason !== null) {
2572
- yield* Effect2.fail(new Error(`[commit-guard] Capture must use its exact foreground shell command in the original session and workdir (${reason}). Call commit_context with refresh: true.`));
2717
+ yield* Effect2.fail(new GuardError({
2718
+ reason: "claim-mismatch",
2719
+ message: `[commit-guard] Capture must use its exact foreground shell command in the original session and workdir (${reason}). Call commit_context with refresh: true.`
2720
+ }));
2573
2721
  return;
2574
2722
  }
2575
2723
  attempt.claimed = { messageID: event.messageID, id: event.id };
2576
2724
  yield* recordState(state.ctx, attempt, "claimed");
2577
2725
  });
2578
- var verifyBaselineAndValidate = (state, event, input, command, shellMode, invocations) => Effect2.gen(function* validate() {
2726
+ var verifyBaselineAndValidate = Effect2.fnUntraced(function* validate(state, event, input, command, shellMode, invocations) {
2579
2727
  const { ctx, config } = state;
2580
2728
  if (ctx.location.workspaceID !== undefined) {
2581
- return yield* Effect2.fail(new Error("[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."));
2729
+ return yield* Effect2.fail(new GuardError({
2730
+ reason: "ambiguous-target",
2731
+ message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."
2732
+ }));
2582
2733
  }
2583
2734
  const session = yield* ctx.session.get({ sessionID: event.sessionID });
2584
2735
  if (session.location.workspaceID !== ctx.location.workspaceID || invocations.some((invocation) => invocation.targetError !== undefined)) {
2585
- return yield* Effect2.fail(new Error("[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."));
2736
+ return yield* Effect2.fail(new GuardError({
2737
+ reason: "ambiguous-target",
2738
+ 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."
2739
+ }));
2586
2740
  }
2587
2741
  const sessionDirectory = session.location.directory ?? ctx.location.directory;
2588
- const workdir = yield* Effect2.try(() => resolveCanonicalWorkdir(sessionDirectory, input.workdir));
2742
+ const workdir = yield* Effect2.try({
2743
+ try: () => resolveCanonicalWorkdir(sessionDirectory, input.workdir),
2744
+ catch: (error) => error instanceof GuardError ? error : new GuardError({
2745
+ reason: "ambiguous-target",
2746
+ message: "[commit-guard] Cannot access the shell workdir. Supply an existing checkout directory and call commit_context there."
2747
+ })
2748
+ });
2589
2749
  const root = findGitRoot(workdir);
2590
2750
  const baseline = yield* load(ctx, scopeFor(ctx, event.sessionID, config, workdir));
2591
2751
  if (baseline === undefined || root === undefined || baseline.directory !== root) {
2592
2752
  const expected = root ?? workdir;
2593
2753
  const hint = JSON.stringify(relative2(sessionDirectory, expected) || ".");
2594
- return yield* Effect2.fail(new Error(`[commit-guard] No published baseline for ${expected}. Call commit_context({ workdir: ${hint} }), then run the returned command immediately, unchanged, in the foreground with that workdir (do not run it in the background). Do not wrap it or chain another command onto it. ${publicationGuidance} RECEIPT_OK alone is insufficient.`));
2754
+ return yield* Effect2.fail(new GuardError({
2755
+ reason: "missing-baseline",
2756
+ message: `[commit-guard] No published baseline for ${expected}. Call commit_context({ workdir: ${hint} }), then run the returned command immediately, unchanged, in the foreground with that workdir (do not run it in the background). Do not wrap it or chain another command onto it. ${publicationGuidance} RECEIPT_OK alone is insufficient.`
2757
+ }));
2595
2758
  }
2596
2759
  if (baseline.gpgsign === "error" || baseline.signingkey === "error") {
2597
- return yield* Effect2.fail(new Error(signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")));
2760
+ return yield* Effect2.fail(new GuardError({
2761
+ reason: "signing-config",
2762
+ message: signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")
2763
+ }));
2598
2764
  }
2599
- yield* Effect2.try(() => {
2600
- validateGitCommits(invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, command, shellMode);
2765
+ yield* Effect2.try({
2766
+ try: () => {
2767
+ validateGitCommits(invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, command, shellMode);
2768
+ },
2769
+ catch: (error) => new GuardError({
2770
+ reason: "commit-validation",
2771
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
2772
+ })
2601
2773
  });
2602
2774
  return yield* Effect2.void;
2603
2775
  });
2604
- var isPwshTool = (state, event) => Effect2.gen(function* detectPwsh() {
2776
+ var isPwshTool = Effect2.fnUntraced(function* detectPwsh(state, event) {
2605
2777
  const description = event.info?.description;
2606
2778
  if (isJSONString(description)) {
2607
2779
  return /using pwsh\./iu.test(description);
@@ -2613,14 +2785,23 @@ var isPwshTool = (state, event) => Effect2.gen(function* detectPwsh() {
2613
2785
  }
2614
2786
  return process.platform === "win32";
2615
2787
  });
2616
- var handleBeforeExecute = (state, event) => Effect2.gen(function* before() {
2788
+ var handleBeforeExecute = Effect2.fnUntraced(function* before(state, event) {
2617
2789
  yield* sweep(state);
2618
2790
  if (event.tool !== "shell" && event.tool !== "bash") {
2619
2791
  return;
2620
2792
  }
2621
- const input = yield* Effect2.try(() => validateFields(event.input, ["workdir"], ["background"]));
2793
+ const input = yield* Effect2.try({
2794
+ try: () => validateFields(event.input, ["workdir"], ["background"]),
2795
+ catch: (error) => error instanceof GuardError ? error : new GuardError({
2796
+ reason: "invalid-input",
2797
+ message: error instanceof Error ? error.message : "[commit-guard] Invalid tool input."
2798
+ })
2799
+ });
2622
2800
  if (!isJSONString(input.command)) {
2623
- yield* Effect2.fail(new Error("[commit-guard] Invalid command; expected a literal command string."));
2801
+ yield* Effect2.fail(new GuardError({
2802
+ reason: "invalid-input",
2803
+ message: "[commit-guard] Invalid command; expected a literal command string."
2804
+ }));
2624
2805
  return;
2625
2806
  }
2626
2807
  const { command } = input;
@@ -2635,7 +2816,10 @@ var handleBeforeExecute = (state, event) => Effect2.gen(function* before() {
2635
2816
  return item.command.trim() === trimmed || command.includes(item.command) || command.includes(item.artifactPath) || encoded !== undefined && command.includes(encoded);
2636
2817
  });
2637
2818
  if (modified !== undefined) {
2638
- yield* Effect2.fail(new Error("[commit-guard] Capture command was modified, wrapped, or chained. Run the exact command returned by commit_context unchanged in the foreground, or call commit_context({ refresh: true })."));
2819
+ yield* Effect2.fail(new GuardError({
2820
+ reason: "modified",
2821
+ message: "[commit-guard] Capture command was modified, wrapped, or chained. Run the exact command returned by commit_context unchanged in the foreground, or call commit_context({ refresh: true })."
2822
+ }));
2639
2823
  return;
2640
2824
  }
2641
2825
  if (state.recentExpired.has(trimmed) || [...state.recentExpired].some((expired) => command.includes(expired))) {
@@ -2643,15 +2827,21 @@ var handleBeforeExecute = (state, event) => Effect2.gen(function* before() {
2643
2827
  return;
2644
2828
  }
2645
2829
  const shellMode = (yield* isPwshTool(state, event)) ? "pwsh" : "posix";
2646
- const invocations = yield* Effect2.try(() => extractGitCommits(command, { shell: shellMode }));
2830
+ const invocations = yield* Effect2.try({
2831
+ try: () => extractGitCommits(command, { shell: shellMode }),
2832
+ catch: (error) => new GuardError({
2833
+ reason: "commit-validation",
2834
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
2835
+ })
2836
+ });
2647
2837
  if (invocations.length > 0 && !invocations.every((invocation) => invocation.isHelp)) {
2648
2838
  yield* verifyBaselineAndValidate(state, event, input, command, shellMode, invocations);
2649
2839
  }
2650
- }).pipe(Effect2.mapError(toToolError));
2840
+ }, Effect2.mapError(toToolError));
2651
2841
  var allowedMetadataKeys = new Set(["status", "exit", "truncated", "timeout"]);
2652
2842
  var unexpectedMetadataKeys = (metadata) => Object.keys(metadata).filter((key) => !allowedMetadataKeys.has(key));
2653
2843
  var isVerifiedShellMetadata = (metadata) => isRecord(metadata) && metadata.status === "completed" && metadata.exit === 0 && metadata.truncated === false && (metadata.timeout === undefined || metadata.timeout === false) && unexpectedMetadataKeys(metadata).length === 0;
2654
- var publishCapturedAttempt = (state, event, attempt) => Effect2.gen(function* publishAttempt() {
2844
+ var publishCapturedAttempt = Effect2.fnUntraced(function* publishAttempt(state, event, attempt) {
2655
2845
  const { ctx } = state;
2656
2846
  if (!isRecord(event.input) || event.input.command !== attempt.command) {
2657
2847
  return "claimed capture command was modified before execution";
@@ -2670,14 +2860,24 @@ var publishCapturedAttempt = (state, event, attempt) => Effect2.gen(function* pu
2670
2860
  if (session === null || session.location.workspaceID !== ctx.location.workspaceID) {
2671
2861
  return "capture session or workspace no longer matches";
2672
2862
  }
2863
+ const isAttemptActive = () => !isScopeClosed(state.activationScope) && !isScopeClosed(attempt.resourceScope) && state.pending.get(attempt.scope) === attempt;
2864
+ if (!isAttemptActive()) {
2865
+ return "capture was superseded by a refresh";
2866
+ }
2673
2867
  const baseline = yield* Effect2.try(() => importCapture(attempt)).pipe(Effect2.orElseSucceed(() => null));
2674
2868
  if (baseline === null || baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined) {
2675
2869
  return "private artifact is invalid or incomplete (END required)";
2676
2870
  }
2871
+ if (!isAttemptActive()) {
2872
+ return "capture was superseded by a refresh";
2873
+ }
2677
2874
  const now = yield* state.clock.currentTimeMillis;
2678
- if (!(yield* publish(ctx, attempt, state.generation, baseline, now).pipe(Effect2.catchCause(() => Effect2.succeed(false))))) {
2875
+ if (!(yield* publish(ctx, attempt, state.generation, baseline, now, isAttemptActive).pipe(Effect2.catchCause(() => Effect2.succeed(false))))) {
2679
2876
  return "capture storage failed or its counter changed";
2680
2877
  }
2878
+ if (!isAttemptActive()) {
2879
+ return "capture was superseded by a refresh";
2880
+ }
2681
2881
  state.failures.delete(attempt.scope);
2682
2882
  return baseline;
2683
2883
  });
@@ -2707,19 +2907,19 @@ var rememberFailure = (state, scope, reason) => {
2707
2907
  }
2708
2908
  }
2709
2909
  };
2710
- var finalizeAttempt = (state, attempt, outcome) => Effect2.gen(function* finalize() {
2711
- if (state.pending.get(attempt.scope) === attempt) {
2712
- state.pending.delete(attempt.scope);
2713
- }
2714
- if (isJSONString(outcome)) {
2715
- rememberFailure(state, attempt.scope, outcome);
2716
- yield* recordState(state.ctx, attempt, "failed", outcome).pipe(Effect2.catchCause(() => Effect2.void));
2717
- yield* invalidateOwned(state.ctx, attempt);
2718
- }
2719
- }).pipe(Effect2.ensuring(Effect2.sync(() => {
2720
- cleanup(attempt);
2721
- })), Effect2.catchCause(() => Effect2.void));
2722
- var handleAfterExecute = (state, event) => Effect2.gen(function* after() {
2910
+ var finalizeAttempt = Effect2.fnUntraced(function* finalize(state, attempt, outcome) {
2911
+ yield* Effect2.gen(function* recordOutcome() {
2912
+ if (state.pending.get(attempt.scope) === attempt) {
2913
+ state.pending.delete(attempt.scope);
2914
+ }
2915
+ if (isJSONString(outcome)) {
2916
+ rememberFailure(state, attempt.scope, outcome);
2917
+ yield* recordState(state.ctx, attempt, "failed", outcome).pipe(Effect2.catchCause(() => Effect2.void));
2918
+ yield* invalidateOwned(state.ctx, attempt).pipe(Effect2.catchCause(() => Effect2.void));
2919
+ }
2920
+ }).pipe(Effect2.ensuring(releasePending(attempt).pipe(Effect2.catchCause(() => Effect2.void))), Effect2.catchCause(() => Effect2.void));
2921
+ });
2922
+ var handleAfterExecute = Effect2.fnUntraced(function* after(state, event) {
2723
2923
  const attempt = [...state.pending.values()].find((item) => item.claimed?.id === event.id && item.claimed?.messageID === event.messageID && item.sessionID === event.sessionID && item.agent === event.agent);
2724
2924
  if (attempt === undefined) {
2725
2925
  return;
@@ -2730,10 +2930,18 @@ var handleAfterExecute = (state, event) => Effect2.gen(function* after() {
2730
2930
  }
2731
2931
  let outcome = "capture import or storage failed";
2732
2932
  yield* Effect2.gen(function* publishing() {
2733
- outcome = yield* publishCapturedAttempt(state, event, attempt);
2734
- if (!isJSONString(outcome)) {
2735
- yield* recordState(state.ctx, attempt, "published");
2933
+ const published = yield* publishCapturedAttempt(state, event, attempt);
2934
+ if (isJSONString(published)) {
2935
+ outcome = published;
2936
+ return;
2736
2937
  }
2938
+ const recorded = yield* recordState(state.ctx, attempt, "published");
2939
+ if (!recorded || isScopeClosed(state.activationScope) || isScopeClosed(attempt.resourceScope) || state.pending.get(attempt.scope) !== attempt) {
2940
+ outcome = "capture was superseded by a refresh";
2941
+ return;
2942
+ }
2943
+ state.pending.delete(attempt.scope);
2944
+ outcome = published;
2737
2945
  }).pipe(Effect2.onExit(() => finalizeAttempt(state, attempt, outcome)), Effect2.catchCause(() => Effect2.void));
2738
2946
  const note = isJSONString(outcome) ? `[commit-guard] This capture did not publish a usable baseline: ${outcome.slice(0, 256)}.
2739
2947
  RECEIPT_OK alone does not authorize a commit.
@@ -2755,9 +2963,11 @@ var plugin = Plugin.define({
2755
2963
  effect: (ctx) => Effect2.gen(function* setup() {
2756
2964
  const config = yield* Effect2.sync(() => parseConfig(ctx.options));
2757
2965
  const clock = yield* Clock.Clock;
2966
+ const activationScope = yield* Effect2.scope;
2758
2967
  const state = {
2759
2968
  ctx,
2760
2969
  clock,
2970
+ activationScope,
2761
2971
  config,
2762
2972
  generation: randomUUID2(),
2763
2973
  pending: new Map,
@@ -2767,12 +2977,14 @@ var plugin = Plugin.define({
2767
2977
  failures: new Map
2768
2978
  };
2769
2979
  yield* Effect2.addFinalizer(() => Effect2.gen(function* unload() {
2770
- for (const attempt of state.pending.values()) {
2771
- cleanup(attempt);
2772
- yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication");
2773
- yield* invalidateOwned(ctx, attempt);
2774
- }
2980
+ const remaining = [...state.pending.values()];
2775
2981
  state.pending.clear();
2982
+ for (const attempt of remaining) {
2983
+ yield* Effect2.gen(function* cleanupAttempt() {
2984
+ yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication").pipe(Effect2.catchCause(() => Effect2.void));
2985
+ yield* invalidateOwned(ctx, attempt).pipe(Effect2.catchCause(() => Effect2.void));
2986
+ }).pipe(Effect2.ensuring(releasePending(attempt).pipe(Effect2.catchCause(() => Effect2.void))), Effect2.catchCause(() => Effect2.void));
2987
+ }
2776
2988
  }));
2777
2989
  yield* ctx.tool.transform((editor) => {
2778
2990
  editor.add({
@@ -2790,21 +3002,7 @@ Use literal message text and real body newlines.
2790
3002
  Example: git commit -m $'scope: Subject\n\nBody line one.\nBody line two.'
2791
3003
  Replace scope and follow the returned line-length and signoff rules.
2792
3004
  Add -s only when the returned policy or repository instructions require it.`,
2793
- input: {
2794
- type: "object",
2795
- properties: {
2796
- refresh: { type: "boolean" },
2797
- workdir: {
2798
- type: "string",
2799
- description: "Working directory of the Git repository relative to the session directory or absolute."
2800
- },
2801
- directory: {
2802
- type: "string",
2803
- description: "Path to the Git repository checkout (alias for workdir)."
2804
- }
2805
- },
2806
- additionalProperties: false
2807
- },
3005
+ input: CommitContextInput,
2808
3006
  execute: (input, toolContext) => runCommitContext(state, input, toolContext)
2809
3007
  });
2810
3008
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-commit-guard",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "OpenCode V2 plugin enforcing git commit format rules",
5
5
  "homepage": "https://github.com/gotenksIN/opencode-commit-guard",
6
6
  "license": "MIT",
@@ -33,17 +33,17 @@
33
33
  "@interfere/landmines": "0.1.1",
34
34
  "@opencode/core": "latest",
35
35
  "@opencode/plugin": "latest",
36
- "@types/bun": "1.4.5",
36
+ "@types/bun": "latest",
37
37
  "effect": "4.1.0",
38
38
  "oxfmt": "latest",
39
39
  "oxlint": "latest",
40
40
  "oxlint-tsgolint": "latest",
41
- "typescript": "7.0.2",
41
+ "typescript": "latest",
42
42
  "ultracite": "latest"
43
43
  },
44
44
  "peerDependencies": {
45
45
  "@opencode/plugin": "^2.4.1",
46
- "effect": "^4.0.0"
46
+ "effect": "^4.1.0"
47
47
  },
48
48
  "engines": {
49
49
  "bun": ">=1.4.0"