@opendesignai/harness 0.4.0-alpha.0 → 0.5.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hook.mjs CHANGED
@@ -1,13 +1,13 @@
1
- import { closeSync, constants, existsSync, fstatSync, globSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { closeSync, constants, existsSync, fstatSync, globSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { parse } from "yaml";
4
4
  import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
5
5
  import { performance } from "node:perf_hooks";
6
- import { n as hookEnv, t as childEnv } from "./child-env-cPBUueQI.mjs";
6
+ import { n as hookEnv, r as hookLogMode, t as childEnv } from "./child-env-BX7ENXDG.mjs";
7
7
  import { createHash, randomUUID } from "node:crypto";
8
- import { createRequire } from "node:module";
9
8
  import { tmpdir } from "node:os";
10
9
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
+ import { createRequire } from "node:module";
11
11
  // src/hook/paths.ts
12
12
  const D_CLASS_PATTERNS = [
13
13
  "oxlint-suppressions.json",
@@ -93,7 +93,7 @@ const PROTECTED_LITERAL_FRAGMENTS = [
93
93
  ".claude/skills/od-",
94
94
  ".git/",
95
95
  ".gitattributes",
96
- ".github/",
96
+ ".github",
97
97
  "knip.json",
98
98
  "knip.jsonc",
99
99
  "knip.ts",
@@ -112,7 +112,7 @@ const PROTECTED_LITERAL_FRAGMENTS = [
112
112
  "pnpm-workspace.yaml",
113
113
  "AGENTS.md",
114
114
  "node_modules/@opendesignai/harness",
115
- "@opendesignai+harness"
115
+ "@opendesignai+harness@"
116
116
  ];
117
117
  function isCaseInsensitivePlatform(platform) {
118
118
  return platform === "darwin" || platform === "win32";
@@ -296,18 +296,25 @@ function classifyProtectedPath(relPath, config, options) {
296
296
  };
297
297
  }
298
298
  const STANDALONE_DOT_GIT_RE = /(?:^|['"`\s\\/])\.git(?:['"`\s\\/]|$)/;
299
+ const FILENAME_CHARACTER = /[\p{L}\p{N}\p{M}_.@+%-]/u;
300
+ function hasPathFragment(text, fragment, prefix = false) {
301
+ for (let at = text.indexOf(fragment); at !== -1; at = text.indexOf(fragment, at + 1)) {
302
+ if (FILENAME_CHARACTER.test(text[at - 1] ?? "")) continue;
303
+ if (prefix || fragment.endsWith("/") || !FILENAME_CHARACTER.test(text[at + fragment.length] ?? "")) return true;
304
+ }
305
+ return false;
306
+ }
299
307
  /** Detect literal protected file or directory names inside dynamic text or inline code. */
300
308
  function findProtectedLiteralMention(text, config) {
301
309
  const lower = text.toLowerCase().replaceAll("\\", "/");
302
- for (const frag of PROTECTED_LITERAL_FRAGMENTS) if (lower.includes(frag.toLowerCase())) return frag;
310
+ for (const frag of PROTECTED_LITERAL_FRAGMENTS) if (hasPathFragment(lower, frag.toLowerCase(), /[-.@]$/.test(frag))) return frag;
303
311
  if (STANDALONE_DOT_GIT_RE.test(lower)) return ".git";
304
- if (config?.denyFiles) for (const pat of config.denyFiles) {
305
- const clean = pat.replace(/[*?]+/g, "").replace(/\/+$/, "");
306
- if (clean.length >= 4 && lower.includes(clean.toLowerCase())) return pat;
307
- }
308
- if (config?.gateFiles) for (const pat of config.gateFiles) {
309
- const clean = pat.replace(/[*?]+/g, "").replace(/\/+$/, "");
310
- if (clean.length >= 4 && lower.includes(clean.toLowerCase())) return pat;
312
+ for (const pattern of [...config?.denyFiles ?? [], ...config?.gateFiles ?? []]) {
313
+ const normalized = pattern.toLowerCase().replaceAll("\\", "/").replace(/^(?:\*\*\/|\.\/|\/)+/, "");
314
+ const fragment = normalized.replace(/[*?]+/g, "").replace(/\/+$/, "");
315
+ if (fragment && hasPathFragment(lower, fragment)) return pattern;
316
+ if (normalized === fragment) continue;
317
+ for (const path of lower.matchAll(/[\p{L}\p{N}\p{M}_.@+%*/?-]+/gu)) for (const suffix of path[0].split("/").map((_, i, parts) => parts.slice(i).join("/"))) if (suffix && matchGlob(suffix, normalized, false)) return pattern;
311
318
  }
312
319
  return null;
313
320
  }
@@ -3678,6 +3685,137 @@ function firstStdinShell(body, state) {
3678
3685
  }
3679
3686
  return null;
3680
3687
  }
3688
+ // src/hook/shell/inline-tokens.ts
3689
+ const REGEXP_PREFIX = /^(?:[({[=,:;!&|?+*~%^<>-]|return|throw|case|yield|await|typeof|void|delete|in|of|else|do)$/;
3690
+ const CONTROL_PAREN = /^(?:if|while|for|with|switch|catch)$/;
3691
+ const BLOCK_PREFIX = /^(?:|;|else|do|try|catch|finally)$/;
3692
+ const LINE_BREAK = /[\r\n\u2028\u2029]/;
3693
+ const REGEXP_STATEMENT_END = /^\s*(?:[;},)\]]|\.(?!\d)|$)/;
3694
+ const REGEXP_TOKEN = "<regexp>";
3695
+ function tokenizeInlineCode(code, interpreter) {
3696
+ const node = interpreter === "node" || interpreter === "deno" || interpreter === "bun";
3697
+ const comments = node ? /\/\*[^]*?\*\/|\/\/[^\r\n]*/.source : /#[^\r\n]*/.source;
3698
+ const quoted = /("""|'''|['"`])(?:\\[^]|(?!\1)[^\\])*\1/.source;
3699
+ const matcher = new RegExp([
3700
+ quoted,
3701
+ comments,
3702
+ /[A-Za-z_$][\w$]*|\r?\n|\+\+|--|[^\s]/.source
3703
+ ].join("|"), "g");
3704
+ const regexLiteral = /\/(?:\\[^\r\n]|\[(?:\\[^\r\n]|[^\]\\\r\n])*\]|[^/\\[\r\n])+\/([a-z]*)/iy;
3705
+ const quoteMatcher = new RegExp(quoted + "|['\"`]", "g");
3706
+ const tokens = [];
3707
+ const controlParens = [];
3708
+ const blockBraces = [];
3709
+ let previous = "";
3710
+ let previousEnd = 0;
3711
+ let regexpMayStart = true;
3712
+ for (let match = matcher.exec(code); match !== null; match = matcher.exec(code)) {
3713
+ const [text, quote] = match;
3714
+ if (quote === void 0 && /^(?:\/\/|\/\*|#)/.test(text)) continue;
3715
+ const start = match.index;
3716
+ if (node && text === "/") {
3717
+ if (code[start + 1] === "*") return null;
3718
+ if (regexpMayStart || previous === "}" || LINE_BREAK.test(code.slice(previousEnd, start))) {
3719
+ regexLiteral.lastIndex = start;
3720
+ const regexp = regexLiteral.exec(code);
3721
+ if (regexpMayStart && !regexp) return null;
3722
+ if (regexp) {
3723
+ const end = regexLiteral.lastIndex;
3724
+ const partialQuote = !regexpMayStart && regexp[0].match(quoteMatcher)?.some((part) => part.length === 1);
3725
+ const statement = regexp[1] === "" && REGEXP_STATEMENT_END.test(code.slice(end)) && (!partialQuote || /^\/['"]\/$/.test(regexp[0]));
3726
+ if (regexpMayStart || statement) {
3727
+ matcher.lastIndex = end;
3728
+ tokens.push({
3729
+ text: REGEXP_TOKEN,
3730
+ start,
3731
+ end
3732
+ });
3733
+ previous = REGEXP_TOKEN;
3734
+ previousEnd = end;
3735
+ regexpMayStart = false;
3736
+ continue;
3737
+ }
3738
+ if (partialQuote) return null;
3739
+ }
3740
+ }
3741
+ }
3742
+ if (quote === void 0 && /^['"`]$/.test(text)) return null;
3743
+ tokens.push({
3744
+ text,
3745
+ start,
3746
+ end: matcher.lastIndex,
3747
+ ...quote === void 0 ? {} : { literal: text.slice(quote.length, -quote.length) }
3748
+ });
3749
+ if (!node || isLineBreak(text)) continue;
3750
+ if (text === "(") controlParens.push(CONTROL_PAREN.test(previous));
3751
+ if (text === "{") blockBraces.push(BLOCK_PREFIX.test(previous) || previous === ")" && regexpMayStart);
3752
+ if (text === ")") regexpMayStart = controlParens.pop() ?? false;
3753
+ else if (text === "}") regexpMayStart = blockBraces.pop() ?? false;
3754
+ else regexpMayStart = REGEXP_PREFIX.test(text);
3755
+ previous = text;
3756
+ previousEnd = matcher.lastIndex;
3757
+ }
3758
+ return tokens;
3759
+ }
3760
+ function isLineBreak(text) {
3761
+ return text === "\n" || text === "\r\n";
3762
+ }
3763
+ const CLOSERS = /* @__PURE__ */ new Map([
3764
+ ["(", ")"],
3765
+ ["[", "]"],
3766
+ ["{", "}"]
3767
+ ]);
3768
+ function inlineGroup(tokens, open) {
3769
+ const initial = CLOSERS.get(tokens[open]?.text ?? "");
3770
+ return initial === void 0 ? null : readInlineArguments(tokens, open + 1, initial);
3771
+ }
3772
+ function inlineStatement(tokens, start) {
3773
+ return readInlineArguments(tokens, start);
3774
+ }
3775
+ function readInlineArguments(tokens, start, initial) {
3776
+ const closers = initial === void 0 ? [] : [initial];
3777
+ const args = [];
3778
+ let arg = [];
3779
+ let i = start;
3780
+ for (; i < tokens.length; i++) {
3781
+ const token = tokens[i];
3782
+ if (token === void 0) break;
3783
+ const { text } = token;
3784
+ if (initial === void 0 && closers.length === 0) {
3785
+ if (/^(?:[;)}\]]|if|unless|while|until|for|do|and|or)$/.test(text)) break;
3786
+ if (isLineBreak(text)) {
3787
+ if (arg.length !== 0 || args.length === 0) break;
3788
+ continue;
3789
+ }
3790
+ }
3791
+ if (text === closers.at(-1)) {
3792
+ closers.pop();
3793
+ if (initial !== void 0 && closers.length === 0) {
3794
+ if (arg.length > 0) args.push(arg);
3795
+ return {
3796
+ args,
3797
+ end: i
3798
+ };
3799
+ }
3800
+ } else if (text === "," && closers.length === (initial === void 0 ? 0 : 1)) {
3801
+ args.push(arg);
3802
+ arg = [];
3803
+ continue;
3804
+ } else {
3805
+ const closer = CLOSERS.get(text);
3806
+ if (closer !== void 0) closers.push(closer);
3807
+ }
3808
+ if (!isLineBreak(text)) arg.push(token);
3809
+ }
3810
+ if (initial === void 0 && closers.length === 0) {
3811
+ if (arg.length > 0) args.push(arg);
3812
+ return {
3813
+ args,
3814
+ end: i
3815
+ };
3816
+ }
3817
+ return null;
3818
+ }
3681
3819
  // src/hook/shell/inline-code.ts
3682
3820
  /** File-writing or file-removing APIs across Node, Deno, Bun, Python, Ruby and Perl. */
3683
3821
  const WRITE_API_PATTERNS = [
@@ -3700,20 +3838,6 @@ const WRITE_API_PATTERNS = [
3700
3838
  /\b(?:shelve|dbm)\.open\s*\(/,
3701
3839
  /\bsqlite3\.connect\s*\(/
3702
3840
  ];
3703
- /** APIs that start a process or a shell. */
3704
- const EXEC_API_PATTERNS = [
3705
- /\b(?:system|popen|spawn\w*|exec\w*|fork)\s*\(/,
3706
- /\b(?:system|exec)\s+['"]/,
3707
- /\b(?:subprocess|child_process|Open3)\b/,
3708
- /\bpty\.spawn\b/,
3709
- /\bcommands\.get/,
3710
- /\bIO\.popen\b/,
3711
- /\bDeno\.(?:run|Command)\b/,
3712
- /\bBun\.(?:spawn\w*|\$)/,
3713
- /%x[({[]/,
3714
- /\bqx\s*[({[/]/,
3715
- /`/
3716
- ];
3717
3841
  /** File-opening calls with a string-literal path: callee, path, and the rest of the arguments. */
3718
3842
  const OPEN_CALL = /\b([A-Za-z_][\w.]*)(?=\s*\(\s*(['"])((?:\\.|(?!\2)[^\\])*)\2\s*(?:,([^)]*))?\))/g;
3719
3843
  const RUBY_OPEN = /\bFile\.(?:new|open)\s+(['"])([^'"]*)\1\s*,\s*([^\s,;]+)/g;
@@ -3767,28 +3891,116 @@ function inlineCodeWrites(code, isProtected) {
3767
3891
  if (WRITE_API_PATTERNS.some((re) => re.test(code))) return true;
3768
3892
  return isProtected !== void 0 && (opensProtectedForWrite(code, isProtected) || writesNamedFile(code, isProtected));
3769
3893
  }
3770
- function inlineCodeExecs(code) {
3771
- return EXEC_API_PATTERNS.some((re) => re.test(code));
3772
- }
3773
- const MAX_LITERALS = 32;
3774
- /**
3775
- * Command strings inline code may hand to a shell: every quoted string literal, plus each list
3776
- * of string literals joined with spaces (`subprocess.run(['git', 'push', 'origin', 'main'])`).
3777
- */
3778
- function extractInlineCommandStrings(code) {
3779
- const literals = [];
3780
- for (const m of code.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)) {
3781
- const body = (m[2] ?? "").replace(/\\(.)/g, "$1");
3782
- if (body.trim() !== "") literals.push(body);
3783
- if (literals.length >= MAX_LITERALS) break;
3784
- }
3785
- for (const m of code.matchAll(/(?:(['"])((?:\\.|(?!\1)[^\\])*)\1\s*,\s*)?\[\s*((?:(['"])(?:\\.|(?!\4)[^\\])*\4\s*,?\s*)+)\]/g)) {
3786
- const items = [...(m[3] ?? "").matchAll(/(['"])((?:\\.|(?!\1)[^\\])*)\1/g)].map((x) => x[2] ?? "");
3787
- if (m[2] !== void 0) items.unshift(m[2]);
3788
- if (items.length > 1) literals.push(items.join(" "));
3789
- if (literals.length >= 64) break;
3790
- }
3791
- return literals;
3894
+ const NODE_WRITES = /^(?:writeFile(?:Sync)?|appendFile(?:Sync)?|createWriteStream)$/;
3895
+ const PATH_METHODS = /^(?:read_bytes|read_text|write_bytes|write_text)$/;
3896
+ const IDENTIFIER = /^[A-Za-z_]\w*$/;
3897
+ const CHANGE_DIRECTORY = /^f?chdir$/;
3898
+ const FILE_WRITE_METHOD = /^(?:write|writelines)$/;
3899
+ function literalPath(arg) {
3900
+ const token = arg?.length === 1 ? arg[0] : void 0;
3901
+ if (token?.literal === void 0 || /^[`]/.test(token.text) || token.literal.includes("\\")) return;
3902
+ return token.literal;
3903
+ }
3904
+ function pathConstructor(tokens, index) {
3905
+ const start = tokens[index]?.text === "pathlib" && tokens[index + 1]?.text === "." ? index + 2 : index;
3906
+ if (tokens[start]?.text !== "Path" || tokens[start + 1]?.text !== "(") return void 0;
3907
+ const group = inlineGroup(tokens, start + 1);
3908
+ return group?.args.length === 1 && group.end === tokens.length - 1 ? literalPath(group.args[0]) : void 0;
3909
+ }
3910
+ function boundPythonPath(code, tokens, name, pathObject) {
3911
+ let path;
3912
+ for (let i = 0; i < tokens.length; i++) {
3913
+ const token = tokens[i];
3914
+ if (token?.text !== name) continue;
3915
+ if (tokens[i + 1]?.text === "=" && (token.start === 0 || /[\n;]/.test(code[token.start - 1] ?? ""))) {
3916
+ let end = i + 2;
3917
+ while (end < tokens.length && !/^[;\r\n]+$/.test(tokens[end]?.text ?? "")) end++;
3918
+ const value = tokens.slice(i + 2, end);
3919
+ if (path !== void 0) return void 0;
3920
+ path = pathObject && value.at(-1)?.text === ")" ? pathConstructor(value, 0) : literalPath(value);
3921
+ if (path === void 0) return void 0;
3922
+ } else if (pathObject) {
3923
+ if (tokens[i + 1]?.text !== "." || !PATH_METHODS.test(tokens[i + 2]?.text ?? "")) return void 0;
3924
+ } else if (tokens[i - 2]?.text !== "open" || tokens[i - 1]?.text !== "(") return;
3925
+ }
3926
+ return path;
3927
+ }
3928
+ function fileArgument(code, tokens, arg) {
3929
+ const direct = literalPath(arg);
3930
+ const name = arg?.length === 1 ? arg[0]?.text : void 0;
3931
+ return direct ?? (name && IDENTIFIER.test(name) ? boundPythonPath(code, tokens, name, false) : void 0);
3932
+ }
3933
+ function pythonContextWrites(tokens, alias) {
3934
+ const name = tokens[alias]?.text ?? "";
3935
+ if (tokens[alias - 1]?.text !== "as" || !IDENTIFIER.test(name) || tokens[alias + 1]?.text !== ":") return [];
3936
+ const writes = [];
3937
+ for (let i = 0; i < tokens.length; i++) {
3938
+ if (i === alias || tokens[i]?.text !== name) continue;
3939
+ if (i < alias || tokens[i - 1]?.text === "." || tokens[i + 1]?.text !== "." || !FILE_WRITE_METHOD.test(tokens[i + 2]?.text ?? "") || tokens[i + 3]?.text !== "(") return [];
3940
+ writes.push(i + 2);
3941
+ }
3942
+ return writes;
3943
+ }
3944
+ function literalInlineWriteTargets(code, interpreter, isProtected) {
3945
+ const python = interpreter.startsWith("python");
3946
+ if (!python && interpreter !== "node" && interpreter !== "bun" && interpreter !== "deno") return null;
3947
+ const tokens = tokenizeInlineCode(code, interpreter);
3948
+ if (tokens === null) return null;
3949
+ const modeled = /* @__PURE__ */ new Set();
3950
+ const pathReceivers = /* @__PURE__ */ new Map();
3951
+ const targets = [];
3952
+ const firstStatement = tokens.findIndex((token) => !/^[\r\n]+$/.test(token.text));
3953
+ let cwdMayChange = false;
3954
+ for (let i = 0; i < tokens.length; i++) {
3955
+ const token = tokens[i];
3956
+ if (!token) continue;
3957
+ const { text, literal } = token;
3958
+ const indexedMember = !python && tokens[i - 1]?.text === "[" && tokens[i + 1]?.text === "]" && /^(?:[\w$]+|[)\]])$/.test(tokens[i - 2]?.text ?? "");
3959
+ cwdMayChange ||= CHANGE_DIRECTORY.test(indexedMember ? literal ?? text : text);
3960
+ if (tokens[i + 1]?.text !== "(") continue;
3961
+ if (/^(?:eval|exec)$/.test(text)) return null;
3962
+ if (python && text === "Path") {
3963
+ const group = inlineGroup(tokens, i + 1);
3964
+ const path = group?.args.length === 1 ? literalPath(group.args[0]) : void 0;
3965
+ if (group && path !== void 0) pathReceivers.set(group.end, path);
3966
+ }
3967
+ if (python && text === "open") {
3968
+ const group = inlineGroup(tokens, i + 1);
3969
+ if (!group || tokens[i - 1]?.text === "." && tokens[i - 2]?.text !== "io") continue;
3970
+ if (group.args.length > 7 || group.args.some((arg) => arg[0]?.text === "opener")) return null;
3971
+ const mode = group.args[1];
3972
+ const writes = mode !== void 0 && !isReadOnlyMode(mode.map((part) => part.text).join("").replace(/^mode=/, ""));
3973
+ const chained = tokens[group.end + 1]?.text === "." && FILE_WRITE_METHOD.test(tokens[group.end + 2]?.text ?? "");
3974
+ const contextMode = mode?.[0]?.text === "mode" && mode[1]?.text === "=" ? mode.slice(2) : mode;
3975
+ const contextWrites = firstStatement === i - 1 && tokens[firstStatement]?.text === "with" && group.args.length === 2 && literalPath(contextMode) !== void 0 ? pythonContextWrites(tokens, group.end + 2) : [];
3976
+ if (!writes && !chained && contextWrites.length === 0) continue;
3977
+ const path = fileArgument(code, tokens, group.args[0]);
3978
+ if (path === void 0) return null;
3979
+ targets.push(path);
3980
+ modeled.add(i);
3981
+ if (chained) modeled.add(group.end + 2);
3982
+ for (const write of contextWrites) modeled.add(write);
3983
+ } else if (python && /^(?:write_text|write_bytes)$/.test(text)) {
3984
+ const receiver = tokens[i - 2]?.text ?? "";
3985
+ const path = pathReceivers.get(i - 2) ?? (IDENTIFIER.test(receiver) ? boundPythonPath(code, tokens, receiver, true) : void 0);
3986
+ if (path === void 0) return null;
3987
+ targets.push(path);
3988
+ modeled.add(i);
3989
+ } else if (!python && NODE_WRITES.test(text)) {
3990
+ const path = literalPath(inlineGroup(tokens, i + 1)?.args[0]);
3991
+ if (path === void 0) return null;
3992
+ targets.push(path);
3993
+ modeled.add(i);
3994
+ }
3995
+ }
3996
+ if (targets.length === 0 || cwdMayChange && targets.some((path) => !isAbsolutePath(path))) return null;
3997
+ const remaining = tokens.map((token, i) => modeled.has(i) ? "_" : token.text).join(" ");
3998
+ const syntax = tokens.map((token, i) => {
3999
+ if (modeled.has(i)) return "_";
4000
+ if (token.literal === void 0 || /^[rwaxbt+]+$|^\s*(?:\+?>|\+<)/.test(token.literal)) return token.text;
4001
+ return "''";
4002
+ }).join(" ");
4003
+ return WRITE_API_PATTERNS.some((re) => re.test(syntax)) || opensProtectedForWrite(remaining.replace(/\s+\.\s+/g, "."), isProtected) || writesNamedFile(code, isProtected) ? null : targets;
3792
4004
  }
3793
4005
  const PYTHON_VALUE_OPTIONS = /* @__PURE__ */ new Set([
3794
4006
  "-W",
@@ -3816,6 +4028,223 @@ function interpreterReadsProgramFromStdin(cmdName, args) {
3816
4028
  }
3817
4029
  return true;
3818
4030
  }
4031
+ // src/hook/shell/inline-exec.ts
4032
+ const EXEC_CALLS = /^(?:system|popen|spawn(?:Sync|l|le|lp|lpe|v|ve|vp|vpe)?|exec(?:Sync|File|FileSync|l|le|lp|lpe|v|ve|vp|vpe)?|fork|Popen|check_call|check_output|capture2e?|capture3|pipeline(?:_r|_rw|_start|_w)?)$/;
4033
+ const EXEC_MODULE_CALLS = /* @__PURE__ */ new Map([
4034
+ ["subprocess", /^(?:run|call|check_call|check_output|Popen|getoutput|getstatusoutput)$/],
4035
+ ["commands", /^get(?:output|statusoutput)$/],
4036
+ ["Deno", /^(?:run|Command)$/],
4037
+ ["IO", /^popen[234]$/],
4038
+ ["Open3", /^popen(?:2e?|3)$/]
4039
+ ]);
4040
+ const OS_EXEC = /^(?:spawn|exec)([lv])(?:e|p|pe)?$/;
4041
+ const BARE_EXEC = /^(?:system|spawn|exec)$/;
4042
+ const RUBY_PIPELINE = /^pipeline(?:_r|_rw|_start|_w)?$/;
4043
+ const UNPARSED_EXEC = /\b(?:system|popen\w*|spawn\w*|exec\w*|fork)\s*\(|\b(?:subprocess|child_process|commands|Open3|Deno|Bun)\b|\b(?:system|exec)\s+['"]/;
4044
+ const MAX_COMMANDS = 32;
4045
+ function staticString(arg) {
4046
+ if (arg?.length !== 1) return void 0;
4047
+ const token = arg[0];
4048
+ if (token?.text.startsWith("`") && token.literal?.includes("${")) return void 0;
4049
+ return token?.literal?.replace(/\\([^])/g, "$1");
4050
+ }
4051
+ function argv(arg, python = false) {
4052
+ if (arg?.[0]?.text !== "[" && !(python && arg?.[0]?.text === "(")) return null;
4053
+ const group = inlineGroup(arg, 0);
4054
+ if (!group || group.end !== arg.length - 1) return null;
4055
+ const values = group.args.map(staticString);
4056
+ return values.every((value) => value !== void 0) ? values : null;
4057
+ }
4058
+ function argvCommand(values) {
4059
+ return {
4060
+ script: values.map((value) => "'" + value.replaceAll("'", "'\\''") + "'").join(" "),
4061
+ hint: values.join(" ")
4062
+ };
4063
+ }
4064
+ function commandArgument(args, name, code, interpreter) {
4065
+ const operand = args[0];
4066
+ if (!operand?.length) return null;
4067
+ if (interpreter === "ruby" && BARE_EXEC.test(name) && operand[0]?.text === "[") {
4068
+ const pair = inlineGroup(operand, 0);
4069
+ const program = pair?.args[0];
4070
+ if (program && pair?.args.length === 2 && pair.end === operand.length - 1) return positionalCommand([program, ...args.slice(1)], code);
4071
+ }
4072
+ const python = interpreter.startsWith("python");
4073
+ const program = staticString(operand);
4074
+ const list = argv(operand, python);
4075
+ if (list) return argvCommand(list);
4076
+ const options = args[1];
4077
+ const operands = name === "Command" ? objectOption(options, "args") : options;
4078
+ if (program !== void 0) {
4079
+ const argumentList = argv(operands);
4080
+ if (argumentList) return argvCommand([program, ...argumentList]);
4081
+ if (operands?.[0]?.text === "[") return {
4082
+ script: null,
4083
+ hint: `${program} ${argumentHint(operands, code)?.hint ?? ""}`
4084
+ };
4085
+ if (args.length > 1 && (interpreter === "ruby" && name !== "popen" || interpreter === "perl" && BARE_EXEC.test(name))) return positionalCommand(args, code);
4086
+ if (!/\s/.test(program) && !/^(?:exec|execSync|system|popen|getoutput|getstatusoutput|capture\w*)$/.test(name)) return argvCommand([program]);
4087
+ return {
4088
+ script: program,
4089
+ hint: program
4090
+ };
4091
+ }
4092
+ if (/^(?:run|spawn|spawnSync)$/.test(name) && operand[0]?.text === "{") {
4093
+ const command = objectOption(operand, "cmd");
4094
+ const commandList = argv(command);
4095
+ return commandList ? argvCommand(commandList) : argumentHint(command ?? operand, code);
4096
+ }
4097
+ if (operands?.[0]?.text === "[") return argumentHint([...operand, ...operands], code);
4098
+ if (args.length > 1 && (interpreter === "ruby" || interpreter === "perl")) return argumentHint(args.flat(), code);
4099
+ return argumentHint(operand, code);
4100
+ }
4101
+ function objectOption(object, key) {
4102
+ if (object?.[0]?.text !== "{") return void 0;
4103
+ return inlineGroup(object, 0)?.args.find((arg) => (arg[0]?.literal ?? arg[0]?.text) === key && arg[1]?.text === ":")?.slice(2);
4104
+ }
4105
+ function argumentHint(operand, code) {
4106
+ const first = operand[0];
4107
+ const last = operand.at(-1);
4108
+ if (first === void 0 || last === void 0) return null;
4109
+ return {
4110
+ script: null,
4111
+ hint: code.slice(first.start, last.end)
4112
+ };
4113
+ }
4114
+ function positionalCommand(args, code) {
4115
+ const values = args.map(staticString);
4116
+ return values.every((value) => value !== void 0) ? argvCommand(values) : argumentHint(args.flat(), code);
4117
+ }
4118
+ function keywordArgument(args, name) {
4119
+ return args.find((arg) => arg[0]?.text === name && arg[1]?.text === "=")?.slice(2);
4120
+ }
4121
+ function pythonOsCommand(args, name, form, code) {
4122
+ const offset = name.startsWith("spawn") ? 1 : 0;
4123
+ const program = keywordArgument(args, "file") ?? keywordArgument(args, "path") ?? args[offset] ?? [];
4124
+ if (form === "v") {
4125
+ const operands = keywordArgument(args, "args") ?? keywordArgument(args, "argv") ?? args[offset + 1] ?? [];
4126
+ const path = staticString(program);
4127
+ const values = argv(operands, true);
4128
+ return path !== void 0 && values ? argvCommand([path, ...values.slice(1)]) : argumentHint([...program, ...operands], code);
4129
+ }
4130
+ const end = name.endsWith("e") ? -1 : void 0;
4131
+ return positionalCommand([program, ...args.slice(offset + 2, end)], code);
4132
+ }
4133
+ function pythonImports(tokens) {
4134
+ const bindings = /* @__PURE__ */ new Map();
4135
+ const starModules = /* @__PURE__ */ new Set();
4136
+ for (let i = 0; i < tokens.length; i++) {
4137
+ if (tokens[i]?.text !== "import") continue;
4138
+ const statement = inlineStatement(tokens, i + 1);
4139
+ if (!statement) continue;
4140
+ const module = tokens[i - 2]?.text === "from" ? tokens[i - 1]?.text : void 0;
4141
+ const group = statement.args[0];
4142
+ const imports = group?.[0]?.text === "(" ? inlineGroup(group, 0)?.args : statement.args;
4143
+ for (const [name, as, alias] of imports ?? []) {
4144
+ if (!name) continue;
4145
+ const local = as?.text === "as" && alias ? alias.text : name.text;
4146
+ if (module === "subprocess" || module === "os") {
4147
+ if (name.text === "*") starModules.add(module);
4148
+ else bindings.set(local, module + "." + name.text);
4149
+ } else if (module === void 0 && (name.text === "subprocess" || name.text === "os")) bindings.set(local, name.text);
4150
+ }
4151
+ }
4152
+ return {
4153
+ bindings,
4154
+ starModules
4155
+ };
4156
+ }
4157
+ function pythonStarOwner(starModules, name) {
4158
+ if (starModules?.has("subprocess") && EXEC_MODULE_CALLS.get("subprocess")?.test(name)) return "subprocess";
4159
+ if (starModules?.has("os") && (OS_EXEC.test(name) || /^(?:system|popen)$/.test(name))) return "os";
4160
+ }
4161
+ function callCommands(args, name, owner, code, interpreter) {
4162
+ if (interpreter.startsWith("python")) {
4163
+ const form = owner === "os" ? OS_EXEC.exec(name)?.[1] : void 0;
4164
+ if (form) return [pythonOsCommand(args, name, form, code)];
4165
+ if (owner === "subprocess" || owner === "os" && /^(?:system|popen)$/.test(name)) {
4166
+ const command = keywordArgument(args, /^(?:run|call|check_call|check_output|Popen)$/.test(name) ? "args" : "cmd") ?? args[0];
4167
+ return [commandArgument(command ? [command] : [], name, code, interpreter)];
4168
+ }
4169
+ }
4170
+ if (interpreter === "ruby" && RUBY_PIPELINE.test(name)) return args.filter((arg) => arg[0]?.text !== "{").map((arg) => commandArgument([arg], name, code, interpreter));
4171
+ let operands = args;
4172
+ if (interpreter === "ruby") {
4173
+ if (operands[0]?.[0]?.text === "{") operands = operands.slice(1);
4174
+ const option = operands.findIndex((arg, index) => index > 0 && (arg[0]?.text === "{" || arg[1]?.text === ":"));
4175
+ if (option !== -1) operands = operands.slice(0, option);
4176
+ }
4177
+ return [commandArgument(operands, name, code, interpreter)];
4178
+ }
4179
+ function extractInlineCommands(code, interpreter) {
4180
+ const tokens = tokenizeInlineCode(code, interpreter);
4181
+ const ruby = interpreter === "ruby";
4182
+ const perl = interpreter === "perl";
4183
+ const python = interpreter.startsWith("python");
4184
+ if (tokens === null) return UNPARSED_EXEC.test(code) || (ruby || perl) && /[%]x|\bqx|`/.test(code) ? [{
4185
+ script: null,
4186
+ hint: code
4187
+ }] : [];
4188
+ const imports = python ? pythonImports(tokens) : void 0;
4189
+ const result = [];
4190
+ for (let i = 0; i < tokens.length && result.length < MAX_COMMANDS; i++) {
4191
+ const token = tokens[i];
4192
+ if (token === void 0) continue;
4193
+ const text = token.text;
4194
+ const literal = token.literal;
4195
+ if ((ruby || perl) && text.startsWith("`") && literal !== void 0) {
4196
+ result.push({
4197
+ script: literal,
4198
+ hint: literal
4199
+ });
4200
+ continue;
4201
+ }
4202
+ const delimiter = tokens[ruby ? i + 2 : i + 1]?.text;
4203
+ if (ruby && text === "%" && tokens[i + 1]?.text === "x" || perl && text === "qx") {
4204
+ const close = delimiter === "{" ? "}" : delimiter === "(" ? ")" : delimiter === "[" ? "]" : delimiter;
4205
+ const start = ruby ? i + 2 : i + 1;
4206
+ const opener = tokens[start];
4207
+ const end = tokens.findIndex((next, index) => index > start && next.text === close);
4208
+ if (opener && close && end !== -1) {
4209
+ const script = code.slice(opener.end, tokens[end]?.start);
4210
+ result.push({
4211
+ script,
4212
+ hint: script
4213
+ });
4214
+ i = end;
4215
+ continue;
4216
+ }
4217
+ }
4218
+ if (interpreter === "bun" && text === "$" && tokens[i + 1]?.text.startsWith("`")) {
4219
+ const script = staticString(tokens.slice(i + 1, i + 2));
4220
+ const hint = script ?? tokens[i + 1]?.literal;
4221
+ if (hint !== void 0) result.push({
4222
+ script: script ?? null,
4223
+ hint
4224
+ });
4225
+ continue;
4226
+ }
4227
+ const member = tokens[i - 1]?.text === ".";
4228
+ const bracketName = !python && !ruby && !perl && tokens[i - 1]?.text === "[" && tokens[i + 1]?.text === "]" && /^(?:[\w$]+|[)\]])$/.test(tokens[i - 2]?.text ?? "") ? literal : void 0;
4229
+ const open = bracketName === void 0 ? i + 1 : i + 2;
4230
+ const receiver = member ? tokens[i - 2]?.text : void 0;
4231
+ const imported = member ? void 0 : imports?.bindings.get(text)?.split(".");
4232
+ const owner = member ? imports?.bindings.get(receiver ?? "") ?? receiver : imported?.[0] ?? pythonStarOwner(imports?.starModules, text);
4233
+ const name = bracketName ?? imported?.[1] ?? text;
4234
+ if (owner === "<regexp>" && name === "exec") continue;
4235
+ if (!EXEC_CALLS.test(name) && !EXEC_MODULE_CALLS.get(owner ?? "")?.test(name)) continue;
4236
+ const parenthesized = tokens[open]?.text === "(";
4237
+ const bare = (ruby || perl) && BARE_EXEC.test(name) && (tokens[open]?.literal !== void 0 || /^[{$]/.test(tokens[open]?.text ?? "") || ruby && tokens[open]?.text === "[");
4238
+ if (!parenthesized && !bare) continue;
4239
+ const group = parenthesized ? inlineGroup(tokens, open) : inlineStatement(tokens, open);
4240
+ const commands = group ? callCommands(group.args, name, owner, code, interpreter) : [argumentHint(tokens.slice(open + Number(parenthesized)), code)];
4241
+ for (const command of commands) {
4242
+ if (command) result.push(command);
4243
+ if (result.length === MAX_COMMANDS) break;
4244
+ }
4245
+ }
4246
+ return result;
4247
+ }
3819
4248
  /** Words longer than this, or with more `{`, are dynamic instead of expanded (bounds the work). */
3820
4249
  const MAX_BRACE_TEXT = 16384;
3821
4250
  const MAX_BRACE_OPENERS = 256;
@@ -5502,14 +5931,14 @@ function analyzeShellCommand(command, initialCwd, repoRoot) {
5502
5931
  }
5503
5932
  return fed;
5504
5933
  }
5505
- /** Inline code that starts processes: keyword fallback on the code and its command strings parsed. */
5506
5934
  function walkInlineExecCode(code, cmdName, state) {
5507
- if (!inlineCodeExecs(code)) return;
5508
- opaqueSegments.push({
5509
- raw: code,
5510
- reason: `inline ${cmdName} code starts a process`
5511
- });
5512
- for (const s of extractInlineCommandStrings(code)) walkNested(s, state, code);
5935
+ for (const { script, hint } of extractInlineCommands(code, cmdName)) {
5936
+ opaqueSegments.push({
5937
+ raw: hint,
5938
+ reason: `inline ${cmdName} code starts a process`
5939
+ });
5940
+ if (script) walkNested(script, state, hint);
5941
+ }
5513
5942
  }
5514
5943
  function analyzeResolvedInvocation(resolvedArgs, state, prefixAssignments, redirects, rawCommand) {
5515
5944
  if (resolvedArgs.length === 0) return;
@@ -5617,7 +6046,10 @@ function analyzeShellCommand(command, initialCwd, repoRoot) {
5617
6046
  });
5618
6047
  }
5619
6048
  for (const wt of cmdWrites) {
5620
- writeTargets.push(wt);
6049
+ writeTargets.push(wt.kind === "inline-code" ? {
6050
+ ...wt,
6051
+ interpreter: cmdName
6052
+ } : wt);
5621
6053
  if (wt.kind === "inline-code") walkInlineExecCode(wt.target ?? wt.raw, cmdName, state);
5622
6054
  }
5623
6055
  commands.push({
@@ -5747,14 +6179,30 @@ const BUILTIN_INTEGRATION_BRANCHES = [
5747
6179
  ];
5748
6180
  /** Default value for `hooks.integrationBranches` when omitted from repository config. */
5749
6181
  const DEFAULT_CONFIG_INTEGRATION_BRANCHES = ["pilot/mfe"];
5750
- /** Allowed `git -c <key>=<value>` keys (Plan 2.1.2 row 3). Matched case-insensitively. */
5751
- const GIT_C_ALLOWLIST = [
6182
+ const GIT_CONFIG_WRITE_ALLOWLIST = [
5752
6183
  "color.*",
5753
6184
  "core.pager",
5754
6185
  "advice.*",
5755
6186
  "user.name",
5756
6187
  "user.email"
5757
6188
  ];
6189
+ /** Allowed `git -c <key>=<value>` keys (Plan 2.1.2 row 3). Matched case-insensitively. */
6190
+ const GIT_C_ALLOWLIST = [
6191
+ ...GIT_CONFIG_WRITE_ALLOWLIST,
6192
+ "rerere.*",
6193
+ "merge.conflictStyle",
6194
+ "diff.algorithm",
6195
+ "diff.context",
6196
+ "diff.interHunkContext",
6197
+ "diff.renames",
6198
+ "log.abbrevCommit",
6199
+ "log.date",
6200
+ "log.decorate",
6201
+ "format.numbered",
6202
+ "format.subjectPrefix",
6203
+ "format.thread",
6204
+ "init.defaultBranch"
6205
+ ];
5758
6206
  /** Exact git config environment variables denied in any assignment position (Plan 2.1.2 row 2). */
5759
6207
  const GIT_CONFIG_ENV_EXACT = /* @__PURE__ */ new Set([
5760
6208
  "GIT_CONFIG_COUNT",
@@ -6083,12 +6531,18 @@ function isProtectedTag(ref, knownTag = false) {
6083
6531
  if (knownTag) return ref.startsWith("v") && ref.length >= 2;
6084
6532
  return /^v\d/.test(ref);
6085
6533
  }
6086
- function isGitCKeyAllowed(key) {
6534
+ function isGitKeyAllowed(key, allowlist) {
6087
6535
  const lower = key.toLowerCase();
6088
- for (const pat of GIT_C_ALLOWLIST) if (pat.endsWith(".*")) {
6089
- if (lower.startsWith(pat.slice(0, -1))) return true;
6090
- } else if (lower === pat) return true;
6091
- return false;
6536
+ return allowlist.some((pattern) => {
6537
+ const normalized = pattern.toLowerCase();
6538
+ return normalized.endsWith(".*") ? lower.startsWith(normalized.slice(0, -1)) : lower === normalized;
6539
+ });
6540
+ }
6541
+ function isGitCKeyAllowed(key) {
6542
+ return isGitKeyAllowed(key, GIT_C_ALLOWLIST);
6543
+ }
6544
+ function isGitConfigWriteKeyAllowed(key) {
6545
+ return isGitKeyAllowed(key, GIT_CONFIG_WRITE_ALLOWLIST);
6092
6546
  }
6093
6547
  // src/hook/rules/verdict.ts
6094
6548
  function makeVerdict(ruleId, ctx, reason, extra) {
@@ -6933,7 +7387,7 @@ function evaluateGitConfig(subArgs, ctx, verdicts) {
6933
7387
  verdicts.push(makeVerdict("git-bypass-hooks", ctx, "Modifying 'core.hooksPath' via 'git config' is denied."));
6934
7388
  return;
6935
7389
  }
6936
- if (!isGitCKeyAllowed(key)) verdicts.push(makeVerdict("git-c-disallowed", ctx, `Modifying non-allowlisted git config key '${key}' via 'git config' is denied.`));
7390
+ if (!isGitConfigWriteKeyAllowed(key)) verdicts.push(makeVerdict("git-c-disallowed", ctx, `Modifying non-allowlisted git config key '${key}' via 'git config' is denied.`));
6937
7391
  }
6938
7392
  function cleanupOptions(command, args) {
6939
7393
  let force = false;
@@ -6978,7 +7432,7 @@ function evaluateGitCommand(cmd, ctx) {
6978
7432
  const parsed = parseGitGlobalOptions(cmd);
6979
7433
  const caseInsensitive = isCaseInsensitivePlatform(ctx.platform);
6980
7434
  for (const pair of parsed.configPairs) if (pair.key.toLowerCase() === "core.hookspath") verdicts.push(makeVerdict("git-bypass-hooks", ctx, `Overriding 'core.hooksPath' via 'git -c ${pair.raw}' is denied.`));
6981
- else if (!isGitCKeyAllowed(pair.key)) verdicts.push(makeVerdict("git-c-disallowed", ctx, `Git config override '-c ${pair.key}' is not in the allowlist (color.*, core.pager, advice.*, user.name, user.email).`));
7435
+ else if (!isGitCKeyAllowed(pair.key)) verdicts.push(makeVerdict("git-c-disallowed", ctx, `Git config override '-c ${pair.key}' is not in the allowlist (${GIT_C_ALLOWLIST.join(", ")}).`));
6982
7436
  for (const pair of parsed.configEnvs) if (pair.key.toLowerCase() === "core.hookspath") verdicts.push(makeVerdict("git-bypass-hooks", ctx, `Overriding 'core.hooksPath' via '--config-env=${pair.raw}' is denied.`));
6983
7437
  else verdicts.push(makeVerdict("git-c-disallowed", ctx, `Setting git config from environment via '--config-env=${pair.raw}' is denied.`));
6984
7438
  for (const option of parsed.redirects) verdicts.push(makeVerdict("git-redirect-option", ctx, `'git ${option}' points git at another repository, work tree or executable directory.`));
@@ -7350,27 +7804,153 @@ function evaluateRmAndBulkWriteCommands(cmd, ctx, verdicts) {
7350
7804
  }
7351
7805
  return;
7352
7806
  }
7353
- if (cmd.name === "tar") {
7354
- if (cmd.args.some((a, idx) => {
7355
- const v = a.value;
7356
- if (!v) return false;
7357
- if (v === "--extract" || v === "--get") return true;
7358
- if (v.startsWith("-") && !v.startsWith("--") && v.includes("x")) return true;
7359
- if (idx === 0 && /^[a-zA-Z]+$/.test(v) && v.includes("x")) return true;
7360
- return false;
7361
- })) {
7362
- let dir = ".";
7363
- for (let i = 0; i < cmd.args.length; i++) {
7364
- const v = cmd.args[i]?.value;
7365
- if (v === "-C" || v === "--directory") {
7366
- dir = cmd.args[i + 1]?.value ?? ".";
7367
- i++;
7368
- } else if (v?.startsWith("--directory=")) dir = v.slice(12);
7807
+ if (cmd.name === "tar") evaluateTarExtract(cmd, ctx, verdicts, caseInsensitive);
7808
+ }
7809
+ const TAR_SHORT_VALUE_FLAGS = /[CbFfgHIKLNTVX]/;
7810
+ const TAR_LONG_VALUE_FLAGS = /* @__PURE__ */ new Set([
7811
+ "--add-file",
7812
+ "--after-date",
7813
+ "--block-size",
7814
+ "--blocking-factor",
7815
+ "--cd",
7816
+ "--checkpoint-action",
7817
+ "--directory",
7818
+ "--exclude",
7819
+ "--exclude-from",
7820
+ "--exclude-ignore",
7821
+ "--exclude-ignore-recursive",
7822
+ "--exclude-tag",
7823
+ "--exclude-tag-all",
7824
+ "--exclude-tag-under",
7825
+ "--file",
7826
+ "--files-from",
7827
+ "--format",
7828
+ "--gid",
7829
+ "--gname",
7830
+ "--group",
7831
+ "--group-map",
7832
+ "--hole-detection",
7833
+ "--include",
7834
+ "--index-file",
7835
+ "--info-script",
7836
+ "--label",
7837
+ "--level",
7838
+ "--listed-incremental",
7839
+ "--mode",
7840
+ "--mtime",
7841
+ "--new-volume-script",
7842
+ "--newer",
7843
+ "--newer-ctime",
7844
+ "--newer-ctime-than",
7845
+ "--newer-mtime",
7846
+ "--newer-mtime-than",
7847
+ "--newer-than",
7848
+ "--no-quote-chars",
7849
+ "--older",
7850
+ "--older-ctime",
7851
+ "--older-ctime-than",
7852
+ "--older-mtime",
7853
+ "--older-mtime-than",
7854
+ "--older-than",
7855
+ "--options",
7856
+ "--owner",
7857
+ "--owner-map",
7858
+ "--passphrase",
7859
+ "--pax-option",
7860
+ "--quote-chars",
7861
+ "--quoting-style",
7862
+ "--record-size",
7863
+ "--rmt-command",
7864
+ "--rsh-command",
7865
+ "--sort",
7866
+ "--sparse-version",
7867
+ "--starting-file",
7868
+ "--strip-components",
7869
+ "--suffix",
7870
+ "--tape-length",
7871
+ "--to-command",
7872
+ "--totals",
7873
+ "--transform",
7874
+ "--uid",
7875
+ "--uname",
7876
+ "--use-compress-program",
7877
+ "--volno-file",
7878
+ "--warning",
7879
+ "--xattrs-exclude",
7880
+ "--xattrs-include",
7881
+ "--xform"
7882
+ ]);
7883
+ function tarShortTakesValue(flag, value) {
7884
+ if (flag !== "s") return TAR_SHORT_VALUE_FLAGS.test(flag);
7885
+ if (!value) return false;
7886
+ const delimiter = value.charAt(0);
7887
+ const patternEnd = value.indexOf(delimiter, 1);
7888
+ const replacementEnd = value.lastIndexOf(delimiter);
7889
+ return patternEnd > 0 && replacementEnd > patternEnd && /^[bghHprRsS]*$/.test(value.slice(replacementEnd + 1));
7890
+ }
7891
+ function evaluateTarExtract(cmd, ctx, verdicts, caseInsensitive) {
7892
+ let extracts = false;
7893
+ let dir = cmd.cwd;
7894
+ let unknownDirectory = cmd.cwdUnknown;
7895
+ let rootDestination = false;
7896
+ const destinations = /* @__PURE__ */ new Set();
7897
+ const applyValueOption = (flag, target) => {
7898
+ if (flag === "C" || flag === "--directory" || flag === "--cd") {
7899
+ dir = resolveTarDirectory(target, dir, ctx, caseInsensitive);
7900
+ unknownDirectory ||= dir === null;
7901
+ } else if (flag === "T" || flag === "--files-from" || flag === "--add-file") destinations.add(dir ?? cmd.cwd);
7902
+ else if (flag === "K" || flag === "--starting-file") destinations.add(cmd.cwd);
7903
+ };
7904
+ for (let i = 0; i < cmd.args.length; i++) {
7905
+ const arg = cmd.args[i];
7906
+ const prefix = arg?.value ?? arg?.segments?.[0] ?? "";
7907
+ if (prefix === "--") break;
7908
+ if (prefix.startsWith("--")) {
7909
+ extracts ||= prefix === "--extract" || prefix === "--get";
7910
+ const [flag = ""] = prefix.split("=", 1);
7911
+ if (!TAR_LONG_VALUE_FLAGS.has(flag)) continue;
7912
+ applyValueOption(flag, prefix.includes("=") ? arg?.value?.slice(flag.length + 1) ?? null : cmd.args[++i]?.value ?? null);
7913
+ } else if (prefix.startsWith("-") && prefix.length > 1) for (let j = 1; j < prefix.length; j++) {
7914
+ const flag = prefix.charAt(j);
7915
+ extracts ||= flag === "x";
7916
+ const attached = arg?.value === null || j + 1 < prefix.length;
7917
+ const target = attached ? arg?.value?.slice(j + 1) ?? null : cmd.args[i + 1]?.value ?? null;
7918
+ if (!tarShortTakesValue(flag, target)) continue;
7919
+ if (!attached) i++;
7920
+ applyValueOption(flag, target);
7921
+ break;
7922
+ }
7923
+ else if (i === 0 && /^[a-zA-Z]+$/.test(prefix)) {
7924
+ extracts = prefix.includes("x");
7925
+ for (const flag of prefix) {
7926
+ const target = cmd.args[i + 1]?.value ?? null;
7927
+ if (!tarShortTakesValue(flag, target)) continue;
7928
+ i++;
7929
+ applyValueOption(flag, target);
7369
7930
  }
7370
- const resolved = resolveRepoRelative(dir, cmd.cwd, ctx.repoRoot, caseInsensitive);
7371
- if (cmd.cwdUnknown || resolved.relPath === ".") verdicts.push(makeVerdict("shell-opaque-write", ctx, "`tar -x` extracts archive entries directly over the repository root."));
7931
+ } else destinations.add(dir ?? cmd.cwd);
7932
+ }
7933
+ if (!extracts) return;
7934
+ destinations.add(dir ?? cmd.cwd);
7935
+ for (const destination of destinations) {
7936
+ const { relPath } = resolveRepoRelative(destination, cmd.cwd, ctx.repoRoot, caseInsensitive);
7937
+ if (relPath === null) continue;
7938
+ rootDestination ||= relPath === ".";
7939
+ const protectedPath = classifyProtectedPath(relPath, ctx.config, {
7940
+ caseInsensitive,
7941
+ recursiveRemovalOrMove: true
7942
+ });
7943
+ if (protectedPath.kind !== "none") {
7944
+ verdicts.push(makeVerdict("shell-write-protected", ctx, `\`tar -x\` extracts archive entries into protected path '${protectedPath.pattern}'.`));
7945
+ return;
7372
7946
  }
7373
7947
  }
7948
+ if (unknownDirectory || rootDestination) verdicts.push(makeVerdict("shell-opaque-write", ctx, unknownDirectory ? "`tar -x` may extract archive entries over the repository root or a protected directory." : "`tar -x` extracts archive entries directly over the repository root."));
7949
+ }
7950
+ function resolveTarDirectory(target, cwd, ctx, caseInsensitive) {
7951
+ if (!target || cwd === null && !isAbsolutePath(target)) return null;
7952
+ const base = cwd ?? ctx.cwd;
7953
+ return resolveRepoRelative(ctx.resolvePath?.(target, base) ?? target, base, ctx.repoRoot, caseInsensitive).normalized;
7374
7954
  }
7375
7955
  /**
7376
7956
  * npm config lines that leave out devDependencies (`omit=dev`, `omit[]=dev`, `production=true`,
@@ -7388,9 +7968,20 @@ function evaluateWriteTargets(targets, ctx, verdicts) {
7388
7968
  for (const wt of targets) {
7389
7969
  if (wt.kind === "inline-code") {
7390
7970
  const code = wt.target ?? wt.raw;
7971
+ const protectedMention = (path) => {
7972
+ const hit = findProtectedLiteralMention(path, ctx.config);
7973
+ if (hit !== null || wt.cwdUnknown) return hit;
7974
+ const { relPath } = resolveRepoRelative(ctx.resolvePath?.(path, wt.cwd) ?? path, wt.cwd, ctx.repoRoot, caseInsensitive);
7975
+ if (relPath === null) return null;
7976
+ return classifyProtectedPath(relPath, ctx.config, {
7977
+ caseInsensitive,
7978
+ touchesManagedBlock: true
7979
+ }).pattern;
7980
+ };
7391
7981
  const isProtected = (path) => findProtectedLiteralMention(path, ctx.config) !== null;
7392
7982
  if (!inlineCodeWrites(code, isProtected)) continue;
7393
- const hit = findProtectedLiteralMention(code, ctx.config);
7983
+ const paths = wt.interpreter ? literalInlineWriteTargets(code, wt.interpreter, isProtected) : null;
7984
+ const hit = paths === null ? findProtectedLiteralMention(code, ctx.config) : paths.map(protectedMention).find((path) => path !== null) ?? null;
7394
7985
  if (hit !== null) verdicts.push(makeVerdict("shell-write-protected", ctx, `Inline script writes protected path '${hit}'. Use dedicated edit tools for gate files, or '--prune-suppressions' / 'size --update' / 'baseline move' for baselines.`));
7395
7986
  continue;
7396
7987
  }
@@ -7534,6 +8125,28 @@ function omitsDevDependencies(cmd, command) {
7534
8125
  if (cmd.name === "npm" && (includesDev("include", false, false) || production === "false" && !prodOnly)) return false;
7535
8126
  return prodOnly || production !== void 0 && production !== "" && production !== "false" || includesDev("omit", config.get("NODE_ENV") === "production", true);
7536
8127
  }
8128
+ function hasNpmGlobalShorthand(args) {
8129
+ let global = false;
8130
+ for (let i = 0; i < args.length;) {
8131
+ const value = args[i]?.value;
8132
+ if (value === "--") break;
8133
+ if (value === null) return false;
8134
+ const option = readPackageOption("npm", args, i);
8135
+ i = option?.nextIndex ?? i + 1;
8136
+ if (option?.flag === "-g") global = value === "-g" && option.enabled;
8137
+ else if (option?.flag === "-L" || overridesNpmGlobal(option?.flag)) global = false;
8138
+ }
8139
+ return global;
8140
+ }
8141
+ function overridesNpmGlobal(flag) {
8142
+ if (!flag?.startsWith("--")) return false;
8143
+ const name = flag.slice(2).replace(/^(?:no-)+/, "");
8144
+ return name !== "" && [
8145
+ "global",
8146
+ "local",
8147
+ "location"
8148
+ ].some((key) => key.startsWith(name));
8149
+ }
7537
8150
  function positionalsAfter(manager, args) {
7538
8151
  const out = [];
7539
8152
  for (let i = 0; i < args.length;) {
@@ -7667,6 +8280,7 @@ function evaluatePackageManagerCommand(cmd, ctx, verdicts) {
7667
8280
  return;
7668
8281
  }
7669
8282
  if (command === "install" || command === "install-test") {
8283
+ if (command === "install" && hasNpmGlobalShorthand(args)) return;
7670
8284
  const hasSaveFlag = afterSub.some((a) => a.value === "-D" || a.value === "-S" || a.value === "-E" || a.value === "--save" || a.value === "--save-dev" || a.value === "--save-optional" || a.value === "--save-exact");
7671
8285
  if (words.length > 0 || hasSaveFlag) verdicts.push(makeVerdict("pkg-modify-deps", ctx, "Installing packages with `npm install` modifies dependencies and lockfiles."));
7672
8286
  return;
@@ -8427,7 +9041,9 @@ function defineHook(spec) {
8427
9041
  ...request.resolvedPushTargets ? { resolvedPushTargets: request.resolvedPushTargets } : {}
8428
9042
  };
8429
9043
  const outcome = await spec.handler(normalized, runtimeCtx);
8430
- emit(renderHookOutput(agent, spec.event, outcome));
9044
+ const output = renderHookOutput(agent, spec.event, outcome);
9045
+ if (!settled) spec.onOutcome?.(outcome, output);
9046
+ emit(output);
8431
9047
  };
8432
9048
  run().catch((err) => {
8433
9049
  fail(formatErrorDetail(err));
@@ -8474,59 +9090,487 @@ async function dispatchHook(registry, request) {
8474
9090
  ...request.io ? { io: request.io } : {}
8475
9091
  });
8476
9092
  }
8477
- // src/hook/runtime/git-config.ts
8478
- function configEntries(output) {
8479
- return output.split("\0").filter(Boolean).map((item) => {
8480
- const separator = item.indexOf("\n");
8481
- return separator === -1 ? [item, null] : [item.slice(0, separator), item.slice(separator + 1)];
9093
+ // src/cli/git.ts
9094
+ /**
9095
+ * A check could not run: not inside a git work tree, git or another tool failed or printed no
9096
+ * report, or a file it reads (a baseline) is malformed. Exit code 2 with one line, without usage
9097
+ * text.
9098
+ */
9099
+ var EnvironmentError = class extends Error {
9100
+ name = "EnvironmentError";
9101
+ };
9102
+ /** One line on why `git <args>` failed: git is missing, or the first line it printed. */
9103
+ function gitFailure(args, error) {
9104
+ const { code, status, stderr } = error;
9105
+ if (code === "ENOENT") return "git is not installed or not on PATH";
9106
+ const said = String(stderr ?? "").split("\n").map((line) => line.trim()).find(Boolean);
9107
+ return `git ${args[0] ?? ""} failed (exit ${status ?? "?"})${said ? `: ${said}` : ""}`;
9108
+ }
9109
+ function git(cwd, args) {
9110
+ try {
9111
+ return execFileSync("git", args, {
9112
+ cwd,
9113
+ encoding: "utf8",
9114
+ maxBuffer: 268435456,
9115
+ stdio: [
9116
+ "ignore",
9117
+ "pipe",
9118
+ "pipe"
9119
+ ]
9120
+ });
9121
+ } catch (error) {
9122
+ throw new EnvironmentError(gitFailure(args, error));
9123
+ }
9124
+ }
9125
+ function readGitRef(cwd, args, absent) {
9126
+ const result = spawnSync("git", args, {
9127
+ cwd,
9128
+ encoding: "utf8"
8482
9129
  });
9130
+ if (result.status === absent) return null;
9131
+ if (result.status !== 0) throw new EnvironmentError(gitFailure(args, result.error ?? result));
9132
+ return result.stdout;
8483
9133
  }
8484
- // src/hook/runtime/push.ts
8485
- const HEADS = "refs/heads/";
8486
- const TAGS = "refs/tags/";
8487
- function currentBranch(io, cwd) {
8488
- const ref = io.git(cwd, [
8489
- "symbolic-ref",
9134
+ /** Local checks need the commit where HEAD diverged from the selected base. */
9135
+ function mergeBase(cwd, ref, read = readGitRef) {
9136
+ const sha = read(cwd, [
9137
+ "rev-parse",
9138
+ "--verify",
8490
9139
  "--quiet",
8491
- "HEAD"
8492
- ], 1)?.trimEnd();
8493
- return ref?.startsWith(HEADS) ? ref.slice(11) : void 0;
9140
+ "--end-of-options",
9141
+ `${ref}^{commit}`
9142
+ ], 1);
9143
+ if (!sha) {
9144
+ const branch = /^origin\/([a-z0-9_./][a-z0-9_./-]*)$/i.exec(ref)?.[1];
9145
+ const fetch = branch ? `git fetch origin ${branch}:refs/remotes/origin/${branch}` : "git fetch";
9146
+ throw new EnvironmentError(`cannot resolve ${JSON.stringify(ref)}. Run \`${fetch}\` or select an available base commit from this branch's history.`);
9147
+ }
9148
+ const commit = read(cwd, [
9149
+ "merge-base",
9150
+ "HEAD",
9151
+ sha.trim()
9152
+ ], 1)?.trim();
9153
+ if (!commit) throw new EnvironmentError(`no merge base with ${JSON.stringify(ref)}. In a shallow clone, run \`git fetch --unshallow\`. For unrelated histories, select the intended base from this branch's history.`);
9154
+ return commit;
8494
9155
  }
8495
- function gitConfig(io, cwd) {
8496
- const settings = /* @__PURE__ */ new Map();
8497
- const output = io.git(cwd, [
8498
- "config",
8499
- "--includes",
8500
- "--null",
8501
- "--list"
8502
- ]) ?? "";
8503
- for (const [key, value] of configEntries(output)) {
8504
- const values = settings.get(key) ?? [];
8505
- values.push(value ?? "true");
8506
- settings.set(key, values);
9156
+ const C_ESCAPES = {
9157
+ a: 7,
9158
+ b: 8,
9159
+ t: 9,
9160
+ n: 10,
9161
+ v: 11,
9162
+ f: 12,
9163
+ r: 13,
9164
+ "\"": 34,
9165
+ "\\": 92
9166
+ };
9167
+ /**
9168
+ * A C-quoted path from git ("a\"b", "a\tb", "\303\244"): git quotes paths with control
9169
+ * characters, quotes or backslashes, and writes bytes as octal escapes (UTF-8).
9170
+ */
9171
+ function unquote(quoted) {
9172
+ const bytes = [];
9173
+ let i = 1;
9174
+ while (i < quoted.length && quoted[i] !== "\"") {
9175
+ if (quoted[i] === "\\") {
9176
+ const octal = /^[0-7]{3}/.exec(quoted.slice(i + 1, i + 4));
9177
+ if (octal) {
9178
+ bytes.push(Number.parseInt(octal[0], 8));
9179
+ i += 4;
9180
+ } else {
9181
+ const next = quoted[i + 1] ?? "";
9182
+ bytes.push(C_ESCAPES[next] ?? next.charCodeAt(0));
9183
+ i += 2;
9184
+ }
9185
+ continue;
9186
+ }
9187
+ const char = String.fromCodePoint(quoted.codePointAt(i) ?? 0);
9188
+ bytes.push(...Buffer.from(char, "utf8"));
9189
+ i += char.length;
8507
9190
  }
8508
- return settings;
9191
+ return Buffer.from(bytes).toString("utf8");
8509
9192
  }
8510
- function target(ref, force = false, deletion = false) {
8511
- return {
8512
- dstBranch: ref.startsWith(HEADS) ? ref.slice(11) : ref,
8513
- isTag: ref.startsWith(TAGS),
8514
- isForce: force,
8515
- isDelete: deletion
8516
- };
9193
+ /**
9194
+ * The path of a `--- ` or `+++ ` diff header: C-quoted when it has special characters; otherwise
9195
+ * as is, except for the TAB git appends to a path that contains a space.
9196
+ */
9197
+ function headerPath(text) {
9198
+ if (text.startsWith("\"")) return unquote(text);
9199
+ return text.endsWith(" ") ? text.slice(0, -1) : text;
8517
9200
  }
8518
- function configuredTargets(io, cwd, branch, specs) {
8519
- return specs.map((spec) => {
8520
- const force = spec.startsWith("+");
8521
- const body = force ? spec.slice(1) : spec;
8522
- const colon = body.indexOf(":");
8523
- const source = colon === -1 ? body : body.slice(0, colon);
8524
- const dest = colon === -1 ? "" : body.slice(colon + 1);
8525
- if (body.includes("*") || !source && !dest) throw new Error("A configured Git push refspec can update multiple refs. Use an explicit branch refspec");
8526
- if (dest.startsWith("refs/")) return target(dest, force, !source);
8527
- const fullSource = source === "HEAD" || source === "@" ? branch && `${HEADS}${branch}` : (io.git(cwd, [
8528
- "rev-parse",
8529
- "--symbolic-full-name",
9201
+ /**
9202
+ * Lines that the working tree adds or changes relative to `commit`, in the files `pathspecs`
9203
+ * selects, per file relative to `cwd` (1-based, inclusive ranges). Renames are followed, so a
9204
+ * moved file only counts its edited lines; untracked files count whole. Every file is compared as
9205
+ * text (`--text`): otherwise a `-diff` or `binary` attribute in .gitattributes, or a NUL byte,
9206
+ * makes git print "Binary files … differ" without lines, and the change would seem to touch none.
9207
+ * `pathspecs` keeps binary files with other extensions out of that comparison (an empty list selects
9208
+ * every file).
9209
+ */
9210
+ function changedLines(cwd, commit, pathspecs, readGit = git, { interHunkContext } = {}) {
9211
+ const diff = readGit(cwd, [
9212
+ "-c",
9213
+ "core.quotePath=false",
9214
+ "diff",
9215
+ "--no-ext-diff",
9216
+ "--no-textconv",
9217
+ "--text",
9218
+ "--no-color",
9219
+ "--no-prefix",
9220
+ "--unified=0",
9221
+ ...interHunkContext === void 0 ? [] : [`--inter-hunk-context=${interHunkContext}`],
9222
+ "--find-renames",
9223
+ "--relative",
9224
+ commit,
9225
+ "--",
9226
+ ...pathspecs
9227
+ ]);
9228
+ const changed = /* @__PURE__ */ new Map();
9229
+ let current = null;
9230
+ let header = false;
9231
+ for (const line of diff.split("\n")) if (line.startsWith("diff --git ")) {
9232
+ header = true;
9233
+ current = null;
9234
+ } else if (header && line.startsWith("+++ ")) {
9235
+ const file = headerPath(line.slice(4));
9236
+ current = file === "/dev/null" ? null : [];
9237
+ if (current) changed.set(file, current);
9238
+ } else if (line.startsWith("@@ ")) {
9239
+ header = false;
9240
+ if (!current) continue;
9241
+ const match = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
9242
+ const start = Number(match?.[1] ?? 0);
9243
+ const count = match?.[2] === void 0 ? 1 : Number(match[2]);
9244
+ if (count > 0) current.push([start, start + count - 1]);
9245
+ }
9246
+ const untracked = readGit(cwd, [
9247
+ "ls-files",
9248
+ "-z",
9249
+ "--others",
9250
+ "--exclude-standard",
9251
+ "--",
9252
+ ...pathspecs
9253
+ ]);
9254
+ for (const file of untracked.split("\0").filter(Boolean)) changed.set(file, [[1, Number.MAX_SAFE_INTEGER]]);
9255
+ return changed;
9256
+ }
9257
+ // src/hook/runtime/state.ts
9258
+ function repoState(state, root, projectRoot) {
9259
+ return state.repositories[root] ??= {
9260
+ projectRoot,
9261
+ dirty: false,
9262
+ notifiedDirectories: [],
9263
+ protectedChanges: {},
9264
+ protectionBlocked: false
9265
+ };
9266
+ }
9267
+ var UnsafeTempDirectoryError = class extends Error {
9268
+ constructor(options) {
9269
+ super("Set TMPDIR to a directory you own or one protected by the sticky bit.", options);
9270
+ }
9271
+ };
9272
+ function checkedTempDirectory(dir, uid) {
9273
+ let parent;
9274
+ let stat;
9275
+ try {
9276
+ parent = realpathSync.native(dir);
9277
+ stat = lstatSync(parent);
9278
+ } catch (cause) {
9279
+ throw new UnsafeTempDirectoryError({ cause });
9280
+ }
9281
+ if (!stat.isDirectory() || stat.uid !== uid && (stat.mode & 512) === 0) throw new UnsafeTempDirectoryError();
9282
+ return parent;
9283
+ }
9284
+ function stateDirectory(create = true) {
9285
+ const uid = process.getuid?.();
9286
+ const parent = uid === void 0 ? tmpdir() : checkedTempDirectory(tmpdir(), uid);
9287
+ const dir = path.join(parent, uid === void 0 ? "od-harness" : `od-harness-${uid}`);
9288
+ if (create) mkdirSync(dir, {
9289
+ recursive: true,
9290
+ mode: 448
9291
+ });
9292
+ const stat = lstatSync(dir);
9293
+ if (!stat.isDirectory() || uid !== void 0 && (stat.uid !== uid || (stat.mode & 63) !== 0)) throw new Error("Hook state directory must be owned by the current user and private");
9294
+ return dir;
9295
+ }
9296
+ function stateFile(agent, session) {
9297
+ const key = createHash("sha256").update(session).digest("hex");
9298
+ return path.join(stateDirectory(), `${agent}-${key}.json`);
9299
+ }
9300
+ function stopMarker(dir, root) {
9301
+ const key = createHash("sha256").update(root).digest("hex");
9302
+ return path.join(dir, `stop-${key}.unverified`);
9303
+ }
9304
+ function setStopUnverified(root, unverified) {
9305
+ const file = stopMarker(stateDirectory(false), root);
9306
+ if (unverified) closeSync(openSync(file, "a", 384));
9307
+ else rmSync(file, { force: true });
9308
+ }
9309
+ function load(file) {
9310
+ const text = readOptional(file);
9311
+ if (text === void 0) return {
9312
+ version: 1,
9313
+ repositories: {},
9314
+ pending: {},
9315
+ stopProgress: {}
9316
+ };
9317
+ let state;
9318
+ try {
9319
+ state = JSON.parse(text);
9320
+ } catch {
9321
+ throw new Error("Hook session state is invalid JSON");
9322
+ }
9323
+ if (state?.version !== 1 || !state.repositories || !state.pending) throw new Error("Hook session state has an unsupported format");
9324
+ state.stopProgress ??= {};
9325
+ return state;
9326
+ }
9327
+ function staleLock(file, mtime) {
9328
+ const pid = Number(readOptional(file));
9329
+ if (Number.isSafeInteger(pid) && pid > 0) try {
9330
+ process.kill(pid, 0);
9331
+ return false;
9332
+ } catch (error) {
9333
+ if (error.code === "ESRCH") return true;
9334
+ }
9335
+ return Date.now() - mtime > 5e3;
9336
+ }
9337
+ async function lockFile(file, io) {
9338
+ for (;;) {
9339
+ const remaining = io.remaining();
9340
+ try {
9341
+ const fd = openSync(file, "wx", 384);
9342
+ try {
9343
+ writeFileSync(fd, String(process.pid));
9344
+ } catch (error) {
9345
+ unlinkSync(file);
9346
+ throw error;
9347
+ } finally {
9348
+ closeSync(fd);
9349
+ }
9350
+ return;
9351
+ } catch (error) {
9352
+ if (error.code !== "EEXIST") throw error;
9353
+ }
9354
+ try {
9355
+ const seen = lstatSync(file);
9356
+ if (staleLock(file, seen.mtimeMs)) {
9357
+ const current = lstatSync(file);
9358
+ if (current.ino === seen.ino && current.mtimeMs === seen.mtimeMs) unlinkSync(file);
9359
+ continue;
9360
+ }
9361
+ } catch (error) {
9362
+ if (!missing(error)) throw error;
9363
+ }
9364
+ await setTimeout$1(Math.min(remaining, 25));
9365
+ }
9366
+ }
9367
+ async function updateState(io, agent, session, update, onlyExisting = false) {
9368
+ const file = stateFile(agent, session);
9369
+ if (onlyExisting) try {
9370
+ lstatSync(file);
9371
+ } catch (error) {
9372
+ if (missing(error)) return void 0;
9373
+ throw error;
9374
+ }
9375
+ const lock = `${file}.lock`;
9376
+ await lockFile(lock, io);
9377
+ try {
9378
+ const state = load(file);
9379
+ const before = JSON.stringify(state);
9380
+ const result = update(state);
9381
+ const next = JSON.stringify(state);
9382
+ if (next !== before) {
9383
+ io.remaining();
9384
+ const temp = `${file}.${randomUUID()}.tmp`;
9385
+ try {
9386
+ writeFileSync(temp, next, {
9387
+ flag: "wx",
9388
+ mode: 384
9389
+ });
9390
+ renameSync(temp, file);
9391
+ } catch (error) {
9392
+ try {
9393
+ unlinkSync(temp);
9394
+ } catch (cleanup) {
9395
+ if (!missing(cleanup)) throw cleanup;
9396
+ }
9397
+ throw error;
9398
+ }
9399
+ }
9400
+ return result;
9401
+ } finally {
9402
+ unlinkSync(lock);
9403
+ }
9404
+ }
9405
+ // src/hook/runtime/decision-log.ts
9406
+ const MAX_LOG_BYTES = 5242880;
9407
+ const MAX_COMMAND_CHARS = 2e3;
9408
+ function decisionLogName(now, daysAgo = 0) {
9409
+ return `decisions-${(/* @__PURE__ */ new Date(now - daysAgo * 864e5)).toISOString().slice(0, 10)}.jsonl`;
9410
+ }
9411
+ function openLogFile(file, access) {
9412
+ const fd = openSync(file, access | constants.O_NOFOLLOW | constants.O_NONBLOCK, 384);
9413
+ try {
9414
+ const stat = fstatSync(fd);
9415
+ if (!stat.isFile() || stat.nlink !== 1 || process.getuid && (stat.uid !== process.getuid() || (stat.mode & 63) !== 0)) throw new Error("Hook decision log must be a private regular file owned by the current user");
9416
+ return {
9417
+ fd,
9418
+ size: stat.size
9419
+ };
9420
+ } catch (error) {
9421
+ closeSync(fd);
9422
+ throw error;
9423
+ }
9424
+ }
9425
+ function openDecisionLog(file, append = false) {
9426
+ if (!append) return {
9427
+ ...openLogFile(file, constants.O_RDONLY),
9428
+ created: false
9429
+ };
9430
+ const access = constants.O_WRONLY | constants.O_APPEND;
9431
+ try {
9432
+ return {
9433
+ ...openLogFile(file, access),
9434
+ created: false
9435
+ };
9436
+ } catch (error) {
9437
+ if (!missing(error)) throw error;
9438
+ }
9439
+ try {
9440
+ return {
9441
+ ...openLogFile(file, access | constants.O_CREAT | constants.O_EXCL),
9442
+ created: true
9443
+ };
9444
+ } catch (error) {
9445
+ if (error.code !== "EEXIST") throw error;
9446
+ return {
9447
+ ...openLogFile(file, access),
9448
+ created: false
9449
+ };
9450
+ }
9451
+ }
9452
+ function pruneLogs(dir, now) {
9453
+ const oldest = decisionLogName(now, 13);
9454
+ for (const name of readdirSync(dir)) if (name < oldest && /^decisions-\d{4}-\d{2}-\d{2}\.jsonl$/.test(name)) try {
9455
+ unlinkSync(path.join(dir, name));
9456
+ } catch {}
9457
+ }
9458
+ function sha256(text) {
9459
+ return createHash("sha256").update(text).digest("hex");
9460
+ }
9461
+ function repositoryDigest(root) {
9462
+ let resolved = path.resolve(root);
9463
+ try {
9464
+ resolved = realpathSync.native(resolved);
9465
+ } catch {}
9466
+ return sha256(resolved);
9467
+ }
9468
+ function decisionDetails(outcome) {
9469
+ switch (outcome?.decision) {
9470
+ case "allow": return {
9471
+ decision: "allow",
9472
+ ruleId: "allow",
9473
+ reason: "No hook rule intervened."
9474
+ };
9475
+ case "allow-with-notice":
9476
+ case "ask":
9477
+ case "deny": {
9478
+ const { decision, ruleId } = outcome;
9479
+ return {
9480
+ decision,
9481
+ ruleId,
9482
+ reason: RULE_TABLE[ruleId]?.category ?? "Repository context advisory."
9483
+ };
9484
+ }
9485
+ default: return {
9486
+ decision: "deny",
9487
+ ruleId: "hook-error",
9488
+ reason: "The hook could not evaluate the tool call."
9489
+ };
9490
+ }
9491
+ }
9492
+ function recordDecision(agent, event, input, repoRoot, outcome, full) {
9493
+ try {
9494
+ const now = Date.now();
9495
+ const dir = stateDirectory();
9496
+ const { fd, size, created } = openDecisionLog(path.join(dir, decisionLogName(now)), true);
9497
+ try {
9498
+ if (created) try {
9499
+ pruneLogs(dir, now);
9500
+ } catch {}
9501
+ if (size >= MAX_LOG_BYTES) return;
9502
+ const command = input?.command ?? null;
9503
+ const paths = input?.editTargets.map((target) => target.path) ?? [];
9504
+ const target = command ?? (paths.length > 1 ? JSON.stringify(paths) : paths[0]);
9505
+ const record = {
9506
+ time: new Date(now).toISOString(),
9507
+ agent,
9508
+ event,
9509
+ ...decisionDetails(outcome),
9510
+ repoHash: repoRoot === void 0 ? null : repositoryDigest(repoRoot),
9511
+ targetHash: target === void 0 ? null : sha256(target),
9512
+ ...full && command !== null ? { command: Array.from(command.slice(0, MAX_COMMAND_CHARS * 2)).slice(0, MAX_COMMAND_CHARS).join("") } : {}
9513
+ };
9514
+ const line = Buffer.from(`${JSON.stringify(record)}\n`);
9515
+ if (size + line.length <= MAX_LOG_BYTES) writeSync(fd, line);
9516
+ } finally {
9517
+ closeSync(fd);
9518
+ }
9519
+ } catch {}
9520
+ }
9521
+ // src/hook/runtime/git-config.ts
9522
+ function configEntries(output) {
9523
+ return output.split("\0").filter(Boolean).map((item) => {
9524
+ const separator = item.indexOf("\n");
9525
+ return separator === -1 ? [item, null] : [item.slice(0, separator), item.slice(separator + 1)];
9526
+ });
9527
+ }
9528
+ // src/hook/runtime/push.ts
9529
+ const HEADS = "refs/heads/";
9530
+ const TAGS = "refs/tags/";
9531
+ function currentBranch(io, cwd) {
9532
+ const ref = io.git(cwd, [
9533
+ "symbolic-ref",
9534
+ "--quiet",
9535
+ "HEAD"
9536
+ ], 1)?.trimEnd();
9537
+ return ref?.startsWith(HEADS) ? ref.slice(11) : void 0;
9538
+ }
9539
+ function gitConfig(io, cwd) {
9540
+ const settings = /* @__PURE__ */ new Map();
9541
+ const output = io.git(cwd, [
9542
+ "config",
9543
+ "--includes",
9544
+ "--null",
9545
+ "--list"
9546
+ ]) ?? "";
9547
+ for (const [key, value] of configEntries(output)) {
9548
+ const values = settings.get(key) ?? [];
9549
+ values.push(value ?? "true");
9550
+ settings.set(key, values);
9551
+ }
9552
+ return settings;
9553
+ }
9554
+ function target(ref, force = false, deletion = false) {
9555
+ return {
9556
+ dstBranch: ref.startsWith(HEADS) ? ref.slice(11) : ref,
9557
+ isTag: ref.startsWith(TAGS),
9558
+ isForce: force,
9559
+ isDelete: deletion
9560
+ };
9561
+ }
9562
+ function configuredTargets(io, cwd, branch, specs) {
9563
+ return specs.map((spec) => {
9564
+ const force = spec.startsWith("+");
9565
+ const body = force ? spec.slice(1) : spec;
9566
+ const colon = body.indexOf(":");
9567
+ const source = colon === -1 ? body : body.slice(0, colon);
9568
+ const dest = colon === -1 ? "" : body.slice(colon + 1);
9569
+ if (body.includes("*") || !source && !dest) throw new Error("A configured Git push refspec can update multiple refs. Use an explicit branch refspec");
9570
+ if (dest.startsWith("refs/")) return target(dest, force, !source);
9571
+ const fullSource = source === "HEAD" || source === "@" ? branch && `${HEADS}${branch}` : (io.git(cwd, [
9572
+ "rev-parse",
9573
+ "--symbolic-full-name",
8530
9574
  "--verify",
8531
9575
  "--end-of-options",
8532
9576
  source
@@ -8607,185 +9651,52 @@ function followedTags(io, cwd, explicitRemote, explicitSources) {
8607
9651
  "for-each-ref",
8608
9652
  "--merged",
8609
9653
  commit,
8610
- "--format=%(objecttype)%09%(refname)",
8611
- "refs/tags/v*"
8612
- ]) ?? "";
8613
- for (const item of merged.trimEnd().split("\n")) {
8614
- const ref = item.slice(4);
8615
- if (item.startsWith("tag ") && isProtectedTag(ref)) reachable.add(ref);
8616
- }
8617
- }
8618
- if (reachable.size === 0) return sources.includes(null) ? null : [];
8619
- const urls = io.git(cwd, [
8620
- "remote",
8621
- "get-url",
8622
- "--push",
8623
- "--all",
8624
- "--",
8625
- remote
8626
- ], 2)?.trimEnd().split("\n") ?? [remote];
8627
- let unknown = sources.includes(null);
8628
- const missing = /* @__PURE__ */ new Set();
8629
- for (const url of urls) {
8630
- const advertisement = io.git(cwd, [
8631
- "-c",
8632
- "credential.helper=",
8633
- "-c",
8634
- "core.gitProxy=none",
8635
- "ls-remote",
8636
- "--refs",
8637
- "--tags",
8638
- "--",
8639
- url,
8640
- "refs/tags/v*"
8641
- ], 128, {
8642
- timeout: 650,
8643
- env: {
8644
- GIT_ALLOW_PROTOCOL: "file:git:http:https:ssh",
8645
- GIT_SSH_COMMAND: "ssh -oBatchMode=yes"
8646
- }
8647
- });
8648
- if (advertisement === null) {
8649
- unknown = true;
8650
- continue;
8651
- }
8652
- const advertised = new Set(advertisement.trimEnd().split("\n").map((line) => line.split(" ")[1]));
8653
- for (const tag of reachable) if (!advertised.has(tag)) missing.add(tag);
8654
- }
8655
- return missing.size > 0 ? [...missing].map((tag) => target(tag)) : unknown ? null : [];
8656
- }
8657
- // src/cli/git.ts
8658
- /**
8659
- * A check could not run: not inside a git work tree, git or another tool failed or printed no
8660
- * report, or a file it reads (a baseline) is malformed. Exit code 2 with one line, without usage
8661
- * text.
8662
- */
8663
- var EnvironmentError = class extends Error {
8664
- name = "EnvironmentError";
8665
- };
8666
- /** One line on why `git <args>` failed: git is missing, or the first line it printed. */
8667
- function gitFailure(args, error) {
8668
- const { code, status, stderr } = error;
8669
- if (code === "ENOENT") return "git is not installed or not on PATH";
8670
- const said = String(stderr ?? "").split("\n").map((line) => line.trim()).find(Boolean);
8671
- return `git ${args[0] ?? ""} failed (exit ${status ?? "?"})${said ? `: ${said}` : ""}`;
8672
- }
8673
- function git(cwd, args) {
8674
- try {
8675
- return execFileSync("git", args, {
8676
- cwd,
8677
- encoding: "utf8",
8678
- maxBuffer: 268435456,
8679
- stdio: [
8680
- "ignore",
8681
- "pipe",
8682
- "pipe"
8683
- ]
8684
- });
8685
- } catch (error) {
8686
- throw new EnvironmentError(gitFailure(args, error));
8687
- }
8688
- }
8689
- const C_ESCAPES = {
8690
- a: 7,
8691
- b: 8,
8692
- t: 9,
8693
- n: 10,
8694
- v: 11,
8695
- f: 12,
8696
- r: 13,
8697
- "\"": 34,
8698
- "\\": 92
8699
- };
8700
- /**
8701
- * A C-quoted path from git ("a\"b", "a\tb", "\303\244"): git quotes paths with control
8702
- * characters, quotes or backslashes, and writes bytes as octal escapes (UTF-8).
8703
- */
8704
- function unquote(quoted) {
8705
- const bytes = [];
8706
- let i = 1;
8707
- while (i < quoted.length && quoted[i] !== "\"") {
8708
- if (quoted[i] === "\\") {
8709
- const octal = /^[0-7]{3}/.exec(quoted.slice(i + 1, i + 4));
8710
- if (octal) {
8711
- bytes.push(Number.parseInt(octal[0], 8));
8712
- i += 4;
8713
- } else {
8714
- const next = quoted[i + 1] ?? "";
8715
- bytes.push(C_ESCAPES[next] ?? next.charCodeAt(0));
8716
- i += 2;
8717
- }
8718
- continue;
9654
+ "--format=%(objecttype)%09%(refname)",
9655
+ "refs/tags/v*"
9656
+ ]) ?? "";
9657
+ for (const item of merged.trimEnd().split("\n")) {
9658
+ const ref = item.slice(4);
9659
+ if (item.startsWith("tag ") && isProtectedTag(ref)) reachable.add(ref);
8719
9660
  }
8720
- const char = String.fromCodePoint(quoted.codePointAt(i) ?? 0);
8721
- bytes.push(...Buffer.from(char, "utf8"));
8722
- i += char.length;
8723
9661
  }
8724
- return Buffer.from(bytes).toString("utf8");
8725
- }
8726
- /**
8727
- * The path of a `--- ` or `+++ ` diff header: C-quoted when it has special characters; otherwise
8728
- * as is, except for the TAB git appends to a path that contains a space.
8729
- */
8730
- function headerPath(text) {
8731
- if (text.startsWith("\"")) return unquote(text);
8732
- return text.endsWith(" ") ? text.slice(0, -1) : text;
8733
- }
8734
- /**
8735
- * Lines that the working tree adds or changes relative to `commit`, in the files `pathspecs`
8736
- * selects, per file relative to `cwd` (1-based, inclusive ranges). Renames are followed, so a
8737
- * moved file only counts its edited lines; untracked files count whole. Every file is compared as
8738
- * text (`--text`): otherwise a `-diff` or `binary` attribute in .gitattributes, or a NUL byte,
8739
- * makes git print "Binary files … differ" without lines, and the change would seem to touch none.
8740
- * `pathspecs` keeps binary files with other extensions out of that comparison (an empty list selects
8741
- * every file).
8742
- */
8743
- function changedLines(cwd, commit, pathspecs, readGit = git, { interHunkContext } = {}) {
8744
- const diff = readGit(cwd, [
8745
- "-c",
8746
- "core.quotePath=false",
8747
- "diff",
8748
- "--no-ext-diff",
8749
- "--no-textconv",
8750
- "--text",
8751
- "--no-color",
8752
- "--no-prefix",
8753
- "--unified=0",
8754
- ...interHunkContext === void 0 ? [] : [`--inter-hunk-context=${interHunkContext}`],
8755
- "--find-renames",
8756
- "--relative",
8757
- commit,
9662
+ if (reachable.size === 0) return sources.includes(null) ? null : [];
9663
+ const urls = io.git(cwd, [
9664
+ "remote",
9665
+ "get-url",
9666
+ "--push",
9667
+ "--all",
8758
9668
  "--",
8759
- ...pathspecs
8760
- ]);
8761
- const changed = /* @__PURE__ */ new Map();
8762
- let current = null;
8763
- let header = false;
8764
- for (const line of diff.split("\n")) if (line.startsWith("diff --git ")) {
8765
- header = true;
8766
- current = null;
8767
- } else if (header && line.startsWith("+++ ")) {
8768
- const file = headerPath(line.slice(4));
8769
- current = file === "/dev/null" ? null : [];
8770
- if (current) changed.set(file, current);
8771
- } else if (line.startsWith("@@ ")) {
8772
- header = false;
8773
- if (!current) continue;
8774
- const match = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
8775
- const start = Number(match?.[1] ?? 0);
8776
- const count = match?.[2] === void 0 ? 1 : Number(match[2]);
8777
- if (count > 0) current.push([start, start + count - 1]);
9669
+ remote
9670
+ ], 2)?.trimEnd().split("\n") ?? [remote];
9671
+ let unknown = sources.includes(null);
9672
+ const missing = /* @__PURE__ */ new Set();
9673
+ for (const url of urls) {
9674
+ const advertisement = io.git(cwd, [
9675
+ "-c",
9676
+ "credential.helper=",
9677
+ "-c",
9678
+ "core.gitProxy=none",
9679
+ "ls-remote",
9680
+ "--refs",
9681
+ "--tags",
9682
+ "--",
9683
+ url,
9684
+ "refs/tags/v*"
9685
+ ], 128, {
9686
+ timeout: 650,
9687
+ env: {
9688
+ GIT_ALLOW_PROTOCOL: "file:git:http:https:ssh",
9689
+ GIT_SSH_COMMAND: "ssh -oBatchMode=yes"
9690
+ }
9691
+ });
9692
+ if (advertisement === null) {
9693
+ unknown = true;
9694
+ continue;
9695
+ }
9696
+ const advertised = new Set(advertisement.trimEnd().split("\n").map((line) => line.split(" ")[1]));
9697
+ for (const tag of reachable) if (!advertised.has(tag)) missing.add(tag);
8778
9698
  }
8779
- const untracked = readGit(cwd, [
8780
- "ls-files",
8781
- "-z",
8782
- "--others",
8783
- "--exclude-standard",
8784
- "--",
8785
- ...pathspecs
8786
- ]);
8787
- for (const file of untracked.split("\0").filter(Boolean)) changed.set(file, [[1, Number.MAX_SAFE_INTEGER]]);
8788
- return changed;
9699
+ return missing.size > 0 ? [...missing].map((tag) => target(tag)) : unknown ? null : [];
8789
9700
  }
8790
9701
  // src/cli/config.ts
8791
9702
  const HARNESS_CONFIG = ".harness/config.json";
@@ -8976,19 +9887,7 @@ function worktreeFingerprint(io, root) {
8976
9887
  return createHash("sha256").update(head ?? "").update(status).update(filesFingerprint(io, root, dirty)).digest("hex");
8977
9888
  }
8978
9889
  function changesFingerprint(io, root, base) {
8979
- const baseSha = io.git(root, [
8980
- "rev-parse",
8981
- "--verify",
8982
- "--end-of-options",
8983
- `${base}^{commit}`
8984
- ], 128);
8985
- if (baseSha === null) throw new Error(`Stop base '${base}' could not be resolved`);
8986
- const mergeBase = io.git(root, [
8987
- "merge-base",
8988
- "HEAD",
8989
- baseSha.trim()
8990
- ], 1)?.trim();
8991
- if (!mergeBase) throw new Error(`HEAD and '${base}' have no merge base`);
9890
+ const commit = mergeBase(root, base, io.git.bind(io));
8992
9891
  const diffArgs = [
8993
9892
  "diff",
8994
9893
  "--no-ext-diff",
@@ -8998,13 +9897,13 @@ function changesFingerprint(io, root, base) {
8998
9897
  ];
8999
9898
  const diff = io.git(root, [
9000
9899
  ...diffArgs,
9001
- mergeBase,
9900
+ commit,
9002
9901
  "--"
9003
9902
  ]);
9004
9903
  const index = io.git(root, [
9005
9904
  ...diffArgs,
9006
9905
  "--cached",
9007
- mergeBase,
9906
+ commit,
9008
9907
  "--"
9009
9908
  ]);
9010
9909
  const untracked = (io.git(root, [
@@ -9015,7 +9914,7 @@ function changesFingerprint(io, root, base) {
9015
9914
  ]) ?? "").split("\0").filter(Boolean);
9016
9915
  if (!diff && !index && untracked.length === 0) return null;
9017
9916
  return createHash("sha256").update(JSON.stringify([
9018
- mergeBase,
9917
+ commit,
9019
9918
  diff,
9020
9919
  index
9021
9920
  ])).update(filesFingerprint(io, root, untracked)).digest("hex");
@@ -9260,123 +10159,6 @@ function protectedSnapshot(io, repo, platform) {
9260
10159
  function changedProtected(before, after) {
9261
10160
  return [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((file) => before[file]?.hash !== after[file]?.hash);
9262
10161
  }
9263
- // src/hook/runtime/state.ts
9264
- function repoState(state, root, projectRoot) {
9265
- return state.repositories[root] ??= {
9266
- projectRoot,
9267
- dirty: false,
9268
- notifiedDirectories: [],
9269
- protectedChanges: {},
9270
- protectionBlocked: false
9271
- };
9272
- }
9273
- function stateFile(agent, session) {
9274
- const dir = path.join(tmpdir(), "od-harness");
9275
- mkdirSync(dir, {
9276
- recursive: true,
9277
- mode: 448
9278
- });
9279
- const stat = lstatSync(dir);
9280
- if (!stat.isDirectory() || process.getuid && (stat.uid !== process.getuid() || (stat.mode & 63) !== 0)) throw new Error("Hook state directory must be owned by the current user and private");
9281
- const key = createHash("sha256").update(session).digest("hex");
9282
- return path.join(dir, `${agent}-${key}.json`);
9283
- }
9284
- function load(file) {
9285
- const text = readOptional(file);
9286
- if (text === void 0) return {
9287
- version: 1,
9288
- repositories: {},
9289
- pending: {},
9290
- stopProgress: {}
9291
- };
9292
- let state;
9293
- try {
9294
- state = JSON.parse(text);
9295
- } catch {
9296
- throw new Error("Hook session state is invalid JSON");
9297
- }
9298
- if (state?.version !== 1 || !state.repositories || !state.pending) throw new Error("Hook session state has an unsupported format");
9299
- state.stopProgress ??= {};
9300
- return state;
9301
- }
9302
- function staleLock(file, mtime) {
9303
- const pid = Number(readOptional(file));
9304
- if (Number.isSafeInteger(pid) && pid > 0) try {
9305
- process.kill(pid, 0);
9306
- return false;
9307
- } catch (error) {
9308
- if (error.code === "ESRCH") return true;
9309
- }
9310
- return Date.now() - mtime > 5e3;
9311
- }
9312
- async function lockFile(file, io) {
9313
- for (;;) {
9314
- const remaining = io.remaining();
9315
- try {
9316
- const fd = openSync(file, "wx", 384);
9317
- try {
9318
- writeFileSync(fd, String(process.pid));
9319
- } catch (error) {
9320
- unlinkSync(file);
9321
- throw error;
9322
- } finally {
9323
- closeSync(fd);
9324
- }
9325
- return;
9326
- } catch (error) {
9327
- if (error.code !== "EEXIST") throw error;
9328
- }
9329
- try {
9330
- const seen = lstatSync(file);
9331
- if (staleLock(file, seen.mtimeMs)) {
9332
- const current = lstatSync(file);
9333
- if (current.ino === seen.ino && current.mtimeMs === seen.mtimeMs) unlinkSync(file);
9334
- continue;
9335
- }
9336
- } catch (error) {
9337
- if (!missing(error)) throw error;
9338
- }
9339
- await setTimeout$1(Math.min(remaining, 25));
9340
- }
9341
- }
9342
- async function updateState(io, agent, session, update, onlyExisting = false) {
9343
- const file = stateFile(agent, session);
9344
- if (onlyExisting) try {
9345
- lstatSync(file);
9346
- } catch (error) {
9347
- if (missing(error)) return void 0;
9348
- throw error;
9349
- }
9350
- const lock = `${file}.lock`;
9351
- await lockFile(lock, io);
9352
- try {
9353
- const state = load(file);
9354
- const before = JSON.stringify(state);
9355
- const result = update(state);
9356
- const next = JSON.stringify(state);
9357
- if (next !== before) {
9358
- io.remaining();
9359
- const temp = `${file}.${randomUUID()}.tmp`;
9360
- try {
9361
- writeFileSync(temp, next, {
9362
- flag: "wx",
9363
- mode: 384
9364
- });
9365
- renameSync(temp, file);
9366
- } catch (error) {
9367
- try {
9368
- unlinkSync(temp);
9369
- } catch (cleanup) {
9370
- if (!missing(cleanup)) throw cleanup;
9371
- }
9372
- throw error;
9373
- }
9374
- }
9375
- return result;
9376
- } finally {
9377
- unlinkSync(lock);
9378
- }
9379
- }
9380
10162
  // src/hook/runtime/session.ts
9381
10163
  const ALLOW$1 = { decision: "allow" };
9382
10164
  function advisory(notice) {
@@ -9391,13 +10173,17 @@ function pendingKey(input) {
9391
10173
  }
9392
10174
  async function beforeShell(io, input, repos, platform) {
9393
10175
  if (!input.sessionId) return;
9394
- await updateState(io, input.agent, input.sessionId, (state) => {
9395
- state.pending[pendingKey(input)] = repos.map((repo) => ({
9396
- root: repo.root,
9397
- worktree: worktreeFingerprint(io, repo.root),
9398
- files: protectedSnapshot(io, repo, platform)
9399
- }));
9400
- });
10176
+ try {
10177
+ await updateState(io, input.agent, input.sessionId, (state) => {
10178
+ state.pending[pendingKey(input)] = repos.map((repo) => ({
10179
+ root: repo.root,
10180
+ worktree: worktreeFingerprint(io, repo.root),
10181
+ files: protectedSnapshot(io, repo, platform)
10182
+ }));
10183
+ });
10184
+ } catch (error) {
10185
+ if (!(error instanceof UnsafeTempDirectoryError)) throw error;
10186
+ }
9401
10187
  }
9402
10188
  function managedBaselineChanges(input) {
9403
10189
  if (!input.command) return /* @__PURE__ */ new Set();
@@ -9512,6 +10298,29 @@ ${detail}` : `The od-harness Stop check could not run (exit ${result.status}).
9512
10298
  ${detail}`
9513
10299
  };
9514
10300
  }
10301
+ async function checkChangesForStop(io, repo, command, cached) {
10302
+ try {
10303
+ const checkIO = new HookIO(io.remaining() - 1e3);
10304
+ const base = (hookEnv().stopBase?.trim() || void 0) ?? repo.config.base ?? "origin/main";
10305
+ const fingerprint = changesFingerprint(checkIO, repo.root, base);
10306
+ const checked = fingerprint !== null && (cached?.fingerprint !== fingerprint || cached.status === 2) ? await runStopCheck(checkIO, repo.root, command, fingerprint) : void 0;
10307
+ return {
10308
+ fingerprint,
10309
+ checked,
10310
+ stillCurrent: !checked || changesFingerprint(checkIO, repo.root, base) === fingerprint
10311
+ };
10312
+ } catch (error) {
10313
+ return {
10314
+ fingerprint: null,
10315
+ checked: {
10316
+ fingerprint: null,
10317
+ status: 2,
10318
+ notice: `The od-harness Stop check could not complete.\n${error instanceof Error ? error.message : String(error)}`
10319
+ },
10320
+ stillCurrent: true
10321
+ };
10322
+ }
10323
+ }
9515
10324
  async function stop(io, input, project, repos, platform) {
9516
10325
  const session = input.sessionId;
9517
10326
  if (!session) return ALLOW$1;
@@ -9566,22 +10375,15 @@ async function stop(io, input, project, repos, platform) {
9566
10375
  if (protection?.decision === "block") return protection;
9567
10376
  if (protection?.decision === "allow-with-notice") messages.push(protection.notice);
9568
10377
  }
9569
- if (input.stopHookActive) {
9570
- if (original.checked?.status === 1) messages.push(original.checked.notice);
9571
- continue;
9572
- }
9573
10378
  const command = repo.config.stopCommand;
9574
10379
  if (!original.dirty || !command) continue;
9575
- const base = hookEnv().stopBase ?? repo.config.base ?? "origin/main";
9576
- const fingerprint = changesFingerprint(io, repo.root, base);
9577
- const cached = original.checked;
9578
- const checked = fingerprint !== null && (cached?.fingerprint !== fingerprint || cached.status === 2) ? await runStopCheck(io, repo.root, command, fingerprint) : void 0;
9579
- const stillCurrent = !checked || changesFingerprint(io, repo.root, base) === fingerprint;
10380
+ const { fingerprint, checked, stillCurrent } = await checkChangesForStop(io, repo, command, original.checked);
9580
10381
  const result = await updateState(io, input.agent, session, (state) => {
9581
10382
  const entry = state.repositories[repo.root];
9582
10383
  const progress = state.stopProgress[project.root];
9583
- if (!entry || entry.revision !== original.revision || progress?.round !== snapshot.round) return ALLOW$1;
9584
- if (fingerprint === null) {
10384
+ if (!entry?.dirty || entry.revision !== original.revision || progress?.round !== snapshot.round) return ALLOW$1;
10385
+ if (fingerprint === null && !checked) {
10386
+ setStopUnverified(repo.root, false);
9585
10387
  entry.dirty = false;
9586
10388
  delete entry.checked;
9587
10389
  return ALLOW$1;
@@ -9592,18 +10394,25 @@ async function stop(io, input, project, repos, platform) {
9592
10394
  return prior.status === 0 ? ALLOW$1 : advisory(prior.notice);
9593
10395
  }
9594
10396
  if (!checked) return ALLOW$1;
9595
- if (stillCurrent) entry.checked = checked;
10397
+ if (stillCurrent) {
10398
+ entry.checked = checked;
10399
+ if (checked.status !== 2) setStopUnverified(repo.root, false);
10400
+ }
9596
10401
  if (checked.status === 0) {
9597
10402
  if (stillCurrent) entry.dirty = false;
9598
10403
  return ALLOW$1;
9599
10404
  }
9600
- if (checked.status === 1 && progress && progress.blocks < 2) {
10405
+ if (progress && progress.blocks < 2) {
9601
10406
  progress.blocks++;
9602
10407
  return {
9603
10408
  decision: "block",
9604
10409
  reason: checked.notice
9605
10410
  };
9606
10411
  }
10412
+ if (checked.status === 2) {
10413
+ setStopUnverified(repo.root, true);
10414
+ return advisory(`NOT VERIFIED: ${checked.notice}`);
10415
+ }
9607
10416
  return advisory(checked.notice);
9608
10417
  });
9609
10418
  if (result?.decision === "block") return result;
@@ -9693,14 +10502,22 @@ const ALLOW = { decision: "allow" };
9693
10502
  function platformKind(platform) {
9694
10503
  return platform === "darwin" || platform === "win32" ? platform : "linux";
9695
10504
  }
9696
- function registry(io, processCwd) {
10505
+ function registry(io, processCwd, log) {
9697
10506
  const platform = platformKind(process.platform);
9698
10507
  function register(event) {
9699
10508
  return defineHook({
9700
10509
  event,
10510
+ onOutcome(outcome, output) {
10511
+ if (log) log.result = {
10512
+ outcome,
10513
+ output
10514
+ };
10515
+ },
9701
10516
  async handler(input) {
9702
10517
  if (event === "pre-invocation") return preInvocation(io, input);
10518
+ if (log) log.input = input;
9703
10519
  const { project, active, cwd, notice } = repositories(input, processCwd, io);
10520
+ if (log) log.repoRoot = active.root;
9704
10521
  const repos = project === active ? [project] : [active, project].map((repo) => ({
9705
10522
  ...repo,
9706
10523
  config: {
@@ -9720,6 +10537,7 @@ function registry(io, processCwd) {
9720
10537
  if (event === "stop") return stop(io, normalized, project, repos, platform);
9721
10538
  if (event === "post-tool") return afterTool(io, normalized, repos, active, platform, notice);
9722
10539
  let warning = notice;
10540
+ let warningRule;
9723
10541
  let ask;
9724
10542
  const pushCache = /* @__PURE__ */ new Map();
9725
10543
  const tagCache = /* @__PURE__ */ new Map();
@@ -9758,7 +10576,10 @@ function registry(io, processCwd) {
9758
10576
  });
9759
10577
  if (outcome.decision === "deny") return outcome;
9760
10578
  if (outcome.decision === "ask") ask = outcome;
9761
- if (outcome.decision === "allow-with-notice") warning = warning ? `${warning}\n${outcome.notice}` : outcome.notice;
10579
+ if (outcome.decision === "allow-with-notice") {
10580
+ warningRule ??= outcome.ruleId;
10581
+ warning = warning ? `${warning}\n${outcome.notice}` : outcome.notice;
10582
+ }
9762
10583
  }
9763
10584
  if (normalized.command !== null) await beforeShell(io, normalized, repos, platform);
9764
10585
  io.remaining();
@@ -9766,7 +10587,13 @@ function registry(io, processCwd) {
9766
10587
  ...ask,
9767
10588
  reason: `${ask.reason}\n${warning}`
9768
10589
  };
9769
- return ask ?? (warning ? advisory(warning) : ALLOW);
10590
+ if (ask) return ask;
10591
+ if (!warning) return ALLOW;
10592
+ return {
10593
+ decision: "allow-with-notice",
10594
+ notice: warning,
10595
+ ruleId: warningRule ?? "hook-runtime"
10596
+ };
9770
10597
  }
9771
10598
  });
9772
10599
  }
@@ -9800,8 +10627,10 @@ async function runHook(agent, event) {
9800
10627
  let output;
9801
10628
  if (isAgentKind(agent) && isHookEventKind(event)) {
9802
10629
  const deadline = hookDeadlineMs(agent, event);
9803
- const io = new HookIO(deadline);
9804
- const hooks = registry(io, process.cwd());
10630
+ const io = new HookIO(event === "stop" ? deadline - 1e3 : deadline);
10631
+ const mode = hookLogMode();
10632
+ const log = mode !== "0" && (event === "pre-bash" || event === "pre-edit") ? {} : void 0;
10633
+ const hooks = registry(io, process.cwd(), log);
9805
10634
  let timer;
9806
10635
  let fault;
9807
10636
  const failure = new Promise((resolve) => {
@@ -9836,6 +10665,10 @@ async function runHook(agent, event) {
9836
10665
  }
9837
10666
  if (!process.stdin.readableEnded) process.stdin.destroy();
9838
10667
  }
10668
+ if (log && (event === "pre-bash" || event === "pre-edit")) {
10669
+ const outcome = log.result?.output === output ? log.result.outcome : void 0;
10670
+ recordDecision(agent, event, log.input, log.repoRoot, outcome, mode === "full");
10671
+ }
9839
10672
  } else output = renderUnknownRouteError(agent, event);
9840
10673
  process.exitCode = output.exitCode;
9841
10674
  await Promise.all([write(process.stdout, output.stdout), write(process.stderr, output.stderr)]);