Skip to content

samuelpatro/.claude / .claude/skills/sync-claude

sync-claude

Verified

Sync the live ~/.claude global config (settings.json, CLAUDE.md, statusline.ts, own skills, skills.sh lock file) into this git backup repo, then commit. Allowlist-based so credentials, history, and project transcripts are never copied. Use when the user says "sync my claude config", "back up .claude", "update the .claude repo", or runs "/sync-claude".

FileKindSize
SKILL.mdskill md3.0 KB
install-skills.tsscript1.8 KB
sync.tsscript8.3 KB
#!/usr/bin/env bun
/**
 * Sync the live Claude Code config into this git repo. Allowlist-based by
 * design: only the paths named below are ever read, so anything else in
 * ~/.claude (.credentials.json, history.jsonl, projects/, sessions/, ...) can
 * never be picked up. A value-shaped secret scan on every copied text file is
 * a second safety net.
 *
 * What is synced (live -> repo):
 *   - FILES from ~/.claude (settings.json, CLAUDE.md, statusline.ts)
 *   - own skills: every entry in ~/.claude/skills that is NOT managed by the
 *     skills.sh CLI, mirrored into skills/<name>/ (symlinks are followed)
 *   - ~/.agents/.skill-lock.json, the skills.sh install manifest, copied to
 *     .agents/.skill-lock.json. Managed skills are never vendored; reinstall
 *     them with `bun .claude/skills/sync-claude/install-skills.ts`.
 *
 * This is a project skill of the backup repo only, it is not installed into
 * ~/.claude/skills, so it never syncs itself.
 *
 *   bun sync.ts          # check: report what would change, copy nothing
 *   bun sync.ts --apply  # copy changed files (text normalized to LF)
 *
 * Exit codes: 0 = ok, 2 = a possible secret was found and that item was skipped.
 */
import {
  existsSync,
  mkdirSync,
  readdirSync,
  readFileSync,
  realpathSync,
  rmSync,
  statSync,
  writeFileSync,
} from "fs";
import { dirname, join, relative } from "path";
import { homedir } from "os";

const FILES = ["settings.json", "CLAUDE.md", "statusline.ts"];
const SKIP_NAMES = new Set([".DS_Store", "node_modules", ".git"]);

// Repo root is three levels up from this script (.claude/skills/sync-claude/sync.ts).
const REPO = join(import.meta.dir, "..", "..", "..");
const LIVE = join(homedir(), ".claude");
const LIVE_SKILLS = join(LIVE, "skills");
const REPO_SKILLS = join(REPO, "skills");
const LIVE_LOCK = join(homedir(), ".agents", ".skill-lock.json");
const REPO_LOCK = join(REPO, ".agents", ".skill-lock.json");

const apply = process.argv.includes("--apply");

// Match secret VALUES, not keywords, so prose like "never print token files"
// in CLAUDE.md does not trip the scan.
const SECRET_PATTERNS: [string, RegExp][] = [
  ["Anthropic key", /sk-ant-[A-Za-z0-9_-]{20,}/],
  ["OpenAI key", /\bsk-[A-Za-z0-9]{32,}\b/],
  ["GitHub token", /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\b/],
  ["GitHub PAT", /\bgithub_pat_[A-Za-z0-9_]{40,}\b/],
  ["AWS key id", /\bAKIA[0-9A-Z]{16}\b/],
  ["Google key", /\bAIza[0-9A-Za-z_-]{35}\b/],
  ["Slack token", /\bxox[baprs]-[A-Za-z0-9-]{10,}/],
  ["Private key", /-----BEGIN (?:RSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/],
  ["JWT", /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/],
  [
    "Secret assignment",
    /(?:secret|token|password|passwd|api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|authorization|bearer)["']?\s*[:=]\s*["'][A-Za-z0-9_\-./+=]{16,}["']/i,
  ],
];

const norm = (s: string) => s.replace(/\r\n/g, "\n");
const isText = (buf: Buffer) => !buf.subarray(0, 8000).includes(0);

function scan(name: string, content: string): string[] {
  const hits: string[] = [];
  content.split("\n").forEach((line, i) => {
    for (const [label, re] of SECRET_PATTERNS) {
      if (re.test(line)) hits.push(`${name}:${i + 1} looks like ${label}`);
    }
  });
  return hits;
}

/** Read a file for comparison/copy: text is LF-normalized, binary is raw. */
function load(path: string): Buffer {
  const buf = readFileSync(path);
  return isText(buf) ? Buffer.from(norm(buf.toString("utf8"))) : buf;
}

const listDir = (dir: string) =>
  readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));

function listFiles(dir: string, base = dir): string[] {
  const out: string[] = [];
  for (const entry of listDir(dir)) {
    if (SKIP_NAMES.has(entry.name)) continue;
    const full = join(dir, entry.name);
    const st = statSync(full); // follows symlinks
    if (st.isDirectory()) out.push(...listFiles(full, base));
    else if (st.isFile()) out.push(relative(base, full));
  }
  return out.sort();
}

