@a2f0/agent-tool 0.1.77 → 0.1.78

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
@@ -93,7 +93,8 @@ validation suite, and release procedures.
93
93
  captured screenshots into a website, and the gallery and carousel web
94
94
  components that show them.
95
95
  - [Permissions](docs/permissions.md): which commands run without approval in
96
- Claude Code and Codex, and the dependency commands that enforce it.
96
+ Claude Code, Codex, and Gemini CLI, and the dependency commands that enforce
97
+ it.
97
98
  - [Dependency maintenance](docs/dependency-upgrades.md): active compatibility
98
99
  constraints and the dependency-update workflow.
99
100
  - [Design](docs/design.md) and [extraction history](docs/extraction.md): component
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.77",
3
+ "version": "0.1.78",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
@@ -50,10 +50,15 @@ still differs, report the mismatch rather than deleting arbitrary dependencies.
50
50
  After upgrading agent-tool, run the repository's skill/permission sync commands.
51
51
  For each ownership manifest they do not refresh, run its installer directly:
52
52
  `agent-tool skills install --harness <existing-scope> --apply` for
53
- `.agent-tool-skills.json`, and
54
- `agent-tool permissions install --harness <existing-scope> --apply` for
55
- `.agent-tool-permissions.json`. Preserve each harness scope, and commit the
56
- ownership manifests with any generated files.
53
+ `.agent-tool-skills.json`, and `agent-tool permissions install --apply` for
54
+ `.agent-tool-permissions.json`, which keeps the scope that manifest records.
55
+ Preserve each harness scope, and commit the ownership manifests with any
56
+ generated files. When `all` gains a harness, the install adds that harness's
57
+ rules file, such as `.gemini/policies/agent-tool.toml`; name it in the PR so the
58
+ reviewer sees the new allow rules. A permissions manifest from before scopes
59
+ that records Claude and Codex, what `all` then wrote, gains `all`; when the
60
+ repository kept those two on purpose, install each with `--harness` instead,
61
+ and ask when its guidance does not say.
57
62
  The manifests record the agent-tool version, so every upgrade changes them, even
58
63
  when no skill or rule changed, and `skills check` and `permissions check` fail
59
64
  until the sync records the new version. Hermes reads the shared `.agents/skills`
@@ -32,8 +32,10 @@ function assertCurrentRules(root: string, command: string): void {
32
32
  const recorded = checkRecordedPermissions(root);
33
33
  // The manifest was there a moment ago; fail closed rather than treat its absence as current rules.
34
34
  assert(recorded, `${PERMISSIONS_MANIFEST} disappeared while checking the rules for '${command}'; rerun the command.`);
35
- const stale = recorded.filter(item => item.status !== "unchanged" && item.path !== PERMISSIONS_MANIFEST);
36
- assert(!stale.length, `Permission rules predate the current class of '${command}'; regenerate them with approval (agent-tool permissions install --apply) before running it.`);
35
+ const stale = recorded.changes.filter(item => item.status !== "unchanged" && item.path !== PERMISSIONS_MANIFEST);
36
+ // A generated file outside the recorded harnesses names its own fix, which no install performs alone.
37
+ const fixes = stale.filter(item => item.detail).map(item => ` ${item.path} is ${item.detail}.`).join("");
38
+ assert(!stale.length, `Permission rules predate the current class of '${command}'; regenerate them with approval (${recorded.install}) before running it.${fixes}`);
37
39
  }
38
40
 
39
41
  /** The package directory's or root's `node_modules/.bin/<name>`: an executable regular file inside the checkout. */
package/src/cli.ts CHANGED
@@ -89,9 +89,9 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
89
89
  bun remove <name>... [--cwd <dir>] Remove declared dependencies only
90
90
  bun test [--cwd <dir>] [--log] [-- args...]
91
91
  bun x <executable> [--cwd <dir>] [--log] [-- args...] Installed executables only, never fetched
92
- permissions show [--harness <all|claude|codex>]
93
- permissions install [--harness <all|claude|codex>] [--apply]
94
- permissions check [--harness <all|claude|codex>]
92
+ permissions show [--harness <all|claude|codex|gemini>]
93
+ permissions install [--harness <all|claude|codex|gemini>] [--apply] Without --harness, the recorded scope (docs/permissions.md)
94
+ permissions check [--harness <all|claude|codex|gemini>] Without --harness, the recorded scope
95
95
  images list [target...] JSON files each image target writes
