opencode-commit-guard 1.1.2 → 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 +20 -38
  2. package/dist/index.js +1344 -325
  3. package/package.json +7 -6
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, 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,12 +23,19 @@ import {
23
23
  } from "fs";
24
24
  import { tmpdir } from "os";
25
25
  import nodePath from "path";
26
- import { gzipSync } from "zlib";
27
- 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";
28
36
 
29
37
  // src/types.ts
30
38
  var isJSONString = (value) => Object.prototype.toString.call(value) === "[object String]";
31
- var isJSONNumber = (value) => Object.prototype.toString.call(value) === "[object Number]";
32
39
  var isJSONBoolean = (value) => Object.prototype.toString.call(value) === "[object Boolean]";
33
40
  var isRecord = (value) => Object.prototype.toString.call(value) === "[object Object]";
34
41
  var defaultConfig = {
@@ -42,9 +49,15 @@ var defaultConfig = {
42
49
  var { dirname, isAbsolute, join, relative, resolve } = nodePath;
43
50
  var version = 1;
44
51
  var maxBytes = 262144;
45
- var captureTimeout = 20000;
52
+ var captureTimeout = Duration.toMillis(Duration.seconds(20));
46
53
  var policy = "commit-guard-context-v1";
47
54
  var storageLock = Semaphore.makeUnsafe(1);
55
+ var taggedError = Schema.TaggedError;
56
+
57
+ class CaptureArtifactError extends taggedError()("CaptureArtifactError", {
58
+ message: Schema.String
59
+ }) {
60
+ }
48
61
  var digest = (text) => createHash("sha256").update(text).digest("hex");
49
62
  var scopeFor = (ctx, sessionID, config, targetDir) => {
50
63
  const { location } = ctx;
@@ -70,15 +83,17 @@ var isGitDirectory = (dir) => {
70
83
  }
71
84
  };
72
85
  var findGitRoot = (startDir) => {
86
+ let found;
73
87
  let current;
74
88
  try {
75
89
  current = realpathSync(startDir);
76
90
  } catch {
77
- return;
91
+ return found;
78
92
  }
79
93
  while (true) {
80
94
  if (isGitDirectory(current)) {
81
- return current;
95
+ found = current;
96
+ break;
82
97
  }
83
98
  const parent = dirname(current);
84
99
  if (parent === current) {
@@ -86,7 +101,7 @@ var findGitRoot = (startDir) => {
86
101
  }
87
102
  current = parent;
88
103
  }
89
- return;
104
+ return found;
90
105
  };
91
106
  var findSubRepos = (dir, maxDepth = 2) => {
92
107
  const repos = [];
@@ -94,23 +109,26 @@ var findSubRepos = (dir, maxDepth = 2) => {
94
109
  if (currentDepth > maxDepth) {
95
110
  return;
96
111
  }
112
+ let entries = [];
97
113
  try {
98
- const entries = readdirSync(currentDir, { withFileTypes: true });
99
- for (const entry of entries) {
100
- if (!entry.isDirectory() && !entry.isSymbolicLink()) {
101
- continue;
102
- }
103
- if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist") {
104
- continue;
105
- }
106
- const fullPath = join(currentDir, entry.name);
107
- if (isGitDirectory(fullPath)) {
108
- repos.push(fullPath);
109
- } else if (currentDepth < maxDepth) {
110
- search(fullPath, currentDepth + 1);
111
- }
114
+ entries = readdirSync(currentDir, { withFileTypes: true });
115
+ } catch {
116
+ return;
117
+ }
118
+ for (const entry of entries) {
119
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) {
120
+ continue;
121
+ }
122
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist") {
123
+ continue;
124
+ }
125
+ const fullPath = join(currentDir, entry.name);
126
+ if (isGitDirectory(fullPath)) {
127
+ repos.push(fullPath);
128
+ } else if (currentDepth < maxDepth) {
129
+ search(fullPath, currentDepth + 1);
112
130
  }
113
- } catch {}
131
+ }
114
132
  };
115
133
  search(dir, 1);
116
134
  return repos;
@@ -141,19 +159,20 @@ var resolveTargetWorkdir = (baseDir, requestedDir) => {
141
159
  return { workdir: realpathSync(baseDir) };
142
160
  }
143
161
  const subRepos = findSubRepos(baseDir);
144
- if (subRepos.length === 1) {
145
- return { workdir: realpathSync(subRepos[0]) };
146
- }
147
- if (subRepos.length === 0) {
162
+ const [firstRepo] = subRepos;
163
+ if (firstRepo === undefined) {
148
164
  return {
149
165
  error: `No Git repository found in ${baseDir}. Specify the repository directory with the 'workdir' option, for example: commit_context({ workdir: "path/to/repo" }).`
150
166
  };
151
167
  }
168
+ if (subRepos.length === 1) {
169
+ return { workdir: realpathSync(firstRepo) };
170
+ }
152
171
  const repoList = subRepos.map((repo) => relative(baseDir, repo)).join(", ");
153
172
  return {
154
173
  error: `The directory ${baseDir} is not a Git repository. Multiple Git repositories were found: ${repoList}.
155
174
  Specify which repository to target with the 'workdir' option, for example:
156
- commit_context({ workdir: "${relative(baseDir, subRepos[0])}" })`
175
+ commit_context({ workdir: "${relative(baseDir, firstRepo)}" })`
157
176
  };
158
177
  };
159
178
  var counterKey = (scope) => `counter/${scope}`;
@@ -178,12 +197,13 @@ var invalidateOwned = (ctx, attempt) => storageLock.withPermits(1)(Effect.gen(fu
178
197
  }));
179
198
  var recordState = (ctx, attempt, state, reason = "") => storageLock.withPermits(1)(Effect.gen(function* storeState() {
180
199
  if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) {
181
- return;
200
+ return false;
182
201
  }
183
202
  yield* ctx.storage.set(`state/${attempt.scope}`, {
184
203
  state,
185
204
  reason: reason.slice(0, 256)
186
205
  });
206
+ return true;
187
207
  }));
188
208
  var captureStatus = (ctx, scope) => Effect.gen(function* readCaptureStatus() {
189
209
  const value = yield* ctx.storage.get(`state/${scope}`);
@@ -201,12 +221,19 @@ var captureStatus = (ctx, scope) => Effect.gen(function* readCaptureStatus() {
201
221
  }
202
222
  return "";
203
223
  });
204
- var validBaseline = (value) => {
205
- if (!isRecord(value)) {
206
- return false;
207
- }
208
- 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));
209
- };
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);
210
237
  var scanStoragePrefix = (ctx, keyPrefix, visitor) => Effect.gen(function* scan() {
211
238
  let after;
212
239
  do {
@@ -243,9 +270,9 @@ var load = (ctx, scope) => storageLock.withPermits(1)(Effect.gen(function* readB
243
270
  }));
244
271
  return newest?.baseline;
245
272
  }));
246
- var captureCommand = (path, watchdogSeconds) => {
247
- if (process.platform === "win32") {
248
- return windowsCaptureCommand(path);
273
+ var captureCommand = (path, watchdogSeconds, platform) => {
274
+ if (platform === "win32") {
275
+ return windowsCaptureCommand(path, watchdogSeconds);
249
276
  }
250
277
  const quoted = `'${path.replaceAll("'", "'\\''")}'`;
251
278
  const script = `set -euo pipefail
@@ -280,7 +307,8 @@ kill "$watchdog" 2>/dev/null
280
307
  wait "$watchdog" 2>/dev/null
281
308
  exit "$status"' bash '${script.replaceAll("'", "'\\''")}' ${quoted} 2>/dev/null`;
282
309
  };
283
- var windowsCaptureCommand = (path) => {
310
+ var windowsCaptureCommand = (path, watchdogSeconds) => {
311
+ const watchdogMs = Math.round(watchdogSeconds * 1000);
284
312
  const script = `$ErrorActionPreference = 'Stop'
285
313
  $clock = [Diagnostics.Stopwatch]::StartNew()
286
314
  $lines = [Collections.Generic.List[string]]::new()
@@ -294,24 +322,26 @@ function gitResult([string]$arguments) {
294
322
  $p = [Diagnostics.Process]::new()
295
323
  $p.StartInfo = $info
296
324
  $memory = [IO.MemoryStream]::new()
325
+ $started = $false
297
326
  try {
298
- if (!$p.Start()) { throw 'Git did not start' }
327
+ $started = $p.Start()
328
+ if (!$started) { throw 'Git did not start' }
299
329
  $p.BeginErrorReadLine()
300
330
  $buffer = [byte[]]::new(4096)
301
331
  while ($true) {
302
332
  $task = $p.StandardOutput.BaseStream.ReadAsync($buffer, 0, $buffer.Length)
303
- $remaining = 15000 - [int]$clock.ElapsedMilliseconds
333
+ $remaining = ${watchdogMs} - [int]$clock.ElapsedMilliseconds
304
334
  if ($remaining -le 0 -or !$task.Wait($remaining)) { throw 'Capture timed out' }
305
335
  $count = $task.Result
306
336
  if ($count -eq 0) { break }
307
337
  if ($memory.Length + $count -gt ${maxBytes}) { throw 'Capture exceeds size limit' }
308
338
  $memory.Write($buffer, 0, $count)
309
339
  }
310
- $remaining = 15000 - [int]$clock.ElapsedMilliseconds
340
+ $remaining = ${watchdogMs} - [int]$clock.ElapsedMilliseconds
311
341
  if ($remaining -le 0 -or !$p.WaitForExit($remaining)) { throw 'Capture timed out' }
312
342
  return @{ Code = $p.ExitCode; Bytes = $memory.ToArray() }
313
343
  } finally {
314
- if ($p.Id -and !$p.HasExited) { & taskkill.exe /PID $p.Id /T /F > $null 2>&1 }
344
+ if ($started -and !$p.HasExited) { try { $p.Kill($true) } catch {} }
315
345
  $p.Dispose()
316
346
  $memory.Dispose()
317
347
  }
@@ -344,56 +374,98 @@ try {
344
374
  }
345
375
  $lines.Add('END')
346
376
  $bytes = [Text.Encoding]::UTF8.GetBytes(($lines -join "\`n") + "\`n")
347
- if ($bytes.Length -gt ${maxBytes} -or $clock.ElapsedMilliseconds -ge 15000) { throw 'Capture exceeds limits' }
348
- $path = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(path).toString("base64")}'))
377
+ if ($bytes.Length -gt ${maxBytes} -or $clock.ElapsedMilliseconds -ge ${watchdogMs}) { throw 'Capture exceeds limits' }
378
+ $path = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Base64.encode(path)}'))
349
379
  $file = [IO.FileStream]::new($path, [IO.FileMode]::Truncate, [IO.FileAccess]::Write, [IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)
350
380
  try { $file.Write($bytes, 0, $bytes.Length) } finally { $file.Dispose() }
351
381
  [Console]::Write("RECEIPT_OK\`n")
352
382
  } catch { exit 1 }`;
353
- const compressed = gzipSync(Buffer.from(script)).toString("base64");
354
- const bootstrap = `$m = [IO.MemoryStream]::new([Convert]::FromBase64String('${compressed}')); $g = [IO.Compression.GZipStream]::new($m, [IO.Compression.CompressionMode]::Decompress); $r = [IO.StreamReader]::new($g, [Text.Encoding]::UTF8); try { Invoke-Expression $r.ReadToEnd() } finally { $r.Dispose(); $g.Dispose(); $m.Dispose() }`;
355
- return `powershell -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(bootstrap, "utf16le").toString("base64")}`;
383
+ return `pwsh -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Base64.encode(Buffer.from(script, "utf16le"))}`;
356
384
  };
357
- var createPending = (scope, sessionID, agent, counterValue, workdir, watchdogSeconds = 15) => {
358
- const directory = mkdtempSync(join(tmpdir(), "commit-context-"));
359
- try {
360
- const file = join(directory, randomUUID());
361
- const fd = openSync(file, constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_RDWR, 384);
362
- const stat = fstatSync(fd);
363
- return {
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
+ });
441
+ const attempt = {
364
442
  scope,
365
443
  sessionID,
366
444
  agent,
367
445
  counter: counterValue,
368
- directory,
446
+ artifactPath: artifact.artifactPath,
447
+ directory: artifact.directory,
369
448
  workdir,
370
- fd,
449
+ fd: artifact.fd,
371
450
  identity: { dev: stat.dev, ino: stat.ino, uid: stat.uid },
372
- expires: Date.now() + captureTimeout,
373
- command: captureCommand(file, watchdogSeconds)
451
+ expires: resolvedNow + captureTimeout,
452
+ command,
453
+ resourceScope
374
454
  };
375
- } catch (error) {
376
- rmSync(directory, { recursive: true, force: true });
377
- throw error;
378
- }
379
- };
380
- var cleanup = (pending) => {
381
- if (pending.closed === true) {
382
- return;
383
- }
384
- pending.closed = true;
385
- closeSync(pending.fd);
386
- rmSync(pending.directory, { recursive: true, force: true });
387
- };
455
+ return attempt;
456
+ }));
457
+ });
458
+ var releasePending = (pending) => Scope.close(pending.resourceScope, Exit.void);
388
459
  var decode = (line) => {
389
460
  if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(line)) {
390
461
  throw new Error("Invalid capture framing");
391
462
  }
