opencode-commit-guard 1.0.7 → 1.1.1

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