@a2f0/agent-tool 0.1.30 → 0.1.31

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.30",
3
+ "version": "0.1.31",
4
4
  "packageManager": "bun@1.4.3",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
@@ -33,4 +33,5 @@ open PRs and requires the branch to be pushed at its local HEAD. It does not
33
33
  push for you. Resolve a fork's head/base identities explicitly if the repository
34
34
  uses fork PRs; the initial open helper supports same-repository branches.
35
35
 
36
- Report the created PR link and any remaining validation or review work.
36
+ Report the created PR link and any remaining validation or review work. Run
37
+ `agent-tool teardown` first, stop what the work started, and report what remains.
@@ -39,6 +39,8 @@ switch, and update by fast-forward only. Never discard or automatically stash
39
39
  edits, force a diverged default branch, or infer shipping from Git ancestry after
40
40
  a squash merge.
41
41
 
42
+ Run `agent-tool teardown` and stop what the finished work left running
43
+ (`teardown --apply` for recorded processes); report anything that remains.
42
44
  Run the repository's documented dependency/hook setup if required. When copied
43
45
  hooks are configured, use `agent-tool hooks check` and `hooks install --apply`;
44
46
  inspect unmanaged hooks before an explicit `--adopt`, which backs them up.
@@ -23,6 +23,9 @@ machine-readable receipts and review findings visible by running `versions
23
23
  prepare`, `review`, and other commands whose output drives a decision directly.
24
24
  Prefer documented compact test reporters when they preserve required evidence;
25
25
  do not reduce test scope, skip checks, silence warnings, or mask failures.
26
+ Start servers, watchers, and other long-running processes with
27
+ `agent-tool proc start --label <name> -- <command>`, never a backgrounded shell
28
+ command, so they can be found and stopped.
26
29
 
27
30
  1. Finish the requested change on a feature branch. Use
28
31
  `agent-tool branch create <branch> --base <base-branch> --remote <remote>`
@@ -73,8 +76,15 @@ do not reduce test scope, skip checks, silence warnings, or mask failures.
73
76
  live checks. Report deployment failures
74
77
  separately from a successful merge; follow project policy for repairs.
75
78
 
79
+ Before the final report, run `agent-tool teardown` in each repository this work
80
+ touched. Stop what the work started (`teardown --apply`, `proc stop`), stop any
81
+ untracked process it started, and remove worktrees it added. Report what
82
+ remains and why; the work is not done while teardown fails for anything it
83
+ started.
84
+
76
85
  Never infer a clean review from process success alone or carry a review across
77
86
  content changes. Do not weaken configured CI policy to get a merge through.
78
87
  If a step fails, preserve useful intermediate work and report the concrete
79
88
  remaining issue. Report PR link, merged commit, review verdict, validation, final
80
- checkout state, and whether the shipped local branch was pruned or preserved.
89
+ checkout state, the teardown result, and whether the shipped local branch was
90
+ pruned or preserved.
package/src/cli.ts CHANGED
@@ -27,6 +27,7 @@ import { hooksCommand } from "./workflows/hooks";
27
27
  import { repoCommand, policyCommand, toolchainCommand } from "./workflows/repository";
28
28
  import { prWorkflowCommand } from "./workflows/pr";
29
29
  import { releaseCommand } from "./release/commands";
30
+ import { procCommand, teardownCommand } from "./processes/commands";
30
31
 
31
32
  export const HELP = `agent-tool ${metadata.version}
32
33
 
@@ -34,6 +35,9 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
34
35
 
35
36
  run [--label text] [--max-bytes N] [--tail-lines N] -- <command> [args...]
36
37
  run-group <plan.json> Sequential checks with durable source-bound receipts
38
+ proc start [--label text] [--keep] -- <command> [args...] Recorded long-running process
39
+ proc list | stop <id...>|--all [--grace-ms N]
40
+ teardown [--apply] What this checkout still runs; --apply stops recorded processes
37
41
  runs list [--head oid] [--branch name] [--since ISO-date]
38
42
  branch check [name...|--pre-push] | status
39
43
  branch create <name> [--base branch] [--remote origin]
@@ -111,6 +115,8 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
111
115
  if (command === "run") return runCommand(args);
112
116
  if (command === "ci") { usage(args.shift() === "gate", "Usage: ci gate <needs.json|-> [--policy policy.json]"); return gateCommand(args); }
113
117
  if (command === "release") return releaseCommand(args);
118
+ if (command === "proc") return procCommand(args);
119
+ if (command === "teardown") return teardownCommand(args);
114
120
  if (command === "logs") return inspectLog(args);
115
121
  if (command === "dependencies" && args[0] === "diff") {
116
122
  usage(args.length === 3 && args[1] === "--base" && !!args[2] && !args[2].startsWith("-"), "Usage: agent-tool dependencies diff --base <ref>");
@@ -6,7 +6,7 @@ import { createLog } from "./logFile";
6
6
 
7
7
  const FORWARDED_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"] as const;
8
8
 
9
- export interface RunReceipt { status: string; label?: string; exitCode: number; signal: string | null; durationMs: number; outputBytes: number; log: string }
9
+ export interface RunReceipt { status: string; label?: string; exitCode: number; signal: string | null; durationMs: number; outputBytes: number; log: string; leftoverProcessGroup?: number }
10
10
 
11
11
  /** Run directly into a private file: child output never accumulates in memory. */
12
12
  export async function runCommand(args: string[], record?: (receipt: RunReceipt) => void, options: { quiet?: boolean; reraiseChildSignal?: boolean } = {}): Promise<number> {
@@ -79,9 +79,18 @@ export async function runCommand(args: string[], record?: (receipt: RunReceipt)
79
79
  forward("SIGKILL");
80
80
  }
81
81
  const exitCode = signal ? 128 + (constants.signals[signal] ?? 0) : status ?? 1;
82
- const receipt: RunReceipt = { status: exitCode === 0 ? "passed" : "failed", ...(label ? { label } : {}), exitCode, signal, durationMs: Math.round(performance.now() - started), outputBytes: fstatSync(fd).size, log };
82
+ // A finite command that left processes behind in its group, such as `server &`, is reported:
83
+ // nothing else would notice them before the work is called done.
84
+ let leftover: number | undefined;
85
+ if (grouped && !interrupted && child.pid) {
86
+ // EPERM still means the group exists, now holding a process this user cannot signal.
87
+ try { process.kill(-child.pid, 0); leftover = child.pid; }
88
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "EPERM") leftover = child.pid; }
89
+ }
90
+ const receipt: RunReceipt = { status: exitCode === 0 ? "passed" : "failed", ...(label ? { label } : {}), exitCode, signal, durationMs: Math.round(performance.now() - started), outputBytes: fstatSync(fd).size, log, ...(leftover ? { leftoverProcessGroup: leftover } : {}) };
83
91
  record?.(receipt);
84
92
  if (!options.quiet) writeSync(1, `${JSON.stringify(receipt)}\n`);
93
+ if (leftover) writeSync(2, `Processes this command started are still running in its process group ${leftover} (\`kill -TERM -${leftover}\`). Stop them, or start long-running processes with \`agent-tool proc start\`.\n`);
85
94
  if (exitCode !== 0) printLogTail(log, limits, 2);
86
95
  } finally {
87
96
  if (timer) clearTimeout(timer);
@@ -19,12 +19,13 @@ export type Decision = "allow" | "ask";
19
19
  export interface CatalogEntry { command: string; class: PermissionClass; applyClass?: PermissionClass }
20
20
 
21
21
  export const CATALOG: CatalogEntry[] = [
22
- ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "images list", "graph check", "permissions show", "permissions check"]
22
+ ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "images list", "graph check", "permissions show", "permissions check", "proc list"]
23
23
  .map(command => ({ command, class: "read" as const })),
24
- ...["bun install", "bun update", "bun remove", "bun test", "branch create", "versions bump", "versions prepare", "versions resolve-conflicts", "images build", "review", "init"]
24
+ ...["bun install", "bun update", "bun remove", "bun test", "branch create", "versions bump", "versions prepare", "versions resolve-conflicts", "images build", "review", "init", "proc stop"]
25
25
  .map(command => ({ command, class: "local" as const })),
26
26
  { command: "skills install", class: "read", applyClass: "local" },
27
27
  { command: "hooks install", class: "read", applyClass: "local" },
28
+ { command: "teardown", class: "read", applyClass: "local" },
28
29
  { command: "permissions install", class: "read", applyClass: "policy" },
29
30
  ...["branch push", "pr open", "pr threads reply", "pr threads resolve"].map(command => ({ command, class: "share" as const })),
30
31
  { command: "pr merge", class: "release" },
@@ -36,7 +37,7 @@ export const CATALOG: CatalogEntry[] = [
36
37
  { command: "openPr", class: "share" },
37
38
  { command: "squashMerge", class: "release" },
38
39
  ];
39
- // `run` and `run-group` execute arbitrary commands, so they stay unclassified and keep the harness default.
40
+ // `run`, `run-group` and `proc start` execute arbitrary commands, so they stay unclassified and keep the harness default.
40
41
  // `bun x` runs only executables that `permissions.executables` classifies; project.ts adds those.
41
42
  // Package scripts are not classified, so `bun run` keeps the harness default.
42
43
 