392
- 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");
393
465
  };
394
- var readCaptureArtifact = (pending) => {
466
+ var readCaptureArtifact = (pending, platform = process.platform) => {
395
467
  const stat = fstatSync(pending.fd);
396
- if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino || stat.uid !== pending.identity.uid || process.platform !== "win32" && (stat.mode & 511) !== 384 || stat.size > maxBytes || stat.size === 0) {
468
+ if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino || stat.uid !== pending.identity.uid || platform !== "win32" && (stat.mode & 511) !== 384 || stat.size > maxBytes || stat.size === 0) {
397
469
  throw new Error("Invalid private capture artifact");
398
470
  }
399
471
  const bytes = Buffer.alloc(stat.size);
@@ -412,28 +484,29 @@ var readCaptureArtifact = (pending) => {
412
484
  return fields;
413
485
  };
414
486
  var decodeConfigField = (state, field) => {
487
+ const value = decode(field).trim();
415
488
  if (state === "set") {
416
- return decode(field).trim();
489
+ return value;
417
490
  }
418
491
  return state === "unset" ? null : "error";
419
492
  };
420
493
  var assertBaselineIdentity = (baseline, fields, rawLog) => {
421
494
  const { directory, gitDir, commonDir, head, messages } = baseline;
422
- if (!isAbsolute(directory) || !isAbsolute(gitDir) || !isAbsolute(commonDir) || directory !== findGitRoot(baseline.workdir) || !["branch", "detached"].includes(fields[4]) || !["head", "unborn"].includes(fields[6]) || head !== null && !/^[a-f0-9]{40,64}$/u.test(head) || head === null && rawLog !== "" || head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\x00\x00"))) {
495
+ if (!isAbsolute(directory) || !isAbsolute(gitDir) || !isAbsolute(commonDir) || directory !== findGitRoot(baseline.workdir) || !["branch", "detached"].includes(fields[4] ?? "") || !["head", "unborn"].includes(fields[6] ?? "") || head !== null && !/^[a-f0-9]{40,64}$/u.test(head) || head === null && rawLog !== "" || head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\x00\x00"))) {
423
496
  throw new Error("Invalid Git baseline");
424
497
  }
425
498
  };
426
- var importCapture = (pending) => {
427
- const fields = readCaptureArtifact(pending);
428
- const rawRoot = decode(fields[1]).trimEnd();
499
+ var importCapture = (pending, platform = process.platform) => {
500
+ const fields = readCaptureArtifact(pending, platform);
501
+ const rawRoot = decode(fields[1] ?? "").trimEnd();
429
502
  const root = isAbsolute(rawRoot) ? realpathSync(resolve(rawRoot)) : rawRoot;
430
- const gitDir = decode(fields[2]).trimEnd();
431
- const commonDir = decode(fields[3]).trimEnd();
432
- const branch = fields[4] === "branch" ? decode(fields[5]).trimEnd() : null;
433
- const head = fields[6] === "head" ? decode(fields[7]).trim() : null;
434
- const rawLog = decode(fields[8]);
503
+ const gitDir = decode(fields[2] ?? "").trimEnd();
504
+ const commonDir = decode(fields[3] ?? "").trimEnd();
505
+ const branch = fields[4] === "branch" ? decode(fields[5] ?? "").trimEnd() : null;
506
+ const head = fields[6] === "head" ? decode(fields[7] ?? "").trim() : null;
507
+ const rawLog = decode(fields[8] ?? "");
435
508
  const messages = head === null ? [] : rawLog.split("\x00\x00").filter((message) => message.length > 0);
436
- const value = decode(fields[10]).trim();
509
+ const value = decode(fields[10] ?? "").trim();
437
510
  let gpgsign = fields[9] === "unset" ? "unset" : "error";
438
511
  if (fields[9] === "set" && (value === "true" || value === "false")) {
439
512
  gpgsign = value;
@@ -447,16 +520,16 @@ var importCapture = (pending) => {
447
520
  head,
448
521
  messages,
449
522
  gpgsign,
450
- signingkey: decodeConfigField(fields[11], fields[12])
523
+ signingkey: decodeConfigField(fields[11] ?? "", fields[12] ?? "")
451
524
  };
452
525
  assertBaselineIdentity(baseline, fields, rawLog);
453
526
  return baseline;
454
527
  };
455
- var publish = (ctx, pending, generation, baseline) => storageLock.withPermits(1)(Effect.gen(function* writeBaseline() {
456
- 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) {
457
530
  return false;
458
531
  }
459
- const sequence = `${Date.now().toString().padStart(15, "0")}-${randomUUID()}`;
532
+ const sequence = `${now.toString().padStart(15, "0")}-${randomUUID()}`;
460
533
  const checksum = snapshotChecksum(pending.scope, pending.counter, generation, sequence, baseline);
461
534
  yield* ctx.storage.set(prefix(pending.scope) + sequence, {
462
535
  schema: version,
@@ -475,10 +548,17 @@ var publish = (ctx, pending, generation, baseline) => storageLock.withPermits(1)
475
548
  return true;
476
549
  }));
477
550
 
551
+ // src/config.ts
552
+ import { Result as Result2, Schema as Schema2 } from "effect";
553
+
478
554
  // src/scope.ts
479
555
  var scopePattern = /^(?<scope>[a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(?<subject>.+)$/u;
480
556
 
481
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));
482
562
  var parseConfig = (options) => {
483
563
  if (options === undefined) {
484
564
  return defaultConfig;
@@ -494,28 +574,15 @@ var parseConfig = (options) => {
494
574
  if (unknownKeys.length > 0) {
495
575
  throw new Error(`Unrecognized plugin options: ${unknownKeys.join(", ")}. Valid options: ${validOptions.join(", ")}.`);
496
576
  }
497
- const {
498
- requireScope = defaultConfig.requireScope,
499
- maxLineLength = defaultConfig.maxLineLength,
500
- allowedScopes: rawScopes
501
- } = options;
502
- if (!isJSONBoolean(requireScope)) {
503
- throw new Error("Invalid plugin option requireScope; expected a boolean.");
504
- }
505
- if (!isJSONNumber(maxLineLength) || !Number.isSafeInteger(maxLineLength) || maxLineLength < 0) {
506
- throw new Error("Invalid plugin option maxLineLength; expected an integer greater than or equal to 0.");
507
- }
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."));
508
579
  let allowedScopes;
509
- if (rawScopes !== undefined) {
510
- if (!Array.isArray(rawScopes)) {
511
- throw new TypeError("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
512
- }
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."));
513
582
  const scopes = [];
514
583
  for (const item of rawScopes) {
515
- if (!isJSONString(item) || item.trim().length === 0) {
516
- throw new Error("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
517
- }
518
- 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();
519
586
  if (scopePattern.exec(`${trimmed}: Subject`)?.[1] !== trimmed) {
520
587
  throw new Error(`Invalid plugin option allowedScopes; scope ${JSON.stringify(item)} cannot match the commit scope syntax.`);
521
588
  }
@@ -532,6 +599,8 @@ var parseConfig = (options) => {
532
599
  };
533
600
 
534
601
  // src/shell.ts
602
+ import { Result as Result3 } from "effect";
603
+ import { Base64 as Base642 } from "effect/encoding";
535
604
  var gitGlobalOptionsWithArg = new Set([
536
605
  "-C",
537
606
  "-c",
@@ -732,7 +801,7 @@ var scanDoubleQuote = (command, start, nesting) => {
732
801
  while (i < command.length && command[i] !== '"') {
733
802
  const character = command[i];
734
803
  if (character === "\\" && i + 1 < command.length) {
735
- const escaped = command[i + 1];
804
+ const escaped = command[i + 1] ?? "";
736
805
  if (escaped !== `
737
806
  `) {
738
807
  content += ['"', "\\", "$", "`"].includes(escaped) ? escaped : `\\${escaped}`;
@@ -818,13 +887,14 @@ var trackSubstitutionWord = (command, state) => {
818
887
  }
819
888
  let word = "";
820
889
  for (let end = state.i;end < command.length; end += 1) {
821
- if (command[end] === "\\" && command[end + 1] === `
890
+ const ch = command[end] ?? "";
891
+ if (ch === "\\" && command[end + 1] === `
822
892
  `) {
823
893
  end += 1;
824
- } else if (isWordSeparator(command[end])) {
894
+ } else if (isWordSeparator(ch)) {
825
895
  break;
826
896
  } else {
827
- word += command[end];
897
+ word += ch;
828
898
  }
829
899
  }
830
900
  advanceCaseState(state.cases, state.depth, word);
@@ -885,7 +955,7 @@ var stepSubstitutionSyntax = (command, state, nesting) => {
885
955
  };
886
956
  var stepSubstitutionWord = (command, state, nesting) => {
887
957
  const { i } = state;
888
- const character = command[i];
958
+ const character = command[i] ?? "";
889
959
  if (character === "#" && state.atWordStart) {
890
960
  const end = command.indexOf(`
891
961
  `, i);
@@ -896,7 +966,7 @@ var stepSubstitutionWord = (command, state, nesting) => {
896
966
  trackSubstitutionWord(command, state);
897
967
  }
898
968
  const result = scanWordFragment(command, i, nesting + 1);
899
- if (result === undefined) {
969
+ if (result === null) {
900
970
  return false;
901
971
  }
902
972
  state.i = result.end;
@@ -953,7 +1023,7 @@ var consumeCommandSubstitution = (command, start, nesting = 0) => {
953
1023
  if (stepSubstitutionSyntax(command, state, nesting) || stepSubstitutionWord(command, state, nesting)) {
954
1024
  continue;
955
1025
  }
956
- const character = command[state.i];
1026
+ const character = command[state.i] ?? "";
957
1027
  if (stepSubstitutionParenthesis(command, state)) {
958
1028
  continue;
959
1029
  }
@@ -995,6 +1065,9 @@ var heredocSubstitutions = (body) => {
995
1065
  var isBraceCommandPosition = (tokens) => {
996
1066
  for (let index = tokens.length - 1;index >= 0; index -= 1) {
997
1067
  const token = tokens[index];
1068
+ if (token === undefined) {
1069
+ continue;
1070
+ }
998
1071
  if (token.type === "operator") {
999
1072
  break;
1000
1073
  }
@@ -1027,8 +1100,11 @@ var scanWord = (command, start, nesting) => {
1027
1100
  let expansion = false;
1028
1101
  let unsupportedDelimiter;
1029
1102
  let i = start;
1030
- while (i < command.length && !isWordSeparator(command[i])) {
1031
- const character = command[i];
1103
+ while (i < command.length) {
1104
+ const character = command[i] ?? "";
1105
+ if (isWordSeparator(character)) {
1106
+ break;
1107
+ }
1032
1108
  if (character === "\\" && command[i + 1] === `
1033
1109
  `) {
1034
1110
  i += 2;
@@ -1045,7 +1121,7 @@ var scanWord = (command, start, nesting) => {
1045
1121
  unsupportedDelimiter = dollarQuote === "'" ? "ANSI-C quoted" : "locale-quoted";
1046
1122
  }
1047
1123
  const result = scanWordFragment(command, i, nesting);
1048
- if (result !== undefined) {
1124
+ if (result !== null) {
1049
1125
  quoted ||= result.quoted === true;
1050
1126
  if (result.bytes === undefined) {
1051
1127
  content += result.content;
@@ -1094,17 +1170,18 @@ var scanWordFragment = (command, i, nesting) => {
1094
1170
  substitutions: [result.content]
1095
1171
  };
1096
1172
  }
1097
- return;
1173
+ return null;
1098
1174
  };
1099
1175
  var skipTrivia = (command, start) => {
1100
1176
  let i = start;
1101
1177
  while (i < command.length) {
1102
- if (/[ \t\r]/u.test(command[i])) {
1178
+ const ch = command[i] ?? "";
1179
+ if (/[ \t\r]/u.test(ch)) {
1103
1180
  i += 1;
1104
- } else if (command[i] === "\\" && command[i + 1] === `
1181
+ } else if (ch === "\\" && command[i + 1] === `
1105
1182
  `) {
1106
1183
  i += 2;
1107
- } else if (command[i] === "#") {
1184
+ } else if (ch === "#") {
1108
1185
  const end = command.indexOf(`
1109
1186
  `, i);
1110
1187
  i = end === -1 ? command.length : end;
@@ -1117,7 +1194,8 @@ var skipTrivia = (command, start) => {
1117
1194
  var readHeredocDelimiter = (command, start, nesting) => {
1118
1195
  const stripTabs = command[start + 2] === "-";
1119
1196
  const i = skipTrivia(command, start + (stripTabs ? 3 : 2));
1120
- if (i >= command.length || isWordSeparator(command[i]) || /[<>]/u.test(command[i])) {
1197
+ const next = command[i];
1198
+ if (next === undefined || isWordSeparator(next) || /[<>]/u.test(next)) {
1121
1199
  throw incompleteHeredoc();
1122
1200
  }
1123
1201
  const word = scanWord(command, i, nesting);
@@ -1127,7 +1205,7 @@ var readHeredocDelimiter = (command, start, nesting) => {
1127
1205
  return {
1128
1206
  delimiter: {
1129
1207
  delimiter: word.content,
1130
- quoted: word.quoted === true,
1208
+ quoted: word.quoted,
1131
1209
  stripTabs
1132
1210
  },
1133
1211
  end: word.end
@@ -1139,6 +1217,9 @@ var readOperator = (command, i, tokens) => {
1139
1217
  return pair;
1140
1218
  }
1141
1219
  const character = command[i];
1220
+ if (character === undefined) {
1221
+ return null;
1222
+ }
1142
1223
  if (`|;
1143
1224
  ()`.includes(character) || character === "&" && command[i + 1] !== ">") {
1144
1225
  return character;
@@ -1149,11 +1230,12 @@ var readOperator = (command, i, tokens) => {
1149
1230
  `) {
1150
1231
  end += 2;
1151
1232
  }
1152
- if (command[end] === undefined || isWordSeparator(command[end]) || /[<>]/u.test(command[end])) {
1233
+ const following = command[end];
1234
+ if (following === undefined || isWordSeparator(following) || /[<>]/u.test(following)) {
1153
1235
  return character;
1154
1236
  }
1155
1237
  }
1156
- return;
1238
+ return null;
1157
1239
  };
1158
1240
  var tokenizeShell = (command) => {
1159
1241
  const tokens = [];
@@ -1163,7 +1245,7 @@ var tokenizeShell = (command) => {
1163
1245
  let i = 0;
1164
1246
  while ((i = skipTrivia(command, i)) < command.length) {
1165
1247
  const operator = readOperator(command, i, tokens);
1166
- if (operator !== undefined) {
1248
+ if (operator !== null) {
1167
1249
  if (operator === "(") {
1168
1250
  if (arithmeticDepth === undefined && command[i + 1] === "(" && isArithmeticCommandPosition(tokens)) {
1169
1251
  arithmeticDepth = depth;
@@ -1182,11 +1264,14 @@ var tokenizeShell = (command) => {
1182
1264
  for (const heredoc of heredocs) {
1183
1265
  const body = consumeHeredoc(command, i, heredoc);
1184
1266
  i = body.end;
1185
- tokens[heredoc.index] = {
1186
- ...tokens[heredoc.index],
1187
- heredoc: { body: body.content, quoted: heredoc.quoted },
1188
- substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body.content)
1189
- };
1267
+ const target = tokens[heredoc.index];
1268
+ if (target !== undefined) {
1269
+ tokens[heredoc.index] = {
1270
+ ...target,
1271
+ heredoc: { body: body.content, quoted: heredoc.quoted },
1272
+ substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body.content)
1273
+ };
1274
+ }
1190
1275
  }
1191
1276
  heredocs.length = 0;
1192
1277
  }
@@ -1219,41 +1304,18 @@ var tokenizeShell = (command) => {
1219
1304
  }
1220
1305
  return tokens;
1221
1306
  };
1222
- var splitSimpleCommands = (tokens) => {
1223
- const commands = [];
1224
- let current = [];
1225
- let precedingPipeline = false;
1226
- for (const token of tokens) {
1227
- if (token.type === "operator") {
1228
- const isPipeline = token.value === "|" || token.value === "|&";
1229
- const hasCommand = current.length > 0;
1230
- if (hasCommand) {
1231
- commands.push({
1232
- tokens: current,
1233
- pipeline: precedingPipeline || isPipeline
1234
- });
1235
- }
1236
- current = [];
1237
- if (hasCommand || token.value !== `
1238
- `) {
1239
- precedingPipeline = isPipeline;
1240
- }
1241
- } else {
1242
- current.push(token);
1243
- }
1244
- }
1245
- if (current.length > 0) {
1246
- commands.push({ tokens: current, pipeline: precedingPipeline });
1247
- }
1248
- return commands;
1249
- };
1250
1307
  var extractCommandWords = (tokens) => {
1251
1308
  const words = [];
1252
1309
  for (let i = 0;i < tokens.length; i += 1) {
1253
- if (tokens[i].type === "redirect") {
1254
- i += tokens[i + 1]?.type === "word" ? 1 : 0;
1255
- } else if (tokens[i].type === "word") {
1256
- words.push(tokens[i]);
1310
+ const token = tokens[i];
1311
+ if (token === undefined) {
1312
+ continue;
1313
+ }
1314
+ if (token.type === "redirect") {
1315
+ const hasEmbeddedTarget = /[<>]&(?:\d+|-)$/u.test(token.value);
1316
+ i += !hasEmbeddedTarget && tokens[i + 1]?.type === "word" ? 1 : 0;
1317
+ } else if (token.type === "word") {
1318
+ words.push(token);
1257
1319
  }
1258
1320
  }
1259
1321
  return words;
@@ -1263,6 +1325,9 @@ var skipWrapperOptions = (words, start, valued) => {
1263
1325
  let index = start;
1264
1326
  while (index < words.length) {
1265
1327
  const argument = words[index];
1328
+ if (argument === undefined) {
1329
+ break;
1330
+ }
1266
1331
  if (argument === "--") {
1267
1332
  return index + 1;
1268
1333
  }
@@ -1277,6 +1342,9 @@ var findCommandStart = (words) => {
1277
1342
  let index = 0;
1278
1343
  while (index < words.length) {
1279
1344
  const word = words[index];
1345
+ if (word === undefined) {
1346
+ break;
1347
+ }
1280
1348
  if (isAssignment(word) || commandPrefixes.has(word)) {
1281
1349
  index += 1;
1282
1350
  } else {
@@ -1294,6 +1362,9 @@ var consumeGitGlobalOptions = (words, start) => {
1294
1362
  let targetError;
1295
1363
  while (index < words.length) {
1296
1364
  const token = words[index];
1365
+ if (token === undefined) {
1366
+ break;
1367
+ }
1297
1368
  const argument = token.value;
1298
1369
  if (token.expansion === true) {
1299
1370
  throw inspectionError("Cannot inspect dynamic Git options or subcommands. Use literal command words.");
@@ -1307,7 +1378,7 @@ var consumeGitGlobalOptions = (words, start) => {
1307
1378
  if (!argument.startsWith("-")) {
1308
1379
  break;
1309
1380
  }
1310
- const option = /^-[Cc]/u.test(argument) ? argument.slice(0, 2) : argument.split("=")[0];
1381
+ const option = /^-[Cc]/u.test(argument) ? argument.slice(0, 2) : argument.split("=")[0] ?? "";
1311
1382
  if (targetGlobalOptions.has(option)) {
1312
1383
  targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
1313
1384
  }
@@ -1315,9 +1386,8 @@ var consumeGitGlobalOptions = (words, start) => {
1315
1386
  }
1316
1387
  return { index, targetError };
1317
1388
  };
1318
- var consumeShortCommitFlags = (words, start, result) => {
1389
+ var consumeShortCommitFlags = (words, start, argument, result) => {
1319
1390
  let index = start;
1320
- const argument = words[start].value;
1321
1391
  for (let i = 1;i < argument.length; i += 1) {
1322
1392
  const option = argument[i];
1323
1393
  if (option === "s") {
@@ -1345,6 +1415,18 @@ var consumeShortCommitFlags = (words, start, result) => {
1345
1415
  }
1346
1416
  return index;
1347
1417
  };
1418
+ var consumeMessageOrFileFlag = (words, index, argument, isMessage, result) => {
1419
+ const equals = argument.indexOf("=");
1420
+ const nextIndex = equals === -1 ? index + 1 : index;
1421
+ const input = equals === -1 ? words[nextIndex]?.value : argument.slice(equals + 1);
1422
+ if (isMessage) {
1423
+ result.messageExpansion ||= words[nextIndex]?.expansion === true;
1424
+ }
1425
+ if (input !== undefined) {
1426
+ (isMessage ? result.messages : result.filePaths).push(input);
1427
+ }
1428
+ return nextIndex;
1429
+ };
1348
1430
  var parseCommitArguments = (words, start) => {
1349
1431
  const result = {
1350
1432
  messages: [],
@@ -1358,45 +1440,40 @@ var parseCommitArguments = (words, start) => {
1358
1440
  hasTrailer: false
1359
1441
  };
1360
1442
  for (let index = start;index < words.length; index += 1) {
1361
- const argument = words[index].value;
1362
- if (argument === "--") {
1443
+ const token = words[index];
1444
+ if (token === undefined || token.value === "--") {
1363
1445
  break;
1364
1446
  }
1447
+ const argument = token.value;
1365
1448
  const boolean = booleanCommitFlags.get(argument);
1366
1449
  if (boolean !== undefined) {
1367
1450
  Object.assign(result, { [boolean[0]]: boolean[1] });
1368
1451
  continue;
1369
1452
  }
1370
- const [option] = argument.split("=");
1453
+ const [option = ""] = argument.split("=");
1371
1454
  const isMessage = option === "--message" || argument === "-m";
1372
1455
  const isFile = option === "--file" || argument === "-F";
1373
1456
  if (isMessage || isFile) {
1374
- const equals = argument.indexOf("=");
1375
- const input = equals === -1 ? words[index += 1]?.value : argument.slice(equals + 1);
1376
- if (isMessage) {
1377
- result.messageExpansion ||= words[index]?.expansion === true;
1378
- }
1379
- if (input !== undefined) {
1380
- (isMessage ? result.messages : result.filePaths).push(input);
1381
- }
1457
+ index = consumeMessageOrFileFlag(words, index, argument, isMessage, result);
1382
1458
  } else if (commitLongOptionsWithArg.has(option)) {
1383
1459
  result.isFixup ||= option === "--fixup";
1384
1460
  result.hasTrailer ||= option === "--trailer";
1385
1461
  index += argument.includes("=") ? 0 : 1;
1386
1462
  } else if (/^-[^-]/u.test(argument)) {
1387
- index = consumeShortCommitFlags(words, index, result);
1463
+ index = consumeShortCommitFlags(words, index, argument, result);
1388
1464
  }
1389
1465
  }
1390
1466
  return result;
1391
1467
  };
1392
- var extractInvocation = (words, start) => {
1468
+ var isGitExecutable = (executable, mode) => mode === "pwsh" ? /^(?:.*[/\\])?git(?:\.exe)?$/iu.test(executable) : executable === "git" || executable.endsWith("/git");
1469
+ var extractInvocation = (words, start, mode) => {
1393
1470
  const executable = words[start]?.value;
1394
- if (executable === undefined || executable !== "git" && !executable.endsWith("/git")) {
1395
- return;
1471
+ if (executable === undefined || !isGitExecutable(executable, mode)) {
1472
+ return null;
1396
1473
  }
1397
1474
  const global = consumeGitGlobalOptions(words, start + 1);
1398
1475
  if (words[global.index]?.value !== "commit") {
1399
- return;
1476
+ return null;
1400
1477
  }
1401
1478
  const wrapperChange = words.slice(0, start).some((word) => word.value === "env" || isAssignment(word.value));
1402
1479
  return {
@@ -1408,7 +1485,7 @@ var consumeShellOptions = (words, start) => {
1408
1485
  let index = start + 1;
1409
1486
  let executeString = false;
1410
1487
  while (index < words.length) {
1411
- const option = words[index].value;
1488
+ const option = words[index]?.value ?? "";
1412
1489
  if (option === "--") {
1413
1490
  index += 1;
1414
1491
  break;
@@ -1429,17 +1506,17 @@ var consumeShellOptions = (words, start) => {
1429
1506
  };
1430
1507
  var extractShellCBody = (words, start) => {
1431
1508
  if (!/^(?:.*\/)?(?:bash|sh|zsh)$/u.test(words[start]?.value ?? "")) {
1432
- return;
1509
+ return null;
1433
1510
  }
1434
1511
  const { index, executeString } = consumeShellOptions(words, start);
1435
1512
  if (!executeString) {
1436
- return;
1513
+ return null;
1437
1514
  }
1438
1515
  const body = words[index];
1439
1516
  if (body === undefined || body.expansion === true) {
1440
1517
  throw inspectionError("Cannot parse an expanded or missing shell -c body reliably. Use a literal shell body; if committing, run git commit directly.");
1441
1518
  }
1442
- if (/^(?:.*\/)?sh$/u.test(words[start].value) && body.value.includes("$'")) {
1519
+ if (/^(?:.*\/)?sh$/u.test(words[start]?.value ?? "") && body.value.includes("$'")) {
1443
1520
  throw inspectionError("Cannot parse $' quoting portably in sh -c. Use a literal bash -c or zsh -c body.");
1444
1521
  }
1445
1522
  return body.value;
@@ -1471,44 +1548,744 @@ var attachStdinHeredoc = (invocation, tokens, pipeline) => {
1471
1548
  stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined
1472
1549
  };
1473
1550
  };
1474
- var extractGitCommits = (command, inheritedDirectoryChange = false, depth = 0) => {
1551
+ var pwshBacktickEscapes = new Map(Object.entries({
1552
+ "0": "\x00",
1553
+ a: "\x07",
1554
+ b: "\b",
1555
+ e: "\x1B",
1556
+ f: "\f",
1557
+ n: `
1558
+ `,
1559
+ r: "\r",
1560
+ t: "\t",
1561
+ v: "\v"
1562
+ }));
1563
+ var pwshTargetMutators = new Set([
1564
+ "cd",
1565
+ "sl",
1566
+ "set-location",
1567
+ "push-location",
1568
+ "pushd",
1569
+ "pop-location",
1570
+ "popd",
1571
+ "set-variable",
1572
+ "sv",
1573
+ "iex",
1574
+ "invoke-expression",
1575
+ "."
1576
+ ]);
1577
+ var isPwshSingleQuote = (character) => character === "'" || character >= "\u2018" && character <= "\u201B";
1578
+ var isPwshDoubleQuote = (character) => character === '"' || character >= "\u201C" && character <= "\u201E";
1579
+ var isPwshHorizontalSpace = (character) => character === " " || character === "\t" || character === "\x85" || character === "\xA0" || character === "\u2028" || character === "\u2029" || character === "\v" || character === "\f" || /^\p{Zs}$/u.test(character);
1580
+ var isPwshNewline = (character) => character === `
1581
+ ` || character === "\r";
1582
+ var isPwshWordSeparator = (character) => isPwshHorizontalSpace(character) || isPwshNewline(character) || ";&|(){}".includes(character);
1583
+ var isPwshVariableStart = (command, index) => command[index] === "$" && /[\p{L}\p{N}_?^$:]/u.test(command[index + 1] ?? "");
1584
+ var decodePwshBacktick = (command, start) => {
1585
+ const next = command[start + 1];
1586
+ if (next === undefined) {
1587
+ return { content: "`", end: start + 1 };
1588
+ }
1589
+ if (next === "\r" && command[start + 2] === `
1590
+ `) {
1591
+ return { content: `
1592
+ `, end: start + 3 };
1593
+ }
1594
+ if (next === "u" && command[start + 2] === "{") {
1595
+ const close = command.indexOf("}", start + 3);
1596
+ const hex = close === -1 ? "" : command.slice(start + 3, close);
1597
+ if (close === -1 || !/^[0-9a-fA-F]{1,6}$/u.test(hex)) {
1598
+ throw inspectionError("Invalid PowerShell Unicode escape sequence. Use valid `u{hex} syntax.");
1599
+ }
1600
+ const code = Number.parseInt(hex, 16);
1601
+ if (code > 1114111 || code >= 55296 && code <= 57343) {
1602
+ throw inspectionError("Invalid PowerShell Unicode scalar value in `u{hex} escape.");
1603
+ }
1604
+ return { content: String.fromCodePoint(code), end: close + 1 };
1605
+ }
1606
+ const mapped = pwshBacktickEscapes.get(next);
1607
+ return { content: mapped ?? next, end: start + 2 };
1608
+ };
1609
+ var scanPwshSingleQuote = (command, start) => {
1610
+ let content = "";
1611
+ let i = start + 1;
1612
+ while (i < command.length) {
1613
+ const ch = command[i] ?? "";
1614
+ if (isPwshSingleQuote(ch)) {
1615
+ const next = command[i + 1] ?? "";
1616
+ if (isPwshSingleQuote(next)) {
1617
+ content += next;
1618
+ i += 2;
1619
+ continue;
1620
+ }
1621
+ return { content, end: i + 1 };
1622
+ }
1623
+ content += ch;
1624
+ i += 1;
1625
+ }
1626
+ throw inspectionError(`Unterminated PowerShell single quote starting at character ${start + 1}. Close the quote before running the command.`);
1627
+ };
1628
+ var scanPwshBracedVar = (command, start) => {
1629
+ for (let i = start + 2;i < command.length; i += 1) {
1630
+ if (command[i] === "`") {
1631
+ i += 1;
1632
+ } else if (command[i] === "}") {
1633
+ return i + 1;
1634
+ }
1635
+ }
1636
+ throw inspectionError(`Unterminated PowerShell braced variable starting at character ${start + 1}.`);
1637
+ };
1638
+ var skipPwshBlockComment = (command, start) => {
1639
+ const end = command.indexOf("#>", start + 2);
1640
+ if (end === -1) {
1641
+ throw inspectionError(`Unterminated PowerShell block comment starting at character ${start + 1}. Close it with #>.`);
1642
+ }
1643
+ return end + 2;
1644
+ };
1645
+ var scanPwshExpandableText = (text, nesting) => {
1646
+ let content = "";
1647
+ let expansion = false;
1648
+ const substitutions = [];
1649
+ let i = 0;
1650
+ while (i < text.length) {
1651
+ const ch = text[i] ?? "";
1652
+ if (ch === "`") {
1653
+ const escaped = decodePwshBacktick(text, i);
1654
+ content += escaped.content;
1655
+ i = escaped.end;
1656
+ } else if (ch === "$" && text[i + 1] === "(") {
1657
+ const sub = consumePwshSubexpression(text, i, nesting);
1658
+ content += text.slice(i, sub.end);
1659
+ substitutions.push(sub.content);
1660
+ expansion = true;
1661
+ i = sub.end;
1662
+ } else if (ch === "$" && text[i + 1] === "{") {
1663
+ const end = scanPwshBracedVar(text, i);
1664
+ content += text.slice(i, end);
1665
+ expansion = true;
1666
+ i = end;
1667
+ } else {
1668
+ expansion ||= isPwshVariableStart(text, i);
1669
+ content += ch;
1670
+ i += 1;
1671
+ }
1672
+ }
1673
+ return { content, expansion, substitutions };
1674
+ };
1675
+ var scanPwshHereString = (command, start, nesting) => {
1676
+ const quote = command[start + 1] ?? "";
1677
+ const isSingle = isPwshSingleQuote(quote);
1678
+ let i = start + 2;
1679
+ while (i < command.length && (command[i] === " " || command[i] === "\t")) {
1680
+ i += 1;
1681
+ }
1682
+ if (command[i] === "\r" && command[i + 1] === `
1683
+ `) {
1684
+ i += 2;
1685
+ } else if (command[i] === `
1686
+ `) {
1687
+ i += 1;
1688
+ } else {
1689
+ throw inspectionError(`Invalid PowerShell here-string header at character ${start + 1}. Put a newline immediately after @${quote}.`);
1690
+ }
1691
+ const lines = [];
1692
+ while (i < command.length) {
1693
+ const lineEnd = command.indexOf(`
1694
+ `, i);
1695
+ const rawEnd = lineEnd === -1 ? command.length : lineEnd;
1696
+ const rawLine = command.slice(i, rawEnd);
1697
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
1698
+ const first = line[0] ?? "";
1699
+ if ((isSingle ? isPwshSingleQuote(first) : isPwshDoubleQuote(first)) && line[1] === "@") {
1700
+ const footerEnd = i + 2;
1701
+ const body = lines.join(`
1702
+ `);
1703
+ if (isSingle) {
1704
+ return {
1705
+ content: body,
1706
+ end: footerEnd,
1707
+ hereString: { body, quoted: true }
1708
+ };
1709
+ }
1710
+ const expanded = scanPwshExpandableText(body, nesting);
1711
+ return {
1712
+ content: expanded.content,
1713
+ end: footerEnd,
1714
+ expansion: expanded.expansion,
1715
+ substitutions: expanded.substitutions,
1716
+ hereString: { body: expanded.content, quoted: false }
1717
+ };
1718
+ }
1719
+ lines.push(line);
1720
+ if (lineEnd === -1) {
1721
+ break;
1722
+ }
1723
+ i = lineEnd + 1;
1724
+ }
1725
+ throw inspectionError(`Unterminated PowerShell here-string starting at character ${start + 1}. Close it with ${isSingle ? "'@" : '"@'} at column 0.`);
1726
+ };
1727
+ var scanPwshDoubleQuote = (command, start, nesting) => {
1728
+ let content = "";
1729
+ let expansion = false;
1730
+ const substitutions = [];
1731
+ let i = start + 1;
1732
+ while (i < command.length) {
1733
+ const ch = command[i] ?? "";
1734
+ if (isPwshDoubleQuote(ch)) {
1735
+ const next = command[i + 1] ?? "";
1736
+ if (isPwshDoubleQuote(next)) {
1737
+ content += next;
1738
+ i += 2;
1739
+ continue;
1740
+ }
1741
+ return { content, end: i + 1, expansion, substitutions };
1742
+ }
1743
+ if (ch === "`") {
1744
+ const escaped = decodePwshBacktick(command, i);
1745
+ content += escaped.content;
1746
+ i = escaped.end;
1747
+ } else if (ch === "$" && command[i + 1] === "(") {
1748
+ const sub = consumePwshSubexpression(command, i, nesting);
1749
+ content += command.slice(i, sub.end);
1750
+ substitutions.push(sub.content);
1751
+ expansion = true;
1752
+ i = sub.end;
1753
+ } else if (ch === "$" && command[i + 1] === "{") {
1754
+ const end = scanPwshBracedVar(command, i);
1755
+ content += command.slice(i, end);
1756
+ expansion = true;
1757
+ i = end;
1758
+ } else {
1759
+ expansion ||= isPwshVariableStart(command, i);
1760
+ content += ch;
1761
+ i += 1;
1762
+ }
1763
+ }
1764
+ throw inspectionError(`Unterminated PowerShell double quote starting at character ${start + 1}. Close the quote before running the command.`);
1765
+ };
1766
+ var stepPwshSubexpression = (command, i, atWordStart, nesting) => {
1767
+ const ch = command[i] ?? "";
1768
+ if (ch === "<" && command[i + 1] === "#") {
1769
+ return skipPwshBlockComment(command, i);
1770
+ }
1771
+ if (ch === "#" && atWordStart) {
1772
+ let end = i + 1;
1773
+ while (end < command.length && !isPwshNewline(command[end] ?? "")) {
1774
+ end += 1;
1775
+ }
1776
+ return end;
1777
+ }
1778
+ if (ch === "@" && (isPwshSingleQuote(command[i + 1] ?? "") || isPwshDoubleQuote(command[i + 1] ?? ""))) {
1779
+ return scanPwshHereString(command, i, nesting + 1).end;
1780
+ }
1781
+ if (isPwshSingleQuote(ch)) {
1782
+ return scanPwshSingleQuote(command, i).end;
1783
+ }
1784
+ if (isPwshDoubleQuote(ch)) {
1785
+ return scanPwshDoubleQuote(command, i, nesting + 1).end;
1786
+ }
1787
+ if (ch === "`") {
1788
+ return decodePwshBacktick(command, i).end;
1789
+ }
1790
+ return null;
1791
+ };
1792
+ var consumePwshSubexpression = (command, start, nesting = 0) => {
1793
+ if (nesting > 12) {
1794
+ throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
1795
+ }
1796
+ let depth = 1;
1797
+ let i = start + 2;
1798
+ let atWordStart = true;
1799
+ while (i < command.length) {
1800
+ const stepped = stepPwshSubexpression(command, i, atWordStart, nesting);
1801
+ if (stepped !== null) {
1802
+ i = stepped;
1803
+ atWordStart = false;
1804
+ continue;
1805
+ }
1806
+ const ch = command[i] ?? "";
1807
+ if (ch === "(") {
1808
+ depth += 1;
1809
+ } else if (ch === ")") {
1810
+ depth -= 1;
1811
+ if (depth === 0) {
1812
+ return { content: command.slice(start + 2, i), end: i + 1 };
1813
+ }
1814
+ }
1815
+ atWordStart = isPwshWordSeparator(ch);
1816
+ i += 1;
1817
+ }
1818
+ throw inspectionError(`Unterminated PowerShell subexpression starting at character ${start + 1}. Close it with ).`);
1819
+ };
1820
+ var skipPwshTrivia = (command, start) => {
1821
+ let i = start;
1822
+ while (i < command.length) {
1823
+ const ch = command[i] ?? "";
1824
+ if (isPwshHorizontalSpace(ch)) {
1825
+ i += 1;
1826
+ } else if (ch === "`" && command[i + 1] === "\r" && command[i + 2] === `
1827
+ `) {
1828
+ i += 3;
1829
+ } else if (ch === "`" && isPwshNewline(command[i + 1] ?? "")) {
1830
+ i += 2;
1831
+ } else if (ch === "<" && command[i + 1] === "#") {
1832
+ i = skipPwshBlockComment(command, i);
1833
+ } else if (ch === "#") {
1834
+ i += 1;
1835
+ while (i < command.length && !isPwshNewline(command[i] ?? "")) {
1836
+ i += 1;
1837
+ }
1838
+ } else {
1839
+ break;
1840
+ }
1841
+ }
1842
+ return i;
1843
+ };
1844
+ var findStopParsingEnd = (command, start) => {
1845
+ let inQuote = false;
1846
+ for (let i = start;i < command.length; i += 1) {
1847
+ const ch = command[i] ?? "";
1848
+ if (isPwshNewline(ch)) {
1849
+ return i;
1850
+ }
1851
+ if (isPwshDoubleQuote(ch)) {
1852
+ inQuote = !inQuote;
1853
+ } else if (!inQuote && (ch === "|" || command.slice(i, i + 2) === "&&" || command.slice(i, i + 2) === "||")) {
1854
+ return i;
1855
+ }
1856
+ }
1857
+ return command.length;
1858
+ };
1859
+ var scanPwshStopParsing = (command, start) => {
1860
+ const end = findStopParsingEnd(command, start);
1861
+ let contentStart = start;
1862
+ while (contentStart < end && isPwshHorizontalSpace(command[contentStart] ?? "")) {
1863
+ contentStart += 1;
1864
+ }
1865
+ const raw = command.slice(contentStart, end);
1866
+ if (/%[^%\r\n]+%/u.test(raw)) {
1867
+ throw inspectionError("Cannot inspect PowerShell stop-parsing (--%) with %VAR% expansion. Supply literal arguments.");
1868
+ }
1869
+ if (/["\u201C-\u201E]/u.test(raw)) {
1870
+ throw inspectionError("Cannot inspect quoted arguments after PowerShell stop-parsing (--%). Supply literal arguments without --%.");
1871
+ }
1872
+ for (const ch of raw) {
1873
+ if (ch !== " " && isPwshHorizontalSpace(ch)) {
1874
+ throw inspectionError("Cannot inspect non-space whitespace after PowerShell stop-parsing (--%). Supply literal arguments without --%.");
1875
+ }
1876
+ }
1877
+ const tokens = [];
1878
+ for (const part of raw.split(" ")) {
1879
+ if (part.length > 0) {
1880
+ tokens.push({ type: "word", value: part });
1881
+ }
1882
+ }
1883
+ return { tokens, end };
1884
+ };
1885
+ var scanPwshWordFragment = (command, i, nesting) => {
1886
+ const ch = command[i] ?? "";
1887
+ if (isPwshSingleQuote(ch)) {
1888
+ return scanPwshSingleQuote(command, i);
1889
+ }
1890
+ if (isPwshDoubleQuote(ch)) {
1891
+ return scanPwshDoubleQuote(command, i, nesting);
1892
+ }
1893
+ if ((ch === "$" || ch === "@") && command[i + 1] === "(") {
1894
+ const sub = consumePwshSubexpression(command, i, nesting);
1895
+ return {
1896
+ content: command.slice(i, sub.end),
1897
+ end: sub.end,
1898
+ expansion: true,
1899
+ substitutions: [sub.content]
1900
+ };
1901
+ }
1902
+ if (ch === "$" && command[i + 1] === "{") {
1903
+ const end = scanPwshBracedVar(command, i);
1904
+ return { content: command.slice(i, end), end, expansion: true };
1905
+ }
1906
+ if (ch === "`") {
1907
+ return decodePwshBacktick(command, i);
1908
+ }
1909
+ return null;
1910
+ };
1911
+ var scanPwshWord = (command, start, nesting) => {
1912
+ const first = command[start] ?? "";
1913
+ const second = command[start + 1] ?? "";
1914
+ if (first === "@" && (isPwshSingleQuote(second) || isPwshDoubleQuote(second))) {
1915
+ return scanPwshHereString(command, start, nesting);
1916
+ }
1917
+ if (first === "@" && /^[\p{L}\p{N}_]/u.test(second)) {
1918
+ throw inspectionError("Cannot inspect PowerShell splatting (@var) reliably. Supply literal arguments.");
1919
+ }
1920
+ let content = "";
1921
+ let expansion = false;
1922
+ const substitutions = [];
1923
+ let i = start;
1924
+ while (i < command.length) {
1925
+ const ch = command[i] ?? "";
1926
+ if (isPwshWordSeparator(ch) || ch === ">" || ch === "<" && command[i + 1] === "#") {
1927
+ break;
1928
+ }
1929
+ const fragment = scanPwshWordFragment(command, i, nesting);
1930
+ if (fragment !== null) {
1931
+ content += fragment.content;
1932
+ expansion ||= fragment.expansion === true;
1933
+ substitutions.push(...fragment.substitutions ?? []);
1934
+ i = fragment.end;
1935
+ continue;
1936
+ }
1937
+ expansion ||= isPwshVariableStart(command, i);
1938
+ content += ch;
1939
+ i += 1;
1940
+ }
1941
+ return { content, end: i, expansion, substitutions };
1942
+ };
1943
+ var readPwshPunctuation = (command, i, tokens) => {
1944
+ const pair = command.slice(i, i + 2);
1945
+ if (pair === "&&" || pair === "||") {
1946
+ tokens.push({ type: "operator", value: pair });
1947
+ return i + 2;
1948
+ }
1949
+ const ch = command[i] ?? "";
1950
+ if (isPwshNewline(ch)) {
1951
+ tokens.push({ type: "operator", value: `
1952
+ ` });
1953
+ return i + (ch === "\r" && command[i + 1] === `
1954
+ ` ? 2 : 1);
1955
+ }
1956
+ if (ch === "(") {
1957
+ const sub = consumePwshSubexpression(command, i - 1, 0);
1958
+ tokens.push({
1959
+ type: "word",
1960
+ value: command.slice(i, sub.end),
1961
+ expansion: true,
1962
+ grouped: true,
1963
+ substitutions: [sub.content]
1964
+ });
1965
+ return sub.end;
1966
+ }
1967
+ if (ch === ")") {
1968
+ throw inspectionError(`Unexpected closing parenthesis at character ${i + 1}.`);
1969
+ }
1970
+ if ("|;{}".includes(ch)) {
1971
+ tokens.push({ type: "operator", value: ch });
1972
+ return i + 1;
1973
+ }
1974
+ if (ch === "&") {
1975
+ const atStart = tokens.length === 0 || tokens.at(-1)?.type === "operator";
1976
+ tokens.push({ type: atStart ? "word" : "operator", value: "&" });
1977
+ return i + 1;
1978
+ }
1979
+ return null;
1980
+ };
1981
+ var tokenizePwsh = (command) => {
1982
+ const tokens = [];
1983
+ let i = 0;
1984
+ while ((i = skipPwshTrivia(command, i)) < command.length) {
1985
+ const next = readPwshPunctuation(command, i, tokens);
1986
+ if (next !== null) {
1987
+ i = next;
1988
+ continue;
1989
+ }
1990
+ const ch = command[i] ?? "";
1991
+ const redirect = /^(?:[1-6*])?(?:>>|>&1|>)/u.exec(command.slice(i))?.[0];
1992
+ if (redirect !== undefined) {
1993
+ tokens.push({ type: "redirect", value: redirect });
1994
+ i += redirect.length;
1995
+ continue;
1996
+ }
1997
+ if (command.slice(i, i + 3) === "--%" && (i + 3 >= command.length || isPwshWordSeparator(command[i + 3] ?? ""))) {
1998
+ const stopped = scanPwshStopParsing(command, i + 3);
1999
+ tokens.push(...stopped.tokens);
2000
+ i = stopped.end;
2001
+ continue;
2002
+ }
2003
+ const word = scanPwshWord(command, i, 0);
2004
+ if (word.end <= i) {
2005
+ throw inspectionError(`Unexpected PowerShell token "${ch}" at character ${i + 1}.`);
2006
+ }
2007
+ tokens.push({
2008
+ type: "word",
2009
+ value: word.content,
2010
+ substitutions: word.substitutions,
2011
+ expansion: word.expansion,
2012
+ hereString: word.hereString
2013
+ });
2014
+ i = word.end;
2015
+ }
2016
+ return tokens;
2017
+ };
2018
+ var decodePwshEncodedCommand = (encoded) => {
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)) {
2020
+ throw inspectionError("Cannot decode invalid pwsh -EncodedCommand base64 payload.");
2021
+ }
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);
2027
+ if (bytes.length % 2 !== 0) {
2028
+ throw inspectionError("Cannot decode pwsh -EncodedCommand payload with odd UTF-16LE byte length.");
2029
+ }
2030
+ return bytes.toString("utf16le");
2031
+ };
2032
+ var pwshSwitchTable = [
2033
+ ["version", "boolean", "v"],
2034
+ ["help", "boolean", "h"],
2035
+ ["login", "boolean", "l"],
2036
+ ["noexit", "unsupported", "noe"],
2037
+ ["noprofile", "boolean", "nop"],
2038
+ ["nologo", "boolean", "nol"],
2039
+ ["noninteractive", "boolean", "noni"],
2040
+ ["sshservermode", "boolean", "sshs"],
2041
+ ["noprofileloadtime", "boolean", "noprofileloadtime"],
2042
+ ["interactive", "boolean", "i"],
2043
+ ["configurationfile", "value", "configurationfile"],
2044
+ ["configurationname", "value", "config"],
2045
+ ["custompipename", "value", "cus"],
2046
+ ["commandwithargs", "commandWithArgs", "commandwithargs"],
2047
+ ["command", "command", "c"],
2048
+ ["windowstyle", "value", "w"],
2049
+ ["file", "unsupported", "f"],
2050
+ ["outputformat", "value", "o"],
2051
+ ["inputformat", "value", "inp"],
2052
+ ["executionpolicy", "value", "ex"],
2053
+ ["encodedcommand", "encodedCommand", "e"],
2054
+ ["encodedarguments", "unsupported", "encodeda"],
2055
+ ["settingsfile", "value", "settings"],
2056
+ ["sta", "boolean", "sta"],
2057
+ ["mta", "boolean", "mta"],
2058
+ ["workingdirectory", "workingDirectory", "wo"]
2059
+ ];
2060
+ var pwshSwitchAliases = new Map([
2061
+ ["?", "boolean"],
2062
+ ["ec", "encodedCommand"],
2063
+ ["cwa", "commandWithArgs"],
2064
+ ["wd", "workingDirectory"],
2065
+ ["ea", "unsupported"],
2066
+ ["if", "value"],
2067
+ ["of", "value"],
2068
+ ["ep", "value"]
2069
+ ]);
2070
+ var classifyPwshSwitch = (raw) => {
2071
+ const normalized = raw.replace(/^[/\-\u2013-\u2015]+/u, "").toLowerCase();
2072
+ if (normalized.length === 0) {
2073
+ return null;
2074
+ }
2075
+ const alias = pwshSwitchAliases.get(normalized);
2076
+ if (alias !== undefined) {
2077
+ return alias;
2078
+ }
2079
+ const matched = pwshSwitchTable.find(([full, , minPrefix]) => full.startsWith(normalized) && normalized.length >= minPrefix.length);
2080
+ return matched?.[1] ?? null;
2081
+ };
2082
+ var isPwshSwitchToken = (raw) => raw.length > 1 && /^[/\-\u2013-\u2015]/u.test(raw);
2083
+ var readPwshCommandArgs = (words, index, kind) => {
2084
+ const target = words[index];
2085
+ if (target === undefined || target.expansion === true) {
2086
+ throw inspectionError("Cannot parse an expanded or missing pwsh command body reliably. Use a literal command.");
2087
+ }
2088
+ if (kind === "encodedCommand") {
2089
+ return decodePwshEncodedCommand(target.value);
2090
+ }
2091
+ if (target.value === "-") {
2092
+ throw inspectionError("Cannot inspect pwsh reading commands from standard input (-). Supply a literal command.");
2093
+ }
2094
+ if (kind === "commandWithArgs") {
2095
+ return target.value;
2096
+ }
2097
+ const remaining = words.slice(index);
2098
+ if (remaining.some((word) => word.expansion === true)) {
2099
+ throw inspectionError("Cannot parse an expanded pwsh -Command body reliably. Use a literal command.");
2100
+ }
2101
+ return remaining.map((word) => word.value).join(" ");
2102
+ };
2103
+ var extractPwshBody = (words, start) => {
2104
+ if (!/^(?:.*[/\\])?pwsh(?:\.exe)?$/iu.test(words[start]?.value ?? "")) {
2105
+ return null;
2106
+ }
2107
+ let index = start + 1;
2108
+ let workingDirectoryChanged = false;
2109
+ let encodedBody;
2110
+ let infoFlag = false;
2111
+ while (index < words.length) {
2112
+ const token = words[index];
2113
+ if (token === undefined) {
2114
+ break;
2115
+ }
2116
+ if (token.expansion === true) {
2117
+ throw inspectionError("Cannot inspect dynamic pwsh arguments reliably. Use literal arguments.");
2118
+ }
2119
+ if (!isPwshSwitchToken(token.value)) {
2120
+ throw inspectionError("Cannot inspect positional pwsh script files reliably. Pass a literal -Command or run git commit directly.");
2121
+ }
2122
+ const kind = classifyPwshSwitch(token.value);
2123
+ if (kind === null || kind === "unsupported") {
2124
+ throw inspectionError(`Cannot inspect unsupported pwsh switch "${token.value}" reliably. Use literal -Command or run git commit directly.`);
2125
+ }
2126
+ const normalized = token.value.replace(/^[/\-\u2013-\u2015]+/u, "").toLowerCase();
2127
+ if (kind === "boolean") {
2128
+ infoFlag ||= normalized === "?" || "help".startsWith(normalized) || "version".startsWith(normalized);
2129
+ index += 1;
2130
+ } else if (kind === "value" || kind === "workingDirectory") {
2131
+ workingDirectoryChanged ||= kind === "workingDirectory";
2132
+ index += 2;
2133
+ } else if (kind === "encodedCommand") {
2134
+ encodedBody = readPwshCommandArgs(words, index + 1, kind);
2135
+ index += 2;
2136
+ } else {
2137
+ return {
2138
+ body: readPwshCommandArgs(words, index + 1, kind),
2139
+ workingDirectoryChanged
2140
+ };
2141
+ }
2142
+ }
2143
+ if (encodedBody !== undefined) {
2144
+ return { body: encodedBody, workingDirectoryChanged };
2145
+ }
2146
+ if (infoFlag) {
2147
+ return null;
2148
+ }
2149
+ throw inspectionError("Cannot inspect bare pwsh invocation without -Command or -EncodedCommand. Supply a literal command.");
2150
+ };
2151
+ var splitPipelines = (tokens, mode) => {
2152
+ const result = [];
2153
+ let stages = [];
2154
+ let current = [];
2155
+ const flush = () => {
2156
+ if (current.length > 0) {
2157
+ stages.push(current);
2158
+ current = [];
2159
+ }
2160
+ if (stages.length === 0) {
2161
+ return;
2162
+ }
2163
+ const isPipeline = stages.length > 1;
2164
+ const [firstStage] = stages;
2165
+ const pipedHereString = mode === "pwsh" && stages.length === 2 && firstStage?.length === 1 && firstStage[0]?.type === "word" && firstStage[0].hereString?.quoted === true ? firstStage[0].hereString.body : undefined;
2166
+ for (let stageIndex = 0;stageIndex < stages.length; stageIndex += 1) {
2167
+ const stageTokens = stages[stageIndex];
2168
+ if (stageTokens !== undefined) {
2169
+ result.push({
2170
+ tokens: stageTokens,
2171
+ pipeline: isPipeline,
2172
+ pipedHereString: stageIndex === 1 ? pipedHereString : undefined
2173
+ });
2174
+ }
2175
+ }
2176
+ stages = [];
2177
+ };
2178
+ for (const token of tokens) {
2179
+ if (token.type === "operator") {
2180
+ if (token.value === "|" || token.value === "|&") {
2181
+ if (current.length > 0) {
2182
+ stages.push(current);
2183
+ current = [];
2184
+ }
2185
+ } else if (token.value !== `
2186
+ ` || current.length > 0 || stages.length === 0) {
2187
+ flush();
2188
+ }
2189
+ } else {
2190
+ current.push(token);
2191
+ }
2192
+ }
2193
+ flush();
2194
+ return result;
2195
+ };
2196
+ var attachPwshStdin = (invocation, stage) => {
2197
+ if (!invocation.filePaths.includes("-")) {
2198
+ return invocation;
2199
+ }
2200
+ if (stage.pipedHereString !== undefined) {
2201
+ return {
2202
+ ...invocation,
2203
+ stdinMessage: stage.pipedHereString
2204
+ };
2205
+ }
2206
+ return {
2207
+ ...invocation,
2208
+ stdinError: "In PowerShell, pipe a single literal here-string (@'...'@ | git commit -F -) or pass -m directly."
2209
+ };
2210
+ };
2211
+ var resolveCommandStart = (words, values, mode) => {
2212
+ if (mode === "posix") {
2213
+ return findCommandStart(values);
2214
+ }
2215
+ if (words[0]?.value === "&") {
2216
+ if (words[1] === undefined || words[1].expansion === true) {
2217
+ throw inspectionError("Cannot inspect a dynamic PowerShell call operator (& $cmd). Use literal command words.");
2218
+ }
2219
+ return 1;
2220
+ }
2221
+ return 0;
2222
+ };
2223
+ var isTargetMutatorCommand = (values, start, mode) => {
2224
+ const commandName = values[start] ?? "";
2225
+ if (mode === "pwsh") {
2226
+ return pwshTargetMutators.has(commandName.toLowerCase()) || /^\$\{?env:/iu.test(values[0] ?? "");
2227
+ }
2228
+ return targetMutators.has(commandName) || values.length > 0 && values.every(isAssignment);
2229
+ };
2230
+ var assertLiteralCommandName = (firstWord, mode) => {
2231
+ if (firstWord?.expansion !== true) {
2232
+ return;
2233
+ }
2234
+ if (mode === "pwsh" && (firstWord.hereString !== undefined || firstWord.grouped === true || /^\$\{?env:/iu.test(firstWord.value))) {
2235
+ return;
2236
+ }
2237
+ throw inspectionError("Cannot inspect a dynamic command name. Use literal command words.");
2238
+ };
2239
+ var collectStageSubstitutions = (tokens, mode, changedDirectory, depth, invocations) => {
2240
+ let mutated = changedDirectory;
2241
+ for (const token of tokens) {
2242
+ for (const substitution of token.substitutions ?? []) {
2243
+ const subResult = extractGitCommitsInternal(substitution, mode, mutated, depth + 1);
2244
+ invocations.push(...subResult.invocations);
2245
+ if (mode === "pwsh" && subResult.changedDirectory) {
2246
+ mutated = true;
2247
+ }
2248
+ }
2249
+ }
2250
+ return mutated;
2251
+ };
2252
+ var extractGitCommitsInternal = (command, mode, inheritedDirectoryChange, depth) => {
1475
2253
  if (depth > 12 || command.length > 262144) {
1476
2254
  throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
1477
2255
  }
1478
- const tokens = tokenizeShell(command);
2256
+ const tokens = mode === "pwsh" ? tokenizePwsh(command) : tokenizeShell(command);
1479
2257
  const invocations = [];
1480
2258
  let changedDirectory = inheritedDirectoryChange;
1481
- for (const simple of splitSimpleCommands(tokens)) {
1482
- const words = extractCommandWords(simple.tokens);
2259
+ for (const stage of splitPipelines(tokens, mode)) {
2260
+ changedDirectory = collectStageSubstitutions(stage.tokens, mode, changedDirectory, depth, invocations);
2261
+ const words = extractCommandWords(stage.tokens);
1483
2262
  const values = words.map((token) => token.value);
1484
- const start = findCommandStart(values);
1485
- if (words[start]?.expansion === true) {
1486
- throw inspectionError("Cannot inspect a dynamic command name. Use literal command words.");
1487
- }
1488
- const invocation = extractInvocation(words, start);
1489
- const body = extractShellCBody(words, start);
1490
- if (body !== undefined) {
1491
- const wrapperChange = values.slice(0, start).some((word) => word === "env" || isAssignment(word));
1492
- invocations.push(...extractGitCommits(body, changedDirectory || wrapperChange, depth + 1));
1493
- }
1494
- if (targetMutators.has(values[start] ?? "") || values.length > 0 && values.every(isAssignment)) {
2263
+ const start = resolveCommandStart(words, values, mode);
2264
+ assertLiteralCommandName(words[start], mode);
2265
+ const invocation = extractInvocation(words, start, mode);
2266
+ const posixBody = extractShellCBody(words, start);
2267
+ const pwshBody = extractPwshBody(words, start);
2268
+ const wrapperChange = mode === "posix" && values.slice(0, start).some((word) => word === "env" || isAssignment(word));
2269
+ if (posixBody !== null) {
2270
+ invocations.push(...extractGitCommitsInternal(posixBody, "posix", changedDirectory || wrapperChange, depth + 1).invocations);
2271
+ }
2272
+ if (pwshBody !== null) {
2273
+ invocations.push(...extractGitCommitsInternal(pwshBody.body, "pwsh", changedDirectory || wrapperChange || pwshBody.workingDirectoryChanged, depth + 1).invocations);
2274
+ }
2275
+ if (isTargetMutatorCommand(values, start, mode)) {
1495
2276
  changedDirectory = true;
1496
2277
  }
1497
- if (invocation !== undefined) {
2278
+ if (invocation !== null) {
1498
2279
  const target = changedDirectory ? {
1499
2280
  ...invocation,
1500
2281
  targetError: "A preceding directory or environment change makes the commit target ambiguous. Run git commit in a separate shell call with the captured workdir."
1501
2282
  } : invocation;
1502
- invocations.push(attachStdinHeredoc(target, simple.tokens, simple.pipeline));
1503
- }
1504
- }
1505
- for (const token of tokens) {
1506
- for (const substitution of token.substitutions ?? []) {
1507
- invocations.push(...extractGitCommits(substitution, changedDirectory, depth + 1));
2283
+ invocations.push(mode === "pwsh" ? attachPwshStdin(target, stage) : attachStdinHeredoc(target, stage.tokens, stage.pipeline));
1508
2284
  }
1509
2285
  }
1510
- return invocations;
2286
+ return { invocations, changedDirectory };
1511
2287
  };
2288
+ var extractGitCommits = (command, options) => extractGitCommitsInternal(command, options?.shell ?? "posix", false, 0).invocations;
1512
2289
 
1513
2290
  // src/validator.ts
1514
2291
  var signoffPattern = /^\s*[sS][iI][gG][nN][eE][dD]-[oO][fF][fF]-[bB][yY]:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/u;
@@ -1517,7 +2294,7 @@ var subjectScopeViolation = (subject, effective) => {
1517
2294
  return 'Subject line is empty. The commit message must begin with "<scope>: <subject>".';
1518
2295
  }
1519
2296
  if (scopePattern.test(effective)) {
1520
- return;
2297
+ return null;
1521
2298
  }
1522
2299
  if (/^:\s*/u.test(effective)) {
1523
2300
  return `Missing scope before colon in subject line "${subject}". Expected format: "<scope>: <subject>".`;
@@ -1530,58 +2307,60 @@ var subjectScopeViolation = (subject, effective) => {
1530
2307
  }
1531
2308
  return `Missing scope in subject line "${subject}". First line must follow "<scope>: <subject>" format.`;
1532
2309
  };
1533
- var resolveMessages = (invocation, violations) => {
2310
+ var resolveMessages = (invocation, violations, shellMode) => {
1534
2311
  if (invocation.messageExpansion === true) {
1535
2312
  violations.push("Cannot validate a message containing shell expansion. Supply the final message literally.");
1536
- return;
2313
+ return null;
1537
2314
  }
1538
2315
  if (invocation.hasTrailer === true) {
1539
2316
  violations.push("Cannot validate --trailer. Put the trailer in the literal message body or use -s.");
1540
- return;
2317
+ return null;
1541
2318
  }
1542
2319
  const filePath = invocation.filePaths.at(-1);
1543
2320
  if (filePath === undefined) {
1544
2321
  return invocation.messages;
1545
2322
  }
2323
+ const inlineHint = shellMode === "pwsh" ? "Use an inline single-quoted -m message or a single literal here-string pipeline (@'...'@ | git commit -F -)." : "Use an inline $'...' message or one quoted stdin heredoc.";
1546
2324
  if (filePath !== "-" || invocation.filePaths.length !== 1) {
1547
- violations.push("Cannot validate a commit message from -F/--file before permission approval. Use an inline $'...' message or one quoted stdin heredoc.");
1548
- return;
2325
+ violations.push(`Cannot validate a commit message from -F/--file before permission approval. ${inlineHint}`);
2326
+ return null;
1549
2327
  }
1550
2328
  if (invocation.stdinError !== undefined || invocation.stdinMessage === undefined || invocation.messages.length > 0) {
1551
- violations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} Use one quoted stdin heredoc or an inline $'...' message.`);
1552
- return;
2329
+ violations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} ${inlineHint}`);
2330
+ return null;
1553
2331
  }
1554
2332
  return [invocation.stdinMessage];
1555
2333
  };
1556
2334
  var checkAllowedScope = (subject, effective, allowed) => {
1557
2335
  const rawScope = scopePattern.exec(effective)?.[1];
1558
2336
  if (rawScope === undefined || allowed.length === 0) {
1559
- return;
2337
+ return null;
1560
2338
  }
1561
2339
  const conventional = /^(?<type>[^(]+)\((?<scope>[^)]+)\)$/u.exec(rawScope);
1562
2340
  if ([rawScope, conventional?.[1], conventional?.[2]].some((scope) => scope !== undefined && allowed.includes(scope))) {
1563
- return;
2341
+ return null;
1564
2342
  }
1565
2343
  const detail = effective === subject ? "" : ` Subject line: "${subject}".`;
1566
2344
  return `Scope "${rawScope}" is not in the allowed scopes list. Allowed scopes: ${allowed.join(", ")}.${detail}`;
1567
2345
  };
1568
- var checkLineLength = (lines, max) => {
2346
+ var checkLineLength = (lines, max, shellMode) => {
1569
2347
  if (max <= 0) {
1570
- return;
2348
+ return null;
1571
2349
  }
1572
2350
  const overlong = lines.flatMap((line, index) => line.length > max ? [` - Line ${index + 1} (${line.length} chars, max ${max}): "${line}"`] : []);
1573
- return overlong.length === 0 ? undefined : `Commit message exceeds maximum line length of ${max} characters:
2351
+ const wrapHint = shellMode === "pwsh" ? "Wrap with real newlines inside a literal @'...'@ here-string or PowerShell `n escapes inside double quotes." : `Wrap with real newlines inside $'...'; "\\n" inside double quotes stays literal.`;
2352
+ return overlong.length === 0 ? null : `Commit message exceeds maximum line length of ${max} characters:
1574
2353
  ${overlong.join(`
1575
2354
  `)}
1576
- Each -m becomes one paragraph line. Wrap with real newlines inside $'...'; "\\n" inside double quotes stays literal.`;
2355
+ Each -m becomes one paragraph line. ${wrapHint}`;
1577
2356
  };
1578
- var validateInvocation = (invocation, config) => {
2357
+ var validateInvocation = (invocation, config, shellMode) => {
1579
2358
  const violations = [];
1580
2359
  if (invocation.isHelp) {
1581
2360
  return violations;
1582
2361
  }
1583
- const messages = resolveMessages(invocation, violations);
1584
- if (messages === undefined) {
2362
+ const messages = resolveMessages(invocation, violations, shellMode);
2363
+ if (messages === null) {
1585
2364
  return violations;
1586
2365
  }
1587
2366
  if (messages.length === 0) {
@@ -1597,10 +2376,10 @@ var validateInvocation = (invocation, config) => {
1597
2376
  const effective = subject.replace(/^(?:(?:fixup|squash)!\s+)+/u, "");
1598
2377
  const checks = [
1599
2378
  checkAllowedScope(subject, effective, config.allowedScopes ?? []),
1600
- config.requireScope ? subjectScopeViolation(subject, effective) : undefined,
1601
- checkLineLength(lines, config.maxLineLength)
2379
+ config.requireScope ? subjectScopeViolation(subject, effective) : null,
2380
+ checkLineLength(lines, config.maxLineLength, shellMode)
1602
2381
  ];
1603
- violations.push(...checks.filter((violation) => violation !== undefined));
2382
+ violations.push(...checks.filter((violation) => violation !== null));
1604
2383
  const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
1605
2384
  const hasTrailer = subjectIndex !== -1 && lines.slice(subjectIndex + 1).some((line) => signoffPattern.test(line));
1606
2385
  if (config.enforceSignoff && !invocation.hasSignoffFlag && !hasTrailer) {
@@ -1608,8 +2387,8 @@ var validateInvocation = (invocation, config) => {
1608
2387
  }
1609
2388
  return violations;
1610
2389
  };
1611
- var validateGitCommits = (invocations, config, _originalCommand) => {
1612
- const violations = invocations.flatMap((invocation) => validateInvocation(invocation, config));
2390
+ var validateGitCommits = (invocations, config, _originalCommand, shellMode = "posix") => {
2391
+ const violations = invocations.flatMap((invocation) => validateInvocation(invocation, config, shellMode));
1613
2392
  if (violations.length === 0) {
1614
2393
  return;
1615
2394
  }
@@ -1618,6 +2397,13 @@ var validateGitCommits = (invocations, config, _originalCommand) => {
1618
2397
  `);
1619
2398
  const scope = config.allowedScopes?.[0] ?? "scope";
1620
2399
  const policy = config.enforceSignoff ? "required: captured commit.gpgsign=true. Keep -s." : "not required: captured commit.gpgsign=false|unset.";
2400
+ const signoff = config.enforceSignoff ? " -s" : "";
2401
+ const example = shellMode === "pwsh" ? ` @'
2402
+ ${scope}: Subject
2403
+
2404
+ Body line one.
2405
+ Body line two.
2406
+ '@ | git commit${signoff} -F -` : ` git commit${signoff} -m $'${scope}: Subject\\n\\nBody line one.\\nBody line two.'`;
1621
2407
  throw new Error(`[commit-guard] Git commit rejected: commit message format rules violated.
1622
2408
 
1623
2409
  Violations:
@@ -1625,20 +2411,47 @@ ${details}
1625
2411
 
1626
2412
  Signoff ${policy}
1627
2413
  Example:
1628
- git commit${config.enforceSignoff ? " -s" : ""} -m $'${scope}: Subject\\n\\nBody line one.\\nBody line two.'`);
2414
+ ${example}`);
1629
2415
  };
1630
2416
 
1631
2417
  // src/plugin.ts
1632
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
+ });
1633
2446
  var publicationGuidance = 'Commit after the shell result reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing.';
1634
2447
  var receiptGuidance = "RECEIPT_OK confirms only that the artifact was written, not that the baseline was published.";
1635
2448
  var toToolError = (cause) => {
1636
- if (Cause.isUnknownError(cause)) {
1637
- return toToolError(cause.cause);
2449
+ let current = cause;
2450
+ while (Cause.isUnknownError(current)) {
2451
+ current = current.cause;
1638
2452
  }
1639
- return cause instanceof Tool.Error ? cause : new Tool.Error({
1640
- message: cause instanceof Error ? cause.message : "[commit-guard] Git commit validation failed.",
1641
- error: cause
2453
+ return current instanceof Tool.Error ? current : new Tool.Error({
2454
+ message: current instanceof Error ? current.message : "[commit-guard] Git commit validation failed."
1642
2455
  });
1643
2456
  };
1644
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.`;
@@ -1648,7 +2461,7 @@ var baselineGuidance = (baseline, config) => {
1648
2461
  }
1649
2462
  const observed = [
1650
2463
  ...new Set(baseline.messages.map((message) => scopePattern.exec(message.split(`
1651
- `)[0])?.[1]).filter((scope) => scope !== undefined && scope.length <= 40))
2464
+ `)[0] ?? "")?.[1]).filter((scope) => scope !== undefined && scope.length <= 40))
1652
2465
  ].slice(0, 3);
1653
2466
  const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
1654
2467
  ` : "";
@@ -1664,11 +2477,31 @@ Set refresh:true after a branch switch, changed signing settings, or changed com
1664
2477
  };
1665
2478
  var captureInstructions = (attempt, status) => `${status}Run this shell command immediately, unchanged, in the foreground with workdir ${attempt.workdir} (do not run it in the background). ` + `Do not wrap it or chain another command onto it. ${publicationGuidance} ${receiptGuidance}
1666
2479
  ${attempt.command}`;
1667
- var sweep = (state) => Effect2.gen(function* sweepPending() {
2480
+ var rememberExpired = (state, command) => {
2481
+ const trimmed = command.trim();
2482
+ state.recentExpired.delete(trimmed);
2483
+ state.recentExpired.add(trimmed);
2484
+ if (state.recentExpired.size > 64) {
2485
+ const oldest = state.recentExpired.values().next().value;
2486
+ if (oldest !== undefined) {
2487
+ state.recentExpired.delete(oldest);
2488
+ }
2489
+ }
2490
+ };
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) {
2496
+ const now = yield* state.clock.currentTimeMillis;
1668
2497
  for (const attempt of [...state.pending.values()].slice(0, 32)) {
2498
+ if (state.pending.get(attempt.scope) !== attempt) {
2499
+ continue;
2500
+ }
1669
2501
  state.pending.delete(attempt.scope);
1670
- if (attempt.claimed === undefined && Date.now() >= attempt.expires) {
1671
- cleanup(attempt);
2502
+ if (attempt.claimed === undefined && now >= attempt.expires) {
2503
+ rememberExpired(state, attempt.command);
2504
+ yield* releasePending(attempt);
1672
2505
  yield* recordState(state.ctx, attempt, "expired");
1673
2506
  yield* invalidateOwned(state.ctx, attempt);
1674
2507
  } else {
@@ -1680,37 +2513,56 @@ var resolveCanonicalWorkdir = (sessionDirectory, workdir) => {
1680
2513
  try {
1681
2514
  return realpathSync2(isJSONString(workdir) ? resolve2(sessionDirectory, workdir) : sessionDirectory);
1682
2515
  } catch {
1683
- 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
+ });
1684
2520
  }
1685
2521
  };
1686
2522
  var validateFields = (input, fields, booleans) => {
1687
2523
  if (!isRecord(input)) {
1688
- 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
+ });
1689
2528
  }
1690
2529
  for (const field of fields) {
1691
2530
  if (input[field] !== undefined && !isJSONString(input[field])) {
1692
- 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
+ });
1693
2535
  }
1694
2536
  }
1695
2537
  for (const field of booleans) {
1696
2538
  if (input[field] !== undefined && !isJSONBoolean(input[field])) {
1697
- 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
+ });
1698
2543
  }
1699
2544
  }
1700
2545
  return input;
1701
2546
  };
1702
- var prepareCapture = (state, toolContext, request, workdir, scope) => Effect2.gen(function* prepare() {
2547
+ var prepareCapture = Effect2.fnUntraced(function* prepare(state, toolContext, request, workdir, scope) {
1703
2548
  const { ctx, pending, config } = state;
2549
+ const now = yield* state.clock.currentTimeMillis;
1704
2550
  const previous = pending.get(scope);
1705
2551
  if (previous !== undefined) {
1706
- if (request.refresh !== true) {
2552
+ if (request.refresh !== true && previous.claimed !== undefined) {
1707
2553
  return {
1708
- content: previous.claimed === undefined ? captureInstructions(previous, "Capture still pending and unclaimed. ") : `Capture claimed; permission approval or execution is pending. Wait for its foreground shell result. ${publicationGuidance} ${receiptGuidance}`
2554
+ content: `Capture claimed; permission approval or execution is pending. Wait for its foreground shell result. ${publicationGuidance} ${receiptGuidance}`
2555
+ };
2556
+ }
2557
+ if (request.refresh !== true && previous.workdir === workdir) {
2558
+ previous.expires = now + captureTimeout;
2559
+ return {
2560
+ content: captureInstructions(previous, "Capture still pending and unclaimed. ")
1709
2561
  };
1710
2562
  }
1711
2563
  pending.delete(scope);
1712
- cleanup(previous);
1713
- yield* recordState(ctx, previous, "failed", "capture replaced by refresh");
2564
+ yield* releasePending(previous);
2565
+ yield* recordState(ctx, previous, "failed", request.refresh === true ? "capture replaced by refresh" : "capture replaced by workdir change");
1714
2566
  yield* invalidateOwned(ctx, previous);
1715
2567
  }
1716
2568
  if (request.refresh !== true) {
@@ -1719,14 +2571,41 @@ var prepareCapture = (state, toolContext, request, workdir, scope) => Effect2.ge
1719
2571
  return { content: baselineGuidance(baseline, config) };
1720
2572
  }
1721
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
+ }
1722
2580
  const count = yield* invalidate(ctx, scope);
1723
- const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, workdir));
1724
- pending.set(scope, attempt);
1725
- const status = state.failures.get(scope) ?? (yield* captureStatus(ctx, scope));
1726
- yield* recordState(ctx, attempt, "prepared");
1727
- 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
+ }));
1728
2607
  });
1729
- var runCommitContext = (state, input, toolContext) => Effect2.gen(function* context() {
2608
+ var runCommitContext = Effect2.fnUntraced(function* context(state, input, toolContext) {
1730
2609
  yield* sweep(state);
1731
2610
  const { ctx } = state;
1732
2611
  if (ctx.location.workspaceID !== undefined) {
@@ -1734,7 +2613,13 @@ var runCommitContext = (state, input, toolContext) => Effect2.gen(function* cont
1734
2613
  content: "Commit context capture is unavailable for remote workspaces."
1735
2614
  };
1736
2615
  }
1737
- 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
+ });
1738
2623
  const session = yield* ctx.session.get({
1739
2624
  sessionID: toolContext.sessionID
1740
2625
  });
@@ -1770,57 +2655,153 @@ var runCommitContext = (state, input, toolContext) => Effect2.gen(function* cont
1770
2655
  return yield* prepareCapture(state, toolContext, request, workdir, scope).pipe(Effect2.ensuring(Effect2.sync(() => {
1771
2656
  state.preparing.delete(scope);
1772
2657
  })));
1773
- }).pipe(Effect2.mapError(toToolError));
1774
- var claimCapture = (state, event, input, attempt) => Effect2.gen(function* claim() {
2658
+ }, Effect2.mapError(toToolError));
2659
+ var claimMismatchReason = (event, input, attempt, sessionDirectory) => {
2660
+ if (event.tool !== "shell") {
2661
+ return `tool "${event.tool}" is not "shell"`;
2662
+ }
2663
+ if (event.sessionID !== attempt.sessionID || event.agent !== attempt.agent) {
2664
+ return "session or agent does not match the original commit_context call";
2665
+ }
2666
+ if (input.background === true) {
2667
+ return "background: true is not allowed; run the capture in the foreground";
2668
+ }
2669
+ if (attempt.claimed !== undefined) {
2670
+ return "capture was already claimed";
2671
+ }
2672
+ let resolvedWorkdir;
2673
+ try {
2674
+ resolvedWorkdir = resolveCanonicalWorkdir(sessionDirectory, input.workdir);
2675
+ } catch {
2676
+ return `shell workdir is inaccessible; expected ${attempt.workdir}`;
2677
+ }
2678
+ if (resolvedWorkdir !== attempt.workdir) {
2679
+ return `resolved workdir ${resolvedWorkdir} does not match expected workdir ${attempt.workdir}`;
2680
+ }
2681
+ return null;
2682
+ };
2683
+ var claimCapture = Effect2.fnUntraced(function* claim(state, event, input, attempt) {
2684
+ const now = yield* state.clock.currentTimeMillis;
2685
+ if (attempt.claimed === undefined && now >= attempt.expires) {
2686
+ state.pending.delete(attempt.scope);
2687
+ rememberExpired(state, attempt.command);
2688
+ yield* releasePending(attempt);
2689
+ yield* recordState(state.ctx, attempt, "expired");
2690
+ yield* invalidateOwned(state.ctx, attempt);
2691
+ yield* Effect2.fail(expiredCaptureError());
2692
+ return;
2693
+ }
1775
2694
  const session = yield* state.ctx.session.get({
1776
2695
  sessionID: event.sessionID
1777
2696
  });
1778
- yield* Effect2.try(() => {
1779
- let matchesWorkdir = false;
1780
- try {
1781
- matchesWorkdir = resolveCanonicalWorkdir(session.location.directory ?? state.ctx.location.directory, input.workdir) === attempt.workdir;
1782
- } catch {}
1783
- if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || !matchesWorkdir || input.background === true || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
1784
- throw new Error("[commit-guard] Capture must use its exact foreground shell command in the original session and workdir. Call commit_context to refresh.");
1785
- }
1786
- attempt.claimed = { messageID: event.messageID, id: event.id };
1787
- });
2697
+ const sessionDirectory = session.location.directory ?? state.ctx.location.directory;
2698
+ const nowAfterSession = yield* state.clock.currentTimeMillis;
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
+ }));
2704
+ return;
2705
+ }
2706
+ if (attempt.claimed === undefined && nowAfterSession >= attempt.expires) {
2707
+ state.pending.delete(attempt.scope);
2708
+ rememberExpired(state, attempt.command);
2709
+ yield* releasePending(attempt);
2710
+ yield* recordState(state.ctx, attempt, "expired");
2711
+ yield* invalidateOwned(state.ctx, attempt);
2712
+ yield* Effect2.fail(expiredCaptureError());
2713
+ return;
2714
+ }
2715
+ const reason = claimMismatchReason(event, input, attempt, sessionDirectory);
2716
+ if (reason !== null) {
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
+ }));
2721
+ return;
2722
+ }
2723
+ attempt.claimed = { messageID: event.messageID, id: event.id };
1788
2724
  yield* recordState(state.ctx, attempt, "claimed");
1789
2725
  });
1790
- var verifyBaselineAndValidate = (state, event, input, command, invocations) => Effect2.gen(function* validate() {
2726
+ var verifyBaselineAndValidate = Effect2.fnUntraced(function* validate(state, event, input, command, shellMode, invocations) {
1791
2727
  const { ctx, config } = state;
1792
2728
  if (ctx.location.workspaceID !== undefined) {
1793
- 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
+ }));
1794
2733
  }
1795
2734
  const session = yield* ctx.session.get({ sessionID: event.sessionID });
1796
2735
  if (session.location.workspaceID !== ctx.location.workspaceID || invocations.some((invocation) => invocation.targetError !== undefined)) {
1797
- 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
+ }));
1798
2740
  }
1799
2741
  const sessionDirectory = session.location.directory ?? ctx.location.directory;
1800
- 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
+ });
1801
2749
  const root = findGitRoot(workdir);
1802
2750
  const baseline = yield* load(ctx, scopeFor(ctx, event.sessionID, config, workdir));
1803
2751
  if (baseline === undefined || root === undefined || baseline.directory !== root) {
1804
2752
  const expected = root ?? workdir;
1805
2753
  const hint = JSON.stringify(relative2(sessionDirectory, expected) || ".");
1806
- 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
+ }));
1807
2758
  }
1808
2759
  if (baseline.gpgsign === "error" || baseline.signingkey === "error") {
1809
- 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
+ }));
1810
2764
  }
1811
- yield* Effect2.try(() => {
1812
- validateGitCommits(invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, command);
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
+ })
1813
2773
  });
1814
2774
  return yield* Effect2.void;
1815
2775
  });
1816
- var handleBeforeExecute = (state, event) => Effect2.gen(function* before() {
2776
+ var isPwshTool = Effect2.fnUntraced(function* detectPwsh(state, event) {
2777
+ const description = event.info?.description;
2778
+ if (isJSONString(description)) {
2779
+ return /using pwsh\./iu.test(description);
2780
+ }
2781
+ const tools = yield* state.ctx.tool.list().pipe(Effect2.orElseSucceed(() => []));
2782
+ const shellTool = tools.find((item) => item.id === event.tool) ?? tools.find((item) => item.id === "shell");
2783
+ if (shellTool !== undefined && isJSONString(shellTool.description)) {
2784
+ return /using pwsh\./iu.test(shellTool.description);
2785
+ }
2786
+ return process.platform === "win32";
2787
+ });
2788
+ var handleBeforeExecute = Effect2.fnUntraced(function* before(state, event) {
1817
2789
  yield* sweep(state);
1818
2790
  if (event.tool !== "shell" && event.tool !== "bash") {
1819
2791
  return;
1820
2792
  }
1821
- 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
+ });
1822
2800
  if (!isJSONString(input.command)) {
1823
- 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
+ }));
1824
2805
  return;
1825
2806
  }
