⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
mermaidiff
Brief any change as a git-style Mermaid flow diff (new / changed / removed) with payload diff, impact and open questions. Use for /mermaidiff, a Jira ticket, GitLab MR or GitHub PR link, commit sha, staged or unstaged changes, branch range, plan, refactor idea, or bug walkthrough, or when the user says "brief me".
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
// README
Quick start
Claude Code plugin (no clone):
/plugin marketplace add osmangoninahid/mermaidiff
/plugin install mermaidiff@mermaidiff
Or with the installer (Claude Code and Codex):
git clone https://github.com/osmangoninahid/mermaidiff && cd mermaidiff && ./install.sh
Then, in any repo, inside your agent (as a plugin the command is /mermaidiff:mermaidiff):
/mermaidiff # your staged or latest change
/mermaidiff <PR or MR link> # someone else's change
The brief opens in your browser. Ask for changes in plain words ("drop the RunTLS step") and the open tab updates. Copy for MR gives you markdown that GitHub and GitLab render as is.
What you get

- One line saying what the code changes, taken from the diff, not the commit message
- A sequence diagram of only the changed steps, colored like a diff
- Proof: up to 5
file:linebullets, one short fact each - The payload diff when a request, response, model or config changes
- ⚠️ may break, only when the code proves a reachable path, and at most 1 open question
- ⚠️ when the commit message or PR text claims something the diff doesn't do
The one rule: no false positives
A wrong warning is worse than a missing one. mermaidiff only shows what the diff or the code proves. It never guesses about systems outside your repo, it just lists them as Not checked.
Tested
10 real commits from FastAPI, gin and excalidraw, every claim checked against the code: 10/10 found, 0 false positives. Briefs in 0.1.5 are 40% shorter than 0.1.4. Details in eval/.

