Add designbook integration tooling + stack-adapter workplan
- designbook/ local mirror of the Claude Design project, with conventions (@dsCard/manifest) and freshness marker docs. - make designbook-sync + scripts/designbook-sync.mjs: record what a sync changed into RecentChanges.md, grouped by layer, with last /design-sync time. - make designbook-check + scripts/check_designbook_staleness.py: llm-connect (claude-code adapter) backend that detects when the cloud designbook moved ahead and warns the local mirror is outdated. - .design-sync/config.json: recorded target project pin (WhyNot Design System). - WHYNOT-WP-0002: workplan for a technology-neutral designbook IR with scaffold+drift-detect stack adapters (Lit reference). - gitignore Python artifacts. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
149
scripts/check_designbook_staleness.py
Normal file
149
scripts/check_designbook_staleness.py
Normal file
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Staleness check for the local designbook mirror, backed by llm-connect.
|
||||
|
||||
`make designbook-sync` can only report what the marker (designbook/.design-sync.json)
|
||||
already knows. This script refreshes the "is the cloud ahead?" half: it asks the
|
||||
Claude Design project for its current `updatedAt` and, if that is newer than the
|
||||
last `/design-sync`, records it so the next report warns the mirror is OUTDATED.
|
||||
|
||||
Only the **claude-code** llm-connect adapter can answer this — it drives the local
|
||||
`claude` binary, which has the DesignSync tool over your claude.ai login. Gemini/
|
||||
OpenRouter/OpenAI cannot see your Claude Design project. No secret is placed in the
|
||||
prompt: DesignSync authenticates through the local login, not an API key — see
|
||||
.claude/rules/credential-routing.md.
|
||||
|
||||
python scripts/check_designbook_staleness.py
|
||||
python scripts/check_designbook_staleness.py --remote-updated <iso> # skip the
|
||||
LLM call and use a known value (offline test / manual override)
|
||||
python scripts/check_designbook_staleness.py --fail-if-stale # exit 3 when stale
|
||||
|
||||
The marker write + RecentChanges.md regeneration are delegated to
|
||||
scripts/designbook-sync.mjs --remote-updated, so the marker format lives in one place.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
MARKER = REPO / "designbook" / ".design-sync.json"
|
||||
PIN = REPO / ".design-sync" / "config.json" # the /design-sync skill's recorded target
|
||||
|
||||
# Strict output contract for the headless claude call.
|
||||
PROMPT = """\
|
||||
Use the DesignSync tool (read-only) to find this user's writable design-system project
|
||||
and report when it last changed. Steps:
|
||||
1. Call DesignSync method "list_projects".
|
||||
2. Pick the project whose projectId is {project_id!r} if that is non-null, otherwise the
|
||||
one whose name best matches {project_name!r}.
|
||||
3. Output ONLY a single JSON object, no prose, no code fence:
|
||||
{{"projectId": "<id>", "name": "<name>", "updatedAt": "<ISO-8601 timestamp>"}}
|
||||
If no matching project is found, output {{"error": "<short reason>"}}.
|
||||
Do not write, create, or modify anything. Do not request any secret or API key.
|
||||
"""
|
||||
|
||||
|
||||
def load_marker() -> dict:
|
||||
if not MARKER.exists():
|
||||
return {}
|
||||
return json.loads(MARKER.read_text())
|
||||
|
||||
|
||||
def pinned_target() -> tuple[str | None, str | None]:
|
||||
"""projectId/projectName recorded by /design-sync in .design-sync/config.json."""
|
||||
if not PIN.exists():
|
||||
return None, None
|
||||
pin = json.loads(PIN.read_text())
|
||||
return pin.get("projectId"), pin.get("projectName")
|
||||
|
||||
|
||||
def parse_iso(value: str) -> datetime:
|
||||
# Tolerate a trailing Z.
|
||||
return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
|
||||
|
||||
|
||||
def fetch_remote_updated_at(project_id: str | None, project_name: str) -> dict:
|
||||
"""Ask the claude-code adapter for the project's updatedAt. Returns parsed JSON."""
|
||||
try:
|
||||
from llm_connect import create_adapter, RunConfig
|
||||
except ImportError as exc: # pragma: no cover - environment guidance
|
||||
sys.exit(
|
||||
f"llm-connect not importable ({exc}). Install it where this runs, e.g.\n"
|
||||
f" pip install -e ~/llm-connect\n"
|
||||
f"or pass --remote-updated <iso> to skip the LLM call."
|
||||
)
|
||||
|
||||
adapter = create_adapter("claude-code")
|
||||
config = RunConfig(temperature=0, max_tokens=400, timeout_seconds=180)
|
||||
prompt = PROMPT.format(project_id=project_id, project_name=project_name)
|
||||
response = adapter.execute_prompt(prompt, config)
|
||||
return extract_json(response.content)
|
||||
|
||||
|
||||
def extract_json(text: str) -> dict:
|
||||
"""Pull the JSON object out of the model's reply (tolerant of stray prose)."""
|
||||
match = re.search(r"\{.*\}", text, re.DOTALL)
|
||||
if not match:
|
||||
sys.exit(f"Could not parse a JSON object from the model reply:\n{text[:500]}")
|
||||
return json.loads(match.group(0))
|
||||
|
||||
|
||||
def record_remote_updated(iso: str) -> None:
|
||||
subprocess.run(
|
||||
["node", "scripts/designbook-sync.mjs", "--remote-updated", iso],
|
||||
cwd=REPO,
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("--remote-updated", metavar="ISO",
|
||||
help="Use this timestamp instead of calling the LLM (test/manual).")
|
||||
ap.add_argument("--fail-if-stale", action="store_true",
|
||||
help="Exit 3 when the mirror is outdated (for automation).")
|
||||
ap.add_argument("--dry-run", action="store_true",
|
||||
help="Report only; do not update the marker.")
|
||||
args = ap.parse_args()
|
||||
|
||||
marker = load_marker()
|
||||
last_sync = marker.get("lastSyncAt")
|
||||
if not last_sync:
|
||||
print("No /design-sync recorded yet — run /design-sync, then "
|
||||
"`node scripts/designbook-sync.mjs --mark-synced`. Nothing to compare against.")
|
||||
return 0
|
||||
|
||||
if args.remote_updated:
|
||||
remote = args.remote_updated
|
||||
else:
|
||||
pin_id, pin_name = pinned_target()
|
||||
project_id = marker.get("projectId") or pin_id
|
||||
project_name = marker.get("projectName") or pin_name or "whynot"
|
||||
result = fetch_remote_updated_at(project_id, project_name)
|
||||
if "error" in result:
|
||||
print(f"Could not determine remote state: {result['error']}")
|
||||
return 1
|
||||
remote = result["updatedAt"]
|
||||
print(f"Claude Design project '{result.get('name', '?')}' last updated: {remote}")
|
||||
|
||||
stale = parse_iso(remote) > parse_iso(last_sync)
|
||||
if not stale:
|
||||
print(f"Up to date — local designbook matches the project as of {last_sync}.")
|
||||
return 0
|
||||
|
||||
print(f"OUTDATED — project changed at {remote}, after the last /design-sync ({last_sync}).")
|
||||
if args.dry_run:
|
||||
print("(--dry-run: marker not updated)")
|
||||
else:
|
||||
record_remote_updated(remote)
|
||||
print("Recorded. `make designbook-sync` will now warn until the next /design-sync.")
|
||||
return 3 if args.fail_if_stale else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
195
scripts/designbook-sync.mjs
Normal file
195
scripts/designbook-sync.mjs
Normal file
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env node
|
||||
// Report what the latest designbook integration changed, into RecentChanges.md.
|
||||
//
|
||||
// node scripts/designbook-sync.mjs # working tree vs HEAD
|
||||
// node scripts/designbook-sync.mjs --range main..HEAD # a committed range
|
||||
//
|
||||
// Driven by `make designbook-sync`. The designbook is the Claude Design project —
|
||||
// the upstream source of truth for the *language*. Its local mirror lives IN this
|
||||
// repo at designbook/ and is pulled via the `/design-sync` skill (the DesignSync
|
||||
// tool), component by component — NOT by this script. This script only inspects
|
||||
// what that sync changed and writes a deterministic RecentChanges.md snapshot.
|
||||
// See designbook/README.md and DesignSystemIntroduction.md §1/§5.
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
// Pathspecs the report covers: the designbook mirror plus the surfaces derived
|
||||
// from it (tokens, CSS, the CSS-embedded _styles.js, and the example pages).
|
||||
const DESIGN_PATHSPECS = ["designbook", "tokens", "src/styles", "src/elements", "examples"];
|
||||
|
||||
const LAYER_ORDER = ["Designbook", "Tokens", "Styles", "Components", "Examples", "Other"];
|
||||
const layerOf = (p) =>
|
||||
p.startsWith("designbook/") ? "Designbook"
|
||||
: p.startsWith("tokens/") ? "Tokens"
|
||||
: p.startsWith("src/styles/") ? "Styles"
|
||||
: p.startsWith("src/elements/") ? "Components"
|
||||
: p.startsWith("examples/") ? "Examples"
|
||||
: "Other";
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const argVal = (name) => { const i = args.indexOf(name); return i !== -1 ? args[i + 1] : null; };
|
||||
const range = argVal("--range");
|
||||
const nowIso = () => new Date().toISOString().replace(/\.\d+Z$/, "Z");
|
||||
|
||||
// Trailing-newline trim only — never .trim(), which would eat the leading status
|
||||
// column of the first `git status --porcelain` line.
|
||||
const git = (gitArgs) =>
|
||||
execFileSync("git", gitArgs, { cwd: repoRoot, encoding: "utf8" }).replace(/\n+$/, "");
|
||||
|
||||
// ---- Sync marker: designbook/.design-sync.json ----
|
||||
// Records when /design-sync last pulled (lastSyncAt) and the latest known cloud
|
||||
// project timestamp (remoteUpdatedAt). `make designbook-sync` reports lastSyncAt;
|
||||
// when remoteUpdatedAt is newer, the local mirror is OUTDATED and we warn.
|
||||
// --mark-synced [--remote-updated <iso>] [--project <id>] [--project-name <s>]
|
||||
// run this right after /design-sync (sets lastSyncAt = now)
|
||||
// --remote-updated <iso>
|
||||
// record that the cloud project changed (e.g. from DesignSync.list_projects)
|
||||
const markerPath = resolve(repoRoot, "designbook/.design-sync.json");
|
||||
const readMarker = () => existsSync(markerPath) ? JSON.parse(readFileSync(markerPath, "utf8")) : null;
|
||||
const writeMarker = (m) => writeFileSync(markerPath, JSON.stringify(m, null, 2) + "\n");
|
||||
|
||||
if (args.includes("--mark-synced")) {
|
||||
const now = nowIso();
|
||||
const m = readMarker() || {};
|
||||
m.lastSyncAt = now;
|
||||
m.remoteUpdatedAt = argVal("--remote-updated") || now;
|
||||
if (argVal("--project")) m.projectId = argVal("--project");
|
||||
if (argVal("--project-name")) m.projectName = argVal("--project-name");
|
||||
writeMarker(m);
|
||||
console.log(`Recorded /design-sync at ${now}.`);
|
||||
} else if (argVal("--remote-updated")) {
|
||||
const m = readMarker() || {};
|
||||
m.remoteUpdatedAt = argVal("--remote-updated");
|
||||
writeMarker(m);
|
||||
console.log(`Recorded remote designbook update at ${m.remoteUpdatedAt}.`);
|
||||
}
|
||||
|
||||
const marker = readMarker();
|
||||
const stale = marker?.lastSyncAt && marker?.remoteUpdatedAt
|
||||
&& new Date(marker.remoteUpdatedAt) > new Date(marker.lastSyncAt);
|
||||
|
||||
function syncStatusLines() {
|
||||
if (!marker?.lastSyncAt) {
|
||||
return [
|
||||
"- Last /design-sync: never recorded",
|
||||
"",
|
||||
"> WARNING — no /design-sync has been recorded, so the local designbook/ may not",
|
||||
"> reflect the Claude Design project. Run `/design-sync` in Claude Code, then",
|
||||
"> `node scripts/designbook-sync.mjs --mark-synced`.",
|
||||
];
|
||||
}
|
||||
const out = [`- Last /design-sync: ${marker.lastSyncAt}`];
|
||||
if (stale) {
|
||||
out.push(
|
||||
"",
|
||||
`> WARNING — the Claude Design project changed at ${marker.remoteUpdatedAt}, after the`,
|
||||
"> last /design-sync. The local designbook/ is OUTDATED — run `/design-sync` to refresh it.",
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Collect changes ----
|
||||
let changes;
|
||||
let source;
|
||||
|
||||
if (range) {
|
||||
source = `range ${range}`;
|
||||
const numstat = git(["diff", "--numstat", range, "--", ...DESIGN_PATHSPECS]);
|
||||
const status = git(["diff", "--name-status", range, "--", ...DESIGN_PATHSPECS]);
|
||||
const counts = numstatMap(numstat);
|
||||
changes = (status ? status.split("\n") : []).map((line) => {
|
||||
const [code, ...rest] = line.split("\t");
|
||||
const path = rest[rest.length - 1]; // rename → new path
|
||||
return { path, status: statusWord(code), ...(counts.get(path) || {}) };
|
||||
});
|
||||
} else {
|
||||
source = "working tree (uncommitted)";
|
||||
// Intent-to-add so freshly-synced (untracked) files show up in the numstat diff.
|
||||
try { git(["add", "-N", "--", ...DESIGN_PATHSPECS]); } catch { /* nothing to add */ }
|
||||
const counts = numstatMap(git(["diff", "--numstat", "HEAD", "--", ...DESIGN_PATHSPECS]));
|
||||
const porcelain = git(["status", "--porcelain", "--", ...DESIGN_PATHSPECS]);
|
||||
changes = (porcelain ? porcelain.split("\n") : []).map((line) => {
|
||||
let path = line.slice(3);
|
||||
if (path.includes(" -> ")) path = path.split(" -> ")[1];
|
||||
return { path, status: statusWord(line.slice(0, 2)), ...(counts.get(path) || {}) };
|
||||
});
|
||||
}
|
||||
|
||||
// The sync marker is bookkeeping, not design content — keep it out of the report.
|
||||
changes = changes.filter((c) => c.path !== "designbook/.design-sync.json");
|
||||
|
||||
function numstatMap(out) {
|
||||
const m = new Map();
|
||||
for (const line of out ? out.split("\n") : []) {
|
||||
const [added, removed, ...rest] = line.split("\t");
|
||||
m.set(rest.join("\t"), { added, removed });
|
||||
}
|
||||
return m;
|
||||
}
|
||||
function statusWord(code) {
|
||||
const c = code.replace(/\s/g, "");
|
||||
return c.includes("D") ? "deleted"
|
||||
: c.includes("R") ? "renamed"
|
||||
: c.includes("A") || c.includes("?") ? "added"
|
||||
: "modified";
|
||||
}
|
||||
|
||||
// ---- Render RecentChanges.md ----
|
||||
const lines = [
|
||||
"# Recent Changes",
|
||||
"",
|
||||
"Snapshot of the last designbook integration. Regenerated by `make designbook-sync`.",
|
||||
"",
|
||||
`- Generated: ${nowIso()}`,
|
||||
`- Compared: ${source}`,
|
||||
...syncStatusLines(),
|
||||
"",
|
||||
"> This file is overwritten on every run — a snapshot, not a log. Fold notable entries",
|
||||
"> into `CHANGELOG.md` under `## [Unreleased]` before releasing; that is the file CI",
|
||||
"> enforces (`pnpm check`). The designbook itself is synced via `/design-sync`, not this script.",
|
||||
"",
|
||||
];
|
||||
|
||||
if (changes.length === 0) {
|
||||
lines.push("## No changes", "", "The design surface is unchanged since the last sync.");
|
||||
} else {
|
||||
lines.push("## Changed files", "");
|
||||
for (const layer of LAYER_ORDER) {
|
||||
const group = changes.filter((c) => layerOf(c.path) === layer);
|
||||
if (!group.length) continue;
|
||||
lines.push(`### ${layer}`);
|
||||
for (const c of group.sort((a, b) => a.path.localeCompare(b.path))) {
|
||||
const tag = c.status.toUpperCase().padEnd(8);
|
||||
const delta =
|
||||
c.status === "deleted" ? ""
|
||||
: c.added != null && c.added !== "-" ? ` (+${c.added} / -${c.removed})`
|
||||
: c.added === "-" ? " (binary)"
|
||||
: "";
|
||||
lines.push(`- \`${tag}\` ${c.path}${delta}`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
if (changes.some((c) => c.path === "src/elements/_styles.js")) {
|
||||
lines.push("> `src/elements/_styles.js` was regenerated from `components.css` — do not edit it by hand.", "");
|
||||
}
|
||||
}
|
||||
|
||||
writeFileSync(resolve(repoRoot, "RecentChanges.md"), lines.join("\n").replace(/\n+$/, "\n"));
|
||||
console.log(`Wrote RecentChanges.md — ${changes.length} changed file(s).`);
|
||||
|
||||
// Surface sync freshness on stdout — this is what tells the user whether the
|
||||
// snapshot reflects the latest design.
|
||||
if (!marker?.lastSyncAt) {
|
||||
console.warn("WARNING: no /design-sync recorded — run /design-sync, then `node scripts/designbook-sync.mjs --mark-synced`.");
|
||||
} else {
|
||||
console.log(`Last /design-sync: ${marker.lastSyncAt}`);
|
||||
if (stale) {
|
||||
console.warn(`WARNING: Claude Design project changed at ${marker.remoteUpdatedAt} — local designbook/ is OUTDATED. Run /design-sync.`);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user