1826
2807
  const { command } = input;
@@ -1829,13 +2810,38 @@ var handleBeforeExecute = (state, event) => Effect2.gen(function* before() {
1829
2810
  yield* claimCapture(state, event, input, attempt);
1830
2811
  return;
1831
2812
  }
1832
- const invocations = yield* Effect2.try(() => extractGitCommits(command));
2813
+ const trimmed = command.trim();
2814
+ const modified = [...state.pending.values()].find((item) => {
2815
+ const encoded = /-EncodedCommand (?<payload>[A-Za-z0-9+/=]+)$/u.exec(item.command)?.groups?.payload;
2816
+ return item.command.trim() === trimmed || command.includes(item.command) || command.includes(item.artifactPath) || encoded !== undefined && command.includes(encoded);
2817
+ });
2818
+ if (modified !== undefined) {
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
+ }));
2823
+ return;
2824
+ }
2825
+ if (state.recentExpired.has(trimmed) || [...state.recentExpired].some((expired) => command.includes(expired))) {
2826
+ yield* Effect2.fail(expiredCaptureError());
2827
+ return;
2828
+ }
2829
+ const shellMode = (yield* isPwshTool(state, event)) ? "pwsh" : "posix";
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
+ });
1833
2837
  if (invocations.length > 0 && !invocations.every((invocation) => invocation.isHelp)) {
1834
- yield* verifyBaselineAndValidate(state, event, input, command, invocations);
2838
+ yield* verifyBaselineAndValidate(state, event, input, command, shellMode, invocations);
1835
2839
  }
