vouchington-tooling 0.59.0 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +59 -0
  2. package/dist/cli/commands/hook.d.mts +2 -0
  3. package/dist/cli/commands/hook.mjs +19 -0
  4. package/dist/cli/index.mjs +6 -0
  5. package/dist/cli/parse-forwarded-commands.d.mts +6 -0
  6. package/dist/cli/parse-forwarded-commands.mjs +4 -0
  7. package/dist/cli/parse.d.mts +6 -0
  8. package/dist/cli/usage-text.d.mts +1 -0
  9. package/dist/cli/usage-text.mjs +170 -0
  10. package/dist/cli/usage.d.mts +2 -1
  11. package/dist/cli/usage.mjs +2 -156
  12. package/dist/command-policy/engine.d.mts +7 -0
  13. package/dist/command-policy/engine.mjs +58 -0
  14. package/dist/command-policy/git-patterns.d.mts +20 -0
  15. package/dist/command-policy/git-patterns.mjs +82 -0
  16. package/dist/command-policy/git-process.d.mts +4 -0
  17. package/dist/command-policy/git-process.mjs +54 -0
  18. package/dist/command-policy/github-checkout-owners.d.mts +22 -0
  19. package/dist/command-policy/github-checkout-owners.mjs +122 -0
  20. package/dist/command-policy/github-command-context.d.mts +6 -0
  21. package/dist/command-policy/github-command-context.mjs +19 -0
  22. package/dist/command-policy/github-command-cwd.d.mts +8 -0
  23. package/dist/command-policy/github-command-cwd.mjs +130 -0
  24. package/dist/command-policy/github-command-position.d.mts +7 -0
  25. package/dist/command-policy/github-command-position.mjs +12 -0
  26. package/dist/command-policy/github-configured-base.d.mts +25 -0
  27. package/dist/command-policy/github-configured-base.mjs +59 -0
  28. package/dist/command-policy/github-invocation.d.mts +9 -0
  29. package/dist/command-policy/github-invocation.mjs +80 -0
  30. package/dist/command-policy/github-merge-authority.d.mts +21 -0
  31. package/dist/command-policy/github-merge-authority.mjs +86 -0
  32. package/dist/command-policy/github-option-flags.d.mts +3 -0
  33. package/dist/command-policy/github-option-flags.mjs +67 -0
  34. package/dist/command-policy/github-options.d.mts +12 -0
  35. package/dist/command-policy/github-options.mjs +73 -0
  36. package/dist/command-policy/github-stack-workflow.d.mts +9 -0
  37. package/dist/command-policy/github-stack-workflow.mjs +94 -0
  38. package/dist/command-policy/github-workflow.d.mts +7 -0
  39. package/dist/command-policy/github-workflow.mjs +50 -0
  40. package/dist/command-policy/hook/args.d.mts +11 -0
  41. package/dist/command-policy/hook/args.mjs +49 -0
  42. package/dist/command-policy/hook/harness.d.mts +26 -0
  43. package/dist/command-policy/hook/harness.mjs +119 -0
  44. package/dist/command-policy/hook/policy-module.d.mts +7 -0
  45. package/dist/command-policy/hook/policy-module.mjs +48 -0
  46. package/dist/command-policy/hook/post-tool-use.d.mts +9 -0
  47. package/dist/command-policy/hook/post-tool-use.mjs +51 -0
  48. package/dist/command-policy/hook/pre-tool-use.d.mts +21 -0
  49. package/dist/command-policy/hook/pre-tool-use.mjs +45 -0
  50. package/dist/command-policy/hook/run.d.mts +17 -0
  51. package/dist/command-policy/hook/run.mjs +69 -0
  52. package/dist/command-policy/hook/types.d.mts +33 -0
  53. package/dist/command-policy/hook/types.mjs +5 -0
  54. package/dist/command-policy/index.d.mts +29 -0
  55. package/dist/command-policy/index.mjs +23 -0
  56. package/dist/command-policy/path-references.d.mts +14 -0
  57. package/dist/command-policy/path-references.mjs +68 -0
  58. package/dist/command-policy/path-rules.d.mts +11 -0
  59. package/dist/command-policy/path-rules.mjs +37 -0
  60. package/dist/command-policy/payload.d.mts +8 -0
  61. package/dist/command-policy/payload.mjs +54 -0
  62. package/dist/command-policy/types.d.mts +77 -0
  63. package/dist/command-policy/types.mjs +1 -0
  64. package/dist/index.d.mts +2 -0
  65. package/dist/index.mjs +1 -0
  66. package/dist/tmux/cli-shared.d.mts +18 -0
  67. package/dist/tmux/cli-shared.mjs +8 -0
  68. package/dist/tmux/cli.d.mts +3 -0
  69. package/dist/tmux/cli.mjs +34 -0
  70. package/dist/tmux/config.d.mts +24 -0
  71. package/dist/tmux/config.mjs +91 -0
  72. package/dist/tmux/fake-tmux.test-helpers.d.mts +46 -0
  73. package/dist/tmux/fake-tmux.test-helpers.mjs +105 -0
  74. package/dist/tmux/hook-payload.d.mts +8 -0
  75. package/dist/tmux/hook-payload.mjs +39 -0
  76. package/dist/tmux/index.d.mts +9 -0
  77. package/dist/tmux/index.mjs +7 -0
  78. package/dist/tmux/launcher.d.mts +11 -0
  79. package/dist/tmux/launcher.mjs +127 -0
  80. package/dist/tmux/reminder-post-tool.d.mts +21 -0
  81. package/dist/tmux/reminder-post-tool.mjs +88 -0
  82. package/dist/tmux/runner.d.mts +11 -0
  83. package/dist/tmux/runner.mjs +26 -0
  84. package/dist/tmux/session-name.d.mts +5 -0
  85. package/dist/tmux/session-name.mjs +10 -0
  86. package/dist/tmux/shell-quote.d.mts +9 -0
  87. package/dist/tmux/shell-quote.mjs +16 -0
  88. package/dist/tmux/up.d.mts +2 -0
  89. package/dist/tmux/up.mjs +73 -0
  90. package/dist/tmux/windows.d.mts +18 -0
  91. package/dist/tmux/windows.mjs +50 -0
  92. package/package.json +11 -1
  93. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
  94. package/scripts/tmux/tmux-agent-reminder.sh +68 -0
  95. package/scripts/tmux/tmux-name.sh +34 -0
  96. package/scripts/tmux/tmux-read-title.sh +13 -0
  97. package/scripts/tmux/tmux-target.sh +130 -0
