Repository navigation
Expand file tree
/
Copy pathwire-user-config.py
More file actions
executable file
·473 lines (410 loc) · 22.2 KB
/
Copy pathwire-user-config.py
File metadata and controls
executable file
·473 lines (410 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#!/usr/bin/env python3
"""Wire ai-config into every agent's user-level config on this machine.
`bootstrap.sh` calls this. Each agent has its own user-global entry point,
and before ai-config#4206 none of them was set, so a session in any repo
other than ai-config saw the rules only if that repo happened to carry its
own wiring:
Claude Code ~/.claude/settings.json -- registers the Morrison-Lab
marketplace and enables `ai-config@Morrison-Lab`, so the CLI,
the desktop app and Remote Control sessions load the plugin
(skills, hooks, and through hooks/inject-core-rules.py the
AGENTS.md rules) in every project.
Run cancel ~/.claude/settings.json -- lets every session cancel a GitHub
Actions run without the auto-mode classifier refusing it
(ai-config#5623): a `Bash(gh run cancel *)` permission rule,
which skips the classifier, and an `autoMode.allow` prose rule
for the API and MCP forms. The classifier reads `autoMode` only
from user or managed settings, never from a repository, so no
repo file can carry it; cloud sessions read neither file.
Branch push ~/.claude/settings.json -- an `autoMode.allow` prose rule
that lets every session push `claude/*` branches (non-force,
never the default branch) beyond the one branch a harness
prompt names (ai-config#5682). Cloud sessions need the same
text as a standing approval in the project instructions (ai-config#5695).
Approvals ~/.claude/settings.json -- three `autoMode.allow` prose rules
(ai-config#5752): posting a cross-model reviewer's verdict
verbatim as a PR comment; every write of a change the user
approved by name, and nothing outside it; and a relay's
server-copied `<cited author="user">` entry as the user's own
words. Cloud sessions need the same text as a standing approval
in the project instructions (ai-config#5695).
Codex $CODEX_HOME/AGENTS.md (default ~/.codex) -- Codex's
user-global instruction file, linked to this checkout's
AGENTS.md.
Gemini CLI ~/.gemini/GEMINI.md -- a marked block importing
`@./ai-config-AGENTS.md`, a link beside it to this
checkout's AGENTS.md (an import stays inside ~/.gemini).
opencode ~/.config/opencode/opencode.json -- this checkout's AGENTS.md
in `instructions` (only when opencode is installed).
Every step is idempotent and conservative:
- An explicit user choice wins. Any `ai-config@*` entry already present in
`enabledPlugins` is left exactly as it is: a true one means the plugin
loads, an all-false set is a deliberate opt-out.
- The plugin is not enabled where it already arrives another way: when a
synced copy or a user-scope install is on disk, or on a machine that
registered the catalog through `scripts/install-hooks.py --fix`. Each of
those plus a marketplace copy fires every hook twice. A remote (claude.ai)
container with no synced copy is reported as `skip`: the account sync is
missing or failed (ai-config#3948), and enabling a second copy there
would double every hook once the sync delivers one.
- A Codex file or link that is not ours is left alone; a dangling link, or
one into another ai-config checkout, is repointed here.
- Each step reports `ok`, `write`/`link`, `todo` (with --check) or `skip`
with its reason. A step that raises is reported as `skip` and the rest
still run.
`--check` writes nothing and exits 1 when any step is not `ok`.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "scripts" / "lib"))
from ai_config_wiring import ( # noqa: E402
MARKETPLACE, MARKETPLACE_SOURCE, PLUGIN, is_ai_config, splice_block)
from plugin_overlap import ai_config_entries # noqa: E402
GEMINI_LINK = "ai-config-AGENTS.md"
GEMINI_BEGIN = "<!-- ai-config:begin (managed by ai-config/scripts/wire-user-config.py) -->"
GEMINI_END = "<!-- ai-config:end -->"
def home() -> Path:
return Path(os.environ.get("HOME", str(Path.home())))
def load_json(path: Path) -> dict | None:
"""The parsed object, {} when absent, None when unreadable or not an object."""
if not path.exists():
return {}
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
return data if isinstance(data, dict) else None
def write_json(path: Path, data: dict) -> None:
"""Write atomically, so a concurrent reader never sees a half-written file."""
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
try:
with os.fdopen(fd, "w", encoding="utf-8") as stream:
stream.write(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
os.replace(tmp, path)
except BaseException:
Path(tmp).unlink(missing_ok=True)
raise
def catalog_scripts() -> set[str]:
catalog = json.loads((ROOT / "hooks" / "hooks.json").read_text(encoding="utf-8"))
return {
hook["script"]
for groups in catalog["hooks"].values()
for group in groups
for hook in group["hooks"]
if "script" in hook
}
def leftover_hook(hook: object, scripts: set[str]) -> bool:
"""True when one settings.json hook entry runs a catalog hook from a `hooks/` directory.
install-hooks.py writes `$HOME/.claude/hooks/<name>` or a literal CLAUDE_HOME
path, so the match is any `hooks/<name>`; a backup such as `<name>.bak` or
`<name>~` is not a registration.
"""
command = hook.get("command", "") if isinstance(hook, dict) else ""
if not isinstance(command, str) or "CLAUDE_PLUGIN_ROOT" in command:
return False
return any(re.search(r"[\\/]hooks[\\/]" + re.escape(name) + r"(?![\w.~-])", command)
for name in scripts)
def non_plugin_hooks_registered(settings: dict) -> bool:
"""True when settings.json runs catalog hooks from ~/.claude/hooks."""
scripts = catalog_scripts()
hooks = settings.get("hooks")
if not isinstance(hooks, dict):
return False
for groups in hooks.values():
for group in groups if isinstance(groups, list) else []:
entries = group.get("hooks") if isinstance(group, dict) else None
for hook in entries if isinstance(entries, list) else []:
if leftover_hook(hook, scripts):
return True
return False
def plugin_on_disk(claude_home: Path) -> str | None:
"""Where an ai-config plugin copy already loads from, if anywhere."""
synced = sorted((claude_home / "plugins" / "synced").glob("*/ai-config"))
if synced:
return f"account plugin sync ({synced[0]})"
installed = load_json(claude_home / "plugins" / "installed_plugins.json") or {}
plugins = installed.get("plugins")
for name, records in (plugins.items() if isinstance(plugins, dict) else ()):
if not name.startswith("ai-config@"):
continue
# A project-scoped install loads only in that project, so it does not
# stand in for a user-wide enable.
records = records if isinstance(records, list) else [records]
if any(isinstance(r, dict) and r.get("scope", "user") == "user" for r in records):
return f"installed plugin {name} (user scope)"
return None
def wire_claude(check: bool) -> tuple[str, bool]:
claude_home = Path(os.environ.get("CLAUDE_HOME", home() / ".claude"))
path = claude_home / "settings.json"
settings = load_json(path)
if settings is None:
return f"skip {path} is not a JSON object; fix it by hand", False
for key in ("enabledPlugins", "extraKnownMarketplaces", "hooks"):
if key in settings and not isinstance(settings[key], dict):
return f"skip {path}: `{key}` is not a JSON object; fix it by hand", False
explicit = ai_config_entries(settings)
if explicit:
state = ", ".join(f"{k}={v}" for k, v in sorted(explicit.items()))
if any(explicit.values()):
return f"ok {path} enables the plugin ({state})", True
return (f"skip {path} disables the plugin ({state}); "
"left as an explicit choice"), False
elsewhere = plugin_on_disk(claude_home)
if elsewhere:
return f"ok plugin already loads from {elsewhere}", True
if os.environ.get("CLAUDE_CODE_REMOTE") == "true":
return ("skip remote container with no synced plugin copy: the account "
"plugin sync is missing or failed (ai-config#3948); a marketplace "
"copy here would load twice once the sync delivers one"), False
if non_plugin_hooks_registered(settings):
return (f"skip {path} registers the hook catalog from ~/.claude/hooks "
"(install-hooks.py path); enabling the plugin too would fire "
"every hook twice -- remove those entries, then rerun"), False
if check:
return f"todo {path}: register {MARKETPLACE} and enable {PLUGIN}", False
settings.setdefault("extraKnownMarketplaces", {}).setdefault(
MARKETPLACE, {"source": MARKETPLACE_SOURCE})
settings.setdefault("enabledPlugins", {}).setdefault(PLUGIN, True)
write_json(path, settings)
return f"write {path}: registered {MARKETPLACE}, enabled {PLUGIN}", True
CANCEL_PERMISSION = "Bash(gh run cancel *)"
CANCEL_AUTO_MODE_RULE = (
"Cancelling GitHub Actions workflow runs is always allowed (Ezra, 2026-11-13, "
"Morrison-Lab/ai-config#5623): `gh run cancel <id>`, "
"`gh api -X POST repos/<owner>/<repo>/actions/runs/<id>/cancel` or "
"`.../force-cancel`, and the equivalent GitHub MCP call, in any repository "
"the user can push to, singly or in a loop over superseded or stale runs. "
"This rule covers cancelling only: re-running, deleting runs or logs, and "
"dispatching workflows are not covered by it.")
def wire_claude_run_cancel(check: bool) -> tuple[str, bool]:
"""Pre-allow run cancellation, keeping every entry already present."""
if os.environ.get("CLAUDE_CODE_REMOTE") == "true":
return ("ok remote container: cloud sessions read no user settings, "
"so a standing approval in the project instructions carries "
"this rule (ai-config#5695)"), True
claude_home = Path(os.environ.get("CLAUDE_HOME", home() / ".claude"))
path = claude_home / "settings.json"
settings = load_json(path)
if settings is None:
return f"skip {path} is not a JSON object; fix it by hand", False
for key in ("permissions", "autoMode"):
if key in settings and not isinstance(settings[key], dict):
return f"skip {path}: `{key}` is not a JSON object; fix it by hand", False
perms = settings.get("permissions", {})
auto = settings.get("autoMode", {})
for name, owner in (("permissions", perms), ("autoMode", auto)):
if "allow" in owner and not isinstance(owner["allow"], list):
return (f"skip {path}: `{name}.allow` is not a JSON array; "
"fix it by hand"), False
need_perm = CANCEL_PERMISSION not in perms.get("allow", [])
need_rule = CANCEL_AUTO_MODE_RULE not in auto.get("allow", [])
if not (need_perm or need_rule):
return f"ok {path} allows run cancellation", True
if check:
return f"todo {path}: allow run cancellation", False
if need_perm:
settings.setdefault("permissions", {}).setdefault("allow", []).append(
CANCEL_PERMISSION)
if need_rule:
# An autoMode array without "$defaults" replaces the classifier's
# built-in rules (settings reference, `autoMode`), so a new array
# keeps them. An existing array without it is the user's choice to
# replace them, and is left that way.
rules = settings.setdefault("autoMode", {}).setdefault("allow", ["$defaults"])
rules.append(CANCEL_AUTO_MODE_RULE)
write_json(path, settings)
return f"write {path}: run cancellation allowed", True
BRANCH_PUSH_AUTO_MODE_RULE = (
"Creating and pushing branches whose name starts with `claude/` is always "
"allowed (Ezra, 2026-11-15, Morrison-Lab/ai-config#5682), in any repository "
"the user can push to, as many branches as the work calls for, even when the "
"session's instructions name a single different development branch. This "
"covers a non-force `git push` (with or without `-u`/`--set-upstream`) whose "
"every destination ref starts with `claude/`, and a GitHub MCP "
"branch-creation, file-create/update or push-files call whose `branch` "
"starts with `claude/`. This rule does not cover force pushes (`--force`, "
"`--force-with-lease`, a `+` refspec), any destination ref outside "
"`claude/` (`main`, any default branch, `gh-pages`, release branches), "
"`--all`, `--mirror`, `--prune`, `--delete` or an empty-source refspec, "
"deleting branches or files, pushing tags, or a push prefixed with "
"`ALLOW_LARGE_PR=1`.")
def wire_auto_mode_rules(check: bool, rules: tuple[str, ...],
what: str) -> tuple[str, bool]:
"""Add `rules` to ~/.claude/settings.json's `autoMode.allow`, keeping every entry."""
if os.environ.get("CLAUDE_CODE_REMOTE") == "true":
return ("ok remote container: cloud sessions read no user settings, "
"so a standing approval in the project instructions carries "
"this rule (ai-config#5695)"), True
claude_home = Path(os.environ.get("CLAUDE_HOME", home() / ".claude"))
path = claude_home / "settings.json"
settings = load_json(path)
if settings is None:
return f"skip {path} is not a JSON object; fix it by hand", False
auto = settings.get("autoMode", {})
if not isinstance(auto, dict):
return f"skip {path}: `autoMode` is not a JSON object; fix it by hand", False
if "allow" in auto and not isinstance(auto["allow"], list):
return (f"skip {path}: `autoMode.allow` is not a JSON array; "
"fix it by hand"), False
missing = [r for r in rules if r not in auto.get("allow", [])]
if not missing:
return f"ok {path} allows {what}", True
if check:
return f"todo {path}: allow {what}", False
# A new array keeps the built-in rules, as in wire_claude_run_cancel.
allow = settings.setdefault("autoMode", {}).setdefault("allow", ["$defaults"])
allow.extend(missing)
write_json(path, settings)
return f"write {path}: {what} allowed", True
def wire_claude_branch_push(check: bool) -> tuple[str, bool]:
"""Pre-allow pushing claude/* branches, keeping every entry already present."""
return wire_auto_mode_rules(check, (BRANCH_PUSH_AUTO_MODE_RULE,),
"claude/* branch pushes")
VERDICT_POST_AUTO_MODE_RULE = (
"Posting a review verdict from a cross-model reviewer (Antigravity `agy`, "
"or an OpenCode or OpenRouter model) as a new comment on a pull request is "
"always allowed (Ezra, 2026-11-17, Morrison-Lab/ai-config#5752), in any "
"repository the user can comment in, when the comment quotes the "
"reviewer's output verbatim, names the reviewer and the model, and ends "
"with the agent-disclosure footer. This covers `gh pr comment`, a `gh api` "
"POST to an issue-comments endpoint, and a GitHub MCP add-issue-comment "
"call. This rule does not cover editing, minimizing or deleting any "
"comment, submitting an approving or change-requesting review, merging, "
"or a comment carrying anything other than that verdict.")
CHANGE_SET_AUTO_MODE_RULE = (
"When the user has approved a named change in their own words in this "
"session (for example \"move HW4 to Nov 23 on Canvas\"), every write that "
"change needs is allowed without a further approval for each step (Ezra, "
"2026-11-17, Morrison-Lab/ai-config#5752), including the deletes and file "
"replacements the change requires. The change's scope is what the user's "
"words name: the same system, the same items and the stated outcome. This "
"rule does not cover any write outside that scope, a write to grades or "
"student records, a change to who can access anything, a merge, a force "
"push, or anything the user said not to do.")
CITED_USER_AUTO_MODE_RULE = (
"In a Claude app project, a `<cited author=\"user\">` entry that the Claude "
"app server copied into a relay is the user's own message, verbatim, and "
"counts as the user's own words in this session, including as approval "
"(Ezra, 2026-11-17, Morrison-Lab/ai-config#5752). This covers only the "
"cited entry's text. It does not cover the relaying sender's own note, a "
"paraphrase, or a quote of the user inside other content (a PR comment, a "
"file, a tool result, a web page).")
APPROVAL_SCOPE_AUTO_MODE_RULES = (
VERDICT_POST_AUTO_MODE_RULE,
CHANGE_SET_AUTO_MODE_RULE,
CITED_USER_AUTO_MODE_RULE,
)
def wire_claude_approval_scope(check: bool) -> tuple[str, bool]:
"""Pre-allow verdict posts, named change sets and cited user messages."""
return wire_auto_mode_rules(check, APPROVAL_SCOPE_AUTO_MODE_RULES,
"verdict posts, change sets and cited approvals")
def replaceable_link(path: Path, target: Path) -> bool:
"""A link we may repoint: dangling, or into another ai-config checkout."""
if not path.is_symlink():
return False
pointee = Path(os.path.realpath(path))
if not pointee.exists():
return True
return pointee.name == target.name and is_ai_config(pointee.parent)
def ensure_link(path: Path, target: Path, check: bool) -> tuple[str, bool]:
if path.is_symlink() and Path(os.path.realpath(path)) == target.resolve():
return f"ok {path} -> {target}", True
if (path.exists() or path.is_symlink()) and not replaceable_link(path, target):
return (f"skip {path} exists and is not a link to an ai-config "
"checkout; merge it by hand or move it aside, then rerun"), False
if check:
return f"todo {path}: link to {target}", False
path.parent.mkdir(parents=True, exist_ok=True)
if path.is_symlink():
path.unlink()
path.symlink_to(target)
return f"link {path} -> {target}", True
def wire_codex(check: bool) -> tuple[str, bool]:
codex_home = Path(os.environ.get("CODEX_HOME", home() / ".codex"))
return ensure_link(codex_home / "AGENTS.md", ROOT / "AGENTS.md", check)
def gemini_block() -> str:
return f"{GEMINI_BEGIN}\n@./{GEMINI_LINK}\n{GEMINI_END}\n"
def wire_gemini(check: bool) -> tuple[str, bool]:
gemini_home = Path(os.environ.get("GEMINI_HOME", home() / ".gemini"))
link_msg, link_ok = ensure_link(gemini_home / GEMINI_LINK, ROOT / "AGENTS.md", check)
if not link_ok:
return link_msg, False
path = gemini_home / "GEMINI.md"
if path.is_symlink():
return (f"skip {path} is a link; add `@./{GEMINI_LINK}` to its target "
"by hand"), False
block = gemini_block()
current = path.read_text(encoding="utf-8") if path.exists() else ""
if block in current:
return f"ok {path} imports ./{GEMINI_LINK}", True
if check:
return f"todo {path}: add the ai-config import block", False
updated = splice_block(current, block, GEMINI_BEGIN, GEMINI_END)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(updated, encoding="utf-8")
return f"write {path}: ai-config import block", True
def stale_instruction(entry: object, agents: str) -> bool:
"""An earlier AGENTS.md entry that is provably another ai-config checkout's.
An entry whose file is gone cannot be attributed, so it is kept: it may be
the user's own entry for a project that is moved or unmounted.
"""
if not isinstance(entry, str) or entry == agents or not entry.endswith("/AGENTS.md"):
return False
candidate = Path(entry)
return candidate.is_absolute() and is_ai_config(candidate.parent)
def wire_opencode(check: bool) -> tuple[str, bool]:
config_dir = Path(os.environ.get("XDG_CONFIG_HOME", home() / ".config")) / "opencode"
if not config_dir.exists() and shutil.which("opencode") is None:
return "ok opencode is not installed; nothing to wire", True
if (config_dir / "opencode.jsonc").exists():
return (f"skip {config_dir / 'opencode.jsonc'} is the user config; add "
f"{ROOT / 'AGENTS.md'} to its instructions by hand"), False
path = config_dir / "opencode.json"
config = load_json(path)
if config is None:
return f"skip {path} is not a JSON object; fix it by hand", False
agents = str(ROOT / "AGENTS.md")
instructions = config.get("instructions") or []
kept = [e for e in instructions if not stale_instruction(e, agents)]
if agents in kept and kept == instructions:
return f"ok {path} instructions include {agents}", True
if check:
return f"todo {path}: add {agents} to instructions", False
config.setdefault("$schema", "https://opencode.ai/config.json")
config["instructions"] = kept if agents in kept else [*kept, agents]
write_json(path, config)
return f"write {path}: instructions now include {agents}", True
STEPS = (
("Claude Code", wire_claude),
("Run cancel", wire_claude_run_cancel),
("Branch push", wire_claude_branch_push),
("Approvals", wire_claude_approval_scope),
("Codex", wire_codex),
("Gemini CLI", wire_gemini),
("opencode", wire_opencode),
)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--check", action="store_true",
help="report only; exit 1 when any step is not ok")
args = parser.parse_args(argv)
all_ok = True
for label, step in STEPS:
try:
message, ok = step(args.check)
except (OSError, UnicodeError, ValueError) as err:
message, ok = f"skip {type(err).__name__}: {err}", False
print(f"{label:<12} {message}")
all_ok = all_ok and ok
return 0 if all_ok or not args.check else 1
if __name__ == "__main__":
sys.exit(main())