1836
- }).pipe(Effect2.mapError(toToolError));
1837
- var isVerifiedShellMetadata = (metadata) => isRecord(metadata) && metadata.status === "completed" && metadata.exit === 0 && metadata.truncated === false && (metadata.timeout === undefined || metadata.timeout === false) && Object.keys(metadata).every((key) => ["status", "exit", "truncated", "timeout"].includes(key));
1838
- var publishCapturedAttempt = (state, event, attempt) => Effect2.gen(function* publishAttempt() {
2840
+ }, Effect2.mapError(toToolError));
2841
+ var allowedMetadataKeys = new Set(["status", "exit", "truncated", "timeout"]);
2842
+ var unexpectedMetadataKeys = (metadata) => Object.keys(metadata).filter((key) => !allowedMetadataKeys.has(key));
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;
2844
+ var publishCapturedAttempt = Effect2.fnUntraced(function* publishAttempt(state, event, attempt) {
1839
2845
  const { ctx } = state;
1840
2846
  if (!isRecord(event.input) || event.input.command !== attempt.command) {
1841
2847
  return "claimed capture command was modified before execution";
@@ -1847,19 +2853,31 @@ var publishCapturedAttempt = (state, event, attempt) => Effect2.gen(function* pu
1847
2853
  return "capture was superseded by a refresh";
1848
2854
  }
1849
2855
  if (!isVerifiedShellMetadata(event.result.metadata)) {
1850
- return "shell result lacks verified foreground completion metadata";
2856
+ const unexpected = isRecord(event.result.metadata) ? unexpectedMetadataKeys(event.result.metadata) : [];
2857
+ return unexpected.length > 0 ? `shell result lacks verified foreground completion metadata (unexpected keys: ${unexpected.join(", ")})` : "shell result lacks verified foreground completion metadata";
1851
2858
  }
1852
2859
  const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => null);
1853
2860
  if (session === null || session.location.workspaceID !== ctx.location.workspaceID) {
1854
2861
  return "capture session or workspace no longer matches";
1855
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
+ }
1856
2867
  const baseline = yield* Effect2.try(() => importCapture(attempt)).pipe(Effect2.orElseSucceed(() => null));
1857
2868
  if (baseline === null || baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined) {
1858
2869
  return "private artifact is invalid or incomplete (END required)";
1859
2870
  }
1860
- if (!(yield* publish(ctx, attempt, state.generation, baseline).pipe(Effect2.catchCause(() => Effect2.succeed(false))))) {
2871
+ if (!isAttemptActive()) {
2872
+ return "capture was superseded by a refresh";
2873
+ }
2874
+ const now = yield* state.clock.currentTimeMillis;
2875
+ if (!(yield* publish(ctx, attempt, state.generation, baseline, now, isAttemptActive).pipe(Effect2.catchCause(() => Effect2.succeed(false))))) {
1861
2876
  return "capture storage failed or its counter changed";
1862
2877
  }
2878
+ if (!isAttemptActive()) {
2879
+ return "capture was superseded by a refresh";
2880
+ }
1863
2881
  state.failures.delete(attempt.scope);
1864
2882
  return baseline;
1865
2883
  });
@@ -1889,19 +2907,19 @@ var rememberFailure = (state, scope, reason) => {
1889
2907
  }
1890
2908
  }
