@mmerterden/multi-agent-pipeline 20.5.0 → 20.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +10 -0
  3. package/docs/facts.json +5 -4
  4. package/install/_dev-only-files.mjs +1 -0
  5. package/manifest.json +84 -82
  6. package/package.json +4 -3
  7. package/pipeline/lib/confusables.json +100 -0
  8. package/pipeline/lib/normalize-text.mjs +48 -0
  9. package/pipeline/lib/outbound-gate.mjs +10 -1
  10. package/pipeline/lib/redact.mjs +4 -1
  11. package/pipeline/lib/vercel-deploy.sh +5 -7
  12. package/pipeline/multi-agent-refs/features/design-conformance.md +62 -64
  13. package/pipeline/scripts/_notices.mjs +11 -0
  14. package/pipeline/scripts/agent-guard.py +30 -1
  15. package/pipeline/scripts/gen-skills-index.mjs +1 -1
  16. package/pipeline/scripts/pre-commit-check.sh +59 -16
  17. package/pipeline/scripts/pre-push-check.sh +3 -3
  18. package/pipeline/scripts/run-ui-tests.sh +5 -5
  19. package/pipeline/scripts/website-deploy-commit.sh +3 -2
  20. package/pipeline/skills/.skill-manifest.json +39 -39
  21. package/pipeline/skills/shared/README.md +1 -1
  22. package/pipeline/skills/shared/external/agent-introspection-debugging/SKILL.md +1 -0
  23. package/pipeline/skills/shared/external/android-architecture/SKILL.md +2 -0
  24. package/pipeline/skills/shared/external/android-performance/SKILL.md +2 -0
  25. package/pipeline/skills/shared/external/android-security/SKILL.md +2 -0
  26. package/pipeline/skills/shared/external/backlog/BACKLOG.md +1 -1
  27. package/pipeline/skills/shared/external/backlog/SKILL.md +56 -33
  28. package/pipeline/skills/shared/external/ci-cd-pipelines/SKILL.md +1 -0
  29. package/pipeline/skills/shared/external/compose-components/SKILL.md +2 -0
  30. package/pipeline/skills/shared/external/compose-navigation/SKILL.md +3 -2
  31. package/pipeline/skills/shared/external/compose-testing/SKILL.md +2 -0
  32. package/pipeline/skills/shared/external/council/SKILL.md +1 -0
  33. package/pipeline/skills/shared/external/css-modern/SKILL.md +1 -0
  34. package/pipeline/skills/shared/external/database-patterns/SKILL.md +1 -0
  35. package/pipeline/skills/shared/external/evidence-github/SKILL.md +2 -0
  36. package/pipeline/skills/shared/external/evidence-registry/SKILL.md +2 -0
  37. package/pipeline/skills/shared/external/gradle-kotlin-dsl/SKILL.md +2 -0
  38. package/pipeline/skills/shared/external/html-semantic/SKILL.md +1 -0
  39. package/pipeline/skills/shared/external/humanizer/SKILL.md +1 -0
  40. package/pipeline/skills/shared/external/ios-coding-standard/SKILL.md +1 -0
  41. package/pipeline/skills/shared/external/ios-module-structure/SKILL.md +1 -0
  42. package/pipeline/skills/shared/external/ios-security/SKILL.md +2 -0
  43. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +91 -283
  44. package/pipeline/skills/shared/external/localization-reuse-map/reference/format-and-output.md +119 -151
  45. package/pipeline/skills/shared/external/localization-reuse-map/reference/publish-and-snapshot.md +60 -90
  46. package/pipeline/skills/shared/external/localization-reuse-map/reference/sources-and-recipes.md +119 -156
  47. package/pipeline/skills/shared/external/localization-reuse-map/scripts/build-artifact.py +726 -787
  48. package/pipeline/skills/shared/external/localization-reuse-map/scripts/build-spreadsheet.py +253 -288
  49. package/pipeline/skills/shared/external/localization-reuse-map/scripts/fetch-annotations.py +243 -304
  50. package/pipeline/skills/shared/external/localization-reuse-map/scripts/fetch-legacy-labels.py +88 -104
  51. package/pipeline/skills/shared/external/localization-reuse-map/scripts/publish-confluence.py +181 -235
  52. package/pipeline/skills/shared/external/localization-reuse-map/scripts/render-key-shots.py +198 -263
  53. package/pipeline/skills/shared/external/localization-reuse-map/scripts/render-overlay.py +461 -466
  54. package/pipeline/skills/shared/external/localization-reuse-map/scripts/resolve-legacy-values.py +145 -151
  55. package/pipeline/skills/shared/external/localization-reuse-map/scripts/resolve-new-values.py +123 -141
  56. package/pipeline/skills/shared/external/localization-reuse-map/scripts/scan-screen-keys.py +146 -157
  57. package/pipeline/skills/shared/external/localization-reuse-map/scripts/snapshot-resources.sh +22 -19
  58. package/pipeline/skills/shared/external/localization-reuse-map/scripts/verify-map.py +156 -140
  59. package/pipeline/skills/shared/external/nextjs-app-router/SKILL.md +1 -0
  60. package/pipeline/skills/shared/external/play-store-review/SKILL.md +2 -0
  61. package/pipeline/skills/shared/external/python-patterns/SKILL.md +1 -0
  62. package/pipeline/skills/shared/external/react-best-practices/SKILL.md +1 -0
  63. package/pipeline/skills/shared/external/rest-api-design/SKILL.md +1 -0
  64. package/pipeline/skills/shared/external/retrofit-networking/SKILL.md +2 -0
  65. package/pipeline/skills/shared/external/room-database/SKILL.md +2 -0
  66. package/pipeline/skills/shared/external/search-first/SKILL.md +1 -0
  67. package/pipeline/skills/shared/external/signal-community/SKILL.md +2 -0
  68. package/pipeline/skills/shared/external/skill-creator/SKILL.md +80 -41
  69. package/pipeline/skills/shared/external/skill-creator/audit.md +63 -59
  70. package/pipeline/skills/shared/external/skill-creator/checklist.md +28 -20
  71. package/pipeline/skills/shared/external/skill-creator/examples.md +40 -40
  72. package/pipeline/skills/shared/external/skill-creator/label-check.md +48 -36
  73. package/pipeline/skills/shared/external/skill-creator/scripts/audit-panel.js +91 -100
  74. package/pipeline/skills/shared/external/skill-creator/template.md +51 -39
  75. package/pipeline/skills/shared/external/tailwind-css/SKILL.md +1 -0
  76. package/pipeline/skills/shared/external/testing-backend/SKILL.md +1 -0
  77. package/pipeline/skills/shared/external/typescript-patterns/SKILL.md +1 -0
  78. package/pipeline/skills/shared/external/vue-composition/SKILL.md +1 -0
  79. package/pipeline/skills/shared/external/web-accessibility/SKILL.md +1 -0
  80. package/pipeline/skills/shared/external/web-performance/SKILL.md +1 -0
  81. package/pipeline/skills/shared/external/web-testing/SKILL.md +1 -0
