Repository navigation
Add visual README and universal agent init - #1
Conversation
Review Summary by QodoAdd universal agent-init command and visual README documentation
WalkthroughsDescription• Adds braid agent-init universal command for Claude, Codex, Cursor, Copilot activation • Implements check/fix/remove modes for agent integration management • Refactors claude-init to delegate to new agent-init command • Expands README with visual diagrams and comprehensive architecture documentation • Adds ADR 0017 decision record for universal agent initialization Diagramflowchart LR
CLI["braid agent-init<br/>--check/fix/remove"]
CLI -->|Claude| Claude["settings.json<br/>hook + MCP"]
CLI -->|Codex| Codex["hooks.json<br/>SessionStart"]
CLI -->|Cursor| Cursor["rules/main.mdc<br/>symlink"]
CLI -->|Copilot| Copilot["instructions.md<br/>symlink"]
Claude -->|manages| Legacy["Migrate legacy<br/>fairlead/wikiforge"]
File Changes2. src/braid/commands/agent.py
|
Code Review by Qodo
1. Agent-init wrong root
|
|
Caution Review failedPull request was closed or merged during review 📝 WalkthroughWalkthroughAdds a canonical ChangesUniversal agent initialization and related ops
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
🤖 Augment PR SummarySummary: This PR standardizes agent activation by introducing Changes:
Technical Notes: The command is designed to be idempotent, avoid indexing/LLM calls, and treat legacy 🤖 Was this summary useful? React with 👍 or 👎 |
| if not path.is_file(): | ||
| return {} | ||
| try: | ||
| return json.loads(path.read_text()) or {} |
There was a problem hiding this comment.
_load_json() swallows JSON parse/read failures and returns {}, which can make agent-init overwrite a user’s existing (but slightly invalid / non-UTF8) config with a minimal Braid config on apply/remove without warning. Consider surfacing an explicit error/drift state (and also handling UnicodeDecodeError) to avoid accidental data loss.
Severity: medium
🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.
| canonical = False | ||
| legacy = False | ||
| for event in events: | ||
| for hook in event.get("hooks", []) or []: |
There was a problem hiding this comment.
_hook_drift() (and _strip_braid_hooks()) assume each SessionStart event and each hook are dicts; if the JSON contains unexpected shapes, .get(...) will raise and the command will crash. Since these are user-edited files, consider validating types before accessing .get so agent-init can report drift instead of throwing.
Severity: medium
Other Locations
src/braid/commands/agent.py:114
🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.
| return (agent,) # type: ignore[return-value] | ||
|
|
||
|
|
||
| def _mode(check: bool, fix: bool, remove: bool) -> Mode: |
There was a problem hiding this comment.
--fix is treated as mutually exclusive but _mode() never returns a distinct mode for it (it becomes apply), so JSON/human output will show mode=apply even when users explicitly request --fix. If consumers rely on the reported mode, this could be confusing.
Severity: low
🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 35b4dffd0c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| def _root() -> Path: | ||
| return find_project_root() or find_git_root() or Path.cwd().resolve() |
There was a problem hiding this comment.
Align hook root with project boundary
Cuando agent-init se ejecuta dentro de un proyecto hijo que tiene marcador propio pero comparte el .git de un contenedor, esta selección instala .claude/.codex bajo el hijo; sin embargo el hook instalado ejecuta braid claude-session-start, que todavía resuelve con find_git_root() en src/braid/commands/claude.py, por lo que reporta y valida la memoria del padre en lugar de la del proyecto donde se instaló. En ese escenario el banner puede pedir indexar el repo equivocado o ignorar .braid del hijo, justo el caso cubierto por test_agent_init_uses_child_project_boundary; el hook debería usar la misma frontera de proyecto que agent-init o recibirla explícitamente.
Useful? React with 👍 / 👎.
| def _root() -> Path: | ||
| return find_project_root() or find_git_root() or Path.cwd().resolve() | ||
|
|
There was a problem hiding this comment.
1. Agent-init wrong root 🐞 Bug ≡ Correctness
agent-init prefers find_project_root() (marker-based, e.g. any directory with README.md) over the git root, so invoking it from a nested folder can write .claude/settings.json / .codex/hooks.json into that folder and the hook integration may not be discovered where the agent expects. This also makes claude-init behavior contradict its <git_root>/.claude/settings.json help text and diverges from claude-session-start, which still reports status using find_git_root().
Agent Prompt
## Issue description
`agent-init` resolves `root` using `find_project_root()` first, while `claude-session-start` uses `find_git_root()`. This can cause hooks/config to be written under a nested marker directory but status (and potentially other commands) to read state from the git root, breaking activation in nested-project scenarios and contradicting CLI help for `claude-init`.
## Issue Context
- `find_project_root()` treats `README.md` as a project marker, so many subdirectories can become “project roots”.
- `claude-init` now delegates to `agent-init`, inheriting this behavior.
## Fix Focus Areas
- src/braid/commands/agent.py[36-38]
- src/braid/commands/claude.py[214-218]
- src/braid/commands/claude.py[94-107]
- src/braid/cli.py[100-105]
## Suggested fix approach
- Decide a single canonical root resolution for *agent activation* and for `claude-session-start` (e.g., use `resolve_context().root` everywhere, or enforce git-root semantics for Claude/Codex configs).
- Update `claude-session-start` to use the same root resolution so the hook reports the correct project boundary.
- If `claude-init` is intended to remain git-root-scoped, enforce `find_git_root()` and error outside git, and/or adjust its help text accordingly.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/braid/commands/claude.py (1)
32-35: 💤 Low valueConsider extracting shared constants to reduce duplication.
HOOK_COMMAND,HOOK_MARKER, andLEGACY_HOOK_MARKERSare defined here and similarly inagent.py. Sincerun_initnow delegates to the agent module, you could import these constants from there. This isn't blocking—the current approach works—but it would reduce future maintenance burden if hook commands change.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/braid/commands/claude.py` around lines 32 - 35, Extract the duplicated hook constants from this file by importing them from the agent module instead of redefining them here: replace the local definitions of HOOK_COMMAND, HOOK_MARKER, and LEGACY_HOOK_MARKERS in src/braid/commands/claude.py with imports from the agent module (the same source where run_init now delegates), update any references in this file to use the imported symbols, and remove the redundant local declarations to keep a single canonical definition.src/braid/commands/agent.py (1)
136-140: 💤 Low valueMinor: Action reporting could be clearer.
When
removed > 0, the function appends a new canonical hook AND reportsnormalized_hook. Whenremoved == 0, it reportsensured_hook. Both cases add the canonical hook, but only one action is reported. Consider reporting bothnormalized_hookandensured_hookwhen applicable, or renamenormalized_hookto something likereplaced_legacy_hookfor clarity.This is cosmetic—the reconciliation logic itself is correct.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/braid/commands/claude.py`:
- Around line 32-35: Extract the duplicated hook constants from this file by
importing them from the agent module instead of redefining them here: replace
the local definitions of HOOK_COMMAND, HOOK_MARKER, and LEGACY_HOOK_MARKERS in
src/braid/commands/claude.py with imports from the agent module (the same source
where run_init now delegates), update any references in this file to use the
imported symbols, and remove the redundant local declarations to keep a single
canonical definition.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 3a20b278-172c-4415-bfc6-d676f15a8118
⛔ Files ignored due to path filters (3)
docs/diagrams/braid-agent-activation.svgis excluded by!**/*.svgdocs/diagrams/braid-memory-boundaries.svgis excluded by!**/*.svgdocs/diagrams/braid-retrieval-flow.svgis excluded by!**/*.svg
📒 Files selected for processing (11)
.braid/memory/MEMORY.md.braid/memory/decisions/0017-universal-agent-init.mdAGENTS.mdREADME.mddocs/diagrams/braid-agent-activation.excalidrawdocs/diagrams/braid-memory-boundaries.excalidrawdocs/diagrams/braid-retrieval-flow.excalidrawsrc/braid/cli.pysrc/braid/commands/agent.pysrc/braid/commands/claude.pytests/test_agent_init.py
There was a problem hiding this comment.
3 issues found across 14 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="src/braid/commands/agent.py">
<violation number="1" location="src/braid/commands/agent.py:97">
P2: `_hook_drift` can crash on malformed but parseable settings because it does not type-check `event`/`hook` entries.</violation>
</file>
<file name="src/braid/commands/claude.py">
<violation number="1" location="src/braid/commands/claude.py:218">
P2: `claude-init` wrapper changed root resolution semantics and can write `.claude/settings.json` outside `<git_root>`.</violation>
</file>
Tip: cubic can generate docs of your entire codebase and keep them up to date. Try it here.
Re-trigger cubic
| events = _session_start_events(settings) | ||
| canonical = False | ||
| legacy = False | ||
| for event in events: |
There was a problem hiding this comment.
P2: _hook_drift can crash on malformed but parseable settings because it does not type-check event/hook entries.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/braid/commands/agent.py, line 97:
<comment>`_hook_drift` can crash on malformed but parseable settings because it does not type-check `event`/`hook` entries.</comment>
<file context>
@@ -0,0 +1,357 @@
+ events = _session_start_events(settings)
+ canonical = False
+ legacy = False
+ for event in events:
+ for hook in event.get("hooks", []) or []:
+ canonical = canonical or _is_canonical_hook(hook)
</file context>
|
|
||
| _save_settings(target, settings) | ||
| return 0 | ||
| return agent_cmd.run(agent="claude", remove=remove) |
There was a problem hiding this comment.
P2: claude-init wrapper changed root resolution semantics and can write .claude/settings.json outside <git_root>.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/braid/commands/claude.py, line 218:
<comment>`claude-init` wrapper changed root resolution semantics and can write `.claude/settings.json` outside `<git_root>`.</comment>
<file context>
@@ -212,66 +212,7 @@ def _strip_braid_hook(events: list[dict]) -> list[dict]:
-
- _save_settings(target, settings)
- return 0
+ return agent_cmd.run(agent="claude", remove=remove)
</file context>
There was a problem hiding this comment.
2 issues found
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name=".github/workflows/ci.yml">
<violation number="1" location=".github/workflows/ci.yml:7">
P2: Workflow omits an explicit least-privilege `permissions` policy for `GITHUB_TOKEN`, increasing CI token exposure.</violation>
</file>
<file name="src/braid/commands/doctor.py">
<violation number="1" location="src/braid/commands/doctor.py:157">
P2: `doctor --fix` can modify agent config in the current directory while reporting a different root in global-profile mode.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
| push: | ||
| pull_request: | ||
|
|
||
| jobs: |
There was a problem hiding this comment.
P2: Workflow omits an explicit least-privilege permissions policy for GITHUB_TOKEN, increasing CI token exposure.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .github/workflows/ci.yml, line 7:
<comment>Workflow omits an explicit least-privilege `permissions` policy for `GITHUB_TOKEN`, increasing CI token exposure.</comment>
<file context>
@@ -0,0 +1,55 @@
+ push:
+ pull_request:
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
</file context>
|
|
||
|
|
||
| def _check_agents(ctx: paths_module.ProjectContext, fix: bool) -> DoctorCheck: | ||
| root = ctx.root if not ctx.global_profile else Path.cwd().resolve() |
There was a problem hiding this comment.
P2: doctor --fix can modify agent config in the current directory while reporting a different root in global-profile mode.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/braid/commands/doctor.py, line 157:
<comment>`doctor --fix` can modify agent config in the current directory while reporting a different root in global-profile mode.</comment>
<file context>
@@ -0,0 +1,279 @@
+
+
+def _check_agents(ctx: paths_module.ProjectContext, fix: bool) -> DoctorCheck:
+ root = ctx.root if not ctx.global_profile else Path.cwd().resolve()
+ mode: agent_cmd.Mode = "apply" if fix else "check"
+ results = [agent_cmd._run_one(name, root, mode) for name in agent_cmd.AGENTS]
</file context>
There was a problem hiding this comment.
1 issue found across 22 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name=".github/workflows/ci.yml">
<violation number="1" location=".github/workflows/ci.yml:34">
P2: README image validation regex is over-escaped, so CI does not detect missing markdown image assets.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
|
|
||
| root = Path.cwd() | ||
| readme = (root / "README.md").read_text() | ||
| links = re.findall(r'!\\[[^\\]]*\\]\\(([^)]+)\\)', readme) |
There was a problem hiding this comment.
P2: README image validation regex is over-escaped, so CI does not detect missing markdown image assets.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .github/workflows/ci.yml, line 34:
<comment>README image validation regex is over-escaped, so CI does not detect missing markdown image assets.</comment>
<file context>
@@ -0,0 +1,55 @@
+
+ root = Path.cwd()
+ readme = (root / "README.md").read_text()
+ links = re.findall(r'!\\[[^\\]]*\\]\\(([^)]+)\\)', readme)
+ missing = [link for link in links if not (root / link).is_file()]
+ if missing:
</file context>
Summary
braid agent-initas the universal activation command for Claude, Codex, Cursor, and Copilot.Test Plan
PYTHONPATH=src .venv/bin/python -m pytest -qPYTHONPATH=src .venv/bin/python -m braid.cli --helpbraid agent-init --check --jsonrg -n "wikiforge|fairlead" README.mdonly shows explicit legacy alias note.git diff --checkgit diff --cached --checkSummary by cubic
Adds a universal
braid agent-initacross Claude, Codex, Cursor, and Copilot, plusbraid doctor,status --json, a newbraid patternsplaybook, and Obsidian export. Replaces the README with a visual, GitHub-ready landing page and updated diagrams.New Features
braid agent-initwith--agent,--check,--fix,--remove,--json. Idempotent; no indexing; respects nearest project boundary. Sets Claude SessionStart hook + MCP (braid mcp-serve), Codex session hook, and Cursor/Copilot discovery symlinks.braid claude-initnow delegates.braid doctor [--json] [--fix]checks install, context, agents, secrets, and drift.braid status --jsonemits a stable payload. Config hardening preserves invalid JSON instead of overwriting.braid patterns [--json]exposes the operational patterns read-only, aligned with the new diagrams.braid wiki build --obsidiancreates an Obsidian vault in.braid/wiki/obsidian/or writes to--vault(underBraid/<dataset_id>/). Supports--outputfor a fresh vault.actions/checkout@v6,actions/setup-python@v6on Python 3.11. ADR 0017/0018/0019/0020 included. Tests cover drift detection, fix/remove, boundary resolution, JSON outputs, patterns, and Obsidian export.Migration
braid agent-init --fixin each repo to normalize hooks, MCP, and discovery symlinks.braid agent-init --check --jsonand/orbraid doctor --jsonin CI to detect drift;--removeuninstalls only Braid-managed blocks.braid wiki build --obsidian.Written for commit 91e6716. Summary will update on new commits.
Summary by CodeRabbit
New Features
braid agent-init(apply/check/fix/remove) with--jsonand backward-compatibleclaude-initdelegation.braid doctor(diagnostics, optional--fix/--json),braid status --json, andbraid patterns [--json].braid wikigains Obsidian vault export mode (--obsidian,--vault/--outputhandling).Documentation
Tests & CI