@yasaswy.nagavolu/agents 0.32.0 → 0.32.1

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.
@@ -121,6 +121,9 @@ feedback stops being one-off fixes and becomes the harness. Nothing is live from
121
121
  near-duplicates another article's hook (token-Jaccard > 0.8); `build_share_caption`
122
122
  also varies the connective/CTA lines per-slug via a stable hash so captions stop
123
123
  reading like the same template. Already-live articles are grandfathered.
124
+ An article may instead carry a full authored `caption:` block (`caption: |`, with `{url}` and, for a
125
+ skill article, `{install}` placeholders); `build_share_caption` then uses it as written, and
126
+ `lint_article.py` checks the placeholders, 60-130 words, and no template claims like "plug-and-play".
124
127
  - **Thumbnails show the actual interactive visual, not just title text.** Fully
125
128
  mechanical, not a judgment call — `pipeline/capture_og_islands.py` runs automatically
126
129
  during every `stage`/`publish` (see `deploy.py`'s two-pass build): it screenshots each
@@ -0,0 +1,142 @@
1
+ """
2
+ arch_render_check.py - rendered-shape and text checks for ONE article's architecture diagram.
3
+
4
+ The council reads screenshots; these rules are numbers, so code checks them (ARCHITECTURE-DIAGRAMS.md, "Rendered shape" and
5
+ "Numeric text floor"). Scoped to the article being linted or mocked, so another live diagram can never block an unrelated article.
6
+
7
+ - wide layout (900 and 1200 px viewports): island height / width <= MAX_ASPECT
8
+ - wide layout: every quadrant of the canvas holds at least one card
9
+ - thumbnail: the island, fitted into the OG thumbnail box, leaves side bars of at most MAX_SIDE_BARS of its width
10
+ - text: every text renders at >= arch_text_floor.FLOOR_PX at 390, 760, 900 and 1200 px
11
+
12
+ problems_for_article() needs a FRESH local build (dist page newer than the article and its islands). With no build, a stale
13
+ build, or no Playwright it returns [] so lint stays usable; `mock` builds first, then runs it for real.
14
+ """
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ sys.path.insert(0, str(Path(__file__).parent))
19
+ import arch_text_floor # noqa: E402
20
+
21
+ MAX_ASPECT = 1.3
22
+ MAX_SIDE_BARS = 0.30
23
+ THUMB_SIZE = (460, 380) # OG_THUMB_SIZE in src/publish-article/pipeline/capture_og_islands.py
24
+ WIDE_VIEWPORTS = (900, 1200)
25
+
26
+ SHAPE_JS = """() => {
27
+ const isl = [...document.querySelectorAll('[data-island="arch-state-machine"]')].find(e => e.offsetParent !== null);
28
+ if (!isl) return null;
29
+ const canvas = [...isl.querySelectorAll('div')].find(d => d.style.transform && d.style.transform.includes('scale'));
30
+ const c = canvas.getBoundingClientRect(), r = isl.getBoundingClientRect();
31
+ const centers = [...isl.querySelectorAll('button[data-box-id]')].map(b => { const x = b.getBoundingClientRect(); return [x.left + x.width / 2, x.top + x.height / 2]; });
32
+ return { width: r.width, height: r.height, canvas: [c.left, c.top, c.width, c.height], centers };
33
+ }"""
34
+
35
+
36
+ def aspect_problem(width: float, height: float, max_aspect: float = MAX_ASPECT) -> str | None:
37
+ if width <= 0:
38
+ return "island has no width"
39
+ ratio = height / width
40
+ return None if ratio <= max_aspect else f"island is {ratio:.2f} tall per unit of width (limit {max_aspect})"
41
+
42
+
43
+ def side_bar_fraction(width: float, height: float, thumb: tuple[int, int] = THUMB_SIZE) -> float:
44
+ """Share of the thumbnail width left blank when the island is fitted entirely inside it (never cropped)."""
45
+ scale = min(thumb[0] / width, thumb[1] / height)
46
+ return max(0.0, 1.0 - (width * scale) / thumb[0])
47
+
48
+
49
+ def empty_quadrants(canvas: list[float], centers: list[list[float]]) -> list[str]:
50
+ left, top, w, h = canvas
51
+ mid_x, mid_y = left + w / 2, top + h / 2
52
+ names = {("top", "left"): "top-left", ("top", "right"): "top-right", ("bottom", "left"): "bottom-left", ("bottom", "right"): "bottom-right"}
53
+ filled = {(("top" if cy < mid_y else "bottom"), ("left" if cx < mid_x else "right")) for cx, cy in centers}
54
+ return [name for key, name in names.items() if key not in filled]
55
+
56
+
57
+ def shape_problems(measurements: dict[int, dict]) -> list[str]:
58
+ """measurements: viewport width -> SHAPE_JS result for the visible island."""
59
+ problems: list[str] = []
60
+ for vw, m in sorted(measurements.items()):
61
+ if m is None:
62
+ continue
63
+ bad = aspect_problem(m["width"], m["height"])
64
+ if bad:
65
+ problems.append(f"{vw}px: {bad}")
66
+ empty = empty_quadrants(m["canvas"], m["centers"])
67
+ if empty:
68
+ problems.append(f"{vw}px: empty canvas quadrant(s): {', '.join(empty)}")
69
+ thumb = measurements.get(1200)
70
+ if thumb:
71
+ bars = side_bar_fraction(thumb["width"], thumb["height"])
72
+ if bars > MAX_SIDE_BARS:
73
+ problems.append(f"thumbnail would have {bars:.0%} blank side bars (limit {MAX_SIDE_BARS:.0%})")
74
+ return problems
75
+
76
+
77
+ def _is_fresh(page: Path, sources: list[Path]) -> bool:
78
+ return page.is_file() and all(not s.exists() or s.stat().st_mtime <= page.stat().st_mtime for s in sources)
79
+
80
+
81
+ def _sources(mdx: Path) -> list[Path]:
82
+ site_src = next((p for p in mdx.parents if (p / "components" / "arch").is_dir()), None)
83
+ out = [mdx]
84
+ if site_src:
85
+ out += [p for p in (site_src / "components").rglob("*.ts*") if p.is_file()]
86
+ return out
87
+
88
+
89
+ def problems_for_article(mdx: Path, require_fresh: bool = True) -> list[str]:
90
+ site_src = next((p for p in mdx.parents if (p / "components" / "arch").is_dir()), None)
91
+ if site_src is None:
92
+ return []
93
+ dist = site_src.parent / "dist"
94
+ slug = mdx.stem
95
+ if not _is_fresh(dist / slug / "index.html", _sources(mdx)) and require_fresh:
96
+ return []
97
+ try:
98
+ from playwright.sync_api import sync_playwright
99
+ except ImportError:
100
+ return []
101
+ server, port = arch_text_floor._serve(dist)
102
+ problems: list[str] = []
103
+ try:
104
+ with sync_playwright() as p:
105
+ browser = p.chromium.launch(headless=True)
106
+ try:
107
+ shapes: dict[int, dict] = {}
108
+ for vw in WIDE_VIEWPORTS:
109
+ ctx = browser.new_context(viewport={"width": vw, "height": 900}, reduced_motion="reduce")
110
+ page = ctx.new_page()
111
+ page.goto(f"http://127.0.0.1:{port}/{slug}/", wait_until="networkidle")
112
+ if page.locator('[data-island="arch-state-machine"]').count() == 0:
113
+ ctx.close()
114
+ return []
115
+ page.wait_for_timeout(600)
116
+ shapes[vw] = page.evaluate(SHAPE_JS)
117
+ ctx.close()
118
+ problems += shape_problems(shapes)
119
+ for vw in arch_text_floor.VIEWPORTS:
120
+ bad = arch_text_floor.violations(arch_text_floor.measure_page(browser, port, slug, vw))
121
+ if bad:
122
+ problems.append(f"{vw}px: text under {arch_text_floor.FLOOR_PX:g}px: {bad[:3]}")
123
+ finally:
124
+ browser.close()
125
+ finally:
126
+ server.shutdown()
127
+ return [f"architecture diagram render check - {p}" for p in problems]
128
+
129
+
130
+ def main() -> int:
131
+ if len(sys.argv) != 2:
132
+ print("usage: arch_render_check.py <mdx-path> (needs a fresh local build)", file=sys.stderr)
133
+ return 2
134
+ problems = problems_for_article(Path(sys.argv[1]), require_fresh=False)
135
+ for p in problems:
136
+ print(p, file=sys.stderr)
137
+ print("PASS" if not problems else "FAIL")
138
+ return 1 if problems else 0
139
+
140
+
141
+ if __name__ == "__main__":
142
+ raise SystemExit(main())
@@ -0,0 +1,129 @@
1
+ """
2
+ arch_text_floor.py - the numeric text floor for architecture diagrams.
3
+
4
+ ARCHITECTURE-DIAGRAMS.md requires every piece of diagram text to RENDER at
5
+ FLOOR_PX or more at each of the VIEWPORTS widths. A diagram is a scaled canvas, so the rendered size is
6
+ computed font-size x canvas scale (text outside the canvas, like the top strip, is unscaled).
7
+ This script measures it in headless Chromium so nobody has to eyeball it.
8
+
9
+ Usage:
10
+ python arch_text_floor.py <dist-dir> [--slug S ...] [--floor 10] [--viewports 390,760,900,1200]
11
+ Exit 0 when every measured text is at or above the floor, 1 when any is below, 2 on a usage or setup error.
12
+ """
13
+ import argparse
14
+ import functools
15
+ import http.server
16
+ import socketserver
17
+ import sys
18
+ import threading
19
+ from pathlib import Path
20
+
21
+ FLOOR_PX = 10.0
22
+ VIEWPORTS = (390, 760, 900, 1200)
23
+
24
+ MEASURE_JS = """() => {
25
+ const isl = [...document.querySelectorAll('[data-island="arch-state-machine"]')].filter(e => e.offsetParent !== null);
26
+ return isl.map(el => {
27
+ const canvas = [...el.querySelectorAll('div')].find(d => d.style.transform && d.style.transform.includes('scale'));
28
+ const scale = canvas.getBoundingClientRect().width / canvas.offsetWidth;
29
+ const texts = [];
30
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
31
+ while (walker.nextNode()) {
32
+ const node = walker.currentNode;
33
+ const text = node.textContent.trim();
34
+ if (!text) continue;
35
+ const parent = node.parentElement;
36
+ texts.push({ text: text.slice(0, 32), fontSize: parseFloat(getComputedStyle(parent).fontSize), scaled: canvas.contains(parent) });
37
+ }
38
+ return { scale, steps: el.getAttribute('data-step-boxes'), texts };
39
+ });
40
+ }"""
41
+
42
+
43
+ def effective_px(font_size: float, scale: float, scaled: bool) -> float:
44
+ return font_size * (scale if scaled else 1.0)
45
+
46
+
47
+ def violations(measured: list[dict], floor: float = FLOOR_PX) -> list[tuple[str, float]]:
48
+ """(text, rendered px) for every text under the floor, smallest first, one row per distinct text."""
49
+ worst: dict[str, float] = {}
50
+ for island in measured:
51
+ for t in island["texts"]:
52
+ px = round(effective_px(t["fontSize"], island["scale"], t["scaled"]), 1)
53
+ if px < floor - 0.05:
54
+ worst[t["text"]] = min(px, worst.get(t["text"], px))
55
+ return sorted(worst.items(), key=lambda kv: kv[1])
56
+
57
+
58
+ def _serve(root: Path) -> tuple[socketserver.TCPServer, int]:
59
+ class Quiet(http.server.SimpleHTTPRequestHandler):
60
+ def log_message(self, *args):
61
+ pass
62
+
63
+ server = socketserver.TCPServer(("127.0.0.1", 0), functools.partial(Quiet, directory=str(root)))
64
+ threading.Thread(target=server.serve_forever, daemon=True).start()
65
+ return server, server.server_address[1]
66
+
67
+
68
+ def measure_page(browser, port: int, slug: str, width: int) -> list[dict]:
69
+ ctx = browser.new_context(viewport={"width": width, "height": 1400}, reduced_motion="reduce")
70
+ try:
71
+ page = ctx.new_page()
72
+ page.goto(f"http://127.0.0.1:{port}/{slug}/", wait_until="networkidle")
73
+ islands = page.locator('[data-island="arch-state-machine"]:visible')
74
+ # step to the end so text that only appears late (the reply, the browser comment) is in the DOM
75
+ for i in range(islands.count()):
76
+ isl = islands.nth(i)
77
+ isl.scroll_into_view_if_needed()
78
+ for box in (isl.get_attribute("data-step-boxes") or "").split(",")[1:]:
79
+ isl.locator(f'button[data-box-id="{box}"]').first.click(force=True)
80
+ page.wait_for_timeout(120)
81
+ page.wait_for_timeout(1500)
82
+ return page.evaluate(MEASURE_JS)
83
+ finally:
84
+ ctx.close()
85
+
86
+
87
+ def main() -> int:
88
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
89
+ ap.add_argument("dist", type=Path)
90
+ ap.add_argument("--slug", action="append", default=[])
91
+ ap.add_argument("--floor", type=float, default=FLOOR_PX)
92
+ ap.add_argument("--viewports", default=",".join(str(v) for v in VIEWPORTS))
93
+ args = ap.parse_args()
94
+ if not args.dist.is_dir():
95
+ print(f"dist not found: {args.dist}", file=sys.stderr)
96
+ return 2
97
+ try:
98
+ from playwright.sync_api import sync_playwright
99
+ except ImportError:
100
+ print("playwright is not installed", file=sys.stderr)
101
+ return 2
102
+ widths = [int(v) for v in args.viewports.split(",") if v]
103
+ slugs = args.slug or sorted(d.name for d in args.dist.iterdir() if (d / "index.html").is_file() and d.name != "how-i-write")
104
+ server, port = _serve(args.dist)
105
+ failed = False
106
+ with sync_playwright() as p:
107
+ browser = p.chromium.launch(headless=True)
108
+ for slug in slugs:
109
+ row = []
110
+ has_arch = False
111
+ for w in widths:
112
+ measured = measure_page(browser, port, slug, w)
113
+ if not measured:
114
+ break
115
+ has_arch = True
116
+ bad = violations(measured, args.floor)
117
+ low = min((effective_px(t["fontSize"], m["scale"], t["scaled"]) for m in measured for t in m["texts"]), default=0)
118
+ row.append(f"{w}px min {low:.1f}" + (f" FAIL {bad[:3]}" if bad else ""))
119
+ failed = failed or bool(bad)
120
+ if has_arch:
121
+ print(f"{slug}: " + " | ".join(row))
122
+ browser.close()
123
+ server.shutdown()
124
+ print("FLOOR", args.floor, "px:", "FAIL" if failed else "PASS")
125
+ return 1 if failed else 0
126
+
127
+
128
+ if __name__ == "__main__":
129
+ raise SystemExit(main())
@@ -27,7 +27,17 @@ import re
27
27
  import sys
28
28
  from pathlib import Path
29
29
 
30
- FEEDBACK_DIR = Path(__file__).parent.parent.parent / "src" / "publish-article" / "feedback"
30
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
31
+ import repo_locate # noqa: E402
32
+
33
+
34
+ def feedback_dir(repo_root: Path) -> Path:
35
+ return repo_root / "src" / "publish-article" / "feedback"
36
+
37
+
38
+ # Resolved through repo_locate (not __file__) so the deployed skill copy and a worktree
39
+ # copy read and write the same feedback store as publish_article.py.
40
+ FEEDBACK_DIR = feedback_dir(repo_locate.locate())
31
41
  COMMENTS_LOG = FEEDBACK_DIR / "review-comments.jsonl"
32
42
  CODIFIED_LOG = FEEDBACK_DIR / "codified.jsonl"
33
43
 
@@ -68,6 +68,7 @@ from pathlib import Path
68
68
  sys.path.insert(0, str(Path(__file__).parent))
69
69
  import architecture_review # noqa: E402
70
70
  import arch_component_lint # noqa: E402
71
+ import arch_render_check # noqa: E402
71
72
  import island_theme_lint # noqa: E402
72
73
 
73
74
  PROBLEM_SIGNAL_RE = re.compile(
@@ -602,6 +603,37 @@ def load_tool_keys(mdx_path: Path) -> list[str] | None:
602
603
  return load_tool_keys_from_site_src(_site_src_dir(mdx_path))
603
604
 
604
605
 
606
+ CAPTION_BLOCK_RE = re.compile(r"^caption:[ \t]*\|-?[ \t]*\n((?:[ \t]+.*\n|[ \t]*\n)+)", re.MULTILINE)
607
+ CAPTION_MIN_WORDS = 60
608
+ CAPTION_MAX_WORDS = 130
609
+ CAPTION_BANNED = ("plug-and-play", "point your ai at the repo")
610
+
611
+
612
+ def lint_caption_override(frontmatter: str) -> list[str]:
613
+ """An authored `caption:` block replaces the generated LinkedIn caption, so
614
+ it must carry the article link and (for a skill article) the install line
615
+ as placeholders, stay a short post, and not reuse the generated template's claims."""
616
+ m = CAPTION_BLOCK_RE.search(frontmatter + "\n")
617
+ if not m:
618
+ if re.search(r"^caption:", frontmatter, re.MULTILINE):
619
+ return ["`caption:` must be a block scalar (`caption: |` followed by indented lines)."]
620
+ return []
621
+ text = "\n".join(line.strip() for line in m.group(1).splitlines())
622
+ problems: list[str] = []
623
+ if "{url}" not in text:
624
+ problems.append("`caption:` must contain the {url} placeholder for the article link.")
625
+ if SKILL_FIELD_RE.search(frontmatter) and "{install}" not in text:
626
+ problems.append("`caption:` on a skill article must contain the {install} placeholder for the install line.")
627
+ words = len(text.replace("{url}", "URL").replace("{install}", "INSTALL").split())
628
+ if not CAPTION_MIN_WORDS <= words <= CAPTION_MAX_WORDS:
629
+ problems.append(f"`caption:` is {words} words; keep it between {CAPTION_MIN_WORDS} and {CAPTION_MAX_WORDS}.")
630
+ low = text.lower()
631
+ for phrase in CAPTION_BANNED:
632
+ if phrase in low:
633
+ problems.append(f'`caption:` uses the generated-template claim "{phrase}"; say what is actually true for this article.')
634
+ return problems
635
+
636
+
605
637
  def lint_skill_field(mdx_path: Path, frontmatter: str) -> list[str]:
606
638
  """Site-wide (not TOOL_TAGS-scoped): if `skill:` is present at all, its
607
639
  value must be a real tools.json key. Mirrors the failure `astro build`
@@ -686,6 +718,7 @@ def lint(mdx_path: Path) -> tuple[bool, list[str]]:
686
718
  # not — the TOOL_TAGS-scoped block below separately requires `skill:` to
687
719
  # exist (and match the title) for tagged articles specifically.
688
720
  problems += lint_skill_field(mdx_path, frontmatter)
721
+ problems += lint_caption_override(frontmatter)
689
722
  problems += lint_series_field(frontmatter)
690
723
 
691
724
  # Terminal-theme gate for EVERY article's islands (site-wide, not just
@@ -713,6 +746,7 @@ def lint(mdx_path: Path) -> tuple[bool, list[str]]:
713
746
  arch_ok, arch_problems = arch_component_lint.lint_arch(mdx_path, body)
714
747
  problems += arch_problems
715
748
  # judgement gate: the council must have cleared it against the current spec
749
+ problems += arch_render_check.problems_for_article(mdx_path)
716
750
  ok, msg = architecture_review.check(mdx_path.stem)
717
751
  if not ok:
718
752
  problems.append(
@@ -55,10 +55,11 @@ import html_mock_review # noqa: E402
55
55
  import review_store # noqa: E402
56
56
  import learn_feedback # noqa: E402
57
57
  import lint_article # noqa: E402
58
+ import arch_render_check # noqa: E402
58
59
  import repo_locate # noqa: E402
59
60
 
60
- DEFAULT_REPO = Path(r"C:\dev\my-agents")
61
- MARKER = Path("src") / "publish-article" / "site"
61
+ DEFAULT_REPO = repo_locate.DEFAULT_REPO
62
+ MARKER = repo_locate.MARKER
62
63
 
63
64
  # Windows consoles default to cp1252; emit UTF-8 so the LinkedIn draft + box chars
64
65
  # don't crash on print.
@@ -81,6 +82,16 @@ def find_repo() -> Path:
81
82
 
82
83
 
83
84
  # ------------------------------------------------------------------- paths/util
85
+ def ensure_node_deps(repo: "Repo", *pkg_dirs: Path) -> None:
86
+ """Install missing npm deps (a fresh worktree has no node_modules) via the repo's shared node_deps.py."""
87
+ import importlib.util
88
+ spec = importlib.util.spec_from_file_location("node_deps", repo.pipeline / "node_deps.py")
89
+ mod = importlib.util.module_from_spec(spec)
90
+ spec.loader.exec_module(mod)
91
+ for d in pkg_dirs:
92
+ mod.ensure_installed(d)
93
+
94
+
84
95
  class Repo:
85
96
  def __init__(self, root: Path):
86
97
  self.root = root
@@ -108,6 +119,10 @@ def check_slug(slug: str) -> str:
108
119
  return slug
109
120
 
110
121
 
122
+ NL = chr(10)
123
+ WS = (" ", chr(9))
124
+
125
+
111
126
  def read_frontmatter(path: Path) -> dict[str, str]:
112
127
  """Tiny YAML-frontmatter reader (flat scalars + inline [list])."""
113
128
  text = path.read_text(encoding="utf-8")
@@ -115,11 +130,24 @@ def read_frontmatter(path: Path) -> dict[str, str]:
115
130
  fm: dict[str, str] = {}
116
131
  if not m:
117
132
  return fm
118
- for line in m.group(1).splitlines():
133
+ lines = m.group(1).splitlines()
134
+ i = 0
135
+ while i < len(lines):
136
+ line = lines[i]
137
+ i += 1
119
138
  if ":" not in line or line.strip().startswith("#"):
120
139
  continue
121
140
  k, _, v = line.partition(":")
122
- fm[k.strip()] = v.strip().strip('"')
141
+ v = v.strip()
142
+ if v in ("|", "|-"):
143
+ block: list[str] = []
144
+ while i < len(lines) and (not lines[i].strip() or lines[i][:1] in WS):
145
+ block.append(lines[i])
146
+ i += 1
147
+ indent = min((len(b) - len(b.lstrip()) for b in block if b.strip()), default=0)
148
+ fm[k.strip()] = NL.join(b[indent:] for b in block).strip(NL)
149
+ continue
150
+ fm[k.strip()] = v.strip('"')
123
151
  return fm
124
152
 
125
153
 
@@ -416,6 +444,14 @@ def _pick_variant(templates: list[str], slug: str, salt: str) -> str:
416
444
  return templates[int(digest, 16) % len(templates)]
417
445
 
418
446
 
447
+ def render_authored_caption(repo: Repo, slug: str, caption: str, skill: str) -> str:
448
+ """An article's own `caption:` block, used as written. Only the {url} and
449
+ {install} placeholders are filled in; nothing is appended or reworded."""
450
+ text = caption.replace("{url}", share_url(repo, slug))
451
+ text = text.replace("{install}", skill_install_command(repo, skill))
452
+ return text.strip() + NL
453
+
454
+
419
455
  def build_share_caption(repo: Repo, slug: str) -> str:
420
456
  """Deterministic, review-ready LinkedIn caption. Video-first (the diagram is
421
457
  the uploaded media); the article link lives in the copy with UTM tags. An
@@ -426,6 +462,9 @@ def build_share_caption(repo: Repo, slug: str) -> str:
426
462
  fm = read_frontmatter(repo.mdx(slug))
427
463
  summary = fm.get("summary", "")
428
464
  skill = fm.get("skill", "")
465
+ authored = fm.get("caption", "")
466
+ if authored:
467
+ return render_authored_caption(repo, slug, authored, skill)
429
468
  hook = fm.get("hook", "")
430
469
  if not hook:
431
470
  hook = (
@@ -803,6 +842,10 @@ def cmd_publish(repo: Repo, slug: str, run_test: bool, dry_run: bool = False) ->
803
842
  # draft:false + publish goes straight to production. What still guards this
804
843
  # path: lint_article.py's editorial gates at stage time, and the prod-smoke
805
844
  # Playwright check (ADR 0015) run just below.
845
+ # A smoke that cannot start must fail before the deploy, not look like a site failure after it.
846
+ if run_test and not dry_run:
847
+ ensure_node_deps(repo, repo.pa / "tests")
848
+
806
849
  deploy_cmd = [sys.executable, str(repo.pipeline / "deploy.py"), "--env", "prod", "--slug", slug]
807
850
  if dry_run:
808
851
  deploy_cmd.append("--dry-run")
@@ -925,6 +968,7 @@ def cmd_mock(repo: Repo, slug: str) -> int:
925
968
  if not npm:
926
969
  sys.exit("`npm` not found on PATH — install Node/npm to build the site locally.")
927
970
 
971
+ ensure_node_deps(repo, repo.site)
928
972
  print(f"building site locally (plain pass, no PUBLISH_BASE) for '{slug}'…", flush=True)
929
973
  # PUBLISH_INCLUDE_DRAFTS lets a draft:true article render in this local review
930
974
  # build (no flip needed). deploy.py never sets it, so a draft can't ship.
@@ -935,6 +979,10 @@ def cmd_mock(repo: Repo, slug: str) -> int:
935
979
 
936
980
  dist = repo.site / "dist"
937
981
  page = dist / slug / "index.html"
982
+ if page.exists():
983
+ render_problems = arch_render_check.problems_for_article(mdx)
984
+ if render_problems:
985
+ sys.exit(NL.join(render_problems) + NL + "fix the diagram, then retry `mock`.")
938
986
  if not page.exists():
939
987
  sys.exit(
940
988
  f"build succeeded but expected page not found: {page}\n"
@@ -953,7 +1001,7 @@ def cmd_mock(repo: Repo, slug: str) -> int:
953
1001
  # bug signal, not a real one; confirmed 2026-07-08).
954
1002
  cmd = (
955
1003
  f'python "{mocker}" "{dist}" --url-path "/{slug}/" --annotate '
956
- f'--feedback-log "{learn_feedback.COMMENTS_LOG}" --out "{out_dir}"'
1004
+ f'--feedback-log "{learn_feedback.feedback_dir(repo.root) / "review-comments.jsonl"}" --out "{out_dir}"'
957
1005
  )
958
1006
  print("\nBuilt (a draft article is included in this review build, no flip needed).")
959
1007
  print("Review it with html-mocker's live --annotate panel. Run the command under the Monitor")
@@ -21,6 +21,10 @@ import os
21
21
  from pathlib import Path
22
22
 
23
23
 
24
+ DEFAULT_REPO = Path(r"C:\dev\my-agents")
25
+ MARKER = Path("src") / "publish-article" / "site"
26
+
27
+
24
28
  def env_candidate() -> Path | None:
25
29
  val = os.environ.get("PUBLISH_ARTICLE_REPO")
26
30
  return Path(val) if val else None
@@ -55,3 +59,9 @@ def find_repo(marker: Path, default: Path) -> Path | None:
55
59
  if cand and (Path(cand) / marker).exists():
56
60
  return Path(cand)
57
61
  return None
62
+
63
+
64
+ def locate() -> Path:
65
+ """The repo root every publish-article script agrees on: the 4-tier resolution
66
+ with the shared marker/default, falling back to the default when nothing matches."""
67
+ return find_repo(MARKER, DEFAULT_REPO) or DEFAULT_REPO
@@ -0,0 +1,47 @@
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ sys.path.insert(0, str(Path(__file__).parent.parent))
7
+ import arch_render_check as rc # noqa: E402
8
+
9
+
10
+ def test_aspect_limit():
11
+ assert rc.aspect_problem(834, 834) is None
12
+ assert rc.aspect_problem(730, 949) is None
13
+ assert "1.39" in rc.aspect_problem(730, 1018)
14
+
15
+
16
+ def test_side_bars_are_the_blank_share_of_the_thumbnail_width():
17
+ # a square island fitted into 460x380 is 380 wide: 80 of 460 px blank
18
+ assert rc.side_bar_fraction(500, 500) == pytest.approx(80 / 460)
19
+ # a tall portrait island leaves much more
20
+ assert rc.side_bar_fraction(730, 1018) > 0.4
21
+ # an island as wide as the thumbnail leaves none
22
+ assert rc.side_bar_fraction(460, 380) == 0
23
+
24
+
25
+ def test_empty_quadrant_is_named():
26
+ canvas = [0, 0, 100, 100]
27
+ assert rc.empty_quadrants(canvas, [[20, 20], [80, 20], [20, 80], [80, 80]]) == []
28
+ assert rc.empty_quadrants(canvas, [[20, 20], [20, 80], [80, 80]]) == ["top-right"]
29
+
30
+
31
+ def test_shape_problems_report_aspect_quadrant_and_thumbnail_per_viewport():
32
+ good = {"width": 834, "height": 834, "canvas": [0, 0, 100, 100], "centers": [[20, 20], [80, 20], [20, 80], [80, 80]]}
33
+ assert rc.shape_problems({900: good, 1200: good}) == []
34
+ tall = dict(good, width=730, height=1018, centers=[[20, 20], [20, 80]])
35
+ out = rc.shape_problems({900: good, 1200: tall})
36
+ assert any("1200px" in p and "tall" in p for p in out)
37
+ assert any("empty canvas quadrant" in p for p in out)
38
+ assert any("blank side bars" in p for p in out)
39
+
40
+
41
+ def test_no_build_means_no_problems(tmp_path):
42
+ site = tmp_path / "site"
43
+ (site / "src" / "components" / "arch").mkdir(parents=True)
44
+ mdx = site / "src" / "content" / "articles" / "a.mdx"
45
+ mdx.parent.mkdir(parents=True)
46
+ mdx.write_text("x", encoding="utf-8")
47
+ assert rc.problems_for_article(mdx) == []
@@ -0,0 +1,26 @@
1
+ import sys
2
+
3
+ import pytest
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).parent.parent))
7
+ import arch_text_floor as floor # noqa: E402
8
+
9
+
10
+ def island(scale, *texts):
11
+ return {"scale": scale, "texts": [{"text": t, "fontSize": fs, "scaled": sc} for t, fs, sc in texts]}
12
+
13
+
14
+ def test_scaled_text_is_multiplied_by_the_canvas_scale_and_unscaled_text_is_not():
15
+ assert floor.effective_px(9, 1.2, True) == pytest.approx(10.8)
16
+ assert floor.effective_px(10, 0.5, False) == 10
17
+
18
+
19
+ def test_violations_list_only_text_under_the_floor_smallest_first():
20
+ measured = [island(0.8, ("label", 9, True), ("title", 12, True), ("note", 10, False))]
21
+ assert floor.violations(measured) == [("label", 7.2), ("title", 9.6)]
22
+
23
+
24
+ def test_text_at_the_floor_passes_and_the_worst_size_of_a_repeated_text_wins():
25
+ measured = [island(1.0, ("ok", 10, True), ("x", 9, True)), island(0.5, ("x", 9, True))]
26
+ assert floor.violations(measured) == [("x", 4.5)]
@@ -0,0 +1,203 @@
1
+ """
2
+ publish-article must behave the same from a fresh git worktree (no node_modules) and from
3
+ the deployed skill copy (~/.claude/skills/publish-article) as from the main checkout.
4
+
5
+ Covers:
6
+ - node_deps.ensure_installed(): installs only what is missing, `npm ci` with a lockfile.
7
+ - cmd_publish(): test deps are installed BEFORE deploy.py runs, and a failed install never deploys.
8
+ - cmd_mock(): the printed --feedback-log path sits inside the resolved repo, not the skill dir.
9
+ - learn_feedback: the deployed skill copy resolves the same repo-local feedback dir.
10
+
11
+ Run: pytest skills/publish-article/tests/test_fresh_worktree_layout.py
12
+ """
13
+ import importlib.util
14
+ import json
15
+ import os
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import pytest
22
+
23
+ SKILL_DIR = Path(__file__).resolve().parent.parent
24
+ PIPELINE_SRC = SKILL_DIR.parent.parent / "src" / "publish-article" / "pipeline"
25
+ sys.path.insert(0, str(SKILL_DIR))
26
+ import publish_article # noqa: E402
27
+ import learn_feedback # noqa: E402
28
+ import repo_locate # noqa: E402
29
+ import review_store # noqa: E402
30
+
31
+
32
+ def _load_node_deps():
33
+ spec = importlib.util.spec_from_file_location("node_deps", PIPELINE_SRC / "node_deps.py")
34
+ mod = importlib.util.module_from_spec(spec)
35
+ spec.loader.exec_module(mod)
36
+ return mod
37
+
38
+
39
+ node_deps = _load_node_deps()
40
+
41
+
42
+ class R:
43
+ def __init__(self, rc=0):
44
+ self.returncode = rc
45
+
46
+
47
+ def _pkg(d: Path, lock=True, installed=False) -> Path:
48
+ d.mkdir(parents=True, exist_ok=True)
49
+ (d / "package.json").write_text(json.dumps({"devDependencies": {"@playwright/test": "^1"}}), encoding="utf-8")
50
+ if lock:
51
+ (d / "package-lock.json").write_text("{}", encoding="utf-8")
52
+ if installed:
53
+ pw = d / "node_modules" / "@playwright" / "test"
54
+ pw.mkdir(parents=True)
55
+ (pw / "package.json").write_text("{}", encoding="utf-8")
56
+ return d
57
+
58
+
59
+ @pytest.fixture(autouse=True)
60
+ def isolated_reviews(tmp_path, monkeypatch):
61
+ monkeypatch.setenv("PUBLISH_ARTICLE_REVIEWS", str(tmp_path / "reviews"))
62
+ monkeypatch.setattr(review_store, "legacy_dirs", lambda kind: [])
63
+
64
+
65
+ # ------------------------------------------------------------------ node_deps
66
+ @pytest.fixture
67
+ def npm_calls(monkeypatch):
68
+ seen = []
69
+ monkeypatch.setattr(node_deps, "_npm", lambda: "npm")
70
+ monkeypatch.setattr(node_deps.subprocess, "run", lambda cmd, **kw: seen.append((cmd, kw.get("cwd"))) or R())
71
+ return seen
72
+
73
+
74
+ def test_fresh_worktree_package_gets_npm_ci(tmp_path, npm_calls):
75
+ d = _pkg(tmp_path / "tests")
76
+ assert node_deps.ensure_installed(d) is True
77
+ assert npm_calls[0][0][:2] == ["npm", "ci"] and npm_calls[0][1] == str(d)
78
+
79
+
80
+ def test_package_without_lockfile_gets_npm_install(tmp_path, npm_calls):
81
+ node_deps.ensure_installed(_pkg(tmp_path / "t", lock=False))
82
+ assert npm_calls[0][0][1] == "install"
83
+
84
+
85
+ def test_installed_package_is_left_alone(tmp_path, npm_calls):
86
+ assert node_deps.ensure_installed(_pkg(tmp_path / "t", installed=True)) is False
87
+ assert npm_calls == []
88
+
89
+
90
+ def test_partial_node_modules_counts_as_missing(tmp_path, npm_calls):
91
+ d = _pkg(tmp_path / "t")
92
+ (d / "node_modules").mkdir()
93
+ assert node_deps.ensure_installed(d) is True
94
+
95
+
96
+ def test_failed_install_exits_with_one_clear_line(tmp_path, monkeypatch):
97
+ monkeypatch.setattr(node_deps, "_npm", lambda: "npm")
98
+ monkeypatch.setattr(node_deps.subprocess, "run", lambda cmd, **kw: R(1))
99
+ with pytest.raises(SystemExit) as e:
100
+ node_deps.ensure_installed(_pkg(tmp_path / "t"))
101
+ assert "npm ci failed" in str(e.value)
102
+
103
+
104
+ def test_deploy_installs_site_deps_before_building():
105
+ src = (PIPELINE_SRC / "deploy.py").read_text(encoding="utf-8")
106
+ assert src.index("node_deps.ensure_installed(SITE_DIR") < src.index('"run", "build"')
107
+
108
+
109
+ # --------------------------------------------------------------- fake worktree
110
+ def make_worktree_repo(base: Path) -> publish_article.Repo:
111
+ (base / repo_locate.MARKER).mkdir(parents=True)
112
+ repo = publish_article.Repo(base)
113
+ repo.articles.mkdir(parents=True)
114
+ repo.pipeline.mkdir(parents=True)
115
+ shutil.copy(PIPELINE_SRC / "node_deps.py", repo.pipeline / "node_deps.py")
116
+ _pkg(repo.pa / "tests")
117
+ _pkg(repo.site)
118
+ repo.mdx("demo").write_text('---\ntitle: "Demo"\ndraft: false\n---\n\nBody.\n', encoding="utf-8")
119
+ return repo
120
+
121
+
122
+ def _is_deploy(cmd) -> bool:
123
+ return "deploy.py" in " ".join(map(str, cmd))
124
+
125
+
126
+ def test_publish_installs_test_deps_before_deploy(tmp_path, monkeypatch):
127
+ repo = make_worktree_repo(tmp_path)
128
+ order = []
129
+
130
+ def fake_run(cmd, **kw):
131
+ if Path(str(cmd[0])).name == "npm":
132
+ order.append(("npm", cmd[1], kw.get("cwd")))
133
+ elif _is_deploy(cmd):
134
+ order.append(("deploy",))
135
+ elif cmd[0] == "npx":
136
+ order.append(("smoke",))
137
+ return R(1)
138
+ return R()
139
+
140
+ monkeypatch.setattr(subprocess, "run", fake_run)
141
+ monkeypatch.setattr(shutil, "which", lambda n: "npm")
142
+ assert publish_article.cmd_publish(repo, "demo", run_test=True) == 1
143
+ assert order == [("npm", "ci", str(repo.pa / "tests")), ("deploy",), ("smoke",)]
144
+
145
+
146
+ def test_publish_does_not_deploy_when_test_deps_cannot_install(tmp_path, monkeypatch):
147
+ repo = make_worktree_repo(tmp_path)
148
+ ran = []
149
+
150
+ def fake_run(cmd, **kw):
151
+ ran.append(cmd)
152
+ return R(1 if Path(str(cmd[0])).name == "npm" else 0)
153
+
154
+ monkeypatch.setattr(subprocess, "run", fake_run)
155
+ monkeypatch.setattr(shutil, "which", lambda n: "npm")
156
+ with pytest.raises(SystemExit):
157
+ publish_article.cmd_publish(repo, "demo", run_test=True)
158
+ assert not any(_is_deploy(c) for c in ran)
159
+
160
+
161
+ def test_publish_without_smoke_does_not_touch_test_deps(tmp_path, monkeypatch):
162
+ repo = make_worktree_repo(tmp_path)
163
+ ran = []
164
+ monkeypatch.setattr(subprocess, "run", lambda cmd, **kw: ran.append(cmd) or R(1))
165
+ publish_article.cmd_publish(repo, "demo", run_test=False)
166
+ assert not any(Path(str(c[0])).name.startswith("npm") for c in ran)
167
+
168
+
169
+ # ------------------------------------------------------------- feedback paths
170
+ def test_mock_feedback_log_points_inside_the_repo(tmp_path, monkeypatch, capsys):
171
+ repo = make_worktree_repo(tmp_path / "repo")
172
+ (repo.site / "dist" / "demo").mkdir(parents=True)
173
+ (repo.site / "dist" / "demo" / "index.html").write_text("<html></html>", encoding="utf-8")
174
+ monkeypatch.setattr(subprocess, "run", lambda cmd, **kw: R())
175
+ monkeypatch.setattr(shutil, "which", lambda n: "npm")
176
+ monkeypatch.setattr(publish_article.arch_render_check, "problems_for_article", lambda mdx: [])
177
+ assert publish_article.cmd_mock(repo, "demo") == 0
178
+ out = capsys.readouterr().out
179
+ expected = repo.root / "src" / "publish-article" / "feedback" / "review-comments.jsonl"
180
+ assert f'--feedback-log "{expected}"' in out
181
+
182
+
183
+ def test_deployed_skill_copy_resolves_feedback_inside_the_repo(tmp_path):
184
+ repo_root = tmp_path / "repo"
185
+ (repo_root / repo_locate.MARKER).mkdir(parents=True)
186
+ deployed = tmp_path / "home" / ".claude" / "skills" / "publish-article"
187
+ shutil.copytree(SKILL_DIR, deployed, ignore=shutil.ignore_patterns("tests", "__pycache__"))
188
+ code = f"import sys; sys.path.insert(0, r'{deployed}'); import learn_feedback as l; print(l.COMMENTS_LOG); print(l.CODIFIED_LOG)"
189
+ out = subprocess.run(
190
+ [sys.executable, "-I", "-c", code],
191
+ capture_output=True, text=True, cwd=str(tmp_path),
192
+ env={**os.environ, "PUBLISH_ARTICLE_REPO": str(repo_root)},
193
+ )
194
+ assert out.returncode == 0, out.stderr
195
+ feedback = repo_root / "src" / "publish-article" / "feedback"
196
+ assert out.stdout.split() == [str(feedback / "review-comments.jsonl"), str(feedback / "codified.jsonl")]
197
+
198
+
199
+ def test_mock_and_learn_feedback_share_one_store(tmp_path, monkeypatch):
200
+ repo_root = tmp_path / "repo"
201
+ (repo_root / repo_locate.MARKER).mkdir(parents=True)
202
+ monkeypatch.setenv("PUBLISH_ARTICLE_REPO", str(repo_root))
203
+ assert learn_feedback.feedback_dir(repo_locate.locate()) == learn_feedback.feedback_dir(publish_article.find_repo())
@@ -434,3 +434,34 @@ def test_no_series_field_no_series_check(tmp_path):
434
434
  p = _write_with_site(tmp_path, fm, GOOD_OPENING + "## Details\ntext\n")
435
435
  ok, messages = lint(p)
436
436
  assert ok is True
437
+
438
+
439
+ CAPTION_WORDS = " ".join(["word"] * 70)
440
+
441
+
442
+ def _caption_fm(caption_lines: str) -> str:
443
+ return '---\ntitle: "t"\nskill: demo-skill\nhook: "A specific, real opener line."\ncaption: |\n' + caption_lines + 'tags: [x]\n---\n\n'
444
+
445
+
446
+ def test_authored_caption_with_url_and_install_passes():
447
+ fm = _caption_fm(f" {CAPTION_WORDS}\n {{install}}\n {{url}}\n")
448
+ assert lint_article.lint_caption_override(fm) == []
449
+
450
+
451
+ def test_authored_caption_needs_url_and_install_placeholders():
452
+ fm = _caption_fm(f" {CAPTION_WORDS}\n")
453
+ problems = lint_article.lint_caption_override(fm)
454
+ assert any("{url}" in p for p in problems)
455
+ assert any("{install}" in p for p in problems)
456
+
457
+
458
+ def test_authored_caption_must_be_a_short_post_without_template_claims():
459
+ short = lint_article.lint_caption_override(_caption_fm(" too short {url} {install}\n"))
460
+ assert any("words" in p for p in short)
461
+ claim = lint_article.lint_caption_override(_caption_fm(f" {CAPTION_WORDS} plug-and-play {{install}} {{url}}\n"))
462
+ assert any("plug-and-play" in p for p in claim)
463
+
464
+
465
+ def test_caption_must_be_a_block_scalar():
466
+ problems = lint_article.lint_caption_override('---\ntitle: "t"\ncaption: "one line"\n---\n')
467
+ assert any("block scalar" in p for p in problems)
@@ -903,6 +903,7 @@ def test_mock_builds_a_draft_preview_and_prints_the_monitor_form(repo, monkeypat
903
903
 
904
904
  monkeypatch.setattr(publish_article.subprocess, "run", fake_run)
905
905
  monkeypatch.setattr(publish_article.shutil, "which", lambda n: "/usr/bin/npm")
906
+ monkeypatch.setattr(publish_article, "ensure_node_deps", lambda repo, *dirs: None)
906
907
  assert publish_article.cmd_mock(repo, slug) == 0
907
908
  build_env = [env for cmd, env in seen if env and "PUBLISH_INCLUDE_DRAFTS" in env]
908
909
  assert build_env and build_env[0]["PUBLISH_INCLUDE_DRAFTS"] == "1"
@@ -1027,3 +1028,32 @@ def test_caption_review_shows_then_records_bound_to_the_kit(repo, monkeypatch, c
1027
1028
  def test_caption_review_without_a_kit_exits(repo):
1028
1029
  with pytest.raises(SystemExit):
1029
1030
  publish_article.cmd_caption_review(repo, "no-kit-slug")
1031
+
1032
+
1033
+ def test_authored_caption_block_is_used_as_written_with_placeholders_filled(repo):
1034
+ repo.mdx("demo-slug").write_text(
1035
+ '---\n'
1036
+ 'title: "Demo"\n'
1037
+ 'summary: "Summary that must not be appended."\n'
1038
+ 'skill: demo-skill\n'
1039
+ 'hook: "Hook that must not be used."\n'
1040
+ 'caption: |\n'
1041
+ ' First line.\n'
1042
+ '\n'
1043
+ ' - bullet one\n'
1044
+ ' - bullet two\n'
1045
+ '\n'
1046
+ ' Install: {install}\n'
1047
+ ' Read: {url}\n'
1048
+ 'tags: [developer-tools]\n'
1049
+ '---\n\nBody.\n',
1050
+ encoding="utf-8",
1051
+ )
1052
+ caption = publish_article.build_share_caption(repo, "demo-slug")
1053
+ assert caption.splitlines()[0] == "First line."
1054
+ assert "- bullet two" in caption
1055
+ assert "Install: npx '@example-org/agents' install --bundle demo-bundle" in caption
1056
+ assert "Read: https://blog.example.com/demo-slug/?utm_source=linkedin" in caption
1057
+ assert "Summary that must not be appended." not in caption
1058
+ assert "plug-and-play" not in caption
1059
+ assert "#" not in caption
package/lib/agentsEnv.js CHANGED
@@ -88,7 +88,7 @@ function readProjectEnvFile(projectRoot) {
88
88
  * key not found).
89
89
  */
90
90
  function readHkcuEnvironmentValue(name) {
91
- if (process.platform !== 'win32') return undefined;
91
+ if (process.platform !== 'win32' || process.env.AGENTS_ENV_SKIP_REGISTRY === '1') return undefined;
92
92
  try {
93
93
  const output = child_process.execFileSync('reg', ['query', 'HKCU\\Environment', '/v', name], {
94
94
  encoding: 'utf8',
@@ -115,18 +115,35 @@ function readHkcuEnvironmentValue(name) {
115
115
  * Returns `defaultValue` (undefined unless given) if no source has a
116
116
  * non-empty value for `name`.
117
117
  */
118
- function getSecret(name, defaultValue, { base, projectRoot } = {}) {
118
+ function resolveSecretSource(name, { base, projectRoot } = {}) {
119
119
  const registryValue = readHkcuEnvironmentValue(name);
120
- if (registryValue) return registryValue;
120
+ if (registryValue) return { value: registryValue, source: 'user environment' };
121
121
  const envValue = process.env[name];
122
- if (envValue) return envValue;
122
+ if (envValue) return { value: envValue, source: 'env var' };
123
123
  const fileValue = readEnvFile(base)[name];
124
- if (fileValue) return fileValue;
124
+ if (fileValue) return { value: fileValue, source: 'agents.env' };
125
125
  if (projectRoot) {
126
126
  const projectValue = readProjectEnvFile(projectRoot)[name];
127
- if (projectValue) return projectValue;
127
+ if (projectValue) return { value: projectValue, source: 'project .env' };
128
128
  }
129
- return defaultValue;
129
+ return null;
130
+ }
131
+
132
+ function getSecret(name, defaultValue, opts = {}) {
133
+ const found = resolveSecretSource(name, opts);
134
+ return found ? found.value : defaultValue;
135
+ }
136
+
137
+ /** Names a secret may be read from when its own name has no value, in order. */
138
+ const SECRET_FALLBACKS = Object.freeze({ GITLAB_RUNNER_PAT: Object.freeze(['GITLAB_TOKEN']) });
139
+
140
+ /** The one lookup for a secret that has fallbacks: { name, value, source } of the first name with a value, else null. */
141
+ function resolveSecretWithFallbacks(name, opts = {}) {
142
+ for (const candidate of [name, ...(SECRET_FALLBACKS[name] || [])]) {
143
+ const found = resolveSecretSource(candidate, opts);
144
+ if (found) return { name: candidate, ...found };
145
+ }
146
+ return null;
130
147
  }
131
148
 
132
149
  module.exports = {
@@ -137,4 +154,7 @@ module.exports = {
137
154
  readEnvFile,
138
155
  readProjectEnvFile,
139
156
  getSecret,
157
+ resolveSecretSource,
158
+ resolveSecretWithFallbacks,
159
+ SECRET_FALLBACKS,
140
160
  };
@@ -132,15 +132,15 @@ function render(checks, { projectId = null, groupId = null } = {}) {
132
132
  lines.push(` ${MARK[c.status] || MARK.info} ${c.label}`);
133
133
  if (c.detail && c.status !== 'ok') lines.push(` ${c.detail}`);
134
134
  }
135
- lines.push(
136
- '',
137
- 'Next',
138
- ` 1. ${CLI} secrets --bundle runner (store your GitLab token)`,
139
- ` 2. ${CLI} runner install ${scope} --dry-run (rehearse; changes nothing)`,
140
- ` 3. ${CLI} runner install ${scope}`,
141
- ` 4. ${CLI} runner doctor (check it again any time)`,
142
- '',
143
- );
135
+ const pat = checks.find((c) => c.id === 'pat');
136
+ const tokenUsable = Boolean(pat) && (pat.status === 'ok' || pat.status === 'warn');
137
+ const steps = [
138
+ ...(tokenUsable ? [] : [`${CLI} secrets --bundle runner (store your GitLab token)`]),
139
+ `${CLI} runner install ${scope} --dry-run (rehearse; changes nothing)`,
140
+ `${CLI} runner install ${scope}`,
141
+ `${CLI} runner doctor (check it again any time)`,
142
+ ];
143
+ lines.push('', 'Next', ...steps.map((step, i) => ` ${i + 1}. ${step}`), '');
144
144
  return lines;
145
145
  }
146
146
 
@@ -14,9 +14,13 @@ function tokenKey(name) {
14
14
  return `${KEY_PREFIX}${toKeyName(name)}_TOKEN`;
15
15
  }
16
16
 
17
- function makeSecrets({ getSecret, readSecrets, writeSecrets, removeSecret, base }) {
17
+ function makeSecrets({ getSecret, resolveWithFallbacks, readSecrets, writeSecrets, removeSecret, base }) {
18
18
  return {
19
19
  getPat() {
20
+ if (resolveWithFallbacks) {
21
+ const found = resolveWithFallbacks('GITLAB_RUNNER_PAT', { base });
22
+ return found ? found.value : null;
23
+ }
20
24
  return getSecret('GITLAB_RUNNER_PAT', undefined, { base })
21
25
  || getSecret('GITLAB_TOKEN', undefined, { base })
22
26
  || null;
@@ -58,6 +62,7 @@ function defaultSecrets({ base } = {}) {
58
62
  const store = require('../secretsStore');
59
63
  return makeSecrets({
60
64
  getSecret: agentsEnv.getSecret,
65
+ resolveWithFallbacks: agentsEnv.resolveSecretWithFallbacks,
61
66
  readSecrets: store.readSecrets,
62
67
  writeSecrets: store.writeSecrets,
63
68
  removeSecret: store.removeSecret,
@@ -2,7 +2,7 @@
2
2
 
3
3
  const readline = require('node:readline');
4
4
  const https = require('node:https');
5
- const { readEnvFile } = require('./agentsEnv');
5
+ const { resolveSecretWithFallbacks } = require('./agentsEnv');
6
6
  const { writeSecrets, envPath } = require('./secretsStore');
7
7
 
8
8
  /**
@@ -54,14 +54,9 @@ function collectComponentSecrets(bundles, manifest) {
54
54
  * this module — callers that display it must go through maskValue()).
55
55
  */
56
56
  function resolveSecretSource(name, targetBase) {
57
- if (process.env[name]) {
58
- return { resolved: true, source: 'env var', value: process.env[name] };
59
- }
60
- const values = readEnvFile(targetBase);
61
- if (values[name] && values[name].length > 0) {
62
- return { resolved: true, source: 'agents.env', value: values[name] };
63
- }
64
- return { resolved: false, source: null, value: null };
57
+ const found = resolveSecretWithFallbacks(name, { base: targetBase });
58
+ if (!found) return { resolved: false, source: null, value: null };
59
+ return { resolved: true, source: found.name === name ? found.source : `${found.source} as ${found.name}`, value: found.value };
65
60
  }
66
61
 
67
62
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yasaswy.nagavolu/agents",
3
- "version": "0.32.0",
3
+ "version": "0.32.1",
4
4
  "description": "CLI for installing the yasaswy.nagavolu agent/skill/hook bundle into Claude Code and Codex. `install` opens an interactive bundle menu in a TTY (or `--bundle <key> --yes` for non-interactive installs), with hash-tracked idempotent deploys, native hook wiring, and masked secret prompting. `update` reconciles installed bundles against the current source (hash-tracked: silent overwrite, conflict diff+prompt, or --theirs/--keep-mine). `uninstall` removes a bundle's files and wiring. `secrets` re-runs secret prompting for already-installed bundles.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",