96
96
  images build [target...] [--out <dir>] Render assets/brand/*.svg per agent-tool.json
97
97
  screenshots build [target...] [--out <dir>] [--json] Stage guarded captures and a gallery manifest
@@ -235,19 +235,20 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
235
235
  if (command === "push-gate") return pushGateCommand(args);
236
236
  if (command === "permissions") {
237
237
  const action = args.shift();
238
- usage(action === "show" || action === "install" || action === "check", "Usage: agent-tool permissions <show|install|check> [--harness <all|claude|codex>] [--apply]");
239
- let target = "all", apply = false;
238
+ usage(action === "show" || action === "install" || action === "check", "Usage: agent-tool permissions <show|install|check> [--harness <all|claude|codex|gemini>] [--apply]");
239
+ let target: string | undefined, apply = false;
240
240
  while (args.length) {
241
241
  const flag = args.shift();
242
242
  if (flag === "--apply") { usage(action === "install" && !apply, "--apply applies once, to permissions install."); apply = true; }
243
243
  else if (flag === "--harness") { const value = args.shift(); usage(!!value, "--harness requires a name."); target = value!; }
244
244
  else throw new Error(`Unknown permissions ${action} argument '${flag}'.`);
245
245
  }
246
- if (action === "show") { writeSync(1, showPermissions(process.cwd(), target)); return 0; }
246
+ if (action === "show") { writeSync(1, showPermissions(process.cwd(), target ?? "all")); return 0; }
247
+ // Bare check and install follow the recorded scope, as the push gate does; show defaults to all.
247
248
  if (action === "check") {
248
- const changes = checkPermissions(process.cwd(), target);
249
+ const { harnesses, changes } = checkPermissions(process.cwd(), target);
249
250
  const ok = changes.every(change => change.status === "unchanged");
250
- output({ ok, changes }); return ok ? 0 : 1;
251
+ output({ ok, harnesses, changes }); return ok ? 0 : 1;
251
252
  }
252
253
  output({ applied: apply, changes: installPermissions(process.cwd(), target, apply) }); return 0;
253
254
  }
@@ -115,3 +115,80 @@ export function codexRules(project: CatalogEntry[] = []): string {
115
115
  }
116
116
  return `${lines.join("\n")}\n`;
117
117
  }
118
+
119
+ /**
120
+ * Gemini CLI's approval modes the rules apply in: `default` alone. A workspace allow would
121
+ * outrank plan mode's read-only deny, YOLO allows every command already, and Gemini CLI before
122
+ * 0.63.0 lets an allowed command redirect anywhere unprompted in `autoEdit`, so `autoEdit` keeps
123
+ * the user's own rules. In `default`, Gemini 0.31.0's engine, the first to load the file, already
124
+ * asks for redirection (`shouldDowngradeForRedirection` skips only `autoEdit` and YOLO); CI
125
+ * checks the releases scripts/testing/gemini-conformance.ts pins, from the 0.37.0 floor.
126
+ */
127
+ export const GEMINI_MODES = ["default"] as const;
128
+ /**
129
+ * Gemini CLI accepts priorities 0 to 999 within a tier and lets the first matching rule of a
130
+ * stable sort by priority decide. Every priority stays inside the workspace tier, below user and
131
+ * admin policies; the lowest also lets a project's own workspace rule at any higher priority win.
132
+ */
133
+ const GEMINI_PRIORITY = 0;
134
+
135
+ const regex = (text: string) => text.replace(/[.^$|?*+()[\]{}\\]/g, "\\$&");
136
+ /**
137
+ * What may follow a command name in its JSON encoding, through the closing quote: nothing, or a
138
+ * space and arguments free of shell syntax, for bash and for PowerShell, which Gemini runs on
139
+ * Windows. An argument may not hold a backtick, `$`, `;`, `&`, `|`, `<`, `>`, `(`, `)`, `{`, `}`,
140
+ * or `%`, or a JSON escape other than an escaped quote or backslash, so no raw newline or control
141
+ * character either. PowerShell evaluates `(…)`, `@(…)`, and the values in `@{…}` in an argument,
142
+ * and cmd.exe, which runs a `.cmd` shim, expands `%…%`; `@` alone only splats a variable, so
143
+ * `name@1.2.3` and `@scope/name` stay allowed. A command that holds
144
+ * any of these fails to match as a whole and falls back to Gemini's own checks, as Codex treats
145
+ * such a script as opaque; those checks alone miss nested substitution in some supported releases
146
+ * (docs/dependency-upgrades.md lists which).
147
+ *
148
+ * Gemini's ReDoS guard refuses a pattern in which a `(` has a quantifier character before the
149
+ * next `)` and any later `)` is quantified. So the one quantified group holds no quantifier, an
150
+ * empty alternative stands in for an outer `?`, and groups capture, since the `?` of a `(?:`
151
+ * would trip the guard.
152
+ */
153
+ export const GEMINI_ARGUMENTS = '( (\\\\["\\\\]|[^`$"\\\\;&|<>(){}%])*|)"';
154
+
155
+ /**
156
+ * Gemini CLI policy rules for `.gemini/policies/`: one allow rule per routine command,
157
+ * as a `commandRegex` matched against the command's JSON encoding through its closing quote.
158
+ * Gemini's own `commandPrefix` also ends at an escaped quote, which the shell joins into the
159
+ * same word (`agent-tool bun x vite"-node"` runs `vite-node`), so each regex ends the command
160
+ * name at a space or at the closing quote of the encoding, as Codex's token prefixes do, and
161
+ * then admits only arguments free of shell syntax (GEMINI_ARGUMENTS); a command whose `--apply`
162
+ * form asks gets no rule. Only allow rules are generated, as for Claude and Codex, so other
163
+ * commands keep the user's approval mode and policies, which outrank workspace rules. The rules
164
+ * name their one mode (GEMINI_MODES). One rule per command keeps each pattern far below Gemini's
165
+ * pattern size limits.
166
+ */
167
+ export function geminiPolicy(project: CatalogEntry[] = []): string {
168
+ const lines = [
169
+ "# Managed by agent-tool; regenerate with `agent-tool permissions install --apply`.",
170
+ "# Only routine commands receive allow rules. Other commands keep the user's",
171
+ "# approval mode and policies, which outrank these workspace rules.",
172
+ "# Each command ends at a space or the end of the command, never a quote; its",
173
+ "# arguments hold no backtick, $, ;, &, |, <, >, (, ), {, }, %, or line break, so",
174
+ "# bash or PowerShell syntax falls back to Gemini's own checks; and a command",
175
+ "# whose --apply form asks gets no rule. The rules apply in the default",
176
+ "# approval mode only: plan mode stays read-only, autoEdit keeps the user's rules,",
177
+ "# and YOLO already allows every command. Requires Gemini CLI 0.37.0 or later.",
178
+ ];
179
+ // Capturing groups throughout: see GEMINI_ARGUMENTS for Gemini's ReDoS guard.
180
+ const invocations = `(${INVOCATIONS.map(regex).join("|")})`;
181
+ for (const value of Object.keys(CLASSES) as PermissionClass[]) {
182
+ if (CLASSES[value].decision !== "allow") continue;
183
+ const entries = [...CATALOG, ...project].filter(entry => strictest(entry) === value);
184
+ if (!entries.length) continue;
185
+ lines.push("", `# ${value}: ${CLASSES[value].description}`);
186
+ for (const entry of entries) {
187
+ // A TOML literal string keeps the pattern readable; command names never hold its quote.
188
+ const pattern = `${invocations} ${regex(entry.command)}${GEMINI_ARGUMENTS}`;
189
+ if (pattern.includes("'")) throw new Error(`Cannot write a Gemini rule for '${entry.command}'.`);
190
+ lines.push("[[rule]]", 'toolName = "run_shell_command"', `commandRegex = '${pattern}'`, 'decision = "allow"', `priority = ${GEMINI_PRIORITY}`, `modes = [${GEMINI_MODES.map(quote).join(", ")}]`);
191
+ }
192
+ }
193
+ return `${lines.join("\n")}\n`;
194
+ }
@@ -3,31 +3,47 @@ import { chmodSync, existsSync, lstatSync, mkdirSync, realpathSync, renameSync,
3
3
  import path from "node:path";
4
4
  import { readRegularFile } from "../system/files";
5
5
  import { AGENT_TOOL_VERSION, manifestVersionCheck, validVersion, type CheckStatus } from "../system/manifestVersion";
6
- import { claudePermissions, codexRules, type CatalogEntry, type ClaudePermissions } from "./catalog";
6
+ import { claudePermissions, codexRules, geminiPolicy, type CatalogEntry, type ClaudePermissions } from "./catalog";
7
7
  import { projectCommands } from "./project";
8
8
 
9
9
  export const PERMISSIONS_MANIFEST = ".agent-tool-permissions.json";
10
10
  const CLAUDE_SETTINGS = ".claude/settings.json";
11
- const CODEX_RULES = ".codex/rules/agent-tool.rules";
12
- const HARNESSES = ["claude", "codex"] as const;
11
+ const HARNESSES = ["claude", "codex", "gemini"] as const;
13
12
  type Harness = typeof HARNESSES[number];
13
+ /** Harnesses whose rules are a whole generated file, owned by its recorded hash. */
14
+ type FileHarness = Exclude<Harness, "claude">;
15
+ const GENERATED: Record<FileHarness, { relative: string; render: (project: CatalogEntry[]) => string }> = {
16
+ codex: { relative: ".codex/rules/agent-tool.rules", render: codexRules },
17
+ gemini: { relative: ".gemini/policies/agent-tool.toml", render: geminiPolicy },
18
+ };
14
19
  const hash = (source: string) => createHash("sha256").update(source).digest("hex");
15
20
 
21
+ interface OwnedFile { file: string; sha256: string }
22
+ /** The harnesses installs asked for: `all`, which follows every harness it covers, or those single installs added up. */
23
+ type Scope = "all" | Harness[];
16
24
  /**
17
- * What an install owns and the agent-tool version that wrote it. Manifests from releases before
18
- * the version field lack it and stay readable; the field is additive, so `schemaVersion` stays 1.
25
+ * What an install owns, the scope it was asked for, and the agent-tool version that wrote it.
26
+ * Manifests from releases before the version or scope field lack it and stay readable; the
27
+ * fields are additive, so `schemaVersion` stays 1.
19
28
  */
20
- interface Manifest { schemaVersion: 1; agentToolVersion?: string; claude?: ClaudePermissions; codex?: { file: string; sha256: string } }
29
+ interface Manifest { schemaVersion: 1; agentToolVersion?: string; scope?: Scope; claude?: ClaudePermissions; codex?: OwnedFile; gemini?: OwnedFile }
21
30
  /** One reading of the manifest: its bytes, none without one, and its parsed contents. */
22
31
  interface Recorded { raw?: string; manifest: Manifest }
23
- export interface PermissionChange { path: string; status: "create" | "update" | "unchanged" }
32
+ /** A scope as the output shows it: `all`, the harnesses a list or an earlier manifest covers, or null for none. */
33
+ type ScopeView = "all" | Harness[] | null;
34
+ export interface PermissionChange { path: string; status: "create" | "update" | "unchanged"; scope?: { from: ScopeView; to: ScopeView } }
24
35
  /** One entry per generated file, then the manifest's own entry with its recorded and running versions. */
25
- export interface PermissionCheck { path: string; status: CheckStatus; recordedVersion?: string | null; currentVersion?: string }
36
+ export interface PermissionCheck { path: string; status: CheckStatus; recordedVersion?: string | null; currentVersion?: string; detail?: string }
37
+
38
+ /** A `--harness` value: `all` or one known harness. */
39
+ function harnessTarget(target: string): Harness | "all" {
40
+ if (target === "all" || (HARNESSES as readonly string[]).includes(target)) return target as Harness | "all";
41
+ throw new Error(`Unknown permissions harness '${target}'; use all, claude, codex, or gemini.`);
42
+ }
26
43
 
27
44
  export function harnesses(target: string): Harness[] {
28
- if (target === "all") return [...HARNESSES];
29
- if (!(HARNESSES as readonly string[]).includes(target)) throw new Error(`Unknown permissions harness '${target}'; use all, claude, or codex.`);
30
- return [target as Harness];
45
+ const parsed = harnessTarget(target);
46
+ return parsed === "all" ? [...HARNESSES] : [parsed];
31
47
  }
32
48
 
33
49
  function destination(root: string, relative: string): string {
@@ -58,10 +74,19 @@ function readManifest(root: string): Recorded {
58
74
  const parsed: unknown = JSON.parse(raw);
59
75
  const object = (item: unknown): item is Record<string, unknown> => !!item && typeof item === "object" && !Array.isArray(item);
60
76
  const strings = (items: unknown) => Array.isArray(items) && items.every(item => typeof item === "string");
61
- // Present ownership entries must be well formed; a falsy one must not drop its harness from the check.
77
+ const owned = (item: unknown) => object(item) && typeof item.file === "string" && typeof item.sha256 === "string" && /^[a-f0-9]{64}$/.test(item.sha256);
78
+ const scope = (item: unknown) => item === "all" || (Array.isArray(item) && item.length > 0 && item.every(harness => (HARNESSES as readonly unknown[]).includes(harness)));
79
+ // A harness a newer release added is not corruption: name it and the release that wrote it.
80
+ if (object(parsed) && Array.isArray(parsed.scope)) {
81
+ const unknown = parsed.scope.filter(harness => typeof harness === "string" && !(HARNESSES as readonly string[]).includes(harness));
82
+ const writer = validVersion(parsed.agentToolVersion) ? ` (${parsed.agentToolVersion})` : "";
83
+ if (unknown.length) throw new Error(`Managed permissions manifest scope names ${unknown.map(name => JSON.stringify(name)).join(", ")}, which this agent-tool release does not know; use the release that wrote it${writer}.`);
84
+ }
85
+ // Present ownership and scope entries must be well formed; a falsy one must not drop a harness from the check.
62
86
  if (!object(parsed) || parsed.schemaVersion !== 1
87
+ || (parsed.scope !== undefined && !scope(parsed.scope))
63
88
  || (parsed.claude !== undefined && !(object(parsed.claude) && strings(parsed.claude.allow) && strings(parsed.claude.ask)))
64
- || (parsed.codex !== undefined && !(object(parsed.codex) && typeof parsed.codex.file === "string" && typeof parsed.codex.sha256 === "string" && /^[a-f0-9]{64}$/.test(parsed.codex.sha256)))) throw new Error("Invalid managed permissions manifest.");
89
+ || (Object.keys(GENERATED) as FileHarness[]).some(harness => parsed[harness] !== undefined && !owned(parsed[harness]))) throw new Error("Invalid managed permissions manifest.");
65
90
  const { agentToolVersion, ...value } = parsed as unknown as Manifest;
66
91
  // The version is provenance, not ownership: an unusable one counts as none, which the check reports and the install replaces.
67
92
  return { raw, manifest: { ...value, ...(validVersion(agentToolVersion) ? { agentToolVersion } : {}) } };
@@ -98,7 +123,7 @@ interface Pending { harness: Harness; relative: string; file: string; contents:
98
123
 
99
124
  function pending(root: string, targets: Harness[], manifest: Manifest, project: CatalogEntry[]): Pending[] {
100
125
  return targets.map(harness => {
101
- const relative = harness === "claude" ? CLAUDE_SETTINGS : CODEX_RULES;
126
+ const relative = harness === "claude" ? CLAUDE_SETTINGS : GENERATED[harness].relative;
102
127
  const file = destination(root, relative);
103
128
  // One read of each destination serves both the merge and the comparison.
104
129
  const read = readRegularFile(file);
@@ -107,25 +132,106 @@ function pending(root: string, targets: Harness[], manifest: Manifest, project:
107
132
  let contents: string;
108
133
  if (harness === "claude") contents = `${JSON.stringify(mergedSettings(parseSettings(current), manifest.claude, claudePermissions(project)), null, 2)}\n`;
109
134
  else {
110
- contents = codexRules(project);
111
- if (current !== undefined && current !== contents && hash(current) !== manifest.codex?.sha256) throw new Error(`Locally edited or unmanaged rules: ${relative}. Preserve them before installing.`);
135
+ contents = GENERATED[harness].render(project);
136
+ if (current !== undefined && current !== contents && hash(current) !== manifest[harness]?.sha256) throw new Error(`Locally edited or unmanaged rules: ${relative}. Preserve them before installing.`);
112
137
  }
113
138
  return { harness, relative, file, contents, status: current === contents ? "unchanged" : current === undefined ? "create" : "update" };
114
139
  });
115
140
  }
116
141
 
117
- /** Each generated file's change, then the manifest's, which every new agent-tool release updates. */
118
- export function installPermissions(rootDir: string, target: string, apply = false): PermissionChange[] {
142
+ /**
143
+ * The harnesses a manifest's installs asked for: none yet, `all`, a recorded list, or, for a
144
+ * manifest from a release before the scope field, the harnesses its entries record. Lists are in
145
+ * harness order without repeats.
146
+ */
147
+ export type ScopeState =
148
+ | { status: "none" }
149
+ | { status: "all" }
150
+ | { status: "listed"; harnesses: Harness[] }
151
+ | { status: "inferred"; harnesses: Harness[] };
152
+
153
+ /**
154
+ * The manifest's scope state. An inferred scope, from a manifest written before the field, covers
155
+ * the harnesses it records; a bare install widens it to `all` only when those are Claude and Codex,
156
+ * what `all` wrote then (scopeTransition), and a bare `check` checks the recorded harnesses alone.
157
+ */
158
+ export function scopeState(manifest: Pick<Manifest, "scope" | Harness>): ScopeState {
159
+ const { scope } = manifest;
160
+ if (scope === "all") return { status: "all" };
161
+ // A list also covers every harness the manifest records, so no recorded rules fall out of the check;
162
+ // a release before scopes keeps the field while an install adds an entry, as after a rollback.
163
+ if (scope !== undefined) return { status: "listed", harnesses: HARNESSES.filter(harness => scope.includes(harness) || manifest[harness] !== undefined) };
164
+ const installed = HARNESSES.filter(harness => manifest[harness] !== undefined);
165
+ return installed.length ? { status: "inferred", harnesses: installed } : { status: "none" };
166
+ }
167
+
168
+ /** What `--harness all` wrote before manifests recorded their scope and `all` covered Gemini. */
169
+ const EARLIER_ALL: readonly Harness[] = ["claude", "codex"];
170
+
171
+ /**
172
+ * What moves a scope: an install of `all`, of one harness, or, for a bare install, of the recorded
173
+ * scope, which keeps a list and the harnesses of an earlier manifest that `all` did not write, and
174
+ * installs `all` otherwise.
175
+ */
176
+ export type ScopeEvent = { type: "install"; target: Harness | "all" | "recorded" };
177
+
178
+ /**
179
+ * One install's transition: an `all` scope, a list already naming the harness, or a list a bare
180
+ * install regenerates stays the same state; a bare install lists an earlier manifest's harnesses
181
+ * unless they are what `all` then wrote; installing `all`, or the recorded scope of such a manifest
182
+ * or none, gives `all`; a single install adds its harness to the list or inferred harnesses, so a
183
+ * later push gate checks each.
184
+ */
185
+ export function scopeTransition(state: ScopeState, event: ScopeEvent): Extract<ScopeState, { status: "all" | "listed" }> {
186
+ switch (state.status) {
187
+ case "all":
188
+ return state;
189
+ case "none":
190
+ case "listed":
191
+ case "inferred": {
192
+ if (event.target === "recorded") {
193
+ if (state.status === "listed") return state;
194
+ if (state.status === "inferred" && !EARLIER_ALL.every(harness => state.harnesses.includes(harness))) return { status: "listed", harnesses: state.harnesses };
195
+ return { status: "all" };
196
+ }
197
+ if (event.target === "all") return { status: "all" };
198
+ if (state.status === "listed" && state.harnesses.includes(event.target)) return state;
199
+ const previous = state.status === "none" ? [] : state.harnesses;
200
+ return { status: "listed", harnesses: HARNESSES.filter(harness => harness === event.target || previous.includes(harness)) };
201
+ }
202
+ default: {
203
+ const unknown: never = state;
204
+ return unknown;
205
+ }
206
+ }
207
+ }
208
+
209
+ /** The harnesses a push gate checks for a scope state: every current one for `all` or none. */
210
+ function scopeHarnesses(state: ScopeState): Harness[] {
211
+ return state.status === "all" || state.status === "none" ? [...HARNESSES] : state.harnesses;
212
+ }
213
+
214
+ /**
215
+ * Each generated file's change, then the manifest's, which every new agent-tool release updates.
216
+ * Without a target it installs the scope scopeTransition gives a bare install: a list, or an earlier
217
+ * manifest recording harnesses other than Claude and Codex, keeps its harnesses, while `all`, an
218
+ * earlier manifest recording Claude and Codex, or none install `all`, so they gain new harnesses.
219
+ */
220
+ export function installPermissions(rootDir: string, target?: string, apply = false): PermissionChange[] {
119
221
  const root = realpathSync(rootDir);
120
222
  const { raw: recorded, manifest } = readManifest(root);
121
223
  const project = projectCommands(root);
122
- const changes = pending(root, harnesses(target), manifest, project);
224
+ const event: ScopeEvent = { type: "install", target: target === undefined ? "recorded" : harnessTarget(target) };
225
+ const scope = scopeTransition(scopeState(manifest), event);
226
+ // A single install writes its harness alone; `all` and the recorded scope write every harness the new scope covers.
227
+ const targets = event.target === "all" || event.target === "recorded" ? scopeHarnesses(scope) : [event.target];
228
+ const changes = pending(root, targets, manifest, project);
123
229
  // Recording the version makes every upgrade change the manifest, so a committed sync is visible.
124
- const { schemaVersion: _schema, agentToolVersion: _version, ...owned } = manifest;
125
- const next: Manifest = { schemaVersion: 1, agentToolVersion: AGENT_TOOL_VERSION, ...owned };
230
+ const { schemaVersion: _schema, agentToolVersion: _version, scope: _scope, ...owned } = manifest;
231
+ const next: Manifest = { schemaVersion: 1, agentToolVersion: AGENT_TOOL_VERSION, scope: scope.status === "all" ? "all" : scope.harnesses, ...owned };
126
232
  for (const change of changes) {
127
233
  if (change.harness === "claude") next.claude = claudePermissions(project);
128
- else next.codex = { file: change.relative, sha256: hash(change.contents) };
234
+ else next[change.harness] = { file: change.relative, sha256: hash(change.contents) };
129
235
  }
130
236
  const manifestFile = destination(root, PERMISSIONS_MANIFEST), contents = `${JSON.stringify(next, null, 2)}\n`;
131
237
  const manifestStatus: PermissionChange["status"] = recorded === contents ? "unchanged" : recorded === undefined ? "create" : "update";
@@ -134,54 +240,105 @@ export function installPermissions(rootDir: string, target: string, apply = fals
134
240
  for (const change of changes) if (change.status !== "unchanged") atomicWrite(change.file, change.contents);
135
241
  if (manifestStatus !== "unchanged") atomicWrite(manifestFile, contents);
136
242
  }
137
- return [...changes.map(({ relative, status }) => ({ path: relative, status })), { path: PERMISSIONS_MANIFEST, status: manifestStatus }];
243
+ // An existing manifest whose scope changes says so, since a widening adds a harness's allow rules.
244
+ // A recorded scope shows as written, so a list that left out a recorded harness shows it added;
245
+ // the comparison ignores order, which a hand-edited list may change.
246
+ const view = (state: ScopeState): ScopeView => (state.status === "all" ? "all" : state.status === "none" ? null : state.harnesses);
247
+ const ordered = (value: ScopeView): ScopeView => (Array.isArray(value) ? HARNESSES.filter(harness => value.includes(harness)) : value);
248
+ const from = manifest.scope ?? view(scopeState(manifest)), to = view(scope);
249
+ const widened = recorded !== undefined && JSON.stringify(ordered(from)) !== JSON.stringify(to) ? { scope: { from, to } } : {};
250
+ return [...changes.map(({ relative, status }) => ({ path: relative, status })), { path: PERMISSIONS_MANIFEST, status: manifestStatus, ...widened }];
251
+ }
252
+
253
+ /**
254
+ * Generated rule files outside the checked harnesses, which their harness still loads: a scope
255
+ * check reports each as `unmanaged`, so narrowing a scope cannot leave stale rules unchecked.
256
+ * Claude's settings file holds the user's own settings too, so only whole generated files count.
257
+ */
258
+ function outsideScope(root: string, checked: Harness[]): PermissionCheck[] {
259
+ // Only a missing file is absent; any other error would hide a file the check could not read.
260
+ const present = (file: string) => {
261
+ try {
262
+ lstatSync(file);
263
+ return true;
264
+ } catch (error) {
265
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
266
+ throw error;
267
+ }
268
+ };
269
+ return (Object.keys(GENERATED) as FileHarness[])
270
+ .filter(harness => !checked.includes(harness) && present(path.join(root, GENERATED[harness].relative)))
271
+ // Every checked set covers the recorded harnesses, so such a file is unrecorded: an install records it only when it
272
+ // already matches the current rules and otherwise refuses to overwrite it, so deleting it is the fix that always works.
273
+ .map(harness => ({ path: GENERATED[harness].relative, status: "unmanaged", detail: `not recorded in the manifest, though ${harness} loads it; delete it, then run agent-tool permissions install --harness ${harness} --apply if ${harness} should keep rules` }));
138
274
  }
139
275
 
140
- /** Each generated file, then the manifest's own entry, against one reading of the manifest. */
141
- function checks(root: string, targets: Harness[], { raw, manifest }: Recorded): PermissionCheck[] {
276
+ /** Each generated file, then for a scope check any outside it, then the manifest's own entry, against one reading of the manifest. */
277
+ function checks(root: string, targets: Harness[], { raw, manifest }: Recorded, scope = false): PermissionCheck[] {
142
278
  const project = projectCommands(root);
143
279
  const files = pending(root, targets, manifest, project).map((change): PermissionCheck => {
144
280
  if (change.status === "create") return { path: change.relative, status: "missing" };
145
281
  if (change.status === "update") return { path: change.relative, status: "outdated" };
146
- const managed = change.harness === "claude" ? JSON.stringify(manifest.claude) === JSON.stringify(claudePermissions(project)) : manifest.codex?.sha256 === hash(change.contents);
282
+ const managed = change.harness === "claude" ? JSON.stringify(manifest.claude) === JSON.stringify(claudePermissions(project)) : manifest[change.harness]?.sha256 === hash(change.contents);
147
283
  return { path: change.relative, status: managed ? "unchanged" : "unmanaged" };
148
284
  });
149
- return [...files, manifestVersionCheck(PERMISSIONS_MANIFEST, raw !== undefined, manifest.agentToolVersion)];
285
+ return [...files, ...(scope ? outsideScope(root, targets) : []), manifestVersionCheck(PERMISSIONS_MANIFEST, raw !== undefined, manifest.agentToolVersion)];
150
286
  }
151
287
 
152
- /** Read-only CI gate: generated rules are current, recorded as managed, and by the running version. */
153
- export function checkPermissions(rootDir: string, target: string): PermissionCheck[] {
288
+ /**
289
+ * Read-only CI gate, `permissions check`: generated rules are current, recorded as managed, and by
290
+ * the running version, for the named harnesses, or without a target the scope the manifest records,
291
+ * as the push gate checks it (every harness without a manifest or a recorded one).
292
+ */
293
+ export function checkPermissions(rootDir: string, target?: string): { harnesses: Harness[]; changes: PermissionCheck[] } {
154
294
  const root = realpathSync(rootDir);
155
- return checks(root, harnesses(target), readManifest(root));
295
+ const recorded = readManifest(root);
296
+ const checked = target === undefined ? scopeHarnesses(scopeState(recorded.manifest)) : harnesses(target);
297
+ return { harnesses: checked, changes: checks(root, checked, recorded, target === undefined) };
156
298
  }
157
299
 
158
300
  /**
159
- * The push gate's check, or null without a manifest: the `--harness` the rules were installed
160
- * for, from the manifest, and its check, from one reading of the manifest.
301
+ * The push gate's check, or null without a manifest: the harnesses the manifest's scope covers
302
+ * and their check, from one reading of the manifest. `all`, and a manifest recording no harness,
303
+ * are checked against every harness `all` covers now, so they fail until the install adds a new one.
161
304
  */
162
- export function checkInstalledPermissions(rootDir: string): { harness: string; changes: PermissionCheck[] } | null {
305
+ export function checkInstalledPermissions(rootDir: string): { harnesses: Harness[]; changes: PermissionCheck[] } | null {
163
306
  const root = realpathSync(rootDir);
164
307
  const recorded = readManifest(root);
165
308
  if (recorded.raw === undefined) return null;
166
- const { claude, codex } = recorded.manifest;
167
- const harness = claude && !codex ? "claude" : codex && !claude ? "codex" : "all";
168
- return { harness, changes: checks(root, harnesses(harness), recorded) };
309
+ const checked = scopeHarnesses(scopeState(recorded.manifest));
310
+ return { harnesses: checked, changes: checks(root, checked, recorded, true) };
169
311
  }
170
312
 
171
313
  /**
172
314
  * `bun x`'s check, or null without a manifest: only the harnesses whose rules the manifest
173
- * records, none when it records none, then the manifest's own entry, from one reading of it.
174
- * Rules no manifest records are the user's by the installer's ownership contract (an install
175
- * keeps them), so they are not judged here, as before the version field.
315
+ * records, none when it records none, then any generated rules file outside them, which its
316
+ * harness still loads, then the manifest's own entry, from one reading of it. Other rules no
317
+ * manifest records are the user's by the installer's ownership contract (an install keeps
318
+ * them), so they are not judged here, as before the version field.
176
319
  */
177
- export function checkRecordedPermissions(rootDir: string): PermissionCheck[] | null {
320
+ export function checkRecordedPermissions(rootDir: string): { changes: PermissionCheck[]; install: string } | null {
178
321
  const root = realpathSync(rootDir);
179
322
  const recorded = readManifest(root);
180
323
  if (recorded.raw === undefined) return null;
181
- return checks(root, HARNESSES.filter(harness => recorded.manifest[harness] !== undefined), recorded);
324
+ return { changes: checks(root, HARNESSES.filter(harness => recorded.manifest[harness] !== undefined), recorded, true), install: installCommands(recorded.manifest) };
325
+ }
326
+
327
+ /**
328
+ * The installs that regenerate a manifest's rules: the bare install, whose scope scopeTransition
329
+ * gives. It keeps a listed or `all` scope, and widens a manifest that records nothing, or one from
330
+ * before scopes that records Claude and Codex, to `all`, since such a pair came from an `all`
331
+ * install. That widening adds the harnesses `all` gained, so one install per recorded harness
332
+ * follows as the choice that keeps only them.
333
+ */
334
+ function installCommands(manifest: Manifest): string {
335
+ const state = scopeState(manifest), all = "agent-tool permissions install --apply";
336
+ if (state.status !== "inferred" || scopeTransition(state, { type: "install", target: "recorded" }).status !== "all") return all;
337
+ const each = state.harnesses.map(harness => `agent-tool permissions install --harness ${harness} --apply`).join(", then ");
338
+ return `${all}, or to keep only the recorded harnesses, ${each}`;
182
339
  }
183
340
 
184
341
  export function showPermissions(rootDir: string, target: string): string {
185
342
  const project = projectCommands(realpathSync(rootDir));
186
- return harnesses(target).map(harness => harness === "claude" ? `${JSON.stringify({ permissions: claudePermissions(project) }, null, 2)}\n` : codexRules(project)).join("\n");
343
+ return harnesses(target).map(harness => harness === "claude" ? `${JSON.stringify({ permissions: claudePermissions(project) }, null, 2)}\n` : GENERATED[harness].render(project)).join("\n");
187
344
  }
@@ -14,7 +14,7 @@ export const BUNDLED_SKILLS: Readonly<Record<string, string>> = {
14
14
  "space-cleanup": "---\nname: space-cleanup\ndescription: Free disk space safely in a repository, across a matrix workspace and its checkouts, or in this machine's developer caches, by removing only regenerable, git-ignored output after a dry run. Use when the disk is low, `bun run health` asks for space, a command fails with ENOSPC, or the user asks to clean up space; not for deleting clones, branches, or anyone's work.\n---\n\n# Space Cleanup\n\nFree space by removing what a command can rebuild, never what a person made.\nMeasure first, remove the cheapest tier that frees enough, and report what\nwas freed from the volume's real free space, not from the estimate.\n\n## Run it\n\n`agent-tool space` does the work; run the repository's pinned agent-tool\n(`bun run agent-tool space` or `node_modules/.bin/agent-tool space`). It is a\ndry run until `--apply`.\n\n- In a repository: `agent-tool space [path...] [flags]`. With no paths it\n covers only the repository holding the working directory; each path names\n the repository holding it.\n- From a matrix workspace (`matrix.json` beside `checkouts/`):\n `agent-tool space [checkout...] [flags]`. With no names it covers the\n workspace and every checkout in `checkouts/`; names are checkout names or\n `owner/name`.\n- If the pinned agent-tool predates the command, run\n `bunx --bun @a2f0/agent-tool@latest space`.\n\nCaches are always included; each other flag adds its own tier independently:\n\n| Flag | Removes | Cost to restore |\n| --- | --- | --- |\n| (default) | Caches: `.turbo`, `.parcel-cache`, `.eslintcache`, `.stylelintcache`, `coverage`, `.nyc_output`, test reports (`test-results`, `playwright-report`, `blob-report`), Python caches (`__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache`), `node_modules/.cache` and `.vite`, `.next/cache`, `.wrangler/tmp` | Next run is slower |\n| `--builds` | Build output: `dist`, `build`, `out`, `.next`, `.nuxt`, `.output`, `.svelte-kit`, `.expo`, `.gradle`, `.build`, `DerivedData`, Rust `target`, `*.tsbuildinfo` | The repository's build |\n| `--deps` | `node_modules`, `.venv`, CocoaPods `Pods`, `vendor/bundle` | The repository's documented install |\n| `--machine` | Xcode DerivedData (not its `SourcePackages` clones), `brew cleanup`, Bun and npm caches, `pnpm store prune` | Re-downloads and rebuilds |\n\n`--json` gives agents the same report, and the command exits 1 when a\nrepository could not be scanned or a removal failed, 2 when it cannot run at\nall (an unknown option, or processes that cannot be listed).\n`--include-busy` cleans repositories other processes are working in; use it\nonly after confirming those processes are your own or finished. It never\napplies to `--machine` items, which always wait for running installs and Xcode\nbuilds.\n\n## Procedure\n\n1. Check the volume: `df -h .` (on macOS, `df -h /System/Volumes/Data`). Note\n how much the task needs; matrix sweeps want 50 GiB free.\n2. Run the dry run with `--builds --deps --machine` to see every tier's size,\n then choose the cheapest set of tiers that frees enough. Default caches\n alone are always fine to apply.\n3. Apply with only the chosen flags plus `--apply`. Read the `Free: before ->\n after` line; APFS clones and hard links mean freed space can be far less\n than the listed sizes, and Time Machine local snapshots can hold it until\n macOS thins them.\n4. After `--deps`, reinstall dependencies in each cleaned repository that will\n be used next, with its documented setup, so hooks and `status` keep\n working. Deleting `node_modules` also deletes the pinned agent-tool, so\n where setup runs `bun run agent-tool bun install`, first bootstrap with the\n repository's pinned Bun: `bun install --frozen-lockfile`.\n After `--builds`, nothing is needed: the next build regenerates output.\n5. Report the before and after free space, the tiers applied, repositories\n skipped as busy, and the `review` items from `--machine` with their sizes,\n so the user can decide about them.\n\n## Safety rules\n\nThe command enforces these; keep them when cleaning by hand:\n\n- Remove a repository path only when git reports it ignored, nothing under it\n is tracked (rechecked just before removal), its name is on the tier's list,\n nothing under it is a repository, `.env` file, `.secrets`, or SQLite\n database, and neither it nor any parent inside the repository is a symlink. Untracked files that are not ignored\n belong to someone: never remove them.\n- Never run `git clean` (`-X` included), `rm -rf` on a whole ignored tree, or\n delete `.env*`, `.secrets`, `.wrangler/state`, local databases, or anything\n under `../matrix-secrets`.\n- Skip a repository another process is working in (a dev server, a test run,\n another agent session). Idle shells and the session running the command do\n not count. When processes cannot be listed, the command stops instead of\n guessing.\n- Never delete clones, worktrees, branches, stashes, Docker data, Gradle\n caches, simulator devices (unavailable ones included: they keep app data),\n or iOS DeviceSupport on your own: the `--machine`\n report lists the large ones as `review` for the user to decide.\n- Package caches wait while an install runs, and DerivedData waits for Xcode.\n- In a matrix workspace, cleaning ignored output does not change any\n checkout's git state, so it is not a sweep and needs no ledger; a checkout's\n `status` need not be `ready`.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill at `skills/space-cleanup/` and\nthe command at `src/space/`, with its tests beside it; `agent-tool skills\ninstall --apply` installs it in each adopting repository. Change it there,\nnever in an installed copy.\n",
15
15
  "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, and reports\n`behind: true` when the live base has moved past the head. A moved base alone\nneeds no integration: integrate, validate, review, and push again only when\nGitHub reports a conflict, when `versions check` fails against the live base,\nor when the repository sets `merge.requireStrictBaseFreshness`. Under that\npolicy the wait stops early at `behind: true`; cancel that head's runs with\n`agent-tool pr cancel-runs --head <reviewed-head>` first. Run\n`agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` immediately\nbefore merging. It checks local and PR identity, that the head contains the\nreviewed base, conflicts and merge readiness, explicit version policy against\nthe live base, configured strict rulesets, and passing checks; under the strict\npolicy the live base must also equal the reviewed one. If an identity changed,\nrefresh, integrate, validate, and review again; a new HEAD that\n`agent-tool review carry <reviewed-head> <new-head>` accepts keeps the earlier\nclean review. Read unresolved feedback with `pr threads list` and follow\nproject 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,\nso a base can move between preflight and merge; without the strict policy that\nis accepted, and a break the combination causes is repaired on the base. 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, with `agent-tool repo cleanup <PR-number> <reviewed-head>\n--apply` rather than raw `git branch -D`. Report the PR and merge result.\n",
16
16
  "take-screenshots": "---\nname: take-screenshots\ndescription: Capture a repository's app screenshots once into the shared matrix-artifacts store, so every clone builds and deploys the newest captures, and check a capture's provenance before a deploy. Use when asked to take, refresh, or check screenshots, before deploying a site or store listing that shows them, or when adding screenshot capture to a repository.\n---\n\n# Take Screenshots\n\nScreenshots are captured once, in any clone, into the shared store's\n`matrix-artifacts/<project>/screenshots`, beside the matrix workspace (or\nbeside the clone outside one). Every clone of the repository links its\ngitignored `.screenshots` there, so a website deploy or\nstore upload in another clone publishes the same, newest captures without\nrecapturing. Brand images are not part of this: they render from\n`assets/brand/*.svg` in each clone.\n\n## Run it\n\n`agent-tool screenshots status|link|capture` does the work; run the\nrepository's pinned agent-tool (`bun run agent-tool screenshots ...` or\n`node_modules/.bin/agent-tool screenshots ...`). `link` and `capture` are dry\nruns until `--apply`; `--json` gives agents the report.\n\n- From any clone: `agent-tool screenshots <command>` covers that repository.\n- From a matrix workspace: `agent-tool screenshots <command> [checkout...]`;\n with no names it covers every checkout that captures.\n- If the pinned agent-tool predates these commands, run\n `bunx --bun @a2f0/agent-tool@latest screenshots <command>`.\n\n| Command | Does |\n| --- | --- |\n| `status [repo...] [--all]` | Link state of each clone and its newest capture relative to HEAD |\n| `link [repo...] [--all] [--apply] [--supersede]` | Point `.screenshots` at the store; moves an existing capture into an empty store, or with `--supersede` to `<project>/superseded/` |\n| `capture [repo] [--apply] [--allow-dirty] [-- args...]` | Once its checks pass, link every clone of the store's projects that has no `.screenshots`, then run the repository's `screenshots` package script under the project lock and record `capture.json` |\n\n`--all` selects every clone on this machine whose project the store already\nholds, beside the store or in a matrix workspace's checkouts, worktrees\nincluded: `link --all --apply` links them all in one run.\n\n`MATRIX_ARTIFACTS_DIR` overrides the store location, and `--project <name>`\nnames the namespace of a repository without a GitHub origin. `status` exits 1\nwhile a selected clone is not linked, `link` while one is blocked, and an\napplied `capture` when it did not finish `complete`; each exits 2 when it\ncannot run at all.\n\n## Procedure\n\n1. `status` first. If the clone is not `linked`, run `link`, then\n `link --apply`; `capture` links a clone with no `.screenshots` itself, and\n `status --all` or `link --all` covers every clone on this machine. A\n `blocked` result names what a person must decide (two\n different captures: compare their dates and commits, and if the store's is\n newer rerun with `--supersede`, a link that points elsewhere, a `.screenshots/` ignore\n pattern that needs its trailing slash removed in a PR).\n2. Decide whether to capture. If the newest capture is `complete`, `merged`,\n and no screens changed since its commit, reuse it: that is the point of the\n store. Recapture after UI, seed data, or capture-code changes, after a\n `failed` capture, or when asked.\n3. Commit first: capture refuses a dirty tree, because the shared store would\n publish uncommitted work. `--allow-dirty` is for a local-only look: it marks the\n capture `dirty`, which builds refuse, so recapture from a commit before\n anyone deploys.\n4. Read the repository's capture docs for prerequisites (simulators, Maestro,\n Playwright browsers, seed data, mise-pinned tools). Maestro drives one\n device at a time on this machine: check for a running `maestro` first.\n5. Run `capture` as a dry run, then with `--apply` through output capture\n (`agent-tool run --label screenshots -- agent-tool screenshots capture\n --apply`, with the repository's pinned agent-tool for both). Captures take\n minutes; run them in the background and do not start a second one for the\n same project (the lock refuses it).\n6. Verify the result, not just the exit code: `status` shows `complete` at your\n commit, and spot-check a few images (open them; check light and dark, each\n layout, and the expected dimensions).\n7. Report the capture's commit, whether it was partial (`args`), and which\n clones see it. Before a deploy, quote `status` for the deploying clone.\n\n## Rules\n\n- Never run a repository's `screenshots` package script directly for a shared\n capture; the lock and `capture.json` keep clones from publishing a partial\n or concurrent capture.\n- Never commit screenshots, copy them into a repository, or delete the store.\n Never remove `.screenshots` itself; capture code clears files inside it.\n- Builds and deploys never capture. `agent-tool screenshots build`, which\n stages screenshots into a website, reads `.screenshots/capture.json` before\n and after copying, and refuses `running`, `failed`, `incomplete`, or `dirty`\n captures and a record that changed meanwhile.\n- Before a deploy that publishes screenshots, run `status` and report the\n capture's commit; recapture only when the screens it shows changed since.\n\n## Adding capture to a repository\n\nFollow `references/adding-capture.md`: the package script, ignore pattern, and\noutput layout every repository shares, and the Playwright (web) and Maestro\n(native) patterns tearleads and nc use. In a matrix workspace, its audit checks\nit with `bun run audit --rule screenshots-store`.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill at `skills/take-screenshots/`\nand the commands at `src/screenshots/store/`, with their tests beside them;\n`agent-tool skills install --apply` installs it in each adopting repository.\nThe store's layout and record are described in its `docs/screenshots.md`.\nChange them there, never in an installed copy.\n",
17
- "update-dependencies": "---\nname: update-dependencies\ndescription: Update dependencies or update everything in a repository, including runtimes, tools, and CI pins, with compatibility checks and safe previews; 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## Checkout setup\n\nThis shared workflow also handles natural-language requests to \"update everything\".\nIf the repository owns an `update-everything` wrapper, read and follow its extra\nrequirements; do not create an alias or overwrite that skill. The workflow works\nfrom a standalone checkout with no workspace coordinator.\n\nAfter a fetch, branch integration, or dependency pin change, check that the local\n`agent-tool --version` matches the repository's declared pin before trusting its\ncommands or generated skills. A stale CLI can reject newer configuration keys.\nAfter screening install scripts and hooks as below, run the documented frozen\ninstall with the repository's pinned runtime. For Bun projects, an already working\nCLI can run `agent-tool bun install`; if it is missing or cannot parse the new\nconfig, run the documented package-manager install directly. A known working\nexecutable may capture it with `agent-tool --repo <checkout> run --label setup --\n<install-command> [args...]`. Do not fetch an unpinned CLI, alter global tools, or\nassume a sibling workspace exists. Verify the installed version afterward; if it\nstill differs, report the mismatch rather than deleting arbitrary dependencies.\n\nAfter upgrading agent-tool, run the repository's skill/permission sync commands.\nFor each ownership manifest they do not refresh, run its installer directly:\n`agent-tool skills install --harness <existing-scope> --apply` for\n`.agent-tool-skills.json`, and\n`agent-tool permissions install --harness <existing-scope> --apply` for\n`.agent-tool-permissions.json`. Preserve each harness scope, and commit the\nownership manifests with any generated files.\nThe manifests record the agent-tool version, so every upgrade changes them, even\nwhen no skill or rule changed, and `skills check` and `permissions check` fail\nuntil the sync records the new version. Hermes reads the shared `.agents/skills`\nin a trusted project; the installer does not grant trust. If discovery is\nunavailable, read those files directly rather than silently using a stale global\ncopy.\n\n## Nonblocking execution\n\nUse the harness's managed background execution for long finite checks, reviews,\npush hooks, CI waits, and release verification; request completion notification\nwhen available and retain its process handle plus agent-tool's log/receipt path.\nRun `run-group` and reviews directly so their reports remain visible. A started\nprocess is not a passed check: read its final status and required evidence before\nshipping, and do not repeatedly poll when completion events are available.\nWithout harness background support, `proc start --label <name> -- agent-tool run\n--label <check> -- <command> [args...]` records the outer process and captures\nits output; inspect `proc list` and `logs` plus the inner run receipt to establish\ncompletion and exit status. An exited process record alone does not prove success.\nUse `proc stop`/`teardown` for owned leftovers; never stop another session's work.\nThese commands need no matrix workspace or global configuration change.\n\nKeep independent compatibility groups moving while a producer release or an\nexternal gate is pending. Only final adoption of that exact published release\nmust wait. Bound CPU/process-heavy concurrency to the machine's available budget;\na failed full suite needs diagnosis and a full-scope rerun, not larger timeouts,\nfewer assertions, or a focused retry presented as suite recovery. Background\nexecution never bypasses an approval, a deployment preview, or exact-head review.\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. For existing Bun catalog entries use\n`agent-tool bun update --catalog default <name@version>...` (or the existing named\ncatalog). Name an explicit exact/ranged registry spec; keep `catalog:` references,\nworkspace membership, other entries, and peer compatibility contracts intact.\nThe helper refuses intake and ambiguous layouts and uses the owning manager to\nrefresh the lock; do not replace catalog references with direct versions.\n\nFor an already-resolved transitive registry package with an eligible owner range,\nuse `agent-tool bun update --resolved <name>...` with the owning Bun 1.4.4 or newer.\nIt selects every locked copy of those names, never a requested version or glob,\nand accepts only a result with identical manifests and unchanged non-target lock\nentries/metadata. It preserves release-age, overrides and patches. If an older\nmanager is pinned, or a required new child prevents a target-only result, this\npath is unsupported: prefer an owning-dependency upgrade through the normal\nhelper, or obtain approval for an explicitly reviewed manager workflow. Do not\nsilently substitute a broad refresh or add a transitive package directly. Inspect\nthe receipt/logs and re-audit; a no-op or warning can leave an advisory unresolved.\nNever 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"
17
+ "update-dependencies": "---\nname: update-dependencies\ndescription: Update dependencies or update everything in a repository, including runtimes, tools, and CI pins, with compatibility checks and safe previews; 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## Checkout setup\n\nThis shared workflow also handles natural-language requests to \"update everything\".\nIf the repository owns an `update-everything` wrapper, read and follow its extra\nrequirements; do not create an alias or overwrite that skill. The workflow works\nfrom a standalone checkout with no workspace coordinator.\n\nAfter a fetch, branch integration, or dependency pin change, check that the local\n`agent-tool --version` matches the repository's declared pin before trusting its\ncommands or generated skills. A stale CLI can reject newer configuration keys.\nAfter screening install scripts and hooks as below, run the documented frozen\ninstall with the repository's pinned runtime. For Bun projects, an already working\nCLI can run `agent-tool bun install`; if it is missing or cannot parse the new\nconfig, run the documented package-manager install directly. A known working\nexecutable may capture it with `agent-tool --repo <checkout> run --label setup --\n<install-command> [args...]`. Do not fetch an unpinned CLI, alter global tools, or\nassume a sibling workspace exists. Verify the installed version afterward; if it\nstill differs, report the mismatch rather than deleting arbitrary dependencies.\n\nAfter upgrading agent-tool, run the repository's skill/permission sync commands.\nFor each ownership manifest they do not refresh, run its installer directly:\n`agent-tool skills install --harness <existing-scope> --apply` for\n`.agent-tool-skills.json`, and `agent-tool permissions install --apply` for\n`.agent-tool-permissions.json`, which keeps the scope that manifest records.\nPreserve each harness scope, and commit the ownership manifests with any\ngenerated files. When `all` gains a harness, the install adds that harness's\nrules file, such as `.gemini/policies/agent-tool.toml`; name it in the PR so the\nreviewer sees the new allow rules. A permissions manifest from before scopes\nthat records Claude and Codex, what `all` then wrote, gains `all`; when the\nrepository kept those two on purpose, install each with `--harness` instead,\nand ask when its guidance does not say.\nThe manifests record the agent-tool version, so every upgrade changes them, even\nwhen no skill or rule changed, and `skills check` and `permissions check` fail\nuntil the sync records the new version. Hermes reads the shared `.agents/skills`\nin a trusted project; the installer does not grant trust. If discovery is\nunavailable, read those files directly rather than silently using a stale global\ncopy.\n\n## Nonblocking execution\n\nUse the harness's managed background execution for long finite checks, reviews,\npush hooks, CI waits, and release verification; request completion notification\nwhen available and retain its process handle plus agent-tool's log/receipt path.\nRun `run-group` and reviews directly so their reports remain visible. A started\nprocess is not a passed check: read its final status and required evidence before\nshipping, and do not repeatedly poll when completion events are available.\nWithout harness background support, `proc start --label <name> -- agent-tool run\n--label <check> -- <command> [args...]` records the outer process and captures\nits output; inspect `proc list` and `logs` plus the inner run receipt to establish\ncompletion and exit status. An exited process record alone does not prove success.\nUse `proc stop`/`teardown` for owned leftovers; never stop another session's work.\nThese commands need no matrix workspace or global configuration change.\n\nKeep independent compatibility groups moving while a producer release or an\nexternal gate is pending. Only final adoption of that exact published release\nmust wait. Bound CPU/process-heavy concurrency to the machine's available budget;\na failed full suite needs diagnosis and a full-scope rerun, not larger timeouts,\nfewer assertions, or a focused retry presented as suite recovery. Background\nexecution never bypasses an approval, a deployment preview, or exact-head review.\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. For existing Bun catalog entries use\n`agent-tool bun update --catalog default <name@version>...` (or the existing named\ncatalog). Name an explicit exact/ranged registry spec; keep `catalog:` references,\nworkspace membership, other entries, and peer compatibility contracts intact.\nThe helper refuses intake and ambiguous layouts and uses the owning manager to\nrefresh the lock; do not replace catalog references with direct versions.\n\nFor an already-resolved transitive registry package with an eligible owner range,\nuse `agent-tool bun update --resolved <name>...` with the owning Bun 1.4.4 or newer.\nIt selects every locked copy of those names, never a requested version or glob,\nand accepts only a result with identical manifests and unchanged non-target lock\nentries/metadata. It preserves release-age, overrides and patches. If an older\nmanager is pinned, or a required new child prevents a target-only result, this\npath is unsupported: prefer an owning-dependency upgrade through the normal\nhelper, or obtain approval for an explicitly reviewed manager workflow. Do not\nsilently substitute a broad refresh or add a transitive package directly. Inspect\nthe receipt/logs and re-audit; a no-op or warning can leave an advisory unresolved.\nNever 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"
18
18
  };
19
19
  /** Files a skill ships beside its SKILL.md (Markdown references, then Codex's agents/openai.yaml), by skill and then by path within the skill directory. */
20
20
  export const BUNDLED_SKILL_REFERENCES: Readonly<Record<string, Readonly<Record<string, string>>>> = {
@@ -165,7 +165,7 @@ function runGuards(root: string, config: AgentToolConfig, tuples: PushTuple[], d
165
165
  // A manifest that vanishes after the presence check fails its guard rather than passing unchecked.
166
166
  const vanished = (file: string) => { throw new Error(`${file} disappeared during the check.`); };
167
167
  if (present(SKILLS_MANIFEST)) guard(guards, "skills", undefined, () => { const { harnesses, changes } = checkInstalledSkills(root) ?? vanished(SKILLS_MANIFEST); const drift = changes.filter(change => change.status !== "unchanged"); return { ok: !drift.length, details: { harnesses, changes: drift } }; });
168
- if (present(PERMISSIONS_MANIFEST)) guard(guards, "permissions", undefined, () => { const { harness, changes } = checkInstalledPermissions(root) ?? vanished(PERMISSIONS_MANIFEST); const drift = changes.filter(change => change.status !== "unchanged"); return { ok: !drift.length, details: { harness, changes: drift } }; });
168
+ if (present(PERMISSIONS_MANIFEST)) guard(guards, "permissions", undefined, () => { const { harnesses, changes } = checkInstalledPermissions(root) ?? vanished(PERMISSIONS_MANIFEST); const drift = changes.filter(change => change.status !== "unchanged"); return { ok: !drift.length, details: { harnesses, changes: drift } }; });
169
169
  guard(guards, "branch", undefined, () => { const branches = pushedBranches(tuples).map(name => ({ name, errors: branchErrors(name, config) })).filter(branch => branch.errors.length); return { ok: !branches.length, details: { branches } }; });
170
170
  let refs: PushedRef[] = [];
171
171
  guard(guards, "ranges", undefined, () => { refs = pushedRefs(tuples, destination); return { ok: true }; });