let changed = 0;
let blocked = 0;
const summary: string[] = [];
const pad = (verb: string) => verb.padEnd(11);
const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;

/** Copy one file live -> repo. */
function syncFile(label: string, livePath: string, repoPath: string) {
  const live = load(livePath);
  const repo = existsSync(repoPath) ? load(repoPath) : null;
  if (repo && repo.equals(live)) {
    summary.push(`${pad("unchanged")}${label}`);
    return;
  }
  const hits = isText(live) ? scan(label, live.toString("utf8")) : [];
  if (hits.length) {
    blocked++;
    summary.push(`${pad("BLOCKED")}${label} (possible secret, not copied):`);
    for (const h of hits) summary.push(`             ${h}`);
    return;
  }
  changed++;
  if (apply) {
    mkdirSync(dirname(repoPath), { recursive: true });
    writeFileSync(repoPath, live);
    summary.push(`${pad("copied")}${label}`);
  } else {
    summary.push(`${pad("would copy")}${label}`);
  }
}

/**
 * Mirror a directory src -> dst: copy changed files, delete files that no
 * longer exist in src. A secret hit in any file skips the whole skill so a
 * half-updated skill never lands in git.
 */
function syncDir(label: string, src: string, dst: string) {
  const srcFiles = listFiles(src);
  const dstFiles = existsSync(dst) ? listFiles(dst) : [];

  const hits: string[] = [];
  const toCopy: string[] = [];
  for (const rel of srcFiles) {
    const live = load(join(src, rel));
    const repoPath = join(dst, rel);
    if (existsSync(repoPath) && load(repoPath).equals(live)) continue;
    if (isText(live)) hits.push(...scan(`${label}/${rel}`, live.toString("utf8")));
    toCopy.push(rel);
  }
  const toDelete = dstFiles.filter((rel) => !srcFiles.includes(rel));

  if (hits.length) {
    blocked++;
    summary.push(`${pad("BLOCKED")}${label} (possible secret, skill not copied):`);
    for (const h of hits) summary.push(`             ${h}`);
    return;
  }
  if (!toCopy.length && !toDelete.length) {
    summary.push(`${pad("unchanged")}${label}`);
    return;
  }

  changed++;
  const what = [
    toCopy.length ? plural(toCopy.length, "file") : "",
    toDelete.length ? `${toDelete.length} removed` : "",
  ]
    .filter(Boolean)
    .join(", ");
  if (!apply) {
    summary.push(`${pad("would copy")}${label} (${what})`);
    return;
  }
  for (const rel of toCopy) {
    const out = join(dst, rel);
    mkdirSync(dirname(out), { recursive: true });
    writeFileSync(out, load(join(src, rel)));
  }
  for (const rel of toDelete) rmSync(join(dst, rel), { force: true });
  summary.push(`${pad("copied")}${label} (${what})`);
}

// 1. Top-level config files.
for (const file of FILES) {
  const livePath = join(LIVE, file);
  if (!existsSync(livePath)) {
    summary.push(`${pad("skip")}${file} (not present in ~/.claude)`);
    continue;
  }
  syncFile(file, livePath, join(REPO, file));
}

// 2. skills.sh lock file. Skills listed in it are managed, never vendored.
const managed = new Set<string>();
if (existsSync(LIVE_LOCK)) {
  const lock = JSON.parse(readFileSync(LIVE_LOCK, "utf8"));
  for (const name of Object.keys(lock.skills ?? {})) managed.add(name);
  syncFile(".agents/.skill-lock.json", LIVE_LOCK, REPO_LOCK);
} else {
  summary.push(`${pad("skip")}.agents/.skill-lock.json (skills.sh not installed)`);
}

// 3. Own skills: everything in ~/.claude/skills that skills.sh does not manage.
const own = new Set<string>();
if (existsSync(LIVE_SKILLS)) {
  for (const entry of listDir(LIVE_SKILLS)) {
    const name = entry.name;
    if (name.startsWith(".")) continue;
    const full = join(LIVE_SKILLS, name);
    if (!statSync(full).isDirectory()) continue; // follows symlinks
    if (managed.has(name)) continue;
    own.add(name);
    syncDir(`skills/${name}`, realpathSync(full), join(REPO_SKILLS, name));
  }
}

// 4. Repo skills that are not live own skills: report, never delete.
if (existsSync(REPO_SKILLS)) {
  for (const entry of listDir(REPO_SKILLS)) {
    const name = entry.name;
    if (!entry.isDirectory() || own.has(name)) continue;
    const why = managed.has(name)
      ? "managed by skills.sh, remove from repo"
      : "not in ~/.claude/skills, delete or restore by hand";
    summary.push(`${pad("orphan")}skills/${name} (${why})`);
  }
}

console.log(summary.join("\n"));
console.log(
  `\n${apply ? "Applied" : "Check"}: ${changed} changed, ${blocked} blocked` +
    (!apply && changed ? "  (run with --apply to copy)" : ""),
);
if (blocked) process.exit(2);
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall