@onsager/awb 0.1.0 → 0.1.2

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 CHANGED
@@ -21,7 +21,7 @@ Agent Workbench is a set of portable skills for Codex and Claude Code that helps
21
21
 
22
22
  2. Start a new Manager session. Use the native subagent tools in your harness to delegate work; setup details and configuration are in the [reference](docs/reference.md).
23
23
 
24
- For manual skill installation, updates, project-local installs, and detailed configuration, see the [reference](docs/reference.md). Setup does not install agent tools or authenticate harnesses.
24
+ For manual skill installation, updates, project-local installs, `awb prune` cleanup, and detailed configuration, see the [reference](docs/reference.md). Setup does not install agent tools or authenticate harnesses.
25
25
 
26
26
  ## Skills
27
27
 
package/bin/awb.mjs CHANGED
@@ -3,8 +3,9 @@ import { spawnSync } from "node:child_process";
3
3
  import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
6
7
 
7
- const commands = ["install", "update", "status", "trust", "uninstall", "workers"];
8
+ const commands = ["install", "update", "status", "trust", "uninstall", "workers", "prune"];
8
9
  const usage = `Usage: awb <command> [options]
9
10
 
10
11
  Commands:
@@ -15,6 +16,7 @@ Commands:
15
16
  trust Review and trust Codex hooks
16
17
  uninstall Remove managed setup
17
18
  workers Show effective Worker configuration
19
+ prune Remove local worktrees and branches with merged PRs
18
20
  help Show this help`;
19
21
 
20
22
  const argv = process.argv.slice(2);
@@ -56,6 +58,10 @@ const run = (executable, parameters) => {
56
58
  };
57
59
  const runWorkbench = (parameters) => run(process.execPath, [script, "--home", home, ...parameters]);
58
60
 
61
+ if (command === "prune") {
62
+ process.exit(run(process.execPath, [fileURLToPath(new URL("./prune.mjs", import.meta.url)), ...args.slice(1)]));
63
+ }
64
+
59
65
  if (command === "setup") {
60
66
  const skillArgs = skillsCmd
61
67
  ? skillsCmd.split(/\s+/).filter(Boolean)
package/bin/prune.mjs ADDED
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ const run = (command, args, cwd) => spawnSync(command, args, { cwd, encoding: "utf8" });
8
+ const git = (repo, ...args) => {
9
+ const result = run("git", args, repo);
10
+ if (result.status !== 0) throw new Error(result.stderr.trim() || `git ${args[0]} failed`);
11
+ return result.stdout.trimEnd();
12
+ };
13
+ const absolute = (value) => path.resolve(value);
14
+
15
+ export function parse(argv) {
16
+ const options = { repo: process.cwd(), apply: false, json: false };
17
+ for (let i = 0; i < argv.length; i += 1) {
18
+ if (argv[i] === "--repo") {
19
+ if (!argv[i + 1]) throw new Error("--repo requires a path");
20
+ options.repo = absolute(argv[++i]);
21
+ } else if (argv[i] === "--apply") options.apply = true;
22
+ else if (argv[i] === "--json") options.json = true;
23
+ else if (argv[i] === "--help" || argv[i] === "-h") options.help = true;
24
+ else throw new Error(`unknown option: ${argv[i]}`);
25
+ }
26
+ return options;
27
+ }
28
+
29
+ function outputError(message) {
30
+ console.error(`awb prune: ${message}`);
31
+ }
32
+
33
+ export function prune({ repo: requestedRepo, apply = false, json = false } = {}) {
34
+ const repo = git(requestedRepo ?? process.cwd(), "rev-parse", "--show-toplevel");
35
+ const common = git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir");
36
+ const primaryRoot = path.dirname(common);
37
+ const currentResult = run("git", ["rev-parse", "--show-toplevel"], process.cwd());
38
+ const current = currentResult.status === 0 ? currentResult.stdout.trim() : (requestedRepo ? repo : "");
39
+ const defaultRef = run("git", ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], repo);
40
+ const defaultBranch = defaultRef.status === 0 ? defaultRef.stdout.trim().split("/").at(-1) : "main";
41
+ const gh = run("gh", ["pr", "list", "--state", "all", "--limit", "1000", "--json", "headRefName,headRefOid,state"], repo);
42
+ if (gh.status !== 0) throw new Error(gh.stderr.trim() || "gh pr list failed");
43
+ const prs = JSON.parse(gh.stdout);
44
+ const worktrees = git(repo, "worktree", "list", "--porcelain").split(/\n\n/).filter(Boolean).map((block) => {
45
+ const entry = {};
46
+ for (const line of block.split("\n")) {
47
+ const at = line.indexOf(" ");
48
+ entry[at < 0 ? line : line.slice(0, at)] = at < 0 ? true : line.slice(at + 1);
49
+ }
50
+ return entry;
51
+ });
52
+ const symlinkRoots = [".claude/skills", ".agents/skills", ".codex/skills"].map((item) => path.join(os.homedir(), item));
53
+ const references = new Set();
54
+ let refsKnown = true;
55
+ try {
56
+ for (const root of symlinkRoots) {
57
+ if (!fs.existsSync(root)) continue;
58
+ if (fs.lstatSync(root).isSymbolicLink()) references.add(realpath(root));
59
+ const visit = (directory) => {
60
+ for (const item of fs.readdirSync(directory, { withFileTypes: true })) {
61
+ const target = path.join(directory, item.name);
62
+ if (item.isSymbolicLink()) references.add(realpath(target));
63
+ else if (item.isDirectory()) visit(target);
64
+ }
65
+ };
66
+ visit(root);
67
+ }
68
+ } catch { refsKnown = false; }
69
+ const processCwds = new Set();
70
+ let processesKnown = true;
71
+ try {
72
+ for (const name of fs.readdirSync("/proc")) {
73
+ if (!/^\d+$/.test(name)) continue;
74
+ try { processCwds.add(fs.realpathSync(`/proc/${name}/cwd`)); }
75
+ // Other users' processes deny cwd reads (EACCES/EPERM); only this user's processes can hold its worktrees.
76
+ catch (error) { if (!["ENOENT", "ESRCH", "EACCES", "EPERM"].includes(error.code)) processesKnown = false; }
77
+ }
78
+ } catch { processesKnown = false; }
79
+ const branches = git(repo, "for-each-ref", "--format=%(refname:short)", "refs/heads").split("\n").filter(Boolean);
80
+ const mergedHeads = new Map();
81
+ const rows = [];
82
+ for (const branch of branches) {
83
+ if ([defaultBranch, "main", "master"].includes(branch)) continue;
84
+ const matches = prs.filter((pr) => pr.headRefName === branch);
85
+ const merged = matches.filter((pr) => pr.state === "MERGED");
86
+ const branchTip = git(repo, "rev-parse", `refs/heads/${branch}`);
87
+ if (!matches.length) {
88
+ // Leftover isolation branches (e.g. Claude's worktree-agent-*) carry no commits beyond the default branch.
89
+ const base = run("git", ["rev-parse", "--verify", `refs/remotes/origin/${defaultBranch}`], repo);
90
+ const hasTree = worktrees.some((tree) => tree.branch === `refs/heads/${branch}`);
91
+ if (base.status === 0 && !hasTree &&
92
+ run("git", ["merge-base", "--is-ancestor", branchTip, base.stdout.trim()], repo).status === 0) {
93
+ mergedHeads.set(branch, base.stdout.trim());
94
+ rows.push({ branch, worktree: "", action: "branch", reason: "no commits beyond origin/" + defaultBranch });
95
+ continue;
96
+ }
97
+ }
98
+ if (!merged.length) {
99
+ const state = matches.some((pr) => pr.state === "OPEN") ? "OPEN PR" : matches.length ? "CLOSED-unmerged PR" : "no PR";
100
+ rows.push({ branch, worktree: "", action: "skip", reason: state });
101
+ continue;
102
+ }
103
+ const qualifying = merged.find((pr) => {
104
+ const ancestor = run("git", ["merge-base", "--is-ancestor", branchTip, pr.headRefOid], repo);
105
+ return branchTip === pr.headRefOid || ancestor.status === 0;
106
+ });
107
+ if (!qualifying) {
108
+ rows.push({ branch, worktree: "", action: "skip", reason: "local commits after merged PR" });
109
+ continue;
110
+ }
111
+ mergedHeads.set(branch, qualifying.headRefOid);
112
+ const associated = worktrees.filter((tree) => tree.branch === `refs/heads/${branch}`);
113
+ if (!associated.length) {
114
+ rows.push({ branch, worktree: "", action: "branch", reason: "merged PR and unchanged tip" });
115
+ continue;
116
+ }
117
+ for (const tree of associated) {
118
+ const directory = tree.worktree;
119
+ let reason = "";
120
+ if (directory === primaryRoot) reason = "primary checkout";
121
+ else if (directory === current) reason = "invoking worktree";
122
+ else if (tree.locked) reason = "locked";
123
+ else if (!processesKnown) reason = "in use unknown";
124
+ else if ([...processCwds].some((cwd) => within(cwd, directory))) reason = "in use";
125
+ else if (!refsKnown) reason = "in use unknown (skill links unchecked)";
126
+ else if ([...references].some((target) => within(target, directory))) reason = "referenced by skill symlink";
127
+ else if (git(directory, "status", "--porcelain").length) reason = "dirty";
128
+ rows.push({ branch, worktree: directory, action: reason ? "skip" : "worktree", reason: reason || "merged PR and unchanged tip" });
129
+ }
130
+ }
131
+ if (apply) {
132
+ for (const row of rows.filter((item) => item.action === "worktree")) {
133
+ if (git(row.worktree, "status", "--porcelain").length) {
134
+ row.action = "skip"; row.reason = "dirty (changed before removal)"; continue;
135
+ }
136
+ const result = run("git", ["worktree", "remove", row.worktree], repo);
137
+ if (result.status !== 0) { row.action = "skip"; row.reason = result.stderr.trim() || "worktree removal failed"; continue; }
138
+ row.action = "removed";
139
+ }
140
+ for (const branch of new Set(rows.filter((row) => row.action === "branch" ||
141
+ (row.action === "removed" && rows.filter((item) => item.branch === row.branch && item.worktree).every((item) => item.action === "removed")))
142
+ .map((row) => row.branch))) {
143
+ const ref = `refs/heads/${branch}`;
144
+ const check = run("git", ["rev-parse", "--verify", ref], repo);
145
+ if (check.status === 0) {
146
+ const tip = check.stdout.trim();
147
+ const mergedHead = mergedHeads.get(branch);
148
+ const ancestor = run("git", ["merge-base", "--is-ancestor", tip, mergedHead], repo);
149
+ if (tip !== mergedHead && ancestor.status !== 0) {
150
+ for (const row of rows.filter((item) => item.branch === branch && ["branch", "removed"].includes(item.action))) {
151
+ row.action = "skip"; row.reason = "local commits added before branch removal";
152
+ }
153
+ continue;
154
+ }
155
+ git(repo, "branch", "-D", branch);
156
+ }
157
+ for (const row of rows.filter((item) => item.branch === branch && ["branch", "removed"].includes(item.action))) row.action = "removed";
158
+ }
159
+ git(repo, "worktree", "prune");
160
+ }
161
+ if (json) console.log(JSON.stringify(rows, null, 2));
162
+ else {
163
+ console.log(`${apply ? "Applied" : "Dry run"} (use --apply to remove eligible items)`);
164
+ for (const row of rows) console.log(`${row.action.padEnd(8)} ${row.branch}${row.worktree ? ` ${row.worktree}` : ""} ${row.reason}`);
165
+ }
166
+ return rows;
167
+ }
168
+
169
+ function within(child, parent) {
170
+ return child === parent || child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep);
171
+ }
172
+ function realpath(target) {
173
+ try { return fs.realpathSync(target); } catch { return path.resolve(target); }
174
+ }
175
+
176
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(new URL(import.meta.url).pathname)) {
177
+ try {
178
+ const args = parse(process.argv.slice(2));
179
+ if (args.help) console.log("Usage: awb prune [--repo PATH] [--apply] [--json]");
180
+ else prune(args);
181
+ } catch (error) { outputError(error.message); process.exitCode = 1; }
182
+ }
package/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "@onsager/awb",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/onsager-ai/agent-workbench.git"
8
+ },
5
9
  "type": "module",
6
10
  "bin": {
7
11
  "awb": "bin/awb.mjs"
@@ -10,7 +14,8 @@
10
14
  "node": ">=22.20"
11
15
  },
12
16
  "files": [
13
- "bin/awb.mjs"
17
+ "bin/awb.mjs",
18
+ "bin/prune.mjs"
14
19
  ],
15
20
  "publishConfig": {
16
21
  "access": "public"