1891
2909
  };
1892
- var finalizeAttempt = (state, attempt, outcome) => Effect2.gen(function* finalize() {
1893
- if (state.pending.get(attempt.scope) === attempt) {
1894
- state.pending.delete(attempt.scope);
1895
- }
1896
- if (isJSONString(outcome)) {
1897
- rememberFailure(state, attempt.scope, outcome);
1898
- yield* recordState(state.ctx, attempt, "failed", outcome).pipe(Effect2.catchCause(() => Effect2.void));
1899
- yield* invalidateOwned(state.ctx, attempt);
1900
- }
1901
- }).pipe(Effect2.ensuring(Effect2.sync(() => {
1902
- cleanup(attempt);
1903
- })), Effect2.catchCause(() => Effect2.void));
1904
- 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) {
1905
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);
1906
2924
  if (attempt === undefined) {
1907
2925
  return;
@@ -1912,10 +2930,18 @@ var handleAfterExecute = (state, event) => Effect2.gen(function* after() {
1912
2930
  }
1913
2931
  let outcome = "capture import or storage failed";
1914
2932
  yield* Effect2.gen(function* publishing() {
1915
- outcome = yield* publishCapturedAttempt(state, event, attempt);
1916
- if (!isJSONString(outcome)) {
1917
- yield* recordState(state.ctx, attempt, "published");
2933
+ const published = yield* publishCapturedAttempt(state, event, attempt);
2934
+ if (isJSONString(published)) {
2935
+ outcome = published;
2936
+ return;
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;
1918
2942
  }
2943
+ state.pending.delete(attempt.scope);
2944
+ outcome = published;
1919
2945
  }).pipe(Effect2.onExit(() => finalizeAttempt(state, attempt, outcome)), Effect2.catchCause(() => Effect2.void));
1920
2946
  const note = isJSONString(outcome) ? `[commit-guard] This capture did not publish a usable baseline: ${outcome.slice(0, 256)}.
1921
2947
  RECEIPT_OK alone does not authorize a commit.
@@ -1936,22 +2962,29 @@ var plugin = Plugin.define({
1936
2962
  id: "opencode-commit-guard",
1937
2963
  effect: (ctx) => Effect2.gen(function* setup() {
1938
2964
  const config = yield* Effect2.sync(() => parseConfig(ctx.options));
2965
+ const clock = yield* Clock.Clock;
2966
+ const activationScope = yield* Effect2.scope;
1939
2967
  const state = {
1940
2968
  ctx,
2969
+ clock,
2970
+ activationScope,
1941
2971
  config,
1942
2972
  generation: randomUUID2(),
1943
2973
  pending: new Map,
2974
+ recentExpired: new Set,
1944
2975
  preparing: new Set,
1945
2976
  lastSessionWorkdir: new Map,
1946
2977
  failures: new Map
1947
2978
  };
1948
2979
  yield* Effect2.addFinalizer(() => Effect2.gen(function* unload() {
1949
- for (const attempt of state.pending.values()) {
1950
- cleanup(attempt);
1951
- yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication");
1952
- yield* invalidateOwned(ctx, attempt);
1953
- }
2980
+ const remaining = [...state.pending.values()];
1954
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
+ }
1955
2988
  }));
1956
2989
  yield* ctx.tool.transform((editor) => {
1957
2990
  editor.add({
@@ -1969,21 +3002,7 @@ Use literal message text and real body newlines.
1969
3002
  Example: git commit -m $'scope: Subject\n\nBody line one.\nBody line two.'
1970
3003
  Replace scope and follow the returned line-length and signoff rules.
1971
3004
  Add -s only when the returned policy or repository instructions require it.`,
1972
- input: {
1973
- type: "object",
1974
- properties: {
1975
- refresh: { type: "boolean" },
1976
- workdir: {
1977
- type: "string",
1978
- description: "Working directory of the Git repository relative to the session directory or absolute."
1979
- },
1980
- directory: {
1981
- type: "string",
1982
- description: "Path to the Git repository checkout (alias for workdir)."
1983
- }
1984
- },
1985
- additionalProperties: false
1986
- },
3005
+ input: CommitContextInput,
1987
3006
  execute: (input, toolContext) => runCommitContext(state, input, toolContext)
1988
3007
  });
1989
3008
  });