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,127 @@
1
+ import { commandFor, decorateWindow, restoreDeadWindows, windowCwd, } from "./windows.mjs";
2
+ const READY_ATTEMPTS = 99;
3
+ const READY_POLL_MS = 100;
4
+ function isReady(context) {
5
+ const marker = `@${context.config.readyMarker}`;
6
+ const result = context.tmux(['show-options', '-qv', '-t', `=${context.session}:`, marker]);
7
+ return result.stdout.trim() === '1';
8
+ }
9
+ function hasSession(context) {
10
+ return context.tmux(['has-session', '-t', `=${context.session}`]).status === 0;
11
+ }
12
+ function finishExisting(context, options) {
13
+ if (options.noAttach) {
14
+ context.out(`Services already running in tmux session '${context.session}'.\n`);
15
+ return 0;
16
+ }
17
+ context.out(`Reattaching to existing tmux session '${context.session}'...\n`);
18
+ return context.tmux(['attach', '-t', `=${context.session}`], true).status ?? 1;
19
+ }
20
+ function waitUntilReady(context, options) {
21
+ for (let attempt = 0; attempt < READY_ATTEMPTS; attempt += 1) {
22
+ if (!hasSession(context)) {
23
+ context.err(`Error: tmux session '${context.session}' disappeared during startup.\n`);
24
+ return 1;
25
+ }
26
+ options.sleep(READY_POLL_MS);
27
+ if (isReady(context))
28
+ return 0;
29
+ }
30
+ if (ownerIsDead(context, options)) {
31
+ context.err(`Error: tmux session '${context.session}' was left unfinished; recreating it.\n`);
32
+ context.tmux(['kill-session', '-t', `=${context.session}`]);
33
+ return 2;
34
+ }
35
+ context.err(`Error: tmux session '${context.session}' did not finish startup.\n`);
36
+ return 1;
37
+ }
38
+ /** True when the session records a launcher pid and that process no longer exists. */
39
+ function ownerIsDead(context, options) {
40
+ const variable = context.config.launcherPidVar;
41
+ const result = context.tmux(['show-environment', '-t', `=${context.session}`, variable]);
42
+ const pid = /=([0-9]+)\s*$/.exec(result.stdout)?.[1];
43
+ return pid !== undefined && !options.isPidAlive(Number(pid));
44
+ }
45
+ /** 0 = done, 2 = session was killed and must be recreated, other = failure. */
46
+ function reuseExisting(context, options, allowRestore) {
47
+ if (!isReady(context)) {
48
+ const waited = waitUntilReady(context, options);
49
+ if (waited !== 0)
50
+ return waited;
51
+ }
52
+ else if (allowRestore && !restoreDeadWindows(context)) {
53
+ context.err('Error: failed to restore managed tmux windows; recreating session.\n');
54
+ context.tmux(['kill-session', '-t', `=${context.session}`]);
55
+ return 2;
56
+ }
57
+ return finishExisting(context, options);
58
+ }
59
+ function ownsSession(context, pid) {
60
+ const variable = context.config.launcherPidVar;
61
+ const result = context.tmux(['show-environment', '-t', `=${context.session}`, variable]);
62
+ return result.stdout.trim() === `${variable}=${pid}`;
63
+ }
64
+ function createSession(context, options) {
65
+ const [first, ...rest] = context.config.windows;
66
+ const target = `=${context.session}`;
67
+ const created = context.tmux([
68
+ 'new-session',
69
+ '-d',
70
+ '-s',
71
+ context.session,
72
+ '-e',
73
+ `${context.config.launcherPidVar}=${options.pid}`,
74
+ '-n',
75
+ first.name,
76
+ '-c',
77
+ windowCwd(context, first),
78
+ commandFor(context, first),
79
+ ]);
80
+ if (created.status !== 0) {
81
+ if (hasSession(context))
82
+ return reuseExisting(context, options, false);
83
+ context.err(`Error: failed to create tmux session '${context.session}'.\n`);
84
+ return 1;
85
+ }
86
+ const steps = rest.map((window) => [
87
+ 'new-window',
88
+ '-t',
89
+ target,
90
+ '-n',
91
+ window.name,
92
+ '-c',
93
+ windowCwd(context, window),
94
+ commandFor(context, window),
95
+ ]);
96
+ const ok = decorateWindow(context, first.name) &&
97
+ rest.every((window, index) => context.tmux(steps[index]).status === 0 && decorateWindow(context, window.name)) &&
98
+ context.tmux(['select-window', '-t', `${target}:${first.name}`]).status === 0 &&
99
+ context.tmux(['set-option', '-t', `${target}:`, `@${context.config.readyMarker}`, '1'])
100
+ .status === 0;
101
+ if (!ok) {
102
+ if (ownsSession(context, options.pid))
103
+ context.tmux(['kill-session', '-t', target]);
104
+ context.err(`Error: failed to start tmux session '${context.session}'.\n`);
105
+ return 1;
106
+ }
107
+ if (options.noAttach) {
108
+ context.out(`Services started in tmux session '${context.session}'.\n`);
109
+ context.out(`To attach: tmux attach -t '${context.session}'\n`);
110
+ return 0;
111
+ }
112
+ context.out(`Attaching to tmux session '${context.session}'...\n`);
113
+ return context.tmux(['attach', '-t', target], true).status ?? 1;
114
+ }
115
+ /** Start the configured windows in a worktree-scoped tmux session, or reuse a running one. */
116
+ export function launchSession(context, options) {
117
+ if (hasSession(context)) {
118
+ const status = reuseExisting(context, options, true);
119
+ if (status !== 2)
120
+ return status;
121
+ }
122
+ for (const line of context.config.summary)
123
+ context.out(`${line}\n`);
124
+ if (context.config.summary.length > 0)
125
+ context.out('\n');
126
+ return createSession(context, options);
127
+ }
@@ -0,0 +1,21 @@
1
+ import { type HookPayload } from './hook-payload.mts';
2
+ export type PaneTitleSpawnResult = {
3
+ error?: NodeJS.ErrnoException | null | undefined;
4
+ status: number | null;
5
+ stdout: string;
6
+ stderr?: string;
7
+ };
8
+ export type PaneTitleSpawn = (command: string, args: readonly string[], env: NodeJS.ProcessEnv) => PaneTitleSpawnResult;
9
+ export type PostToolTmuxOptions = {
10
+ env?: NodeJS.ProcessEnv | undefined;
11
+ spawnPaneTitle?: PaneTitleSpawn | undefined;
12
+ /** Command the reminder tells the agent to run. Default: `TMUX_NAME_COMMAND` or `vouchington tmux name`. */
13
+ nameCommand?: string | undefined;
14
+ };
15
+ /**
16
+ * Remind the agent to (re)name its tmux window at the checkpoints a post-tool payload can
17
+ * detect: a plan was accepted, a PR was created, a push landed without a `-pr<N>` title suffix,
18
+ * or reset-worktree left a stale title. Silent (`null`) without a verified pane and for every
19
+ * other tool call. The pane is read only after a checkpoint matches.
20
+ */
21
+ export declare function renderPostToolReminder(payload: HookPayload, options?: PostToolTmuxOptions): string | null;
@@ -0,0 +1,88 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { packageScriptPath } from "../cli/script-path.mjs";
3
+ import { extractToolCommand, hookToolName, toolExitCode, } from "./hook-payload.mjs";
4
+ const PR_CREATE_COMMAND_PATTERN = /(^|[;&|])\s*gh\s+pr\s+create(\s|$)/;
5
+ const GIT_PUSH_COMMAND_PATTERN = /(^|[;&|])\s*git\s+push(\s|$)/;
6
+ const RESET_WORKTREE_PATTERN = /(^|[;&|])\s*(?:\S*\/)?reset-worktree(?:\.sh)?(?:\s+(--help|-h))?(?=[;&|]|\s|$)/g;
7
+ const SHELL_TOOLS = new Set(['Bash', 'Shell', 'run_terminal_command']);
8
+ const PR_SUFFIX_PATTERN = /-pr\d+$/;
9
+ const transientSpawnCodes = new Set(['EAGAIN', 'EBUSY', 'EINTR', 'EMFILE', 'ENFILE', 'ETXTBSY']);
10
+ const transientStderrPattern = /\b(?:EAGAIN|EBUSY|EINTR|EMFILE|ENFILE|ETXTBSY)\b|resource temporarily unavailable|device or resource busy|interrupted system call|too many open files|text file busy/i;
11
+ const spawnAttempts = 3;
12
+ function spawnReadTitle(command, args, env) {
13
+ // Diagnostics are matched below, so request stable English errno text for this helper only.
14
+ const result = spawnSync(command, [...args], { encoding: 'utf8', env: { ...env, LC_ALL: 'C' } });
15
+ return {
16
+ error: result.error,
17
+ status: result.status,
18
+ stdout: result.stdout,
19
+ stderr: result.stderr,
20
+ };
21
+ }
22
+ function paneTitle(env, spawn) {
23
+ // The script validates the socket, pane, and worktree before reading, so a failed
24
+ // lookup is not an empty pane title.
25
+ const script = packageScriptPath('scripts/tmux/tmux-read-title.sh');
26
+ for (let attempt = 0; attempt < spawnAttempts; attempt += 1) {
27
+ const result = spawn('bash', [script], env);
28
+ if (result.status === 0)
29
+ return result.stdout.trim();
30
+ const code = result.error?.code;
31
+ const retryableSpawn = typeof code === 'string' && transientSpawnCodes.has(code);
32
+ if (!retryableSpawn && !transientStderrPattern.test(result.stderr ?? ''))
33
+ return null;
34
+ }
35
+ return null;
36
+ }
37
+ // Scans every reset-worktree invocation separately: a compound command like
38
+ // `reset-worktree --help; reset-worktree --force` still runs a real reset.
39
+ function hasNonHelpResetInvocation(command) {
40
+ const pattern = new RegExp(RESET_WORKTREE_PATTERN.source, 'g');
41
+ for (let match = pattern.exec(command); match !== null; match = pattern.exec(command)) {
42
+ if (match[2] === undefined)
43
+ return true;
44
+ }
45
+ return false;
46
+ }
47
+ /**
48
+ * Remind the agent to (re)name its tmux window at the checkpoints a post-tool payload can
49
+ * detect: a plan was accepted, a PR was created, a push landed without a `-pr<N>` title suffix,
50
+ * or reset-worktree left a stale title. Silent (`null`) without a verified pane and for every
51
+ * other tool call. The pane is read only after a checkpoint matches.
52
+ */
53
+ export function renderPostToolReminder(payload, options = {}) {
54
+ const env = { ...(options.env ?? process.env) };
55
+ const spawn = options.spawnPaneTitle ?? spawnReadTitle;
56
+ const name = options.nameCommand ?? env.TMUX_NAME_COMMAND ?? 'vouchington tmux name';
57
+ const hint = '(dangerouslyDisableSandbox: true)';
58
+ const toolName = hookToolName(payload);
59
+ if (toolName === 'ExitPlanMode') {
60
+ if (paneTitle(env, spawn) === null)
61
+ return null;
62
+ return `[tmux-window-name] Plan accepted — refine window name if scope shifted. ${name} <name> ${hint}`;
63
+ }
64
+ if (!SHELL_TOOLS.has(toolName))
65
+ return null;
66
+ const command = extractToolCommand(payload);
67
+ const exitCode = toolExitCode(payload);
68
+ if (command === '' || (exitCode !== undefined && exitCode !== 0))
69
+ return null;
70
+ if (PR_CREATE_COMMAND_PATTERN.test(command)) {
71
+ if (paneTitle(env, spawn) === null)
72
+ return null;
73
+ return `[tmux-window-name] PR created — add the -pr<N> suffix: ${name} <feature-pr123> ${hint}`;
74
+ }
75
+ if (GIT_PUSH_COMMAND_PATTERN.test(command)) {
76
+ const title = paneTitle(env, spawn);
77
+ if (title === null || PR_SUFFIX_PATTERN.test(title))
78
+ return null;
79
+ return `[tmux-window-name] git push on PR branch — confirm -pr<N> suffix is set: ${name} <feature-pr123> ${hint}`;
80
+ }
81
+ if (hasNonHelpResetInvocation(command)) {
82
+ const title = paneTitle(env, spawn);
83
+ if (title === null || title === '')
84
+ return null;
85
+ return `[tmux-window-name] reset-worktree ran — pane title should be empty. ${name} "" ${hint}`;
86
+ }
87
+ return null;
88
+ }
@@ -0,0 +1,11 @@
1
+ export type TmuxResult = {
2
+ status: number | null;
3
+ stdout: string;
4
+ };
5
+ /** Runs one tmux command. `inherit` hands the terminal to tmux (attach). */
6
+ export type TmuxRun = (args: readonly string[], inherit?: boolean) => TmuxResult;
7
+ export declare function createTmuxRun(bin: string): TmuxRun;
8
+ /** True when the process has any child process (the window's command is running). */
9
+ export declare function pgrepHasChildren(pid: string): boolean;
10
+ export declare function isPidAlive(pid: number): boolean;
11
+ export declare function sleepMs(milliseconds: number): void;
@@ -0,0 +1,26 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ export function createTmuxRun(bin) {
3
+ return (args, inherit = false) => {
4
+ const result = spawnSync(bin, [...args], {
5
+ encoding: 'utf8',
6
+ stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'ignore'],
7
+ });
8
+ return { status: result.error ? null : result.status, stdout: result.stdout ?? '' };
9
+ };
10
+ }
11
+ /** True when the process has any child process (the window's command is running). */
12
+ export function pgrepHasChildren(pid) {
13
+ return spawnSync('pgrep', ['-P', pid, '.'], { stdio: 'ignore' }).status === 0;
14
+ }
15
+ export function isPidAlive(pid) {
16
+ try {
17
+ process.kill(pid, 0);
18
+ return true;
19
+ }
20
+ catch (error) {
21
+ return error.code === 'EPERM';
22
+ }
23
+ }
24
+ export function sleepMs(milliseconds) {
25
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
26
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Session names are the configured prefix plus a hash of the physical worktree
3
+ * path, so same-basename worktrees never share a session.
4
+ */
5
+ export declare function tmuxSessionName(prefix: string, root: string): string;
@@ -0,0 +1,10 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { realpathSync } from 'node:fs';
3
+ /**
4
+ * Session names are the configured prefix plus a hash of the physical worktree
5
+ * path, so same-basename worktrees never share a session.
6
+ */
7
+ export function tmuxSessionName(prefix, root) {
8
+ const physical = realpathSync(root);
9
+ return `${prefix}d${createHash('sha256').update(physical).digest('hex').slice(0, 12)}`;
10
+ }
@@ -0,0 +1,9 @@
1
+ import type { TmuxSessionConfig, TmuxWindowConfig } from './config.mts';
2
+ export declare function quoteShellArg(value: string): string;
3
+ /**
4
+ * The shell command tmux runs in a window: `bash -lc` with one quoted body that first exports
5
+ * the extra, shared, then per-window environment and then runs the command. Exporting inside
6
+ * the body (rather than prefixing `bash`) keeps a configured PATH from hiding `bash` itself and
7
+ * lets the configured values win over login-profile defaults.
8
+ */
9
+ export declare function windowCommand(config: TmuxSessionConfig, window: TmuxWindowConfig, extraEnv?: Readonly<Record<string, string>>): string;
@@ -0,0 +1,16 @@
1
+ export function quoteShellArg(value) {
2
+ return `'${value.replaceAll("'", "'\\''")}'`;
3
+ }
4
+ /**
5
+ * The shell command tmux runs in a window: `bash -lc` with one quoted body that first exports
6
+ * the extra, shared, then per-window environment and then runs the command. Exporting inside
7
+ * the body (rather than prefixing `bash`) keeps a configured PATH from hiding `bash` itself and
8
+ * lets the configured values win over login-profile defaults.
9
+ */
10
+ export function windowCommand(config, window, extraEnv = {}) {
11
+ const exports = Object.entries({ ...extraEnv, ...config.env, ...window.env })
12
+ .map(([key, value]) => `export ${key}=${quoteShellArg(value)}; `)
13
+ .join('');
14
+ const body = `${exports}${window.command}${window.keepOpen ? '; read' : ''}`;
15
+ return `bash -lc ${quoteShellArg(body)}`;
16
+ }
@@ -0,0 +1,2 @@
1
+ import { type TmuxCliDeps } from './cli-shared.mts';
2
+ export declare function runUp(args: readonly string[], deps: TmuxCliDeps): number;
@@ -0,0 +1,73 @@
1
+ import { resolve } from 'node:path';
2
+ import { TMUX_USAGE } from "./cli-shared.mjs";
3
+ import { loadTmuxConfig } from "./config.mjs";
4
+ import { launchSession } from "./launcher.mjs";
5
+ import { createTmuxRun, isPidAlive, pgrepHasChildren, sleepMs } from "./runner.mjs";
6
+ import { tmuxSessionName } from "./session-name.mjs";
7
+ function parseUp(args) {
8
+ const flags = { noAttach: false, verbose: false };
9
+ for (let index = 0; index < args.length; index += 1) {
10
+ const arg = args[index];
11
+ if (arg === '--no-attach' || arg === '--verbose' || arg === '-v') {
12
+ const key = arg === '--no-attach' ? 'noAttach' : 'verbose';
13
+ if (flags[key])
14
+ return `duplicate option: ${arg}`;
15
+ flags[key] = true;
16
+ }
17
+ else if (arg === '--config' || arg === '--root') {
18
+ const value = args[index + 1];
19
+ if (value === undefined || value === '')
20
+ return `missing value for ${arg}`;
21
+ flags[arg === '--config' ? 'config' : 'root'] = value;
22
+ index += 1;
23
+ }
24
+ else {
25
+ return `unknown option: ${arg}`;
26
+ }
27
+ }
28
+ return flags.config === undefined ? '--config is required' : flags;
29
+ }
30
+ export function runUp(args, deps) {
31
+ const err = deps.err ?? ((text) => void process.stderr.write(text));
32
+ const env = deps.env ?? process.env;
33
+ const flags = parseUp(args);
34
+ if (typeof flags === 'string') {
35
+ err(`vouchington: ${flags}\n${TMUX_USAGE}`);
36
+ return 2;
37
+ }
38
+ const tmux = deps.tmux ?? createTmuxRun(env.TMUX_TARGET_BIN || 'tmux');
39
+ if (tmux(['-V']).status !== 0) {
40
+ err('Error: tmux is not installed.\n');
41
+ return 1;
42
+ }
43
+ if (env.TMUX && !flags.noAttach) {
44
+ err('Error: run this outside tmux. Pass --no-attach to start services without attaching.\n');
45
+ return 1;
46
+ }
47
+ const cwd = deps.cwd ?? process.cwd();
48
+ const root = resolve(cwd, flags.root ?? env.TMUX_TARGET_ROOT ?? '.');
49
+ try {
50
+ const config = loadTmuxConfig(resolve(cwd, flags.config));
51
+ const context = {
52
+ config,
53
+ root,
54
+ session: tmuxSessionName(config.sessionPrefix, root),
55
+ extraEnv: { TMUX_LOG_LEVEL: flags.verbose ? 'info' : 'error' },
56
+ tmux,
57
+ hasChildren: deps.hasChildren ?? pgrepHasChildren,
58
+ out: deps.out ?? ((text) => void process.stdout.write(text)),
59
+ err,
60
+ };
61
+ const sleep = deps.sleep ?? sleepMs;
62
+ return launchSession(context, {
63
+ noAttach: flags.noAttach,
64
+ pid: deps.pid ?? process.pid,
65
+ sleep,
66
+ isPidAlive: deps.isPidAlive ?? isPidAlive,
67
+ });
68
+ }
69
+ catch (error) {
70
+ err(`vouchington: ${error.message}\n`);
71
+ return 2;
72
+ }
73
+ }
@@ -0,0 +1,18 @@
1
+ import type { TmuxSessionConfig, TmuxWindowConfig } from './config.mts';
2
+ import type { TmuxRun } from './runner.mts';
3
+ export type SessionContext = {
4
+ config: TmuxSessionConfig;
5
+ root: string;
6
+ session: string;
7
+ /** Variables injected into every window, e.g. the log level. */
8
+ extraEnv: Record<string, string>;
9
+ tmux: TmuxRun;
10
+ hasChildren: (pid: string) => boolean;
11
+ out: (text: string) => void;
12
+ err: (text: string) => void;
13
+ };
14
+ export declare function windowCwd(context: SessionContext, window: TmuxWindowConfig): string;
15
+ export declare function commandFor(context: SessionContext, window: TmuxWindowConfig): string;
16
+ export declare function decorateWindow(context: SessionContext, name: string): boolean;
17
+ /** Respawn dead windows (or recreate missing ones). False when any step fails. */
18
+ export declare function restoreDeadWindows(context: SessionContext): boolean;
@@ -0,0 +1,50 @@
1
+ import { resolve } from 'node:path';
2
+ import { windowCommand } from "./shell-quote.mjs";
3
+ export function windowCwd(context, window) {
4
+ return resolve(context.root, window.cwd ?? '.');
5
+ }
6
+ export function commandFor(context, window) {
7
+ return windowCommand(context.config, window, context.extraEnv);
8
+ }
9
+ function windowExists(context, name) {
10
+ const result = context.tmux(['list-windows', '-t', `=${context.session}`, '-F', '#{window_name}']);
11
+ return result.stdout.split('\n').includes(name);
12
+ }
13
+ // A keep-open pane leaves its shell running after the command ends, so only a child process
14
+ // proves the command is alive. Without keepOpen the pane closes with the command, and bash may
15
+ // exec it directly (no child), so the window existing is the liveness signal.
16
+ function windowIsLive(context, window) {
17
+ const name = window.name;
18
+ if (!windowExists(context, name))
19
+ return false;
20
+ if (!window.keepOpen)
21
+ return true;
22
+ const result = context.tmux([
23
+ 'list-panes',
24
+ '-t',
25
+ `=${context.session}:${name}`,
26
+ '-F',
27
+ '#{pane_pid}',
28
+ ]);
29
+ return result.stdout.split('\n').some((pid) => /^[0-9]+$/.test(pid) && context.hasChildren(pid));
30
+ }
31
+ export function decorateWindow(context, name) {
32
+ const target = `=${context.session}:${name}`;
33
+ return (context.tmux(['select-pane', '-T', name, '-t', target]).status === 0 &&
34
+ context.tmux(['set-option', '-w', '-t', target, 'pane-border-status', 'top']).status === 0);
35
+ }
36
+ /** Respawn dead windows (or recreate missing ones). False when any step fails. */
37
+ export function restoreDeadWindows(context) {
38
+ for (const window of context.config.windows) {
39
+ if (windowIsLive(context, window))
40
+ continue;
41
+ const base = ['-c', windowCwd(context, window), commandFor(context, window)];
42
+ const target = `=${context.session}`;
43
+ const args = windowExists(context, window.name)
44
+ ? ['respawn-pane', '-k', '-t', `${target}:${window.name}`, ...base]
45
+ : ['new-window', '-d', '-t', target, '-n', window.name, ...base];
46
+ if (context.tmux(args).status !== 0 || !decorateWindow(context, window.name))
47
+ return false;
48
+ }
49
+ return true;
50
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vouchington-tooling",
3
- "version": "0.59.0",
3
+ "version": "0.60.0",
4
4
  "description": "Vouchington CLI and extractable tooling libraries.",
5
5
  "homepage": "https://github.com/vouchington/vouchington-tooling/tree/main/packages/vouchington-tooling#readme",
6
6
  "bugs": {
@@ -60,6 +60,11 @@
60
60
  "import": "./dist/host-storage/index.mjs",
61
61
  "default": "./dist/host-storage/index.mjs"
62
62
  },
63
+ "./command-policy": {
64
+ "types": "./dist/command-policy/index.d.mts",
65
+ "import": "./dist/command-policy/index.mjs",
66
+ "default": "./dist/command-policy/index.mjs"
67
+ },
63
68
  "./shell-parse": {
64
69
  "types": "./dist/shell-parse/index.d.mts",
65
70
  "import": "./dist/shell-parse/index.mjs",
@@ -311,6 +316,11 @@
311
316
  "import": "./dist/dead-code/index.mjs",
312
317
  "default": "./dist/dead-code/index.mjs"
313
318
  },
319
+ "./tmux": {
320
+ "types": "./dist/tmux/index.d.mts",
321
+ "import": "./dist/tmux/index.mjs",
322
+ "default": "./dist/tmux/index.mjs"
323
+ },
314
324
  "./workflow-secrets-drift": {
315
325
  "types": "./dist/workflow-secrets-drift/index.d.mts",
316
326
  "import": "./dist/workflow-secrets-drift/index.mjs",
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Remind the agent to rename the tmux window at workflow checkpoints.
5
+ # Called by agent hooks; stdout is injected as context.
6
+ #
7
+ # Usage: vouchington tmux agent-reminder <event>
8
+ # event: session-start | user-prompt
9
+ # TMUX_TARGET_BIN: optional tmux binary (default: tmux on PATH).
10
+ # TMUX_TARGET_ROOT: worktree the pane must belong to (default: $PWD).
11
+ # TMUX_NAME_COMMAND: command the reminder tells the agent to run
12
+ # (default: vouchington tmux name).
13
+ #
14
+ # Silently exits 0 when no tmux context is available.
15
+
16
+ EVENT="${1:-}"
17
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
18
+ # shellcheck source=tmux-target.sh
19
+ source "$SCRIPT_DIR/tmux-target.sh"
20
+ tmux_target_socket=''
21
+ tmux_target_pane=''
22
+ TMUX_TARGET_BIN="${TMUX_TARGET_BIN:-tmux}"
23
+ NAME_COMMAND="${TMUX_NAME_COMMAND:-vouchington tmux name}"
24
+
25
+ if tmux_target_resolve "${TMUX_TARGET_ROOT:-$PWD}" "${AGENT_TMUX_SOCKET:-}" "${AGENT_TMUX_PANE:-}" "${AGENT_TMUX_WORKTREE:-}"; then
26
+ :
27
+ else
28
+ # Hook reminders are advisory. The resolver diagnoses invalid bindings and
29
+ # the hook leaves the agent's work alone.
30
+ exit 0
31
+ fi
32
+
33
+ # Drain the hook payload so the caller never blocks on an unread pipe.
34
+ cat >/dev/null
35
+
36
+ pane_title() {
37
+ "$TMUX_TARGET_BIN" -S "$tmux_target_socket" display-message -p -t "$tmux_target_pane" '#{pane_title}' 2>/dev/null || true
38
+ }
39
+
40
+ POLICY="Run: $NAME_COMMAND <name> (must run unsandboxed: Claude/Codex dangerouslyDisableSandbox; Cursor disable sandbox)
41
+ Checkpoints: (1) topic clear → short-hyphenated-name; (2) plan accepted → refine if scope shifted; (3) PR created → append -pr<N> suffix; (4) git push on PR branch → confirm -pr<N> still set; (5) after compaction → verify name still matches topic; (6) reset-worktree → confirm pane title is empty."
42
+
43
+ json_escape() {
44
+ local value=$1
45
+ value=${value//\\/\\\\}
46
+ value=${value//\"/\\\"}
47
+ value=${value//$'\n'/\\n}
48
+ value=${value//$'\t'/\\t}
49
+ printf '%s' "$value"
50
+ }
51
+
52
+ # Emit structured hook context for events that require JSON stdout.
53
+ emit_json() {
54
+ printf '{"hookSpecificOutput":{"hookEventName":"%s","additionalContext":"%s"}}\n' \
55
+ "$(json_escape "$1")" "$(json_escape "$2")"
56
+ }
57
+
58
+ case "$EVENT" in
59
+ session-start)
60
+ emit_json "SessionStart" "[tmux-window-name] $POLICY"
61
+ ;;
62
+ user-prompt)
63
+ TITLE="$(pane_title)"
64
+ if [ -z "$TITLE" ] || printf '%s' "$TITLE" | grep -qE '^(claude|codex|grok|cursor|agent|zsh|bash|fish|reset|sh)$'; then
65
+ printf '[tmux-window-name] Topic is clear — set the window name now. %s\n' "$POLICY"
66
+ fi
67
+ ;;
68
+ esac
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Name the tmux window and pane that belong to the caller's worktree.
5
+ # The worktree defaults to the git root of $PWD; override with TMUX_TARGET_ROOT.
6
+ # The tmux binary defaults to `tmux`; override with TMUX_TARGET_BIN.
7
+
8
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
9
+ if [ "$#" -eq 1 ] && { [ "$1" = "-h" ] || [ "$1" = "--help" ]; }; then
10
+ echo 'Usage: vouchington tmux name [--socket PATH --pane %ID --worktree PATH] NAME'
11
+ exit 0
12
+ fi
13
+ # shellcheck source=tmux-target.sh
14
+ source "$SCRIPT_DIR/tmux-target.sh"
15
+ tmux_target_socket=''
16
+ tmux_target_pane=''
17
+ TMUX_TARGET_BIN="${TMUX_TARGET_BIN:-tmux}"
18
+
19
+ if tmux_target_parse "${TMUX_TARGET_ROOT:-$PWD}" "$@"; then
20
+ :
21
+ else
22
+ resolve_status=$?
23
+ # An interactive command outside tmux has no target. Invalid, partial, stale,
24
+ # and mismatched bindings retain the resolver's diagnostic.
25
+ if [ "$resolve_status" -eq 3 ]; then exit 0; fi
26
+ exit "$resolve_status"
27
+ fi
28
+
29
+ if [ -z "$tmux_target_name" ]; then
30
+ "$TMUX_TARGET_BIN" -S "$tmux_target_socket" set-window-option -t "$tmux_target_pane" automatic-rename on
31
+ else
32
+ "$TMUX_TARGET_BIN" -S "$tmux_target_socket" rename-window -t "$tmux_target_pane" -- "$tmux_target_name"
33
+ fi
34
+ "$TMUX_TARGET_BIN" -S "$tmux_target_socket" select-pane -t "$tmux_target_pane" -T "$tmux_target_name"
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
5
+ # shellcheck source=tmux-target.sh
6
+ source "$SCRIPT_DIR/tmux-target.sh"
7
+ tmux_target_socket=''
8
+ tmux_target_pane=''
9
+ TMUX_TARGET_BIN="${TMUX_TARGET_BIN:-tmux}"
10
+
11
+ # A title read uses the same pane/worktree check as tmux-name.
12
+ tmux_target_resolve "${TMUX_TARGET_ROOT:-$PWD}" "${AGENT_TMUX_SOCKET:-}" "${AGENT_TMUX_PANE:-}" "${AGENT_TMUX_WORKTREE:-}"
13
+ "$TMUX_TARGET_BIN" -S "$tmux_target_socket" display-message -p -t "$tmux_target_pane" '#{pane_title}'