@@ -0,0 +1,283 @@
1
+ // `proc start|list|stop` and `teardown`: long-running processes started through agent-tool are
2
+ // recorded so they can be found and stopped, and teardown reports everything a piece of work
3
+ // may have left running in the repository before an agent says it is done.
4
+ import { spawn } from "node:child_process";
5
+ import { closeSync, realpathSync } from "node:fs";
6
+ import { constants } from "node:os";
7
+ import path from "node:path";
8
+ import { createLog } from "../commands/logFile";
9
+ import { plainText } from "../commands/output";
10
+ import { assert, git, output } from "../workflows/core";
11
+ import { claimedBy, ledgerDirectory, membersOf, newId, observe, readRecords, removeRecord, saveRecord, type ProcessRecord, type ProcessState } from "./ledger";
12
+ import { ancestors, carrying, listeningPorts, processTable, startOf, workingDirectories, type ProcessRow } from "./table";
13
+
14
+ const STOP_GRACE_MS = 5000;
15
+ const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
16
+ // A bound on another wait that does not itself keep the process alive once that wait is over.
17
+ const bound = (ms: number) => new Promise<undefined>(resolve => { (setTimeout(resolve, ms) as unknown as NodeJS.Timeout).unref(); });
18
+
19
+ function within(root: string, candidate: string): boolean {
20
+ const relative = path.relative(root, candidate);
21
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
22
+ }
23
+
24
+ function signal(pid: number, value: NodeJS.Signals, group: boolean): void {
25
+ try { process.kill(group ? -pid : pid, value); }
26
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
27
+ }
28
+
29
+ interface Described { id: string; label: string | null; state: ProcessState; keep: boolean; pid: number; command: string[]; cwd: string; log: string; startedAt: string; members: { pid: number; command: string }[]; ports: string[] }
30
+
31
+ // Read-only: `proc list` and report-only `teardown` never write records.
32
+ function describe(record: ProcessRecord, table: Map<number, ProcessRow>, ports: Map<number, string[]>, others: ProcessRecord[]): Described {
33
+ const { state, members } = membersOf(record, table, others);
34
+ return {
35
+ id: record.id, label: record.label, state, keep: record.keep, pid: record.pid, command: record.command, cwd: record.cwd, log: record.log, startedAt: record.startedAt,
36
+ members: members.map(row => ({ pid: row.pid, command: row.command })),
37
+ ports: [...new Set(members.flatMap(row => ports.get(row.pid) ?? []))].sort(),
38
+ };
39
+ }
40
+
41
+ const alive = (state: ProcessState) => state === "running" || state === "orphaned";
42
+
43
+ /**
44
+ * Stops one record's processes: SIGTERM to its group and to members outside it, then SIGKILL
45
+ * after the grace period. Every member seen is remembered with its start time, so a descendant
46
+ * that left the group and outlived its parent is still signalled, and only while it is the same
47
+ * process; the group is signalled only while its leader, or a member of it, is ours.
48
+ */
49
+ async function stopRecord(directory: string, record: ProcessRecord, grace = STOP_GRACE_MS): Promise<{ id: string; stopped: boolean; remaining: number[] }> {
50
+ const known = new Map<number, string>();
51
+ const look = () => {
52
+ const table = processTable(), others = readRecords(directory).records, { state, members } = membersOf(record, table, others);
53
+ observe(directory, record, state, members);
54
+ for (const member of members) known.set(member.pid, member.started);
55
+ const claimed = claimedBy(record, table, others);
56
+ const live = [...known].filter(([pid, started]) => table.get(pid)?.started === started && !claimed.has(pid)).map(([pid]) => table.get(pid)!);
57
+ // The group id is ours while our leader runs, or while a member we know still holds it;
58
+ // otherwise it may name someone else's group, and members are signalled one by one.
59
+ return { group: state === "running" || live.some(member => member.pgid === record.pid), live };
60
+ };
61
+ const send = (value: NodeJS.Signals) => {
62
+ const { group, live } = look();
63
+ if (group) signal(record.pid, value, true);
64
+ for (const member of live) if (!group || member.pgid !== record.pid) signal(member.pid, value, false);
65
+ };
66
+ const running = () => { const { group, live } = look(); return group || live.length > 0; };
67
+ send("SIGTERM");
68
+ const deadline = performance.now() + grace;
69
+ while (performance.now() < deadline && running()) await sleep(50);
70
+ send("SIGKILL");
71
+ for (let tries = 0; tries < 20 && running(); tries += 1) await sleep(50);
72
+ const { group, live } = look();
73
+ const stopped = !group && live.length === 0;
74
+ // observe() may have rewritten the record while stopping; remove it only after the last look.
75
+ if (stopped) removeRecord(directory, record.id);
76
+ return { id: record.id, stopped, remaining: stopped ? [] : live.map(row => row.pid) };
77
+ }
78
+
79
+ /**
80
+ * The members of a launcher's group that are provably its own once the launcher has exited and
81
+ * the group id could name another group: those carrying the record's id, or started while the
82
+ * launcher ran, to the second `ps` reports with a second's margin either side.
83
+ */
84
+ export function adoptable(candidates: ProcessRow[], tagged: Set<number>, spawnedAt: number, exitedAt: number): ProcessRow[] {
85
+ const from = Math.floor(spawnedAt / 1000) * 1000 - 1000, until = exitedAt + 1000;
86
+ return candidates.filter(row => {
87
+ const at = Date.parse(`${row.started} UTC`);
88
+ return tagged.has(row.pid) || (at >= from && at <= until);
89
+ });
90
+ }
91
+
92
+ async function start(args: string[]): Promise<number> {
93
+ let label: string | null = null, keep = false;
94
+ while (args.length && args[0] !== "--") {
95
+ const flag = args.shift();
96
+ if (flag === "--label") {
97
+ const value = args.shift();
98
+ assert(value && value.length <= 120, "--label requires 1 to 120 characters.");
99
+ label = plainText(value);
100
+ } else if (flag === "--keep") keep = true;
101
+ else throw new Error(`Unknown proc start argument '${flag}'.`);
102
+ }
103
+ assert(args.shift() === "--" && args[0], "Usage: agent-tool proc start [--label text] [--keep] -- <command> [args...]");
104
+ const directory = ledgerDirectory();
105
+ // Without a working ps nothing started could be identified, recorded or stopped later.
106
+ try { processTable(); }
107
+ catch (error) { throw new Error(`Cannot inspect processes with ps, so nothing was started: ${(error as Error).message}`); }
108
+ const id = newId(), { log, fd } = createLog("agent-tool-proc-");
109
+ let record: ProcessRecord | undefined;
110
+ try {
111
+ // Its own process group, so stopping it reaches everything it starts that stays in the group.
112
+ const spawnedAt = Date.now();
113
+ let exitedAt: number | undefined;
114
+ const child = spawn(args[0]!, args.slice(1), { cwd: process.cwd(), detached: true, stdio: ["ignore", fd, fd], env: { ...process.env, AGENT_TOOL_PROCESS: id } });
115
+ const exited = new Promise<{ code: number | null; signal?: NodeJS.Signals | null; error?: string }>(resolve => {
116
+ child.once("error", error => resolve({ code: (error as NodeJS.ErrnoException).code === "ENOENT" ? 127 : 126, error: error.message }));
117
+ child.once("exit", (code, signal) => { exitedAt = Date.now(); resolve({ code, signal }); });
118
+ });
119
+ if (child.pid) {
120
+ const started = startOf(child.pid);
121
+ if (started) {
122
+ record = { schemaVersion: 1, id, label, pid: child.pid, started, command: [...args], cwd: process.cwd(), log, startedAt: new Date().toISOString(), keep };
123
+ try { saveRecord(directory, record); }
124
+ catch (error) {
125
+ // An unrecorded process could never be found and stopped by teardown.
126
+ signal(child.pid, "SIGKILL", true);
127
+ await Promise.race([exited, bound(2000)]);
128
+ throw new Error(`Could not record the process, so it was stopped: ${(error as Error).message}`);
129
+ }
130
+ } else if (!(await Promise.race([exited, bound(300)]))) {
131
+ // Running, but its identity could not be read, so it could never be stopped safely later.
132
+ signal(child.pid, "SIGKILL", true);
133
+ await Promise.race([exited, bound(2000)]);
134
+ throw new Error("Could not read the started process's identity with ps; stopped it. Nothing was recorded.");
135
+ }
136
+ }
137
+ // A command that fails at once is reported here rather than found later.
138
+ const early = await Promise.race([exited, bound(300)]);
139
+ child.unref();
140
+ if (child.pid) {
141
+ const table = processTable();
142
+ if (table.get(child.pid)?.started === record?.started && record) {
143
+ const { state, members } = membersOf(record, table, readRecords(directory).records);
144
+ observe(directory, record, state, members);
145
+ } else if (!table.has(child.pid)) {
146
+ // The launcher exited, perhaps before its identity could be read, and its group id may
147
+ // already name another group. A member is ours when it carries this record's id, or
148
+ // started while the launcher ran (to the second `ps` reports, with a second's margin).
149
+ const candidates = [...table.values()].filter(row => row.pgid === child.pid);
150
+ const survivors = adoptable(candidates, carrying(candidates.map(row => row.pid), "AGENT_TOOL_PROCESS", id), spawnedAt, exitedAt ?? Date.now());
151
+ if (survivors.length) {
152
+ record ??= { schemaVersion: 1, id, label, pid: child.pid, started: "", command: [...args], cwd: process.cwd(), log, startedAt: new Date().toISOString(), keep };
153
+ record.members = survivors.map(row => ({ pid: row.pid, started: row.started }));
154
+ try { saveRecord(directory, record); }
155
+ catch (error) {
156
+ for (const row of survivors) signal(row.pid, "SIGKILL", false);
157
+ throw new Error(`Could not record the processes the command left running, so they were stopped: ${(error as Error).message}`);
158
+ }
159
+ }
160
+ }
161
+ }
162
+ const receipt = { id, ...(label ? { label } : {}), pid: child.pid ?? null, keep, log, ...(early ? { exited: early.code, ...(early.signal ? { signal: early.signal } : {}), ...(early.error ? { error: early.error } : {}) } : {}) };
163
+ if (early && record && !alive(membersOf(record, processTable()).state)) removeRecord(directory, id);
164
+ output(receipt);
165
+ if (early?.signal) return 128 + (constants.signals[early.signal] ?? 0);
166
+ return early && early.code !== 0 ? (early.code ?? 1) : 0;
167
+ } finally { closeSync(fd); }
168
+ }
169
+
170
+ function parseStopTargets(args: string[]): { all: boolean; ids: string[]; grace: number } {
171
+ let all = false, grace = STOP_GRACE_MS;
172
+ const ids: string[] = [];
173
+ while (args.length) {
174
+ const value = args.shift()!;
175
+ if (value === "--all") all = true;
176
+ else if (value === "--grace-ms") {
177
+ grace = Number(args.shift());
178
+ assert(Number.isInteger(grace) && grace >= 0 && grace <= 60_000, "--grace-ms requires 0 to 60000.");
179
+ } else { assert(/^[a-f0-9]{8}$/.test(value), `Unknown process id '${value}'.`); ids.push(value); }
180
+ }
181
+ assert(all !== ids.length > 0, "Usage: agent-tool proc stop <id...>|--all [--grace-ms N]");
182
+ return { all, ids, grace };
183
+ }
184
+
185
+ export async function procCommand(args: string[]): Promise<number> {
186
+ const action = args.shift();
187
+ if (action === "start") return start(args);
188
+ const directory = ledgerDirectory();
189
+ if (action === "list") {
190
+ assert(args.length === 0, "Usage: agent-tool proc list");
191
+ const { records, skipped } = readRecords(directory), table = processTable(), { ports } = listeningPorts();
192
+ output({ processes: records.map(record => describe(record, table, ports, records)), skipped });
193
+ return 0;
194
+ }
195
+ assert(action === "stop", "Usage: agent-tool proc <start|list|stop>");
196
+ const { all, ids, grace } = parseStopTargets(args);
197
+ const { records, skipped } = readRecords(directory);
198
+ for (const id of ids) assert(records.some(record => record.id === id), `No recorded process '${id}'.`);
199
+ const results = [];
200
+ for (const record of records.filter(record => all || ids.includes(record.id))) results.push(await stopRecord(directory, record, grace));
201
+ output({ stopped: results, skipped });
202
+ // An unreadable record may name processes --all could not stop.
203
+ return results.every(result => result.stopped) && (!all || skipped.length === 0) ? 0 : 1;
204
+ }
205
+
206
+ export interface TeardownReport {
207
+ ok: boolean;
208
+ applied: boolean;
209
+ root: string;
210
+ /** Recorded processes still running: they fail teardown unless started with --keep. */
211
+ leftover: Described[];
212
+ kept: Described[];
213
+ /** Records whose processes have ended; --apply removes them. */
214
+ finished: { id: string; label: string | null; state: ProcessState }[];
215
+ stopped: { id: string; stopped: boolean; remaining: number[] }[];
216
+ /** Processes started some other way whose working directory is in the repository. Listeners fail teardown. */
217
+ untracked: { pid: number; command: string; cwd: string; ports: string[] }[];
218
+ worktrees: { path: string; branch: string | null }[];
219
+ unavailable: string[];
220
+ skipped: { file: string; reason: string }[];
221
+ }
222
+
223
+ function survey(root: string, directory: string): Omit<TeardownReport, "ok" | "applied" | "stopped"> {
224
+ const table = processTable(), { records, skipped } = readRecords(directory);
225
+ const listening = listeningPorts(), cwd = workingDirectories(table.keys());
226
+ const described = records.map(record => describe(record, table, listening.ports, records));
227
+ const owned = new Set(described.flatMap(item => alive(item.state) ? item.members.map(member => member.pid) : []));
228
+ const excluded = ancestors(table);
229
+ const untracked = [...cwd.cwd].flatMap(([pid, directoryOf]) => {
230
+ const row = table.get(pid);
231
+ if (!row || excluded.has(pid) || owned.has(pid) || !within(root, directoryOf)) return [];
232
+ // Processes this command started to look (ps, lsof) are its children.
233
+ if (row.ppid === process.pid) return [];
234
+ const ports = listening.ports.get(pid) ?? [];
235
+ // A pipeline's other commands (`agent-tool teardown | jq`) share its shell and group; one that
236
+ // listens is still reported, since a server backgrounded from the same shell looks alike.
237
+ const self = table.get(process.pid);
238
+ if (self && row.pgid === self.pgid && row.ppid === self.ppid && ports.length === 0) return [];
239
+ return [{ pid, command: row.command, cwd: directoryOf, ports }];
240
+ }).sort((a, b) => a.pid - b.pid);
241
+ const worktrees: { path: string; branch: string | null }[] = [];
242
+ let current: { path: string; branch: string | null } | undefined;
243
+ for (const line of git(["worktree", "list", "--porcelain"]).split("\n")) {
244
+ if (line.startsWith("worktree ")) worktrees.push(current = { path: line.slice(9), branch: null });
245
+ else if (line.startsWith("branch ") && current) current.branch = line.slice(7).replace(/^refs\/heads\//, "");
246
+ }
247
+ return {
248
+ root,
249
+ leftover: described.filter(item => alive(item.state) && !item.keep),
250
+ kept: described.filter(item => alive(item.state) && item.keep),
251
+ finished: described.filter(item => !alive(item.state)).map(item => ({ id: item.id, label: item.label, state: item.state })),
252
+ untracked,
253
+ // The first entry is the main worktree; the rest were added and may need removing.
254
+ worktrees: worktrees.slice(1),
255
+ unavailable: [...(listening.available ? [] : ["listening ports (lsof)"]), ...(cwd.available ? [] : ["working directories (lsof)"])],
256
+ skipped,
257
+ };
258
+ }
259
+
260
+ export async function teardownCommand(args: string[]): Promise<number> {
261
+ let apply = false;
262
+ for (const value of args) {
263
+ assert(value === "--apply" && !apply, "Usage: agent-tool teardown [--apply]");
264
+ apply = true;
265
+ }
266
+ const root = realpathSync(git(["rev-parse", "--show-toplevel"])), directory = ledgerDirectory();
267
+ const stopped: TeardownReport["stopped"] = [];
268
+ if (apply) {
269
+ const { records } = readRecords(directory), table = processTable();
270
+ for (const record of records) {
271
+ const { state, members } = membersOf(record, table, records);
272
+ observe(directory, record, state, members);
273
+ if (!alive(state)) removeRecord(directory, record.id);
274
+ else if (!record.keep) stopped.push(await stopRecord(directory, record));
275
+ }
276
+ }
277
+ const found = survey(root, directory);
278
+ // A clean report needs every inspection: without lsof a listening server would go unseen.
279
+ // Unreadable records may name running processes, so they fail teardown too.
280
+ const ok = found.leftover.length === 0 && found.untracked.every(item => item.ports.length === 0) && found.unavailable.length === 0 && found.skipped.length === 0;
281
+ output({ ok, applied: apply, ...found, stopped } satisfies TeardownReport);
282
+ return ok ? 0 : 1;
283
+ }
@@ -0,0 +1,123 @@
1
+ // Long-running processes agent-tool started for a repository, recorded one file each under the
2
+ // Git common directory, so every worktree and clone-local session sees the same list and it
3
+ // survives branch switches. A record names the process group agent-tool created; whether that
4
+ // group still runs is decided from the live process table, never from the record alone.
5
+ import { randomUUID } from "node:crypto";
6
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { git } from "../workflows/core";
9
+ import { carrying, type ProcessRow } from "./table";
10
+
11
+ export interface ProcessRecord {
12
+ schemaVersion: 1;
13
+ id: string;
14
+ label: string | null;
15
+ /** The group leader agent-tool spawned; its pid is the group id. */
16
+ pid: number;
17
+ /** The leader's start time as `ps` prints it, which tells a reused pid apart. */
18
+ started: string;
19
+ command: string[];
20
+ cwd: string;
21
+ log: string;
22
+ startedAt: string;
23
+ /** Started to outlive the work, such as a dev server the user asked to keep: teardown reports it without failing. */
24
+ keep: boolean;
25
+ /** Members seen while the leader ran, by start time, so they are still known once it has gone. */
26
+ members?: { pid: number; started: string }[];
27
+ }
28
+
29
+ export type ProcessState = "running" | "orphaned" | "exited" | "replaced";
30
+
31
+ export function ledgerDirectory(cwd = process.cwd()): string {
32
+ return path.join(git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd), "agent-tool", "processes");
33
+ }
34
+
35
+ export function newId(): string { return randomUUID().slice(0, 8); }
36
+
37
+ export function saveRecord(directory: string, record: ProcessRecord): void {
38
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
39
+ const file = path.join(directory, `${record.id}.json`), temporary = `${file}.${randomUUID()}.tmp`;
40
+ writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600, flag: "wx" });
41
+ renameSync(temporary, file);
42
+ }
43
+
44
+ export function removeRecord(directory: string, id: string): void { rmSync(path.join(directory, `${id}.json`), { force: true }); }
45
+
46
+ const ID = /^[a-f0-9]{8}$/;
47
+ // Generous enough for any argv the OS accepts plus the member list, which keeps only live members.
48
+ const MAX_RECORD_BYTES = 4 * 1024 * 1024;
49
+ const MAX_MEMBERS = 1000;
50
+
51
+ function valid(value: unknown): value is ProcessRecord {
52
+ const record = value as ProcessRecord;
53
+ return !!record && record.schemaVersion === 1 && typeof record.id === "string" && ID.test(record.id) && Number.isInteger(record.pid) && record.pid > 1
54
+ && typeof record.started === "string" && Array.isArray(record.command) && record.command.every(arg => typeof arg === "string")
55
+ && typeof record.cwd === "string" && typeof record.log === "string" && typeof record.startedAt === "string"
56
+ && (record.label === null || typeof record.label === "string") && typeof record.keep === "boolean"
57
+ && (record.members === undefined || (Array.isArray(record.members) && record.members.every(member => Number.isInteger(member?.pid) && typeof member.started === "string")));
58
+ }
59
+
60
+ /** Every record, and the files that could not be read as one. */
61
+ export function readRecords(directory: string): { records: ProcessRecord[]; skipped: { file: string; reason: string }[] } {
62
+ const records: ProcessRecord[] = [], skipped: { file: string; reason: string }[] = [];
63
+ for (const file of existsSync(directory) ? readdirSync(directory).filter(name => name.endsWith(".json")).sort() : []) {
64
+ try {
65
+ const full = path.join(directory, file), stat = lstatSync(full);
66
+ if (!stat.isFile() || stat.size > MAX_RECORD_BYTES) throw new Error("Not a process record file.");
67
+ const record = JSON.parse(readFileSync(full, "utf8")) as unknown;
68
+ if (!valid(record) || `${record.id}.json` !== file) throw new Error("Invalid process record.");
69
+ records.push(record);
70
+ } catch (error) { skipped.push({ file, reason: (error as Error).message }); }
71
+ }
72
+ return { records, skipped };
73
+ }
74
+
75
+ /**
76
+ * The processes that belong to a record. While its leader runs, that is its group and the live
77
+ * descendants of the group. Once the leader has gone its pid, and so the group id, can be reused,
78
+ * so a leaderless member counts only when it was seen while the leader ran (same pid and start
79
+ * time) or carries the record's AGENT_TOOL_PROCESS id; descendants of counted members count too.
80
+ */
81
+ /** The live leaders of records other than `record`, which own their own process trees. */
82
+ export function claimedBy(record: ProcessRecord, table: Map<number, ProcessRow>, others: ProcessRecord[]): Set<number> {
83
+ return new Set(others.filter(other => other.id !== record.id && table.get(other.pid)?.started === other.started).map(other => other.pid));
84
+ }
85
+
86
+ export function membersOf(record: ProcessRecord, table: Map<number, ProcessRow>, others: ProcessRecord[] = []): { state: ProcessState; members: ProcessRow[] } {
87
+ // Another record's live leader, and everything under it, belongs to that record, even when it
88
+ // was started from inside this one (a nested `proc start --keep`).
89
+ const claimed = claimedBy(record, table, others);
90
+ const leader = table.get(record.pid);
91
+ const ours = !!leader && leader.started === record.started;
92
+ const seen = new Set((record.members ?? []).map(member => `${member.pid} ${member.started}`));
93
+ const known = (row: ProcessRow) => seen.has(`${row.pid} ${row.started}`);
94
+ let group: ProcessRow[] = [];
95
+ // Another process now holding the leader's pid makes the group id unreliable too: only
96
+ // remembered members still count.
97
+ if (ours) group = [...table.values()].filter(row => row.pgid === record.pid);
98
+ else if (!leader) {
99
+ const candidates = [...table.values()].filter(row => row.pgid === record.pid);
100
+ const tagged = carrying(candidates.filter(row => !known(row)).map(row => row.pid), "AGENT_TOOL_PROCESS", record.id);
101
+ group = candidates.filter(row => known(row) || tagged.has(row.pid));
102
+ }
103
+ // Members seen before, wherever they are now: a descendant that left the group keeps its
104
+ // identity after its parent exits and it is no longer anyone's descendant.
105
+ const members = new Map([...group, ...[...table.values()].filter(known)].filter(row => !claimed.has(row.pid)).map(row => [row.pid, row]));
106
+ // Children that left the group (setsid, a new process group) are still reached through their parents.
107
+ for (let grew = true; grew;) {
108
+ grew = false;
109
+ for (const row of table.values()) if (!members.has(row.pid) && !claimed.has(row.pid) && members.has(row.ppid)) { members.set(row.pid, row); grew = true; }
110
+ }
111
+ const list = [...members.values()].sort((a, b) => a.pid - b.pid);
112
+ return { state: ours ? "running" : list.length ? "orphaned" : leader ? "replaced" : "exited", members: list };
113
+ }
114
+
115
+ /** Remembers the live members seen while the leader runs, for when it has gone; dead ones are dropped. */
116
+ export function observe(directory: string, record: ProcessRecord, state: ProcessState, members: ProcessRow[]): void {
117
+ if (state !== "running") return;
118
+ const next = members.slice(0, MAX_MEMBERS).map(row => ({ pid: row.pid, started: row.started }));
119
+ const key = (list: { pid: number; started: string }[]) => list.map(member => `${member.pid} ${member.started}`).sort().join("\n");
120
+ if (key(next) === key(record.members ?? [])) return;
121
+ record.members = next;
122
+ try { saveRecord(directory, record); } catch { /* Best effort: an unrecorded member is only found while the leader runs. */ }
123
+ }
@@ -0,0 +1,111 @@
1
+ // The machine's processes as agent-tool sees them: identity (pid, parent, group and start time),
2
+ // working directory, and listening TCP ports. Read through `ps`, `lsof` and, on Linux, `/proc`,
3
+ // so it needs nothing beyond the operating system.
4
+ import { execFileSync } from "node:child_process";
5
+ import { readFileSync, readlinkSync } from "node:fs";
6
+
7
+ export interface ProcessRow { pid: number; ppid: number; pgid: number; started: string; command: string }
8
+
9
+ // One locale and time zone, so start times read the same in every shell that compares them.
10
+ const C_LOCALE = { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC" };
11
+ // `stat` is one token; `lstart` prints a fixed-width date of five fields, such as `Fri Oct 30 21:43:01 2026`.
12
+ const ROW = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+([A-Z][a-z]{2}\s+[A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s(.*)$/;
13
+
14
+ /**
15
+ * Rows of `ps -o pid=,ppid=,pgid=,stat=,lstart=,command=`. Zombies are left out: they have
16
+ * exited, cannot be signalled, and may never be reaped where PID 1 does not reap orphans.
17
+ */
18
+ export function parseRows(text: string): ProcessRow[] {
19
+ return text.split("\n").flatMap(line => {
20
+ const match = ROW.exec(line);
21
+ if (!match || match[4]!.startsWith("Z")) return [];
22
+ return [{ pid: Number(match[1]), ppid: Number(match[2]), pgid: Number(match[3]), started: match[5]!.replace(/\s+/g, " "), command: match[6]!.trim() }];
23
+ });
24
+ }
25
+
26
+ /** Every live process, by pid. */
27
+ export function processTable(): Map<number, ProcessRow> {
28
+ const text = execFileSync("ps", ["-A", "-o", "pid=,ppid=,pgid=,stat=,lstart=,command="], { encoding: "utf8", env: C_LOCALE, maxBuffer: 64 * 1024 * 1024 });
29
+ return new Map(parseRows(text).map(row => [row.pid, row]));
30
+ }
31
+
32
+ /** When a running process started, as `ps` prints it, or undefined once it has gone. */
33
+ export function startOf(pid: number): string | undefined {
34
+ try {
35
+ const text = execFileSync("ps", ["-o", "stat=,lstart=", "-p", String(pid)], { encoding: "utf8", env: C_LOCALE, stdio: ["ignore", "pipe", "ignore"] }).trim();
36
+ const match = /^(\S+)\s+(.+)$/.exec(text);
37
+ return match && !match[1]!.startsWith("Z") ? match[2]!.replace(/\s+/g, " ") : undefined;
38
+ } catch { return undefined; }
39
+ }
40
+
41
+ /** lsof's output, or undefined when it is missing or failed rather than finding nothing. */
42
+ function lsof(args: string[]): string | undefined {
43
+ try {
44
+ return execFileSync("lsof", args, { encoding: "utf8", env: C_LOCALE, stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 });
45
+ } catch (error) {
46
+ // lsof exits 1 when nothing matches, perhaps with warnings. With another diagnostic, any other status, a
47
+ // missing binary or a signal, the inspection failed and may have missed what it looked for.
48
+ const result = error as { status?: number | null; stdout?: string; stderr?: string };
49
+ const failures = (result.stderr ?? "").split("\n").filter(line => line.trim() && !line.startsWith("lsof: WARNING"));
50
+ return result.status === 1 && failures.length === 0 ? result.stdout ?? "" : undefined;
51
+ }
52
+ }
53
+
54
+ /** Parses `lsof -F pn` output into the names each pid holds. */
55
+ export function parseFields(text: string): Map<number, string[]> {
56
+ const found = new Map<number, string[]>();
57
+ let pid = 0;
58
+ for (const line of text.split("\n")) {
59
+ if (line.startsWith("p")) pid = Number(line.slice(1));
60
+ else if (line.startsWith("n") && pid) found.set(pid, [...found.get(pid) ?? [], line.slice(1)]);
61
+ }
62
+ return found;
63
+ }
64
+
65
+ /** Each process's working directory; `available` is false when neither lsof nor /proc can say. */
66
+ export function workingDirectories(pids: Iterable<number>): { available: boolean; cwd: Map<number, string> } {
67
+ const text = lsof(["-a", "-d", "cwd", "-F", "pn"]);
68
+ if (text !== undefined) return { available: true, cwd: new Map([...parseFields(text)].map(([pid, names]) => [pid, names[0]!])) };
69
+ if (process.platform !== "linux") return { available: false, cwd: new Map() };
70
+ const cwd = new Map<number, string>();
71
+ for (const pid of pids) { try { cwd.set(pid, readlinkSync(`/proc/${pid}/cwd`)); } catch { /* Gone or not ours. */ } }
72
+ return { available: true, cwd };
73
+ }
74
+
75
+ /** The TCP addresses each process listens on; `available` is false without lsof. */
76
+ export function listeningPorts(): { available: boolean; ports: Map<number, string[]> } {
77
+ const text = lsof(["-nP", "-iTCP", "-sTCP:LISTEN", "-F", "pn"]);
78
+ if (text === undefined) return { available: false, ports: new Map() };
79
+ return { available: true, ports: new Map([...parseFields(text)].map(([pid, names]) => [pid, [...new Set(names)]])) };
80
+ }
81
+
82
+ /** This process and every process above it, which teardown never reports or stops. */
83
+ export function ancestors(table: Map<number, ProcessRow>, pid = process.pid): Set<number> {
84
+ const found = new Set<number>();
85
+ for (let current: number | undefined = pid; current && !found.has(current); current = table.get(current)?.ppid) found.add(current);
86
+ return found;
87
+ }
88
+
89
+ /**
90
+ * The processes among `pids` whose environment carries `NAME=value`, as `proc start` sets for
91
+ * everything it launches. macOS hides the environment of protected system binaries, which then
92
+ * never match.
93
+ */
94
+ export function carrying(pids: number[], name: string, value: string): Set<number> {
95
+ const found = new Set<number>(), entry = `${name}=${value}`;
96
+ if (pids.length === 0) return found;
97
+ if (process.platform === "linux") {
98
+ for (const pid of pids) {
99
+ try { if (readFileSync(`/proc/${pid}/environ`, "latin1").split("\0").includes(entry)) found.add(pid); } catch { /* Gone or not ours. */ }
100
+ }
101
+ return found;
102
+ }
103
+ try {
104
+ const text = execFileSync("ps", ["-E", "-ww", "-o", "pid=,command=", "-p", pids.join(",")], { encoding: "utf8", env: C_LOCALE, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 });
105
+ for (const line of text.split("\n")) {
106
+ const match = /^\s*(\d+)\s(.*)$/.exec(line);
107
+ if (match && ` ${match[2]} `.includes(` ${entry} `)) found.add(Number(match[1]));
108
+ }
109
+ } catch { /* None readable. */ }
110
+ return found;
111
+ }
@@ -1,9 +1,9 @@
1
1
  // Generated by scripts/build/bundle-skills.ts; edit skills/*/SKILL.md.
2
2
  export const BUNDLED_SKILLS: Readonly<Record<string, string>> = {
3
3
  "cross-agent-review": "---\nname: cross-agent-review\ndescription: Review committed branch changes with an independent Claude Code, Codex, or OpenCode reviewer, and repair actionable findings when requested.\n---\n\n# Cross-Agent Review\n\nUse the installed `agent-tool` executable. Read the repository's development and\nreview policy and `agent-tool.json` when present. Keep project validation commands\nand release rules in the repository; do not assume Bun, a workspace layout, or\nparticular CI job names.\n\nSelect a reviewer different from the coordinating agent when possible. Honor a\nrequested reviewer or effort; otherwise use an available independent reviewer.\nRun `agent-tool doctor` if CLI compatibility is uncertain.\n\nRun noisy validation or repair checks through\n`agent-tool run --label <check> -- <command> [args...]`. Read its bounded failure\ntail and use `agent-tool logs <log>` or a targeted search for more evidence.\nKeep `agent-tool review` direct: it retains reviewer stderr in a private local\nlog and displays the complete final review. Never hide, truncate, or substitute\na command success receipt for findings and the final verdict.\n\nReview committed changes with `agent-tool review claude`, `agent-tool review codex`,\nor `agent-tool review opencode`. Optional effort is `low`, `medium`, `high`,\n`xhigh`, or `max`. For a local or non-GitHub repository, add `--base <commit-or-ref>`.\nFor a coordinated GitHub review, pin the fetched base using\n`AGENT_TOOL_REVIEW_BASE_REF`, the base branch name such as `main` (not a\nremote-tracking ref like `origin/main`), and `AGENT_TOOL_REVIEW_BASE_OID`, its\nfetched commit. Fetch from the repository that owns the PR, which can differ\nfrom the checkout's origin.\n\nUse `agent-tool repo context --fetch` to resolve and fetch the PR's own base,\nthen record the exact base and HEAD before reviewing. The tool reviews raw committed\nfiles and excludes worktree edits. A zero exit means a complete review was\nreturned; it does not mean the findings are non-blocking. Read the final\n`VERDICT: BLOCKER|MAJOR|MINOR|SUGGESTION|CLEAN` and the findings. A reviewer\nthat labels findings `[P0]` through `[P3]` uses the same scale: `[P0]` and\n`[P1]` are BLOCKER and MAJOR, `[P2]` and `[P3]` are MINOR and SUGGESTION.\n\nIf a CLI is unavailable, out of credits, or returns an unusable review, try another\navailable reviewer and disclose the fallback. Do not silently convert a failed\nreview into CLEAN or call an in-session review independent.\n\nFor report-only requests, report findings without changing files or history.\nWhen repairs are authorized, address actionable BLOCKER and MAJOR findings,\nvalidate with the repository's relevant checks, commit the repairs, and review\nthe new HEAD. Continue while meaningful progress is possible; report an impasse\nwhen progress requires a material user decision. A repaired commit is unreviewed\nuntil the next review completes. Preserve unrelated work.\n\nBefore reporting success, confirm HEAD still matches the reviewed commit and\nthat an existing PR points to that same commit. If the base moved, refresh it and\nreview again before shipping. Report reviewer, exact base and head IDs, verdict,\nremaining findings, validation, and any repairs performed. This skill does not\nauthorize pushing, opening a PR, or merging unless the user requested that work.\n",
4
- "open-pr": "---\nname: open-pr\ndescription: Open a GitHub pull request for the current feature branch with a validated title and a reviewable description.\n---\n\n# Open PR\n\nUse the installed `agent-tool`. Follow repository policy for validation, commits,\nand branch naming. Resolve the repository and default branch with `agent-tool repo context`;\ndo not assume the branch is named main. Preserve unrelated work and finish\nrequested changes and appropriate checks before publishing them.\n\nEnsure the intended commit is on a feature branch and use\n`agent-tool branch push <reviewed-head> --remote <remote>` through normal hooks.\nIt names the destination explicitly and verifies local/remote HEAD afterward;\na changed result needs another review. Respect existing push authorization.\nIf the user only requested a draft description, prepare it without publishing.\n\nWrite a title that satisfies the data-only `agent-tool.json` subject policy.\nDescribe the concrete resulting behavior and relevant validation. When the\nbranch changes package manifests, run\n`agent-tool dependencies diff --base <base-oid>` and name every `newPackages`\nentry in the body with its manifest and version, so a reviewer sees new\nthird-party code however it was added. Put multiline body text in a temporary\nfile, then run:\n\n```sh\nagent-tool pr open 'feat: describe the change' --body-file /path/to/pr-body.txt\n```\n\nOmitting the title uses the latest commit subject. The tool refuses duplicate\nopen PRs and requires the branch to be pushed at its local HEAD. It does not\npush for you. Resolve a fork's head/base identities explicitly if the repository\nuses fork PRs; the initial open helper supports same-repository branches.\n\nReport the created PR link and any remaining validation or review work.\n",
5
- "reset": "---\nname: reset\ndescription: Return a clean checkout to its updated default branch after confirmed shipping or an explicit checkout cleanup request.\n---\n\n# Reset\n\nThis is checkout cleanup, not a destructive Git reset. Read repository guidance\nfor setup and hooks. Determine the default branch through the repository's\nremote metadata rather than assuming main.\n\nFor post-merge cleanup, preview with\n`agent-tool repo cleanup <PR-number> <shipped-head>`, then run it with `--apply`\nwithin the authorized cleanup scope. It requires a confirmed MERGED PR, preserves\nlocal edits, checks exact local/remote feature commits, verifies the merge is on\nthe default branch, and fast-forwards that branch. By default it prunes the\nshipped local feature branch and deletes the matching remote branch if present.\nLocal pruning also applies after a squash merge or when GitHub already deleted\nthe remote branch; a missing remote is not evidence that local cleanup is done.\nPass `--keep-branch` when the user asked to preserve both feature refs.\nRead the receipt's completed steps if a later operation fails; do not claim full\ncleanup from a partial result. Verify the final branch and clean worktree, and\ncheck that `git branch --list <feature-branch>` is empty unless keeping the branch.\nIf the feature branch is checked out in another worktree, shared cleanup reports\na partial failure after updating the default branch and leaves both feature refs\nin place; preserve that worktree and report the remaining cleanup.\n\nRemote branch deletion uses GitHub REST after checking the live ref to avoid\npre-push hooks. The API has no atomic expected-OID delete guard; the check and\ndeletion retain a small concurrent-update window. Fork PRs require manual remote\nhandling and are refused by the shared cleanup command.\nUse a repository's stronger cleanup procedure when required, including atomic\nremote deletion or additional local verification; do not weaken it to use the\nshared command. The same local pruning and keep-branch outcomes still apply.\n\nFor an explicit checkout cleanup without a merged PR, preserve all feature refs:\ncheck worktree/index, resolve the default branch with `repo context`, fetch it,\nswitch, and update by fast-forward only. Never discard or automatically stash\nedits, force a diverged default branch, or infer shipping from Git ancestry after\na squash merge.\n\nRun the repository's documented dependency/hook setup if required. When copied\nhooks are configured, use `agent-tool hooks check` and `hooks install --apply`;\ninspect unmanaged hooks before an explicit `--adopt`, which backs them up.\nDo not assume a package manager. Report final branch, commit, whether the shipped\nlocal branch was pruned or preserved, and unfinished cleanup or setup.\n",
6
- "ship-pr": "---\nname: ship-pr\ndescription: Complete an authorized commit, independent review, repair, PR, CI, and squash-merge workflow for a GitHub repository.\n---\n\n# Ship PR\n\nUse the installed `agent-tool`. Read repository guidance and policy first;\nvalidation, versioning, package management, and hook bodies remain project\nconcerns. Use shared branch, hook, check, cleanup, and release commands where\nconfigured; keep application-specific commands in repository guidance. Shipping authorizes this workflow within the user's stated scope.\nPreserve unrelated edits and honor requested stopping points such as open-PR\nonly, report-only review, or keeping the feature branch.\n\nUse `agent-tool run --label <check> -- <command> [args...]` for noisy setup,\nvalidation, builds, and hook-running Git commands. It preserves exit status and\ncomplete private logs, prints one success receipt, and shows a bounded failure\ntail. Inspect more with `agent-tool logs <log> --max-bytes 8192 --tail-lines 80`\nor a targeted search; never dump an entire suite log or pipe checks into `tail`.\nThe receipt proves process completion, not absence of warnings: inspect required\nwarning, coverage, timing, or artifact evidence before accepting a check. Keep\nmachine-readable receipts and review findings visible by running `versions\nprepare`, `review`, and other commands whose output drives a decision directly.\nPrefer documented compact test reporters when they preserve required evidence;\ndo not reduce test scope, skip checks, silence warnings, or mask failures.\n\n1. Finish the requested change on a feature branch. Use\n `agent-tool branch create <branch> --base <base-branch> --remote <remote>`\n from a clean checkout; it fetches and pins the base, checks naming policy and\n collisions, and creates without a local upstream. Use `branch check` with\n explicit destination names in CI or hooks.\n Validate it with appropriate project checks and commit only the intended\n files.\n2. Use `agent-tool repo context --fetch` to resolve the PR's base repository\n and branch, or the default branch when no PR exists, and fetch its exact base.\n Record the returned base/head identities. Integrate the fetched base\n using the repository's normal workflow, resolving conflicts without losing\n user work. If project policy versions packages, prepare versions against the\n pinned base after every integration or repair and before each review, using\n the project's commands or `agent-tool versions prepare <base-oid>`, which\n commits bumped manifests and the refreshed lockfile.\n `agent-tool versions resolve-conflicts` resolves conflicts confined to\n version fields. Review the resulting committed HEAD with an independent\n reviewer using the bundled cross-agent-review skill. Repair blocking findings\n and review every changed HEAD again. Review failure blocks shipping.\n3. Run `agent-tool branch push <reviewed-head> --remote <remote>` through\n normal hooks; it verifies local and remote identity afterward. If a hook\n changed content or HEAD, review that result.\n Open the PR using the open-pr skill, or update the existing PR as needed.\n4. Allow configured review bots time to respond, then use\n `agent-tool pr threads list` to fetch review threads and all comments. Follow repository policy for feedback: fix valid findings,\n reply with `pr threads reply <comment-id>` (body file or stdin), and use\n `pr threads resolve <thread-id>` only for fully addressed findings.\n Validate, commit, push, and independently review every feedback or CI repair.\n Wait with `agent-tool pr checks --wait --head <reviewed-head>`, whose limit\n defaults to `agent-tool.json` `merge.checksTimeoutSeconds`; when a job\n fails, read its log with `agent-tool pr logs --head <reviewed-head>`. Then run\n `agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` to\n recheck CI, live base, PR identity, local state, and explicit version policy.\n A changed base requires integration, validation, and another review. When\n versions are managed, `agent-tool versions check <base-oid>` must pass for the\n live base. Use the squash-merge skill to merge the exact reviewed HEAD.\n5. After confirmed MERGED, use the reset skill to return to the updated default\n branch and prune the shipped local feature branch as part of cleanup, honoring\n stronger repository cleanup rules. If the user requested keep-branch, preserve\n both feature refs. Check the cleanup receipt and verify the local feature ref\n is absent unless preserved; report incomplete cleanup explicitly. Apply\n documented dependency/hook setup.\n6. When the project publishes npm packages, use `agent-tool release verify\n <package> <version> <merge-oid> --workflow <publish-workflow>` to verify the\n exact workflow and tarball, allowing registry propagation time. When the\n project deploys the merged branch, verify that deployment and documented\n live checks. Report deployment failures\n separately from a successful merge; follow project policy for repairs.\n\nNever infer a clean review from process success alone or carry a review across\ncontent changes. Do not weaken configured CI policy to get a merge through.\nIf a step fails, preserve useful intermediate work and report the concrete\nremaining issue. Report PR link, merged commit, review verdict, validation, final\ncheckout state, and whether the shipped local branch was pruned or preserved.\n",
4
+ "open-pr": "---\nname: open-pr\ndescription: Open a GitHub pull request for the current feature branch with a validated title and a reviewable description.\n---\n\n# Open PR\n\nUse the installed `agent-tool`. Follow repository policy for validation, commits,\nand branch naming. Resolve the repository and default branch with `agent-tool repo context`;\ndo not assume the branch is named main. Preserve unrelated work and finish\nrequested changes and appropriate checks before publishing them.\n\nEnsure the intended commit is on a feature branch and use\n`agent-tool branch push <reviewed-head> --remote <remote>` through normal hooks.\nIt names the destination explicitly and verifies local/remote HEAD afterward;\na changed result needs another review. Respect existing push authorization.\nIf the user only requested a draft description, prepare it without publishing.\n\nWrite a title that satisfies the data-only `agent-tool.json` subject policy.\nDescribe the concrete resulting behavior and relevant validation. When the\nbranch changes package manifests, run\n`agent-tool dependencies diff --base <base-oid>` and name every `newPackages`\nentry in the body with its manifest and version, so a reviewer sees new\nthird-party code however it was added. Put multiline body text in a temporary\nfile, then run:\n\n```sh\nagent-tool pr open 'feat: describe the change' --body-file /path/to/pr-body.txt\n```\n\nOmitting the title uses the latest commit subject. The tool refuses duplicate\nopen PRs and requires the branch to be pushed at its local HEAD. It does not\npush for you. Resolve a fork's head/base identities explicitly if the repository\nuses fork PRs; the initial open helper supports same-repository branches.\n\nReport the created PR link and any remaining validation or review work. Run\n`agent-tool teardown` first, stop what the work started, and report what remains.\n",
5
+ "reset": "---\nname: reset\ndescription: Return a clean checkout to its updated default branch after confirmed shipping or an explicit checkout cleanup request.\n---\n\n# Reset\n\nThis is checkout cleanup, not a destructive Git reset. Read repository guidance\nfor setup and hooks. Determine the default branch through the repository's\nremote metadata rather than assuming main.\n\nFor post-merge cleanup, preview with\n`agent-tool repo cleanup <PR-number> <shipped-head>`, then run it with `--apply`\nwithin the authorized cleanup scope. It requires a confirmed MERGED PR, preserves\nlocal edits, checks exact local/remote feature commits, verifies the merge is on\nthe default branch, and fast-forwards that branch. By default it prunes the\nshipped local feature branch and deletes the matching remote branch if present.\nLocal pruning also applies after a squash merge or when GitHub already deleted\nthe remote branch; a missing remote is not evidence that local cleanup is done.\nPass `--keep-branch` when the user asked to preserve both feature refs.\nRead the receipt's completed steps if a later operation fails; do not claim full\ncleanup from a partial result. Verify the final branch and clean worktree, and\ncheck that `git branch --list <feature-branch>` is empty unless keeping the branch.\nIf the feature branch is checked out in another worktree, shared cleanup reports\na partial failure after updating the default branch and leaves both feature refs\nin place; preserve that worktree and report the remaining cleanup.\n\nRemote branch deletion uses GitHub REST after checking the live ref to avoid\npre-push hooks. The API has no atomic expected-OID delete guard; the check and\ndeletion retain a small concurrent-update window. Fork PRs require manual remote\nhandling and are refused by the shared cleanup command.\nUse a repository's stronger cleanup procedure when required, including atomic\nremote deletion or additional local verification; do not weaken it to use the\nshared command. The same local pruning and keep-branch outcomes still apply.\n\nFor an explicit checkout cleanup without a merged PR, preserve all feature refs:\ncheck worktree/index, resolve the default branch with `repo context`, fetch it,\nswitch, and update by fast-forward only. Never discard or automatically stash\nedits, force a diverged default branch, or infer shipping from Git ancestry after\na squash merge.\n\nRun `agent-tool teardown` and stop what the finished work left running\n(`teardown --apply` for recorded processes); report anything that remains.\nRun the repository's documented dependency/hook setup if required. When copied\nhooks are configured, use `agent-tool hooks check` and `hooks install --apply`;\ninspect unmanaged hooks before an explicit `--adopt`, which backs them up.\nDo not assume a package manager. Report final branch, commit, whether the shipped\nlocal branch was pruned or preserved, and unfinished cleanup or setup.\n",
6
+ "ship-pr": "---\nname: ship-pr\ndescription: Complete an authorized commit, independent review, repair, PR, CI, and squash-merge workflow for a GitHub repository.\n---\n\n# Ship PR\n\nUse the installed `agent-tool`. Read repository guidance and policy first;\nvalidation, versioning, package management, and hook bodies remain project\nconcerns. Use shared branch, hook, check, cleanup, and release commands where\nconfigured; keep application-specific commands in repository guidance. Shipping authorizes this workflow within the user's stated scope.\nPreserve unrelated edits and honor requested stopping points such as open-PR\nonly, report-only review, or keeping the feature branch.\n\nUse `agent-tool run --label <check> -- <command> [args...]` for noisy setup,\nvalidation, builds, and hook-running Git commands. It preserves exit status and\ncomplete private logs, prints one success receipt, and shows a bounded failure\ntail. Inspect more with `agent-tool logs <log> --max-bytes 8192 --tail-lines 80`\nor a targeted search; never dump an entire suite log or pipe checks into `tail`.\nThe receipt proves process completion, not absence of warnings: inspect required\nwarning, coverage, timing, or artifact evidence before accepting a check. Keep\nmachine-readable receipts and review findings visible by running `versions\nprepare`, `review`, and other commands whose output drives a decision directly.\nPrefer documented compact test reporters when they preserve required evidence;\ndo not reduce test scope, skip checks, silence warnings, or mask failures.\nStart servers, watchers, and other long-running processes with\n`agent-tool proc start --label <name> -- <command>`, never a backgrounded shell\ncommand, so they can be found and stopped.\n\n1. Finish the requested change on a feature branch. Use\n `agent-tool branch create <branch> --base <base-branch> --remote <remote>`\n from a clean checkout; it fetches and pins the base, checks naming policy and\n collisions, and creates without a local upstream. Use `branch check` with\n explicit destination names in CI or hooks.\n Validate it with appropriate project checks and commit only the intended\n files.\n2. Use `agent-tool repo context --fetch` to resolve the PR's base repository\n and branch, or the default branch when no PR exists, and fetch its exact base.\n Record the returned base/head identities. Integrate the fetched base\n using the repository's normal workflow, resolving conflicts without losing\n user work. If project policy versions packages, prepare versions against the\n pinned base after every integration or repair and before each review, using\n the project's commands or `agent-tool versions prepare <base-oid>`, which\n commits bumped manifests and the refreshed lockfile.\n `agent-tool versions resolve-conflicts` resolves conflicts confined to\n version fields. Review the resulting committed HEAD with an independent\n reviewer using the bundled cross-agent-review skill. Repair blocking findings\n and review every changed HEAD again. Review failure blocks shipping.\n3. Run `agent-tool branch push <reviewed-head> --remote <remote>` through\n normal hooks; it verifies local and remote identity afterward. If a hook\n changed content or HEAD, review that result.\n Open the PR using the open-pr skill, or update the existing PR as needed.\n4. Allow configured review bots time to respond, then use\n `agent-tool pr threads list` to fetch review threads and all comments. Follow repository policy for feedback: fix valid findings,\n reply with `pr threads reply <comment-id>` (body file or stdin), and use\n `pr threads resolve <thread-id>` only for fully addressed findings.\n Validate, commit, push, and independently review every feedback or CI repair.\n Wait with `agent-tool pr checks --wait --head <reviewed-head>`, whose limit\n defaults to `agent-tool.json` `merge.checksTimeoutSeconds`; when a job\n fails, read its log with `agent-tool pr logs --head <reviewed-head>`. Then run\n `agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` to\n recheck CI, live base, PR identity, local state, and explicit version policy.\n A changed base requires integration, validation, and another review. When\n versions are managed, `agent-tool versions check <base-oid>` must pass for the\n live base. Use the squash-merge skill to merge the exact reviewed HEAD.\n5. After confirmed MERGED, use the reset skill to return to the updated default\n branch and prune the shipped local feature branch as part of cleanup, honoring\n stronger repository cleanup rules. If the user requested keep-branch, preserve\n both feature refs. Check the cleanup receipt and verify the local feature ref\n is absent unless preserved; report incomplete cleanup explicitly. Apply\n documented dependency/hook setup.\n6. When the project publishes npm packages, use `agent-tool release verify\n <package> <version> <merge-oid> --workflow <publish-workflow>` to verify the\n exact workflow and tarball, allowing registry propagation time. When the\n project deploys the merged branch, verify that deployment and documented\n live checks. Report deployment failures\n separately from a successful merge; follow project policy for repairs.\n\nBefore the final report, run `agent-tool teardown` in each repository this work\ntouched. Stop what the work started (`teardown --apply`, `proc stop`), stop any\nuntracked process it started, and remove worktrees it added. Report what\nremains and why; the work is not done while teardown fails for anything it\nstarted.\n\nNever infer a clean review from process success alone or carry a review across\ncontent changes. Do not weaken configured CI policy to get a merge through.\nIf a step fails, preserve useful intermediate work and report the concrete\nremaining issue. Report PR link, merged commit, review verdict, validation, final\ncheckout state, the teardown result, and whether the shipped local branch was\npruned or preserved.\n",
7
7
  "squash-merge": "---\nname: squash-merge\ndescription: Squash-merge a reviewed GitHub pull request while binding the mutation to the reviewed commit and checking CI.\n---\n\n# Squash Merge\n\nUse the installed `agent-tool` and repository merge policy. Merge only within\nthe user's authorized scope. Have the exact reviewed HEAD, base commit, and base\nbranch available, and read the verdict and unresolved findings. BLOCKER or MAJOR\nfindings require repair and a new review before merging.\nFollow the repository's review-bot policy and require all actionable blocking\nreview feedback to be addressed before merging.\n\nWait with `agent-tool pr checks --wait --head <reviewed-head>`, which waits for\nchecks to appear and for every workflow/job/event entry to finish. Run\n`agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` immediately\nbefore merging. It checks local and PR identity, live base, ancestry, explicit\nversion policy, merge readiness, configured strict rulesets, and passing checks.\nIf an identity changed, refresh, integrate, validate, and review again. Read\nunresolved feedback with `pr threads list` and follow project review policy.\n\nUse a title that satisfies `agent-tool.json` and pass both reviewed HEAD and\nbase branch:\n\n```sh\nagent-tool pr merge 'feat: describe the change' <reviewed-head-oid> <base-branch>\n```\n\nThe helper enforces HEAD atomically through GitHub's `expectedHeadOid`, checks\nCI, rejects queued or automatic merges, and creates a subject-only squash with\nthe PR reference. GitHub has no atomic expected-base argument in this mutation;\nrepository branch protection must enforce any required base freshness. With\n`merge.requireStrictBaseFreshness`, the helper refuses to merge unless an\nactive strict status ruleset that the actor cannot bypass protects the base. Do\nnot retarget the PR concurrently with merging.\n\nConfirm GitHub reports MERGED before any cleanup. A failed or uncertain mutation\nis not evidence of a merge. Preserve the branch on failure. After a confirmed\nmerge, perform checkout cleanup only when requested or as part of an authorized\nshipping workflow. Report the PR and merge result.\n",
8
8
  "update-dependencies": "---\nname: update-dependencies\ndescription: Update repository dependencies, runtimes, tools, and CI pins with compatibility checks and safe infrastructure previews, then ship through review, CI, merge, and release verification unless a narrower scope is requested.\n---\n\n# Update Dependencies\n\nUse the repository's package managers and installed `agent-tool`. Read `AGENTS.md`,\nREADME, existing dependency-maintenance notes, linked setup/release documents,\nand repository-owned upgrade skills before editing. Follow their hooks, version\npolicy, checks, and requested stopping point.\nUpdate applicable dependencies throughout the repository, including workspaces\nand examples. When asked to perform dependency updates, invoke the installed\n[`ship-pr`](../ship-pr/SKILL.md) to complete review, PR, CI, and merge, then verify\nthe repository's normal merge-triggered publication or deployment. An explicit\nnarrower scope, such as inventory-only, local changes, or open-PR-only, takes\nprecedence. This default does not authorize standalone infrastructure applies,\ndeployments, or global tool changes. Default dependency-update merge subject:\n`chore: update dependencies`, subject to repository title policy and any explicit\nuser subject.\n\nRun noisy installs, checks, tests, and builds with\n`agent-tool run --label <check> -- <command> [args...]` to retain full private\nlogs and return the original status with compact output. Inspect bounded excerpts\nusing `agent-tool logs <log>` and targeted searches for warnings and evidence;\na successful receipt does not establish a warning-free upgrade. Keep structured\naudit/plan results, deployment previews, and review findings directly visible\nwhen they drive a safety decision. Do not dump full suite logs into context,\nsilence warnings at their source, or change check scope to reduce output.\n\n## Safety before execution\n\n**Always dry-run before any infrastructure apply or deployment. Never destroy,\nreplace, or recreate a resource during an upgrade.** This includes Terraform,\nOpenTofu, Wrangler, Ansible, other infrastructure tools, and effects triggered by\ninstallation, tests, hooks, Git push, opening a PR, CI, or merging. Greenfield\nprojects and approval to ship do not waive this rule.\n\nBefore running project commands or pushing, trace their scripts, hooks, workflow\ntriggers, reusable workflows, and deployment commands. A dry-run flag alone is\ninsufficient: inspect tasks, provisioners, plugins, external programs, and actions\nthat can mutate despite preview mode. Avoid such a preview unless its effects\nare proven read-only. Do not run destroy/delete, taint/replace, state removal,\nbackend migration, forced database reset, or an automatic \"repair\" that bypasses\nthe rule. Do not hide destruction with targeting, disabled refresh, ignored\nchanges, new resource identities, or weakened policy.\n\nPreview with the proposed versions and complete configuration for each affected\nenvironment, using its real backend/workspace/account, variables, inventory, and\nresource identities. An empty local state, mocked credentials, validate-only run,\nor bundle build cannot establish safety for production. Check the current baseline\nas well when needed to distinguish existing drift from the upgrade. Keep state,\nbinary plans, JSON plans, and secret-bearing diffs out of Git and public reports.\n\nIf a preview proposes deletion or replacement, fails, is incomplete, omits\naffected resources, or cannot establish safety, skip that dependency and its\ncoupled migrations. Restore only this task's edits to the affected compatibility\ngroup, retain independent safe upgrades, and record the reason and affected\nresources. Never apply to find out. A preview is not deployment authorization.\n\nBefore an authorized apply/deploy, verify the exact validated commit, toolchain,\nconfiguration, environment, and current state still match the preview. Re-preview\nafter relevant changes or drift. CI must enforce the same order and stop on an\nunsafe preview before mutation; a successful local preview does not excuse an\nunguarded push- or merge-triggered deployment. Establish a narrowly scoped guard\nwhen authorized and reviewable, or hold the affected upgrade before triggering\nthat workflow. Do not disable protections to ship. A plan must be inspected before\nthe operation; inspecting deployment logs afterward is too late.\nAn unsafe workflow triggered on every branch push also blocks pushing otherwise\nindependent upgrades until that trigger has a proven safe guard.\n\n### Terraform and OpenTofu\n\nRead core, provider, and module upgrade guides, including intermediate major\nmigrations. Regenerate provider locks with the pinned CLI, preserving supported\nplatform hashes. Backend initialization/migration is also subject to the safety\ngate. Inspect external data programs and provisioners before planning.\n\nUse a full refreshed saved plan with locking and the real variables, for example\n`terraform plan -input=false -out=<private-plan>`; if using `-detailed-exitcode`,\n0 and 2 are success, 1 is failure. Inspect `terraform show -json <private-plan>`.\nRun `agent-tool dependencies check-terraform-plan <private-plan.json>` to check\nsupported JSON resource actions. It fails for every action containing `delete`,\nincluding both replacement orders, unknown actions, incomplete/deferred plans,\nfailed checks, or opaque provider action invocations. It prints actions and\ndiagnostics without resource attribute values; it does not prove that a plan is\nfresh, comprehensive, authentic, or that provider code has no hidden effects.\nOlder/unsupported plan formats that cannot establish completeness are skipped.\nOpenTofu currently omits `complete` in its JSON format and is rejected by this\nhelper; report that limitation rather than adding a synthetic completeness flag.\nAlso inspect resource identity, drift, warnings, provider semantics, and any\neffects outside resource actions. For an authorized apply, consume the exact\napproved saved plan, not an uninspected newly generated plan.\n\nSource: [Terraform JSON plan format](https://developer.hashicorp.com/terraform/internals/json-format).\n\n### Wrangler and other deployment tools\n\nUse the proposed pinned Wrangler for `wrangler deploy --dry-run` with the same\nbuild/configuration/environment used by deployment. This checks bundling, not a\ncomplete remote resource plan. Separately verify account, worker name, routes,\nbindings and resource IDs against the existing deployment and read migration\nsemantics. Review Durable Object deleted/renamed classes, D1 schema/data\nmigrations, storage resources, queues, containers, and deployment integrations.\nNever infer \"no destruction\" from a successful bundle. Resource removals,\nreplacement, or unprovable remote effects skip the affected group. Apply the\nequivalent preview and identity checks to other tools rather than assuming they\nshare Terraform's guarantees.\n\nDo not assume `wrangler d1 migrations list --remote` is read-only. The\nimplementation inspected for this skill initializes migration tracking with\n`CREATE TABLE IF NOT EXISTS`; verify the pinned Wrangler version before using\nthe command. Verify database identity and compare migration files with the\ndatabase's configured migration tracking table through audited read-only\nqueries. A missing table, pending migration, or unverifiable schema/data\neffects hold the affected upgrade/deployment group. Never initialize schema\nmerely to establish preview safety.\n\nWrangler runs a custom `build.command` again during deployment. Use supported\nconfiguration referencing the same validated artifacts for both preview and\ndeployment, preventing another unvalidated build before upload. Bind the\nartifacts, configuration, and pinned tool to the authorized commit, and recheck\ntheir identities before upload and after relevant changes. Hold the affected\ngroup if the pinned Wrangler cannot upload the validated output without\nrebuilding it, or if the upload cannot be proven to match the preview.\n\nSources: [Wrangler command documentation](https://developers.cloudflare.com/workers/wrangler/commands/),\n[D1 migration listing implementation](https://github.com/cloudflare/workers-sdk/blob/e3d186776fcc2e4b5cc4cfd7155591778a375957/packages/wrangler/src/d1/migrations/list.ts),\n[migration table initialization](https://github.com/cloudflare/workers-sdk/blob/e3d186776fcc2e4b5cc4cfd7155591778a375957/packages/wrangler/src/d1/migrations/helpers.ts),\nand [Wrangler custom builds](https://developers.cloudflare.com/workers/wrangler/custom-builds/).\n\n### Ansible\n\nCheck controller Python, ansible-core, collections/roles, and target Python support\ntogether; read porting guides. Inspect all tasks and invoked scripts before\n`ansible-playbook --check --diff` with the real inventory and variables.\n`check_mode: false` forces mutation even with `--check`; unsupported modules and\nconditions based on registered results can omit effects. Inspect deletion,\nrecreation, service/data reset, and package removal semantics beyond the diff.\nSkipped or opaque tasks are a safety gap, not a clean preview. Redact diffs.\n\nSource: [Ansible check mode limits](https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_checkmode.html).\n\n## Inventory and choose compatible targets\n\nRecord each dependency source, current resolved version, latest stable candidate,\nselected target, compatibility constraints, upstream migration links, and checks\nin the run ledger described under Report.\nQuery authoritative registries, official releases, support matrices, and migration\nguides at execution time; do not treat remembered versions or prereleases as\nlatest stable. Inspect runtime requirements, peer dependencies, ABI/API changes,\nplatform availability, maintained release lines, and changed defaults, including\nsecurity, privacy/telemetry, data retention, and postinstall/native behavior.\nCheck transitive dependencies' peer/runtime constraints as well as direct ones. Unsupported\nor unpublished targets stay pinned with an explanation.\n\nInventory manifests, locks, tool configuration, CI/reusable actions, containers,\nscripts, deployment files, and executable documentation. Search duplicate version\npins and aliases, not just filenames; exclude vendored/generated snapshots unless\nthe repository owns their update process. Examples of sources to inspect:\n\n| Ecosystem | Sources and compatibility group |\n| --- | --- |\n| JavaScript/TypeScript | All package.json dependency fields, overrides/resolutions, workspace catalogs, packageManager/engines, npm/Bun/pnpm/Yarn locks, Node/Bun pins, compiler and lint/build/test plugins |\n| Toolchains | mise.toml/.mise.toml, mise.lock, .tool-versions, runtime version files, tool URLs/checksums, CI pins and container images; include every tool declared by mise, not just mise itself |\n| Python/Ansible | pyproject/requirements, uv/Poetry/pip locks, Python pins, ansible-core, collection/role requirements, lint plugins and managed host constraints |\n| Ruby/iOS | .ruby-version, Gemfile/lock, Bundler, CocoaPods, Podfile/lock, podspecs, Swift packages and Xcode/iOS deployment requirements |\n| Infrastructure | Terraform/OpenTofu CLI constraints, provider locks/constraints, module versions/Git refs, Wrangler and Cloudflare integration dependencies |\n| CI/system/native | Actions/reusable workflow refs, Docker tags/digests, OS images/packages, Rust/Cargo toolchain and locks, Go modules, Gradle/AGP/Kotlin/JDK and other repository-specific manifests |\n\nBuild connected compatibility groups before editing. Select the newest supported\ncombination, which can be older than an individual package's latest. Upgrade the\nframework first or keep its compatible toolchain pinned; do not force peer\nresolution, drop compatibility checks, or add blanket overrides to make installs\npass. Preserve source pin policy (exact version, digest, full Git SHA) and resolve\nimmutable pins from verified upstream releases. Preserve intentional runtime\nminimums unless migration requires changing the support contract.\n\nFor React Native, use its version-specific upgrade guide/template diffs and\nrepository upgrade skills. Couple React and its renderer, native modules,\nMetro/Babel, CLI, codegen, Hermes/New Architecture, CocoaPods/Bundler/Ruby,\nXcode/iOS deployment targets, and Android Gradle/AGP/Kotlin/JDK/SDK/NDK. For Expo,\nuse the chosen SDK's supported React Native/dependency matrix and its dependency\nchecks. Do not independently update framework-managed pods or generated native\nfiles; use the framework's regeneration workflow and prove iOS/Android builds.\nPermissive peer ranges alone do not prove native renderer or toolchain compatibility;\ncheck the framework's actual supported versions and native implementation.\nAn unavailable native toolchain is a reported validation limit; do not claim the\ngroup verified. See [React Native upgrading](https://reactnative.dev/docs/upgrading).\n\nCheck developer tools' own dependencies too: a compiler release without its old\nprogrammatic API may break test/lint runners that import it even when `tsc` passes.\nAction runtime upgrades can require newer self-hosted runners; preserve workflow\npermissions, action inputs/outputs, caching, artifact semantics, and job names.\n\nCheck current advisories with read-only ecosystem audits against the baseline and\nproposed lockfiles, using the repository's configured registry/advisory sources.\nDo not send private dependency metadata to an unconfigured or unauthorized service;\nreport the resulting coverage limit. Cover direct and resolved transitive dependencies,\nincluding native/platform-specific binaries. Latest direct packages can still\npin vulnerable transitive versions. Trace each finding to its owning dependency,\nverify affected versions, runtime conditions, and remediation in the maintainer's\nadvisory and fixed release. When the owner's range permits a fixed version, use a\ntargeted refresh with the lockfile's owning manager and preserve unrelated\nresolutions; otherwise prefer a supported owner upgrade.\nIf the owner still pins a vulnerable version, a narrowly scoped security patch\noverride may be used only with API/ABI/runtime compatibility evidence and focused\nregression checks of the actual affected integration. Document its rationale and\nremoval condition; a passing install or bundle alone is insufficient. Do not run\nblind audit fixes or use blanket overrides to bypass compatibility constraints.\nReport unresolved advisories and unavailable audit coverage accurately; current\ndirect pins or a partial clean audit do not\nestablish that the whole dependency graph is safe.\n\n## Migrate and validate\n\nCapture relevant baseline checks and warnings first, after screening their side\neffects. Update one compatibility group at a time. Read the upstream instructions\nfor every breaking step; implement required source/config/schema migrations and\nremoved API replacements. Use the manager that owns each lockfile, on the selected\nruntime, and inspect the resulting diff. For Bun lockfiles, change declared\nversions with `agent-tool bun update <name[@version]>` and drop packages with\n`agent-tool bun remove <name>`; both use the pinned Bun and refuse to add a\npackage. A new dependency goes through `agent-tool bun add <name@version>`, which\nasks for approval; never introduce one by editing `package.json` and\nreinstalling. Refresh transitive dependencies through\ntheir owning direct dependency; do not hand-edit integrity hashes or lock entries.\nReview intentional patches, overrides, and pins before removal; retain them until\nupstream fixes and regression checks demonstrate they are unnecessary.\nAvoid unrelated global installations or environment changes. Use task-local or\nrepository-scoped tools for testing changed runtime pins.\nFor published packages, also validate tarballs and consumer installs with their\ndocumented supported package managers, including manifest/override syntax and\nruntime requirements. A successful owning-manager install does not prove that\npublished metadata works for those consumers.\n\nRun the repository's setup/hooks, frozen installs, lint, typechecks, tests, builds,\npackage/platform smoke checks, and relevant safe integration previews. Resolve\nupgrade-related deprecation warnings at their source. Do not suppress warnings,\nweaken tests, or disable checks; report remaining upstream/pre-existing warnings\nwith evidence and keep a target pinned when migration cannot be completed.\nAdd focused regression coverage when a migration changes behavior; avoid tests\nthat merely assert version strings. Re-run checks after repairs. Report checks\nblocked by missing credentials, platforms, or external services accurately.\nRe-audit the final resolved graph after migrations and repairs.\n\nConfirm every inventory row is upgraded, already current, intentionally constrained,\nor skipped with a concrete reason. Do not present an unresolved group as complete.\nWhen upgrading agent-tool itself, install its managed skills with the same harness\nscope and commit the ownership manifest; never edit generated managed skill copies.\n\nWhen changes depend on another repository's release, ship the producer first and\nconfirm publishing and registry availability before pinning the consumer; include\nits exact version/commit and API migration notes. Independent groups may proceed.\nComplete the installed `ship-pr` workflow within the requested scope, including\nindependent review of every changed HEAD, required CI and review feedback, merge,\nand verification of the merge's normal publication or deployment. Do not stop at\nan open PR unless the user requested that stopping point or a concrete blocker\nprevents continuing. Check deployment safety again before push/open/merge;\nshipping defaults do not waive the preview gates above.\n\n## Report\n\nKeep run-specific evidence in the upgrade PR body or a linked PR comment: the\ninventory and old/selected versions, completed migrations, validation and warnings,\nbaseline/final audits and coverage limits, preview environment/commit/tool versions\nand safe action summary, and skipped/constrained dependencies with reasons. Include\nsecurity overrides, their rationale and removal condition, and unresolved advisories.\nIf the user requested a scope that stops before a PR, provide this ledger in the\ntask report and honor that limit. For a sweep, keep one entry per repository,\nincluding unready and unchanged checkouts, and use an existing tracking issue only\nwhen explicitly requested. Never create an issue merely to store upgrade evidence.\n\nKeep durable repository guidance focused on what the next upgrade needs: current\ncompatibility constraints, intentional pins/overrides, unresolved advisories, and\nreusable repository-specific procedures. Prefer the existing maintenance document;\notherwise create `docs/dependency-upgrades.md` (or the repository's equivalent)\nonly when there is substantive guidance to preserve. For each constraint, record\nits rationale, upstream advisory/migration/issue link or originating PR, and the\ncondition and check for removing or revisiting it. Do not copy version inventories,\naudit output, validation/preview receipts, or dated run journals into that document.\n\nOn every upgrade, reconcile the existing maintenance document against the final\ndependency graph and checks: update constraints in place, remove resolved entries,\nand link the PR for historical evidence. Keep the root README focused on purpose,\nsetup, supported requirements, and normal usage, with a concise maintenance link\nwhen needed. Keep dependency-maintenance guidance in `AGENTS.md` to a short\nrouting rule and link; do not accumulate upgrade reports in either entrypoint\nor duplicate the maintenance document.\n\nFor shipping, report the branch, reviewed commit/verdict, PR, merge, publish/deploy\nresult, and final checkout state. Keep full logs private; never publish credentials,\nstate, or plan contents in any of these locations.\n"
9
9
  };