All commands
/mermaidiff staged, else unstaged, else last commit
/mermaidiff staged
/mermaidiff wip unstaged changes
/mermaidiff a1b2c3d one commit
/mermaidiff main..feature a range
/mermaidiff <PR link> · #123 GitHub, needs gh
/mermaidiff <MR link> · !123 GitLab, needs glab
/mermaidiff ABC-123 a ticket (experimental, needs a Jira MCP)
/mermaidiff "move sync to a queue" a plan, no code yet
Install options
Needs git and python3. Recommended: rg, and CodeGraph or Graphify for faster caller lookups (falls back to grep).
./install.sh # for you: ~/.claude/skills and ~/.agents/skills
./install.sh --project # for a repo, shared with your team
./install.sh --link # symlink, if you work on mermaidiff itself
The installer downloads Mermaid once for offline use and adds .mermaidiff/ to your global git ignore. The plugin skips both: the viewer loads Mermaid from a CDN, so add .mermaidiff/ to your git ignore yourself.
Status
| commit, staged, wip, range | tested |
| GitHub PR, GitLab MR | tested |
| browser viewer, live reload, copy for MR | tested |
| ticket mode, Codex | experimental |
| CI job that posts the brief on every PR | planned |
| before / after split view | planned |
How it works
skill/SKILL.md tells the agent how to gather facts (git, gh, glab, grep or a code graph)
skill/format.md the output format and the rules, including "no false positives"
skill/scripts/view.py renders the brief to html, recounts the stat line, opens the browser
eval/ test cases, expected answers, run prompt, scores
examples/ briefs from public repos
Contributing
Found a wrong claim in a brief? That's the most useful bug report: open an issue with the brief and a link to the commit or PR. See CONTRIBUTING.md.
License
MIT. Not affiliated with the Mermaid project, it just draws with it.
// HOW IT'S BUILT
// FILES
6 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
skill/SKILL.md6.5 KBab25ad5e5023upstream ↗
--- name: mermaidiff description: Brief any change as a git-style Mermaid flow diff (new / changed / removed) with payload diff, impact and open questions. Use for /mermaidiff, a Jira ticket, GitLab MR or GitHub PR link, commit sha, staged or unstaged changes, branch range, plan, refactor idea, or bug walkthrough, or when the user says "brief me". allowed-tools: Bash(python3 "${CLAUDE_PLUGIN_ROOT}/skill/scripts/collect.py":*) Bash(python3 "${CLAUDE_PLUGIN_ROOT}/skill/scripts/view.py":*) --- # mermaidiff Gather the facts, write the brief in the exact format in `format.md` (same folder), then open it in the browser. ## 0. Collect the facts first Your first tool call, before reading anything else: run the bundled collector with the user's argument as one quoted string (empty string if none): ```bash python3 "${CLAUDE_SKILL_DIR}/scripts/collect.py" '<argument>' ``` It prints the mode, the diff, the claim (commit message or PR text), and the callers and readers from `git grep`, taken at the right commit, in about a second. It ends with the full text of `format.md`, so you don't need to read that file. Use its output and don't run those git commands again: - `**stop:**` or `**empty:**` → reply with that reason in one line and stop. - `**cache hit:**` → do what it says and stop. - Otherwise go to step 2, and only fetch what is still missing. If the script can't run (no `python3`) or prints an error, collect the facts yourself with step 1 and read `format.md` in this skill's folder. **Be fast:** when you need several files or searches, request them all in one turn (parallel tool calls), not one by one. ## 1. Parse the argument (only if the collector failed) | Argument | Mode | Get the change with | |---|---|---| | (none) | auto | staged if any, else unstaged, else last commit | | `staged` | staged | `git diff --cached` | | `wip` | unstaged | `git diff` | | 7–40 hex chars, or `commit <x>` | commit | `git show --stat <sha>` then `git diff <sha>^ <sha>` | | contains `..` | range | `git diff <base>...<head>` | | GitHub PR URL, `#123`, or `pr <x>` | pr | `gh pr view <n> --json title,body,baseRefName,headRefName,headRefOid` and `gh pr diff <n>` | | GitLab MR URL, `!123`, or `mr <x>` | mr | `glab mr view <iid>` and `glab mr diff <iid>` | | a bare number | pr or mr | pick by `git remote get-url origin`: github.com → `gh`, gitlab → `glab` | | Jira key (`ABC-123`) or Atlassian URL | ticket | Read issue + comments (Jira MCP), then find the current flow in code. "After" side is `(inferred)` | | anything else | plan | Current flow from code, "after" from the text. Mark it `(inferred)` | If the diff is empty (nothing staged, no changes), reply with one line only: `Nothing to brief: <why>. Try /mermaidiff <sha> or stage changes.` Don't write or overwrite a brief. For a PR or MR, read code at its head, not your local checkout. Fetch it by number, which also works for forks: GitHub `git fetch origin pull/<n>/head`, GitLab `git fetch origin merge-requests/<iid>/head`. Then read files with `git show FETCH_HEAD:<path>`. The PR/MR title and body are claims, like a commit message. If `gh` or `glab` is missing or not logged in, still brief the PR or MR with git alone. Fetch the head as above, then: 1. Base: `git merge-base origin/HEAD FETCH_HEAD`. If `origin/HEAD` is not set, run `git remote set-head origin -a` once, or try `origin/main`, then `origin/master`. 2. Diff: `git diff <base> FETCH_HEAD`. 3. Say in one line: `No gh login: PR title and description skipped.` (or `glab`, `MR`). Never fall back to the local diff for a PR or MR. If the fetch fails (private repo, wrong number, or the PR is from another repo than `origin`), say why in one line and stop. If a Jira login is missing, say so in one line and brief the ticket text the user gave as a plan. If the change is only tests, docs, comments, logs or formatting: brief is `**No flow change.** <what changed>`. Skip step 2. ## 2. Find the relatives of the change For each changed function, class, model or field: 1. **If `.codegraph/` exists:** `codegraph callers <symbol> --json`, `codegraph callees <symbol> --json`, `codegraph impact <symbol> --depth 2 --json` 2. **Else if `graphify-out/graph.json` exists:** `graphify explain "<symbol>"`, `graphify query "<question>"` 3. **Else:** grep for the symbol name. For changed **fields** (payload, model, DB doc), also grep for string access, since graphs miss it: `rg -n "['\"]<field>['\"]|\.<field>\b"` For each reader, check: **required or optional?** (`x["f"]` vs `x.get("f")`, `Optional[...]`, `omitempty`, `?.`, `??`) Before reporting any break, prove it is reachable: walk back from the reader to an entry point and look for guards that block it (`if`, early `return`, `raise`, feature flag, type or category check, config). Blocked or unsure → drop it. Report only proven breaks (see "The first rule" in `format.md`). Keep 1–2 hops only. You need the path the change travels, not the whole system. **Scope is the current repo only.** Don't open sibling repos, even if they are on disk. Callers outside the repo (UI, other services, API clients) are one participant in the diagram and one line in `Not checked:`. ## 3. Write and show the brief 1. Write the brief to `.mermaidiff/<mode>.md` in the repo root with the Write tool (the folder is gitignored by convention). If the facts gave a cache key, make the first line `<!-- mermaidiff-key: <key> -->`. 2. Render it: `python3 "${CLAUDE_SKILL_DIR}/scripts/view.py" .mermaidiff/<mode>.md --open` (a plain command, no `&&` or heredoc, so it matches the pre-approved rule). It writes `.mermaidiff/<mode>.html` and opens it in the default browser. No server. Run it outside any sandbox so it can open the browser. 3. In the chat reply, print only: the summary line, ⚠️ may-break lines, ❓ line, and the `file://` link `view.py` printed. Never print the `.md` path as a link. ## 4. Adjust and execute - If the change came from git (commit, staged, wip, range, PR, MR), the diff is fact. The user may hide steps, but never rewrite facts to match: keep proof, payload and impact true, and add one line `Hidden by you: N steps · <what>` under the stat line. Only plan and ticket briefs can be changed freely. - If the user edits lines ("drop step 4", "make it optional"), rewrite only those parts in the same file and run `view.py` again **without** `--open`. The open tab reloads itself. - When approved, the approved brief is the spec. Implement exactly that. - After implementing, run `git diff` and compare built vs approved: list ✅ matches and ⚠️ gaps (asked but not built, or built but not asked).skill/scripts/collect.py16 KB091adb8783e0upstream ↗
#!/usr/bin/env python3 """Collect the facts for a mermaidiff brief in one go, before the model starts. Reads the /mermaidiff argument from argv, works out the mode, gets the diff with git, lists the changed symbols and fields, and greps their callers and readers. Prints markdown for SKILL.md to use, followed by format.md so the model needs no extra read or permission for it. It must never fail the skill: every error becomes a line in the output and the exit code is always 0. Only the standard library is used. """ import hashlib import os import re import shutil import subprocess import sys import time T0 = time.time() DIFF_CAP = 80_000 # chars of diff text shown inline HITS_PER_NAME = 8 # caller / reader lines per symbol or field MAX_NAMES = 12 # symbols and fields to look up NOISE = ("*.lock", "*lock.json", "*.min.js", "*.min.css", "*.map", "*.svg", "*.png", "*.jpg", "*.gif", "*.ico", "*.pdf", "*.snap", "go.sum", "uv.lock") DOC_OR_TEST = re.compile(r"(\.(md|rst|txt)$|(^|/)(docs?|tests?|__tests__|spec)/|_test\.\w+$|\.(test|spec)\.\w+$|(^|/)test_[^/]+$)") KEYWORDS = {"self", "this", "return", "class", "def", "func", "function", "const", "let", "var", "if", "else", "for", "while", "import", "from", "true", "false", "none", "null", "type", "struct", "interface", "string", "int", "bool", "float", "async", "await", "public", "private", "static", "export", "default", "new", "err", "error", "ctx"} out = [] def say(line=""): out.append(line) def run(args, timeout=30): """Run a command, return (code, text). Never raises.""" try: p = subprocess.run(args, capture_output=True, text=True, timeout=timeout) return p.returncode, (p.stdout or "") + (p.stderr if p.returncode else "") except Exception as e: # missing tool, timeout, ... return 127, str(e) def git(*args, timeout=30): return run(["git", *args], timeout) def ok(*args): code, text = git(*args) return text.strip() if code == 0 else None def origin_host_and_path(): url = ok("remote", "get-url", "origin") or "" m = re.search(r"(?:@|//)([^/:]+)[:/](.+?)(?:\.git)?/?$", url) return (m.group(1).lower(), m.group(2).lower()) if m else ("", "") def default_base(): ref = ok("rev-parse", "--abbrev-ref", "origin/HEAD") if not ref: git("remote", "set-head", "origin", "-a", timeout=30) ref = ok("rev-parse", "--abbrev-ref", "origin/HEAD") for cand in ([ref] if ref else []) + ["origin/main", "origin/master", "main", "master"]: if cand and ok("rev-parse", "--verify", "--quiet", cand + "^{commit}"): return cand return None def logged_in(tool): if not shutil.which(tool): return False code, _ = run([tool, "auth", "status"], timeout=10) return code == 0 # ---------------------------------------------------------------- mode def parse(arg): a = arg.strip() first = a.split()[0] if a else "" m = re.search(r"github\.com/([^/]+/[^/]+)/pull/(\d+)", a) if m: return "pr", {"n": m.group(2), "repo": m.group(1).lower(), "host": "github"} m = re.search(r"https?://([^/]+)/(.+?)/-/merge_requests/(\d+)", a) if m: return "mr", {"n": m.group(3), "repo": m.group(2).lower(), "host": "gitlab"} m = re.fullmatch(r"(?:#|pr\s+)(\d+)", a, re.I) if m: return "pr", {"n": m.group(1), "host": "github"} m = re.fullmatch(r"(?:!|mr\s+)(\d+)", a, re.I) if m: return "mr", {"n": m.group(1), "host": "gitlab"} if re.fullmatch(r"\d+", a): host, _ = origin_host_and_path() return ("mr", {"n": a, "host": "gitlab"}) if "gitlab" in host else ("pr", {"n": a, "host": "github"}) if a == "": return "auto", {} if a in ("staged", "wip"): return a, {} m = re.fullmatch(r"(?:commit\s+)?([0-9a-fA-F]{7,40})", a) if m: return "commit", {"sha": m.group(1)} if ".." in first and " " not in a: return "range", {"spec": a} if re.fullmatch(r"[A-Z][A-Z0-9]+-\d+", first) or "atlassian.net" in a: return "ticket", {} return "plan", {} # ---------------------------------------------------------------- diff per mode def diff_cmd(base, head=None): """git diff args with noise files excluded.""" args = ["diff", "--no-color", "-U3", base] + ([head] if head else []) + ["--", "."] args += [f":(exclude,glob)**/{p}" for p in NOISE] return args def get_change(mode, info): """Return dict: mode, base, head, label, claim, notes, read_at.""" c = {"mode": mode, "notes": [], "claim": None, "read_at": "working tree"} if mode == "auto": if git("diff", "--cached", "--quiet")[0] == 1: mode = "staged" elif git("diff", "--quiet")[0] == 1: mode = "wip" else: mode = "commit" info = {"sha": "HEAD"} c["notes"].append(f"auto picked: {mode}") c["mode"] = mode if mode == "staged": c.update(base="--cached", head=None, label="staged changes", read_at="working tree (staged)") elif mode == "wip": c.update(base="HEAD", head=None, label="unstaged changes", read_at="working tree") c["wip"] = True elif mode == "commit": sha = ok("rev-parse", "--verify", "--quiet", info["sha"] + "^{commit}") if not sha: return fail(c, f"commit {info['sha']} not found in this repo") parent = ok("rev-parse", "--verify", "--quiet", sha + "^") base = parent or ok("hash-object", "-t", "tree", "/dev/null") c.update(base=base, head=sha, label=f"commit {sha[:10]}", read_at=sha) c["claim"] = ok("show", "-s", "--format=%s%n%n%b", sha) if ok("rev-parse", "--verify", "--quiet", sha + "^2"): c["notes"].append("merge commit: diff is against the first parent") elif mode == "range": spec = info["spec"] three = "..." in spec a, b = spec.split("..." if three else "..", 1) b = b or "HEAD" base = ok("merge-base", a, b) if three else ok("rev-parse", "--verify", "--quiet", a) head = ok("rev-parse", "--verify", "--quiet", b) if not base or not head: return fail(c, f"range {spec} not found") c.update(base=base, head=head, label=f"range {spec}", read_at=head) elif mode in ("pr", "mr"): return get_pr(c, mode, info) return c def fail(c, why): c["error"] = why return c def get_pr(c, mode, info): n = info["n"] host, path = origin_host_and_path() if info.get("repo") and path and not path.endswith(info["repo"]) and info["repo"] not in path: return fail(c, f"the link is for {info['repo']}, but this repo's origin is {path}. Run it inside that repo") ref = f"refs/mermaidiff/{mode}-{n}" src = f"pull/{n}/head" if mode == "pr" else f"merge-requests/{n}/head" code, text = git("fetch", "-q", "--no-tags", "origin", f"+{src}:{ref}", timeout=90) if code != 0: return fail(c, f"could not fetch {src} from origin ({text.strip().splitlines()[-1] if text.strip() else 'no output'}). Private repo without git login, or wrong number") head = ok("rev-parse", ref) base_branch = None tool = "gh" if mode == "pr" else "glab" if logged_in(tool): if mode == "pr": code, j = run(["gh", "pr", "view", n, "--json", "title,body,baseRefName"], timeout=20) if code == 0: import json d = json.loads(j) base_branch = d.get("baseRefName") c["claim"] = f"{d.get('title', '')}\n\n{d.get('body', '') or ''}".strip() else: code, j = run(["glab", "mr", "view", n, "-F", "json"], timeout=20) if code == 0: import json d = json.loads(j) base_branch = d.get("target_branch") c["claim"] = f"{d.get('title', '')}\n\n{d.get('description', '') or ''}".strip() else: c["notes"].append(f"No {tool} login: {'PR' if mode == 'pr' else 'MR'} title and description skipped.") base_ref = None if base_branch: git("fetch", "-q", "--no-tags", "origin", base_branch, timeout=60) if ok("rev-parse", "--verify", "--quiet", f"origin/{base_branch}"): base_ref = f"origin/{base_branch}" base_ref = base_ref or default_base() if not base_ref: return fail(c, "could not find the base branch (no origin/HEAD, main or master)") base = ok("merge-base", base_ref, head) if not base: return fail(c, f"no merge-base between {base_ref} and the {mode.upper()} head") c.update(base=base, head=head, label=f"{mode.upper()} {n} ({base_ref} → {ref})", read_at=ref) return c # ---------------------------------------------------------------- names and lookups DEF_RE = re.compile(r"^[+-]\s*(?:export\s+|public\s+|private\s+|protected\s+|static\s+|async\s+|pub\s+)*" r"(?:def|class|func|function|fn|interface|struct|enum|type|message|service)\s+" r"(?:\([^)]*\)\s*)?([A-Za-z_]\w*)") CONST_FN_RE = re.compile(r"^[+-]\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_]\w*)\s*=\s*(?:async\s*)?(?:\(|function)") HUNK_RE = re.compile(r"^@@[^@]*@@\s*(?:.*?\b(?:def|class|func|function|fn)\s+(?:\([^)]*\)\s*)?)?([A-Za-z_]\w*)?") FIELD_RE = re.compile(r"^[+-]\s*(?:readonly\s+)?([A-Za-z_]\w*)\??\s*:\s*[A-Za-z\[\{\"'(]") GO_FIELD_RE = re.compile(r'^[+-]\s*([A-Z]\w*)\s+[\w.*\[\]]+\s*(?:`[^`]*json:"(\w+))?') KEY_RE = re.compile(r"""^[+-].*?["'](\w{3,})["']\s*[:=]""") def names_from(diff): syms, fields = [], [] for line in diff.splitlines(): if line.startswith(("+++", "---")): continue if line.startswith("@@"): m = HUNK_RE.match(line) if m and m.group(1): syms.append(m.group(1)) continue if not line.startswith(("+", "-")): continue for rx, bucket in ((DEF_RE, syms), (CONST_FN_RE, syms)): m = rx.match(line) if m: bucket.append(m.group(1)) m = GO_FIELD_RE.match(line) if m and (m.group(2) or m.group(1)): fields.append(m.group(2) or m.group(1)) m = FIELD_RE.match(line) if m: fields.append(m.group(1)) m = KEY_RE.match(line) if m: fields.append(m.group(1)) def clean(xs): seen, res = set(), [] for x in xs: if len(x) < 3 or x.lower() in KEYWORDS or x in seen or re.match(r"(Test|test_|Benchmark|Example)", x): continue seen.add(x) res.append(x) return res[:MAX_NAMES] syms = clean(syms) fields = [f for f in clean(fields) if f not in syms] return syms, fields def grep(pattern, at, word=False, regex=False): """git grep at a commit or the working tree. Returns lines, capped.""" args = ["grep", "-n", "-I", "--no-color"] if word: args.append("-w") args += ["-E" if regex else "-F", "-e", pattern] if at: args.append(at) args += ["--", "."] + [f":(exclude,glob)**/{p}" for p in NOISE] code, text = git(*args, timeout=30) lines = [l for l in text.splitlines() if l.strip()] if code == 0 else [] if at: lines = [l[len(at) + 1:] if l.startswith(at + ":") else l for l in lines] more = len(lines) - HITS_PER_NAME return lines[:HITS_PER_NAME], max(more, 0) # ---------------------------------------------------------------- main def main(): arg = " ".join(sys.argv[1:]) arg = arg.strip() if not ok("rev-parse", "--is-inside-work-tree"): say("mermaidiff facts: not inside a git repo. Plan or ticket mode only.") return mode, info = parse(arg) say("## Pre-collected facts") say(f"- argument: `{arg or '(none)'}` → mode **{mode}**") if mode in ("ticket", "plan"): say("- no git diff for this mode. Follow SKILL.md steps 1 and 2 by hand.") return c = get_change(mode, info) for n in c["notes"]: say(f"- {n}") if c.get("error"): say(f"- **stop:** {c['error']}") return mode = c["mode"] base, head = c["base"], c["head"] stat_args = ["diff", "--stat=120"] + ([base] if base != "--cached" else ["--cached"]) + ([head] if head else []) if base == "--cached": dargs = ["diff", "--cached", "--no-color", "-U3", "--", "."] + [f":(exclude,glob)**/{p}" for p in NOISE] else: dargs = diff_cmd(base, head) stat = ok(*stat_args) or "" _, diff = git(*dargs, timeout=60) if not diff.strip(): say(f"- **empty:** nothing changed in {c['label']}.") return files = ok(*(["diff", "--name-only"] + (["--cached"] if base == "--cached" else [base]) + ([head] if head else []))) or "" files = [f for f in files.splitlines() if f] key = hashlib.sha256((mode + diff).encode()).hexdigest()[:16] brief = os.path.join(".mermaidiff", f"{mode}.md") say(f"- change: {c['label']}") say(f"- read code at: `{c['read_at']}`" + (" (use `git show <ref>:<path>`)" if c['read_at'] not in ("working tree", "working tree (staged)") else "")) say(f"- brief file: `{brief}` · cache key: `{key}`") try: with open(brief, encoding="utf-8") as fh: if f"mermaidiff-key: {key}" in fh.readline(): say(f"- **cache hit:** `{brief}` already briefs this exact diff. Reuse it: rerun view.py with --open, reply with its summary, and stop.") except OSError: pass graphs = [g for g in (".codegraph", "graphify-out/graph.json") if os.path.exists(g)] say(f"- code graph: {', '.join(graphs) if graphs else 'none, callers below come from git grep'}") if files and all(DOC_OR_TEST.search(f) for f in files): say("- hint: only docs or tests changed. Likely **No flow change.**") if c.get("claim"): say("\n### Claim (commit message / PR text, not proof)") say("```text") say(c["claim"][:3000]) say("```") say("\n### Diff stat") say("```text") say(stat.strip()[:4000]) say("```") say("\n### Diff") say("```diff") if len(diff) > DIFF_CAP: say(diff[:DIFF_CAP]) say("```") say(f"(diff cut at {DIFF_CAP} chars of {len(diff)}. Read the rest of the files listed in the stat with `git diff` or Read.)") else: say(diff.rstrip()) say("```") syms, fields = names_from(diff) at = None if c["read_at"].startswith("working tree") else c["read_at"] if syms: say("\n### Callers of changed symbols (git grep, word match)") for s in syms: lines, more = grep(s, at, word=True) if len(lines) + more > 40: say(f"- `{s}`: {len(lines) + more} hits, too common to list. Search it yourself if it matters.") continue say(f"- `{s}`: {len(lines) + more} hits" + (f" (first {len(lines)})" if more else "")) for l in lines: say(f" - {l[:200]}") if fields: say("\n### Readers of changed fields (string and attribute access)") for f in fields: pat = rf"""["']{re.escape(f)}["']|\.{re.escape(f)}\b""" lines, more = grep(pat, at, regex=True) if len(lines) + more > 40: say(f"- `{f}`: {len(lines) + more} hits, too common to list. Search it yourself if it matters.") continue say(f"- `{f}`: {len(lines) + more} hits" + (f" (first {len(lines)})" if more else "")) for l in lines: say(f" - {l[:200]}") say(f"\n_collected in {time.time() - T0:.1f}s_") if __name__ == "__main__": try: main() except Exception as e: # never fail the skill say(f"- collect.py error: {e}. Collect the facts by hand (SKILL.md steps 1 and 2).") try: fmt = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "format.md") with open(fmt, encoding="utf-8") as fh: say("\n---\n## Output format (format.md)\n") say(fh.read()) except OSError as e: say(f"- could not read format.md ({e}). Read it from the skill folder.") print("\n".join(out)) sys.exit(0)skill/scripts/view.py4.7 KB8dcdd765b014upstream ↗
#!/usr/bin/env python3 """Render a mermaidiff brief (.md) to a standalone .html and open it in the default browser. Usage: view.py <brief.md> [--open] [--no-open] No server. Writes <name>.html and <name>.version.js next to the brief. An open tab re-reads the version file every ~1.5s and reloads itself when the brief changes. --open opens the browser (use it for a new /mermaidiff run). Without it, the browser opens only the first time a brief is rendered; later renders just update the open tab. """ import hashlib, json, platform, re, subprocess, sys from pathlib import Path HERE = Path(__file__).resolve().parent TEMPLATE = HERE / "viewer.html" def open_in_browser(target): """Open a URL or file in the default browser. Returns True on success.""" system = platform.system() if system == "Darwin": cmd = ["open", target] elif system == "Windows": cmd = ["cmd", "/c", "start", "", target] elif "microsoft" in platform.release().lower(): # WSL cmd = ["wslview", target] else: cmd = ["xdg-open", target] try: return subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10).returncode == 0 except Exception: return False SYMBOLS = [("➕", "+{} new"), ("✏️", "~{} changed"), ("➖", "−{} removed"), ("⚠️", "⚠️ {} may break")] TIERS = [("🟢", "verified"), ("🔵", "backed by code"), ("🟡", "inferred")] def compute_stat(text): """Count the change symbols in the diagram, so the stat line is never wrong.""" blocks = re.findall(r"```mermaid\n(.*?)```", text, re.S) if not blocks: return None labels = [l.split(":", 1)[1].strip() for b in blocks for l in b.splitlines() if ":" in l and re.search(r"-?->>|-x|--x|->", l)] changed = [l for l in labels if l.startswith(tuple(sym for sym, _ in SYMBOLS))] parts = [fmt.format(n) for sym, fmt in SYMBOLS if (n := sum(l.startswith(sym) for l in labels))] questions = max(sum(l.startswith("❓") for l in labels), len(re.findall(r"^\s*[-*] ❓", text, re.M))) if questions: parts.append(f"❓ {questions}") for sym, word in TIERS: n = sum(sym in l for l in changed) if n and changed: parts.append(f"{sym} {n} of {len(changed)} {word}") return "`" + " · ".join(parts) + "`" if parts else None def fix_stat_line(brief): """Replace the stat line with the computed one. Keeps exactly one, wherever it was.""" text = brief.read_text() stat = compute_stat(text) if not stat: return text pattern = re.compile(r"`[^`]*\b(new|changed|removed|break|may break)\b[^`]*`") lines = text.split("\n") hits = [i for i, l in enumerate(lines) if pattern.fullmatch(l.strip())] if hits: lines[hits[0]] = stat for i in reversed(hits[1:]): # drop extra stat lines del lines[i] if i < len(lines) and i > 0 and not lines[i].strip() and not lines[i - 1].strip(): del lines[i] else: end = next((i for i, l in enumerate(lines) if i > 0 and not l.strip()), 1) lines[end:end] = ["", stat] new = "\n".join(lines) if new != text: brief.write_text(new) return new def render(brief): """Write <name>.html (the page) and then <name>.version.js (the reload signal).""" text = fix_stat_line(brief) version = hashlib.sha1(text.encode()).hexdigest()[:12] head = ( "<script>" f"window.MERMAIDIFF_EMBED={json.dumps(text)};" f"window.MERMAIDIFF_VERSION={json.dumps(version)};" f"window.MERMAIDIFF_NAME={json.dumps(brief.parent.name + '/' + brief.name)};" f"window.MERMAIDIFF_VENDOR={json.dumps((HERE / 'vendor').as_uri() + '/')};" "</script>\n" ) html = brief.with_suffix(".html") html.write_text(TEMPLATE.read_text().replace("<script>", head + "<script>", 1)) stamp = brief.parent / (brief.stem + ".version.js") stamp.write_text(f"window.__mermaidiffVersion && window.__mermaidiffVersion({json.dumps(version)});\n") return html def main(): args = sys.argv[1:] files = [a for a in args if not a.startswith("--")] if not files: sys.exit(__doc__) brief = Path(files[0]).resolve() if not brief.is_file() or brief.suffix != ".md": sys.exit(f"mermaidiff: not a .md file: {brief}") html = render(brief) url = html.as_uri() marker = brief.parent / f".opened-{brief.stem}" if "--no-open" not in args and (not marker.exists() or "--open" in args): if open_in_browser(url): marker.touch() else: print("mermaidiff: could not open a browser, open the link below") print(f"mermaidiff: {url}") if __name__ == "__main__": main()skill/scripts/viewer.html8.9 KBb78d5fa2ca2cupstream ↗
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mermaidiff</title> <style> :root{--bg:#fbfaf7;--fg:#1f1e1b;--muted:#6b6a64;--line:#e4e2da;--card:#ffffff;--add:#e6f4ea;--addfg:#1a7f37;--del:#fdecec;--delfg:#b42318;--code:#f3f2ee} @media (prefers-color-scheme:dark){:root{--bg:#161614;--fg:#e8e6df;--muted:#9c9a92;--line:#2c2b28;--card:#1d1c1a;--add:#0f2a17;--addfg:#6fdc8c;--del:#2e1212;--delfg:#ff8a80;--code:#232220}} *{box-sizing:border-box} body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",Inter,sans-serif} header{position:sticky;top:0;z-index:2;display:flex;gap:12px;align-items:center;padding:10px 20px;background:var(--bg);border-bottom:1px solid var(--line);font-size:13px;color:var(--muted)} header b{color:var(--fg);font-weight:600} header .sp{flex:1} header button{font:inherit;color:var(--fg);background:var(--card);border:1px solid var(--line);border-radius:6px;padding:4px 10px;cursor:pointer} #dot{width:8px;height:8px;border-radius:50%;background:#1a7f37} main{max-width:980px;margin:0 auto;padding:24px 20px 80px} main>p:first-child{font-size:20px;line-height:1.4} h1,h2,h3{font-weight:600;line-height:1.3} code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.88em;background:var(--code);padding:1px 5px;border-radius:4px} pre{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:12px 0;overflow:auto} pre code{background:none;padding:0;display:block} .dl{display:block;padding:0 16px;white-space:pre} .dl.add{background:var(--add);color:var(--addfg)} .dl.del{background:var(--del);color:var(--delfg)} .mmd{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:16px;margin:16px 0;overflow:auto;text-align:center} .stat{display:flex;flex-wrap:wrap;gap:8px;margin:8px 0 4px;font-size:13px} .stat span{padding:2px 8px;border-radius:999px;border:1px solid var(--line);background:var(--card)} .stat .warn{border-color:#d08700;color:#b26b00} .err{color:var(--delfg);white-space:pre-wrap;text-align:left;font-size:13px} ul{padding-left:22px} li{margin:4px 0} </style> </head> <body> <header><span id="dot"></span><b>mermaidiff</b><span id="file"></span><span class="sp"></span><span id="when"></span><button id="copy" title="Copy markdown, GitLab renders the Mermaid">Copy for MR</button></header> <main id="out">Loading…</main> <script> // Load a script from the local vendor folder first, then the CDN. Resolves null if both fail. function load(local, cdn) { return new Promise(ok => { const tag = src => { const s = document.createElement("script"); s.src = src; s.onload = () => ok(src); s.onerror = () => src === cdn ? ok(null) : tag(cdn); document.head.appendChild(s); }; tag(local); }); } </script> <script type="module"> // Filled in by view.py when it writes the .html. No server: the page is a snapshot // that reloads itself when <name>.version.js reports a new version. const RAW = window.MERMAIDIFF_EMBED || ""; const VERSION = window.MERMAIDIFF_VERSION || ""; const VENDOR = window.MERMAIDIFF_VENDOR || "vendor/"; const esc = s => s.replace(/[&<>]/g, c => ({"&":"&","<":"<",">":">"}[c])); document.getElementById("file").textContent = window.MERMAIDIFF_NAME || ""; const markedSrc = await load(VENDOR + "marked.min.js", "https://cdn.jsdelivr.net/npm/marked@12/marked.min.js"); const mermaidSrc = await load(VENDOR + "mermaid.min.js", "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"); const mermaid = window.mermaid; if (mermaid) { const dark = matchMedia("(prefers-color-scheme: dark)").matches; // Notes are neutral grey so they never look like a ✏️ changed (yellow) block. mermaid.initialize({startOnLoad:false, theme: dark ? "dark" : "default", securityLevel:"strict", sequence:{useMaxWidth:true}, themeVariables: dark ? {noteBkgColor:"#2c2c2a", noteBorderColor:"#5f5e5a", noteTextColor:"#d3d1c7"} : {noteBkgColor:"#f1efe8", noteBorderColor:"#d3d1c7", noteTextColor:"#444441"}}); } async function render(){ const out = document.getElementById("out"); if (!markedSrc) { out.innerHTML = `<pre><code>${esc(RAW)}</code></pre>`; return; } out.innerHTML = marked.parse(RAW); for (const el of out.querySelectorAll("pre code.language-diff")) { el.innerHTML = el.textContent.replace(/\n$/,"").split("\n").map(l => `<span class="dl ${l.startsWith("+") ? "add" : l.startsWith("-") ? "del" : ""}">${esc(l) || " "}</span>`).join(""); } const src = [...out.querySelectorAll("pre code.language-mermaid")].map(e => e.textContent).join("\n"); const arrows = src.split("\n").filter(l => /(->>|-->>|->|-->|-x|--x)/.test(l) && l.includes(":")).map(l => l.split(":").slice(1).join(":")); const c = k => arrows.filter(l => l.trim().startsWith(k)).length; const qList = [...out.querySelectorAll("li")].filter(li => li.textContent.trim().startsWith("❓")).length; const counts = {"+ new": c("➕"), "~ changed": c("✏️"), "− removed": c("➖"), "⚠️ may break": c("⚠️"), "❓": Math.max(c("❓"), qList)}; const tiers = {"🟢": arrows.filter(l => l.includes("🟢")).length, "🔵": arrows.filter(l => l.includes("🔵")).length, "🟡": arrows.filter(l => l.includes("🟡")).length}; const changed = counts["+ new"] + counts["~ changed"] + counts["− removed"] + counts["⚠️ may break"]; if (src) { const st = document.createElement("div"); st.className = "stat"; const pill = (t, w) => `<span class="${w ? "warn" : ""}">${t}</span>`; let h = Object.entries(counts).filter(([, v]) => v).map(([k, v]) => pill(k.startsWith("❓") ? `❓ ${v}` : k.startsWith("⚠️") ? `⚠️ ${v} may break` : `${k.split(" ")[0]}${v} ${k.split(" ")[1]}`, k.startsWith("⚠️"))).join(""); h += Object.entries(tiers).filter(([, v]) => v).map(([k, v]) => pill(`${k} ${v}/${changed} ${{"🟢":"verified","🔵":"code","🟡":"inferred"}[k]}`)).join(""); const untiered = arrows.filter(l => /^\s*(➕|✏️|➖|⚠️)/.test(l) && !/[🟢🔵🟡]/u.test(l)).length; if (untiered) h += pill(`${untiered} changed step(s) without a tier`, true); // the stat line is a paragraph that holds only one inline code span const statP = [...out.querySelectorAll("p")].find(p => p.children.length === 1 && p.firstElementChild.tagName === "CODE" && p.textContent.trim() === p.firstElementChild.textContent.trim() && /new|changed|removed|break|❓/.test(p.textContent)); const written = statP ? statP.firstElementChild : null; if (written) { const w = written.textContent.replace(/-(\d)/g, "−$1"), num = re => +((w.match(re) || [0, 0])[1]); if (num(/\+(\d+)/) !== counts["+ new"] || num(/~(\d+)/) !== counts["~ changed"] || num(/−(\d+)/) !== counts["− removed"]) h += pill("stat line does not match diagram", true); } st.innerHTML = h; out.querySelector("p").after(st); if (written && written.parentElement.textContent.trim() === written.textContent.trim()) { st.title = "LLM wrote: " + written.textContent; written.parentElement.remove(); } } let n = 0; for (const el of out.querySelectorAll("pre code.language-mermaid")) { if (!mermaid) break; const box = document.createElement("div"); box.className = "mmd"; el.parentElement.replaceWith(box); try { box.innerHTML = (await mermaid.render("m" + (n++), el.textContent)).svg; } catch (e) { box.innerHTML = `<div class="err">Mermaid error: ${esc(String(e.message || e))}</div><pre><code>${esc(el.textContent)}</code></pre>`; } } const t = out.querySelector("p strong"); if (t) document.title = "mermaidiff · " + t.textContent.slice(0, 60); const mode = !mermaidSrc ? "no mermaid · " : mermaidSrc.startsWith("https://cdn") ? "cdn · " : "offline · "; document.getElementById("when").textContent = mode + "updated " + new Date().toLocaleTimeString(); const m = location.hash.match(/y=(\d+)/); if (m) scrollTo(0, +m[1]); } // Live reload without a server: re-load <name>.version.js and reload the page if it changed. const stamp = location.pathname.split("/").pop().replace(/\.html$/, ".version.js"); window.__mermaidiffVersion = v => { document.getElementById("dot").style.background = "#1a7f37"; if (v && v !== VERSION) { location.hash = "y=" + Math.round(scrollY); location.reload(); } }; function poll(){ const s = document.createElement("script"); s.src = stamp + "?t=" + Date.now(); s.onload = () => { s.remove(); setTimeout(poll, 1500); }; s.onerror = () => { s.remove(); document.getElementById("dot").style.background = "#9c9a92"; setTimeout(poll, 3000); }; document.head.appendChild(s); } document.getElementById("copy").onclick = async () => { try { await navigator.clipboard.writeText(RAW); } catch { const ta = Object.assign(document.createElement("textarea"), {value: RAW}); document.body.append(ta); ta.select(); document.execCommand("copy"); ta.remove(); } const b = document.getElementById("copy"); b.textContent = "Copied"; setTimeout(() => b.textContent = "Copy for MR", 1200); }; await render(); poll(); </script> </body> </html>skill/format.md6.6 KB23f642709d4dupstream ↗
# mermaidiff output format You turn a change into a short, git-style brief. Input can be a git diff, code graph data (callers, callees, readers), a ticket, or a plan from discussion. Output ONLY the sections below, in this order. No intro, no apology, no story of what you read, no "now I understand". If a section has nothing, skip it. ## The first rule: no false positives A wrong warning is worse than a missing one. It confuses the reader and adds reading. - Only state what the diff or the code proves. **If it isn't proven, leave it out.** - Never warn about something that "could" happen. A risk is shown only when you can name the exact reader that breaks AND show the path to it is reachable (no guard, flag, type check or early return blocks it). - Anything outside the repo (other services, UIs, queues, config in production) is unknown. Don't warn about it. Name it once in `Not checked:`. - Describe only what this repo's code does. Commit messages, MR titles and tickets are claims, not facts: never repeat what they say about other systems ("the UI now joins…"). Say what the code itself shows ("`clusters[].id` now equals `nodes[].cluster_id` in the same response"). - Name callers and receivers outside the repo by role only: `API client`, `consumer`, `publisher`, `job runner`. Never by a product name you didn't read in this repo's code. - Fewer lines win. When in doubt, cut. - **Below the diagram, facts only.** Each line is a file:line, a value or a name. No "this means", no "so that", no repeating the diagram in words. ## Rules - **Evidence tier on every changed step.** End each ➕ / ✏️ / ➖ / ⚠️ label with one tier: - 🟢 verified: seen in a test run or real trace - 🔵 code: backed by the diff or code you read - 🟡 inferred: from a ticket, plan, or your own reading Never upgrade a tier. When unsure, use 🟡. - **No flow change** (only tests, docs, comments, logs, formatting, renames with no behavior change) → output one line: `**No flow change.** <what changed in 5–10 words>` and stop. - **Payload-only change** (model, schema, DTO, env) → show the payload diff and a small diagram of **where that payload travels** (endpoint → service → storage → readers). - **Hide unchanged steps.** Keep only the steps needed to understand the change. Max 12 steps. - **Show where the change goes, not only where it happens.** Prefer arrows between participants (the value travelling to its reader) over self-arrows like `BE->>BE`. Use a self-arrow only for pure internal logic. - **Shared code: name every entry point.** If the changed code is called from more than one route, job or handler, the entry participant lists them all (`participant R as orders · admin orders · export`). - **Short labels.** Max 8 words per arrow or note. Plain words. - **Never guess file paths or names.** If unknown, say so in ❓. ## Sections ### 1. Summary One bold line: what the code changes. Max 2 lines. Build it from the diff only, never from the commit message, MR title or ticket. If the commit message or MR title claims a change the diff does not show (wrong area, missing piece, different behavior), add one line right after the summary: `⚠️ Message says "<quote>", the diff <what it actually changes>.` Only when the mismatch is clear from the diff itself. Vague or partial messages are fine, don't flag them. Then a stat line, like `git --stat`, counting changed diagram steps. `view.py` recounts it from the diagram and overwrites it, so a wrong count is fixed automatically: `+3 new · ~2 changed · −1 removed · ⚠️ 1 may break · ❓ 1 · 🔵 5 of 6 backed by code` ### 2. Flow diff A Mermaid `sequenceDiagram`: - `autonumber` on. - Short participant aliases: `participant API as orders-api`. - Max 5 participants. Merge participants that only pass data through. - Group changed steps in colored blocks: - ➕ new: `rect rgba(0,180,0,0.12)` - ✏️ changed: `rect rgba(255,190,0,0.15)` - ➖ removed: `rect rgba(220,0,0,0.12)` - ⚠️ may break (proven path): `rect rgba(255,140,0,0.18)` with ⚠️ in the label - ❓ unclear: plain step with ❓ in the label - Start each changed arrow label with its symbol: `➕`, `✏️`, `➖`, `⚠️`, `❓`. - Unchanged context steps: no color, no symbol. Keep at most 1 before and 1 after each changed block. Replace any other run of unchanged steps with one `Note over A,B: … N unchanged steps`. - Do not use `;` or `#` in labels. Use `·` to separate parts. ### 3. Proof Max 5 bullets. One per changed step, numbered to match `autonumber`; steps in the same file share one bullet. Only the step number, `file.py:line` and the code fact, max 6 words. No symbol or tier (the diagram has them). Full path only if two changed files share a name: `- 3 · checkout.py:88 · coupon applied before tax` ### 4. Payload diff Only if a request, response, event, model, DB document, or env changed. Put `↳ step N` above the block (the step that carries it). Use a ```diff block, max 10 lines. Show only changed keys plus 1 neighbor for context. Note the type and whether it is required or optional. ### 5. May break Max 3. Only readers in this repo with a proven reachable path (see the first rule), each with its proof: - ⚠️ `file.py:line` · what breaks, max 8 words · reached from `trigger.py:line` No proven path → skip the list. Don't list safe readers, guesses or "may behave differently". Then always one line, max 12 words: `Not checked: <outside the repo, by role only>.` ### 6. Open questions Max 1 ❓. Only questions about the change itself that the diff can't answer (intent, missing case in the code). Never questions about other systems. ## Example **Coupons now apply before tax, and expired coupons are rejected at checkout.** `+1 new · ~1 changed · ❓ 1 · 🔵 2 of 2 backed by code` ```mermaid sequenceDiagram autonumber actor C as API client participant API as POST /checkout participant P as PricingService participant DB as Postgres C->>API: checkout cart API->>P: price(cart, coupon) rect rgba(0,180,0,0.12) P->>DB: ➕ reject coupon if expires_at passed 🔵 end rect rgba(255,190,0,0.15) P-->>API: ✏️ discount applied before tax 🔵 end API-->>C: order total ``` - 3, 4 · `pricing.py:42,61` · expiry check · discount before `add_tax()` ↳ step 4 ```diff order: subtotal: 100.00 - tax: 10.00 # on full subtotal + tax: 9.00 # on discounted subtotal discount: 10.00 - total: 100.00 + total: 99.00 ``` - ⚠️ `invoice.py:77` · taxes full subtotal, total won't match · reached from `checkout.py:95` Not checked: API clients outside the repo. - ❓ Should orders already in the cart keep the old tax rule?README.mdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/osmangoninahid-mermaidiff-skill.md