@@ -1,297 +1,232 @@
1
1
  #!/usr/bin/env python3
2
- """Render a PER-KEY "screenpiece" for every mapping row: a cropped band of the screen
3
- with a RED BOX around exactly that element, so the table's "Ekran Görüntüsü" cell shows
4
- the content team where each key lives on screen (ported from the web skill's
5
- render-key-shots.mjs). No AI image generation - pure geometry + HTML + headless Chrome.
6
-
7
- Input modes (same split as render-overlay.py):
8
- * REST (default) - Figma token (--token / env / keychain FIGMA_ACCESS_TOKEN):
9
- geometry GET /v1/files/<key>/nodes?ids=<frame> → per-text absoluteBoundingBox,
10
- with ANCESTOR VISIBILITY (`visible!=false`) + cumulative opacity tracked,
11
- so hidden component variants with stale bboxes are never boxed;
12
- image GET /v1/images/<key>?ids=<frame>&format=png&scale=<n> → one render,
13
- cropped per key.
14
- * --spec <file> (repeatable; MCP / offline) - the SAME spec shape render-overlay.py
15
- takes: { fileKey?, pages:[{nodeId, image, frame:{w,h}, nodes:[{id, characters,
16
- x,y,w,h}]}] }. `image` may be a data URL **or a file path** (resolved relative to
17
- the spec file) - a committed example spec can reference screenshot.png instead of
18
- inlining base64. Several --spec files = several screen states; each row is boxed
19
- on the FIRST spec/page where its node matches.
20
-
21
- Rows are matched to nodes exactly like the overlay: by `cmsNodeId` first, else by
22
- normalized value (new/cms/legacy tr+en, element label). Every matched row gets a shot;
23
- unmatched rows are listed in the manifest's `missing` (blank cell in the table - never
24
- a guessed crop).
25
-
26
- Output, into --out:
27
- keyshots/keyshot__<NN>__<key>.png one per matched row; NN = the row's 1-based
28
- position in mapping.rows - the SAME number the
29
- table and the overlay cards use.
30
- <slug>.keyshots.manifest.json {shots:[{row,key,element,file,...}], missing:[...]}
31
- build-artifact.py reads this (mapping top-level
32
- `keyshots`) to fill the table cells;
33
- publish-confluence.py --keyshots attaches the PNGs.
34
- No headless Chrome → per-shot `.html` files are written instead (open/print manually);
35
- the manifest marks them `"fallback": "html"`. Read-only against every source.
2
+ """Cut one crop per mapped row, with the element framed in red, for the Screenshot column.
3
+
4
+ A crop keeps the whole frame width and a strip of --pad pixels over and under
5
+ the element, which gets a red outline. Output lands in
6
+ keyshots/keyshot__NN__<key>.png, NN being the row's index in mapping.rows
7
+ counted from 1. A row whose element cannot be found on screen is reported as
8
+ missing and gets no picture; crops are never guessed. Node matching and the
9
+ Figma calls are shared with render-overlay.py, loaded from this folder.
36
10
  """
37
11
  import argparse
38
- import base64
39
12
  import importlib.util
40
13
  import json
41
14
  import os
42
15
  import re
16
+ import subprocess
43
17
  import sys
44
- import tempfile
45
-
46
- sys.dont_write_bytecode = True
47
- _HERE = os.path.dirname(os.path.abspath(__file__))
48
- sys.path.insert(0, _HERE)
49
18
 
50
- # Shared with the overlay renderer on purpose: SAME matching = the shot, the
51
- # overlay card and the table row can never disagree about which node a key is.
52
- # The filename is not a valid identifier, so it loads by path rather than by
53
- # `import`: spec_from_file_location yields a real module object, and no source
54
- # text is evaluated at runtime.
55
- _RO_PATH = os.path.join(_HERE, "render-overlay.py")
56
- _spec = importlib.util.spec_from_file_location("render_overlay", _RO_PATH)
57
- if _spec is None or _spec.loader is None:
58
- sys.exit(f"render-key-shots: cannot load {_RO_PATH}")
59
- _ro = importlib.util.module_from_spec(_spec)
60
- sys.modules["render_overlay"] = _ro
61
- _spec.loader.exec_module(_ro)
19
+ SCRIPT_DIR = os.path.split(os.path.abspath(__file__))[0]
20
+ BOX_COLOUR = "#E81932"
21
+ ID_FIELD = "cmsNodeId"
22
+ INSET = 6
23
+ UNSAFE = re.compile(r"[\\/:*?\"<>|\s]+")
24
+ TRAILING_MARKER = re.compile(r"\s*\([^()]*\)\s*$")
62
25
 
63
- canon_id = _ro.canon_id
64
- slug = _ro.slug
65
- build_index = _ro.build_index
66
- match_row = _ro.match_row
67
- figma_token = _ro.figma_token
68
- http_get_json = _ro.http_get_json
69
- http_get_bytes = _ro.http_get_bytes
70
- find_chrome = _ro.find_chrome
71
- FIGMA_API = _ro.FIGMA_API
72
26
 
73
- RED = "#E81932"
27
+ def load_overlay():
28
+ path = os.path.join(SCRIPT_DIR, "render-overlay.py")
29
+ try:
30
+ spec = importlib.util.spec_from_file_location("render_overlay", path)
31
+ module = importlib.util.module_from_spec(spec)
32
+ spec.loader.exec_module(module)
33
+ except Exception as exc:
34
+ sys.exit(f"cannot load {path}: {exc}")
35
+ return module
74
36
 
75
37
 
76
- def key_file(num, key):
77
- # Drop a trailing "(owned by ...)" marker first: it is provenance, not identity, so
78
- # letting it into the filename churns every PNG (and orphans the old ones) whenever
79
- # a component is renamed or the tag is added. Matches build-spreadsheet's clean_key.
80
- bare = re.sub(r"\s*\(.*\)\s*$", "", key or "").strip()
81
- safe = re.sub(r'[/\\:*?"<>|\s]+', "-", bare or "key").strip("-")
82
- return f"keyshot__{num:02d}__{safe}.png"
38
+ ov = load_overlay()
83
39
 
84
40
 
85
- def build_shot_html(img_src, fw, fh, box, pad):
86
- """Full-frame-width band: `pad` px of context above/below the element, red box on it."""
87
- cy0 = max(0, box["y"] - pad)
88
- cy1 = min(fh, box["y"] + box["h"] + pad)
89
- crop_w, crop_h = fw, cy1 - cy0
90
- bx = max(0, box["x"] - 6)
91
- by = box["y"] - cy0 - 6
92
- bw, bh = box["w"] + 12, box["h"] + 12
93
- html = f"""<!doctype html><html><head><meta charset="utf-8"><style>
94
- *{{margin:0;padding:0;box-sizing:border-box}}
95
- body{{width:{crop_w}px;height:{crop_h}px;overflow:hidden;position:relative;background:#fff}}
96
- img{{position:absolute;left:0;top:{-cy0}px;width:{fw}px;height:{fh}px}}
97
- .box{{position:absolute;left:{bx}px;top:{by}px;width:{bw}px;height:{bh}px;
98
- border:3px solid {RED};border-radius:6px;box-shadow:0 0 0 2px rgba(232,25,50,.15)}}
99
- </style></head><body><img src="{img_src.replace('"', '&quot;')}"/><div class="box"></div></body></html>"""
100
- return html, crop_w, crop_h
41
+ def shot_name(row_number, key):
42
+ clean = UNSAFE.sub("-", TRAILING_MARKER.sub("", key).strip()).strip("-")
43
+ return f"keyshot__{row_number:02d}__{clean}"
101
44
 
102
45
 
103
- def render_shot_png(chrome, html, w, h, out_path, scale):
104
- """One headless-Chrome screenshot. Returns None on success, else an error string."""
105
- import subprocess
106
- with tempfile.NamedTemporaryFile("w", suffix=".html", delete=False, encoding="utf-8") as tf:
107
- tf.write(html)
108
- tmp = tf.name
109
- try:
110
- r = subprocess.run(
111
- [chrome, "--headless", "--disable-gpu", "--hide-scrollbars",
112
- f"--force-device-scale-factor={scale}",
113
- f"--window-size={w},{int(h)}",
114
- f"--screenshot={out_path}", tmp],
115
- capture_output=True, text=True, timeout=120)
116
- if not os.path.isfile(out_path):
117
- return (r.stderr or "no output")[:200]
118
- return None
119
- except Exception as exc: # timeout / spawn failure - fall back per shot, not per run
120
- return str(exc)[:200]
121
- finally:
122
- try:
123
- os.unlink(tmp)
124
- except OSError:
125
- pass
126
-
127
-
128
- def spec_image_src(page, spec_path):
129
- """`image` as a browser src: pass a data URL through; inline a file path (relative
130
- to the spec file) as base64 so the crop HTML stays self-contained for Chrome."""
131
- img = page.get("image") or ""
132
- if img.startswith("data:"):
133
- return img
134
- cand = img if os.path.isabs(img) else os.path.join(os.path.dirname(os.path.abspath(spec_path)), img)
135
- if not os.path.isfile(cand):
136
- sys.exit(f"spec image not found: {cand}")
137
- with open(cand, "rb") as fh:
138
- return "data:image/png;base64," + base64.b64encode(fh.read()).decode("ascii")
46
+ def spec_pages(paths):
47
+ pages = []
48
+ for path in paths:
49
+ spec, loaded = ov.load_spec_pages(path)
50
+ if not loaded:
51
+ sys.exit(f"--spec lists no pages: {path}")
52
+ pages.extend(loaded)
53
+ return pages
139
54
 
140
55
 
141
- def collect_rest_pages(file_key, node_ids, token, ca_file, scale):
142
- """Fetch each frame's VISIBLE text nodes (+ image render) - visibility is ancestor
143
- `visible` AND cumulative opacity, exactly the web port's rule, because a node tree
144
- carries text that is not rendered in this state and its stale bbox would land the
145
- red box on the wrong content."""
146
- headers = {"X-Figma-Token": token}
147
- import urllib.parse
56
+ def visible_text_nodes(document):
57
+ frame = document.get("absoluteBoundingBox") or {}
58
+ fx, fy = frame.get("x", 0), frame.get("y", 0)
59
+ found = []
60
+ pending = [(document, True, 1.0)]
61
+ while pending:
62
+ node, shown, alpha = pending.pop()
63
+ shown = shown and node.get("visible", True) is not False
64
+ alpha = alpha * float(node.get("opacity", 1.0))
65
+ if not shown or alpha <= 0:
66
+ continue
67
+ box = node.get("absoluteBoundingBox")
68
+ text = node.get("characters")
69
+ is_text = node.get("type") == "TEXT"
70
+ if is_text and box and text and text.strip():
71
+ found.append({
72
+ "id": node.get("id"),
73
+ "characters": text,
74
+ "x": round(box["x"] - fx),
75
+ "y": round(box["y"] - fy),
76
+ "w": round(box["width"]),
77
+ "h": round(box["height"]),
78
+ })
79
+ pending.extend((child, shown, alpha) for child in reversed(node.get("children") or []))
80
+ return found
81
+
82
+
83
+ def rest_pages(file_key, node_ids, scale, token, ca_file):
148
84
  pages = []
149
- for nid in node_ids:
150
- data = http_get_json(f"{FIGMA_API}/files/{file_key}/nodes?ids={urllib.parse.quote(nid, safe='')}",
151
- headers, ca_file)
152
- doc = ((data.get("nodes") or {}).get(nid) or {}).get("document")
153
- if not doc:
154
- sys.stderr.write(f"# warning: node {nid} not found - skipped\n")
85
+ for raw in node_ids:
86
+ node_id = ov.canon_id(raw)
87
+ document = ov.fetch_node(file_key, node_id, token, ca_file)
88
+ if not document:
89
+ print(f"# warning: {file_key} has no frame {node_id}; skipping it", file=sys.stderr)
155
90
  continue
156
- fb = doc.get("absoluteBoundingBox") or {"x": 0, "y": 0, "width": 0, "height": 0}
157
- nodes = []
158
-
159
- def walk(n, anc_visible, opacity):
160
- vis = anc_visible and n.get("visible") is not False
161
- op = opacity * (n.get("opacity") if isinstance(n.get("opacity"), (int, float)) else 1)
162
- b = n.get("absoluteBoundingBox")
163
- is_text = n.get("type") == "TEXT" and isinstance(n.get("characters"), str) and n["characters"].strip()
164
- if is_text and b and vis and op > 0:
165
- nodes.append({"id": n.get("id"), "characters": n["characters"],
166
- "x": round(b["x"] - fb["x"]), "y": round(b["y"] - fb["y"]),
167
- "w": round(b["width"]), "h": round(b["height"])})
168
- for c in n.get("children") or []:
169
- walk(c, vis, op)
170
-
171
- walk(doc, True, 1)
172
- img = http_get_json(
173
- f"{FIGMA_API}/images/{file_key}?ids={urllib.parse.quote(nid, safe='')}&format=png&scale={scale}",
174
- headers, ca_file)
175
- url = (img.get("images") or {}).get(nid)
176
- if not url:
177
- sys.stderr.write(f"# warning: no image render for {nid} - skipped\n")
91
+ image = ov.render_image(file_key, node_id, scale, token, ca_file)
92
+ if not image:
93
+ print(f"# warning: Figma returned no render of {node_id}; skipping it", file=sys.stderr)
178
94
  continue
179
- raw = http_get_bytes(url, ca_file)
180
- pages.append({"nodeId": nid,
181
- "image": "data:image/png;base64," + base64.b64encode(raw).decode("ascii"),
182
- "frame": {"w": round(fb.get("width", 0)), "h": round(fb.get("height", 0))},
183
- "nodes": nodes, "_src": "rest"})
95
+ box = document.get("absoluteBoundingBox") or {}
96
+ pages.append({
97
+ "nodeId": node_id,
98
+ "name": document.get("name"),
99
+ "image": image,
100
+ "frame": {"w": round(box.get("width", 0)), "h": round(box.get("height", 0))},
101
+ "nodes": visible_text_nodes(document),
102
+ })
103
+ if not pages:
104
+ sys.exit("none of the frames could be rendered")
184
105
  return pages
185
106
 
186
107
 
187
- def main():
188
- ap = argparse.ArgumentParser(description=__doc__,
189
- formatter_class=argparse.RawDescriptionHelpFormatter)
190
- ap.add_argument("--mapping", required=True, help="mapping JSON (rows + figmaFileKey/figmaNodes + screen)")
191
- ap.add_argument("--spec", action="append", default=[],
192
- help="spec JSON (repeatable - one per screen state; overlay-compatible shape; "
193
- "image may be a data URL or a file path relative to the spec)")
194
- ap.add_argument("--file", help="Figma fileKey (REST; else mapping figmaFileKey)")
195
- ap.add_argument("--nodes", help="comma-separated frame node-ids (REST; else mapping figmaNodes)")
196
- ap.add_argument("--pad", type=int, default=150, help="context band above/below the element (px)")
197
- ap.add_argument("--scale", type=int, default=2)
198
- ap.add_argument("--token")
199
- ap.add_argument("--ca-file")
200
- ap.add_argument("--out", default=".", help="output dir (shots go under <out>/keyshots/)")
201
- ap.add_argument("--slug", help="override slug (default from screen name)")
202
- args = ap.parse_args()
108
+ def assign(rows, pages):
109
+ index = ov.build_index(rows)
110
+ hits = {}
111
+ for page in pages:
112
+ ordered = sorted(page.get("nodes") or [], key=lambda item: float(item.get("y", 0)))
113
+ for node in ordered:
114
+ position = ov.match_row(node, index)
115
+ if position is not None:
116
+ hits.setdefault(position, (page, node))
117
+ return hits
118
+
119
+
120
+ def crop_html(page, node, pad):
121
+ fw, fh = (float(page["frame"][side]) for side in ("w", "h"))
122
+ x, y, w, h = (float(node.get(axis, 0)) for axis in ("x", "y", "w", "h"))
123
+ top = max(0.0, y - pad)
124
+ height = max(1.0, min(fh, y + h + pad) - top)
125
+ pin_left = "left:0;"
126
+ box_class = "box"
127
+ style = (
128
+ f"html,body{{margin:0;padding:0;}}body{{width:{fw:.0f}px;height:{height:.0f}px;position:relative;overflow:hidden;}}"
129
+ f"img{{position:absolute;{pin_left}top:{-top:.0f}px;width:{fw:.0f}px;height:{fh:.0f}px;}}"
130
+ f".{box_class}{{position:absolute;left:{x - INSET:.0f}px;top:{y - top - INSET:.0f}px;width:{w + 2 * INSET:.0f}px;"
131
+ f"height:{h + 2 * INSET:.0f}px;border:3px solid {BOX_COLOUR};border-radius:6px;box-sizing:border-box;}}"
132
+ )
133
+ document = (
134
+ f"{ov.PAGE_OPEN}{ov.META_UTF8}<style>{style}</style></head>"
135
+ f'<body><img src="{page["image"]}"><div class="{box_class}"></div></body></html>'
136
+ )
137
+ return document, fw, height
203
138
 
204
- with open(args.mapping, encoding="utf-8") as fh:
205
- m = json.load(fh)
206
- rows = m.get("rows") or []
207
- screen = m.get("screen") or "screen"
208
- sl = args.slug or slug(screen)
209
- shots_dir = os.path.join(args.out, "keyshots")
210
- os.makedirs(shots_dir, exist_ok=True)
211
139
 
212
- # ---- geometry pages, in precedence order (first match wins per row) ----
213
- if args.spec:
214
- pages = []
215
- for sp in args.spec:
216
- with open(sp, encoding="utf-8") as fh:
217
- spec = json.load(fh)
218
- for page in spec.get("pages") or []:
219
- page["_img_src"] = spec_image_src(page, sp)
220
- pages.append(page)
221
- if not pages:
222
- sys.exit("--spec files carry no pages")
140
+ def main():
141
+ cli = argparse.ArgumentParser(description=__doc__.splitlines()[0])
142
+ cli.add_argument("--mapping", required=True, help="the reuse-map JSON")
143
+ cli.add_argument("--spec", action="append", help="geometry spec for one screen state; may be repeated")
144
+ cli.add_argument("--file", help="Figma file key; falls back to figmaFileKey in the mapping")
145
+ cli.add_argument("--nodes", help="frame node-ids separated by commas; falls back to figmaNodes")
146
+ cli.add_argument("--pad", default=150, type=int, help="pixels of surrounding context kept over and under the element")
147
+ cli.add_argument("--scale", default=2, type=int)
148
+ cli.add_argument("--token", help="Figma token; FIGMA_ACCESS_TOKEN or the keychain is safer since other processes can read argv")
149
+ cli.add_argument("--ca-file", help="PEM roots to trust when a proxy intercepts TLS")
150
+ cli.add_argument("--out", dest="target_dir", default=".", help="folder for the manifest; the crops go into <out>/keyshots/")
151
+ cli.add_argument("--slug", help="stem of the manifest name; derived from the screen name when omitted")
152
+ opts = cli.parse_args()
153
+
154
+ with open(opts.mapping, encoding="utf-8") as stream:
155
+ mapping = json.load(stream)
156
+ rows = mapping.get("rows") or []
157
+ stem = opts.slug or ov.slug(mapping.get("screen"))
158
+
159
+ if opts.spec:
160
+ pages = spec_pages(opts.spec)
223
161
  else:
224
- file_key = args.file or m.get("figmaFileKey")
225
- node_ids = [canon_id(n) for n in (args.nodes or "").split(",") if n.strip()] or \
226
- [canon_id(str(n)) for n in (m.get("figmaNodes") or [])]
227
- if not (file_key and node_ids):
228
- ap.error("REST needs a fileKey + node-ids (via --file/--nodes or the mapping). "
229
- "Or pass --spec for the offline path.")
230
- token = figma_token(args)
162
+ file_key = opts.file or mapping.get("figmaFileKey")
163
+ nodes = ov.split_nodes(opts.nodes, mapping)
164
+ if not (file_key and nodes):
165
+ cli.error("need a Figma file key and frame node-ids (flags or mapping), or --spec")
166
+ token = ov.figma_token(opts.token)
231
167
  if not token:
232
- sys.exit("No Figma token - pass --token, set FIGMA_ACCESS_TOKEN, or add the "
233
- "keychain item FIGMA_ACCESS_TOKEN (or use --spec).")
234
- pages = collect_rest_pages(file_key, node_ids, token, args.ca_file, args.scale)
235
- for page in pages:
236
- page["_img_src"] = page["image"]
237
- if not pages:
238
- sys.exit("no renderable frames")
239
-
240
- # ---- choose one node per row: first page (in order) whose nodes match it ----
241
- by = [build_index([r]) for r in rows] # per-row index → exact same matcher as overlay
242
- chosen = {} # row idx (0-based) → {page, node}
243
- for page in pages:
244
- for n in sorted(page["nodes"], key=lambda x: x.get("y", 0)):
245
- for i, r in enumerate(rows):
246
- if i in chosen or not r.get("newKey"):
247
- continue
248
- if match_row(n, *by[i]) is r:
249
- chosen[i] = {"page": page, "node": n}
250
- missing = [{"row": i + 1, "key": r.get("newKey"),
251
- "reason": "no visible node matched (cmsNodeId/value)"}
252
- for i, r in enumerate(rows) if r.get("newKey") and i not in chosen]
168
+ sys.exit("No Figma token found (FIGMA_ACCESS_TOKEN, FIGMA_TOKEN, keychain FIGMA_ACCESS_TOKEN or --token). "
169
+ "Without one, build --spec files from the screenshots instead.")
170
+ pages = rest_pages(file_key, nodes, opts.scale, token, opts.ca_file)
171
+
172
+ crops_dir = os.path.join(opts.target_dir, "keyshots")
173
+ os.makedirs(crops_dir, exist_ok=True)
174
+ chrome = ov.find_chrome()
175
+ hits = assign(rows, pages)
176
+ shots, missing = [], []
177
+ failed = 0
178
+
179
+ for number, row in enumerate(rows, 1):
180
+ key = str(row.get("newKey") or "").strip()
181
+ if not key:
182
+ continue
183
+ if number - 1 not in hits:
184
+ missing.append({"row": number, "key": key, "reason": f"no visible node matched ({ID_FIELD}/value)"})
185
+ continue
186
+ page, node = hits[number - 1]
187
+ document, width, height = crop_html(page, node, opts.pad)
188
+ base = shot_name(number, key)
189
+ entry = {
190
+ "row": number,
191
+ "key": TRAILING_MARKER.sub("", key),
192
+ "element": row.get("element"),
193
+ "pageNode": page.get("nodeId"),
194
+ "cropW": int(round(width)),
195
+ "cropH": int(round(height)),
196
+ }
197
+ if not chrome:
198
+ with open(os.path.join(crops_dir, base + ".html"), "w", encoding="utf-8") as sink:
199
+ sink.write(document)
200
+ entry.update(file=f"keyshots/{base}.html", fallback="html")
201
+ shots.append(entry)
202
+ continue
203
+ try:
204
+ ov.chrome_screenshot(chrome, document, os.path.join(crops_dir, base + ".png"), width, height, opts.scale)
205
+ except (RuntimeError, subprocess.SubprocessError) as exc:
206
+ failed += 1
207
+ print(f"# row {number} {key}: {exc}", file=sys.stderr)
208
+ continue
209
+ entry["file"] = f"keyshots/{base}.png"
210
+ shots.append(entry)
211
+
212
+ manifest_name = f"{stem}.keyshots.manifest.json"
213
+ manifest = {
214
+ "screen": mapping.get("screen"),
215
+ "slug": stem,
216
+ "pad": opts.pad,
217
+ "scale": opts.scale,
218
+ "dir": "keyshots",
219
+ "shots": shots,
220
+ "missing": missing,
221
+ }
222
+ with open(os.path.join(opts.target_dir, manifest_name), "w", encoding="utf-8") as sink:
223
+ json.dump(manifest, sink, indent=2, ensure_ascii=False)
224
+ sink.write("\n")
253
225
 
254
- chrome = find_chrome()
255
226
  if not chrome:
256
- sys.stderr.write("# no headless Chrome - writing per-shot .html fallbacks\n")
257
-
258
- manifest = {"screen": screen, "slug": sl, "pad": args.pad, "scale": args.scale,
259
- "dir": "keyshots", "shots": [], "missing": missing}
260
- ok = fail = 0
261
- for i in sorted(chosen):
262
- r, c = rows[i], chosen[i]
263
- page, n = c["page"], c["node"]
264
- num = i + 1
265
- html, w, h = build_shot_html(page["_img_src"], page["frame"]["w"], page["frame"]["h"],
266
- {"x": n["x"], "y": n["y"], "w": n["w"], "h": n["h"]}, args.pad)
267
- fname = key_file(num, r["newKey"])
268
- out_png = os.path.join(shots_dir, fname)
269
- entry = {"row": num, "key": r["newKey"], "element": r.get("element"),
270
- "file": f"keyshots/{fname}", "pageNode": page.get("nodeId"),
271
- "cropW": w, "cropH": h}
272
- if chrome:
273
- err = render_shot_png(chrome, html, w, h, out_png, args.scale)
274
- if err:
275
- fail += 1
276
- sys.stderr.write(f"# ✗ row {num} {r['newKey']}: {err}\n")
277
- continue
278
- else:
279
- alt = out_png[:-4] + ".html"
280
- with open(alt, "w", encoding="utf-8") as fh:
281
- fh.write(html)
282
- entry["file"] = f"keyshots/{os.path.basename(alt)}"
283
- entry["fallback"] = "html"
284
- ok += 1
285
- manifest["shots"].append(entry)
286
-
287
- mpath = os.path.join(args.out, sl + ".keyshots.manifest.json")
288
- with open(mpath, "w", encoding="utf-8") as fh:
289
- json.dump(manifest, fh, ensure_ascii=False, indent=2)
290
- fh.write("\n")
291
- sys.stderr.write(f"# keyshots: {ok} written, {len(missing)} unmatched, {fail} failed → "
292
- f"{shots_dir}/ · manifest: {mpath}\n")
293
- sys.stderr.write(f'# set the mapping\'s top-level "keyshots": "{os.path.basename(mpath)}" '
294
- "so build-artifact.py fills the table cells\n")
227
+ print("# Chrome, Chromium and Edge are all missing; the crops were saved as .html", file=sys.stderr)
228
+ print(f"# keyshots: {len(shots)} written, {len(missing)} unmatched, {failed} failed", file=sys.stderr)
229
+ print(f'# point the mapping\'s top-level "keyshots" field at "{manifest_name}"', file=sys.stderr)
295
230
 
296
231
 
297
232
  if __name__ == "__main__":