@a2f0/agent-tool 0.1.72 → 0.1.73
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/README.md +6 -5
- package/package.json +2 -1
- package/skills/performance-pass/SKILL.md +107 -0
- package/skills/performance-pass/agents/openai.yaml +4 -0
- package/skills/performance-pass/references/lessons.md +30 -0
- package/skills/space-cleanup/SKILL.md +96 -0
- package/skills/space-cleanup/agents/openai.yaml +4 -0
- package/src/cli.ts +8 -0
- package/src/perf/browser.ts +269 -0
- package/src/perf/command.ts +82 -0
- package/src/perf/diff.ts +115 -0
- package/src/perf/graph.ts +100 -0
- package/src/perf/options.ts +107 -0
- package/src/perf/serve.ts +163 -0
- package/src/permissions/catalog.ts +4 -1
- package/src/skills/bundled.ts +9 -0
- package/src/space/candidates.ts +228 -0
- package/src/space/command.ts +325 -0
- package/src/space/machine.ts +303 -0
- package/src/space/processes.ts +186 -0
- package/src/space/targets.ts +24 -0
- package/src/system/checkouts.ts +113 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/** Which repositories other processes are working in. */
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
export interface Proc {
|
|
6
|
+
readonly pid: number;
|
|
7
|
+
readonly ppid: number;
|
|
8
|
+
/** Process group: members of the caller's shell pipeline share it. */
|
|
9
|
+
readonly pgid?: number;
|
|
10
|
+
readonly name: string;
|
|
11
|
+
readonly args: string;
|
|
12
|
+
cwd?: string;
|
|
13
|
+
/** lsof named the working directory but could not read it, as Linux does for non-dumpable processes. */
|
|
14
|
+
readonly unreadable?: true;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const PIPELINE_FILTERS = new Set(["head", "tail", "less", "more", "cat", "tee", "grep", "rg", "sed", "awk", "jq", "sort", "uniq", "wc", "cut", "tr", "column"]);
|
|
18
|
+
/** An interactive shell waiting at a prompt; `bash build.sh` and `sh -c ...` are working. */
|
|
19
|
+
const IDLE_SHELL = /^-?(?:\S*\/)?(?:zsh|bash|sh|fish|dash|tmux)(?:\s+-[il]+)*$/;
|
|
20
|
+
function idleShell(proc: Proc): boolean {
|
|
21
|
+
return IDLE_SHELL.test(proc.args.trim());
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Every process's cwd; throws when it cannot list them, so busy repositories are never mistaken for idle ones. */
|
|
25
|
+
export function processes(): Proc[] {
|
|
26
|
+
const list = (command: string, args: string[]) => {
|
|
27
|
+
const result = spawnSync(command, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
28
|
+
// lsof exits 1 when some processes are unreadable but still lists the rest; completeness is checked below.
|
|
29
|
+
if (result.error || !result.stdout || (result.status !== 0 && !(command === "lsof" && result.status === 1))) {
|
|
30
|
+
throw new Error(`cannot list processes with ${command} (${result.error?.message ?? `exit ${result.status}`}); ${UNLISTED}`);
|
|
31
|
+
}
|
|
32
|
+
return result.stdout;
|
|
33
|
+
};
|
|
34
|
+
const table = list("ps", ["-axo", "pid=,ppid=,pgid=,uid=,stat=,comm="]);
|
|
35
|
+
// -ww: never truncate command lines, which busy detection reads for path arguments and installs.
|
|
36
|
+
const args = list("ps", ["-ww", "-axo", "pid=,args="]);
|
|
37
|
+
const cwds = list("lsof", ["-nP", "-d", "cwd", "-Fpn"]);
|
|
38
|
+
return parseProcesses(table, args, cwds, process.getuid?.() ?? -1, pid => {
|
|
39
|
+
try {
|
|
40
|
+
process.kill(pid, 0);
|
|
41
|
+
return true;
|
|
42
|
+
} catch {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const UNLISTED = "without every process's working directory busy repositories cannot be detected, so pass --include-busy only if none is in use";
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Joins `ps` and `lsof` output. Throws when lsof lists no working directory
|
|
52
|
+
* for a live process of this user, so partial visibility never passes for
|
|
53
|
+
* idle. A working directory lsof lists as unreadable (Linux's non-dumpable
|
|
54
|
+
* processes, such as `(sd-pam)` or an `sshd` session) is marked `unreadable`,
|
|
55
|
+
* and busyRoots attributes that process by its absolute path arguments.
|
|
56
|
+
* Other users' processes (root daemons) are listed when lsof can read them.
|
|
57
|
+
*/
|
|
58
|
+
export function parseProcesses(table: string, argsOutput: string, lsofOutput: string, uid: number, alive: (pid: number) => boolean): Proc[] {
|
|
59
|
+
const rows = parseTable(table);
|
|
60
|
+
const args = parseArgs(argsOutput);
|
|
61
|
+
const { cwds, unreadable } = parseCwds(lsofOutput);
|
|
62
|
+
// A process that exited between ps and lsof has nothing left to protect.
|
|
63
|
+
const unseen = rows.filter(row => row.uid === uid && !row.zombie && !cwds.has(row.pid) && !unreadable.has(row.pid) && alive(row.pid));
|
|
64
|
+
if (unseen.length > 0) {
|
|
65
|
+
throw new Error(
|
|
66
|
+
`cannot read the working directory of ${unseen
|
|
67
|
+
.slice(0, 3)
|
|
68
|
+
.map(row => `${row.name} ${row.pid}`)
|
|
69
|
+
.join(", ")}${unseen.length > 3 ? ", ..." : ""}; ${UNLISTED}`,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
return rows
|
|
73
|
+
.filter(row => !row.zombie)
|
|
74
|
+
.map(({ pid, ppid, pgid, name }) => ({ pid, ppid, pgid, name, args: args.get(pid) ?? "", cwd: cwds.get(pid), ...(unreadable.has(pid) ? { unreadable: true as const } : {}) }));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface Row {
|
|
78
|
+
pid: number;
|
|
79
|
+
ppid: number;
|
|
80
|
+
pgid: number;
|
|
81
|
+
uid: number;
|
|
82
|
+
zombie: boolean;
|
|
83
|
+
name: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Rows of `ps -axo pid=,ppid=,pgid=,uid=,stat=,comm=`. */
|
|
87
|
+
function parseTable(table: string): Row[] {
|
|
88
|
+
const rows: Row[] = [];
|
|
89
|
+
for (const line of table.split("\n")) {
|
|
90
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
|
|
91
|
+
if (match)
|
|
92
|
+
rows.push({
|
|
93
|
+
pid: Number(match[1]),
|
|
94
|
+
ppid: Number(match[2]),
|
|
95
|
+
pgid: Number(match[3]),
|
|
96
|
+
uid: Number(match[4]),
|
|
97
|
+
zombie: match[5]!.startsWith("Z"),
|
|
98
|
+
name: path.basename(match[6]!.trim()),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return rows;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Command lines by pid from `ps -axo pid=,args=`. */
|
|
105
|
+
function parseArgs(argsOutput: string): Map<number, string> {
|
|
106
|
+
const args = new Map<number, string>();
|
|
107
|
+
for (const line of argsOutput.split("\n")) {
|
|
108
|
+
const match = /^\s*(\d+)\s+(.*)$/.exec(line);
|
|
109
|
+
if (match) args.set(Number(match[1]), match[2]!);
|
|
110
|
+
}
|
|
111
|
+
return args;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Working directories by pid from `lsof -d cwd -Fpn`. */
|
|
115
|
+
function parseCwds(lsofOutput: string): { cwds: Map<number, string>; unreadable: Set<number> } {
|
|
116
|
+
const cwds = new Map<number, string>();
|
|
117
|
+
const unreadable = new Set<number>();
|
|
118
|
+
let current = 0;
|
|
119
|
+
for (const line of lsofOutput.split("\n")) {
|
|
120
|
+
if (line.startsWith("p")) current = Number(line.slice(1));
|
|
121
|
+
else if (!line.startsWith("n") || !current) continue;
|
|
122
|
+
// Linux's lsof names an unreadable cwd `/proc/<pid>/cwd (readlink: Permission denied)`: that is no directory.
|
|
123
|
+
else if (/ \((?:readlink|stat): /.test(line)) unreadable.add(current);
|
|
124
|
+
else cwds.set(current, line.slice(1));
|
|
125
|
+
}
|
|
126
|
+
return { cwds, unreadable };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Absolute paths that a command line's path-like arguments (`a/b`, `--flag=./x`, `-C ../dir`) resolve to;
|
|
131
|
+
* without a working directory, only the absolute ones.
|
|
132
|
+
*/
|
|
133
|
+
function argumentPaths(args: string, cwd: string | undefined): string[] {
|
|
134
|
+
const paths: string[] = [];
|
|
135
|
+
for (const token of args.split(/\s+/).slice(1)) {
|
|
136
|
+
const value = token.startsWith("-") && token.includes("=") ? token.slice(token.indexOf("=") + 1) : token;
|
|
137
|
+
if (value === "" || value.startsWith("-")) continue;
|
|
138
|
+
if (cwd === undefined ? path.isAbsolute(value) : value.includes("/") || value === "." || value === "..") paths.push(path.resolve(cwd ?? "/", value));
|
|
139
|
+
}
|
|
140
|
+
return paths;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** This process and its ancestors: the agent, shell, or launcher (`bunx`, `bun run`) that ran it. */
|
|
144
|
+
export function selfAndAncestors(procs: Proc[], self = process.pid): Set<number> {
|
|
145
|
+
const parent = new Map(procs.map(proc => [proc.pid, proc.ppid]));
|
|
146
|
+
const ancestors = new Set<number>();
|
|
147
|
+
for (let pid: number | undefined = self; pid && !ancestors.has(pid); pid = parent.get(pid)) ancestors.add(pid);
|
|
148
|
+
return ancestors;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Processes working in each root, other than this process, its ancestors (the
|
|
153
|
+
* agent or shell that ran it), its children, idle shells, and text filters
|
|
154
|
+
* in its process group (`| head`, `| jq`: the rest of the caller's pipeline).
|
|
155
|
+
* A process counts for the root holding its cwd and for every root a path in
|
|
156
|
+
* its arguments points into.
|
|
157
|
+
* A build or server in the same group still counts: non-interactive shells
|
|
158
|
+
* put background jobs there too. A process in a
|
|
159
|
+
* nested root counts only for the deepest root containing it.
|
|
160
|
+
*/
|
|
161
|
+
export function busyRoots(procs: Proc[], roots: string[], self = process.pid): Map<string, Proc[]> {
|
|
162
|
+
const ancestors = selfAndAncestors(procs, self);
|
|
163
|
+
const group = procs.find(proc => proc.pid === self)?.pgid;
|
|
164
|
+
const busy = new Map<string, Proc[]>();
|
|
165
|
+
const byDepth = roots.toSorted((a, b) => b.length - a.length);
|
|
166
|
+
for (const proc of procs) {
|
|
167
|
+
const pipeline = group !== undefined && proc.pgid === group && PIPELINE_FILTERS.has(proc.name);
|
|
168
|
+
if ((!proc.cwd && !proc.unreadable) || ancestors.has(proc.pid) || proc.ppid === self || pipeline || idleShell(proc)) continue;
|
|
169
|
+
for (const root of touchedRoots(proc.cwd, proc.args, byDepth)) busy.set(root, [...(busy.get(root) ?? []), proc]);
|
|
170
|
+
}
|
|
171
|
+
return busy;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The deepest root holding a process's cwd, when it is known, and the deepest holding each path in its arguments. */
|
|
175
|
+
function touchedRoots(cwd: string | undefined, args: string, byDepth: string[]): Set<string> {
|
|
176
|
+
const deepest = (location: string) => byDepth.find(candidate => location === candidate || location.startsWith(`${candidate}/`));
|
|
177
|
+
const touched = new Set<string>();
|
|
178
|
+
const home = cwd === undefined ? undefined : deepest(cwd);
|
|
179
|
+
if (home) touched.add(home);
|
|
180
|
+
// A process can work in a root it is not in: `cargo build --manifest-path checkouts/app/Cargo.toml`.
|
|
181
|
+
for (const location of argumentPaths(args, cwd)) {
|
|
182
|
+
const root = deepest(location);
|
|
183
|
+
if (root) touched.add(root);
|
|
184
|
+
}
|
|
185
|
+
return touched;
|
|
186
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** The repositories a space cleanup covers. */
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { type Checkout, namedRoot, workspaceAt, workspaceCheckouts } from "../system/checkouts";
|
|
4
|
+
|
|
5
|
+
export type Target = Checkout;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Repositories to clean. From a matrix workspace: the workspace and every
|
|
9
|
+
* checkout, or the named checkouts. From anywhere else: the repository
|
|
10
|
+
* containing the working directory, or the named paths.
|
|
11
|
+
*/
|
|
12
|
+
export function resolveTargets(cwd: string, names: string[]): { workspace?: string; targets: Target[] } {
|
|
13
|
+
const { here, workspace } = workspaceAt(cwd);
|
|
14
|
+
if (names.length === 0) {
|
|
15
|
+
if (workspace) return { workspace, targets: [{ name: path.basename(workspace), root: workspace }, ...workspaceCheckouts(workspace)] };
|
|
16
|
+
if (!here) throw new Error(`${cwd} is not inside a git repository; name one`);
|
|
17
|
+
return { targets: [{ name: path.basename(here), root: here }] };
|
|
18
|
+
}
|
|
19
|
+
const targets = names.map(name => {
|
|
20
|
+
const root = namedRoot(cwd, workspace, name);
|
|
21
|
+
return { name: path.basename(root), root };
|
|
22
|
+
});
|
|
23
|
+
return { workspace, targets: targets.filter((target, index) => targets.findIndex(other => other.root === target.root) === index) };
|
|
24
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The repositories a machine-level command covers: a matrix workspace and the
|
|
3
|
+
* checkouts in its `checkouts/`, or the repository holding a path. Git runs
|
|
4
|
+
* isolated from the caller's environment, so a hook's `GIT_DIR` or an
|
|
5
|
+
* inherited `-c` setting never points it at another repository.
|
|
6
|
+
*/
|
|
7
|
+
import { spawnSync } from "node:child_process";
|
|
8
|
+
import { existsSync, readdirSync, realpathSync } from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
|
|
11
|
+
// From `git rev-parse --local-env-vars`: variables that bind Git to one repository,
|
|
12
|
+
// such as those a hook sets, and that would override `-C`.
|
|
13
|
+
const REPOSITORY_VARIABLES = [
|
|
14
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
15
|
+
"GIT_CONFIG",
|
|
16
|
+
"GIT_CONFIG_PARAMETERS",
|
|
17
|
+
"GIT_CONFIG_COUNT",
|
|
18
|
+
"GIT_OBJECT_DIRECTORY",
|
|
19
|
+
"GIT_DIR",
|
|
20
|
+
"GIT_WORK_TREE",
|
|
21
|
+
"GIT_IMPLICIT_WORK_TREE",
|
|
22
|
+
"GIT_GRAFT_FILE",
|
|
23
|
+
"GIT_INDEX_FILE",
|
|
24
|
+
"GIT_NO_REPLACE_OBJECTS",
|
|
25
|
+
"GIT_REPLACE_REF_BASE",
|
|
26
|
+
"GIT_PREFIX",
|
|
27
|
+
"GIT_SHALLOW_FILE",
|
|
28
|
+
"GIT_COMMON_DIR",
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
/** The environment without variables that bind Git to another repository or configuration, and without prompts. */
|
|
32
|
+
export function isolatedGitEnvironment(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
|
|
33
|
+
// No optional locks: a status here must never make another session's `git add` or commit fail on index.lock.
|
|
34
|
+
const clean: NodeJS.ProcessEnv = { ...env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" };
|
|
35
|
+
for (const name of REPOSITORY_VARIABLES) delete clean[name];
|
|
36
|
+
return clean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Git in `cwd` without hooks, fsmonitor commands, prompts, or inherited
|
|
41
|
+
* repository variables. stdout is untrimmed; `error` is set when Git could not
|
|
42
|
+
* be started.
|
|
43
|
+
*/
|
|
44
|
+
export function isolatedGit(cwd: string, args: string[]): { status: number | null; stdout: string; error?: Error } {
|
|
45
|
+
const result = spawnSync("git", ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", ...args], {
|
|
46
|
+
cwd,
|
|
47
|
+
env: isolatedGitEnvironment(),
|
|
48
|
+
encoding: "utf8",
|
|
49
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
50
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
51
|
+
});
|
|
52
|
+
return { status: result.status, stdout: result.stdout ?? "", ...(result.error ? { error: result.error } : {}) };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The top level of the repository holding `cwd`, undefined outside one. */
|
|
56
|
+
export function toplevel(cwd: string): string | undefined {
|
|
57
|
+
const result = isolatedGit(cwd, ["rev-parse", "--show-toplevel"]);
|
|
58
|
+
const top = result.stdout.trim();
|
|
59
|
+
return result.status === 0 && top ? top : undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A matrix workspace: `matrix.json` beside a `checkouts/` directory. */
|
|
63
|
+
export function isMatrixWorkspace(root: string): boolean {
|
|
64
|
+
return existsSync(path.join(root, "matrix.json")) && existsSync(path.join(root, "checkouts"));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The matrix workspace holding `cwd` at its top level, by real path; undefined elsewhere. */
|
|
68
|
+
export function workspaceAt(cwd: string): { here: string | undefined; workspace: string | undefined } {
|
|
69
|
+
const top = toplevel(cwd);
|
|
70
|
+
// Real paths, so they compare equal to the working directories lsof reports.
|
|
71
|
+
const here = top && realpathSync(top);
|
|
72
|
+
return { here, workspace: here && isMatrixWorkspace(here) ? here : undefined };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface Checkout {
|
|
76
|
+
readonly name: string;
|
|
77
|
+
readonly root: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Every checkout in a workspace's `checkouts/` that is its own Git working
|
|
82
|
+
* tree, by name, with real roots. A directory whose `.git` Git cannot read is
|
|
83
|
+
* left out, since Git would answer for the enclosing workspace instead.
|
|
84
|
+
*/
|
|
85
|
+
export function workspaceCheckouts(workspace: string): Checkout[] {
|
|
86
|
+
return readdirSync(path.join(workspace, "checkouts"), { withFileTypes: true })
|
|
87
|
+
.filter(entry => entry.isDirectory() && existsSync(path.join(workspace, "checkouts", entry.name, ".git")))
|
|
88
|
+
.map(entry => ({ name: entry.name, root: realpathSync(path.join(workspace, "checkouts", entry.name)) }))
|
|
89
|
+
.filter(checkout => {
|
|
90
|
+
const top = toplevel(checkout.root);
|
|
91
|
+
return top !== undefined && realpathSync(top) === checkout.root;
|
|
92
|
+
})
|
|
93
|
+
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The real root a name selects: the workspace checkout it names (owner/name
|
|
98
|
+
* counts by its last part unless it is a path), else the repository holding
|
|
99
|
+
* that path.
|
|
100
|
+
*/
|
|
101
|
+
export function namedRoot(cwd: string, workspace: string | undefined, name: string): string {
|
|
102
|
+
const short = name.includes("/") && !existsSync(path.resolve(cwd, name)) ? name.split("/").pop()! : name;
|
|
103
|
+
if (workspace && existsSync(path.join(workspace, "checkouts", short, ".git"))) {
|
|
104
|
+
const root = realpathSync(path.join(workspace, "checkouts", short));
|
|
105
|
+
const top = toplevel(root);
|
|
106
|
+
// Git would answer for the enclosing workspace instead.
|
|
107
|
+
if (top === undefined || realpathSync(top) !== root) throw new Error(`checkouts/${short} is not a Git repository Git can read`);
|
|
108
|
+
return root;
|
|
109
|
+
}
|
|
110
|
+
const top = existsSync(path.resolve(cwd, name)) ? toplevel(path.resolve(cwd, name)) : undefined;
|
|
111
|
+
if (!top) throw new Error(`${name} is neither a checkout name nor a path inside a git repository`);
|
|
112
|
+
return realpathSync(top);
|
|
113
|
+
}
|