@termwire/cli 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,54 @@
1
1
  # @termwire/cli
2
2
 
3
+ ## 0.4.1
4
+
5
+ ### Patch Changes
6
+
7
+ - `termwire --version` prints the installed release.
8
+
9
+ There was no way to tell which version was installed: both `--version` and `-V`
10
+ failed with `unknown option`, leaving `npm ls -g @termwire/cli` as the only
11
+ answer. The number is read from the package manifest at runtime, the way
12
+ `@termwire/mcp` already reports its own version, so no build step has to inject
13
+ it and a checkout reports the same way an install does.
14
+
15
+ - @termwire/tmux@0.4.1
16
+ - @termwire/nvim@0.4.1
17
+
18
+ ## 0.4.0
19
+
20
+ ### Minor Changes
21
+
22
+ - 7e73a29: Closing a workspace session now kills the processes started in it.
23
+
24
+ `tmux kill-session` only sends `SIGHUP` to the foreground process group of each
25
+ pane, so background agent jobs detached from the terminal survived it and were
26
+ adopted by `init`. They accumulated for weeks, in one case 158 processes across
27
+ nine abandoned sessions, five of whose worktrees no longer existed on disk.
28
+
29
+ `up` now installs one global tmux `session-closed` hook that runs a hidden
30
+ `termwire _reap <session>` subcommand. The reap collects the processes of the
31
+ current user whose environment still carries `TERMWIRE_SESSION=<session>`, sends
32
+ `SIGTERM`, then confirms the survivors still carry the label before escalating
33
+ them to `SIGKILL`. It signals exactly that list of pids and never a pattern
34
+ match, and never the tmux server or anything it descends from. Each run appends
35
+ one line to `$XDG_STATE_HOME/termwire/reap.log`, because a tmux hook's output is
36
+ shown nowhere.
37
+
38
+ Installing the hook is idempotent. A repeated `up` updates our entry when the
39
+ interpreter or script path changed, drops duplicates of ours, and leaves a
40
+ `session-closed` hook of your own untouched. A tmux server that refuses the hook
41
+ only produces a warning; the workspace still comes up.
42
+
43
+ `@termwire/tmux` gains `showHooks`, `setHook`, and `unsetHook`. It keeps no
44
+ knowledge of what the hooks are for.
45
+
46
+ ### Patch Changes
47
+
48
+ - Updated dependencies [7e73a29]
49
+ - @termwire/tmux@0.4.0
50
+ - @termwire/nvim@0.4.0
51
+
3
52
  ## 0.3.0
4
53
 
5
54
  ### Minor Changes
package/README.md CHANGED
@@ -8,6 +8,7 @@ Requires Node >=22.12, tmux >=3.2, and Neovim >=0.9. It runs on Bun as well.
8
8
  ```bash
9
9
  npm install -g @termwire/cli
10
10
  termwire --help
11
+ termwire --version
11
12
  termwire up dev
12
13
  termwire open src/app.ts:42
13
14
  ```
@@ -35,6 +36,55 @@ Git branch names and replaced only in filesystem-safe worktree directory names.
35
36
  is changed only when `--branch` is present. Existing tmux sessions attach without Git mutations or
36
37
  rereading/reconciling configuration.
37
38
 
39
+ ## Session cleanup
40
+
41
+ `up` installs one global tmux hook, `session-closed`, that runs a hidden
42
+ `termwire _reap <session>` for the session that just closed. Without it,
43
+ processes started in a workspace outlive `tmux kill-session`: tmux only sends
44
+ `SIGHUP` to the foreground process group of each pane, so a background agent job
45
+ detached from the terminal is adopted by `init` and keeps running for weeks.
46
+
47
+ The reap finds every process of the current user whose environment still carries
48
+ `TERMWIRE_SESSION=<session>` (from `ps -E` on macOS, from `/proc` on Linux),
49
+ sends `SIGTERM`, waits two seconds, confirms the survivors still carry the label,
50
+ then escalates them to `SIGKILL`. It signals that list of pids and nothing else,
51
+ never a pattern match. The tmux server and everything it descends from are never
52
+ signalled, even when the server's own environment carries the label.
53
+
54
+ Each run appends one line to `$XDG_STATE_HOME/termwire/reap.log`, defaulting to
55
+ `~/.local/state/termwire/reap.log`, because a tmux hook's output is not shown
56
+ anywhere. The reap inherits the tmux server's environment, so `XDG_STATE_HOME`
57
+ is read as the server saw it when it started, not as your current shell exports
58
+ it. The log is never rotated; it gains one line per session close.
59
+
60
+ Installing the hook is idempotent: a repeated `up` updates our entry when the
61
+ interpreter or script path changed, drops duplicates of ours, and leaves any
62
+ `session-closed` hook you configured yourself in place. When the tmux server
63
+ refuses the hook, `up` warns and still brings the workspace up.
64
+
65
+ Two things escape the reap. A process that clears or rewrites its own
66
+ environment no longer carries the label, and on macOS the kernel hides the
67
+ environment of Apple's own signed binaries, so a bare `sleep` started in a pane
68
+ is invisible to `ps -E` while a `node` or `pnpm` process is not. Everything that
69
+ does carry the label is killed, including processes you started in the session
70
+ yourself; for a session you are closing, that is the point.
71
+
72
+ One false positive is possible on macOS, where `ps -E` flattens the environment
73
+ into a single line: a process holding `TERMWIRE_SESSION=<session>` inside the
74
+ *value* of another variable, a captured command line for instance, is
75
+ indistinguishable from one that carries the label itself. Linux reads `/proc`
76
+ and matches exactly.
77
+
78
+ The hook records the absolute path of the interpreter and script that installed
79
+ it, and the next `up` rewrites it when either moved. A path that disappears
80
+ without a further `up`, after `npx` prunes its cache for example, leaves a hook
81
+ that silently does nothing. Remove it by index:
82
+
83
+ ```bash
84
+ tmux show-hooks -g | grep TERMWIRE_REAP_HOOK # e.g. session-closed[1]
85
+ tmux set-hook -gu 'session-closed[1]'
86
+ ```
87
+
38
88
  ## `open`