@@ -0,0 +1,119 @@
1
+ import { isRecord } from "../payload.mjs";
2
+ /** Environment variables that mark an automated launch. Set to anything but empty, `0`, or `false`. */
3
+ const AUTOMATION_MARKERS = [
4
+ 'CI',
5
+ 'GITHUB_ACTIONS',
6
+ 'GITLAB_CI',
7
+ 'BUILDKITE',
8
+ 'CIRCLECI',
9
+ 'JENKINS_URL',
10
+ 'TF_BUILD',
11
+ 'CODEBUILD_BUILD_ID',
12
+ ];
13
+ /**
14
+ * True when the process runs unattended, where merge authority is never delegated: Claude's
15
+ * `claude -p` (`CLAUDE_CODE_SESSION_ATTENDED=0`) or a CI marker. `extraMarkers` adds
16
+ * caller-specific variable names.
17
+ */
18
+ export function isAutomationContext(env, extraMarkers = []) {
19
+ if (env.CLAUDE_CODE_SESSION_ATTENDED === '0')
20
+ return true;
21
+ return [...AUTOMATION_MARKERS, ...extraMarkers].some((name) => {
22
+ const value = env[name]?.trim().toLowerCase();
23
+ return value !== undefined && value !== '' && value !== '0' && value !== 'false';
24
+ });
25
+ }
26
+ /**
27
+ * Parses hook stdin into a payload. Blank, invalid, or non-object input is an empty payload unless
28
+ * `strict`, which throws so a blocking hook fails closed instead of reading a missing or truncated
29
+ * payload as "nothing to judge".
30
+ */
31
+ export function parseHookPayload(stdin, strict = false) {
32
+ if (stdin.trim() === '') {
33
+ if (strict)
34
+ throw new Error('hook payload is empty');
35
+ return {};
36
+ }
37
+ let parsed;
38
+ try {
39
+ parsed = JSON.parse(stdin);
40
+ }
41
+ catch (error) {
42
+ if (strict)
43
+ throw new Error(`hook payload is not valid JSON: ${error.message}`);
44
+ return {};
45
+ }
46
+ if (isRecord(parsed) && !Array.isArray(parsed))
47
+ return normalizeCursorShellPayload(parsed);
48
+ if (strict)
49
+ throw new Error('hook payload is not a JSON object');
50
+ return {};
51
+ }
52
+ // Cursor runs the Claude-compat hooks but names its shell tool `Shell` and reports the result as
53
+ // `tool_output`, a JSON string `{exitCode, output}`. Normalizing both to Claude's `Bash` +
54
+ // `tool_response` shape means policy reads one payload dialect. An existing `tool_response` is
55
+ // never overwritten.
56
+ export function normalizeCursorShellPayload(payload) {
57
+ if (payload.tool_name !== 'Shell')
58
+ return payload;
59
+ const result = cursorShellResult(payload.tool_output);
60
+ return {
61
+ ...payload,
62
+ tool_name: 'Bash',
63
+ ...(result === undefined || payload.tool_response !== undefined
64
+ ? {}
65
+ : { tool_response: result }),
66
+ };
67
+ }
68
+ function cursorShellResult(raw) {
69
+ let parsed = raw;
70
+ if (typeof raw === 'string') {
71
+ try {
72
+ parsed = JSON.parse(raw);
73
+ }
74
+ catch {
75
+ return undefined;
76
+ }
77
+ }
78
+ if (!isRecord(parsed) || typeof parsed.exitCode !== 'number')
79
+ return undefined;
80
+ return {
81
+ exit_code: parsed.exitCode,
82
+ stdout: firstString(parsed.stdout, parsed.output),
83
+ };
84
+ }
85
+ // GROK_AGENT is deliberately not a signal: it is a shell-level marker that could be exported in a
86
+ // Claude or Codex session.
87
+ function isGrokHookProcess(env) {
88
+ return Boolean(env.GROK_SESSION_ID || env.GROK_HOOK_EVENT);
89
+ }
90
+ // Cursor passes `cursor_version` in every payload and sets CURSOR_VERSION/CURSOR_PROJECT_DIR in the
91
+ // hook env. It runs the Claude-compat config, so the markers only override `claude`, never `codex`.
92
+ function isCursorHookProcess(declared, env, payload) {
93
+ return (declared === 'claude' &&
94
+ (typeof payload.cursor_version === 'string' ||
95
+ Boolean(env.CURSOR_VERSION || env.CURSOR_PROJECT_DIR)));
96
+ }
97
+ /**
98
+ * The harness actually calling. Grok and Cursor reuse another harness's hook configuration, so
99
+ * their own env and payload markers win over the declared `--harness`. Cursor resolves before
100
+ * `claude` is trusted because it inherits Claude's attended env when launched from a Claude session.
101
+ */
102
+ export function resolveHarness(declared, env, payload) {
103
+ if (isGrokHookProcess(env))
104
+ return 'grok';
105
+ if (isCursorHookProcess(declared, env, payload))
106
+ return 'cursor';
107
+ return declared;
108
+ }
109
+ /**
110
+ * True only when Claude Code marks the session attended (CLAUDE_CODE_SESSION_ATTENDED=1; 0 for
111
+ * `claude -p`). A missing or changed variable fails safe: no silent merge allow.
112
+ */
113
+ export function isAttendedClaudeSession(env) {
114
+ return env.CLAUDE_CODE_SESSION_ATTENDED === '1';
115
+ }
116
+ // Cursor documents `stdout`; `output` is kept as a fallback for older payloads.
117
+ function firstString(...values) {
118
+ return values.find((value) => typeof value === 'string') ?? '';
119
+ }
@@ -0,0 +1,7 @@
1
+ import type { HookContext, HookPolicy } from './types.mts';
2
+ /**
3
+ * Imports a `--policy` module and resolves its policy. The module's default export (or a named
4
+ * `policy` export) is a `HookPolicy` object or a function of the hook context that returns one.
5
+ * A relative path resolves against the repository root.
6
+ */
7
+ export declare function loadHookPolicy(specifier: string, context: HookContext): Promise<HookPolicy>;
@@ -0,0 +1,48 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { resolve } from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+ import { isRecord } from "../payload.mjs";
12
+ /**
13
+ * Imports a `--policy` module and resolves its policy. The module's default export (or a named
14
+ * `policy` export) is a `HookPolicy` object or a function of the hook context that returns one.
15
+ * A relative path resolves against the repository root.
16
+ */
17
+ export async function loadHookPolicy(specifier, context) {
18
+ const url = pathToFileURL(resolve(context.root, specifier)).href;
19
+ const loaded = (await import(__rewriteRelativeImportExtension(url)));
20
+ const exported = selectExport(loaded);
21
+ const policy = typeof exported === 'function' ? await exported(context) : exported;
22
+ if (!isRecord(policy) || Array.isArray(policy)) {
23
+ throw new Error(`policy module ${specifier} must default-export a policy object or a function returning one`);
24
+ }
25
+ return validated(policy, specifier);
26
+ }
27
+ const FIELD_SHAPES = {
28
+ command: (value) => isRecord(value) && !Array.isArray(value),
29
+ checkers: Array.isArray,
30
+ reminder: (value) => typeof value === 'function',
31
+ onPayload: (value) => typeof value === 'function',
32
+ };
33
+ // A misspelled shape would silently disable the policy, so a present field must have its type.
34
+ function validated(policy, specifier) {
35
+ for (const [field, isValid] of Object.entries(FIELD_SHAPES)) {
36
+ if (policy[field] !== undefined && !isValid(policy[field])) {
37
+ throw new Error(`policy module ${specifier} has an invalid \`${field}\``);
38
+ }
39
+ }
40
+ return policy;
41
+ }
42
+ // A CommonJS module's `default` is its whole `module.exports`, so `exports.policy = {...}` shows up as
43
+ // `default: { policy }` beside the named `policy`; the named export is the policy then.
44
+ function selectExport(loaded) {
45
+ const wrapper = loaded.default;
46
+ const wrapsNamed = isRecord(wrapper) && loaded.policy !== undefined && wrapper.policy === loaded.policy;
47
+ return wrapsNamed ? loaded.policy : (wrapper ?? loaded.policy);
48
+ }
@@ -0,0 +1,9 @@
1
+ import type { HookContext, HookPolicy, PostToolUseWarning } from './types.mts';
2
+ /** Runs every matching checker. A checker that throws becomes one error warning, never a crash. */
3
+ export declare function checkFile(filePath: string, root: string, checkers?: HookPolicy['checkers']): PostToolUseWarning[];
4
+ /**
5
+ * The stdout of a post-tool-use hook: one `additionalContext` JSON object carrying the checkers'
6
+ * `[level] message` lines and the reminder, or an empty string when there is nothing to say. The
7
+ * hook is advisory and never blocks, so failures here are swallowed.
8
+ */
9
+ export declare function postToolUseOutput(context: HookContext, policy: HookPolicy): Promise<string>;
@@ -0,0 +1,51 @@
1
+ import { hookFilePath, hookToolInput } from "../payload.mjs";
2
+ import { patchResultPaths } from "../path-references.mjs";
3
+ function failure(error) {
4
+ const message = error instanceof Error ? error.message : String(error);
5
+ return { level: 'error', message: `Unexpected error in post-tool-use checks: ${message}` };
6
+ }
7
+ /** Runs every matching checker. A checker that throws becomes one error warning, never a crash. */
8
+ export function checkFile(filePath, root, checkers = []) {
9
+ return checkers.flatMap((checker) => {
10
+ try {
11
+ return checker.matches(filePath, root) ? checker.check(filePath, root) : [];
12
+ }
13
+ catch (error) {
14
+ return [failure(error)];
15
+ }
16
+ });
17
+ }
18
+ // Edit/Write report `file_path`; Codex's apply_patch carries every touched file in its patch headers,
19
+ // and only files that exist afterwards are checked.
20
+ function editedPaths(context) {
21
+ const command = hookToolInput(context.payload)?.command;
22
+ if (typeof command === 'string' && command.startsWith('*** Begin Patch')) {
23
+ return patchResultPaths(command);
24
+ }
25
+ const filePath = hookFilePath(context.payload);
26
+ return filePath === '' ? [] : [filePath];
27
+ }
28
+ async function reminderOf(policy, context) {
29
+ try {
30
+ return (await policy.reminder?.(context)) || null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ /**
37
+ * The stdout of a post-tool-use hook: one `additionalContext` JSON object carrying the checkers'
38
+ * `[level] message` lines and the reminder, or an empty string when there is nothing to say. The
39
+ * hook is advisory and never blocks, so failures here are swallowed.
40
+ */
41
+ export async function postToolUseOutput(context, policy) {
42
+ const warnings = editedPaths(context).flatMap((path) => checkFile(path, context.root, policy.checkers));
43
+ const lines = warnings.map(({ level, message }) => `[${level}] ${message}`);
44
+ const reminder = await reminderOf(policy, context);
45
+ const text = [...lines, ...(reminder === null ? [] : [reminder])].join('\n');
46
+ if (text === '')
47
+ return '';
48
+ return `${JSON.stringify({
49
+ hookSpecificOutput: { additionalContext: text, hookEventName: 'PostToolUse' },
50
+ })}\n`;
51
+ }
@@ -0,0 +1,21 @@
1
+ import type { CommandPolicy, HookPayload } from '../types.mts';
2
+ import type { HookHarness } from './types.mts';
3
+ /**
4
+ * What a pre-tool-use hook writes and exits with. Exit 2 is the block all four harnesses honor.
5
+ * Claude, Codex, and Grok surface the stderr reason; Cursor surfaces the stdout JSON. Exit 0 with
6
+ * empty stdio is no opinion.
7
+ */
8
+ export type PreToolUseResult = {
9
+ exitCode: 0 | 2;
10
+ stderr: string;
11
+ stdout: string;
12
+ };
13
+ export type PreToolUseOptions = {
14
+ harness?: HookHarness | undefined;
15
+ /** True only when the harness marked the session attended (see isAttendedClaudeSession). */
16
+ attended?: boolean | undefined;
17
+ /** See EvaluateOptions.automationContext. */
18
+ automationContext?: boolean | undefined;
19
+ cwd?: string | undefined;
20
+ };
21
+ export declare function preToolUseOutput(payload: HookPayload, policy: CommandPolicy | undefined, options?: PreToolUseOptions): PreToolUseResult;
@@ -0,0 +1,45 @@
1
+ import { evaluateCommandPolicy } from "../engine.mjs";
2
+ export function preToolUseOutput(payload, policy, options = {}) {
3
+ // A policy module without a command table has no opinion, merge authority included.
4
+ if (policy === undefined) {
5
+ return { exitCode: 0, stderr: '', stdout: noOpinion(options) };
6
+ }
7
+ const decision = evaluateCommandPolicy(payload, policy, {
8
+ ...(options.automationContext === undefined
9
+ ? {}
10
+ : { automationContext: options.automationContext }),
11
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
12
+ });
13
+ if (decision === null) {
14
+ return { exitCode: 0, stderr: '', stdout: noOpinion(options) };
15
+ }
16
+ if (decision.disposition === 'confirm') {
17
+ return { exitCode: 0, stderr: '', stdout: renderConfirm(policy, options) };
18
+ }
19
+ return {
20
+ exitCode: 2,
21
+ stderr: `${decision.reason}\n`,
22
+ stdout: JSON.stringify({ decision: 'deny', reason: decision.reason }),
23
+ };
24
+ }
25
+ // Cursor treats a hook that prints nothing as failed (and blocks the call under `failClosed`), so
26
+ // "no opinion" there is an empty JSON object. Every other harness reads empty stdio as no opinion.
27
+ function noOpinion(options) {
28
+ return options.harness === 'cursor' ? '{}' : '';
29
+ }
30
+ // Only an attended Claude session gets a silent allow: the human already made the merge decision by
31
+ // asking for it, so a second tool-level click is redundant. Codex, Cursor, Grok, and an unattended
32
+ // Claude session (`claude -p`) get no opinion, so the harness's own prompt or classifier decides.
33
+ function renderConfirm(policy, options) {
34
+ if (options.harness !== 'claude' || options.attended !== true) {
35
+ return noOpinion(options);
36
+ }
37
+ const guidance = policy.mergeGuidance === undefined ? '' : ` ${policy.mergeGuidance}`;
38
+ return JSON.stringify({
39
+ hookSpecificOutput: {
40
+ hookEventName: 'PreToolUse',
41
+ permissionDecision: 'allow',
42
+ permissionDecisionReason: `Interactive merge: proceeding on the human decision already made in this session.${guidance}`,
43
+ },
44
+ });
45
+ }
@@ -0,0 +1,17 @@
1
+ export type HookIo = {
2
+ readStdin: () => Promise<string>;
3
+ stdout: {
4
+ write(text: string): unknown;
5
+ };
6
+ stderr: {
7
+ write(text: string): unknown;
8
+ };
9
+ env: NodeJS.ProcessEnv;
10
+ cwd: string;
11
+ };
12
+ /**
13
+ * `vouchington hook <event> --harness <h> --policy <module>`. Pre-tool-use fails closed (exit 2) when
14
+ * its policy cannot load, because the gates it enforces are a security boundary; post-tool-use is
15
+ * advisory and always exits 0. Bad arguments exit 2 before anything is read.
16
+ */
17
+ export declare function runHook(args: readonly string[], io: HookIo): Promise<number>;
@@ -0,0 +1,69 @@
1
+ import { resolve } from 'node:path';
2
+ import { hookCwd } from "../payload.mjs";
3
+ import { parseHookArgs } from "./args.mjs";
4
+ import { isAttendedClaudeSession, isAutomationContext, parseHookPayload, resolveHarness, } from "./harness.mjs";
5
+ import { loadHookPolicy } from "./policy-module.mjs";
6
+ import { postToolUseOutput } from "./post-tool-use.mjs";
7
+ import { preToolUseOutput } from "./pre-tool-use.mjs";
8
+ /**
9
+ * `vouchington hook <event> --harness <h> --policy <module>`. Pre-tool-use fails closed (exit 2) when
10
+ * its policy cannot load, because the gates it enforces are a security boundary; post-tool-use is
11
+ * advisory and always exits 0. Bad arguments exit 2 before anything is read.
12
+ */
13
+ export async function runHook(args, io) {
14
+ let parsed;
15
+ try {
16
+ parsed = parseHookArgs(args);
17
+ }
18
+ catch (error) {
19
+ io.stderr.write(`${error.message}\n`);
20
+ // Post-tool-use is advisory: an argument typo must not reject an already-completed tool call.
21
+ return args[0] === 'post-tool-use' ? 0 : 2;
22
+ }
23
+ const blocking = parsed.event === 'pre-tool-use';
24
+ try {
25
+ const payload = parseHookPayload(await io.readStdin(), blocking);
26
+ const context = {
27
+ harness: resolveHarness(parsed.harness, io.env, payload),
28
+ payload,
29
+ env: io.env,
30
+ root: resolve(io.cwd, parsed.root ?? '.'),
31
+ };
32
+ const policy = await loadHookPolicy(parsed.policy, context);
33
+ await runOnPayload(policy, context, io);
34
+ if (blocking) {
35
+ const result = preToolUseOutput(payload, policy.command, {
36
+ harness: context.harness,
37
+ attended: isAttendedClaudeSession(io.env),
38
+ automationContext: isAutomationContext(io.env, parsed.automationEnv),
39
+ // The configured root, not the hook process's directory, when the payload names none.
40
+ cwd: hookCwd(payload, context.root),
41
+ });
42
+ if (result.stdout !== '')
43
+ io.stdout.write(result.stdout);
44
+ if (result.stderr !== '')
45
+ io.stderr.write(result.stderr);
46
+ return result.exitCode;
47
+ }
48
+ const output = await postToolUseOutput(context, policy);
49
+ if (output !== '')
50
+ io.stdout.write(output);
51
+ return 0;
52
+ }
53
+ catch (error) {
54
+ const message = error instanceof Error ? error.message : String(error);
55
+ io.stderr.write(`vouchington hook ${parsed.event}: ${message}\n`);
56
+ return blocking ? 2 : 0;
57
+ }
58
+ }
59
+ // A failing side effect (for example persisting a session id) is reported, never allowed to
60
+ // suppress the command policy or the post-tool-use checks.
61
+ async function runOnPayload(policy, context, io) {
62
+ try {
63
+ await policy.onPayload?.(context);
64
+ }
65
+ catch (error) {
66
+ const message = error instanceof Error ? error.message : String(error);
67
+ io.stderr.write(`vouchington hook: onPayload failed: ${message}\n`);
68
+ }
69
+ }
@@ -0,0 +1,33 @@
1
+ import type { CommandPolicy, HookPayload } from '../types.mts';
2
+ export declare const HOOK_HARNESSES: readonly ["claude", "codex", "cursor", "grok"];
3
+ export type HookHarness = (typeof HOOK_HARNESSES)[number];
4
+ export type HookContext = {
5
+ harness: HookHarness;
6
+ payload: HookPayload;
7
+ env: NodeJS.ProcessEnv;
8
+ /** Repository root: `--root`, else the hook process's working directory. */
9
+ root: string;
10
+ };
11
+ export type PostToolUseWarning = {
12
+ level: 'warn' | 'error';
13
+ message: string;
14
+ };
15
+ /** A file check run after an Edit/Write. `filePath` is as the tool reported it. */
16
+ export type PostToolUseChecker = {
17
+ matches: (filePath: string, root: string) => boolean;
18
+ check: (filePath: string, root: string) => PostToolUseWarning[];
19
+ };
20
+ /** What a `--policy <module>` exports, as its default export or a function returning it. */
21
+ export type HookPolicy = {
22
+ /** Rule table for `pre-tool-use`. Without it the hook has no opinion. */
23
+ command?: CommandPolicy;
24
+ /** File checks for `post-tool-use`. */
25
+ checkers?: readonly PostToolUseChecker[];
26
+ /** Extra context for the model after a tool call, or nothing. Must not throw to matter. */
27
+ reminder?: (context: HookContext) => string | null | undefined | Promise<string | null | undefined>;
28
+ /** Runs first on both events, for example to persist the harness session id. */
29
+ onPayload?: (context: HookContext) => void | Promise<void>;
30
+ };
31
+ export type HookPolicyExport = HookPolicy | ((context: HookContext) => HookPolicy | Promise<HookPolicy>);
32
+ /** Identity helper that types a policy module's default export. */
33
+ export declare function defineHookPolicy<T extends HookPolicyExport>(policy: T): T;
@@ -0,0 +1,5 @@
1
+ export const HOOK_HARNESSES = ['claude', 'codex', 'cursor', 'grok'];
2
+ /** Identity helper that types a policy module's default export. */
3
+ export function defineHookPolicy(policy) {
4
+ return policy;
5
+ }
@@ -0,0 +1,29 @@
1
+ export { evaluateCommandPolicy } from './engine.mts';
2
+ export { parseHookArgs } from './hook/args.mts';
3
+ export { isAttendedClaudeSession, isAutomationContext, normalizeCursorShellPayload, parseHookPayload, resolveHarness, } from './hook/harness.mts';
4
+ export { loadHookPolicy } from './hook/policy-module.mts';
5
+ export { checkFile, postToolUseOutput } from './hook/post-tool-use.mts';
6
+ export { preToolUseOutput } from './hook/pre-tool-use.mts';
7
+ export type { PreToolUseOptions, PreToolUseResult } from './hook/pre-tool-use.mts';
8
+ export { runHook } from './hook/run.mts';
9
+ export type { HookIo } from './hook/run.mts';
10
+ export { HOOK_HARNESSES, defineHookPolicy } from './hook/types.mts';
11
+ export type { HookContext, HookHarness, HookPolicy, HookPolicyExport, PostToolUseChecker, PostToolUseWarning, } from './hook/types.mts';
12
+ export { PLAIN_FORCE_PUSH_REASON, findBlockedPatternReason, standardGitPatterns, } from './git-patterns.mts';
13
+ export { defaultGitProbe } from './git-process.mts';
14
+ export { checkoutOwner, checkoutOwners, githubOwner, ownerOfRepoSelector, sessionHomeOwners, } from './github-checkout-owners.mts';
15
+ export { commandsToInspectForGitHubPolicy } from './github-command-context.mts';
16
+ export { commandCwd } from './github-command-cwd.mts';
17
+ export { commandPrefixAt, commandSegmentStart } from './github-command-position.mts';
18
+ export { configuredPullRequestBase, findHandRolledStackBaseBlock, } from './github-configured-base.mts';
19
+ export { parseGhInvocation, parseGhOrGhStackInvocation } from './github-invocation.mts';
20
+ export type { GhInvocation } from './github-invocation.mts';
21
+ export { findAutomationMergeBlock, findInteractiveMergeConfirm, isLoneMergeCommand, } from './github-merge-authority.mts';
22
+ export { hasNamedFlag, hasNumericPrSelector, lastNamedOption } from './github-option-flags.mts';
23
+ export { isGhCommandSeparator, parseGhOptions } from './github-options.mts';
24
+ export type { GhOptions } from './github-options.mts';
25
+ export { findGitHubStackWorkflowBlock } from './github-stack-workflow.mts';
26
+ export { findGitHubWorkflowBlock } from './github-workflow.mts';
27
+ export { extractToolCommand, hookCwd, hookFilePath, hookSessionId, hookToolInput, hookToolName, } from './payload.mts';
28
+ export { findPathTypo, protectedPathMatch, referencesProtectedPath } from './path-rules.mts';
29
+ export type { BlockDecision, CommandPolicy, EvaluateOptions, GitProbe, HookPayload, PathTypoRule, PatternRule, ProtectedPaths, StackPolicy, } from './types.mts';
@@ -0,0 +1,23 @@
1
+ export { evaluateCommandPolicy } from "./engine.mjs";
2
+ export { parseHookArgs } from "./hook/args.mjs";
3
+ export { isAttendedClaudeSession, isAutomationContext, normalizeCursorShellPayload, parseHookPayload, resolveHarness, } from "./hook/harness.mjs";
4
+ export { loadHookPolicy } from "./hook/policy-module.mjs";
5
+ export { checkFile, postToolUseOutput } from "./hook/post-tool-use.mjs";
6
+ export { preToolUseOutput } from "./hook/pre-tool-use.mjs";
7
+ export { runHook } from "./hook/run.mjs";
8
+ export { HOOK_HARNESSES, defineHookPolicy } from "./hook/types.mjs";
9
+ export { PLAIN_FORCE_PUSH_REASON, findBlockedPatternReason, standardGitPatterns, } from "./git-patterns.mjs";
10
+ export { defaultGitProbe } from "./git-process.mjs";
11
+ export { checkoutOwner, checkoutOwners, githubOwner, ownerOfRepoSelector, sessionHomeOwners, } from "./github-checkout-owners.mjs";
12
+ export { commandsToInspectForGitHubPolicy } from "./github-command-context.mjs";
13
+ export { commandCwd } from "./github-command-cwd.mjs";
14
+ export { commandPrefixAt, commandSegmentStart } from "./github-command-position.mjs";
15
+ export { configuredPullRequestBase, findHandRolledStackBaseBlock, } from "./github-configured-base.mjs";
16
+ export { parseGhInvocation, parseGhOrGhStackInvocation } from "./github-invocation.mjs";
17
+ export { findAutomationMergeBlock, findInteractiveMergeConfirm, isLoneMergeCommand, } from "./github-merge-authority.mjs";
18
+ export { hasNamedFlag, hasNumericPrSelector, lastNamedOption } from "./github-option-flags.mjs";
19
+ export { isGhCommandSeparator, parseGhOptions } from "./github-options.mjs";
20
+ export { findGitHubStackWorkflowBlock } from "./github-stack-workflow.mjs";
21
+ export { findGitHubWorkflowBlock } from "./github-workflow.mjs";
22
+ export { extractToolCommand, hookCwd, hookFilePath, hookSessionId, hookToolInput, hookToolName, } from "./payload.mjs";
23
+ export { findPathTypo, protectedPathMatch, referencesProtectedPath } from "./path-rules.mjs";
@@ -0,0 +1,14 @@
1
+ import type { HookPayload } from './types.mts';
2
+ /**
3
+ * The files an apply_patch leaves behind: added files and move destinations, plus updated files
4
+ * that are not moved. Deleted files and the pre-move side of a move are gone afterwards.
5
+ */
6
+ export declare function patchResultPaths(patch: string): string[];
7
+ /**
8
+ * Whether a path-shaped reference in the payload or the command satisfies `matches`: the payload's
9
+ * path-like string fields, an apply_patch's header lines, and the command's shell words. The
10
+ * command's own `command` field is read as shell text, never as a field value.
11
+ */
12
+ export declare function referencesPath(payload: HookPayload, command: string, matches: (token: string) => boolean, options?: {
13
+ splitRedirections?: boolean;
14
+ }): boolean;
@@ -0,0 +1,68 @@
1
+ import { tokenizeShellWords } from "../shell-parse/index.mjs";
2
+ import { commandsToInspectForGitHubPolicy } from "./github-command-context.mjs";
3
+ import { isRecord } from "./payload.mjs";
4
+ const PATCH_BEGIN = '*** Begin Patch';
5
+ const PATCH_HEADER_PREFIX = /^(?:\*\*\* (?:Add|Delete|Update) File:|\*\*\* Move to:)\s+/;
6
+ const KEY_PATH_LIKE_RE = /(?:^|_)(?:cwd|file|filename|path|workdir|workspace)(?:_|$)/i;
7
+ function keyLooksPathLike(key) {
8
+ const snake = key.replaceAll(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);
9
+ return KEY_PATH_LIKE_RE.test(snake);
10
+ }
11
+ /** Header lines name the files an apply_patch touches; body text that mentions a path does not. */
12
+ function patchHeaderPaths(patch) {
13
+ return patch
14
+ .split('\n')
15
+ .filter((line) => PATCH_HEADER_PREFIX.test(line))
16
+ .map((line) => line.replace(PATCH_HEADER_PREFIX, ''));
17
+ }
18
+ /**
19
+ * The files an apply_patch leaves behind: added files and move destinations, plus updated files
20
+ * that are not moved. Deleted files and the pre-move side of a move are gone afterwards.
21
+ */
22
+ export function patchResultPaths(patch) {
23
+ const lines = patch.split('\n').filter((line) => PATCH_HEADER_PREFIX.test(line));
24
+ return lines.flatMap((line, index) => {
25
+ const path = line.replace(PATCH_HEADER_PREFIX, '');
26
+ if (line.startsWith('*** Delete File:'))
27
+ return [];
28
+ const moved = lines[index + 1]?.startsWith('*** Move to:') === true;
29
+ return line.startsWith('*** Update File:') && moved ? [] : [path];
30
+ });
31
+ }
32
+ /**
33
+ * Whether a path-shaped reference in the payload or the command satisfies `matches`: the payload's
34
+ * path-like string fields, an apply_patch's header lines, and the command's shell words. The
35
+ * command's own `command` field is read as shell text, never as a field value.
36
+ */
37
+ export function referencesPath(payload, command, matches, options = {}) {
38
+ return valueReferences(payload, matches) || commandReferences(command, matches, options);
39
+ }
40
+ function commandReferences(command, matches, options) {
41
+ if (command.trimStart().startsWith(PATCH_BEGIN)) {
42
+ return patchHeaderPaths(command).some(matches);
43
+ }
44
+ // `apply_patch <<'EOF'` carries its patch in a data heredoc that shell scanning blanks out.
45
+ if (command.includes(PATCH_BEGIN) &&
46
+ tokenizeShellWords(command, { splitRedirections: true }).includes('apply_patch') &&
47
+ patchHeaderPaths(command).some(matches)) {
48
+ return true;
49
+ }
50
+ // Without splitRedirections a no-space redirect like `>dir/file` stays fused to its operator.
51
+ // Nested scripts (`sh -c`, substitutions, heredoc shell bodies) are read like the outer command.
52
+ return commandsToInspectForGitHubPolicy(command).some((script) => tokenizeShellWords(script, options).some(matches));
53
+ }
54
+ function valueReferences(value, matches, key) {
55
+ if (typeof value === 'string') {
56
+ if (value.startsWith(PATCH_BEGIN)) {
57
+ return patchHeaderPaths(value).some(matches);
58
+ }
59
+ return key !== undefined && keyLooksPathLike(key) && matches(value);
60
+ }
61
+ if (Array.isArray(value)) {
62
+ return value.some((nested) => valueReferences(nested, matches, key));
63
+ }
64
+ if (!isRecord(value)) {
65
+ return false;
66
+ }
67
+ return Object.entries(value).some(([nestedKey, nested]) => nestedKey !== 'command' && valueReferences(nested, matches, nestedKey));
68
+ }
@@ -0,0 +1,11 @@
1
+ import type { HookPayload, PathTypoRule, ProtectedPaths } from './types.mts';
2
+ /** The first typo rule the payload or command references, or undefined. */
3
+ export declare function findPathTypo(payload: HookPayload, command: string, rules: readonly PathTypoRule[]): PathTypoRule | undefined;
4
+ /**
5
+ * Whether `rawToken` names a protected file or directory. Dot segments collapse
6
+ * (`dir/./hooks/x` -> `dir/hooks/x`) so redundant path noise cannot hide a literal match. The match
7
+ * is deliberately not resolved against the command's cwd, so a `cd` plus a relative path is the
8
+ * indirection this check does not catch.
9
+ */
10
+ export declare function protectedPathMatch(rawToken: string, protectedPaths: ProtectedPaths): boolean;
11
+ export declare function referencesProtectedPath(payload: HookPayload, command: string, protectedPaths: ProtectedPaths): boolean;
@@ -0,0 +1,37 @@
1
+ import { posix } from 'node:path';
2
+ import { referencesPath } from "./path-references.mjs";
3
+ /** True when `token` is the segment, or has it as a leading, trailing, or interior path segment. */
4
+ function tokenReferencesSegment(token, segment) {
5
+ return (token === segment ||
6
+ token.startsWith(`${segment}/`) ||
7
+ token.endsWith(`/${segment}`) ||
8
+ token.includes(`/${segment}/`));
9
+ }
10
+ /** The first typo rule the payload or command references, or undefined. */
11
+ export function findPathTypo(payload, command, rules) {
12
+ return rules.find((rule) => referencesPath(payload, command, (token) => tokenReferencesSegment(token, rule.segment)));
13
+ }
14
+ /**
15
+ * Whether `rawToken` names a protected file or directory. Dot segments collapse
16
+ * (`dir/./hooks/x` -> `dir/hooks/x`) so redundant path noise cannot hide a literal match. The match
17
+ * is deliberately not resolved against the command's cwd, so a `cd` plus a relative path is the
18
+ * indirection this check does not catch.
19
+ */
20
+ export function protectedPathMatch(rawToken, protectedPaths) {
21
+ const token = rawToken === '' ? rawToken : posix.normalize(rawToken);
22
+ if (protectedPaths.exactFiles.some((file) => token === file || token.endsWith(`/${file}`))) {
23
+ return true;
24
+ }
25
+ return protectedPaths.dirPrefixes.some((prefix) => {
26
+ const bareDir = prefix.slice(0, -1);
27
+ return (token === bareDir ||
28
+ token.startsWith(prefix) ||
29
+ token.endsWith(`/${bareDir}`) ||
30
+ token.includes(`/${prefix}`));
31
+ });
32
+ }
33
+ export function referencesProtectedPath(payload, command, protectedPaths) {
34
+ return referencesPath(payload, command, (token) => protectedPathMatch(token, protectedPaths), {
35
+ splitRedirections: true,
36
+ });
37
+ }
@@ -0,0 +1,8 @@
1
+ import type { HookPayload } from './types.mts';
2
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
3
+ export declare function hookToolInput(payload: HookPayload): Record<string, unknown> | undefined;
4
+ export declare function extractToolCommand(payload: HookPayload): string;
5
+ export declare function hookToolName(payload: HookPayload): string;
6
+ export declare function hookSessionId(payload: HookPayload): string;
7
+ export declare function hookFilePath(payload: HookPayload): string;
8
+ export declare function hookCwd(payload: HookPayload, fallback?: string): string;