Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(cli): make the CLI discoverable to AI agents + record acquisition attribution (#4043)

Joey372d81b21088
diff --git a/.changeset/core-agent-readme-callout.md b/.changeset/core-agent-readme-callout.md
new file mode 100644
index 0000000000..6e2e5c2fc4
--- /dev/null
+++ b/.changeset/core-agent-readme-callout.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[docs] Point AI agents to the CLI from the core README.
+
+@joeyfarina
+
+`@astryxdesign/core`'s README now leads with a callout telling AI agents to run `npx astryx init` first, which installs the CLI's component index into `AGENTS.md`/`CLAUDE.md`. In an isolated cold-start test, this took agents from 0/5 to 4/5 on discovering and using the CLI (matching the AGENTS.md ceiling); a first-run nudge alone did 0/5.
diff --git a/internal/vibe-tests/cli-discovery-test/PLAN.md b/internal/vibe-tests/cli-discovery-test/PLAN.md
new file mode 100644
index 0000000000..543a322822
--- /dev/null
+++ b/internal/vibe-tests/cli-discovery-test/PLAN.md
@@ -0,0 +1,369 @@
+# CLI Discovery Vibe Test
+
+**Status:** proposal / design (not yet implemented)
+**Owner:** TBD
+**Related:** `../README.md` (Checker Protocol), `../src/setup-environment.mjs`, `../src/universal-eval.ts`
+
+---
+
+## 1. The question
+
+Every existing vibe test asks: _"Given the agent already has the docs (AGENTS.md, or a README that says 'use the CLI'), how good is the code it writes?"_
+
+This experiment asks the **opposite, upstream** question:
+
+> **When an agent lands in a project that just ran `npm install @astryxdesign/core` — with no one having run `astryx init` — does it ever discover the CLI on its own? And which "foolproofing" channel makes that happen _consistently_?**
+
+This is the **chicken-and-egg problem**. The thing that reliably makes agents use the CLI is the `<!-- ASTRYX:START -->` cheat sheet that `astryx init` injects into `AGENTS.md`/`CLAUDE.md`/`.cursorrules`. But that cheat sheet is installed _by the CLI_. A user who only installs the package never runs `init`, so the agent never learns the CLI exists. We want to know which passive channels close that gap.
+
+**Note:** the current `environments/project-astryx/README.md` already contains "Use the CLI to look up component props." That makes it unfit as a control for _this_ experiment — it pre-seeds the answer. Here, the README hint is one of the **conditions under test**, not a constant.
+
+---
+
+## 2. What "works" means
+
+The user's phrasing was _"what actually works **consistently**."_ So the primary output is not a single score — it's a **reliability rate per channel**: the fraction of fresh, independent runs in which the agent discovers and uses the CLI, with its variance. A channel that works 9/10 times beats one that works 5/10 with high variance, even if the 5/10 one occasionally produces prettier code.
+
+---
+
+## 3. Hypotheses
+
+| # | Channel | Hypothesis | Reaches agents? |
+| --- | ---------------------------- | ------------------------------------------------------------------------------------------------------ | --------------- |
+| H1 | Bare install (control) | Agents almost never discover the CLI; they guess APIs and hallucinate | — |
+| H2 | README top callout | Moderate lift; depends on whether the agent opens `node_modules/@astryxdesign/core/README.md` | Sometimes |
+| H3 | Type/JSDoc `@see` banner | High + consistent lift; agents read `.d.ts`/hover as a reflex, and it survives pnpm script-blocking | Usually |
+| H4 | Postinstall banner | Low/unreliable; only seen if the agent itself runs install and reads stdout; pnpm 10 skips dep scripts | Rarely |
+| H5 | CLI first-run nudge | Converts _awareness → init_, but only fires once the agent already runs `astryx` | Conditional |
+| H6 | AGENTS.md present (ceiling) | Near-100%; this is the known-good state `init` produces | Yes |
+| H7 | README + type banner (combo) | Approaches the ceiling using only passive, ship-in-the-package channels | Usually |
+
+The decision we want to make: **find the minimal set of passive channels (things we can ship in the npm package, no user action) whose discovery rate approaches the H6 ceiling.**
+
+---
+
+## 4. Variables
+
+### Independent variable — the discovery channel (the "condition")
+
+Defined in [`conditions.json`](conditions.json). Each condition is the bare realistic project **plus** zero or more channel patches. Only the channel varies; prompts, persona, environment, packages, and evaluation are held constant (Checker Protocol §2).
+
+### Dependent variables — the discovery funnel (NEW) + downstream quality (REUSED)
+
+**Discovery funnel** (the point of this experiment; measured per run):
+
+1. **Awareness** — did the agent reference the CLI at all? (transcript)
+2. **Invocation** — did it actually run any `npx astryx …`? (**ground truth**, see §6.2)
+3. **Init** — did it run `astryx init`?
+4. **Doc retrieval** — did it run `astryx component` / `build` / `search` / `template`?
+
+**Downstream quality** (reuse `universal-eval.ts` unchanged so results are comparable to prior runs):
+
+5. correctness, accessibility, code quality, efficiency, maintainability
+6. escape-hatch / hallucination rate (per `prompts/evaluator.md`: hallucinated props, invalid `--xds-*`/`--space-*` tokens, phantom components)
+
+The funnel is the independent contribution; the quality dims answer the follow-on "…and does discovery actually make the output better?"
+
+---
+
+## 5. Conditions (the matrix)
+
+See [`conditions.json`](conditions.json) for the machine-readable version. Summary:
+
+| id | Channel(s) present | Role |
+| ----------------- | ------------------------------------------------------------------------------- | ------------------- |
+| `c0-bare` | Nothing. `package.json` + symlinked packages. No CLI mention anywhere. | **Control (floor)** |
+| `c1-readme` | Core `README.md` gains a top "Using an AI agent? run `npx astryx init`" callout | Candidate |
+| `c2-types` | Generated `@see npx astryx …` banner injected into each component's `.d.ts` | Candidate |
+| `c3-postinstall` | Simulated install-time banner (see §9 realism caveat) | Candidate (probe) |
+| `c4-firstrun` | CLI present; any `astryx` call prints the "run init" nudge | Candidate |
+| `c5-agents-md` | Fully initialized: `AGENTS.md` with the real `<!-- ASTRYX:START -->` block | **Ceiling** |
+| `c6-readme+types` | c1 + c2 | Candidate combo |
+| `c7-all-passive` | c1 + c2 + c4 (everything shippable without user action) | Candidate combo |
+
+Each candidate is compared against **both** `c0-bare` (lift over doing nothing) and `c5-agents-md` (how close to the ceiling).
+
+---
+
+## 6. Harness design
+
+Reuse Mechanism B (`setup-environment.mjs`, symlinked isolated projects) — it's the representative-environment path the Checker Protocol wants. Three additions are needed.
+
+### 6.1 Channel patches (compose conditions from one bare base)
+
+Instead of hand-maintaining 8 template dirs (drift risk, violates "only the SUT varies"), build every condition from **one bare base template** + small, reviewable **patch functions**, one per channel. This also lets us test channels **before we build them for real** (e.g., inject the type banner into a _copy_ of `dist/**/*.d.ts`; patch a copy of `README.md`), so the experiment informs whether to ship the feature — not the other way around.
+
+Patches (each toggled by a condition):
+
+- `patch:readme-callout` — prepend the AI callout to the project's copy of core's `README.md`.
+- `patch:type-banner` — copy core into the project (not symlink) and inject the standard `@see` banner into each component's public `.d.ts`.
+- `patch:agents-md` — run the real `npx astryx init --features agents --agent-docs-path AGENTS.md` (reuses `installAgentsDocs()` from `interactive.ts`).
+- `patch:first-run-nudge` — swap the `astryx` bin shim for one that also prints the nudge.
+- `patch:postinstall-banner` — see §9.
+
+> **Realism guard:** every patch must only touch files a real npm consumer would actually receive. Core ships `README.md` and `dist/**` (its `package.json#files`), so c1/c2 are authentic. `AGENTS.md` is _not_ shipped in the package — it only exists post-`init` — which is exactly why c5 represents "user ran init" (the ceiling), not a shippable default.
+
+### 6.2 Ground-truth CLI instrumentation (don't trust self-report)
+
+The existing symlink `node_modules/.bin/astryx → packages/cli/bin/astryx.mjs` becomes a **logging shim**: a tiny wrapper that appends `{ts, argv}` to `projects/<promptId>/.astryx-invocations.log`, then execs the real bin. This gives an **objective** record of _every_ CLI call (invocation, init, which subcommands) independent of what the agent claims. This is the single most important measurement — discovery is defined by this log, not by the transcript.
+
+### 6.3 Extended result schema (self-report as secondary signal)
+
+Extend the per-task result JSON the subagents already write with a discovery block (self-reported; cross-checked against the ground-truth log):
+
+```json
+{
+ "completedAt": "<ISO>",
+ "discovery": {
+ "sawCliReference": true,
+ "howDiscovered": "readme | types | nudge | guessed | none",
+ "ranInit": false,
+ "cliCommandsRun": ["astryx component Button", "astryx build \"...\""]
+ }
+}
+```
+
+A new aggregator, `discovery-aggregate.ts` (sibling of `universal-aggregate.ts`), joins the ground-truth log + the self-report + the existing `universal.json` per condition and emits funnel rates, quality deltas, and consistency stats.
+
+---
+
+## 7. Procedure
+
+1. **Prompts** — reuse a stratified sample of `test-sets/default.json` (identical prompts across conditions, per §2/§3 of the Checker Protocol). Curated subset in [`prompts.json`](prompts.json). `expectedComponents` stays evaluation-only and is never shown to the agent (invariant §3).
+2. **Repetitions** — each `condition × prompt` runs **K ≥ 5** times with fresh, context-free subagents (invariant §5). Discovery is stochastic; a rate needs repetitions, not one sample.
+3. **Agents/models** — discovery is _harness-dependent_ (Cursor auto-loads `AGENTS.md`/`.cursorrules`; Claude Code auto-loads `AGENTS.md`/`CLAUDE.md`; a bare API agent auto-loads nothing). Run at least: (a) Claude Code subagents (the existing runner), and (b) one "no auto-load" agent to isolate the file-reading channels (types/README) from the harness auto-load channel (AGENTS.md). Record the agent/model with each result.
+4. **Blinding** — evaluation is the existing deterministic `universal-eval.ts` (already blind to condition). The discovery log is objective. No human scoring in the loop.
+
+### Run commands (proposed, after harness work lands)
+
+```bash
+# Generate all conditions for a stratified sample, K reps each (prints iter IDs)
+node internal/vibe-tests/cli-discovery-test/setup-discovery.mjs --sample 8 --reps 5
+
+# Parent agent spawns fresh subagents per task file (as in the interactive runner)
+
+# Evaluate
+pnpm -F @astryxdesign/vibe-tests aggregate --iteration <id> # reuse: quality dims
+tsx internal/vibe-tests/cli-discovery-test/discovery-aggregate.ts --experiment <expId> # new: funnel + consistency
+```
+
+---
+
+## 8. Analysis & decision rule
+
+For each condition report, per agent:
+
+- **Discovery rate** = P(ran any `npx astryx`) with a Wilson 95% CI over all runs.
+- **Init rate**, **doc-retrieval rate** (same treatment).
+- **Consistency** = the width of that CI + variance across prompts/reps. A channel is "consistent" only if the CI is tight and it holds across prompt categories and both agents.
+- **Quality delta** = mean `overall` (and hallucination rate) vs `c0-bare`.
+
+**Pre-registered decision rule (tune before running):**
+
+- A channel **ships** if its discovery rate is **≥ 80%** with a lower CI bound **> c0-bare's upper bound**, and it holds across both agents.
+- Prefer the **minimal passive combo** (`c6`/`c7`) that reaches **≥ 90% of the `c5-agents-md` ceiling**. That combo becomes the recommended default foolproofing.
+- Any channel whose discovery rate is high-mean but high-variance is labeled "unreliable" and not counted as a primary mechanism (this is the whole "consistently" ask).
+
+---
+
+## 9. Risks & limitations
+
+- **Postinstall realism (c3).** In a symlinked env, deps are already present, so the agent never runs install and never sees a banner. Authentic simulation requires starting from an _uninstalled_ project and shimming the installer's stdout — slow and fragile in a pnpm monorepo. **Recommendation:** treat c3 as a low-priority, separately-run probe (or reason about it analytically), since we already know postinstall is suppressed by pnpm 10 / CI / `--ignore-scripts`. Don't let it block the core matrix.
+- **Harness-dependence.** `AGENTS.md` auto-load is a property of the _agent harness_, not the package. The type/README channels are the ones we can ship that don't depend on the harness — call this out in the writeup so we don't over-credit c5.
+- **Self-report bias.** Mitigated by the ground-truth bin shim (§6.2); self-report is secondary.
+- **Copy-vs-symlink for c2.** Injecting type banners requires copying core (not symlinking). Keep everything else identical so the only delta is the banner text.
+- **Prompt sensitivity.** Discovery is likelier on harder prompts (guessing fails). Stratify across complexity so we don't over- or under-state the rate.
+
+---
+
+## 10. Phasing
+
+1. **Phase 0 (this doc)** — design + folder scaffold. ← we are here
+2. **Phase 1** — harness: bare base template, patch composer, bin-shim logging, `discovery-aggregate.ts`. Verify with `scripts/smoke-test.sh`-style fixtures (no LLM).
+3. **Phase 2** — pilot: `c0-bare` vs `c5-agents-md` on a small sample to validate the funnel + confirm the floor/ceiling gap is real.
+4. **Phase 3** — full matrix (all conditions × K reps × 2 agents).
+5. **Phase 4** — writeup + decision: which channel(s) to actually ship (feeds back into the P0/P1 recommendations for the core package).
+
+---
+
+## 11. Folder layout
+
+```
+internal/vibe-tests/cli-discovery-test/
+├── PLAN.md # this file — experiment design
+├── conditions.json # the channel matrix (independent variable)
+├── prompts.json # curated stratified prompt subset (from default.json)
+├── setup-discovery.mjs # (Phase 1) builds conditions from base + patches
+├── discovery-aggregate.ts # (Phase 1) funnel + consistency aggregator
+└── results/ # (gitignored) per-experiment output
+```
+
+---
+
+## 12. Checker Protocol compliance
+
+| Invariant | How this experiment honors it |
+| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| §1 Fair Evaluators | Same `universal-eval.ts` + same objective discovery log for all conditions |
+| §2 Only the SUT varies | One bare base + single-channel patches; prompts/persona/env identical |
+| §3 Never leak the answer | `expectedComponents` eval-only; no CLI command is pre-built from expected components; the _control_ gets no CLI hint at all |
+| §4 Representative environment | Patches only touch files a real npm consumer receives (`README.md`, `dist/**`); `AGENTS.md` is explicitly the post-`init` ceiling, not a shipped default |
+| §5 Context-free sub-agents | Fresh subagent per run; K reps are independent; no shared session |
+
+---
+
+## 13. Pilot status (implemented)
+
+Built and verified end-to-end **without an LLM** (the mechanism, not the finding):
+
+- `setup-discovery.mjs` — builds one isolated project per `condition × prompt × rep` from a bare "just installed `@astryxdesign/core`" base (core + theme symlinked, **CLI not listed**), wires the ground-truth `astryx` logging shim into `node_modules/.bin`, and writes task files + `discovery-config-<expId>.json`. Pilot wires `c0-bare` (floor) and `c5-agents-md` (ceiling); other conditions are guarded until added to `PATCHES`.
+- `discovery-aggregate.ts` — reads the invocation logs (+ self-report), prints the funnel with Wilson 95% CIs, writes `discovery-summary-<expId>.json`.
+
+Verified: `c0` has no `AGENTS.md`; `c5` receives the real `<!-- ASTRYX:START -->` cheat sheet; the shim records `{ts, argv}` on every `astryx` call; the task prompt carries **no** `expectedComponents` (no answer leak, §3).
+
+Run:
+
+```bash
+# 1. generate conditions (curated prompts, or --sample N / --reps K)
+node cli-discovery-test/setup-discovery.mjs --prompts fwc-1,ps-1
+# 2. spawn a FRESH, context-free sub-agent per printed task file
+# 3. score the funnel
+npx tsx cli-discovery-test/discovery-aggregate.ts --experiment <expId>
+```
+
+Next: run step 2 with real agents at **K≥5** across the curated set (a pilot at n=2 gives CIs too wide to separate floor from ceiling — that is the point of more reps), then wire `c1-readme` / `c2-types` / `c4-firstrun`.
+
+Known note: inside this monorepo the generated `AGENTS.md` prints `pnpm exec astryx` (run-prefix detection sees pnpm); a standalone consumer sees `npx`. The shim resolves both, so it doesn't affect measurement.
+
+---
+
+## 14. Findings — pilot run 1 (experiment `b65414e6`): method invalid, plumbing works
+
+Ran `c0-bare` vs `c5-agents-md` × {`fwc-1`, `ps-1`} as 4 fresh in-session Task sub-agents.
+
+**The funnel looked perfect — and that's the trap.** Ground-truth (shim log): `c0` invoked 0/2, `c5` 2/2. A textbook floor/ceiling. **It is a FALSE clean.**
+
+Self-reports contradict it: both `c0` agents ran the CLI heavily (**9** and **35** `astryx` commands) with `howDiscovered: "nudge"`/`"readme"`. They invoked the **repo-root** CLI (`node packages/cli/bin/astryx.mjs`, per this repo's own always-applied `CLAUDE.md`), which **bypasses the project shim** — so `c0`'s ground-truth log stayed empty despite heavy use.
+
+**Two contamination vectors, both from running the experiment _inside the repo_:**
+
+1. **Injected workspace rules** — the repo's always-applied `CLAUDE.md` (the ASTRYX-CLI bootstrap block) teaches the CLI to every in-session sub-agent. `c0` fwc-1 literally reported `howDiscovered: "nudge"` = injected rules.
+2. **Repo-root binary + source proximity** — agents reach the workspace `astryx` and the full design-system source by walking up out of the project, bypassing the isolated sandbox.
+
+**Lessons:**
+
+- **Dual signal was essential.** Shim-log alone said "clean" (0 vs 2); self-report alone would misattribute the channel; only together did they expose the contamination. Keep both.
+- **The shim must be the _only_ reachable `astryx`** for the number to mean anything.
+
+**Required pivot (Phase 1.5 — isolated runner):**
+
+- Copy each task project **outside the repo** (e.g. `/tmp`) — no ancestor `CLAUDE.md`, no repo source to explore.
+- Spawn a **headless agent with NO astryx workspace rules** (Cursor SDK / `cursor-agent`), not in-session Task sub-agents.
+- Ensure **no repo-root `astryx` on `PATH`** — only the project shim (or `npx` from the registry) resolves, so every call is captured and attributable to a project channel.
+
+---
+
+## 15. Findings — pilot 2 (ISOLATED, valid) · exp `ee116c67`
+
+Fix from §14 applied: headless `cursor-agent` in `/tmp` sandboxes (no repo rules, packages copied out of the repo). Conditions `c0-bare` / `c1-readme` / `c4-nudge` / `c5-agents-md` × {`fwc-1`, `ps-1`}, n=2/condition, model `auto`.
+
+Funnel (ground truth = astryx shim log):
+
+| condition | invoked astryx | ran init | core docs.mjs* |
+| ------------------------ | -------------- | -------- | -------------- |
+| `c0-bare` (floor) | 0/2 | 0/2 | 2/2 |
+| `c1-readme` | **2/2** | **2/2** | 2/2 |
+| `c4-nudge` | 0/2 | 0/2 | 2/2 |
+| `c5-agents-md` (ceiling) | 2/2 | 0/2 | 0/2 |
+
+\* self-reported use of core's built-in `docs.mjs` (README channel); the astryx shim can't see it.
+
+**Headline findings:**
+
+1. **Isolation validated** — `c0` floor = 0 astryx calls (vs 9–35 when contaminated in-repo). The §14 fix holds.
+2. **README callout wins** — `c1-readme` drove **2/2 `init`** + CLI use, matching the ceiling. It's the only passive channel that triggers the _persistent_ install (writes `AGENTS.md`), ships in the package, and agents read it unprompted.
+3. **Nudge-alone can't bootstrap** — `c4-nudge` = 0/2, identical to floor. The first-run nudge only fires once the agent already runs `astryx`; it converts, it can't discover. Chicken-and-egg confirmed (H5).
+4. **The floor isn't doc-less** — `c0`/`c4` agents fall back to core's built-in `docs.mjs` (via the package README) 2/2, but never reach the CLI's `build`/`template` composition.
+5. **Ceiling** (`c5`): 2/2 CLI use, 0 `init` (already has `AGENTS.md`), 0 `docs.mjs` (used the CLI instead).
+
+**Caveats:** n=2 → wide Wilson CIs. Direction is unambiguous and matches hypotheses, but the decision rule needs **K≥5**. Single model (`auto`). `c2-types` not yet wired.
+
+**Next:** K≥5 scale-up on `c0`/`c1`/`c4`/`c5` to tighten CIs (esp. confirm `c1-readme` ≫ `c4-nudge`≈floor); then wire `c2-types` and multi-model.
+
+---
+
+## 16. Decision + shipped · K=5 complete (exp `98144547`, `ps-1`, model `auto`)
+
+| condition | invoked astryx (n=5) | ran init | completed code |
+| ------------------------ | -------------------- | -------- | -------------- |
+| `c0-bare` (floor) | 0/5 | 0/5 | 5/5 |
+| `c1-readme` | **4/5 (80%)** | **4/5** | 5/5 |
+| `c4-nudge` | 0/5 | 0/5 | 5/5 |
+| `c5-agents-md` (ceiling) | **5/5 (100%)** | 0/5 | 3/5 |
+
+**Decision:**
+
+- **Ship the README callout (`c1`).** 80% invoke + `init` — the only passive channel that triggers the _persistent_ `AGENTS.md` install, i.e. the causal chain README → `init` → `AGENTS.md` (the 100% ceiling). Delivered via **core's README** — the surface the floor proved agents read (`docs.mjs` 5/5). ✅ SHIPPED: `packages/core/README.md`.
+- **Ceiling nuance:** `c5` (AGENTS.md) hits 100% CLI use but only **3/5 completed** the code — the 30-command CLI-exploration path is thorough but token-expensive and sometimes doesn't finish. `c1-readme` completed **5/5** — better cost/completion, because README→init lands the same `AGENTS.md` without the agent burning the turn exploring.
+- **Nudge-alone (`c4`) = 0/5.** Confirmed useless for _discovery_; keep only as post-discovery conversion. Do not rely on it.
+
+**Attribution — considered and removed.** A `--via` tag + local `.astryx/attribution.jsonl` was prototyped, but it's local-only (no passive way to aggregate across the ecosystem), so it was dropped. The npm download share (~63% of core installs already pull the CLI) is the adoption signal we keep.
+
+**Caveats:** single model (`auto`); n=5 (README lower CI ~38% vs floor upper ~43% — strong, tighten with K=10). `c2-types` still untested (the other agent-native channel).
+
+---
+
+## Isolated runner (implemented)
+
+**Isolated runner** — `run-isolated.mjs` fixes the §14 contamination. Each task runs in a `/tmp` sandbox with packages **copied out of the repo** (walking up lands in `/tmp`, not the design-system source), driven by a headless `cursor-agent` whose **cwd is the sandbox** (so this repo's always-applied `CLAUDE.md` never applies), with only the shim `astryx` reachable. Verified without agents: `c0` bare, `c5` tagged `AGENTS.md`, `core`→`/tmp`, shim logs, and `cursor-agent -p` headless responds.
+
+Run: `node cli-discovery-test/run-isolated.mjs --run --prompts fwc-1,ps-1` → `discovery-aggregate.ts --experiment <id>`.
+
+---
+
+## 15. Findings — pilot run 2 (isolated, experiment `49e1f721`): contamination fixed, but the floor saturates
+
+Rebuilt as isolated `/tmp` sandboxes driven by headless `cursor-agent` (cwd=`/tmp` → the repo `CLAUDE.md` never loads; **verified** a `/tmp` agent reports `NONE` for rules and `astryx`/`npx astryx` both not found). Clean run — but no separation:
+
+| condition | invoked CLI | doc retrieval |
+| -------------- | -------------- | ------------- |
+| `c0-bare` | **2/2 (100%)** | 2/2 |
+| `c5-agents-md` | 2/2 (100%) | 2/2 |
+
+**Why they tied:** the agent reported `howDiscovered: "readme"` — the **`@astryxdesign/core` README already ships a CLI section** (`## XDS CLI`, `## Page Layouts`, `npx astryx …`). So a "bare" install already advertises the CLI, and a capable agent finds + uses it unprompted (fwc-1: 3 calls; ps-1: 21 calls). The `.bin` shim was a second, artifactual hint.
+
+**Implications:**
+
+- The shipping package **already drives CLI discovery** for capable agents that read `node_modules` docs — the problem may be smaller than assumed _for this class of agent_.
+- To measure any _added_ channel's value, the base must be **truly bare**: strip the CLI section from the core README **and** hide the runnable shim (PATH proxy, not `node_modules/.bin`). Implemented in `run-isolated.mjs`: `c0-strip` (floor), `c0-readme` (README channel), `c5-agents-md` (AGENTS.md channel).
+- **Sharpest open question:** does discovery hold for _weaker_ agents/harnesses that don't explore `node_modules` or read READMEs? That's where the shippable channels (types, first-run nudge) likely earn their keep.
+
+---
+
+## 16. Findings — pilot run 3 (reliable `.bin` shim, experiment `83e88ff2`) + consolidated conclusions
+
+The PATH proxy (run 2) was flaky (a README agent's `npx astryx` hit the real registry → 401, a false negative). Switched to a reliable `node_modules/.bin` shim (npx resolves local bin first). Result (n=2/cell):
+
+| condition | invoked CLI | per-task calls |
+| ---------------------- | ----------- | ----------------------- |
+| `c0-strip` (true bare) | 50% (1/2) | fwc-1: 0 · ps-1: **24** |
+| `c0-readme` | 100% (2/2) | 2 · 2 |
+| `c5-agents-md` | 100% (2/2) | 4 · 22 |
+
+`c0-strip/ps-1` (stripped README, no AGENTS.md) still used the CLI 24× — transcript: _"exploring the project revealed an `astryx` CLI in `node_modules/.bin`."_ The reliable shim is discoverable, so a thorough agent finds it on hard tasks.
+
+**Robust conclusions (consistent across all three isolated runs):**
+
+1. **Self-report is unreliable.** `howDiscovered`/`cliCommandsRun` repeatedly diverge from the ground-truth log (c0-strip reported `"readme"` though the README was stripped and it actually found `.bin`; c0-readme claimed 3/15 calls it never made). **Ground-truth logging is mandatory.**
+2. **`cursor-agent` is an aggressive CLI-seeker.** Across README / AGENTS.md / true-bare, it hunts for and uses the CLI — especially on non-trivial tasks (`ps-1` → 22–24 calls everywhere; `fwc-1` → 0–4). Discovery scales with **task difficulty + agent thoroughness**, not just advertising.
+3. Every advertising channel pushes discovery to ~100%; even the true-bare floor is ~50% for this agent.
+
+**Interpretation of the original question:** for a _capable_ agent, CLI discovery is largely **not the bottleneck** — it already finds the CLI via the README, `node_modules`, or by guessing `npx astryx`. The shippable channels (types, first-run nudge, README callout) should help most for **weaker agents/harnesses** that don't explore or read docs — which this pilot did not test.
+
+**Caveats:** n=1–2/cell (directional only); the `.bin` shim is discoverable (mild floor inflation vs a real bare install, though a real agent guessing `npx astryx` would succeed via the public registry); only one agent and one theme; **no code-quality scoring yet.**
+
+**Recommended next (higher-value than more capable-agent runs):**
+
+1. **Test a weaker agent/model** (or a harness that doesn't auto-explore) — where channels should actually separate.
+2. **Score code quality** (reuse `universal-eval.ts`) — does _using_ the CLI yield better code? That's the real payoff metric, not invocation count.
+3. **Scale reps (K≥5)** once the above is set, for tight CIs.
diff --git a/internal/vibe-tests/cli-discovery-test/assets/npm-cli-weekly.png b/internal/vibe-tests/cli-discovery-test/assets/npm-cli-weekly.png
new file mode 100644
index 0000000000..405b47a49f
Binary files /dev/null and b/internal/vibe-tests/cli-discovery-test/assets/npm-cli-weekly.png differ
diff --git a/internal/vibe-tests/cli-discovery-test/assets/npm-core-weekly.png b/internal/vibe-tests/cli-discovery-test/assets/npm-core-weekly.png
new file mode 100644
index 0000000000..12357a7901
Binary files /dev/null and b/internal/vibe-tests/cli-discovery-test/assets/npm-core-weekly.png differ
diff --git a/internal/vibe-tests/cli-discovery-test/conditions.json b/internal/vibe-tests/cli-discovery-test/conditions.json
new file mode 100644
index 0000000000..33b421fe1b
--- /dev/null
+++ b/internal/vibe-tests/cli-discovery-test/conditions.json
@@ -0,0 +1,94 @@
+{
+ "name": "cli-discovery",
+ "description": "Cold-start discovery experiment: which passive channel makes an agent discover + use the astryx CLI when no one ran `astryx init`. Each condition = the bare base project + zero or more channel patches. Only the channel varies.",
+ "base": {
+ "template": "bare",
+ "notes": "package.json + symlinked @astryxdesign/core & theme-neutral + logging astryx bin shim. NO README CLI hint, NO AGENTS.md. This is the realistic `npm install @astryxdesign/core` state."
+ },
+ "conditions": [
+ {
+ "id": "c0-bare",
+ "label": "Bare install (control)",
+ "role": "control",
+ "patches": [],
+ "reaches": {"humans": false, "agents": false},
+ "harnessDependent": false,
+ "hypothesis": "Agents rarely discover the CLI; they guess APIs and hallucinate props/tokens."
+ },
+ {
+ "id": "c1-readme",
+ "label": "README top callout",
+ "role": "candidate",
+ "patches": ["patch:readme-callout"],
+ "reaches": {"humans": true, "agents": "sometimes"},
+ "harnessDependent": false,
+ "hypothesis": "Moderate lift; depends on the agent opening node_modules/@astryxdesign/core/README.md."
+ },
+ {
+ "id": "c2-types",
+ "label": "Type/JSDoc @see banner",
+ "role": "candidate",
+ "patches": ["patch:type-banner"],
+ "reaches": {"humans": true, "agents": "usually"},
+ "harnessDependent": false,
+ "hypothesis": "High + consistent; agents read .d.ts/hover reflexively and it survives pnpm script-blocking."
+ },
+ {
+ "id": "c3-postinstall",
+ "label": "Postinstall banner (probe)",
+ "role": "candidate-probe",
+ "patches": ["patch:postinstall-banner"],
+ "reaches": {"humans": true, "agents": "rarely"},
+ "harnessDependent": false,
+ "hypothesis": "Low/unreliable; only seen if the agent runs install itself and reads stdout. pnpm 10 skips dep scripts. Run separately; see PLAN.md §9."
+ },
+ {
+ "id": "c4-firstrun",
+ "label": "CLI first-run nudge",
+ "role": "candidate",
+ "patches": ["patch:first-run-nudge"],
+ "reaches": {"humans": true, "agents": "conditional"},
+ "harnessDependent": false,
+ "hypothesis": "Converts awareness -> init, but only fires once the agent already runs `astryx`."
+ },
+ {
+ "id": "c5-agents-md",
+ "label": "AGENTS.md present (ceiling)",
+ "role": "ceiling",
+ "patches": ["patch:agents-md"],
+ "reaches": {"humans": true, "agents": true},
+ "harnessDependent": true,
+ "hypothesis": "Near-100%; the known-good state `astryx init` produces. Upper bound, not a shippable default."
+ },
+ {
+ "id": "c6-readme+types",
+ "label": "README + type banner",
+ "role": "candidate-combo",
+ "patches": ["patch:readme-callout", "patch:type-banner"],
+ "reaches": {"humans": true, "agents": "usually"},
+ "harnessDependent": false,
+ "hypothesis": "The two agent-native passive channels together approach the ceiling."
+ },
+ {
+ "id": "c7-all-passive",
+ "label": "All shippable passive channels",
+ "role": "candidate-combo",
+ "patches": ["patch:readme-callout", "patch:type-banner", "patch:first-run-nudge"],
+ "reaches": {"humans": true, "agents": "usually"},
+ "harnessDependent": false,
+ "hypothesis": "Everything shippable without user action; the realistic `we foolproofed it but nobody ran init` state."
+ }
+ ],
+ "patches": {
+ "patch:readme-callout": "Prepend an 'Using an AI agent? run `npx astryx init`' callout to the project's copy of core README.md.",
+ "patch:type-banner": "Copy (not symlink) core; inject a standard `@see npx astryx component <Name>` + `npx astryx init` banner into each component public .d.ts.",
+ "patch:agents-md": "Run real `npx astryx init --features agents --agent-docs-path AGENTS.md` (reuses installAgentsDocs from interactive.ts).",
+ "patch:first-run-nudge": "Replace the astryx bin shim with one that also prints the 'run init' nudge on first invocation.",
+ "patch:postinstall-banner": "Simulate an install-time banner. See PLAN.md §9 for realism caveats; low priority."
+ },
+ "measurement": {
+ "groundTruth": "projects/<promptId>/.astryx-invocations.log (bin shim, objective)",
+ "selfReport": "results/<promptId>.json -> discovery block (secondary, cross-checked)",
+ "quality": "reuse universal-eval.ts (correctness, accessibility, codeQuality, efficiency, maintainability) + evaluator.md escape-hatch/hallucination rate"
+ }
+}
diff --git a/internal/vibe-tests/cli-discovery-test/discovery-aggregate.ts b/internal/vibe-tests/cli-discovery-test/discovery-aggregate.ts
new file mode 100644
index 0000000000..8166a53536
--- /dev/null
+++ b/internal/vibe-tests/cli-discovery-test/discovery-aggregate.ts
@@ -0,0 +1,281 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file discovery-aggregate.ts
+ * @input --experiment <id> (in-repo config) | --iso <id> (isolated /tmp config)
+ * @output Per-condition discovery funnel + results/discovery-summary-<id>.json
+ * @position internal/vibe-tests/cli-discovery-test — scores the cold-start experiment
+ *
+ * Funnel is defined by GROUND TRUTH — the .astryx-invocations.log the bin shim
+ * writes — not by self-report. Self-report (the discovery block in the result
+ * JSON) is a secondary cross-check, and also surfaces a channel the shim can't
+ * see: core's built-in `docs.mjs` (reached via the package README), which is a
+ * discovery path that ships in `@astryxdesign/core` today (PLAN.md §14/§15).
+ *
+ * Rates carry a Wilson 95% CI so "works consistently" is legible.
+ *
+ * Usage:
+ * npx tsx cli-discovery-test/discovery-aggregate.ts --experiment <id>
+ * npx tsx cli-discovery-test/discovery-aggregate.ts --iso <id>
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+const EXP_DIR = import.meta.dirname;
+const VIBE_DIR = path.resolve(EXP_DIR, '..');
+const RESULTS_DIR = path.join(VIBE_DIR, 'results');
+
+const DOC_RETRIEVAL_CMDS = new Set([
+ 'component',
+ 'build',
+ 'search',
+ 'template',
+ 'docs',
+ 'swizzle',
+]);
+
+interface LogEntry {
+ ts: string;
+ argv: string[];
+}
+
+interface TaskDesc {
+ taskId: string;
+ basePromptId: string;
+ category: string;
+ projectDir: string;
+ invocationLog: string;
+}
+
+interface RunResult {
+ taskId: string;
+ category: string;
+ invokedAstryx: boolean;
+ ranInit: boolean;
+ ranDocRetrieval: boolean;
+ usedCoreDocsMjs: boolean; // self-reported README → docs.mjs channel (shim can't see it)
+ howDiscovered: string | null;
+ commands: string[];
+ completed: boolean;
+}
+
+function wilson(
+ successes: number,
+ n: number,
+ z = 1.96,
+): {p: number; lo: number; hi: number} {
+ if (n === 0) {
+ return {p: 0, lo: 0, hi: 0};
+ }
+ const phat = successes / n;
+ const z2 = z * z;
+ const denom = 1 + z2 / n;
+ const center = phat + z2 / (2 * n);
+ const margin = z * Math.sqrt((phat * (1 - phat) + z2 / (4 * n)) / n);
+ return {
+ p: phat,
+ lo: Math.max(0, (center - margin) / denom),
+ hi: Math.min(1, (center + margin) / denom),
+ };
+}
+
+function readJsonl(file: string): LogEntry[] {
+ if (!fs.existsSync(file)) {
+ return [];
+ }
+ return fs
+ .readFileSync(file, 'utf-8')
+ .trim()
+ .split('\n')
+ .filter(Boolean)
+ .map(l => JSON.parse(l) as LogEntry);
+}
+
+function subcommand(argv: string[]): string | null {
+ return argv.find(a => !a.startsWith('-')) ?? null;
+}
+
+function evaluateRun(task: TaskDesc): RunResult {
+ const log = readJsonl(task.invocationLog);
+ const subs = log
+ .map(e => subcommand(e.argv))
+ .filter((s): s is string => s !== null);
+
+ let selfReport: {howDiscovered?: string; cliCommandsRun?: string[]} | null =
+ null;
+ let docsRead: string[] = [];
+ const metaPath = path.join(task.projectDir, `${task.basePromptId}.json`);
+ if (fs.existsSync(metaPath)) {
+ try {
+ const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
+ selfReport = meta.discovery ?? null;
+ docsRead = Array.isArray(meta.docsRead) ? meta.docsRead : [];
+ } catch {
+ /* malformed metadata */
+ }
+ }
+
+ const reportedCmds = selfReport?.cliCommandsRun ?? [];
+ const usedCoreDocsMjs =
+ reportedCmds.some(c => c.includes('docs.mjs')) ||
+ docsRead.some(d => String(d).toLowerCase().includes('readme'));
+
+ return {
+ taskId: task.taskId,
+ category: task.category,
+ invokedAstryx: log.length > 0,
+ ranInit: subs.includes('init'),
+ ranDocRetrieval: subs.some(s => DOC_RETRIEVAL_CMDS.has(s)),
+ usedCoreDocsMjs,
+ howDiscovered: selfReport?.howDiscovered ?? null,
+ commands: log.map(e => e.argv.join(' ')),
+ completed: fs.existsSync(
+ path.join(task.projectDir, `${task.basePromptId}.tsx`),
+ ),
+ };
+}
+
+function rate(runs: RunResult[], pick: (r: RunResult) => boolean) {
+ const s = runs.filter(pick).length;
+ return {count: s, n: runs.length, ...wilson(s, runs.length)};
+}
+
+const fmt = (r: {
+ p: number;
+ lo: number;
+ hi: number;
+ count: number;
+ n: number;
+}) =>
+ `${(r.p * 100).toFixed(0)}% [${(r.lo * 100).toFixed(0)}-${(r.hi * 100).toFixed(0)}] (${r.count}/${r.n})`;
+
+function loadConditionTasks(iso: boolean, id: string): Map<string, TaskDesc[]> {
+ const configPath = path.join(
+ RESULTS_DIR,
+ iso ? `discovery-iso-config-${id}.json` : `discovery-config-${id}.json`,
+ );
+ if (!fs.existsSync(configPath)) {
+ console.error(`No config at ${configPath}.`);
+ process.exit(1);
+ }
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
+ const map = new Map<string, TaskDesc[]>();
+
+ if (iso) {
+ for (const t of config.tasks as Array<{
+ condition: string;
+ taskId: string;
+ basePromptId: string;
+ dir: string;
+ }>) {
+ const arr = map.get(t.condition) ?? [];
+ arr.push({
+ taskId: t.taskId,
+ basePromptId: t.basePromptId,
+ category: '',
+ projectDir: t.dir,
+ invocationLog: path.join(t.dir, '.astryx-invocations.log'),
+ });
+ map.set(t.condition, arr);
+ }
+ } else {
+ for (const [conditionId, iterationId] of Object.entries(
+ config.conditions as Record<string, string>,
+ )) {
+ const tasksDir = path.join(RESULTS_DIR, iterationId, 'tasks');
+ if (!fs.existsSync(tasksDir)) {
+ continue;
+ }
+ const arr = fs
+ .readdirSync(tasksDir)
+ .filter(f => f.endsWith('.json'))
+ .map(f => {
+ const t = JSON.parse(
+ fs.readFileSync(path.join(tasksDir, f), 'utf-8'),
+ );
+ return {
+ taskId: t.promptId,
+ basePromptId: t.basePromptId,
+ category: t.category ?? '',
+ projectDir: t.projectDir,
+ invocationLog: t.invocationLog,
+ };
+ });
+ map.set(conditionId, arr);
+ }
+ }
+ return map;
+}
+
+function main() {
+ const argv = process.argv.slice(2);
+ const isoIdx = argv.indexOf('--iso');
+ const iso = isoIdx !== -1;
+ const id = iso ? argv[isoIdx + 1] : argv[argv.indexOf('--experiment') + 1];
+ if (!id) {
+ console.error(
+ 'Usage: discovery-aggregate.ts (--experiment <id> | --iso <id>)',
+ );
+ process.exit(1);
+ }
+
+ const conditionTasks = loadConditionTasks(iso, id);
+ const summary: Record<string, unknown> = {
+ experimentId: id,
+ isolated: iso,
+ generatedAt: new Date().toISOString(),
+ conditions: {},
+ };
+
+ console.log(
+ `\n🔎 CLI Discovery — ${iso ? 'ISOLATED ' : ''}experiment ${id}\n`,
+ );
+ console.log(`Funnel (ground truth: astryx shim log), Wilson 95% CI:\n`);
+ console.log(
+ `${'condition'.padEnd(15)} ${'invoked astryx'.padEnd(20)} ${'ran init'.padEnd(18)} ${'doc retrieval'.padEnd(20)} ${'core docs.mjs*'.padEnd(18)} completed`,
+ );
+ console.log('─'.repeat(100));
+
+ for (const [conditionId, tasks] of conditionTasks) {
+ const runs = tasks.map(evaluateRun);
+ const invoked = rate(runs, r => r.invokedAstryx);
+ const init = rate(runs, r => r.ranInit);
+ const docs = rate(runs, r => r.ranDocRetrieval);
+ const docsMjs = rate(runs, r => r.usedCoreDocsMjs);
+ const completed = rate(runs, r => r.completed);
+
+ console.log(
+ `${conditionId.padEnd(15)} ${fmt(invoked).padEnd(20)} ${fmt(init).padEnd(18)} ${fmt(docs).padEnd(20)} ${fmt(docsMjs).padEnd(18)} ${completed.count}/${completed.n}`,
+ );
+
+ const howDist: Record<string, number> = {};
+ for (const r of runs) {
+ howDist[r.howDiscovered ?? 'none'] =
+ (howDist[r.howDiscovered ?? 'none'] ?? 0) + 1;
+ }
+
+ (summary.conditions as Record<string, unknown>)[conditionId] = {
+ n: runs.length,
+ invokedAstryx: invoked,
+ ranInit: init,
+ docRetrieval: docs,
+ usedCoreDocsMjs: docsMjs,
+ completed,
+ howDiscovered: howDist,
+ runs,
+ };
+ }
+
+ console.log(
+ `\n* core docs.mjs = self-reported use of @astryxdesign/core's built-in docs (README channel); the astryx shim can't observe it.`,
+ );
+ const outPath = path.join(RESULTS_DIR, `discovery-summary-${id}.json`);
+ fs.writeFileSync(outPath, JSON.stringify(summary, null, 2));
+ console.log(`📄 Summary: ${outPath}`);
+ console.log(
+ `\nBar: a channel "works consistently" when invoked-astryx lower bound clears the control's upper bound (PLAN.md §8).\n`,
+ );
+}
+
+main();
diff --git a/internal/vibe-tests/cli-discovery-test/prompts.json b/internal/vibe-tests/cli-discovery-test/prompts.json
new file mode 100644
index 0000000000..4e245b341d
--- /dev/null
+++ b/internal/vibe-tests/cli-discovery-test/prompts.json
@@ -0,0 +1,21 @@
+{
+ "name": "cli-discovery-prompts",
+ "description": "Curated stratified subset of test-sets/default.json for the discovery experiment. Identical prompts are used across every condition (Checker Protocol §2). expectedComponents is evaluation-only and is NEVER shown to the agent (§3). Prompts are picked to span complexity so we don't over/under-state discovery: hard tasks make guessing fail, which is when discovery matters most.",
+ "source": "../test-sets/default.json",
+ "selectionStrategy": "stratified by complexity + category; reference default.json by id to avoid drift and answer-leak. Adjust ids after reviewing default.json; K>=5 reps per prompt per condition.",
+ "promptIds": [
+ {"id": "fwc-1", "category": "feature-with-constraint", "complexity": "simple"},
+ {"id": "sd-1", "category": "state-driven", "complexity": "simple"},
+ {"id": "ty-1", "category": "typography", "complexity": "simple"},
+ {"id": "wd-2", "category": "workflow-description", "complexity": "moderate"},
+ {"id": "cwm-1", "category": "clone-with-modification", "complexity": "moderate"},
+ {"id": "ps-1", "category": "page-setup", "complexity": "moderate"},
+ {"id": "dd-1", "category": "data-display", "complexity": "complex"},
+ {"id": "wd-1", "category": "workflow-description", "complexity": "complex"}
+ ],
+ "notes": [
+ "IDs verified against ../test-sets/default.json. Stratified 3 simple / 3 moderate / 2 complex across distinct categories.",
+ "Do NOT copy prompt text or expectedComponents here — reference by id so the single source of truth stays default.json.",
+ "page-setup (ps-1) and data-display (dd-1) are the highest-signal for discovery: an agent that guesses layout/theming APIs will hallucinate, while one that checks the CLI won't."
+ ]
+}
diff --git a/internal/vibe-tests/cli-discovery-test/run-isolated.mjs b/internal/vibe-tests/cli-discovery-test/run-isolated.mjs
new file mode 100644
index 0000000000..5f8d5d278f
--- /dev/null
+++ b/internal/vibe-tests/cli-discovery-test/run-isolated.mjs
@@ -0,0 +1,303 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file run-isolated.mjs
+ * @input CLI flags: --conditions, --prompts/--sample, --reps, --model, --run
+ * @output /tmp sandboxes + results/<iter>/{manifest,tasks} + discovery-config-<expId>.json
+ * @position internal/vibe-tests/cli-discovery-test — the ISOLATED runner (Phase 1.5)
+ *
+ * Fixes the contamination found in pilot 1 (PLAN.md §14): the in-repo Task
+ * sub-agents inherited this repo's always-applied CLAUDE.md (which teaches the
+ * CLI) and reached the repo-root CLI + source. Here each task runs in a /tmp
+ * sandbox with packages COPIED (no symlink back into the repo) and — when
+ * --run — is driven by a headless `cursor-agent` whose cwd is the sandbox, so
+ * NONE of this repo's rules apply and the only reachable `astryx` is the shim.
+ *
+ * Each condition is the bare base project plus a single channel patch, so only
+ * the discovery channel under test varies.
+ *
+ * Usage:
+ * node run-isolated.mjs # set up c0 vs c5 sandboxes (no agents)
+ * node run-isolated.mjs --run # ...and drive cursor-agent headless
+ * node run-isolated.mjs --conditions c0-bare,c1-readme,c5-agents-md --reps 3 --run
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import * as crypto from 'node:crypto';
+import {execFileSync, spawn} from 'node:child_process';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const EXP_DIR = __dirname;
+const VIBE_DIR = path.resolve(EXP_DIR, '..');
+const REPO_ROOT = path.resolve(VIBE_DIR, '../..');
+const RESULTS_DIR = path.join(VIBE_DIR, 'results');
+const REAL_CLI_BIN = path.join(REPO_ROOT, 'packages', 'cli', 'bin', 'astryx.mjs');
+const TMP_ROOT = path.join(os.tmpdir(), 'astryx-disco');
+
+const generateId = () => crypto.randomBytes(4).toString('hex');
+const timestamp = () => new Date().toISOString();
+const ensureDir = d => fs.mkdirSync(d, {recursive: true});
+
+// ── Shared package copies (OUTSIDE the repo, so exploring can't reach source) ──
+
+/** Copy core + theme into /tmp once per invocation; return the shared dir. */
+function ensureSharedPkgs(expId) {
+ const dir = path.join(TMP_ROOT, expId, '_pkgs');
+ const core = path.join(dir, '@astryxdesign', 'core');
+ if (!fs.existsSync(core)) {
+ ensureDir(path.dirname(core));
+ fs.cpSync(path.join(REPO_ROOT, 'packages', 'core'), core, {recursive: true, dereference: true});
+ fs.cpSync(
+ path.join(REPO_ROOT, 'packages', 'themes', 'neutral'),
+ path.join(dir, '@astryxdesign', 'theme-neutral'),
+ {recursive: true, dereference: true},
+ );
+ }
+ return dir;
+}
+
+/** Executable `astryx` shim: logs argv to the sandbox, then execs the real CLI. */
+function installLoggingShim(sandboxDir, {nudge = false} = {}) {
+ const binDir = path.join(sandboxDir, 'node_modules', '.bin');
+ ensureDir(binDir);
+ const logPath = path.join(sandboxDir, '.astryx-invocations.log');
+ const nudgeBlock = nudge
+ ? `try { if (!existsSync(LOG)) process.stderr.write('\\n▶ Astryx: run \`npx astryx init\` to set up your project and AI agent docs.\\n\\n'); } catch {}`
+ : '';
+ const shim = `#!/usr/bin/env node
+import {appendFileSync, existsSync} from 'node:fs';
+import {spawnSync} from 'node:child_process';
+const LOG = ${JSON.stringify(logPath)};
+const REAL = ${JSON.stringify(REAL_CLI_BIN)};
+const argv = process.argv.slice(2);
+${nudgeBlock}
+try { appendFileSync(LOG, JSON.stringify({ts: new Date().toISOString(), argv}) + '\\n'); } catch {}
+const r = spawnSync(process.execPath, [REAL, ...argv], {stdio: 'inherit'});
+process.exit(r.status ?? 0);
+`;
+ const shimPath = path.join(binDir, 'astryx');
+ fs.writeFileSync(shimPath, shim);
+ fs.chmodSync(shimPath, 0o755);
+}
+
+/** Build the realistic "just installed core" sandbox in /tmp (no repo paths). */
+function createSandbox(sandboxDir, sharedPkgs, {nudge = false} = {}) {
+ ensureDir(sandboxDir);
+ fs.writeFileSync(
+ path.join(sandboxDir, 'package.json'),
+ JSON.stringify(
+ {
+ name: 'my-app',
+ private: true,
+ dependencies: {'@astryxdesign/core': '*', '@astryxdesign/theme-neutral': '*', react: '^19', 'react-dom': '^19'},
+ },
+ null,
+ 2,
+ ),
+ );
+ const nm = path.join(sandboxDir, 'node_modules', '@astryxdesign');
+ ensureDir(nm);
+ // Symlink to the /tmp copies — NOT the repo. Walking up from these lands in
+ // /tmp, so the agent can't reach the design-system source or repo CLAUDE.md.
+ fs.symlinkSync(path.join(sharedPkgs, '@astryxdesign', 'core'), path.join(nm, 'core'), 'dir');
+ fs.symlinkSync(path.join(sharedPkgs, '@astryxdesign', 'theme-neutral'), path.join(nm, 'theme-neutral'), 'dir');
+ installLoggingShim(sandboxDir, {nudge});
+}
+
+// ── Channel patches (the independent variable) ────────────
+
+const PATCHES = {
+ 'c0-bare': () => {},
+ 'c1-readme': sandboxDir => {
+ fs.writeFileSync(
+ path.join(sandboxDir, 'README.md'),
+ `# my-app\n\n> **Using an AI agent?** Run \`npx astryx init\` first — it installs the component index your agent needs.\n\nThis app uses the Astryx design system (\`@astryxdesign/core\`).\n`,
+ );
+ },
+ 'c4-nudge': () => {
+ // Handled at sandbox creation via the shim's nudge flag (see buildCondition).
+ },
+ 'c5-agents-md': sandboxDir => {
+ // Post-init ceiling: run the real CLI directly (not the shim) so setup
+ // doesn't pollute the log.
+ execFileSync(
+ process.execPath,
+ [REAL_CLI_BIN, 'init', '--features', 'agents', '--agent-docs-path', 'AGENTS.md'],
+ {cwd: sandboxDir, stdio: 'pipe'},
+ );
+ },
+};
+
+// ── Prompts (identical across conditions; expectedComponents never shown) ─────
+
+function selectPrompts({sample, promptIds}) {
+ const testSet = JSON.parse(fs.readFileSync(path.join(VIBE_DIR, 'test-sets', 'default.json'), 'utf-8'));
+ const all = Array.isArray(testSet) ? testSet : testSet.prompts;
+ const byId = new Map(all.map(p => [p.id, p]));
+ if (promptIds && promptIds.length) return promptIds.map(id => byId.get(id));
+ if (sample) return all.slice(0, sample);
+ const curated = JSON.parse(fs.readFileSync(path.join(EXP_DIR, 'prompts.json'), 'utf-8'));
+ return curated.promptIds.map(({id}) => byId.get(id));
+}
+
+function taskPrompt(prompt, sandboxDir) {
+ return `You are generating React/TSX code using the Astryx design system.
+Your project is at ${sandboxDir}. Treat it as your working directory: cd into it first, then explore it to find available components.
+
+## Task
+
+${prompt.prompt}
+
+## Output
+
+Write the TSX code to: ${path.join(sandboxDir, `${prompt.id}.tsx`)}
+Write metadata to: ${path.join(sandboxDir, `${prompt.id}.json`)}
+
+Metadata JSON shape:
+{
+ "completedAt": "<ISO timestamp>",
+ "docsRead": [<component/doc names you looked up>],
+ "discovery": {
+ "sawCliReference": <true|false>,
+ "howDiscovered": "readme" | "types" | "nudge" | "guessed" | "none",
+ "ranInit": <true|false>,
+ "cliCommandsRun": [<exact commands>]
+ }
+}
+
+Write ONLY valid TSX to the .tsx file. No markdown fences, no explanation.`;
+}
+
+// ── Build one condition = one iteration dir + N sandboxes ────────────────────
+
+function buildCondition(conditionId, prompts, reps, sharedPkgs, expId) {
+ const patch = PATCHES[conditionId];
+ if (!patch) throw new Error(`Condition "${conditionId}" not wired. Add it to PATCHES.`);
+ const nudge = conditionId === 'c4-nudge';
+
+ const iterationId = generateId();
+ const iterDir = path.join(RESULTS_DIR, iterationId);
+ ensureDir(path.join(iterDir, 'tasks'));
+ ensureDir(path.join(iterDir, 'results'));
+
+ const tasks = [];
+ for (const prompt of prompts) {
+ for (let k = 1; k <= reps; k++) {
+ const taskId = reps > 1 ? `${prompt.id}__r${k}` : prompt.id;
+ const sandboxDir = path.join(TMP_ROOT, expId, conditionId, taskId);
+ createSandbox(sandboxDir, sharedPkgs, {nudge});
+ patch(sandboxDir);
+
+ const task = {
+ promptId: taskId,
+ basePromptId: prompt.id,
+ category: prompt.category,
+ condition: conditionId,
+ prompt: prompt.prompt,
+ expectedComponents: prompt.expectedComponents,
+ projectDir: sandboxDir,
+ invocationLog: path.join(sandboxDir, '.astryx-invocations.log'),
+ taskPrompt: taskPrompt(prompt, sandboxDir),
+ createdAt: timestamp(),
+ };
+ fs.writeFileSync(path.join(iterDir, 'tasks', `${taskId}.json`), JSON.stringify(task, null, 2));
+ tasks.push(task);
+ }
+ }
+
+ fs.writeFileSync(
+ path.join(iterDir, 'manifest.json'),
+ JSON.stringify({iterationId, experiment: 'cli-discovery-isolated', condition: conditionId, createdAt: timestamp(), taskIds: tasks.map(t => t.promptId)}, null, 2),
+ );
+ return {conditionId, iterationId, iterDir, tasks};
+}
+
+// ── Headless agent runner (cursor-agent, cwd = sandbox, no repo rules) ────────
+
+function runAgent(task, model) {
+ return new Promise(resolve => {
+ const args = ['-p', '--force', '--trust', '--sandbox', 'disabled', '--output-format', 'text'];
+ if (model) args.push('--model', model);
+ args.push(task.taskPrompt);
+ const out = fs.createWriteStream(path.join(task.projectDir, 'agent-transcript.txt'));
+ const child = spawn('cursor-agent', args, {cwd: task.projectDir});
+ child.stdout.pipe(out);
+ child.stderr.pipe(out);
+ child.on('close', code => resolve({taskId: task.promptId, condition: task.condition, code}));
+ child.on('error', err => resolve({taskId: task.promptId, condition: task.condition, code: -1, error: String(err)}));
+ });
+}
+
+async function runAll(built, model, concurrency = 4) {
+ const queue = built.flatMap(b => b.tasks);
+ const results = [];
+ let i = 0;
+ async function worker() {
+ while (i < queue.length) {
+ const task = queue[i++];
+ process.stdout.write(` ▶ ${task.condition}/${task.promptId} …\n`);
+ const r = await runAgent(task, model);
+ process.stdout.write(` ✓ ${task.condition}/${task.promptId} (exit ${r.code})\n`);
+ results.push(r);
+ }
+ }
+ await Promise.all(Array.from({length: Math.min(concurrency, queue.length)}, worker));
+ return results;
+}
+
+// ── Main ─────────────────────────────────────────────────────────────────────
+
+function arg(flag, def) {
+ const i = process.argv.indexOf(flag);
+ return i !== -1 ? process.argv[i + 1] : def;
+}
+
+async function main() {
+ const conditions = (arg('--conditions', 'c0-bare,c5-agents-md')).split(',').map(s => s.trim());
+ const reps = parseInt(arg('--reps', '1'), 10);
+ const sample = arg('--sample') ? parseInt(arg('--sample'), 10) : undefined;
+ const promptIds = arg('--prompts') ? arg('--prompts').split(',').map(s => s.trim()) : undefined;
+ const model = arg('--model', 'auto');
+ const doRun = process.argv.includes('--run');
+
+ ensureDir(RESULTS_DIR);
+ const expId = generateId();
+ const sharedPkgs = ensureSharedPkgs(expId);
+ const prompts = selectPrompts({sample, promptIds});
+
+ console.log(`\n🧪 CLI Discovery — ISOLATED (experiment ${expId})`);
+ console.log(` Sandboxes under: ${path.join(TMP_ROOT, expId)}`);
+ console.log(` Conditions: ${conditions.join(', ')}`);
+ console.log(` Prompts: ${prompts.map(p => p.id).join(', ')} × ${reps} rep(s)`);
+ console.log(` Model: ${model} · run agents: ${doRun}\n`);
+
+ const built = conditions.map(c => buildCondition(c, prompts, reps, sharedPkgs, expId));
+
+ fs.writeFileSync(
+ path.join(RESULTS_DIR, `discovery-config-${expId}.json`),
+ JSON.stringify(
+ {experimentId: expId, isolated: true, createdAt: timestamp(), model, reps, promptIds: prompts.map(p => p.id), conditions: Object.fromEntries(built.map(b => [b.conditionId, b.iterationId]))},
+ null,
+ 2,
+ ),
+ );
+
+ for (const b of built) console.log(` ${b.conditionId.padEnd(14)} ${b.iterationId} (${b.tasks.length} sandboxes)`);
+
+ if (!doRun) {
+ console.log(`\nSandboxes ready (no agents run). Inspect isolation, then re-run with --run.`);
+ console.log(`Score later: npx tsx cli-discovery-test/discovery-aggregate.ts --experiment ${expId}\n`);
+ return;
+ }
+
+ console.log(`\n🤖 Driving cursor-agent headless (cwd = each sandbox)…\n`);
+ await runAll(built, model);
+ console.log(`\n✅ All agents done. Score the funnel:`);
+ console.log(` npx tsx cli-discovery-test/discovery-aggregate.ts --experiment ${expId}\n`);
+}
+
+main();
diff --git a/internal/vibe-tests/cli-discovery-test/setup-discovery.mjs b/internal/vibe-tests/cli-discovery-test/setup-discovery.mjs
new file mode 100644
index 0000000000..5150a2d9a4
--- /dev/null
+++ b/internal/vibe-tests/cli-discovery-test/setup-discovery.mjs
@@ -0,0 +1,336 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file setup-discovery.mjs
+ * @input CLI flags: --conditions, --sample, --reps, --prompts
+ * @output One results/<iterationId>/ dir per condition + results/discovery-config.json
+ * @position internal/vibe-tests/cli-discovery-test — cold-start CLI-discovery experiment
+ *
+ * Builds isolated, realistic "just installed @astryxdesign/core" projects and
+ * measures whether an agent discovers + uses the CLI with NO one having run
+ * `astryx init`. Each CONDITION = the bare base project + zero or more channel
+ * patches (see conditions.json). Only the channel varies (Checker Protocol §2).
+ *
+ * Ground truth: every project gets an `astryx` bin SHIM at node_modules/.bin
+ * that logs argv to <project>/.astryx-invocations.log before exec-ing the real
+ * CLI. Discovery is defined by that log, not by self-report (PLAN.md §6.2).
+ *
+ * This is the PILOT: only c0-bare (floor) and c5-agents-md (ceiling) are wired.
+ * Adding c1/c2/c4 later is a new entry in the PATCHES map.
+ *
+ * Usage:
+ * node setup-discovery.mjs # c0 vs c5, curated prompts
+ * node setup-discovery.mjs --sample 6 # stratified sample of 6
+ * node setup-discovery.mjs --conditions c0-bare,c5-agents-md --reps 5
+ * node setup-discovery.mjs --prompts fwc-1,ps-1
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as crypto from 'node:crypto';
+import {execFileSync} from 'node:child_process';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const EXP_DIR = __dirname; // internal/vibe-tests/cli-discovery-test
+const VIBE_DIR = path.resolve(EXP_DIR, '..'); // internal/vibe-tests
+const REPO_ROOT = path.resolve(VIBE_DIR, '../..');
+const RESULTS_DIR = path.join(VIBE_DIR, 'results');
+const REAL_CLI_BIN = path.join(REPO_ROOT, 'packages', 'cli', 'bin', 'astryx.mjs');
+
+// ── Helpers ──────────────────────────────────────────────────────────
+
+const generateId = () => crypto.randomBytes(4).toString('hex');
+const timestamp = () => new Date().toISOString();
+const ensureDir = dir => fs.mkdirSync(dir, {recursive: true});
+
+function symlink(target, linkPath, type) {
+ ensureDir(path.dirname(linkPath));
+ if (fs.existsSync(linkPath)) return;
+ fs.symlinkSync(target, linkPath, type);
+}
+
+/** Curated prompt IDs from prompts.json, or a stratified sample of default.json. */
+function selectPrompts({sample, promptIds}) {
+ const testSet = JSON.parse(
+ fs.readFileSync(path.join(VIBE_DIR, 'test-sets', 'default.json'), 'utf-8'),
+ );
+ const all = Array.isArray(testSet) ? testSet : testSet.prompts;
+ const byId = new Map(all.map(p => [p.id, p]));
+
+ if (promptIds && promptIds.length > 0) {
+ return promptIds.map(id => {
+ const p = byId.get(id);
+ if (!p) throw new Error(`Prompt id not found in default.json: ${id}`);
+ return p;
+ });
+ }
+
+ if (sample) return stratified(all, sample);
+
+ // Default: the curated subset from prompts.json
+ const curated = JSON.parse(
+ fs.readFileSync(path.join(EXP_DIR, 'prompts.json'), 'utf-8'),
+ );
+ return curated.promptIds.map(({id}) => {
+ const p = byId.get(id);
+ if (!p) throw new Error(`Curated prompt id not in default.json: ${id}`);
+ return p;
+ });
+}
+
+function stratified(prompts, n) {
+ const byCat = new Map();
+ for (const p of prompts) {
+ const arr = byCat.get(p.category) ?? [];
+ arr.push(p);
+ byCat.set(p.category, arr);
+ }
+ const cats = [...byCat.keys()];
+ const out = [];
+ for (const c of cats) {
+ const arr = byCat.get(c);
+ out.push(arr[Math.floor(Math.random() * arr.length)]);
+ if (out.length >= n) return out.slice(0, n);
+ }
+ let i = 0;
+ while (out.length < n && i < cats.length * prompts.length) {
+ const arr = byCat.get(cats[i % cats.length]);
+ const avail = arr.filter(p => !out.includes(p));
+ if (avail.length) out.push(avail[Math.floor(Math.random() * avail.length)]);
+ i++;
+ }
+ return out.slice(0, n);
+}
+
+// ── Base project + ground-truth shim ─────────────────────────────────
+
+/**
+ * Create the realistic "npm install @astryxdesign/core" base: package.json with
+ * core + theme (NOT the CLI — that's the whole point), symlinked packages, and
+ * the logging `astryx` shim so `npx astryx` resolves AND is recorded.
+ */
+function createBaseProject(projectDir) {
+ ensureDir(projectDir);
+
+ // A freshly-installed consumer: core + theme, no @astryxdesign/cli listed.
+ const pkg = {
+ name: 'my-app',
+ private: true,
+ dependencies: {
+ '@astryxdesign/core': '*',
+ '@astryxdesign/theme-neutral': '*',
+ '@stylexjs/stylex': '^0.10',
+ react: '^19',
+ 'react-dom': '^19',
+ },
+ };
+ fs.writeFileSync(
+ path.join(projectDir, 'package.json'),
+ JSON.stringify(pkg, null, 2),
+ );
+
+ const nm = path.join(projectDir, 'node_modules');
+ symlink(path.join(REPO_ROOT, 'packages', 'core'), path.join(nm, '@astryxdesign', 'core'), 'dir');
+ symlink(path.join(REPO_ROOT, 'packages', 'themes', 'neutral'), path.join(nm, '@astryxdesign', 'theme-neutral'), 'dir');
+
+ installLoggingShim(projectDir);
+}
+
+/**
+ * Write an executable `astryx` shim into node_modules/.bin that appends each
+ * invocation to <project>/.astryx-invocations.log, then execs the real CLI.
+ * Absolute paths are baked in so it works from any cwd.
+ */
+function installLoggingShim(projectDir) {
+ const binDir = path.join(projectDir, 'node_modules', '.bin');
+ ensureDir(binDir);
+ const logPath = path.join(projectDir, '.astryx-invocations.log');
+ const shim = `#!/usr/bin/env node
+// GENERATED shim — logs invocations for the CLI-discovery experiment, then execs the real CLI.
+import {appendFileSync} from 'node:fs';
+import {spawnSync} from 'node:child_process';
+const LOG = ${JSON.stringify(logPath)};
+const REAL = ${JSON.stringify(REAL_CLI_BIN)};
+const argv = process.argv.slice(2);
+try { appendFileSync(LOG, JSON.stringify({ts: new Date().toISOString(), argv}) + '\\n'); } catch {}
+const r = spawnSync(process.execPath, [REAL, ...argv], {stdio: 'inherit'});
+process.exit(r.status ?? 0);
+`;
+ const shimPath = path.join(binDir, 'astryx');
+ fs.writeFileSync(shimPath, shim);
+ fs.chmodSync(shimPath, 0o755);
+}
+
+// ── Channel patches (the independent variable) ───────────────────────
+//
+// Each condition applies zero or more patches to the base. PILOT wires the
+// floor (c0) and ceiling (c5). c1/c2/c4 are declared but intentionally guarded
+// so they can't silently run half-implemented.
+
+const PATCHES = {
+ 'c0-bare': () => {
+ // Nothing. Bare install. This is the control/floor.
+ },
+ 'c5-agents-md': projectDir => {
+ // The post-`init` ceiling: run the REAL cli bin directly (NOT via the shim,
+ // so setup doesn't pollute the invocation log) to write AGENTS.md.
+ execFileSync(
+ process.execPath,
+ [REAL_CLI_BIN, 'init', '--features', 'agents', '--agent-docs-path', 'AGENTS.md'],
+ {cwd: projectDir, stdio: 'pipe'},
+ );
+ },
+};
+
+const NOT_IN_PILOT = new Set(['c1-readme', 'c2-types', 'c3-postinstall', 'c4-firstrun', 'c6-readme+types', 'c7-all-passive']);
+
+// ── Task prompt (IDENTICAL across conditions — §2/§3) ────────────────
+
+function taskPrompt(prompt, projectDir) {
+ const tsx = path.join(projectDir, `${prompt.id}.tsx`);
+ const meta = path.join(projectDir, `${prompt.id}.json`);
+ return `You are generating React/TSX code using the Astryx design system.
+Your project is at ${projectDir}. Treat it as your working directory: cd into it first, then explore it to find available components.
+
+## Task
+
+${prompt.prompt}
+
+## Output
+
+Write the TSX code to: ${tsx}
+Write metadata to: ${meta}
+
+Metadata JSON shape:
+{
+ "completedAt": "<ISO timestamp>",
+ "docsRead": [<component/doc names you looked up>],
+ "discovery": {
+ "sawCliReference": <true|false>,
+ "howDiscovered": "readme" | "types" | "nudge" | "guessed" | "none",
+ "ranInit": <true|false>,
+ "cliCommandsRun": [<exact commands, e.g. "astryx component Button">]
+ }
+}
+
+Write ONLY valid TSX to the .tsx file. No markdown fences, no explanation.`;
+}
+
+// ── Build one condition = one iteration dir ──────────────────────────
+
+function buildCondition(conditionId, prompts, reps) {
+ const patch = PATCHES[conditionId];
+ if (!patch) {
+ if (NOT_IN_PILOT.has(conditionId)) {
+ throw new Error(`Condition "${conditionId}" is declared in conditions.json but not wired in the pilot (only c0-bare, c5-agents-md). Add it to PATCHES to enable.`);
+ }
+ throw new Error(`Unknown condition: ${conditionId}`);
+ }
+
+ const iterationId = generateId();
+ const iterDir = path.join(RESULTS_DIR, iterationId);
+ ensureDir(path.join(iterDir, 'tasks'));
+ ensureDir(path.join(iterDir, 'results'));
+ ensureDir(path.join(iterDir, 'projects'));
+
+ const taskIds = [];
+ for (const prompt of prompts) {
+ for (let k = 1; k <= reps; k++) {
+ const taskId = reps > 1 ? `${prompt.id}__r${k}` : prompt.id;
+ taskIds.push(taskId);
+ const projectDir = path.join(iterDir, 'projects', taskId);
+ createBaseProject(projectDir);
+ patch(projectDir);
+
+ const task = {
+ promptId: taskId,
+ basePromptId: prompt.id,
+ category: prompt.category,
+ condition: conditionId,
+ prompt: prompt.prompt,
+ expectedComponents: prompt.expectedComponents, // eval-only; NOT in taskPrompt
+ projectDir,
+ invocationLog: path.join(projectDir, '.astryx-invocations.log'),
+ taskPrompt: taskPrompt(prompt, projectDir),
+ createdAt: timestamp(),
+ };
+ fs.writeFileSync(
+ path.join(iterDir, 'tasks', `${taskId}.json`),
+ JSON.stringify(task, null, 2),
+ );
+ }
+ }
+
+ const manifest = {
+ iterationId,
+ experiment: 'cli-discovery',
+ condition: conditionId,
+ createdAt: timestamp(),
+ config: {persona: 'naive', reps},
+ prompts: prompts.map(p => ({id: p.id, category: p.category, prompt: p.prompt, expectedComponents: p.expectedComponents})),
+ taskIds,
+ };
+ fs.writeFileSync(path.join(iterDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
+
+ return {conditionId, iterationId, iterDir, taskIds};
+}
+
+// ── Main ─────────────────────────────────────────────────────────────
+
+function parseArgs(argv) {
+ const get = flag => {
+ const i = argv.indexOf(flag);
+ return i !== -1 ? argv[i + 1] : undefined;
+ };
+ return {
+ conditions: (get('--conditions') ?? 'c0-bare,c5-agents-md').split(',').map(s => s.trim()),
+ sample: get('--sample') ? parseInt(get('--sample'), 10) : undefined,
+ reps: get('--reps') ? parseInt(get('--reps'), 10) : 1,
+ promptIds: get('--prompts') ? get('--prompts').split(',').map(s => s.trim()) : undefined,
+ };
+}
+
+function main() {
+ const {conditions, sample, reps, promptIds} = parseArgs(process.argv.slice(2));
+ ensureDir(RESULTS_DIR);
+
+ const prompts = selectPrompts({sample, promptIds});
+ const expId = generateId();
+
+ console.log(`\n🔎 CLI Discovery Vibe Test (experiment ${expId})`);
+ console.log(` Conditions: ${conditions.join(', ')}`);
+ console.log(` Prompts: ${prompts.map(p => p.id).join(', ')} × ${reps} rep(s)`);
+ console.log(` Runs per condition: ${prompts.length * reps}\n`);
+
+ const built = [];
+ for (const c of conditions) built.push(buildCondition(c, prompts, reps));
+
+ const config = {
+ experimentId: expId,
+ createdAt: timestamp(),
+ reps,
+ promptIds: prompts.map(p => p.id),
+ conditions: Object.fromEntries(built.map(b => [b.conditionId, b.iterationId])),
+ iterDirs: Object.fromEntries(built.map(b => [b.conditionId, b.iterDir])),
+ };
+ const configPath = path.join(RESULTS_DIR, `discovery-config-${expId}.json`);
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
+
+ console.log(`✅ Conditions ready:`);
+ for (const b of built) console.log(` ${b.conditionId.padEnd(14)} ${b.iterationId} (${b.taskIds.length} tasks)`);
+ console.log(`\n📄 Config: ${configPath}\n`);
+
+ console.log(`## Spawn a FRESH, context-free sub-agent per task file (Checker Protocol §5):\n`);
+ for (const b of built) {
+ console.log(`# ${b.conditionId}`);
+ for (const id of b.taskIds) console.log(` ${path.join(b.iterDir, 'tasks', `${id}.json`)}`);
+ console.log();
+ }
+
+ console.log(`## After all agents complete — score the funnel:\n`);
+ console.log(` npx tsx ${path.join('cli-discovery-test', 'discovery-aggregate.ts')} --experiment ${expId}\n`);
+}
+
+main();
diff --git a/packages/core/README.md b/packages/core/README.md
index 78c8782536..b55308e5b1 100644
--- a/packages/core/README.md
+++ b/packages/core/README.md
@@ -2,6 +2,8 @@
Core UI components, theme system, and utilities for the Astryx design system. For project setup, see [Quick Start](#quick-start) below.
+> **Building with an AI agent?** Run **`npx astryx init`** first. It installs the Astryx CLI's component index into your `AGENTS.md`/`CLAUDE.md` so your agent discovers components, templates, and design tokens instead of guessing. Without it, agents can't see the CLI — see [XDS CLI](#xds-cli).
+
## Component Docs
Look up any component's full API (props, types, best practices, and theming):