39
89
 
40
90
  ```bash
@@ -339,6 +389,8 @@ while preserving the original failure.
339
389
  - The default layout does not start OpenCode automatically. Users may start it manually in an
340
390
  ordinary shell pane, or configure `["opencode"]` as a pane command. They may also reshape the
341
391
  workspace with tmux after creation.
392
+ - Closing a workspace session kills the processes it started, through the global
393
+ tmux `session-closed` hook that `up` installs.
342
394
  - `open <target>` resolves the path, checks that Neovim answers on the socket,
343
395
  opens the file, then focuses the editor pane when one is known.
344
396
  - The CLI does not need to be in `PATH` for the MCP server or the OpenCode
package/dist/exec.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export interface ExecResult {
2
+ exitCode: number;
3
+ stdout: string;
4
+ stderr: string;
5
+ }
6
+ export type Exec = (argv: readonly string[]) => Promise<ExecResult>;
7
+ export declare function spawnCapture(argv: readonly string[]): Promise<ExecResult>;
package/dist/exec.js ADDED
@@ -0,0 +1,22 @@
1
+ import { spawn } from "node:child_process";
2
+ export async function spawnCapture(argv) {
3
+ const [command, ...args] = argv;
4
+ if (command === undefined) {
5
+ throw new Error("command must not be empty");
6
+ }
7
+ return await new Promise((resolve, reject) => {
8
+ const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
9
+ let stdout = "";
10
+ let stderr = "";
11
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
12
+ stdout += chunk;
13
+ });
14
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
15
+ stderr += chunk;
16
+ });
17
+ child.once("error", reject);
18
+ child.once("close", (code) => {
19
+ resolve({ exitCode: code ?? 1, stdout, stderr });
20
+ });
21
+ });
22
+ }
package/dist/index.d.ts CHANGED
@@ -1,8 +1,16 @@
1
1
  export { prepareBranch } from "./branch.js";
2
+ export type { Exec, ExecResult } from "./exec.js";
3
+ export { spawnCapture } from "./exec.js";
2
4
  export type { NvimClient, OpenDependencies, OpenRequest, OpenResult, TmuxClient, } from "./open.js";
3
5
  export { open, parseTarget } from "./open.js";
4
- export type { ProgramDependencies, RuntimeDependencies, RuntimeOpenDependencies, } from "./program.js";
5
- export { createProgram, createRuntimeOpen, createRuntimeUp, executeGit, removeStaleSocket, run, } from "./program.js";
6
+ export type { DarwinProcessRow, DarwinScanDependencies, LinuxScanDependencies, ProcessEntry, ProcessScan, ProcessScanner, ProcessScannerDependencies, } from "./process-scan.js";
7
+ export { containsAssignment, createProcessScanner, parseDarwinArguments, parseDarwinProcesses, parseLinuxPpid, sessionVariable, } from "./process-scan.js";
8
+ export type { ProgramDependencies, RuntimeDependencies, RuntimeOpenDependencies, RuntimeReapDependencies, } from "./program.js";
9
+ export { createProgram, createRuntimeOpen, createRuntimeReap, createRuntimeUp, executeGit, killProcess, removeStaleSocket, run, } from "./program.js";
10
+ export type { KillOutcome, ReapDependencies, ReapReport, ReapSignal } from "./reap.js";
11
+ export { formatReapFailure, formatReapReport, protectedPids, reapLogPath, reapSession, selectTargets, } from "./reap.js";
12
+ export type { ReapHookOutcome, ReapHookPaths, ReapHookTmux } from "./reap-hook.js";
13
+ export { createReapHookCommand, ensureReapHook, reapCommandName, reapHookMarker, reapHookName, } from "./reap-hook.js";
6
14
  export type { UpDependencies, UpRequest } from "./up.js";
7
15
  export { up } from "./up.js";
8
16
  export type { GitExec, WorktreeEntry } from "./worktree.js";
package/dist/index.js CHANGED
@@ -1,5 +1,9 @@
1
1
  export { prepareBranch } from "./branch.js";
2
+ export { spawnCapture } from "./exec.js";
2
3
  export { open, parseTarget } from "./open.js";
3
- export { createProgram, createRuntimeOpen, createRuntimeUp, executeGit, removeStaleSocket, run, } from "./program.js";
4
+ export { containsAssignment, createProcessScanner, parseDarwinArguments, parseDarwinProcesses, parseLinuxPpid, sessionVariable, } from "./process-scan.js";
5
+ export { createProgram, createRuntimeOpen, createRuntimeReap, createRuntimeUp, executeGit, killProcess, removeStaleSocket, run, } from "./program.js";
6
+ export { formatReapFailure, formatReapReport, protectedPids, reapLogPath, reapSession, selectTargets, } from "./reap.js";
7
+ export { createReapHookCommand, ensureReapHook, reapCommandName, reapHookMarker, reapHookName, } from "./reap-hook.js";
4
8
  export { up } from "./up.js";
5
9
  export { findGitRoot, parseWorktreeList, prepareWorktree } from "./worktree.js";
@@ -0,0 +1,37 @@
1
+ import type { Exec } from "./exec.js";
2
+ export declare const sessionVariable = "TERMWIRE_SESSION";
3
+ export interface ProcessEntry {
4
+ pid: number;
5
+ ppid: number;
6
+ }
7
+ export interface ProcessScan {
8
+ /** Every process visible to the current user, used to protect our own ancestors. */
9
+ processes: ProcessEntry[];
10
+ /** Processes whose environment carries the scanned session label. */
11
+ labeled: number[];
12
+ }
13
+ export type ProcessScanner = (session: string) => Promise<ProcessScan>;
14
+ export interface DarwinScanDependencies {
15
+ exec: Exec;
16
+ uid: number;
17
+ }
18
+ export interface LinuxScanDependencies {
19
+ readdir: (path: string) => Promise<string[]>;
20
+ readFile: (path: string) => Promise<string>;
21
+ }
22
+ export interface ProcessScannerDependencies extends DarwinScanDependencies, LinuxScanDependencies {
23
+ platform: string;
24
+ }
25
+ export interface DarwinProcessRow extends ProcessEntry {
26
+ /** The command line, followed by the environment when `ps -E` could read it. */
27
+ details: string;
28
+ }
29
+ export declare function createProcessScanner(dependencies: ProcessScannerDependencies): ProcessScanner;
30
+ export declare function parseDarwinProcesses(stdout: string): DarwinProcessRow[];
31
+ export declare function parseDarwinArguments(stdout: string): Map<number, string>;
32
+ export declare function parseLinuxPpid(stat: string): number | undefined;
33
+ /**
34
+ * True when `text` assigns `needle`, meaning the match is a whole space-separated
35
+ * token. A command line that merely mentions the variable never qualifies.
36
+ */
37
+ export declare function containsAssignment(text: string, needle: string): boolean;
@@ -0,0 +1,138 @@
1
+ export const sessionVariable = "TERMWIRE_SESSION";
2
+ export function createProcessScanner(dependencies) {
3
+ if (dependencies.platform === "darwin") {
4
+ return createDarwinScanner(dependencies);
5
+ }
6
+ if (dependencies.platform === "linux") {
7
+ return createLinuxScanner(dependencies);
8
+ }
9
+ throw new Error(`process scanning is not supported on ${dependencies.platform}`);
10
+ }
11
+ export function parseDarwinProcesses(stdout) {
12
+ const rows = [];
13
+ for (const line of stdout.split("\n")) {
14
+ const parsed = /^\s*(\d+)\s+(\d+)\s(.*)$/.exec(line);
15
+ if (!parsed)
16
+ continue;
17
+ rows.push({ pid: Number(parsed[1]), ppid: Number(parsed[2]), details: parsed[3] });
18
+ }
19
+ return rows;
20
+ }
21
+ export function parseDarwinArguments(stdout) {
22
+ const args = new Map();
23
+ for (const line of stdout.split("\n")) {
24
+ const parsed = /^\s*(\d+)\s(.*)$/.exec(line);
25
+ if (!parsed)
26
+ continue;
27
+ args.set(Number(parsed[1]), parsed[2]);
28
+ }
29
+ return args;
30
+ }
31
+ export function parseLinuxPpid(stat) {
32
+ const commandEnd = stat.lastIndexOf(")");
33
+ if (commandEnd === -1)
34
+ return undefined;
35
+ const fields = stat
36
+ .slice(commandEnd + 1)
37
+ .trim()
38
+ .split(/\s+/);
39
+ const ppid = Number(fields[1]);
40
+ return Number.isInteger(ppid) ? ppid : undefined;
41
+ }
42
+ /**
43
+ * True when `text` assigns `needle`, meaning the match is a whole space-separated
44
+ * token. A command line that merely mentions the variable never qualifies.
45
+ */
46
+ export function containsAssignment(text, needle) {
47
+ let index = text.indexOf(needle);
48
+ while (index !== -1) {
49
+ const before = index === 0 ? " " : text.charAt(index - 1);
50
+ const after = index + needle.length >= text.length ? " " : text.charAt(index + needle.length);
51
+ if (/\s/.test(before) && /\s/.test(after))
52
+ return true;
53
+ index = text.indexOf(needle, index + 1);
54
+ }
55
+ return false;
56
+ }
57
+ /**
58
+ * macOS has no `/proc`, so the environment comes from `ps -E`, which appends it to
59
+ * the command column. A process that only mentions the label on its command line
60
+ * would look identical, so every candidate is re-read without `-E` and the command
61
+ * line is stripped off before the label is looked up in what remains.
62
+ */
63
+ function createDarwinScanner(dependencies) {
64
+ return async (session) => {
65
+ const needle = `${sessionVariable}=${session}`;
66
+ const rows = parseDarwinProcesses(await runPs(dependencies.exec, [
67
+ "ps",
68
+ "-Eww",
69
+ "-o",
70
+ "pid=,ppid=,command=",
71
+ "-U",
72
+ String(dependencies.uid),
73
+ ]));
74
+ const processes = rows.map(({ pid, ppid }) => ({ pid, ppid }));
75
+ const candidates = rows.filter((row) => containsAssignment(row.details, needle));
76
+ if (candidates.length === 0) {
77
+ return { processes, labeled: [] };
78
+ }
79
+ const args = parseDarwinArguments(await runPs(dependencies.exec, ["ps", "-ww", "-o", "pid=,args=", "-p", candidates.map((c) => c.pid).join(",")],
80
+ // `ps` exits non-zero when none of the requested pids exist any more, and a
81
+ // candidate that just died is simply not a target.
82
+ { allowMissingPids: true }));
83
+ const labeled = candidates
84
+ .filter((row) => {
85
+ const argv = args.get(row.pid);
86
+ if (argv === undefined || !row.details.startsWith(argv))
87
+ return false;
88
+ return containsAssignment(row.details.slice(argv.length), needle);
89
+ })
90
+ .map((row) => row.pid);
91
+ return { processes, labeled };
92
+ };
93
+ }
94
+ function createLinuxScanner(dependencies) {
95
+ return async (session) => {
96
+ const label = `${sessionVariable}=${session}`;
97
+ const processes = [];
98
+ const labeled = [];
99
+ for (const entry of await dependencies.readdir("/proc")) {
100
+ if (!/^\d+$/.test(entry))
101
+ continue;
102
+ const pid = Number(entry);
103
+ const stat = await readOptional(dependencies, `/proc/${entry}/stat`);
104
+ if (stat === undefined)
105
+ continue;
106
+ const ppid = parseLinuxPpid(stat);
107
+ if (ppid === undefined)
108
+ continue;
109
+ processes.push({ pid, ppid });
110
+ // Readable only for our own processes, so other users are skipped silently.
111
+ const environ = await readOptional(dependencies, `/proc/${entry}/environ`);
112
+ if (environ === undefined)
113
+ continue;
114
+ if (environ.split("\0").includes(label))
115
+ labeled.push(pid);
116
+ }
117
+ return { processes, labeled };
118
+ };
119
+ }
120
+ async function runPs(exec, argv, options = {}) {
121
+ const execution = await exec(argv);
122
+ if (execution.exitCode === 0)
123
+ return execution.stdout;
124
+ if (options.allowMissingPids && execution.stdout.trim().length === 0)
125
+ return "";
126
+ // A failed listing must not read as an empty one: that would log a clean reap
127
+ // while the processes it exists to kill keep running.
128
+ const details = execution.stderr.trim();
129
+ throw new Error(`${argv.join(" ")} failed (exit ${execution.exitCode})${details ? `: ${details}` : ""}`);
130
+ }
131
+ async function readOptional(dependencies, path) {
132
+ try {
133
+ return await dependencies.readFile(path);
134
+ }
135
+ catch {
136
+ return undefined;
137
+ }
138
+ }
package/dist/program.d.ts CHANGED
@@ -1,12 +1,15 @@
1
1
  import { createNvim } from "@termwire/nvim";
2
2
  import { createTmux } from "@termwire/tmux";
3
3
  import { Command } from "commander";
4
+ import { type Exec } from "./exec.js";
4
5
  import { type OpenRequest, type OpenResult } from "./open.js";
6
+ import { type KillOutcome, type ReapSignal } from "./reap.js";
5
7
  import { type UpRequest } from "./up.js";
6
8
  import { type GitExec } from "./worktree.js";
7
9
  export interface ProgramDependencies {
8
10
  up: (request: UpRequest) => Promise<void>;
9
11
  open: (request: OpenRequest) => Promise<OpenResult>;
12
+ reap: (session: string) => Promise<void>;
10
13
  writeError: (message: string) => void;
11
14
  writeOutput: (message: string) => void;
12
15
  }
@@ -15,6 +18,9 @@ export interface RuntimeDependencies {
15
18
  cwd: () => string;
16
19
  env: Record<string, string | undefined>;
17
20
  homedir: () => string;
21
+ execPath: string;
22
+ scriptPath: string | undefined;
23
+ warn: (message: string) => void;
18
24
  readFile: (path: string, encoding: "utf8") => Promise<string>;
19
25
  gitExec: GitExec;
20
26
  mkdir: (path: string, options: {
@@ -23,6 +29,23 @@ export interface RuntimeDependencies {
23
29
  pathExists: (path: string) => Promise<boolean>;
24
30
  unlink: (path: string) => Promise<void>;
25
31
  }
32
+ export interface RuntimeReapDependencies {
33
+ env: Record<string, string | undefined>;
34
+ homedir: () => string;
35
+ platform: string;
36
+ uid: number;
37
+ pid: number;
38
+ exec: Exec;
39
+ readdir: (path: string) => Promise<string[]>;
40
+ readFile: (path: string) => Promise<string>;
41
+ kill: (pid: number, signal: ReapSignal) => KillOutcome;
42
+ wait: (milliseconds: number) => Promise<void>;
43
+ appendFile: (path: string, contents: string) => Promise<void>;
44
+ mkdir: (path: string, options: {
45
+ recursive: true;
46
+ }) => Promise<unknown>;
47
+ now: () => Date;
48
+ }
26
49
  export interface RuntimeOpenDependencies {
27
50
  createNvim: () => ReturnType<typeof createNvim>;
28
51
  createTmux: () => ReturnType<typeof createTmux>;
@@ -32,6 +55,8 @@ export interface RuntimeOpenDependencies {
32
55
  export declare const executeGit: GitExec;
33
56
  export declare function removeStaleSocket(path: string, unlink: (path: string) => Promise<void>): Promise<void>;
34
57
  export declare function createRuntimeUp(dependencies?: Partial<RuntimeDependencies>): (request: UpRequest) => Promise<void>;
58
+ export declare function killProcess(pid: number, signal: ReapSignal): KillOutcome;
59
+ export declare function createRuntimeReap(dependencies?: Partial<RuntimeReapDependencies>): (session: string) => Promise<void>;
35
60
  export declare function createRuntimeOpen(dependencies?: Partial<RuntimeOpenDependencies>): (request: OpenRequest) => Promise<OpenResult>;
36
61
  export declare function createProgram(dependencies: ProgramDependencies): Command;
37
62
  export declare function run(argv: readonly string[], dependencies?: Partial<ProgramDependencies>): Promise<number>;
package/dist/program.js CHANGED
@@ -1,16 +1,29 @@
1
1
  import { spawn } from "node:child_process";
2
- import { mkdir as mkdirDirectory, readFile as readFileFromDisk, stat, unlink as unlinkFile, } from "node:fs/promises";
2
+ import { readFileSync } from "node:fs";
3
+ import { appendFile as appendFileToDisk, mkdir as mkdirDirectory, readdir as readDirectory, readFile as readFileFromDisk, stat, unlink as unlinkFile, } from "node:fs/promises";
3
4
  import { homedir as getHomeDirectory } from "node:os";
5
+ import { dirname, resolve as resolvePath } from "node:path";
4
6
  import { createNvim } from "@termwire/nvim";
5
7
  import { createTmux } from "@termwire/tmux";
6
8
  import { Command, CommanderError } from "commander";
7
9
  import { prepareBranch } from "./branch.js";
8
10
  import { createConfigLoader } from "./config-loader.js";
9
11
  import { resolveLayout } from "./config-validation.js";
12
+ import { spawnCapture } from "./exec.js";
10
13
  import { createLayout } from "./layout.js";
11
14
  import { open } from "./open.js";
15
+ import { createProcessScanner } from "./process-scan.js";
16
+ import { formatReapFailure, formatReapReport, parseTmuxServerPid, reapLogPath, reapSession, } from "./reap.js";
17
+ import { ensureReapHook, reapCommandName } from "./reap-hook.js";
12
18
  import { up } from "./up.js";
13
19
  import { findGitRoot, prepareWorktree } from "./worktree.js";
20
+ /**
21
+ * Read at runtime rather than baked in at build time, the way `@termwire/mcp`
22
+ * reports its own version. `dist/program.js` and `src/program.ts` both sit one
23
+ * level below the package root, so the same specifier resolves in a published
24
+ * install and from a checkout.
25
+ */
26
+ const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
14
27
  export const executeGit = async (argv, options) => {
15
28
  const [command, ...args] = argv;
16
29
  if (command === undefined) {
@@ -68,6 +81,9 @@ export function createRuntimeUp(dependencies = {}) {
68
81
  }
69
82
  });
70
83
  const unlink = dependencies.unlink ?? unlinkFile;
84
+ const execPath = dependencies.execPath ?? process.execPath;
85
+ const scriptPath = "scriptPath" in dependencies ? dependencies.scriptPath : process.argv[1];
86
+ const warn = dependencies.warn ?? ((message) => process.stderr.write(message));
71
87
  const loader = createConfigLoader({ env, homedir, exists: pathExists, readFile });
72
88
  const loadGlobalConfig = loader.loadGlobal;
73
89
  const loadProjectConfig = loader.loadProject;
@@ -81,12 +97,95 @@ export function createRuntimeUp(dependencies = {}) {
81
97
  },
82
98
  removeFile: (path) => removeStaleSocket(path, unlink),
83
99
  tmux,
100
+ installReapHook: () => installReapHook({ tmux, execPath, scriptPath, warn }),
84
101
  loadGlobalConfig,
85
102
  loadProjectConfig,
86
103
  resolveLayout,
87
104
  createLayout,
88
105
  });
89
106
  }
107
+ /**
108
+ * Installing the cleanup hook is best effort: a workspace is still usable when the
109
+ * tmux server refuses the hook, so `up` only warns.
110
+ */
111
+ async function installReapHook(options) {
112
+ try {
113
+ if (options.scriptPath === undefined) {
114
+ throw new Error("the termwire script path is unknown");
115
+ }
116
+ await ensureReapHook({
117
+ tmux: options.tmux,
118
+ execPath: options.execPath,
119
+ scriptPath: resolvePath(options.scriptPath),
120
+ });
121
+ }
122
+ catch (error) {
123
+ const message = error instanceof Error ? error.message : String(error);
124
+ options.warn(`termwire: session cleanup hook not installed: ${message}\n`);
125
+ }
126
+ }
127
+ export function killProcess(pid, signal) {
128
+ try {
129
+ process.kill(pid, signal);
130
+ return "signalled";
131
+ }
132
+ catch (error) {
133
+ const code = error.code;
134
+ if (code === "ESRCH")
135
+ return "gone";
136
+ if (code === "EPERM")
137
+ return "denied";
138
+ throw error;
139
+ }
140
+ }
141
+ export function createRuntimeReap(dependencies = {}) {
142
+ const env = dependencies.env ?? process.env;
143
+ const homedir = dependencies.homedir ?? getHomeDirectory;
144
+ const platform = dependencies.platform ?? process.platform;
145
+ const uid = dependencies.uid ?? process.getuid?.() ?? 0;
146
+ const pid = dependencies.pid ?? process.pid;
147
+ const exec = dependencies.exec ?? spawnCapture;
148
+ const readdir = dependencies.readdir ?? ((path) => readDirectory(path));
149
+ const readFile = dependencies.readFile ?? ((path) => readFileFromDisk(path, "utf8"));
150
+ const kill = dependencies.kill ?? killProcess;
151
+ const wait = dependencies.wait ??
152
+ ((milliseconds) => new Promise((resolveWait) => {
153
+ setTimeout(resolveWait, milliseconds);
154
+ }));
155
+ const appendFile = dependencies.appendFile ??
156
+ ((path, contents) => appendFileToDisk(path, contents));
157
+ const mkdir = dependencies.mkdir ?? mkdirDirectory;
158
+ const now = dependencies.now ?? (() => new Date());
159
+ const record = async (line) => {
160
+ const path = reapLogPath({ env, homedir });
161
+ try {
162
+ await mkdir(dirname(path), { recursive: true });
163
+ await appendFile(path, line);
164
+ }
165
+ catch {
166
+ // A missing log must not hide the reap itself.
167
+ }
168
+ };
169
+ return async (session) => {
170
+ try {
171
+ const serverPid = parseTmuxServerPid(env.TMUX);
172
+ const report = await reapSession(session, {
173
+ scan: createProcessScanner({ platform, exec, uid, readdir, readFile }),
174
+ kill,
175
+ wait,
176
+ selfPid: pid,
177
+ // The reap inherits the tmux server's environment, TMUX included, which is
178
+ // the only way back to the server it must not kill.
179
+ ...(serverPid === undefined ? {} : { serverPid }),
180
+ });
181
+ await record(formatReapReport(report, now().toISOString()));
182
+ }
183
+ catch (error) {
184
+ await record(formatReapFailure(session, error, now().toISOString()));
185
+ throw error;
186
+ }
187
+ };
188
+ }
90
189
  export function createRuntimeOpen(dependencies = {}) {
91
190
  const nvim = (dependencies.createNvim ?? (() => createNvim()))();
92
191
  const tmux = (dependencies.createTmux ?? (() => createTmux()))();
@@ -101,6 +200,7 @@ export function createProgram(dependencies) {
101
200
  });
102
201
  program.exitOverride();
103
202
  program.showHelpAfterError();
203
+ program.version(manifest.version, "-V, --version", "print the installed termwire version");
104
204
  program
105
205
  .command("up <name>")
106
206
  .description("create or attach to the workspace tmux session <project>-<name>")
@@ -146,6 +246,14 @@ Target syntax:
146
246
  const suffix = result.line === undefined ? "" : ` at line ${result.line}`;
147
247
  dependencies.writeOutput(`Opened ${result.path}${suffix}\n`);
148
248
  });
249
+ // Part of the `up` lifecycle, not a user-facing command: the global tmux
250
+ // `session-closed` hook installed by `up` invokes it with the closed session.
251
+ program
252
+ .command(`${reapCommandName} <session>`, { hidden: true })
253
+ .description("kill the processes a closed workspace session left behind")
254
+ .action(async (session) => {
255
+ await dependencies.reap(session);
256
+ });
149
257
  return program;
150
258
  }
151
259
  export async function run(argv, dependencies = {}) {
@@ -153,6 +261,7 @@ export async function run(argv, dependencies = {}) {
153
261
  const program = createProgram({
154
262
  up: dependencies.up ?? createRuntimeUp(),
155
263
  open: dependencies.open ?? createRuntimeOpen(),
264
+ reap: dependencies.reap ?? createRuntimeReap(),
156
265
  writeError,
157
266
  writeOutput: dependencies.writeOutput ?? ((message) => process.stdout.write(message)),
158
267
  });
@@ -0,0 +1,41 @@
1
+ import type { HookEntry, SetHookOptions, ShowHooksOptions, UnsetHookOptions } from "@termwire/tmux";
2
+ export declare const reapHookName = "session-closed";
3
+ /**
4
+ * Identifies our entry among the user's own `session-closed` hooks, and doubles as
5
+ * a harmless environment assignment in the shell command that carries it.
6
+ */
7
+ export declare const reapHookMarker = "TERMWIRE_REAP_HOOK=1";
8
+ export declare const reapCommandName = "_reap";
9
+ export type ReapHookOutcome = "created" | "updated" | "unchanged";
10
+ export interface ReapHookTmux {
11
+ showHooks: (options?: ShowHooksOptions) => Promise<HookEntry[]>;
12
+ setHook: (options: SetHookOptions) => Promise<void>;
13
+ unsetHook: (options: UnsetHookOptions) => Promise<void>;
14
+ }
15
+ export interface ReapHookPaths {
16
+ execPath: string;
17
+ scriptPath: string;
18
+ }
19
+ /**
20
+ * The tmux server has its own environment and no `PATH` we control, so the hook
21
+ * names the interpreter and the script by absolute path. `#{hook_session_name}` is
22
+ * expanded by tmux when the hook fires; only the global hook sees it, because a
23
+ * session is destroyed before its own hooks run.
24
+ *
25
+ * `run-shell -b` never runs when the session being closed is the last one, because
26
+ * the server shuts down first. A foreground `run-shell` does run, and the trailing
27
+ * `&` hands the reap to a detached child that outlives the server, so tmux waits
28
+ * only for the fork and the closing client never blocks on it.
29
+ *
30
+ * The hook is global and therefore fires for sessions Termwire never created,
31
+ * whose names it never sanitized. `#{q:...}` is what makes that safe: tmux escapes
32
+ * the sh(1) special characters in the name, so the name must stay unquoted here.
33
+ * Quoting it would disarm the escaping and turn a session named
34
+ * `evil'; rm -rf ~; '` into a command.
35
+ */
36
+ export declare function createReapHookCommand(paths: ReapHookPaths): string;
37
+ export declare function ensureReapHook(options: {
38
+ tmux: ReapHookTmux;
39
+ execPath: string;
40
+ scriptPath: string;
41
+ }): Promise<ReapHookOutcome>;
@@ -0,0 +1,76 @@
1
+ import { isAbsolute } from "node:path";
2
+ export const reapHookName = "session-closed";
3
+ /**
4
+ * Identifies our entry among the user's own `session-closed` hooks, and doubles as
5
+ * a harmless environment assignment in the shell command that carries it.
6
+ */
7
+ export const reapHookMarker = "TERMWIRE_REAP_HOOK=1";
8
+ export const reapCommandName = "_reap";
9
+ /** tmux expands this when the hook fires; `#{q:...}` escapes it for sh(1). */
10
+ const sessionFormat = "hook_session_name";
11
+ /**
12
+ * The tmux server has its own environment and no `PATH` we control, so the hook
13
+ * names the interpreter and the script by absolute path. `#{hook_session_name}` is
14
+ * expanded by tmux when the hook fires; only the global hook sees it, because a
15
+ * session is destroyed before its own hooks run.
16
+ *
17
+ * `run-shell -b` never runs when the session being closed is the last one, because
18
+ * the server shuts down first. A foreground `run-shell` does run, and the trailing
19
+ * `&` hands the reap to a detached child that outlives the server, so tmux waits
20
+ * only for the fork and the closing client never blocks on it.
21
+ *
22
+ * The hook is global and therefore fires for sessions Termwire never created,
23
+ * whose names it never sanitized. `#{q:...}` is what makes that safe: tmux escapes
24
+ * the sh(1) special characters in the name, so the name must stay unquoted here.
25
+ * Quoting it would disarm the escaping and turn a session named
26
+ * `evil'; rm -rf ~; '` into a command.
27
+ */
28
+ export function createReapHookCommand(paths) {
29
+ const execPath = shellQuote(paths.execPath, "interpreter path");
30
+ const scriptPath = shellQuote(paths.scriptPath, "script path");
31
+ const session = `#{q:${sessionFormat}}`;
32
+ const command = `${reapHookMarker} ${execPath} ${scriptPath} ${reapCommandName} ${session}`;
33
+ return `run-shell "${command} >/dev/null 2>&1 &"`;
34
+ }
35
+ export async function ensureReapHook(options) {
36
+ const command = createReapHookCommand(options);
37
+ const entries = await options.tmux.showHooks({ global: true });
38
+ const [existing, ...duplicates] = entries.filter((entry) => entry.name === reapHookName && entry.command.includes(reapHookMarker));
39
+ if (existing === undefined) {
40
+ // Appending keeps any `session-closed` hook the user configured themselves.
41
+ await options.tmux.setHook({ name: reapHookName, command, global: true, append: true });
42
+ return "created";
43
+ }
44
+ let outcome = "unchanged";
45
+ if (existing.command !== command) {
46
+ await options.tmux.setHook({ name: hookTarget(existing), command, global: true });
47
+ outcome = "updated";
48
+ }
49
+ // Earlier versions, or a hand-edited server, can leave more than one of ours.
50
+ for (const duplicate of [...duplicates].reverse()) {
51
+ await options.tmux.unsetHook({ name: hookTarget(duplicate), global: true });
52
+ outcome = "updated";
53
+ }
54
+ return outcome;
55
+ }
56
+ function hookTarget(entry) {
57
+ return entry.index === undefined ? entry.name : `${entry.name}[${entry.index}]`;
58
+ }
59
+ /**
60
+ * The path is read by two parsers: tmux, which expands `#{...}` and backslash
61
+ * escapes inside double quotes, and then `sh`. Quoting characters would have to
62
+ * survive both, so they are rejected instead of escaped twice.
63
+ */
64
+ function shellQuote(value, label) {
65
+ if (value.trim().length === 0) {
66
+ throw new Error(`${label} must not be empty`);
67
+ }
68
+ if (!isAbsolute(value)) {
69
+ throw new Error(`${label} must be absolute: ${value}`);
70
+ }
71
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters break both parsers
72
+ if (/['"\\#\n\r\t\u0000-\u001f]/.test(value)) {
73
+ throw new Error(`${label} contains characters a tmux hook cannot carry: ${value}`);
74
+ }
75
+ return `'${value}'`;
76
+ }
package/dist/reap.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { ProcessScan, ProcessScanner } from "./process-scan.js";
2
+ export type ReapSignal = "SIGTERM" | "SIGKILL" | 0;
3
+ export type KillOutcome = "signalled" | "gone" | "denied";
4
+ export interface ReapDependencies {
5
+ scan: ProcessScanner;
6
+ kill: (pid: number, signal: ReapSignal) => KillOutcome;
7
+ wait: (milliseconds: number) => Promise<void>;
8
+ selfPid: number;
9
+ /** The tmux server, which the hook detaches from and may itself carry the label. */
10
+ serverPid?: number;
11
+ graceMs?: number;
12
+ settleMs?: number;
13
+ }
14
+ export interface ReapReport {
15
+ session: string;
16
+ targets: number[];
17
+ terminated: number[];
18
+ killed: number[];
19
+ survived: number[];
20
+ denied: number[];
21
+ /** Still alive at escalation time, but no longer labeled: a recycled pid. */
22
+ unlabeled: number[];
23
+ }
24
+ export declare const defaultGraceMs = 2000;
25
+ export declare const defaultSettleMs = 250;
26
+ /**
27
+ * Processes never worth signalling: this process, the tmux server, whatever either
28
+ * of them descends from, and init.
29
+ *
30
+ * Walking up from this process alone is not enough. The hook detaches the reap with
31
+ * `&`, so the forking shell is gone and this process is already a child of init by
32
+ * the time it scans. The tmux server is therefore not an ancestor, and it does
33
+ * inherit the environment of whoever started it, label included: without naming it
34
+ * the reap would kill the server and every other session on it.
35
+ */
36
+ export declare function protectedPids(scan: ProcessScan, selfPid: number, serverPid?: number): Set<number>;
37
+ export declare function selectTargets(scan: ProcessScan, selfPid: number, serverPid?: number): number[];
38
+ /** Parses the server pid out of `TMUX`, which tmux sets to `socket,pid,session`. */
39
+ export declare function parseTmuxServerPid(tmux: string | undefined): number | undefined;
40
+ export declare function reapSession(session: string, dependencies: ReapDependencies): Promise<ReapReport>;
41
+ export declare function formatReapReport(report: ReapReport, timestamp: string): string;
42
+ export declare function formatReapFailure(session: string, error: unknown, timestamp: string): string;
43
+ /** `run-shell` output goes nowhere, so every reap records what it did here. */
44
+ export declare function reapLogPath(dependencies: {
45
+ env: Record<string, string | undefined>;
46
+ homedir: () => string;
47
+ }): string;
package/dist/reap.js ADDED
@@ -0,0 +1,117 @@
1
+ import { isAbsolute, join } from "node:path";
2
+ export const defaultGraceMs = 2000;
3
+ export const defaultSettleMs = 250;
4
+ const killRounds = 2;
5
+ /**
6
+ * Processes never worth signalling: this process, the tmux server, whatever either
7
+ * of them descends from, and init.
8
+ *
9
+ * Walking up from this process alone is not enough. The hook detaches the reap with
10
+ * `&`, so the forking shell is gone and this process is already a child of init by
11
+ * the time it scans. The tmux server is therefore not an ancestor, and it does
12
+ * inherit the environment of whoever started it, label included: without naming it
13
+ * the reap would kill the server and every other session on it.
14
+ */
15
+ export function protectedPids(scan, selfPid, serverPid) {
16
+ const parents = new Map(scan.processes.map((entry) => [entry.pid, entry.ppid]));
17
+ const protectedSet = new Set([0, 1, selfPid]);
18
+ if (serverPid !== undefined)
19
+ protectedSet.add(serverPid);
20
+ for (const start of [selfPid, serverPid]) {
21
+ if (start === undefined)
22
+ continue;
23
+ let current = parents.get(start);
24
+ while (current !== undefined && !protectedSet.has(current)) {
25
+ protectedSet.add(current);
26
+ current = parents.get(current);
27
+ }
28
+ }
29
+ return protectedSet;
30
+ }
31
+ export function selectTargets(scan, selfPid, serverPid) {
32
+ const excluded = protectedPids(scan, selfPid, serverPid);
33
+ return [...new Set(scan.labeled)].filter((pid) => !excluded.has(pid)).sort((a, b) => a - b);
34
+ }
35
+ /** Parses the server pid out of `TMUX`, which tmux sets to `socket,pid,session`. */
36
+ export function parseTmuxServerPid(tmux) {
37
+ const pid = Number(tmux?.split(",")[1]);
38
+ return Number.isInteger(pid) && pid > 0 ? pid : undefined;
39
+ }
40
+ export async function reapSession(session, dependencies) {
41
+ const scan = await dependencies.scan(session);
42
+ const targets = selectTargets(scan, dependencies.selfPid, dependencies.serverPid);
43
+ const denied = new Set();
44
+ if (targets.length === 0) {
45
+ return {
46
+ session,
47
+ targets,
48
+ terminated: [],
49
+ killed: [],
50
+ survived: [],
51
+ denied: [],
52
+ unlabeled: [],
53
+ };
54
+ }
55
+ for (const pid of targets) {
56
+ if (dependencies.kill(pid, "SIGTERM") === "denied")
57
+ denied.add(pid);
58
+ }
59
+ await dependencies.wait(dependencies.graceMs ?? defaultGraceMs);
60
+ const survivingPids = targets.filter((pid) => dependencies.kill(pid, 0) !== "gone");
61
+ const terminated = targets.filter((pid) => !survivingPids.includes(pid));
62
+ // The grace period is long enough for a pid to be freed and handed to something
63
+ // else, so survivors are confirmed against a fresh scan before SIGKILL. A scan
64
+ // that fails here aborts the escalation rather than risk an innocent pid.
65
+ const relabeled = survivingPids.length === 0
66
+ ? new Set()
67
+ : new Set(selectTargets(await dependencies.scan(session), dependencies.selfPid, dependencies.serverPid));
68
+ let alive = survivingPids.filter((pid) => relabeled.has(pid));
69
+ const unlabeled = survivingPids.filter((pid) => !relabeled.has(pid));
70
+ const killed = [];
71
+ for (let round = 0; round < killRounds && alive.length > 0; round += 1) {
72
+ for (const pid of alive) {
73
+ if (dependencies.kill(pid, "SIGKILL") === "denied")
74
+ denied.add(pid);
75
+ }
76
+ await dependencies.wait(dependencies.settleMs ?? defaultSettleMs);
77
+ const survivors = alive.filter((pid) => dependencies.kill(pid, 0) !== "gone");
78
+ killed.push(...alive.filter((pid) => !survivors.includes(pid)));
79
+ alive = survivors;
80
+ }
81
+ return {
82
+ session,
83
+ targets,
84
+ terminated,
85
+ killed: killed.sort((a, b) => a - b),
86
+ survived: alive,
87
+ denied: [...denied].sort((a, b) => a - b),
88
+ unlabeled,
89
+ };
90
+ }
91
+ export function formatReapReport(report, timestamp) {
92
+ const fields = [
93
+ `session=${report.session}`,
94
+ `targets=${formatPids(report.targets)}`,
95
+ `terminated=${formatPids(report.terminated)}`,
96
+ `killed=${formatPids(report.killed)}`,
97
+ `survived=${formatPids(report.survived)}`,
98
+ `denied=${formatPids(report.denied)}`,
99
+ `unlabeled=${formatPids(report.unlabeled)}`,
100
+ ];
101
+ return `${timestamp} ${fields.join(" ")}\n`;
102
+ }
103
+ export function formatReapFailure(session, error, timestamp) {
104
+ const message = error instanceof Error ? error.message : String(error);
105
+ return `${timestamp} session=${session} error=${message.replace(/\s+/g, " ")}\n`;
106
+ }
107
+ /** `run-shell` output goes nowhere, so every reap records what it did here. */
108
+ export function reapLogPath(dependencies) {
109
+ const xdgStateHome = dependencies.env.XDG_STATE_HOME;
110
+ const stateHome = xdgStateHome && isAbsolute(xdgStateHome)
111
+ ? xdgStateHome
112
+ : join(dependencies.homedir(), ".local", "state");
113
+ return join(stateHome, "termwire", "reap.log");
114
+ }
115
+ function formatPids(pids) {
116
+ return pids.length === 0 ? "-" : pids.join(",");
117
+ }
package/dist/up.d.ts CHANGED
@@ -23,6 +23,8 @@ export interface UpDependencies {
23
23
  mkdir: (path: string) => Promise<void>;
24
24
  removeFile: (path: string) => Promise<void>;
25
25
  tmux: ReturnType<typeof createTmux>;
26
+ /** Best effort: a workspace is worth having even without the cleanup hook. */
27
+ installReapHook: () => Promise<void>;
26
28
  loadGlobalConfig: () => Promise<LoadedConfig | undefined>;
27
29
  loadProjectConfig: (gitRoot: string) => Promise<LoadedConfig | undefined>;
28
30
  resolveLayout: (globalConfig: LoadedConfig | undefined, projectConfig: LoadedConfig | undefined) => LayoutConfig;
package/dist/up.js CHANGED
@@ -10,6 +10,7 @@ export async function up(request, dependencies) {
10
10
  const gitRoot = await dependencies.findGitRoot(cwd);
11
11
  const identity = createIdentity({ cwd, gitRoot, name: request.name });
12
12
  if (await dependencies.tmux.hasSession(identity.session)) {
13
+ await bestEffortInstallReapHook(dependencies);
13
14
  await dependencies.tmux.attach(identity.session);
14
15
  return;
15
16
  }
@@ -23,6 +24,7 @@ export async function up(request, dependencies) {
23
24
  cwd: workspace,
24
25
  });
25
26
  try {
27
+ await bestEffortInstallReapHook(dependencies);
26
28
  await dependencies.tmux.setSessionTitle(identity.session);
27
29
  await dependencies.createLayout({
28
30
  tmux: dependencies.tmux,
@@ -66,6 +68,15 @@ async function resolveWorkspace(request, dependencies, identity, gitRoot, cwd) {
66
68
  branch: request.branch ?? name,
67
69
  });
68
70
  }
71
+ async function bestEffortInstallReapHook(dependencies) {
72
+ try {
73
+ await dependencies.installReapHook();
74
+ }
75
+ catch {
76
+ // Never trade the workspace for the cleanup hook: an implementation that
77
+ // reports failures does so itself, before throwing.
78
+ }
79
+ }
69
80
  async function bestEffortKillSession(tmux, session) {
70
81
  try {
71
82
  await tmux.killSession(session);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@termwire/cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -37,8 +37,8 @@
37
37
  "url": "https://github.com/max-konin/termwire/issues"
38
38
  },
39
39
  "dependencies": {
40
- "@termwire/nvim": "^0.3.0",
41
- "@termwire/tmux": "^0.3.0",
40
+ "@termwire/nvim": "^0.4.1",
41
+ "@termwire/tmux": "^0.4.1",
42
42
  "commander": "^15.0.0",
43
43
  "jsonc-parser": "^3.3.1",
44
44
  "zod": "^4.0.0"