opencode-commit-guard 1.0.7 → 1.1.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.
package/dist/index.js CHANGED
@@ -1,32 +1,44 @@
1
1
  // @bun
2
2
  // src/plugin.ts
3
- import { Plugin } from "@opencode/plugin/effect";
4
- import { Tool } from "@opencode/schema/tool";
5
- import { Effect as Effect2 } from "effect";
6
3
  import { randomUUID as randomUUID2 } from "crypto";
7
4
  import { existsSync as existsSync2, realpathSync as realpathSync2 } from "fs";
8
- import { relative as relative2, resolve as resolve2 } from "path";
5
+ import path from "path";
6
+ import { Plugin, Tool } from "@opencode/plugin/effect";
7
+ import { Effect as Effect2, Schema as Schema2 } from "effect";
9
8
 
10
9
  // src/capture.ts
11
10
  import { createHash, randomUUID } from "crypto";
12
- import { closeSync, constants, existsSync, fstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync, statSync } from "fs";
11
+ import {
12
+ closeSync,
13
+ constants,
14
+ existsSync,
15
+ fstatSync,
16
+ mkdtempSync,
17
+ openSync,
18
+ readdirSync,
19
+ readSync,
20
+ realpathSync,
21
+ rmSync,
22
+ statSync
23
+ } from "fs";
13
24
  import { tmpdir } from "os";
14
- import { dirname, join, relative, resolve } from "path";
25
+ import nodePath from "path";
26
+ import { gzipSync } from "zlib";
15
27
  import { Effect, Semaphore } from "effect";
16
28
 
17
29
  // src/types.ts
18
- function isJSONString(value) {
30
+ var isJSONString = function isJSONString(value) {
19
31
  return Object.prototype.toString.call(value) === "[object String]";
20
- }
21
- function isJSONNumber(value) {
32
+ };
33
+ var isJSONNumber = function isJSONNumber(value) {
22
34
  return Object.prototype.toString.call(value) === "[object Number]";
23
- }
24
- function isJSONBoolean(value) {
35
+ };
36
+ var isJSONBoolean = function isJSONBoolean(value) {
25
37
  return Object.prototype.toString.call(value) === "[object Boolean]";
26
- }
27
- function isRecord(value) {
38
+ };
39
+ var isRecord = function isRecord(value) {
28
40
  return value instanceof Object && !Array.isArray(value);
29
- }
41
+ };
30
42
  var defaultConfig = {
31
43
  requireScope: true,
32
44
  allowedScopes: undefined,
@@ -35,16 +47,17 @@ var defaultConfig = {
35
47
  };
36
48
 
37
49
  // src/capture.ts
50
+ var { dirname, isAbsolute, join, relative, resolve } = nodePath;
38
51
  var version = 1;
39
52
  var maxBytes = 262144;
40
53
  var captureTimeout = 20000;
41
54
  var policy = "commit-guard-context-v1";
42
55
  var storageLock = Semaphore.makeUnsafe(1);
43
- function digest(text) {
56
+ var digest = function digest(text) {
44
57
  return createHash("sha256").update(text).digest("hex");
45
- }
46
- function scopeFor(ctx, sessionID, config, targetDir) {
47
- const location = ctx.location;
58
+ };
59
+ var scopeFor = function scopeFor(ctx, sessionID, config, targetDir) {
60
+ const { location } = ctx;
48
61
  const directory = targetDir ?? location.directory;
49
62
  const root = findGitRoot(directory) ?? realpathSync(directory);
50
63
  return digest(JSON.stringify([
@@ -58,15 +71,15 @@ function scopeFor(ctx, sessionID, config, targetDir) {
58
71
  config.allowedScopes ?? null,
59
72
  config.maxLineLength
60
73
  ]));
61
- }
62
- function isGitDirectory(dir) {
74
+ };
75
+ var isGitDirectory = function isGitDirectory(dir) {
63
76
  try {
64
77
  return existsSync(join(dir, ".git"));
65
78
  } catch {
66
79
  return false;
67
80
  }
68
- }
69
- function findGitRoot(startDir) {
81
+ };
82
+ var findGitRoot = function findGitRoot(startDir) {
70
83
  let current;
71
84
  try {
72
85
  current = realpathSync(startDir);
@@ -84,19 +97,22 @@ function findGitRoot(startDir) {
84
97
  current = parent;
85
98
  }
86
99
  return;
87
- }
88
- function findSubRepos(dir, maxDepth = 2) {
100
+ };
101
+ var findSubRepos = function findSubRepos(dir, maxDepth = 2) {
89
102
  const repos = [];
90
- function search(currentDir, currentDepth) {
91
- if (currentDepth > maxDepth)
103
+ const search = function search(currentDir, currentDepth) {
104
+ if (currentDepth > maxDepth) {
92
105
  return;
106
+ }
93
107
  try {
94
108
  const entries = readdirSync(currentDir, { withFileTypes: true });
95
109
  for (const entry of entries) {
96
- if (!entry.isDirectory() && !entry.isSymbolicLink())
110
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) {
97
111
  continue;
98
- if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist")
112
+ }
113
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist") {
99
114
  continue;
115
+ }
100
116
  const fullPath = join(currentDir, entry.name);
101
117
  if (isGitDirectory(fullPath)) {
102
118
  repos.push(fullPath);
@@ -105,11 +121,11 @@ function findSubRepos(dir, maxDepth = 2) {
105
121
  }
106
122
  }
107
123
  } catch {}
108
- }
124
+ };
109
125
  search(dir, 1);
110
126
  return repos;
111
- }
112
- function resolveTargetWorkdir(baseDir, requestedDir) {
127
+ };
128
+ var resolveTargetWorkdir = function resolveTargetWorkdir(baseDir, requestedDir) {
113
129
  if (requestedDir !== undefined) {
114
130
  const resolvedDir = resolve(baseDir, requestedDir);
115
131
  if (!existsSync(resolvedDir)) {
@@ -124,7 +140,9 @@ function resolveTargetWorkdir(baseDir, requestedDir) {
124
140
  }
125
141
  const gitRoot = findGitRoot(resolvedDir);
126
142
  if (gitRoot === undefined) {
127
- return { error: `Directory "${requestedDir}" is not a Git repository or inside one.` };
143
+ return {
144
+ error: `Directory "${requestedDir}" is not a Git repository or inside one.`
145
+ };
128
146
  }
129
147
  return { workdir: realpathSync(resolvedDir) };
130
148
  }
@@ -147,93 +165,121 @@ function resolveTargetWorkdir(baseDir, requestedDir) {
147
165
  Specify which repository to target with the 'workdir' option, for example:
148
166
  commit_context({ workdir: "${relative(baseDir, subRepos[0])}" })`
149
167
  };
150
- }
151
- function counterKey(scope) {
168
+ };
169
+ var counterKey = function counterKey(scope) {
152
170
  return `counter/${scope}`;
153
- }
154
- function prefix(scope) {
171
+ };
172
+ var prefix = function prefix(scope) {
155
173
  return `snap/${scope}/`;
156
- }
157
- function counter(ctx, scope) {
158
- return Effect.gen(function* () {
174
+ };
175
+ var counter = function counter(ctx, scope) {
176
+ return Effect.gen(function* readCounter() {
159
177
  const value = yield* ctx.storage.get(counterKey(scope));
160
- if (value === undefined)
178
+ if (value === undefined) {
161
179
  return 0;
180
+ }
162
181
  return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : -1;
163
182
  });
164
- }
165
- function invalidate(ctx, scope) {
166
- return storageLock.withPermits(1)(Effect.gen(function* () {
183
+ };
184
+ var invalidate = function invalidate(ctx, scope) {
185
+ return storageLock.withPermits(1)(Effect.gen(function* incrementCounter() {
167
186
  const previous = yield* counter(ctx, scope);
168
187
  const next = previous < 0 ? 1 : previous + 1;
169
188
  yield* ctx.storage.set(counterKey(scope), next);
170
189
  return next;
171
190
  }));
172
- }
173
- function invalidateOwned(ctx, attempt) {
174
- return storageLock.withPermits(1)(Effect.gen(function* () {
191
+ };
192
+ var invalidateOwned = function invalidateOwned(ctx, attempt) {
193
+ return storageLock.withPermits(1)(Effect.gen(function* invalidateAttempt() {
175
194
  if ((yield* counter(ctx, attempt.scope)) === attempt.counter) {
176
195
  yield* ctx.storage.set(counterKey(attempt.scope), attempt.counter + 1);
177
196
  }
178
197
  }));
179
- }
180
- function recordState(ctx, attempt, state, reason = "") {
181
- return storageLock.withPermits(1)(Effect.gen(function* () {
182
- if ((yield* counter(ctx, attempt.scope)) !== attempt.counter)
198
+ };
199
+ var recordState = function recordState(ctx, attempt, state, reason = "") {
200
+ return storageLock.withPermits(1)(Effect.gen(function* storeState() {
201
+ if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) {
183
202
  return;
184
- yield* ctx.storage.set(`state/${attempt.scope}`, { state, reason: reason.slice(0, 256) });
203
+ }
204
+ yield* ctx.storage.set(`state/${attempt.scope}`, {
205
+ state,
206
+ reason: reason.slice(0, 256)
207
+ });
185
208
  }));
186
- }
187
- function captureStatus(ctx, scope) {
188
- return Effect.gen(function* () {
209
+ };
210
+ var captureStatus = function captureStatus(ctx, scope) {
211
+ return Effect.gen(function* readCaptureStatus() {
189
212
  const value = yield* ctx.storage.get(`state/${scope}`);
190
- if (!isRecord(value))
213
+ if (!isRecord(value)) {
191
214
  return "";
192
- if (value["state"] === "expired")
215
+ }
216
+ if (value.state === "expired") {
193
217
  return "The previous capture expired before its command was claimed; no matching shell result was observed. ";
194
- if (value["state"] === "failed" && isJSONString(value["reason"]))
195
- return `The previous capture failed: ${value["reason"]}. `;
196
- if (value["state"] === "prepared" || value["state"] === "claimed")
218
+ }
219
+ if (value.state === "failed" && isJSONString(value.reason)) {
220
+ return `The previous capture failed: ${value.reason}. `;
221
+ }
222
+ if (value.state === "prepared" || value.state === "claimed") {
197
223
  return "The previous capture was interrupted before publication. ";
224
+ }
198
225
  return "";
199
226
  });
200
- }
201
- function validBaseline(value) {
202
- if (!isRecord(value))
227
+ };
228
+ var validBaseline = function validBaseline(value) {
229
+ if (!isRecord(value)) {
203
230
  return false;
204
- return ["directory", "workdir", "gitDir", "commonDir"].every((key) => isJSONString(value[key])) && (value["branch"] === null || isJSONString(value["branch"])) && (value["head"] === null || /^[0-9a-f]{40,64}$/.test(String(value["head"]))) && Array.isArray(value["messages"]) && value["messages"].length <= 10 && value["messages"].every((message) => isJSONString(message)) && ["true", "false", "unset", "error"].includes(String(value["gpgsign"])) && (value["signingkey"] === null || value["signingkey"] === "error" || isJSONString(value["signingkey"]));
205
- }
206
- function load(ctx, scope) {
207
- return storageLock.withPermits(1)(Effect.gen(function* () {
231
+ }
232
+ 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));
233
+ };
234
+ var load = function load(ctx, scope) {
235
+ return storageLock.withPermits(1)(Effect.gen(function* readBaseline() {
208
236
  const current = yield* counter(ctx, scope);
209
- if (current < 0)
210
- return;
237
+ if (current < 0) {
238
+ return yield* Effect.succeed(undefined);
239
+ }
211
240
  let after;
212
241
  let newest;
213
242
  do {
214
- const page = yield* ctx.storage.scan({ prefix: prefix(scope), after, limit: 100 });
243
+ const page = yield* ctx.storage.scan({
244
+ prefix: prefix(scope),
245
+ after,
246
+ limit: 100
247
+ });
215
248
  for (const record of page.entries) {
216
249
  const raw = record.value;
217
- if (!isRecord(raw) || raw["schema"] !== version || raw["scope"] !== scope || raw["counter"] !== current || !isJSONString(raw["generation"]) || !isJSONString(raw["sequence"]) || !isJSONString(raw["checksum"]) || !validBaseline(raw["baseline"]))
250
+ if (!isRecord(raw) || raw.schema !== version || raw.scope !== scope || raw.counter !== current || !isJSONString(raw.generation) || !isJSONString(raw.sequence) || !isJSONString(raw.checksum) || !validBaseline(raw.baseline)) {
218
251
  continue;
219
- const baseline = raw["baseline"];
220
- if (digest(JSON.stringify([version, scope, current, raw["generation"], raw["sequence"], baseline])) !== raw["checksum"])
252
+ }
253
+ const { baseline } = raw;
254
+ if (digest(JSON.stringify([
255
+ version,
256
+ scope,
257
+ current,
258
+ raw.generation,
259
+ raw.sequence,
260
+ baseline
261
+ ])) !== raw.checksum) {
221
262
  continue;
222
- if (newest === undefined || raw["sequence"] > newest.sequence)
223
- newest = { sequence: raw["sequence"], baseline };
263
+ }
264
+ if (newest === undefined || raw.sequence > newest.sequence) {
265
+ newest = { sequence: raw.sequence, baseline };
266
+ }
224
267
  }
225
268
  after = page.next;
226
269
  } while (after !== undefined);
227
270
  return newest?.baseline;
228
271
  }));
229
- }
230
- function captureCommand(path) {
272
+ };
273
+ var captureCommand = function captureCommand(path) {
274
+ if (process.platform === "win32") {
275
+ return windowsCaptureCommand(path);
276
+ }
231
277
  const quoted = `'${path.replaceAll("'", "'\\''")}'`;
232
- return `timeout 15s bash -c 'set -euo pipefail
278
+ const script = `set -euo pipefail
233
279
  ulimit -f 256
234
280
  out=$1
235
281
  printf "CTX1\\n" > "$out"
236
- field() { "$@" 2>/dev/null | base64 -w0 >> "$out"; printf "\\n" >> "$out"; }
282
+ field() { "$@" 2>/dev/null | base64 | tr -d "\\r\\n" >> "$out"; printf "\\n" >> "$out"; }
237
283
  field git rev-parse --show-toplevel
238
284
  field git rev-parse --absolute-git-dir
239
285
  field git rev-parse --path-format=absolute --git-common-dir
@@ -242,9 +288,100 @@ if git rev-parse --verify HEAD >/dev/null 2>&1; then printf "head\\n" >> "$out";
242
288
  if git config --type=bool --get commit.gpgsign >/dev/null 2>&1; then printf "set\\n" >> "$out"; field git config --type=bool --get commit.gpgsign; else status=$?; if [ "$status" -eq 1 ]; then printf "unset\\n\\n" >> "$out"; else printf "error\\n\\n" >> "$out"; fi; fi
243
289
  if git config --get user.signingkey >/dev/null 2>&1; then printf "set\\n" >> "$out"; field git config --get user.signingkey; else status=$?; if [ "$status" -eq 1 ]; then printf "unset\\n\\n" >> "$out"; else printf "error\\n\\n" >> "$out"; fi; fi
244
290
  printf "END\\n" >> "$out"
245
- printf "RECEIPT_OK\\n"' bash ${quoted} 2>/dev/null`;
291
+ printf "RECEIPT_OK\\n"`;
292
+ return `bash -c 'set -m
293
+ bash -c "$1" bash "$2" &
294
+ worker=$!
295
+ (
296
+ sleep 15 &
297
+ timer=$!
298
+ trap "kill $timer 2>/dev/null" EXIT
299
+ trap "exit 0" TERM
300
+ wait "$timer"
301
+ kill -KILL -- "-$worker" 2>/dev/null
302
+ ) &
303
+ watchdog=$!
304
+ wait "$worker"
305
+ status=$?
306
+ kill "$watchdog" 2>/dev/null
307
+ wait "$watchdog" 2>/dev/null
308
+ exit "$status"' bash '${script.replaceAll("'", "'\\''")}' ${quoted} 2>/dev/null`;
309
+ };
310
+ var windowsCaptureCommand = function windowsCaptureCommand(path) {
311
+ const script = `$ErrorActionPreference = 'Stop'
312
+ $clock = [Diagnostics.Stopwatch]::StartNew()
313
+ $lines = [Collections.Generic.List[string]]::new()
314
+ $lines.Add('CTX1')
315
+ function gitResult([string]$arguments) {
316
+ $info = [Diagnostics.ProcessStartInfo]::new('git', $arguments)
317
+ $info.UseShellExecute = $false
318
+ $info.CreateNoWindow = $true
319
+ $info.RedirectStandardOutput = $true
320
+ $info.RedirectStandardError = $true
321
+ $p = [Diagnostics.Process]::new()
322
+ $p.StartInfo = $info
323
+ $memory = [IO.MemoryStream]::new()
324
+ try {
325
+ if (!$p.Start()) { throw 'Git did not start' }
326
+ $p.BeginErrorReadLine()
327
+ $buffer = [byte[]]::new(4096)
328
+ while ($true) {
329
+ $task = $p.StandardOutput.BaseStream.ReadAsync($buffer, 0, $buffer.Length)
330
+ $remaining = 15000 - [int]$clock.ElapsedMilliseconds
331
+ if ($remaining -le 0 -or !$task.Wait($remaining)) { throw 'Capture timed out' }
332
+ $count = $task.Result
333
+ if ($count -eq 0) { break }
334
+ if ($memory.Length + $count -gt ${maxBytes}) { throw 'Capture exceeds size limit' }
335
+ $memory.Write($buffer, 0, $count)
336
+ }
337
+ $remaining = 15000 - [int]$clock.ElapsedMilliseconds
338
+ if ($remaining -le 0 -or !$p.WaitForExit($remaining)) { throw 'Capture timed out' }
339
+ return @{ Code = $p.ExitCode; Bytes = $memory.ToArray() }
340
+ } finally {
341
+ if ($p.Id -and !$p.HasExited) { & taskkill.exe /PID $p.Id /T /F > $null 2>&1 }
342
+ $p.Dispose()
343
+ $memory.Dispose()
344
+ }
246
345
  }
247
- function createPending(scope, sessionID, agent, counterValue, workdir) {
346
+ function field([string]$arguments) {
347
+ $result = gitResult $arguments
348
+ if ($result.Code -ne 0) { throw 'Git capture failed' }
349
+ $lines.Add([Convert]::ToBase64String($result.Bytes))
350
+ }
351
+ try {
352
+ field 'rev-parse --show-toplevel'
353
+ field 'rev-parse --absolute-git-dir'
354
+ field 'rev-parse --path-format=absolute --git-common-dir'
355
+ $branch = gitResult 'symbolic-ref -q --short HEAD'
356
+ if ($branch.Code -eq 0) { $lines.Add('branch'); $lines.Add([Convert]::ToBase64String($branch.Bytes)) }
357
+ elseif ($branch.Code -eq 1) { $lines.Add('detached'); $lines.Add('') }
358
+ else { throw 'Invalid branch' }
359
+ $head = gitResult 'rev-parse --verify HEAD'
360
+ if ($head.Code -eq 0) {
361
+ $lines.Add('head'); $lines.Add([Convert]::ToBase64String($head.Bytes))
362
+ field 'log -10 -z --format=%B%x00'
363
+ } elseif ($head.Code -eq 128 -and (gitResult 'symbolic-ref -q HEAD').Code -eq 0 -and (gitResult 'status --porcelain').Code -eq 0) {
364
+ $lines.Add('unborn'); $lines.Add(''); $lines.Add('')
365
+ } else { throw 'Invalid HEAD' }
366
+ foreach ($arguments in @('config --type=bool --get commit.gpgsign', 'config --get user.signingkey')) {
367
+ $result = gitResult $arguments
368
+ if ($result.Code -eq 0) { $lines.Add('set'); $lines.Add([Convert]::ToBase64String($result.Bytes)) }
369
+ elseif ($result.Code -eq 1) { $lines.Add('unset'); $lines.Add('') }
370
+ else { $lines.Add('error'); $lines.Add('') }
371
+ }
372
+ $lines.Add('END')
373
+ $bytes = [Text.Encoding]::UTF8.GetBytes(($lines -join "\`n") + "\`n")
374
+ if ($bytes.Length -gt ${maxBytes} -or $clock.ElapsedMilliseconds -ge 15000) { throw 'Capture exceeds limits' }
375
+ $path = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(path).toString("base64")}'))
376
+ $file = [IO.FileStream]::new($path, [IO.FileMode]::Truncate, [IO.FileAccess]::Write, [IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)
377
+ try { $file.Write($bytes, 0, $bytes.Length) } finally { $file.Dispose() }
378
+ [Console]::Write("RECEIPT_OK\`n")
379
+ } catch { exit 1 }`;
380
+ const compressed = gzipSync(Buffer.from(script)).toString("base64");
381
+ 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() }`;
382
+ return `powershell -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(bootstrap, "utf16le").toString("base64")}`;
383
+ };
384
+ var createPending = function createPending(scope, sessionID, agent, counterValue, workdir) {
248
385
  const directory = mkdtempSync(join(tmpdir(), "commit-context-"));
249
386
  try {
250
387
  const file = join(directory, randomUUID());
@@ -266,55 +403,99 @@ function createPending(scope, sessionID, agent, counterValue, workdir) {
266
403
  rmSync(directory, { recursive: true, force: true });
267
404
  throw error;
268
405
  }
269
- }
270
- function cleanup(pending) {
271
- if (pending.closed === true)
406
+ };
407
+ var cleanup = function cleanup(pending) {
408
+ if (pending.closed === true) {
272
409
  return;
410
+ }
273
411
  pending.closed = true;
274
412
  closeSync(pending.fd);
275
413
  rmSync(pending.directory, { recursive: true, force: true });
276
- }
277
- function decode(line) {
278
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(line))
414
+ };
415
+ var decode = function decode(line) {
416
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(line)) {
279
417
  throw new Error("Invalid capture framing");
280
- return Buffer.from(line, "base64").toString("utf8");
281
- }
282
- function importCapture(pending) {
283
- const stat = fstatSync(pending.fd);
284
- if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino || stat.uid !== pending.identity.uid || (stat.mode & 511) !== 384 || stat.size > maxBytes || stat.size === 0) {
285
- throw new Error("Invalid private capture artifact");
286
418
  }
287
- const bytes = Buffer.alloc(stat.size);
288
- if (readSync(pending.fd, bytes, 0, stat.size, 0) !== stat.size)
289
- throw new Error("Incomplete private capture artifact");
290
- const completed = fstatSync(pending.fd);
291
- if (completed.size !== stat.size || completed.dev !== stat.dev || completed.ino !== stat.ino)
292
- throw new Error("Capture changed during import");
293
- const fields = bytes.toString("utf8").split(`
419
+ return Buffer.from(line, "base64").toString("utf-8");
420
+ };
421
+ var importCapture = function importCapture(pending) {
422
+ const readArtifact = () => {
423
+ const stat = fstatSync(pending.fd);
424
+ 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) {
425
+ throw new Error("Invalid private capture artifact");
426
+ }
427
+ const bytes = Buffer.alloc(stat.size);
428
+ if (readSync(pending.fd, bytes, 0, stat.size, 0) !== stat.size) {
429
+ throw new Error("Incomplete private capture artifact");
430
+ }
431
+ const completed = fstatSync(pending.fd);
432
+ if (completed.size !== stat.size || completed.dev !== stat.dev || completed.ino !== stat.ino) {
433
+ throw new Error("Capture changed during import");
434
+ }
435
+ return bytes;
436
+ };
437
+ const bytes = readArtifact();
438
+ const fields = bytes.toString("utf-8").split(`
294
439
  `);
295
- if (fields.length !== 15 || fields[0] !== "CTX1" || fields[13] !== "END" || fields[14] !== "")
440
+ if (fields.length !== 15 || fields[0] !== "CTX1" || fields[13] !== "END" || fields[14] !== "") {
296
441
  throw new Error("Incomplete capture");
297
- const root = decode(fields[1]).trimEnd();
442
+ }
443
+ const rawRoot = decode(fields[1]).trimEnd();
444
+ const root = isAbsolute(rawRoot) ? realpathSync(resolve(rawRoot)) : rawRoot;
298
445
  const gitDir = decode(fields[2]).trimEnd();
299
446
  const commonDir = decode(fields[3]).trimEnd();
300
447
  const branch = fields[4] === "branch" ? decode(fields[5]).trimEnd() : null;
301
448
  const head = fields[6] === "head" ? decode(fields[7]).trim() : null;
302
449
  const rawLog = decode(fields[8]);
303
450
  const messages = head === null ? [] : rawLog.split("\x00\x00").filter((message) => message.length > 0);
304
- if (!root.startsWith("/") || !gitDir.startsWith("/") || !commonDir.startsWith("/") || root !== findGitRoot(pending.workdir) || !["branch", "detached"].includes(fields[4]) || !["head", "unborn"].includes(fields[6]) || head !== null && !/^[a-f0-9]{40,64}$/.test(head) || head === null && rawLog !== "" || head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\x00\x00")))
305
- throw new Error("Invalid Git baseline");
306
- const configState = fields[9];
451
+ const validateIdentity = () => {
452
+ if (!isAbsolute(root) || !isAbsolute(gitDir) || !isAbsolute(commonDir) || root !== findGitRoot(pending.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"))) {
453
+ throw new Error("Invalid Git baseline");
454
+ }
455
+ };
456
+ validateIdentity();
457
+ const [configState] = fields.slice(9);
307
458
  const value = decode(fields[10]).trim();
308
- const gpgsign = configState === "set" && (value === "true" || value === "false") ? value : configState === "unset" ? "unset" : "error";
309
- const signingkey = fields[11] === "set" ? decode(fields[12]).trim() : fields[11] === "unset" ? null : "error";
310
- return { directory: root, workdir: pending.workdir, gitDir, commonDir, branch, head, messages, gpgsign, signingkey };
311
- }
312
- function publish(ctx, pending, generation, baseline) {
313
- return storageLock.withPermits(1)(Effect.gen(function* () {
314
- if ((yield* counter(ctx, pending.scope)) !== pending.counter)
459
+ const readSigningPolicy = () => {
460
+ if (configState === "set" && (value === "true" || value === "false")) {
461
+ return value;
462
+ }
463
+ return configState === "unset" ? "unset" : "error";
464
+ };
465
+ const readSigningKey = () => {
466
+ if (fields[11] === "set") {
467
+ return decode(fields[12]).trim();
468
+ }
469
+ return fields[11] === "unset" ? null : "error";
470
+ };
471
+ const gpgsign = readSigningPolicy();
472
+ const signingkey = readSigningKey();
473
+ return {
474
+ directory: root,
475
+ workdir: pending.workdir,
476
+ gitDir,
477
+ commonDir,
478
+ branch,
479
+ head,
480
+ messages,
481
+ gpgsign,
482
+ signingkey
483
+ };
484
+ };
485
+ var publish = function publish(ctx, pending, generation, baseline) {
486
+ return storageLock.withPermits(1)(Effect.gen(function* writeBaseline() {
487
+ if ((yield* counter(ctx, pending.scope)) !== pending.counter) {
315
488
  return false;
489
+ }
316
490
  const sequence = `${Date.now().toString().padStart(15, "0")}-${randomUUID()}`;
317
- const checksum = digest(JSON.stringify([version, pending.scope, pending.counter, generation, sequence, baseline]));
491
+ const checksum = digest(JSON.stringify([
492
+ version,
493
+ pending.scope,
494
+ pending.counter,
495
+ generation,
496
+ sequence,
497
+ baseline
498
+ ]));
318
499
  yield* ctx.storage.set(prefix(pending.scope) + sequence, {
319
500
  schema: version,
320
501
  scope: pending.scope,
@@ -326,41 +507,49 @@ function publish(ctx, pending, generation, baseline) {
326
507
  });
327
508
  let after;
328
509
  do {
329
- const page = yield* ctx.storage.scan({ prefix: prefix(pending.scope), after, limit: 100 });
510
+ const page = yield* ctx.storage.scan({
511
+ prefix: prefix(pending.scope),
512
+ after,
513
+ limit: 100
514
+ });
330
515
  for (const record of page.entries) {
331
- if (record.key < prefix(pending.scope) + sequence)
516
+ if (record.key < prefix(pending.scope) + sequence) {
332
517
  yield* ctx.storage.remove(record.key);
518
+ }
333
519
  }
334
520
  after = page.next;
335
521
  } while (after !== undefined);
336
522
  return true;
337
523
  }));
338
- }
524
+ };
525
+
526
+ // src/config.ts
527
+ import { Schema } from "effect";
339
528
 
340
529
  // src/scope.ts
341
- var scopePattern = /^([a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(.+)$/;
530
+ var scopePattern = /^(?<scope>[a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(?<subject>.+)$/u;
342
531
 
343
532
  // src/config.ts
344
- function parseConfig(options) {
533
+ var parseConfig = function parseConfig(options) {
345
534
  if (options === undefined) {
346
535
  return defaultConfig;
347
536
  }
348
537
  if (!isRecord(options)) {
349
538
  throw new Error("Invalid plugin options; expected an object.");
350
539
  }
351
- const rawRequireScope = options["requireScope"];
352
- let requireScope = defaultConfig.requireScope;
540
+ const rawRequireScope = options.requireScope;
541
+ let { requireScope } = defaultConfig;
353
542
  if (rawRequireScope !== undefined) {
354
543
  if (!isJSONBoolean(rawRequireScope)) {
355
544
  throw new Error("Invalid plugin option requireScope; expected a boolean.");
356
545
  }
357
546
  requireScope = rawRequireScope;
358
547
  }
359
- const rawAllowedScopes = options["allowedScopes"];
548
+ const rawAllowedScopes = options.allowedScopes;
360
549
  let allowedScopes = defaultConfig.allowedScopes;
361
550
  if (rawAllowedScopes !== undefined) {
362
- if (!Array.isArray(rawAllowedScopes)) {
363
- throw new Error("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
551
+ if (!Schema.is(Schema.Array(Schema.Json))(rawAllowedScopes)) {
552
+ throw new TypeError("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
364
553
  }
365
554
  const scopes = [];
366
555
  for (const item of rawAllowedScopes) {
@@ -374,15 +563,15 @@ function parseConfig(options) {
374
563
  }
375
564
  allowedScopes = scopes.length > 0 ? scopes : undefined;
376
565
  }
377
- const rawMaxLineLength = options["maxLineLength"];
378
- let maxLineLength = defaultConfig.maxLineLength;
566
+ const rawMaxLineLength = options.maxLineLength;
567
+ let { maxLineLength } = defaultConfig;
379
568
  if (rawMaxLineLength !== undefined) {
380
569
  if (!isJSONNumber(rawMaxLineLength) || !Number.isSafeInteger(rawMaxLineLength) || rawMaxLineLength < 0) {
381
570
  throw new Error("Invalid plugin option maxLineLength; expected an integer greater than or equal to 0.");
382
571
  }
383
572
  maxLineLength = rawMaxLineLength;
384
573
  }
385
- if (options["requireSignoff"] !== undefined) {
574
+ if (options.requireSignoff !== undefined) {
386
575
  throw new Error("Plugin option requireSignoff has been removed; signoff follows the captured effective commit.gpgsign value.");
387
576
  }
388
577
  return {
@@ -391,7 +580,7 @@ function parseConfig(options) {
391
580
  maxLineLength,
392
581
  enforceSignoff: defaultConfig.enforceSignoff
393
582
  };
394
- }
583
+ };
395
584
 
396
585
  // src/shell.ts
397
586
  var gitGlobalOptionsWithArg = new Set([
@@ -443,13 +632,14 @@ var commitLongOptionsWithArg = new Set([
443
632
  "--squash",
444
633
  "--template"
445
634
  ]);
446
- function isWordSeparator(character) {
635
+ var isWordSeparator = function isWordSeparator(character) {
447
636
  return character === " " || character === "\t" || character === "\r" || character === `
448
637
  ` || character === ";" || character === "&" || character === "|" || character === "(" || character === ")";
449
- }
450
- function consumeCommandSubstitution(command, start, nesting = 0) {
451
- if (nesting > 12)
452
- throw new Error("Shell parsing limit exceeded. Run git commit directly.");
638
+ };
639
+ var consumeCommandSubstitution = function consumeCommandSubstitution(command, start, nesting = 0) {
640
+ if (nesting > 12) {
641
+ throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
642
+ }
453
643
  let depth = 1;
454
644
  let quote;
455
645
  let i = start + 2;
@@ -458,224 +648,356 @@ function consumeCommandSubstitution(command, start, nesting = 0) {
458
648
  let timeOption = false;
459
649
  let arithmeticDepth = command[start + 2] === "(" ? 1 : undefined;
460
650
  const pendingHeredocs = [];
651
+ const cases = [];
461
652
  while (i < command.length) {
462
653
  const character = command[i];
463
- if (character === undefined)
654
+ if (character === undefined) {
464
655
  break;
465
- if (quote === "$'") {
466
- if (character === "'")
467
- quote = undefined;
468
- else if (character === "\\") {
469
- i = ansiEscape(command, i).end;
470
- continue;
471
- }
472
- i++;
473
- continue;
474
656
  }
475
- if (quote === "'") {
476
- if (character === "'")
477
- quote = undefined;
478
- i++;
657
+ const activeCase = cases.at(-1);
658
+ const consumedQuote = (() => {
659
+ if (quote === "$'") {
660
+ if (character === "'") {
661
+ quote = undefined;
662
+ } else if (character === "\\") {
663
+ i = ansiEscape(command, i).end;
664
+ return true;
665
+ }
666
+ i += 1;
667
+ return true;
668
+ }
669
+ if (quote === "'") {
670
+ if (character === "'") {
671
+ quote = undefined;
672
+ }
673
+ i += 1;
674
+ return true;
675
+ }
676
+ if (quote === '"') {
677
+ if (character === "\\") {
678
+ i += i + 1 < command.length ? 2 : 1;
679
+ } else if (character === '"') {
680
+ quote = undefined;
681
+ i += 1;
682
+ } else if (character === "$" && command[i + 1] === "(") {
683
+ i = consumeCommandSubstitution(command, i, nesting + 1).end;
684
+ } else if (character === "$" && command[i + 1] === "{") {
685
+ i = consumeQuotedParameter(command, i);
686
+ } else if (character === "`") {
687
+ i = consumeBackticks(command, i, true).end;
688
+ } else {
689
+ i += 1;
690
+ }
691
+ return true;
692
+ }
693
+ return false;
694
+ })();
695
+ if (consumedQuote) {
479
696
  continue;
480
697
  }
481
- if (quote === '"') {
698
+ const consumedEscapeOrHeredoc = (() => {
482
699
  if (character === "\\") {
700
+ if (command[i + 1] !== `
701
+ `) {
702
+ if (activeCase?.depth === depth && activeCase.phase === "pattern") {
703
+ activeCase.patternStart = false;
704
+ }
705
+ atWordStart = false;
706
+ atCommandStart = false;
707
+ }
483
708
  i += i + 1 < command.length ? 2 : 1;
484
- } else if (character === '"') {
485
- quote = undefined;
486
- i++;
487
- } else if (character === "$" && command[i + 1] === "(") {
488
- i = consumeCommandSubstitution(command, i, nesting + 1).end;
489
- } else if (character === "$" && command[i + 1] === "{") {
490
- i = consumeQuotedParameter(command, i);
491
- } else if (character === "`") {
492
- i = consumeBackticks(command, i, true).end;
493
- } else {
494
- i++;
709
+ return true;
495
710
  }
496
- continue;
497
- }
498
- if (character === "\\") {
499
- if (command[i + 1] !== `
500
- `) {
501
- atWordStart = false;
502
- atCommandStart = false;
711
+ if (arithmeticDepth === undefined && character === "<" && command[i + 1] === "<") {
712
+ if (command[i + 2] === "<") {
713
+ i += 3;
714
+ } else {
715
+ const parsed = tokenizeShellInput(command, i, true, nesting + 1);
716
+ if (parsed.delimiter === undefined) {
717
+ throw incompleteHeredoc();
718
+ }
719
+ pendingHeredocs.push(parsed.delimiter);
720
+ i = parsed.end;
721
+ }
722
+ atWordStart = true;
723
+ return true;
503
724
  }
504
- i += i + 1 < command.length ? 2 : 1;
505
- continue;
506
- }
507
- if (arithmeticDepth === undefined && character === "<" && command[i + 1] === "<") {
508
- if (command[i + 2] === "<") {
509
- i += 3;
510
- } else {
511
- const parsed = tokenizeShellInput(command, i, true, nesting + 1);
512
- if (parsed.delimiter === undefined)
513
- throw incompleteHeredoc();
514
- pendingHeredocs.push(parsed.delimiter);
515
- i = parsed.end;
725
+ if (character === `
726
+ ` && pendingHeredocs.length > 0) {
727
+ i += 1;
728
+ for (const heredoc of pendingHeredocs) {
729
+ i = consumeHeredoc(command, i, heredoc).end;
730
+ }
731
+ pendingHeredocs.length = 0;
732
+ atWordStart = true;
733
+ atCommandStart = true;
734
+ timeOption = false;
735
+ return true;
516
736
  }
517
- atWordStart = true;
737
+ return false;
738
+ })();
739
+ if (consumedEscapeOrHeredoc) {
518
740
  continue;
519
741
  }
520
- if (character === `
521
- ` && pendingHeredocs.length > 0) {
522
- i++;
523
- for (const heredoc of pendingHeredocs)
524
- i = consumeHeredoc(command, i, heredoc).end;
525
- pendingHeredocs.length = 0;
526
- atWordStart = true;
527
- atCommandStart = true;
528
- timeOption = false;
742
+ const consumedCaseTerminator = (() => {
743
+ if (activeCase?.depth === depth && activeCase.phase === "body" && character === ";" && (command[i + 1] === ";" || command[i + 1] === "&")) {
744
+ i += command.slice(i, i + 3) === ";;&" ? 3 : 2;
745
+ activeCase.phase = "pattern";
746
+ activeCase.patternStart = true;
747
+ atWordStart = true;
748
+ atCommandStart = true;
749
+ return true;
750
+ }
751
+ return false;
752
+ })();
753
+ if (consumedCaseTerminator) {
529
754
  continue;
530
755
  }
531
- if (atCommandStart && atWordStart && !isWordSeparator(character) && character !== "#") {
532
- let word = "";
533
- for (let end = i;end < command.length; end++) {
534
- const next = command[end];
535
- if (next === "\\" && command[end + 1] === `
756
+ (() => {
757
+ if ((atCommandStart || activeCase?.phase === "word" || activeCase?.phase === "in" || activeCase?.phase === "pattern") && atWordStart && !isWordSeparator(character) && character !== "#") {
758
+ const word = (() => {
759
+ let headerWord = "";
760
+ for (let end = i;end < command.length; end += 1) {
761
+ const next = command[end];
762
+ if (next === "\\" && command[end + 1] === `
536
763
  `) {
537
- end++;
538
- continue;
764
+ end += 1;
765
+ continue;
766
+ }
767
+ if (isWordSeparator(next)) {
768
+ break;
769
+ }
770
+ headerWord += next;
771
+ }
772
+ return headerWord;
773
+ })();
774
+ const patternWord = activeCase?.phase === "pattern";
775
+ (() => {
776
+ if (activeCase?.depth === depth && activeCase.phase === "word") {
777
+ activeCase.phase = "in";
778
+ } else if (activeCase?.depth === depth && activeCase.phase === "in") {
779
+ if (word !== "in") {
780
+ throw inspectionError("Cannot parse case header. Simplify the unsupported syntax.");
781
+ }
782
+ activeCase.phase = "pattern";
783
+ } else if (word === "esac" && activeCase?.depth === depth && (activeCase.phase !== "pattern" || activeCase.patternStart)) {
784
+ cases.pop();
785
+ } else if (word === "case" && activeCase?.phase !== "pattern") {
786
+ cases.push({ depth, phase: "word", patternStart: true });
787
+ }
788
+ })();
789
+ if (activeCase !== undefined && patternWord) {
790
+ activeCase.patternStart = false;
539
791
  }
540
- if (isWordSeparator(next))
541
- break;
542
- word += next;
792
+ if (!patternWord && (word === "function" || word === "coproc")) {
793
+ throw inspectionError("Cannot parse function or coproc declarations inside a command substitution. Run the declaration separately.");
794
+ }
795
+ (() => {
796
+ atCommandStart = timeOption && (word === "-p" || word === "--") || commandPrefixes.has(word) || word === "{";
797
+ timeOption = word === "time" || timeOption && word === "-p";
798
+ })();
543
799
  }
544
- if (word === "case") {
545
- throw new Error("Cannot parse case patterns inside a command substitution. Run the case command separately or run git commit directly.");
800
+ })();
801
+ const consumedQuotedStartOrSubstitution = (() => {
802
+ if (character === "$" && command[i + 1] === "'") {
803
+ quote = "$'";
804
+ atWordStart = false;
805
+ i += 2;
806
+ return true;
546
807
  }
547
- if (word === "function" || word === "coproc") {
548
- throw new Error("Cannot parse function or coproc declarations inside a command substitution. Run the declaration separately or run git commit directly.");
808
+ if (character === "'") {
809
+ quote = "'";
810
+ atWordStart = false;
811
+ i += 1;
812
+ return true;
549
813
  }
550
- atCommandStart = timeOption && (word === "-p" || word === "--") || commandPrefixes.has(word) || word === "{";
551
- timeOption = word === "time" || timeOption && word === "-p";
552
- }
553
- if (character === "$" && command[i + 1] === "'") {
554
- quote = "$'";
555
- atWordStart = false;
556
- i += 2;
557
- continue;
558
- }
559
- if (character === "'") {
560
- quote = "'";
561
- atWordStart = false;
562
- i++;
563
- continue;
564
- }
565
- if (character === '"') {
566
- quote = '"';
567
- atWordStart = false;
568
- i++;
569
- continue;
570
- }
571
- if (character === "#" && atWordStart) {
572
- while (i < command.length && command[i] !== `
573
- `)
574
- i++;
575
- continue;
576
- }
577
- if (character === "$" && command[i + 1] === "(") {
578
- i = consumeCommandSubstitution(command, i, nesting + 1).end;
579
- atWordStart = false;
814
+ if (character === '"') {
815
+ quote = '"';
816
+ atWordStart = false;
817
+ i += 1;
818
+ return true;
819
+ }
820
+ if (character === "#" && atWordStart) {
821
+ while (i < command.length && command[i] !== `
822
+ `) {
823
+ i += 1;
824
+ }
825
+ return true;
826
+ }
827
+ if (character === "$" && command[i + 1] === "(") {
828
+ i = consumeCommandSubstitution(command, i, nesting + 1).end;
829
+ atWordStart = false;
830
+ return true;
831
+ }
832
+ if (character === "`") {
833
+ i = consumeBackticks(command, i).end;
834
+ atWordStart = false;
835
+ return true;
836
+ }
837
+ return false;
838
+ })();
839
+ if (consumedQuotedStartOrSubstitution) {
580
840
  continue;
581
841
  }
582
- if (character === "`") {
583
- i = consumeBackticks(command, i).end;
584
- atWordStart = false;
585
- continue;
842
+ let completed;
843
+ const consumedParenthesis = (() => {
844
+ if (character === "(") {
845
+ if (activeCase?.depth === depth && activeCase.phase === "pattern") {
846
+ activeCase.patternStart = false;
847
+ i += 1;
848
+ atWordStart = true;
849
+ return true;
850
+ }
851
+ if (arithmeticDepth === undefined && atCommandStart && command[i + 1] === "(") {
852
+ arithmeticDepth = depth;
853
+ }
854
+ depth += 1;
855
+ i += 1;
856
+ atWordStart = true;
857
+ atCommandStart = true;
858
+ return true;
859
+ }
860
+ if (character === ")") {
861
+ if (activeCase?.depth === depth && activeCase.phase === "pattern") {
862
+ activeCase.phase = "body";
863
+ atCommandStart = true;
864
+ atWordStart = true;
865
+ i += 1;
866
+ return true;
867
+ }
868
+ depth -= 1;
869
+ if (depth === arithmeticDepth) {
870
+ arithmeticDepth = undefined;
871
+ }
872
+ if (depth === 0) {
873
+ if (pendingHeredocs.length > 0) {
874
+ throw incompleteHeredoc();
875
+ }
876
+ completed = { content: command.slice(start + 2, i), end: i + 1 };
877
+ return true;
878
+ }
879
+ atWordStart = true;
880
+ }
881
+ return false;
882
+ })();
883
+ if (completed !== undefined) {
884
+ return completed;
586
885
  }
587
- if (character === "(") {
588
- if (arithmeticDepth === undefined && atCommandStart && command[i + 1] === "(")
589
- arithmeticDepth = depth;
590
- depth++;
591
- i++;
592
- atWordStart = true;
593
- atCommandStart = true;
886
+ if (consumedParenthesis) {
594
887
  continue;
595
888
  }
596
- if (character === ")") {
597
- depth--;
598
- if (depth === arithmeticDepth)
599
- arithmeticDepth = undefined;
600
- if (depth === 0) {
601
- if (pendingHeredocs.length > 0)
602
- throw incompleteHeredoc();
603
- return { content: command.slice(start + 2, i), end: i + 1 };
604
- }
605
- atWordStart = true;
606
- }
607
889
  if ([";", "&", "|", `
608
890
  `, ")"].includes(character)) {
609
891
  atCommandStart = true;
610
892
  timeOption = false;
611
893
  }
612
- if (isWordSeparator(character))
613
- atWordStart = true;
614
- else
615
- atWordStart = false;
616
- i++;
894
+ atWordStart = isWordSeparator(character);
895
+ i += 1;
617
896
  }
618
- if (pendingHeredocs.length > 0)
897
+ if (pendingHeredocs.length > 0) {
619
898
  throw incompleteHeredoc();
620
- throw new Error(`Unterminated $( substitution starting at character ${start + 1}. Close it with ) or use single quotes for literal text.`);
621
- }
622
- function consumeBackticks(command, start, doubleQuoted = false) {
899
+ }
900
+ throw inspectionError(`Unterminated $( substitution starting at character ${start + 1}. Close it with ) or use single quotes for literal text.`);
901
+ };
902
+ var consumeBackticks = function consumeBackticks(command, start, doubleQuoted = false) {
623
903
  let content = "";
624
- for (let i = start + 1;i < command.length; i++) {
625
- if (command[i] === "`")
904
+ for (let i = start + 1;i < command.length; i += 1) {
905
+ if (command[i] === "`") {
626
906
  return { content, end: i + 1 };
627
- if (command[i] === "\\" && (["$", "`", "\\"].includes(command[i + 1] ?? "") || doubleQuoted && command[i + 1] === '"'))
628
- i++;
907
+ }
908
+ if (command[i] === "\\" && (["$", "`", "\\"].includes(command[i + 1] ?? "") || doubleQuoted && command[i + 1] === '"')) {
909
+ i += 1;
910
+ }
629
911
  content += command[i];
630
912
  }
631
- throw new Error(`Unterminated backtick substitution starting at character ${start + 1}. Close it, escape a literal backtick as \\\`, or use single quotes.`);
632
- }
633
- function consumeQuotedParameter(command, start) {
634
- for (let i = start + 2;i < command.length; i++) {
913
+ throw inspectionError(`Unterminated backtick substitution starting at character ${start + 1}. Close it, escape a literal backtick as \\\`, or use single quotes.`);
914
+ };
915
+ var consumeQuotedParameter = function consumeQuotedParameter(command, start, nesting = 0) {
916
+ if (nesting > 12) {
917
+ throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
918
+ }
919
+ let quote = false;
920
+ for (let i = start + 2;i < command.length; i += 1) {
635
921
  const character = command[i];
636
- if (character === "}")
922
+ if (character === "`" || character === "$" && command[i + 1] === "(") {
923
+ throw inspectionError("Cannot inspect command substitutions inside a double-quoted parameter expansion. Run substitutions separately or quote literal text.");
924
+ }
925
+ if (character === "\\") {
926
+ i += 1;
927
+ } else if (character === '"') {
928
+ quote = !quote;
929
+ } else if (character === "$" && command[i + 1] === "{") {
930
+ i = consumeQuotedParameter(command, i, nesting + 1) - 1;
931
+ } else if (character === "}" && !quote) {
637
932
  return i + 1;
638
- if (["'", '"', "\\", "`", "$", "{"].includes(character))
639
- break;
933
+ }
640
934
  }
641
- throw new Error('Cannot parse nested quoting or expansions in a double-quoted parameter expansion. Use a simple parameter such as "${HOME}" or run git commit directly.');
642
- }
643
- function ansiEscape(command, start) {
935
+ throw inspectionError("Cannot parse an incomplete double-quoted parameter expansion. Close its quotes and braces or quote literal text.");
936
+ };
937
+ var inspectionError = function inspectionError(message) {
938
+ return new Error(`[commit-guard] Pre-execution shell inspection failed: ${message}`);
939
+ };
940
+ var ansiEscape = function ansiEscape(command, start) {
644
941
  const escaped = command[start + 1] ?? "";
645
- const simple = new Map(Object.entries({ a: "\x07", b: "\b", e: "\x1B", E: "\x1B", f: "\f", n: `
646
- `, r: "\r", t: "\t", v: "\v", "\\": "\\", "'": "'", '"': '"', "?": "?" }));
942
+ const simple = new Map(Object.entries({
943
+ a: "\x07",
944
+ b: "\b",
945
+ e: "\x1B",
946
+ E: "\x1B",
947
+ f: "\f",
948
+ n: `
949
+ `,
950
+ r: "\r",
951
+ t: "\t",
952
+ v: "\v",
953
+ "\\": "\\",
954
+ "'": "'",
955
+ '"': '"',
956
+ "?": "?"
957
+ }));
647
958
  const literal = simple.get(escaped);
648
- if (literal !== undefined)
959
+ if (literal !== undefined) {
649
960
  return { content: literal, end: start + 2 };
961
+ }
650
962
  if (escaped === "c" && command[start + 2] !== undefined && command[start + 2] !== "'") {
651
963
  const character = command[start + 2];
652
964
  const end = start + (character === "\\" && command[start + 3] === "\\" ? 4 : 3);
653
- return { content: String.fromCharCode(character === "?" ? 127 : character.toUpperCase().charCodeAt(0) & 31), end };
965
+ return {
966
+ content: String.fromCodePoint(character === "?" ? 127 : (character.toUpperCase().codePointAt(0) ?? 0) & 31),
967
+ end
968
+ };
654
969
  }
655
- const count = escaped === "x" ? 2 : escaped === "u" ? 4 : escaped === "U" ? 8 : 0;
656
- const digits = count > 0 ? command.slice(start + 2).match(new RegExp(`^[0-9a-fA-F]{1,${count}}`))?.[0] : command.slice(start + 1).match(/^[0-7]{1,3}/)?.[0];
970
+ const count = new Map([
971
+ ["x", 2],
972
+ ["u", 4],
973
+ ["U", 8]
974
+ ]).get(escaped) ?? 0;
975
+ const digits = count > 0 ? new RegExp(`^[0-9a-fA-F]{1,${count}}`, "u").exec(command.slice(start + 2))?.[0] : /^[0-7]{1,3}/u.exec(command.slice(start + 1))?.[0];
657
976
  if (digits !== undefined) {
658
- const code = Number.parseInt(digits, count > 0 ? 16 : 8);
659
- if (code > 1114111)
660
- throw new Error("Cannot validate this ANSI-C escape. Supply the message literally.");
977
+ const radix = count > 0 ? 16 : 8;
978
+ const code = Number.parseInt(digits, radix);
979
+ if (code > 1114111) {
980
+ throw inspectionError("Cannot validate this ANSI-C escape. Supply literal text.");
981
+ }
661
982
  const end = start + (count > 0 ? 2 : 1) + digits.length;
662
- if (count === 0 || escaped === "x")
983
+ if (count === 0 || escaped === "x") {
663
984
  return { content: "", byte: code & 255, end };
985
+ }
664
986
  return { content: String.fromCodePoint(code), end };
665
987
  }
666
988
  return { content: `\\${escaped}`, end: start + 2 };
667
- }
668
- function pushWord(tokens, value, substitutions, expansion) {
989
+ };
990
+ var pushWord = function pushWord(tokens, value, substitutions, expansion) {
669
991
  const token = substitutions.length > 0 ? { type: "word", value, substitutions } : { type: "word", value };
670
992
  tokens.push(expansion ? { ...token, expansion: true } : token);
671
- }
672
- function heredocSubstitutions(body) {
993
+ };
994
+ var heredocSubstitutions = function heredocSubstitutions(body) {
673
995
  const substitutions = [];
674
- for (let i = 0;i < body.length; i++) {
996
+ for (let i = 0;i < body.length; i += 1) {
675
997
  if (body[i] === "\\" && ["\\", "$", "`"].includes(body[i + 1] ?? "")) {
676
- i++;
998
+ i += 1;
677
999
  } else if (body[i] === "`") {
678
- throw new Error("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.");
1000
+ throw inspectionError("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.");
679
1001
  } else if (body[i] === "$" && body[i + 1] === "(") {
680
1002
  const substitution = consumeCommandSubstitution(body, i);
681
1003
  substitutions.push(substitution.content);
@@ -683,11 +1005,11 @@ function heredocSubstitutions(body) {
683
1005
  }
684
1006
  }
685
1007
  return substitutions;
686
- }
687
- function incompleteHeredoc() {
688
- return new Error("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.");
689
- }
690
- function consumeHeredoc(command, start, heredoc) {
1008
+ };
1009
+ var incompleteHeredoc = function incompleteHeredoc() {
1010
+ return inspectionError("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.");
1011
+ };
1012
+ var consumeHeredoc = function consumeHeredoc(command, start, heredoc) {
691
1013
  let i = start;
692
1014
  let body = "";
693
1015
  while (i < command.length) {
@@ -696,10 +1018,10 @@ function consumeHeredoc(command, start, heredoc) {
696
1018
  while (i < command.length) {
697
1019
  const lineEnd = command.indexOf(`
698
1020
  `, i);
699
- const end = lineEnd < 0 ? command.length : lineEnd;
1021
+ const end = lineEnd === -1 ? command.length : lineEnd;
700
1022
  const physicalLine = command.slice(i, end);
701
- const backslashes = physicalLine.match(/\\+$/)?.[0].length ?? 0;
702
- newline = lineEnd >= 0;
1023
+ const backslashes = /\\+$/u.exec(physicalLine)?.[0].length ?? 0;
1024
+ newline = lineEnd !== -1;
703
1025
  i = newline ? end + 1 : end;
704
1026
  if (!heredoc.quoted && newline && backslashes % 2 === 1) {
705
1027
  line += physicalLine.slice(0, -1);
@@ -708,280 +1030,338 @@ function consumeHeredoc(command, start, heredoc) {
708
1030
  line += physicalLine;
709
1031
  break;
710
1032
  }
711
- if (heredoc.stripTabs)
712
- line = line.replace(/^\t+/, "");
713
- if (line === heredoc.delimiter)
1033
+ if (heredoc.stripTabs) {
1034
+ line = line.replace(/^\t+/u, "");
1035
+ }
1036
+ if (line === heredoc.delimiter) {
714
1037
  return { content: body, end: i };
1038
+ }
715
1039
  body += line + (newline ? `
716
1040
  ` : "");
717
1041
  }
718
1042
  throw incompleteHeredoc();
719
- }
720
- function tokenizeShell(command) {
1043
+ };
1044
+ var tokenizeShell = function tokenizeShell(command) {
721
1045
  return tokenizeShellInput(command).tokens;
722
- }
723
- function tokenizeShellInput(command, start = 0, delimiterOnly = false, nesting = 0) {
1046
+ };
1047
+ var tokenizeShellInput = function tokenizeShellInput(command, start = 0, delimiterOnly = false, nesting = 0) {
724
1048
  const tokens = [];
725
1049
  const pendingHeredocs = [];
726
1050
  let pendingDelimiter;
727
1051
  let i = start;
728
1052
  while (i < command.length) {
729
1053
  const character = command[i];
730
- if (character === undefined)
1054
+ if (character === undefined) {
731
1055
  break;
732
- if (character === " " || character === "\t" || character === "\r") {
733
- i++;
734
- continue;
735
1056
  }
736
- if (character === "\\" && command[i + 1] === `
1057
+ const skippedTrivia = (() => {
1058
+ if (character === " " || character === "\t" || character === "\r") {
1059
+ i += 1;
1060
+ return true;
1061
+ }
1062
+ if (character === "\\" && command[i + 1] === `
737
1063
  `) {
738
- i += 2;
739
- continue;
740
- }
741
- if (character === "#") {
742
- while (i < command.length && command[i] !== `
743
- `)
744
- i++;
1064
+ i += 2;
1065
+ return true;
1066
+ }
1067
+ if (character === "#") {
1068
+ while (i < command.length && command[i] !== `
1069
+ `) {
1070
+ i += 1;
1071
+ }
1072
+ return true;
1073
+ }
1074
+ return false;
1075
+ })();
1076
+ if (skippedTrivia) {
745
1077
  continue;
746
1078
  }
747
1079
  const twoCharacters = command.slice(i, i + 2);
748
1080
  let standaloneBrace = false;
749
- if (delimiterOnly && pendingDelimiter !== undefined && (isWordSeparator(character) || character === "<" || character === ">")) {
750
- throw incompleteHeredoc();
751
- }
1081
+ (() => {
1082
+ if (delimiterOnly && pendingDelimiter !== undefined && (isWordSeparator(character) || character === "<" || character === ">")) {
1083
+ throw incompleteHeredoc();
1084
+ }
1085
+ })();
752
1086
  if (character === "{" || character === "}") {
753
- let commandPosition = true;
754
- for (let index = tokens.length - 1;index >= 0; index--) {
755
- const token = tokens[index];
756
- if (token.type === "operator")
757
- break;
758
- if (token.type === "word") {
759
- const precedingWord = tokens[index - 1]?.type === "word" ? tokens[index - 1]?.value : undefined;
760
- if (index === tokens.length - 1 && token.value === "coproc")
761
- continue;
762
- if (token.value === "--" && (precedingWord === "time" || precedingWord === "-p" && tokens[index - 2]?.type === "word" && tokens[index - 2]?.value === "time"))
763
- continue;
764
- if (index === tokens.length - 1 && (precedingWord === "function" || precedingWord === "coproc") || precedingWord === "time" && token.value === "-p") {
765
- index--;
766
- continue;
1087
+ const braceCommandPosition = (() => {
1088
+ let commandPosition = true;
1089
+ for (let index = tokens.length - 1;index >= 0; index -= 1) {
1090
+ const token = tokens[index];
1091
+ if (token.type === "operator") {
1092
+ break;
1093
+ }
1094
+ if (token.type === "word") {
1095
+ const precedingWord = tokens[index - 1]?.type === "word" ? tokens[index - 1]?.value : undefined;
1096
+ if (index === tokens.length - 1 && token.value === "coproc") {
1097
+ continue;
1098
+ }
1099
+ const followsTime = () => precedingWord === "time" || precedingWord === "-p" && tokens[index - 2]?.type === "word" && tokens[index - 2]?.value === "time";
1100
+ if (token.value === "--" && followsTime()) {
1101
+ continue;
1102
+ }
1103
+ if (index === tokens.length - 1 && (precedingWord === "function" || precedingWord === "coproc") || precedingWord === "time" && token.value === "-p") {
1104
+ index -= 1;
1105
+ continue;
1106
+ }
1107
+ }
1108
+ if (token.type !== "word" || !commandPrefixes.has(token.value)) {
1109
+ commandPosition = false;
1110
+ break;
767
1111
  }
768
1112
  }
769
- if (token.type !== "word" || !commandPrefixes.has(token.value)) {
770
- commandPosition = false;
771
- break;
772
- }
773
- }
1113
+ return commandPosition;
1114
+ })();
774
1115
  let braceEnd = i + 1;
775
1116
  while (command[braceEnd] === "\\" && command[braceEnd + 1] === `
776
- `)
1117
+ `) {
777
1118
  braceEnd += 2;
778
- standaloneBrace = commandPosition && (command[braceEnd] === undefined || isWordSeparator(command[braceEnd]) || command[braceEnd] === "<" || command[braceEnd] === ">");
779
- }
780
- if (twoCharacters === "&&" || twoCharacters === "||" || twoCharacters === "|&" || twoCharacters === ";;") {
781
- tokens.push({ type: "operator", value: twoCharacters });
782
- i += 2;
783
- continue;
1119
+ }
1120
+ standaloneBrace = braceCommandPosition && (command[braceEnd] === undefined || isWordSeparator(command[braceEnd]) || command[braceEnd] === "<" || command[braceEnd] === ">");
784
1121
  }
785
- if (character === "|" || character === ";" || character === "&" && command[i + 1] !== ">" || character === `
1122
+ const consumedOperator = (() => {
1123
+ if (twoCharacters === "&&" || twoCharacters === "||" || twoCharacters === "|&" || twoCharacters === ";;") {
1124
+ tokens.push({ type: "operator", value: twoCharacters });
1125
+ i += 2;
1126
+ return true;
1127
+ }
1128
+ if (character === "|" || character === ";" || character === "&" && command[i + 1] !== ">" || character === `
786
1129
  ` || character === "(" || character === ")" || standaloneBrace) {
787
- tokens.push({ type: "operator", value: character });
788
- i++;
789
- if (character === `
1130
+ tokens.push({ type: "operator", value: character });
1131
+ i += 1;
1132
+ if (character === `
790
1133
  ` && pendingHeredocs.length > 0) {
791
- for (const heredoc of pendingHeredocs) {
792
- const body = consumeHeredoc(command, i, heredoc);
793
- i = body.end;
794
- tokens[heredoc.index] = {
795
- ...tokens[heredoc.index],
796
- heredoc: { body: body.content, quoted: heredoc.quoted },
797
- substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body.content)
798
- };
1134
+ for (const heredoc of pendingHeredocs) {
1135
+ const body = consumeHeredoc(command, i, heredoc);
1136
+ i = body.end;
1137
+ tokens[heredoc.index] = {
1138
+ ...tokens[heredoc.index],
1139
+ heredoc: { body: body.content, quoted: heredoc.quoted },
1140
+ substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body.content)
1141
+ };
1142
+ }
1143
+ pendingHeredocs.length = 0;
799
1144
  }
800
- pendingHeredocs.length = 0;
1145
+ return true;
801
1146
  }
1147
+ return false;
1148
+ })();
1149
+ if (consumedOperator) {
802
1150
  continue;
803
1151
  }
804
- const redirectMatch = command.slice(i).match(/^(?:\d+)?(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)|^&>>?/);
1152
+ const redirectMatch = /^(?:\d+)?(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)|^&>>?/u.exec(command.slice(i));
805
1153
  if (redirectMatch !== null && redirectMatch[0] !== undefined) {
806
1154
  tokens.push({ type: "redirect", value: redirectMatch[0] });
807
- if (/^\d*<<-?$/.test(redirectMatch[0]))
1155
+ if (/^\d*<<-?$/u.test(redirectMatch[0])) {
808
1156
  pendingDelimiter = tokens.length - 1;
1157
+ }
809
1158
  i += redirectMatch[0].length;
810
1159
  continue;
811
1160
  }
812
- let value = "";
813
- const wordBytes = [];
814
- let quoted = false;
815
- let unsupportedDelimiter;
816
- let expansion = false;
817
- const substitutions = [];
818
- while (i < command.length) {
819
- const current = command[i];
820
- if (current === undefined || isWordSeparator(current))
821
- break;
822
- if (current === "\\" && command[i + 1] === `
1161
+ const result = (() => {
1162
+ let value = "";
1163
+ const wordBytes = [];
1164
+ let quoted = false;
1165
+ let unsupportedDelimiter;
1166
+ let expansion = false;
1167
+ const substitutions = [];
1168
+ while (i < command.length) {
1169
+ const current = command[i];
1170
+ if (current === undefined || isWordSeparator(current)) {
1171
+ break;
1172
+ }
1173
+ if (current === "\\" && command[i + 1] === `
823
1174
  `) {
824
- i += 2;
825
- continue;
826
- }
827
- if (current === "\\") {
828
- quoted = true;
829
- if (i + 1 < command.length) {
830
- value += command[i + 1];
831
1175
  i += 2;
832
- } else {
833
- value += "\\";
834
- i++;
1176
+ continue;
835
1177
  }
836
- continue;
837
- }
838
- if (current === "$") {
839
- let quoteStart = i + 1;
840
- while (command[quoteStart] === "\\" && command[quoteStart + 1] === `
841
- `)
842
- quoteStart += 2;
843
- if (command[quoteStart] === '"')
844
- unsupportedDelimiter = "locale-quoted";
845
- else if (command[quoteStart] === "'")
846
- unsupportedDelimiter = "ANSI-C quoted";
847
- }
848
- if (current === "$" && command[i + 1] === "'") {
849
- const quoteStart = i;
850
- wordBytes.push(...Buffer.from(value));
851
- value = "";
852
- quoted = true;
853
- unsupportedDelimiter = "ANSI-C quoted";
854
- i += 2;
855
- const bytes = [];
856
- let complete = false;
857
- while (i < command.length) {
858
- const ansiCharacter = command[i];
859
- if (ansiCharacter === undefined)
860
- break;
861
- if (ansiCharacter === "'") {
862
- i++;
863
- complete = true;
864
- break;
865
- }
866
- if (ansiCharacter === "\\" && i + 1 < command.length) {
867
- const escaped = ansiEscape(command, i);
868
- bytes.push(...escaped.byte === undefined ? Buffer.from(escaped.content) : [escaped.byte]);
869
- i = escaped.end;
1178
+ if (current === "\\") {
1179
+ quoted = true;
1180
+ if (i + 1 < command.length) {
1181
+ value += command[i + 1];
1182
+ i += 2;
870
1183
  } else {
871
- const literal = String.fromCodePoint(command.codePointAt(i));
872
- bytes.push(...Buffer.from(literal));
873
- i += literal.length;
1184
+ value += "\\";
1185
+ i += 1;
874
1186
  }
1187
+ continue;
875
1188
  }
876
- if (!complete)
877
- throw new Error(`Unterminated ANSI-C quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
878
- const nul = bytes.indexOf(0);
879
- wordBytes.push(...nul < 0 ? bytes : bytes.slice(0, nul));
880
- continue;
881
- }
882
- if (current === "'") {
883
- const quoteStart = i;
884
- quoted = true;
885
- i++;
886
- while (i < command.length && command[i] !== "'") {
887
- value += command[i];
888
- i++;
889
- }
890
- if (command[i] !== "'")
891
- throw new Error(`Unterminated single quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
892
- i++;
893
- continue;
894
- }
895
- if (current === '"') {
896
- const quoteStart = i;
897
- quoted = true;
898
- i++;
899
- while (i < command.length && command[i] !== '"') {
900
- const quotedCharacter = command[i];
901
- if (quotedCharacter === undefined)
902
- break;
903
- if (quotedCharacter === "\\" && i + 1 < command.length) {
904
- const escaped = command[i + 1];
905
- if (escaped === `
1189
+ (() => {
1190
+ if (current === "$") {
1191
+ let quoteStart = i + 1;
1192
+ while (command[quoteStart] === "\\" && command[quoteStart + 1] === `
906
1193
  `) {
907
- i += 2;
908
- } else if (escaped === '"' || escaped === "\\" || escaped === "$" || escaped === "`") {
909
- value += escaped;
910
- i += 2;
911
- } else {
912
- value += `\\${escaped}`;
913
- i += 2;
1194
+ quoteStart += 2;
1195
+ }
1196
+ if (command[quoteStart] === '"') {
1197
+ unsupportedDelimiter = "locale-quoted";
1198
+ } else if (command[quoteStart] === "'") {
1199
+ unsupportedDelimiter = "ANSI-C quoted";
914
1200
  }
915
- } else if (quotedCharacter === "$" && command[i + 1] === "(") {
916
- const substitution = consumeCommandSubstitution(command, i, nesting);
917
- value += command.slice(i, substitution.end);
918
- substitutions.push(substitution.content);
919
- expansion = true;
920
- i = substitution.end;
921
- } else if (quotedCharacter === "$" && command[i + 1] === "{") {
922
- const end = consumeQuotedParameter(command, i);
923
- value += command.slice(i, end);
924
- expansion = true;
925
- i = end;
926
- } else if (quotedCharacter === "`") {
927
- const substitution = consumeBackticks(command, i, true);
928
- value += command.slice(i, substitution.end);
929
- substitutions.push(substitution.content);
930
- expansion = true;
931
- i = substitution.end;
932
- } else {
933
- if (quotedCharacter === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? ""))
934
- expansion = true;
935
- value += quotedCharacter;
936
- i++;
937
1201
  }
1202
+ })();
1203
+ if (current === "$" && command[i + 1] === "'") {
1204
+ (() => {
1205
+ const quoteStart = i;
1206
+ wordBytes.push(...Buffer.from(value));
1207
+ value = "";
1208
+ quoted = true;
1209
+ unsupportedDelimiter = "ANSI-C quoted";
1210
+ i += 2;
1211
+ const bytes = [];
1212
+ let complete = false;
1213
+ while (i < command.length) {
1214
+ const ansiCharacter = command[i];
1215
+ if (ansiCharacter === undefined) {
1216
+ break;
1217
+ }
1218
+ if (ansiCharacter === "'") {
1219
+ i += 1;
1220
+ complete = true;
1221
+ break;
1222
+ }
1223
+ if (ansiCharacter === "\\" && i + 1 < command.length) {
1224
+ const escaped = ansiEscape(command, i);
1225
+ bytes.push(...escaped.byte === undefined ? Buffer.from(escaped.content) : [escaped.byte]);
1226
+ i = escaped.end;
1227
+ } else {
1228
+ const literal = String.fromCodePoint(command.codePointAt(i) ?? 0);
1229
+ bytes.push(...Buffer.from(literal));
1230
+ i += literal.length;
1231
+ }
1232
+ }
1233
+ if (!complete) {
1234
+ throw inspectionError(`Unterminated ANSI-C quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
1235
+ }
1236
+ const nul = bytes.indexOf(0);
1237
+ wordBytes.push(...nul === -1 ? bytes : bytes.slice(0, nul));
1238
+ })();
1239
+ continue;
938
1240
  }
939
- if (command[i] !== '"')
940
- throw new Error(`Unterminated double quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
941
- i++;
942
- continue;
943
- }
944
- if (current === "$" && command[i + 1] === "(") {
945
- const substitution = consumeCommandSubstitution(command, i, nesting);
946
- value += command.slice(i, substitution.end);
947
- substitutions.push(substitution.content);
948
- expansion = true;
949
- i = substitution.end;
950
- continue;
951
- }
952
- if (current === "`") {
953
- const substitution = consumeBackticks(command, i);
954
- value += command.slice(i, substitution.end);
955
- substitutions.push(substitution.content);
956
- expansion = true;
957
- i = substitution.end;
958
- continue;
1241
+ if (current === "'") {
1242
+ (() => {
1243
+ const quoteStart = i;
1244
+ quoted = true;
1245
+ i += 1;
1246
+ while (i < command.length && command[i] !== "'") {
1247
+ value += command[i];
1248
+ i += 1;
1249
+ }
1250
+ if (command[i] !== "'") {
1251
+ throw inspectionError(`Unterminated single quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
1252
+ }
1253
+ i += 1;
1254
+ })();
1255
+ continue;
1256
+ }
1257
+ if (current === '"') {
1258
+ (() => {
1259
+ const quoteStart = i;
1260
+ quoted = true;
1261
+ i += 1;
1262
+ while (i < command.length && command[i] !== '"') {
1263
+ const quotedCharacter = command[i];
1264
+ if (quotedCharacter === undefined) {
1265
+ break;
1266
+ }
1267
+ if (quotedCharacter === "\\" && i + 1 < command.length) {
1268
+ const escaped = command[i + 1];
1269
+ if (escaped === `
1270
+ `) {} else if (escaped === '"' || escaped === "\\" || escaped === "$" || escaped === "`") {
1271
+ value += escaped;
1272
+ } else {
1273
+ value += `\\${escaped}`;
1274
+ }
1275
+ i += 2;
1276
+ } else if (quotedCharacter === "$" && command[i + 1] === "(") {
1277
+ const substitution = consumeCommandSubstitution(command, i, nesting);
1278
+ value += command.slice(i, substitution.end);
1279
+ substitutions.push(substitution.content);
1280
+ expansion = true;
1281
+ i = substitution.end;
1282
+ } else if (quotedCharacter === "$" && command[i + 1] === "{") {
1283
+ const end = consumeQuotedParameter(command, i);
1284
+ value += command.slice(i, end);
1285
+ expansion = true;
1286
+ i = end;
1287
+ } else if (quotedCharacter === "`") {
1288
+ const substitution = consumeBackticks(command, i, true);
1289
+ value += command.slice(i, substitution.end);
1290
+ substitutions.push(substitution.content);
1291
+ expansion = true;
1292
+ i = substitution.end;
1293
+ } else {
1294
+ if (quotedCharacter === "$" && /[a-zA-Z0-9_{[*#?@!$-]/u.test(command[i + 1] ?? "")) {
1295
+ expansion = true;
1296
+ }
1297
+ value += quotedCharacter;
1298
+ i += 1;
1299
+ }
1300
+ }
1301
+ if (command[i] !== '"') {
1302
+ throw inspectionError(`Unterminated double quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
1303
+ }
1304
+ i += 1;
1305
+ })();
1306
+ continue;
1307
+ }
1308
+ if (current === "$" && command[i + 1] === "(") {
1309
+ const substitution = consumeCommandSubstitution(command, i, nesting);
1310
+ value += command.slice(i, substitution.end);
1311
+ substitutions.push(substitution.content);
1312
+ expansion = true;
1313
+ i = substitution.end;
1314
+ continue;
1315
+ }
1316
+ if (current === "`") {
1317
+ const substitution = consumeBackticks(command, i);
1318
+ value += command.slice(i, substitution.end);
1319
+ substitutions.push(substitution.content);
1320
+ expansion = true;
1321
+ i = substitution.end;
1322
+ continue;
1323
+ }
1324
+ if (current === "$" && /[a-zA-Z0-9_{[*#?@!$-]/u.test(command[i + 1] ?? "")) {
1325
+ expansion = true;
1326
+ }
1327
+ const nextRedirect = /^(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)/u.exec(command.slice(i));
1328
+ if (nextRedirect !== null) {
1329
+ break;
1330
+ }
1331
+ value += current;
1332
+ i += 1;
959
1333
  }
960
- if (current === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? ""))
961
- expansion = true;
962
- const nextRedirect = command.slice(i).match(/^(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)/);
963
- if (nextRedirect !== null)
964
- break;
965
- value += current;
966
- i++;
967
- }
968
- if (wordBytes.length > 0)
969
- value = Buffer.from([...wordBytes, ...Buffer.from(value)]).toString("utf8");
970
- pushWord(tokens, value, substitutions, expansion);
971
- if (pendingDelimiter !== undefined) {
972
- if (unsupportedDelimiter !== undefined) {
973
- throw new Error(`Cannot validate this ${unsupportedDelimiter} heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.`);
974
- }
975
- const delimiter = { delimiter: value, quoted, stripTabs: tokens[pendingDelimiter]?.value.endsWith("-") === true };
976
- if (delimiterOnly)
977
- return { tokens, end: i, delimiter };
978
- pendingHeredocs.push({ index: pendingDelimiter, ...delimiter });
979
- pendingDelimiter = undefined;
1334
+ const finishedWord = (() => {
1335
+ if (wordBytes.length > 0) {
1336
+ value = Buffer.from([...wordBytes, ...Buffer.from(value)]).toString("utf-8");
1337
+ }
1338
+ pushWord(tokens, value, substitutions, expansion);
1339
+ if (pendingDelimiter !== undefined) {
1340
+ if (unsupportedDelimiter !== undefined) {
1341
+ throw inspectionError(`Cannot validate this ${unsupportedDelimiter} heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.`);
1342
+ }
1343
+ const delimiter = {
1344
+ delimiter: value,
1345
+ quoted,
1346
+ stripTabs: tokens[pendingDelimiter]?.value.endsWith("-")
1347
+ };
1348
+ if (delimiterOnly) {
1349
+ return { tokens, end: i, delimiter };
1350
+ }
1351
+ pendingHeredocs.push({ index: pendingDelimiter, ...delimiter });
1352
+ pendingDelimiter = undefined;
1353
+ }
1354
+ return null;
1355
+ })();
1356
+ return finishedWord;
1357
+ })();
1358
+ if (result !== null) {
1359
+ return result;
980
1360
  }
981
1361
  }
982
1362
  return { tokens, end: i };
983
- }
984
- function splitSimpleCommands(tokens) {
1363
+ };
1364
+ var splitSimpleCommands = function splitSimpleCommands(tokens) {
985
1365
  const commands = [];
986
1366
  let current = [];
987
1367
  let precedingPipeline = false;
@@ -989,51 +1369,56 @@ function splitSimpleCommands(tokens) {
989
1369
  if (token.type === "operator") {
990
1370
  const isPipeline = token.value === "|" || token.value === "|&";
991
1371
  const hasCommand = current.length > 0;
992
- if (hasCommand)
993
- commands.push({ tokens: current, pipeline: precedingPipeline || isPipeline });
1372
+ if (hasCommand) {
1373
+ commands.push({
1374
+ tokens: current,
1375
+ pipeline: precedingPipeline || isPipeline
1376
+ });
1377
+ }
994
1378
  current = [];
995
1379
  if (hasCommand || token.value !== `
996
- `)
1380
+ `) {
997
1381
  precedingPipeline = isPipeline;
1382
+ }
998
1383
  } else {
999
1384
  current.push(token);
1000
1385
  }
1001
1386
  }
1002
- if (current.length > 0)
1387
+ if (current.length > 0) {
1003
1388
  commands.push({ tokens: current, pipeline: precedingPipeline });
1389
+ }
1004
1390
  return commands;
1005
- }
1006
- function extractCommandWords(tokens) {
1391
+ };
1392
+ var extractCommandWords = function extractCommandWords(tokens) {
1007
1393
  const words = [];
1008
1394
  let i = 0;
1009
1395
  while (i < tokens.length) {
1010
1396
  const token = tokens[i];
1011
- if (token === undefined)
1397
+ if (token === undefined) {
1012
1398
  break;
1399
+ }
1013
1400
  if (token.type === "redirect") {
1014
- if (tokens[i + 1]?.type === "word")
1015
- i += 2;
1016
- else
1017
- i++;
1401
+ i += tokens[i + 1]?.type === "word" ? 2 : 1;
1018
1402
  continue;
1019
1403
  }
1020
1404
  if (token.type === "word") {
1021
1405
  words.push(token);
1022
1406
  }
1023
- i++;
1407
+ i += 1;
1024
1408
  }
1025
1409
  return words;
1026
- }
1027
- function isAssignment(word) {
1028
- return /^[a-zA-Z_][a-zA-Z0-9_]*=/.test(word);
1029
- }
1030
- function skipAssignments(words, start) {
1410
+ };
1411
+ var isAssignment = function isAssignment(word) {
1412
+ return /^[a-zA-Z_][a-zA-Z0-9_]*=/u.test(word);
1413
+ };
1414
+ var skipAssignments = function skipAssignments(words, start) {
1031
1415
  let index = start;
1032
- while (words[index] !== undefined && isAssignment(words[index]))
1033
- index++;
1416
+ while (words[index] !== undefined && isAssignment(words[index])) {
1417
+ index += 1;
1418
+ }
1034
1419
  return index;
1035
- }
1036
- function findCommandStart(words) {
1420
+ };
1421
+ var findCommandStart = function findCommandStart(words) {
1037
1422
  let index = skipAssignments(words, 0);
1038
1423
  while (index < words.length) {
1039
1424
  const word = words[index];
@@ -1042,109 +1427,132 @@ function findCommandStart(words) {
1042
1427
  continue;
1043
1428
  }
1044
1429
  if (word === "env") {
1045
- index++;
1046
- while (index < words.length) {
1047
- const argument = words[index];
1048
- if (argument === undefined)
1049
- break;
1050
- if (argument === "--") {
1051
- index++;
1052
- break;
1053
- }
1054
- if (argument === "-u" || argument === "--unset") {
1055
- index += 2;
1056
- } else if (argument === "-C" || argument === "--chdir") {
1057
- index += 2;
1058
- } else if (argument.startsWith("--chdir=") || /^-C.+/.test(argument)) {
1059
- index++;
1060
- } else if (argument.startsWith("--unset=") || /^-u.+/.test(argument)) {
1061
- index++;
1062
- } else if (argument.startsWith("-")) {
1063
- index++;
1064
- } else if (isAssignment(argument)) {
1065
- index++;
1066
- } else {
1067
- break;
1430
+ index += 1;
1431
+ (() => {
1432
+ while (index < words.length) {
1433
+ const argument = words[index];
1434
+ if (argument === undefined) {
1435
+ break;
1436
+ }
1437
+ if (argument === "--") {
1438
+ index += 1;
1439
+ break;
1440
+ }
1441
+ if (argument === "-u" || argument === "--unset") {
1442
+ index += 2;
1443
+ } else if (argument === "-C" || argument === "--chdir") {
1444
+ index += 2;
1445
+ } else if (argument.startsWith("--chdir=") || /^-C.+/u.test(argument)) {
1446
+ index += 1;
1447
+ } else if (argument.startsWith("--unset=") || /^-u.+/u.test(argument)) {
1448
+ index += 1;
1449
+ } else if (argument.startsWith("-")) {
1450
+ index += 1;
1451
+ } else if (isAssignment(argument)) {
1452
+ index += 1;
1453
+ } else {
1454
+ break;
1455
+ }
1068
1456
  }
1069
- }
1457
+ })();
1070
1458
  index = skipAssignments(words, index);
1071
1459
  continue;
1072
1460
  }
1073
1461
  if (word === "exec") {
1074
- index++;
1462
+ index += 1;
1075
1463
  while (index < words.length) {
1076
1464
  const argument = words[index];
1077
1465
  if (argument === "--") {
1078
- index++;
1466
+ index += 1;
1079
1467
  break;
1080
1468
  }
1081
- if (argument === "-a")
1469
+ if (argument === "-a") {
1082
1470
  index += 2;
1083
- else if (argument !== undefined && argument.startsWith("-"))
1084
- index++;
1085
- else
1471
+ } else if (argument !== undefined && argument.startsWith("-")) {
1472
+ index += 1;
1473
+ } else {
1086
1474
  break;
1475
+ }
1087
1476
  }
1088
1477
  index = skipAssignments(words, index);
1089
1478
  continue;
1090
1479
  }
1091
1480
  if (word === "command" || word === "nohup" || word === "builtin") {
1092
- index++;
1093
- while (words[index]?.startsWith("-"))
1094
- index++;
1481
+ index += 1;
1482
+ while (words[index]?.startsWith("-")) {
1483
+ index += 1;
1484
+ }
1095
1485
  index = skipAssignments(words, index);
1096
1486
  continue;
1097
1487
  }
1098
1488
  break;
1099
1489
  }
1100
1490
  return index;
1101
- }
1102
- function extractInvocation(words, commandStart, wordTokens) {
1491
+ };
1492
+ var extractInvocation = function extractInvocation(words, commandStart, wordTokens) {
1103
1493
  let wordIndex = commandStart;
1104
1494
  const executable = words[wordIndex];
1105
- if (executable === undefined || executable !== "git" && !executable.endsWith("/git"))
1495
+ if (executable === undefined || executable !== "git" && !executable.endsWith("/git")) {
1106
1496
  return;
1107
- wordIndex++;
1497
+ }
1498
+ wordIndex += 1;
1108
1499
  let subcommand;
1109
1500
  let targetError = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word) || word === "export") ? "Environment or wrapper changes can redirect a Git commit target. Use a direct git commit in the captured workdir." : undefined;
1110
- while (wordIndex < words.length) {
1111
- const argument = words[wordIndex];
1112
- if (argument === undefined)
1113
- break;
1114
- if (argument === "--") {
1115
- subcommand = words[wordIndex + 1];
1116
- wordIndex += 2;
1117
- break;
1118
- }
1119
- if (gitGlobalOptionsWithArg.has(argument)) {
1120
- if (argument === "-C" || argument === "--git-dir" || argument === "--work-tree" || argument === "-c" || argument === "--config-env") {
1121
- targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
1501
+ const readSubcommand = () => {
1502
+ while (wordIndex < words.length) {
1503
+ const argument = words[wordIndex];
1504
+ if (argument === undefined) {
1505
+ break;
1122
1506
  }
1123
- wordIndex += 2;
1124
- continue;
1125
- }
1126
- if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--namespace=") || argument.startsWith("--exec-path=") || argument.startsWith("--super-prefix=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
1127
- if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
1128
- targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
1507
+ if (wordTokens[wordIndex]?.expansion === true) {
1508
+ throw inspectionError("Cannot inspect dynamic Git options or subcommands. Use literal command words.");
1129
1509
  }
1130
- wordIndex++;
1131
- continue;
1132
- }
1133
- if (argument.startsWith("-C")) {
1134
- targetError = "git -C can change the commit target. Run git commit directly in the captured workdir.";
1135
- wordIndex++;
1136
- continue;
1137
- }
1138
- if (argument.startsWith("-")) {
1139
- wordIndex++;
1140
- continue;
1510
+ if (argument === "--") {
1511
+ if (wordTokens[wordIndex + 1]?.expansion === true) {
1512
+ throw inspectionError("Cannot inspect a dynamic Git subcommand. Use literal command words.");
1513
+ }
1514
+ subcommand = words[wordIndex + 1];
1515
+ wordIndex += 2;
1516
+ break;
1517
+ }
1518
+ if (gitGlobalOptionsWithArg.has(argument)) {
1519
+ if (["-C", "--git-dir", "--work-tree", "-c", "--config-env"].includes(argument)) {
1520
+ targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
1521
+ }
1522
+ wordIndex += 2;
1523
+ continue;
1524
+ }
1525
+ const consumedAttachedGlobal = (() => {
1526
+ if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--namespace=") || argument.startsWith("--exec-path=") || argument.startsWith("--super-prefix=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
1527
+ if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
1528
+ targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
1529
+ }
1530
+ wordIndex += 1;
1531
+ return true;
1532
+ }
1533
+ return false;
1534
+ })();
1535
+ if (consumedAttachedGlobal) {
1536
+ continue;
1537
+ }
1538
+ if (argument.startsWith("-C")) {
1539
+ targetError = "git -C can change the commit target. Run git commit directly in the captured workdir.";
1540
+ wordIndex += 1;
1541
+ continue;
1542
+ }
1543
+ if (argument.startsWith("-")) {
1544
+ wordIndex += 1;
1545
+ continue;
1546
+ }
1547
+ subcommand = argument;
1548
+ wordIndex += 1;
1549
+ break;
1141
1550
  }
1142
- subcommand = argument;
1143
- wordIndex++;
1144
- break;
1145
- }
1146
- if (subcommand !== "commit")
1551
+ };
1552
+ readSubcommand();
1553
+ if (subcommand !== "commit") {
1147
1554
  return;
1555
+ }
1148
1556
  const messages = [];
1149
1557
  const filePaths = [];
1150
1558
  let hasSignoffFlag = false;
@@ -1155,87 +1563,118 @@ function extractInvocation(words, commandStart, wordTokens) {
1155
1563
  let messageExpansion = false;
1156
1564
  let hasTrailer = false;
1157
1565
  const collectMessage = (word) => {
1158
- if (word === undefined)
1566
+ if (word === undefined) {
1159
1567
  return;
1568
+ }
1160
1569
  messages.push(word);
1161
1570
  };
1162
1571
  const collectFile = (word) => {
1163
- if (word === undefined)
1572
+ if (word === undefined) {
1164
1573
  return;
1574
+ }
1165
1575
  filePaths.push(word);
1166
1576
  };
1167
- for (let index = wordIndex;index < words.length; index++) {
1577
+ for (let index = wordIndex;index < words.length; index += 1) {
1168
1578
  const argument = words[index];
1169
- if (argument === undefined)
1579
+ if (argument === undefined) {
1170
1580
  break;
1581
+ }
1171
1582
  const equalsIndex = argument.indexOf("=");
1172
1583
  const longOptionName = equalsIndex > 0 ? argument.slice(0, equalsIndex) : argument;
1173
- if (argument === "--")
1584
+ if (argument === "--") {
1174
1585
  break;
1175
- if (argument === "-h" || argument === "--help") {
1176
- isHelp = true;
1177
- } else if (argument === "--amend") {
1178
- isAmend = true;
1179
- } else if (argument === "--no-edit") {
1180
- hasNoEdit = true;
1181
- } else if (argument === "--edit") {
1182
- hasNoEdit = false;
1183
- } else if (argument === "-s" || argument === "--signoff") {
1184
- hasSignoffFlag = true;
1185
- } else if (argument === "--no-signoff") {
1186
- hasSignoffFlag = false;
1187
- } else if (argument === "-m" || argument === "--message") {
1188
- index++;
1189
- messageExpansion ||= wordTokens[index]?.expansion === true;
1190
- collectMessage(words[index]);
1191
- } else if (argument.startsWith("--message=")) {
1192
- messageExpansion ||= wordTokens[index]?.expansion === true;
1193
- collectMessage(argument.slice("--message=".length));
1194
- } else if (argument === "-F" || argument === "--file") {
1195
- index++;
1196
- collectFile(words[index]);
1197
- } else if (argument.startsWith("--file=")) {
1198
- collectFile(argument.slice("--file=".length));
1199
- } else if (argument === "--fixup" || argument.startsWith("--fixup=")) {
1200
- isFixup = true;
1201
- if (equalsIndex < 0)
1202
- index++;
1203
- } else if (longOptionName === "--trailer") {
1204
- hasTrailer = true;
1205
- if (equalsIndex < 0)
1206
- index++;
1207
- } else if (commitLongOptionsWithArg.has(longOptionName)) {
1208
- if (equalsIndex < 0)
1209
- index++;
1210
- } else if (argument.startsWith("-") && !argument.startsWith("--") && argument.length > 1) {
1211
- for (let characterIndex = 1;characterIndex < argument.length; characterIndex++) {
1212
- const option = argument[characterIndex];
1213
- if (option === "s") {
1214
- hasSignoffFlag = true;
1215
- } else if (option === "h") {
1216
- isHelp = true;
1217
- } else if (option === "e") {
1218
- hasNoEdit = false;
1219
- } else if (option === "m" || option === "F") {
1220
- const attached = argument.slice(characterIndex + 1);
1221
- const input = attached.length > 0 ? attached : words[++index];
1222
- if (option === "m") {
1223
- messageExpansion ||= wordTokens[index]?.expansion === true;
1224
- collectMessage(input);
1225
- } else
1226
- collectFile(input);
1227
- break;
1228
- } else if (option === "S") {
1229
- break;
1230
- } else if (option === "u") {
1231
- break;
1232
- } else if (option === "c" || option === "C" || option === "t") {
1233
- if (argument.slice(characterIndex + 1).length === 0)
1234
- index++;
1235
- break;
1236
- }
1586
+ }
1587
+ const consumedBooleanFlag = (() => {
1588
+ if (argument === "-h" || argument === "--help") {
1589
+ isHelp = true;
1590
+ } else if (argument === "--amend") {
1591
+ isAmend = true;
1592
+ } else if (argument === "--no-edit") {
1593
+ hasNoEdit = true;
1594
+ } else if (argument === "--edit") {
1595
+ hasNoEdit = false;
1596
+ } else if (argument === "-s" || argument === "--signoff") {
1597
+ hasSignoffFlag = true;
1598
+ } else if (argument === "--no-signoff") {
1599
+ hasSignoffFlag = false;
1600
+ } else {
1601
+ return false;
1237
1602
  }
1603
+ return true;
1604
+ })();
1605
+ if (consumedBooleanFlag) {
1606
+ continue;
1238
1607
  }
1608
+ const consumedMessageOption = (() => {
1609
+ if (argument === "-m" || argument === "--message") {
1610
+ index += 1;
1611
+ messageExpansion ||= wordTokens[index]?.expansion === true;
1612
+ collectMessage(words[index]);
1613
+ } else if (argument.startsWith("--message=")) {
1614
+ messageExpansion ||= wordTokens[index]?.expansion === true;
1615
+ collectMessage(argument.slice("--message=".length));
1616
+ } else if (argument === "-F" || argument === "--file") {
1617
+ index += 1;
1618
+ collectFile(words[index]);
1619
+ } else if (argument.startsWith("--file=")) {
1620
+ collectFile(argument.slice("--file=".length));
1621
+ } else {
1622
+ return false;
1623
+ }
1624
+ return true;
1625
+ })();
1626
+ if (consumedMessageOption) {
1627
+ continue;
1628
+ }
1629
+ (() => {
1630
+ if (argument === "--fixup" || argument.startsWith("--fixup=")) {
1631
+ isFixup = true;
1632
+ if (equalsIndex === -1) {
1633
+ index += 1;
1634
+ }
1635
+ } else if (longOptionName === "--trailer") {
1636
+ hasTrailer = true;
1637
+ if (equalsIndex === -1) {
1638
+ index += 1;
1639
+ }
1640
+ } else if (commitLongOptionsWithArg.has(longOptionName)) {
1641
+ if (equalsIndex === -1) {
1642
+ index += 1;
1643
+ }
1644
+ } else if (argument.startsWith("-") && !argument.startsWith("--") && argument.length > 1) {
1645
+ (() => {
1646
+ for (let characterIndex = 1;characterIndex < argument.length; characterIndex += 1) {
1647
+ const option = argument[characterIndex];
1648
+ if (option === "s") {
1649
+ hasSignoffFlag = true;
1650
+ } else if (option === "h") {
1651
+ isHelp = true;
1652
+ } else if (option === "e") {
1653
+ hasNoEdit = false;
1654
+ } else if (option === "m" || option === "F") {
1655
+ const attached = argument.slice(characterIndex + 1);
1656
+ const input = attached.length > 0 ? attached : words[index += 1];
1657
+ if (option === "m") {
1658
+ messageExpansion ||= wordTokens[index]?.expansion === true;
1659
+ collectMessage(input);
1660
+ } else {
1661
+ collectFile(input);
1662
+ }
1663
+ break;
1664
+ } else if (option === "S") {
1665
+ break;
1666
+ } else if (option === "u") {
1667
+ break;
1668
+ } else if (option === "c" || option === "C" || option === "t") {
1669
+ if (argument.slice(characterIndex + 1).length === 0) {
1670
+ index += 1;
1671
+ }
1672
+ break;
1673
+ }
1674
+ }
1675
+ })();
1676
+ }
1677
+ })();
1239
1678
  }
1240
1679
  return {
1241
1680
  messages,
@@ -1249,10 +1688,11 @@ function extractInvocation(words, commandStart, wordTokens) {
1249
1688
  messageExpansion,
1250
1689
  hasTrailer
1251
1690
  };
1252
- }
1253
- function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0) {
1254
- if (depth > 12 || command.length > 262144)
1255
- throw new Error("Shell parsing limit exceeded. Run git commit directly.");
1691
+ };
1692
+ var extractGitCommits = function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0) {
1693
+ if (depth > 12 || command.length > 262144) {
1694
+ throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
1695
+ }
1256
1696
  const tokens = tokenizeShell(command);
1257
1697
  const invocations = [];
1258
1698
  let changedDirectory = inheritedDirectoryChange;
@@ -1261,68 +1701,87 @@ function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0)
1261
1701
  const wordTokens = extractCommandWords(commandTokens);
1262
1702
  const words = wordTokens.map((token) => token.value);
1263
1703
  const commandStart = findCommandStart(words);
1704
+ if (wordTokens[commandStart]?.expansion === true) {
1705
+ throw inspectionError("Cannot inspect a dynamic command name. Use literal command words.");
1706
+ }
1264
1707
  const invocation = extractInvocation(words, commandStart, wordTokens);
1265
- if (/^(?:.*\/)?(?:bash|sh|zsh)$/.test(words[commandStart] ?? "")) {
1266
- let bodyIndex = commandStart + 1;
1267
- let executeString = false;
1268
- while (bodyIndex < words.length) {
1269
- const option = words[bodyIndex];
1270
- if (option === "--") {
1271
- bodyIndex++;
1272
- break;
1273
- }
1274
- if (!option.startsWith("-") && !option.startsWith("+"))
1275
- break;
1276
- if (/^-[a-zA-Z]*c[a-zA-Z]*$/.test(option))
1277
- executeString = true;
1278
- const shortOptions = /^[+-][a-zA-Z]+$/.test(option);
1279
- if (shortOptions && /[oO]/.test(option) && !/[oO]$/.test(option)) {
1280
- throw new Error("Cannot parse shell options reliably. Run git commit directly.");
1281
- }
1282
- const next = words[bodyIndex + 1];
1283
- const optionName = next !== undefined && !/^[+-]/.test(next);
1284
- bodyIndex += shortOptions && /[oO]$/.test(option) && optionName || ["--rcfile", "--init-file"].includes(option) ? 2 : 1;
1285
- }
1286
- if (executeString) {
1287
- const body = wordTokens[bodyIndex];
1288
- if (body === undefined || body.expansion)
1289
- throw new Error("Cannot parse shell -c body reliably. Run git commit directly.");
1290
- if (/^(?:.*\/)?sh$/.test(words[commandStart] ?? "") && body.value.includes("$'")) {
1291
- throw new Error("Cannot parse $' quoting portably in sh -c. Use a literal bash -c or zsh -c body, or run git commit directly.");
1708
+ const directoryChanged = changedDirectory;
1709
+ (() => {
1710
+ if (/^(?:.*\/)?(?:bash|sh|zsh)$/u.test(words[commandStart] ?? "")) {
1711
+ let bodyIndex = commandStart + 1;
1712
+ let executeString = false;
1713
+ (() => {
1714
+ while (bodyIndex < words.length) {
1715
+ const option = words[bodyIndex];
1716
+ if (option === "--") {
1717
+ bodyIndex += 1;
1718
+ break;
1719
+ }
1720
+ if (!option.startsWith("-") && !option.startsWith("+")) {
1721
+ break;
1722
+ }
1723
+ if (/^-[a-zA-Z]*c[a-zA-Z]*$/u.test(option)) {
1724
+ executeString = true;
1725
+ }
1726
+ const shortOptions = /^[+-][a-zA-Z]+$/u.test(option);
1727
+ if (shortOptions && /[oO]/u.test(option) && !/[oO]$/u.test(option)) {
1728
+ throw inspectionError("Cannot parse shell options reliably. Simplify the unsupported syntax.");
1729
+ }
1730
+ const next = words[bodyIndex + 1];
1731
+ const optionName = next !== undefined && !/^[+-]/u.test(next);
1732
+ bodyIndex += shortOptions && /[oO]$/u.test(option) && optionName || ["--rcfile", "--init-file"].includes(option) ? 2 : 1;
1733
+ }
1734
+ })();
1735
+ if (executeString) {
1736
+ const body = wordTokens[bodyIndex];
1737
+ if (body === undefined || body.expansion === true) {
1738
+ throw inspectionError("Cannot parse an expanded or missing shell -c body reliably. Use a literal shell body; if committing, run git commit directly.");
1739
+ }
1740
+ if (/^(?:.*\/)?sh$/u.test(words[commandStart] ?? "") && body.value.includes("$'")) {
1741
+ throw inspectionError("Cannot parse $' quoting portably in sh -c. Use a literal bash -c or zsh -c body.");
1742
+ }
1743
+ const wrapperChange = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word));
1744
+ invocations.push(...extractGitCommits(body.value, directoryChanged || wrapperChange, depth + 1));
1292
1745
  }
1293
- const wrapperChange = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word));
1294
- invocations.push(...extractGitCommits(body.value, changedDirectory || wrapperChange, depth + 1));
1295
1746
  }
1296
- }
1297
- if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment))
1747
+ })();
1748
+ if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment)) {
1298
1749
  changedDirectory = true;
1750
+ }
1299
1751
  if (invocation !== undefined) {
1300
- const target = changedDirectory ? { ...invocation, targetError: "A preceding directory or environment change makes the commit target ambiguous. Run git commit in a separate shell call with the captured workdir." } : invocation;
1752
+ const target = changedDirectory ? {
1753
+ ...invocation,
1754
+ targetError: "A preceding directory or environment change makes the commit target ambiguous. Run git commit in a separate shell call with the captured workdir."
1755
+ } : invocation;
1301
1756
  if (!invocation.filePaths.includes("-")) {
1302
1757
  invocations.push(target);
1303
1758
  continue;
1304
1759
  }
1305
- const heredocs = commandTokens.filter((token) => token.type === "redirect" && /^\d*<<$/.test(token.value));
1306
- const stdinRedirects = commandTokens.filter((token) => {
1307
- if (token.type !== "redirect")
1308
- return false;
1309
- const match = token.value.match(/^(\d*)([<>])/);
1310
- return match !== null && (match[1] === "" ? match[2] === "<" : Number(match[1]) === 0);
1311
- });
1312
- const heredoc = heredocs[0];
1313
- let stdinError;
1314
- if (simple.pipeline)
1315
- stdinError = "Pipelines cannot supply a validated commit message.";
1316
- else if (heredocs.length !== 1 || stdinRedirects.length !== 1 || heredoc?.value !== "<<" && heredoc?.value !== "0<<") {
1317
- stdinError = "Use exactly one quoted stdin heredoc on git commit -F -, with no other stdin redirects.";
1318
- } else if (heredoc.heredoc?.quoted !== true) {
1319
- stdinError = "Use a complete quoted heredoc delimiter, for example: git commit -s -F - <<'EOF'.";
1320
- }
1321
- invocations.push({
1322
- ...target,
1323
- stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined,
1324
- stdinError
1325
- });
1760
+ const collectStdinMessage = () => {
1761
+ const heredocs = commandTokens.filter((token) => token.type === "redirect" && /^\d*<<$/u.test(token.value));
1762
+ const stdinRedirects = commandTokens.filter((token) => {
1763
+ if (token.type !== "redirect") {
1764
+ return false;
1765
+ }
1766
+ const match = /^(?<descriptor>\d*)(?<direction>[<>])/u.exec(token.value);
1767
+ return match !== null && (match[1] === "" ? match[2] === "<" : Number(match[1]) === 0);
1768
+ });
1769
+ const [heredoc] = heredocs;
1770
+ let stdinError;
1771
+ if (simple.pipeline) {
1772
+ stdinError = "Pipelines cannot supply a validated commit message.";
1773
+ } else if (heredocs.length !== 1 || stdinRedirects.length !== 1 || heredoc?.value !== "<<" && heredoc?.value !== "0<<") {
1774
+ stdinError = "Use exactly one quoted stdin heredoc on git commit -F -, with no other stdin redirects.";
1775
+ } else if (heredoc.heredoc?.quoted !== true) {
1776
+ stdinError = "Use a complete quoted heredoc delimiter, for example: git commit -s -F - <<'EOF'.";
1777
+ }
1778
+ invocations.push({
1779
+ ...target,
1780
+ stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined,
1781
+ stdinError
1782
+ });
1783
+ };
1784
+ collectStdinMessage();
1326
1785
  }
1327
1786
  }
1328
1787
  for (const token of tokens) {
@@ -1331,24 +1790,25 @@ function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0)
1331
1790
  }
1332
1791
  }
1333
1792
  return invocations;
1334
- }
1793
+ };
1335
1794
 
1336
1795
  // src/validator.ts
1337
- var signoffPattern = /^\s*Signed-off-by:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/i;
1338
- function hasSignoffTrailer(lines) {
1796
+ var signoffPattern = /^\s*[sS][iI][gG][nN][eE][dD]-[oO][fF][fF]-[bB][yY]:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/u;
1797
+ var hasSignoffTrailer = function hasSignoffTrailer(lines) {
1339
1798
  const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
1340
- return subjectIndex >= 0 && lines.slice(subjectIndex + 1).some((line) => signoffPattern.test(line));
1341
- }
1342
- function validateAllowedScope(rawScope, allowedScopes) {
1343
- const parenthesizedScope = rawScope.match(/^([^(]+)\(([^)]+)\)$/);
1799
+ return subjectIndex !== -1 && lines.slice(subjectIndex + 1).some((line) => signoffPattern.test(line));
1800
+ };
1801
+ var validateAllowedScope = function validateAllowedScope(rawScope, allowedScopes) {
1802
+ const parenthesizedScope = /^(?<type>[^(]+)\((?<scope>[^)]+)\)$/u.exec(rawScope);
1344
1803
  const conventionalType = parenthesizedScope?.[1];
1345
1804
  const innerScope = parenthesizedScope?.[2];
1346
1805
  const isAllowed = allowedScopes.includes(rawScope) || innerScope !== undefined && allowedScopes.includes(innerScope) || conventionalType !== undefined && allowedScopes.includes(conventionalType);
1347
- if (isAllowed)
1806
+ if (isAllowed) {
1348
1807
  return;
1808
+ }
1349
1809
  return `Scope "${rawScope}" is not in the allowed scopes list. Allowed scopes: ${allowedScopes.join(", ")}.`;
1350
- }
1351
- function createCommitGuardError(violations, config) {
1810
+ };
1811
+ var createCommitGuardError = function createCommitGuardError(violations, config) {
1352
1812
  const header = "[commit-guard] Git commit rejected: commit message format rules violated.";
1353
1813
  const violationText = violations.map((v, i) => `${i + 1}. ${v}`).join(`
1354
1814
 
@@ -1363,33 +1823,39 @@ Violations:
1363
1823
  ${violationText}
1364
1824
 
1365
1825
  ${examples}`);
1366
- }
1367
- function validateGitCommits(invocations, config, _originalCommand) {
1826
+ };
1827
+ var validateGitCommits = function validateGitCommits(invocations, config, _originalCommand) {
1368
1828
  const allViolations = [];
1369
1829
  for (const invocation of invocations) {
1370
1830
  if (invocation.isHelp) {
1371
1831
  continue;
1372
1832
  }
1373
- if (invocation.messageExpansion) {
1833
+ if (invocation.messageExpansion === true) {
1374
1834
  allViolations.push("Cannot validate a message containing shell expansion. Supply the final message literally.");
1375
1835
  continue;
1376
1836
  }
1377
- if (invocation.hasTrailer) {
1837
+ if (invocation.hasTrailer === true) {
1378
1838
  allViolations.push("Cannot validate --trailer. Put the trailer in the literal message body or use -s.");
1379
1839
  continue;
1380
1840
  }
1381
1841
  const collectedMessages = [...invocation.messages];
1382
1842
  const filePath = invocation.filePaths.at(-1);
1383
- if (filePath !== undefined) {
1384
- if (filePath !== "-" || invocation.filePaths.length !== 1) {
1385
- allViolations.push("Cannot validate a commit message from -F/--file before permission approval. Use an inline $'...' message or one quoted stdin heredoc.");
1386
- continue;
1387
- }
1388
- if (invocation.stdinError !== undefined || invocation.stdinMessage === undefined || collectedMessages.length > 0) {
1389
- allViolations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} Use one quoted stdin heredoc or an inline $'...' message.`);
1390
- continue;
1843
+ const collectFileMessage = () => {
1844
+ if (filePath !== undefined) {
1845
+ if (filePath !== "-" || invocation.filePaths.length !== 1) {
1846
+ allViolations.push("Cannot validate a commit message from -F/--file before permission approval. Use an inline $'...' message or one quoted stdin heredoc.");
1847
+ return false;
1848
+ }
1849
+ if (invocation.stdinError !== undefined || invocation.stdinMessage === undefined || collectedMessages.length > 0) {
1850
+ allViolations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} Use one quoted stdin heredoc or an inline $'...' message.`);
1851
+ return false;
1852
+ }
1853
+ collectedMessages.push(invocation.stdinMessage);
1391
1854
  }
1392
- collectedMessages.push(invocation.stdinMessage);
1855
+ return true;
1856
+ };
1857
+ if (!collectFileMessage()) {
1858
+ continue;
1393
1859
  }
1394
1860
  if (collectedMessages.length === 0) {
1395
1861
  if (invocation.isAmend && invocation.hasNoEdit === true) {
@@ -1406,10 +1872,10 @@ function validateGitCommits(invocations, config, _originalCommand) {
1406
1872
  const fullMessage = collectedMessages.join(`
1407
1873
 
1408
1874
  `);
1409
- const lines = fullMessage.split(/\r?\n/);
1875
+ const lines = fullMessage.split(/\r?\n/u);
1410
1876
  const firstLine = lines[0] ?? "";
1411
1877
  const subjectLine = firstLine.trim();
1412
- const effectiveSubject = subjectLine.replace(/^(?:(?:fixup|squash)!\s+)+/, "");
1878
+ const effectiveSubject = subjectLine.replace(/^(?:(?:fixup|squash)!\s+)+/u, "");
1413
1879
  const scopeMatch = effectiveSubject.match(scopePattern);
1414
1880
  if (scopeMatch?.[1] !== undefined && config.allowedScopes !== undefined && config.allowedScopes.length > 0) {
1415
1881
  const scopeViolation = validateAllowedScope(scopeMatch[1], config.allowedScopes);
@@ -1418,56 +1884,68 @@ function validateGitCommits(invocations, config, _originalCommand) {
1418
1884
  allViolations.push(`${scopeViolation}${fullSubjectDetail}`);
1419
1885
  }
1420
1886
  }
1421
- if (config.requireScope) {
1422
- if (subjectLine.length === 0) {
1423
- allViolations.push('Subject line is empty. The commit message must begin with "<scope>: <subject>".');
1424
- } else if (scopeMatch === null) {
1425
- if (/^:\s*/.test(effectiveSubject)) {
1426
- allViolations.push(`Missing scope before colon in subject line "${subjectLine}". Expected format: "<scope>: <subject>".`);
1427
- } else if (/^[^:]+:\S/.test(effectiveSubject)) {
1428
- allViolations.push(`Missing space after colon in subject line "${subjectLine}". Expected format: "<scope>: <subject>".`);
1429
- } else if (/^[^:]+:\s*$/.test(effectiveSubject)) {
1430
- allViolations.push(`Subject text after colon is empty in "${subjectLine}". Expected format: "<scope>: <subject>".`);
1431
- } else {
1432
- allViolations.push(`Missing scope in subject line "${subjectLine}". First line must follow "<scope>: <subject>" format.`);
1887
+ const validateSubject = () => {
1888
+ if (config.requireScope) {
1889
+ if (subjectLine.length === 0) {
1890
+ allViolations.push('Subject line is empty. The commit message must begin with "<scope>: <subject>".');
1891
+ } else if (scopeMatch === null) {
1892
+ if (/^:\s*/u.test(effectiveSubject)) {
1893
+ allViolations.push(`Missing scope before colon in subject line "${subjectLine}". Expected format: "<scope>: <subject>".`);
1894
+ } else if (/^[^:]+:\S/u.test(effectiveSubject)) {
1895
+ allViolations.push(`Missing space after colon in subject line "${subjectLine}". Expected format: "<scope>: <subject>".`);
1896
+ } else if (/^[^:]+:\s*$/u.test(effectiveSubject)) {
1897
+ allViolations.push(`Subject text after colon is empty in "${subjectLine}". Expected format: "<scope>: <subject>".`);
1898
+ } else {
1899
+ allViolations.push(`Missing scope in subject line "${subjectLine}". First line must follow "<scope>: <subject>" format.`);
1900
+ }
1433
1901
  }
1434
1902
  }
1435
- }
1436
- if (config.maxLineLength > 0) {
1437
- const overlongLines = [];
1438
- for (let i = 0;i < lines.length; i++) {
1439
- const line = lines[i];
1440
- if (line !== undefined && line.length > config.maxLineLength) {
1441
- overlongLines.push({ lineNumber: i + 1, length: line.length, text: line });
1903
+ };
1904
+ validateSubject();
1905
+ const validateLength = () => {
1906
+ if (config.maxLineLength > 0) {
1907
+ const overlongLines = [];
1908
+ for (let i = 0;i < lines.length; i += 1) {
1909
+ const line = lines[i];
1910
+ if (line !== undefined && line.length > config.maxLineLength) {
1911
+ overlongLines.push({
1912
+ lineNumber: i + 1,
1913
+ length: line.length,
1914
+ text: line
1915
+ });
1916
+ }
1442
1917
  }
1443
- }
1444
- if (overlongLines.length > 0) {
1445
- const details = overlongLines.map((l) => ` - Line ${l.lineNumber} (${l.length} chars, max ${config.maxLineLength}): "${l.text}"`).join(`
1918
+ if (overlongLines.length > 0) {
1919
+ const details = overlongLines.map((l) => ` - Line ${l.lineNumber} (${l.length} chars, max ${config.maxLineLength}): "${l.text}"`).join(`
1446
1920
  `);
1447
- allViolations.push(`Commit message exceeds maximum line length of ${config.maxLineLength} characters:
1921
+ allViolations.push(`Commit message exceeds maximum line length of ${config.maxLineLength} characters:
1448
1922
  ${details}
1449
1923
  Each -m becomes one paragraph line. Wrap with real newlines inside $'...'; "\\n" inside double quotes stays literal.`);
1924
+ }
1450
1925
  }
1451
- }
1452
- if (config.enforceSignoff) {
1453
- const hasSignoff = invocation.hasSignoffFlag || hasSignoffTrailer(lines);
1454
- if (!hasSignoff) {
1455
- allViolations.push("Missing commit signoff. Commit must either include the '-s' or '--signoff' flag, or contain a valid 'Signed-off-by: Name <email>' trailer in the message body.");
1926
+ };
1927
+ validateLength();
1928
+ const validateSignoff = () => {
1929
+ if (config.enforceSignoff) {
1930
+ const hasSignoff = invocation.hasSignoffFlag || hasSignoffTrailer(lines);
1931
+ if (!hasSignoff) {
1932
+ allViolations.push("Missing commit signoff. Commit must either include the '-s' or '--signoff' flag, or contain a valid 'Signed-off-by: Name <email>' trailer in the message body.");
1933
+ }
1456
1934
  }
1457
- }
1935
+ };
1936
+ validateSignoff();
1458
1937
  }
1459
1938
  if (allViolations.length > 0) {
1460
1939
  throw createCommitGuardError(allViolations.slice(0, 10).map((text) => text.slice(0, 2048)), config);
1461
1940
  }
1462
- }
1941
+ };
1463
1942
 
1464
1943
  // src/plugin.ts
1944
+ var { relative: relative2, resolve: resolve2 } = path;
1465
1945
  var plugin = Plugin.define({
1466
1946
  id: "opencode-commit-guard",
1467
- effect: (ctx) => Effect2.gen(function* () {
1468
- const config = yield* Effect2.sync(() => {
1469
- return parseConfig(ctx.options);
1470
- });
1947
+ effect: (ctx) => Effect2.gen(function* setupGuard() {
1948
+ const config = yield* Effect2.sync(() => parseConfig(ctx.options));
1471
1949
  const generation = randomUUID2();
1472
1950
  const pending = new Map;
1473
1951
  const preparing = new Set;
@@ -1476,21 +1954,26 @@ var plugin = Plugin.define({
1476
1954
  const rememberFailure = (scope, reason) => {
1477
1955
  failures.delete(scope);
1478
1956
  failures.set(scope, `The previous capture failed: ${reason.slice(0, 256)}. `);
1479
- if (failures.size > 128)
1480
- failures.delete(failures.keys().next().value);
1957
+ if (failures.size > 128) {
1958
+ const oldest = failures.keys().next().value;
1959
+ if (oldest !== undefined) {
1960
+ failures.delete(oldest);
1961
+ }
1962
+ }
1481
1963
  };
1482
- const sweep = () => Effect2.gen(function* () {
1964
+ const sweep = () => Effect2.gen(function* sweepPending() {
1483
1965
  for (const attempt of [...pending.values()].slice(0, 32)) {
1484
1966
  pending.delete(attempt.scope);
1485
1967
  if (attempt.claimed === undefined && Date.now() >= attempt.expires) {
1486
1968
  cleanup(attempt);
1487
1969
  yield* recordState(ctx, attempt, "expired");
1488
1970
  yield* invalidateOwned(ctx, attempt);
1489
- } else
1971
+ } else {
1490
1972
  pending.set(attempt.scope, attempt);
1973
+ }
1491
1974
  }
1492
1975
  });
1493
- yield* Effect2.addFinalizer(() => Effect2.gen(function* () {
1976
+ yield* Effect2.addFinalizer(() => Effect2.gen(function* unloadGuard() {
1494
1977
  for (const attempt of pending.values()) {
1495
1978
  cleanup(attempt);
1496
1979
  yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication");
@@ -1498,9 +1981,10 @@ var plugin = Plugin.define({
1498
1981
  }
1499
1982
  pending.clear();
1500
1983
  }));
1501
- yield* ctx.tool.transform((editor) => editor.add({
1502
- name: "commit_context",
1503
- description: String.raw`Prepare a Git baseline. Run the returned command unchanged in the foreground; require "Frozen commit baseline".
1984
+ yield* ctx.tool.transform((editor) => {
1985
+ editor.add({
1986
+ name: "commit_context",
1987
+ description: String.raw`Prepare a Git baseline. Run the returned command unchanged in the foreground; require "Frozen commit baseline".
1504
1988
  Call before your first commit in each session and checkout.
1505
1989
  Set workdir when targeting another repository.
1506
1990
  Run the returned command immediately, unchanged, with the indicated workdir and background:false.
@@ -1514,106 +1998,140 @@ Use literal message text and real body newlines.
1514
1998
  Example: git commit -m $'scope: Subject\n\nBody line one.\nBody line two.'
1515
1999
  Replace scope and follow the returned line-length and signoff rules.
1516
2000
  Add -s only when the returned policy or repository instructions require it.`,
1517
- input: {
1518
- type: "object",
1519
- properties: {
1520
- refresh: { type: "boolean" },
1521
- workdir: { type: "string", description: "Working directory of the Git repository relative to the session directory or absolute." },
1522
- directory: { type: "string", description: "Path to the Git repository checkout (alias for workdir)." }
2001
+ input: {
2002
+ type: "object",
2003
+ properties: {
2004
+ refresh: { type: "boolean" },
2005
+ workdir: {
2006
+ type: "string",
2007
+ description: "Working directory of the Git repository relative to the session directory or absolute."
2008
+ },
2009
+ directory: {
2010
+ type: "string",
2011
+ description: "Path to the Git repository checkout (alias for workdir)."
2012
+ }
2013
+ },
2014
+ additionalProperties: false
1523
2015
  },
1524
- additionalProperties: false
1525
- },
1526
- execute: (input, toolContext) => Effect2.gen(function* () {
1527
- yield* sweep();
1528
- if (ctx.location.workspaceID !== undefined)
1529
- return { content: "Commit context capture is unavailable for remote workspaces." };
1530
- const session = yield* ctx.session.get({ sessionID: toolContext.sessionID });
1531
- if (session.location.workspaceID !== ctx.location.workspaceID) {
1532
- return { content: "Commit context capture is unavailable for remote workspaces." };
1533
- }
1534
- const request = input;
1535
- const requestedDir = isJSONString(request.workdir) ? request.workdir : isJSONString(request.directory) ? request.directory : undefined;
1536
- const sessionDirectory = session.location.directory ?? ctx.location.directory;
1537
- let target = resolveTargetWorkdir(sessionDirectory, requestedDir);
1538
- if (target.workdir === undefined && requestedDir === undefined) {
1539
- const remembered = lastSessionWorkdir.get(toolContext.sessionID);
1540
- if (remembered !== undefined && existsSync2(remembered) && findGitRoot(remembered) !== undefined) {
1541
- target = { workdir: remembered };
2016
+ execute: (input, toolContext) => Effect2.gen(function* execute() {
2017
+ yield* sweep();
2018
+ if (ctx.location.workspaceID !== undefined) {
2019
+ return {
2020
+ content: "Commit context capture is unavailable for remote workspaces."
2021
+ };
1542
2022
  }
1543
- }
1544
- if (target.error !== undefined || target.workdir === undefined) {
1545
- return { content: target.error ?? "Could not determine target Git repository." };
1546
- }
1547
- const targetWorkdir = target.workdir;
1548
- lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir);
1549
- const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir);
1550
- if (preparing.has(scope))
1551
- return { content: "A commit context capture is preparing for this session and checkout. Wait for its command, then follow its instructions." };
1552
- preparing.add(scope);
1553
- return yield* Effect2.gen(function* () {
1554
- const previous = pending.get(scope);
1555
- if (previous !== undefined) {
1556
- if (previous.claimed !== undefined && request.refresh !== true) {
1557
- return { content: 'Capture claimed; permission approval or execution is pending. Wait for its foreground shell result. Commit after it reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing. RECEIPT_OK confirms only that the artifact was written, not that the baseline was published.' };
1558
- }
1559
- if (request.refresh !== true) {
1560
- return { content: captureInstructions(previous, "Capture still pending and unclaimed. ") };
1561
- }
1562
- pending.delete(scope);
1563
- cleanup(previous);
1564
- yield* recordState(ctx, previous, "failed", "capture replaced by refresh");
1565
- yield* invalidateOwned(ctx, previous);
2023
+ const session = yield* ctx.session.get({
2024
+ sessionID: toolContext.sessionID
2025
+ });
2026
+ if (session.location.workspaceID !== ctx.location.workspaceID) {
2027
+ return {
2028
+ content: "Commit context capture is unavailable for remote workspaces."
2029
+ };
2030
+ }
2031
+ const request = Schema2.is(Schema2.Json)(input) && isRecord(input) ? input : {};
2032
+ let requestedDir;
2033
+ if (isJSONString(request.workdir)) {
2034
+ requestedDir = request.workdir;
2035
+ } else if (isJSONString(request.directory)) {
2036
+ requestedDir = request.directory;
1566
2037
  }
1567
- if (request.refresh !== true) {
1568
- const baseline = yield* load(ctx, scope);
1569
- if (baseline !== undefined && baseline.directory === findGitRoot(targetWorkdir)) {
1570
- return { content: baselineGuidance(baseline, config) };
2038
+ const sessionDirectory = session.location.directory ?? ctx.location.directory;
2039
+ let target = resolveTargetWorkdir(sessionDirectory, requestedDir);
2040
+ if (target.workdir === undefined && requestedDir === undefined) {
2041
+ const remembered = lastSessionWorkdir.get(toolContext.sessionID);
2042
+ if (remembered !== undefined && existsSync2(remembered) && findGitRoot(remembered) !== undefined) {
2043
+ target = { workdir: remembered };
1571
2044
  }
1572
2045
  }
1573
- const count = yield* invalidate(ctx, scope);
1574
- const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, targetWorkdir));
1575
- pending.set(scope, attempt);
1576
- const status = failures.get(scope) ?? (yield* captureStatus(ctx, scope));
1577
- yield* recordState(ctx, attempt, "prepared");
1578
- return { content: captureInstructions(attempt, status) };
1579
- }).pipe(Effect2.ensuring(Effect2.sync(() => {
1580
- preparing.delete(scope);
1581
- })));
1582
- }).pipe(Effect2.mapError(() => new Tool.Error({
1583
- message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout."
1584
- })))
1585
- }));
1586
- yield* ctx.tool.hook("execute.before", (event) => Effect2.gen(function* () {
2046
+ if (target.error !== undefined || target.workdir === undefined) {
2047
+ return {
2048
+ content: target.error ?? "Could not determine target Git repository."
2049
+ };
2050
+ }
2051
+ const targetWorkdir = target.workdir;
2052
+ lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir);
2053
+ const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir);
2054
+ if (preparing.has(scope)) {
2055
+ return {
2056
+ content: "A commit context capture is preparing for this session and checkout. Wait for its command, then follow its instructions."
2057
+ };
2058
+ }
2059
+ preparing.add(scope);
2060
+ return yield* Effect2.gen(function* prepareCapture() {
2061
+ const previous = pending.get(scope);
2062
+ if (previous !== undefined) {
2063
+ if (previous.claimed !== undefined && request.refresh !== true) {
2064
+ return {
2065
+ content: 'Capture claimed; permission approval or execution is pending. Wait for its foreground shell result. Commit after it reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing. RECEIPT_OK confirms only that the artifact was written, not that the baseline was published.'
2066
+ };
2067
+ }
2068
+ if (request.refresh !== true) {
2069
+ return {
2070
+ content: captureInstructions(previous, "Capture still pending and unclaimed. ")
2071
+ };
2072
+ }
2073
+ pending.delete(scope);
2074
+ cleanup(previous);
2075
+ yield* recordState(ctx, previous, "failed", "capture replaced by refresh");
2076
+ yield* invalidateOwned(ctx, previous);
2077
+ }
2078
+ if (request.refresh !== true) {
2079
+ const baseline = yield* load(ctx, scope);
2080
+ if (baseline !== undefined && baseline.directory === findGitRoot(targetWorkdir)) {
2081
+ return { content: baselineGuidance(baseline, config) };
2082
+ }
2083
+ }
2084
+ const count = yield* invalidate(ctx, scope);
2085
+ const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, targetWorkdir));
2086
+ pending.set(scope, attempt);
2087
+ const status = failures.get(scope) ?? (yield* captureStatus(ctx, scope));
2088
+ yield* recordState(ctx, attempt, "prepared");
2089
+ return { content: captureInstructions(attempt, status) };
2090
+ }).pipe(Effect2.ensuring(Effect2.sync(() => {
2091
+ preparing.delete(scope);
2092
+ })));
2093
+ }).pipe(Effect2.mapError(() => new Tool.Error({
2094
+ message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout."
2095
+ })))
2096
+ });
2097
+ });
2098
+ yield* ctx.tool.hook("execute.before", (event) => Effect2.gen(function* beforeExecution() {
1587
2099
  yield* sweep();
1588
- const captureSession = event.tool === "shell" || event.tool === "bash" ? yield* ctx.session.get({ sessionID: event.sessionID }) : undefined;
2100
+ const rawInput = Schema2.is(Schema2.Json)(event.input) ? event.input : undefined;
2101
+ if ((event.tool === "shell" || event.tool === "bash") && rawInput === undefined) {
2102
+ yield* Effect2.fail(new Tool.Error({
2103
+ message: "[commit-guard] Cannot inspect non-JSON shell input. Supply literal command and workdir fields."
2104
+ }));
2105
+ }
2106
+ const captureSession = (event.tool === "shell" || event.tool === "bash") && [...pending.values()].some((attempt) => isRecord(rawInput) && rawInput.command === attempt.command) ? yield* ctx.session.get({ sessionID: event.sessionID }) : undefined;
1589
2107
  const captureSessionDirectory = captureSession?.location.directory ?? ctx.location.directory;
1590
2108
  const parsed = yield* Effect2.try({
1591
2109
  try: () => {
1592
2110
  if (event.tool !== "shell" && event.tool !== "bash") {
1593
- return;
2111
+ return null;
1594
2112
  }
1595
- const rawInput = event.input;
1596
2113
  if (!isRecord(rawInput)) {
1597
- return;
2114
+ return null;
1598
2115
  }
1599
- const command = rawInput["command"];
2116
+ const { command } = rawInput;
1600
2117
  if (!isJSONString(command)) {
1601
- return;
2118
+ return null;
1602
2119
  }
1603
- const rawWorkdir = rawInput["workdir"];
2120
+ const rawWorkdir = rawInput.workdir;
1604
2121
  for (const attempt of pending.values()) {
1605
- if (command !== attempt.command)
2122
+ if (command !== attempt.command) {
1606
2123
  continue;
2124
+ }
1607
2125
  const matchesWorkdir = rawWorkdir === attempt.workdir || isJSONString(rawWorkdir) && resolve2(captureSessionDirectory, rawWorkdir) === attempt.workdir || rawWorkdir === undefined && captureSessionDirectory === attempt.workdir;
1608
- if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || !matchesWorkdir || rawInput["background"] === true || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
2126
+ if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || !matchesWorkdir || rawInput.background === true || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
1609
2127
  throw new Error("[commit-guard] Capture must use its exact foreground shell command in the original session and workdir. Call commit_context to refresh.");
1610
2128
  }
1611
2129
  attempt.claimed = { messageID: event.messageID, id: event.id };
1612
- return;
2130
+ return null;
1613
2131
  }
1614
2132
  const invocations = extractGitCommits(command);
1615
2133
  if (invocations.length === 0) {
1616
- return;
2134
+ return null;
1617
2135
  }
1618
2136
  return { invocations, command, rawInput };
1619
2137
  },
@@ -1622,81 +2140,99 @@ Add -s only when the returned policy or repository instructions require it.`,
1622
2140
  })
1623
2141
  });
1624
2142
  for (const attempt of pending.values()) {
1625
- if (attempt.claimed?.messageID === event.messageID && attempt.claimed.id === event.id && attempt.sessionID === event.sessionID && attempt.agent === event.agent)
2143
+ if (attempt.claimed?.messageID === event.messageID && attempt.claimed.id === event.id && attempt.sessionID === event.sessionID && attempt.agent === event.agent) {
1626
2144
  yield* recordState(ctx, attempt, "claimed");
2145
+ }
1627
2146
  }
1628
- if (parsed === undefined || parsed.invocations.every((invocation) => invocation.isHelp))
2147
+ if (parsed === null || parsed.invocations.every((invocation) => invocation.isHelp)) {
1629
2148
  return;
1630
- if (ctx.location.workspaceID !== undefined)
1631
- return yield* Effect2.fail(new Tool.Error({
1632
- message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."
1633
- }));
1634
- const session = yield* ctx.session.get({ sessionID: event.sessionID });
1635
- if (session.location.workspaceID !== ctx.location.workspaceID || parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
1636
- return yield* Effect2.fail(new Tool.Error({
1637
- 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."
1638
- }));
1639
- }
1640
- const sessionDirectory = session.location.directory ?? ctx.location.directory;
1641
- const rawWorkdir = parsed.rawInput["workdir"];
1642
- const effectiveWorkdir = yield* Effect2.try(() => realpathSync2(isJSONString(rawWorkdir) ? resolve2(sessionDirectory, rawWorkdir) : sessionDirectory));
1643
- const targetGitRoot = findGitRoot(effectiveWorkdir);
1644
- const scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir);
1645
- const baseline = yield* load(ctx, scope);
1646
- const expectedDir = targetGitRoot ?? effectiveWorkdir;
1647
- const baselineValid = baseline !== undefined && targetGitRoot !== undefined && baseline.directory === targetGitRoot && baseline.directory === expectedDir;
1648
- if (!baselineValid || baseline === undefined) {
1649
- const relWorkdir = relative2(sessionDirectory, expectedDir);
1650
- const workdirHint = JSON.stringify(relWorkdir.length > 0 ? relWorkdir : ".");
1651
- return yield* Effect2.fail(new Tool.Error({
1652
- message: `[commit-guard] No published baseline for ${expectedDir}. Call commit_context({ workdir: ${workdirHint} }), then run the returned command immediately, unchanged, in the foreground with that workdir and background:false. Do not wrap it or chain another command onto it. Commit after the shell result reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing. RECEIPT_OK alone is insufficient.`
1653
- }));
1654
2149
  }
1655
- if (baseline.gpgsign === "error" || baseline.signingkey === "error")
1656
- return yield* Effect2.fail(new Tool.Error({
1657
- message: signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")
1658
- }));
1659
- yield* Effect2.try({
1660
- try: () => validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command),
1661
- catch: (error) => new Tool.Error({
1662
- message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
1663
- })
2150
+ yield* Effect2.gen(function* validateTarget() {
2151
+ if (ctx.location.workspaceID !== undefined) {
2152
+ return yield* Effect2.fail(new Tool.Error({
2153
+ message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."
2154
+ }));
2155
+ }
2156
+ const session = captureSession ?? (yield* ctx.session.get({ sessionID: event.sessionID }));
2157
+ if (session.location.workspaceID !== ctx.location.workspaceID || parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
2158
+ return yield* Effect2.fail(new Tool.Error({
2159
+ 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."
2160
+ }));
2161
+ }
2162
+ const sessionDirectory = session.location.directory ?? ctx.location.directory;
2163
+ const rawWorkdir = parsed.rawInput.workdir;
2164
+ const effectiveWorkdir = yield* Effect2.try(() => realpathSync2(isJSONString(rawWorkdir) ? resolve2(sessionDirectory, rawWorkdir) : sessionDirectory));
2165
+ const targetGitRoot = findGitRoot(effectiveWorkdir);
2166
+ const scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir);
2167
+ const baseline = yield* load(ctx, scope);
2168
+ const expectedDir = targetGitRoot ?? effectiveWorkdir;
2169
+ const baselineValid = baseline !== undefined && targetGitRoot !== undefined && baseline.directory === targetGitRoot && baseline.directory === expectedDir;
2170
+ if (!baselineValid || baseline === undefined) {
2171
+ const relWorkdir = relative2(sessionDirectory, expectedDir);
2172
+ const workdirHint = JSON.stringify(relWorkdir.length > 0 ? relWorkdir : ".");
2173
+ return yield* Effect2.fail(new Tool.Error({
2174
+ message: `[commit-guard] No published baseline for ${expectedDir}. Call commit_context({ workdir: ${workdirHint} }), then run the returned command immediately, unchanged, in the foreground with that workdir and background:false. Do not wrap it or chain another command onto it. Commit after the shell result reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing. RECEIPT_OK alone is insufficient.`
2175
+ }));
2176
+ }
2177
+ if (baseline.gpgsign === "error" || baseline.signingkey === "error") {
2178
+ return yield* Effect2.fail(new Tool.Error({
2179
+ message: signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")
2180
+ }));
2181
+ }
2182
+ yield* Effect2.try({
2183
+ try: () => {
2184
+ validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command);
2185
+ },
2186
+ catch: (error) => new Tool.Error({
2187
+ message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
2188
+ })
2189
+ });
2190
+ return yield* Effect2.void;
1664
2191
  });
1665
2192
  }).pipe(Effect2.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
1666
2193
  message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
1667
2194
  }))));
1668
- yield* ctx.tool.hook("execute.after", (event) => Effect2.gen(function* () {
1669
- if (event.tool !== "shell")
2195
+ yield* ctx.tool.hook("execute.after", (event) => Effect2.gen(function* afterExecution() {
2196
+ if (event.tool !== "shell") {
1670
2197
  return;
2198
+ }
1671
2199
  const attempt = [...pending.values()].find((item) => item.claimed?.id === event.id && item.claimed?.messageID === event.messageID && item.sessionID === event.sessionID && item.agent === event.agent);
1672
- if (attempt === undefined)
2200
+ if (attempt === undefined) {
1673
2201
  return;
2202
+ }
1674
2203
  let published = false;
1675
2204
  let captured;
1676
2205
  let reason = "capture import or storage failed";
1677
- yield* Effect2.gen(function* () {
2206
+ yield* Effect2.gen(function* publishCapture() {
1678
2207
  reason = "shell result did not complete successfully";
1679
- if (event.status !== "completed")
2208
+ if (event.status !== "completed") {
1680
2209
  return;
2210
+ }
1681
2211
  reason = "capture was superseded by a refresh";
1682
- if ((yield* counter(ctx, attempt.scope)) !== attempt.counter)
2212
+ if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) {
1683
2213
  return;
2214
+ }
1684
2215
  const metadata = event.result.metadata;
1685
2216
  reason = "shell result lacks verified foreground completion metadata";
1686
- if (!isRecord(metadata))
2217
+ if (!isRecord(metadata)) {
1687
2218
  return;
1688
- if (metadata["status"] !== "completed" || metadata["exit"] !== 0 || metadata["truncated"] !== false || metadata["timeout"] !== undefined && metadata["timeout"] !== false || metadata["shellID"] !== undefined || Object.keys(metadata).some((key) => !["status", "exit", "truncated", "timeout"].includes(key)))
1689
- return;
1690
- const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {
2219
+ }
2220
+ if (metadata.status !== "completed" || metadata.exit !== 0 || metadata.truncated !== false || metadata.timeout !== undefined && metadata.timeout !== false || metadata.shellID !== undefined || Object.keys(metadata).some((key) => !["status", "exit", "truncated", "timeout"].includes(key))) {
1691
2221
  return;
1692
- });
2222
+ }
2223
+ const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {});
1693
2224
  reason = "capture session or workspace no longer matches";
1694
- if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID)
2225
+ if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID) {
1695
2226
  return;
2227
+ }
1696
2228
  reason = "private artifact is invalid or incomplete (END required)";
1697
- const baseline = yield* Effect2.try({ try: () => importCapture(attempt), catch: () => new Error("Invalid capture") });
1698
- if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined)
2229
+ const baseline = yield* Effect2.try({
2230
+ try: () => importCapture(attempt),
2231
+ catch: () => new Error("Invalid capture")
2232
+ });
2233
+ if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined) {
1699
2234
  return;
2235
+ }
1700
2236
  reason = "capture storage failed or its counter changed";
1701
2237
  published = yield* publish(ctx, attempt, generation, baseline);
1702
2238
  if (published) {
@@ -1704,37 +2240,48 @@ Add -s only when the returned policy or repository instructions require it.`,
1704
2240
  failures.delete(attempt.scope);
1705
2241
  yield* recordState(ctx, attempt, "published");
1706
2242
  }
1707
- }).pipe(Effect2.onExit(() => Effect2.gen(function* () {
1708
- if (pending.get(attempt.scope) === attempt)
2243
+ }).pipe(Effect2.onExit(() => Effect2.gen(function* finalizeCapture() {
2244
+ if (pending.get(attempt.scope) === attempt) {
1709
2245
  pending.delete(attempt.scope);
2246
+ }
1710
2247
  if (!published) {
1711
2248
  rememberFailure(attempt.scope, reason);
1712
2249
  yield* recordState(ctx, attempt, "failed", reason).pipe(Effect2.catchCause(() => Effect2.void));
1713
2250
  yield* invalidateOwned(ctx, attempt);
1714
2251
  }
1715
- }).pipe(Effect2.ensuring(Effect2.sync(() => cleanup(attempt))))), Effect2.catchCause(() => Effect2.void));
2252
+ }).pipe(Effect2.ensuring(Effect2.sync(() => {
2253
+ cleanup(attempt);
2254
+ })))), Effect2.catchCause(() => Effect2.void));
1716
2255
  const note = published && captured !== undefined ? baselineGuidance(captured, config) : `[commit-guard] This capture did not publish a usable baseline: ${reason.slice(0, 256)}.
1717
2256
  ` + `RECEIPT_OK alone does not authorize a commit.
1718
2257
  ` + "Call commit_context with the same workdir for status and next steps.";
1719
2258
  if (event.status === "error") {
1720
- event.error = new Tool.Error({ message: `${event.error.message}
2259
+ event.error = new Tool.Error({
2260
+ error: event.error.error,
2261
+ metadata: event.error.metadata,
2262
+ message: `${event.error.message}
1721
2263
 
1722
- ${note}` });
1723
- } else
2264
+ ${note}`
2265
+ });
2266
+ } else {
1724
2267
  event.result = appendCaptureNote(event.result, note);
2268
+ }
1725
2269
  }));
1726
2270
  })
1727
2271
  });
1728
2272
  var plugin_default = plugin;
1729
- function captureInstructions(attempt, status) {
2273
+ var captureInstructions = function captureInstructions(attempt, status) {
1730
2274
  return `${status}Run this shell command immediately, unchanged, in the foreground with workdir ${attempt.workdir} and background:false. ` + 'Do not wrap it or chain another command onto it. Commit after the shell result reports "Frozen commit baseline"; ' + "otherwise call commit_context again with the same workdir before committing. " + `RECEIPT_OK confirms only that the artifact was written, not that the baseline was published:
1731
2275
  ${attempt.command}`;
1732
- }
1733
- function baselineGuidance(baseline, config) {
1734
- if (baseline.gpgsign === "error" || baseline.signingkey === "error")
2276
+ };
2277
+ var baselineGuidance = function baselineGuidance(baseline, config) {
2278
+ if (baseline.gpgsign === "error" || baseline.signingkey === "error") {
1735
2279
  return signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey");
1736
- const observed = [...new Set(baseline.messages.map((message) => message.split(`
1737
- `)[0]?.match(/^([a-zA-Z0-9_./-]{1,40}): /)?.[1]).filter((value) => value !== undefined))].slice(0, 3);
2280
+ }
2281
+ const observed = [
2282
+ ...new Set(baseline.messages.map((message) => /^(?<scope>[a-zA-Z0-9_./-]{1,40}): /u.exec(message.split(`
2283
+ `)[0])?.[1]).filter((value) => value !== undefined))
2284
+ ].slice(0, 3);
1738
2285
  const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
1739
2286
  ` : "";
1740
2287
  const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." : `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`;
@@ -1746,21 +2293,31 @@ ${examples}Effective commit.gpgsign: ${baseline.gpgsign}. ${signoff}
1746
2293
  ` + `user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}. Signoff is not a cryptographic signature.
1747
2294
  ` + `A second commit_context call is optional.
1748
2295
  ` + "Set refresh:true after a branch switch, changed signing settings, or changed commit instructions.";
1749
- }
1750
- function appendCaptureNote(result, note) {
1751
- const content = Array.isArray(result.content) ? result.content : result.content === undefined ? [] : [{ type: "text", text: String(result.content) }];
1752
- const output = result.output;
1753
- const annotated = { ...result, content: [...content, { type: "text", text: note }] };
1754
- if (isRecord(output) && isJSONString(output["output"])) {
1755
- return { ...annotated, output: { ...output, output: `${output["output"]}
2296
+ };
2297
+ var appendCaptureNote = function appendCaptureNote(result, note) {
2298
+ const content = isJSONString(result.content) ? [{ type: "text", text: result.content }] : result.content ?? [];
2299
+ const rawOutput = result.output;
2300
+ const output = Schema2.is(Schema2.Json)(rawOutput) ? rawOutput : undefined;
2301
+ const annotated = {
2302
+ ...result,
2303
+ content: [...content, { type: "text", text: note }]
2304
+ };
2305
+ if (isRecord(output) && isJSONString(output.output)) {
2306
+ return {
2307
+ ...annotated,
2308
+ output: {
2309
+ ...Object.fromEntries(Object.entries(output)),
2310
+ output: `${output.output}
1756
2311
 
1757
- ${note}` } };
2312
+ ${note}`
2313
+ }
2314
+ };
1758
2315
  }
1759
2316
  return annotated;
1760
- }
1761
- function signingError(setting) {
2317
+ };
2318
+ var signingError = function signingError(setting) {
1762
2319
  return `[commit-guard] Git could not read ${setting} as valid. Repeating the capture will not fix it. Inspect with git config --show-origin --get-all ${setting}; fix the value without changing the intended signing policy, then call commit_context with refresh:true.`;
1763
- }
2320
+ };
1764
2321
  export {
1765
2322
  plugin_default as default
1766
2323
  };