@lifeaitools/rdc-skills 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,338 @@
1
+ ---
2
+ name: lifeai-brochure-author
3
+ version: 0.1.0
4
+ description: |
5
+ The mandatory contract for authoring brochure JSX using @lifeai/brochure-kit. Use this skill EVERY TIME any AI engine (Claude, Cursor, Copilot, /design, Cowork, v0) generates JSX intended for the Brochurify pipeline — whether the user says "write a brochure," "make a one-pager," "draft a PDF report," or any equivalent. Also trigger when a file imports from @lifeai/brochure-kit. Failing to read this skill before authoring is a defect.
6
+
7
+ triggers:
8
+ - "write a brochure"
9
+ - "make a one-pager"
10
+ - "draft a PDF report"
11
+ - "design a brochure"
12
+ - "create an investor doc"
13
+ - "generate a fact sheet"
14
+ - "brochurify"
15
+ - "@lifeai/brochure-kit"
16
+ - any JSX file under apps/*/brochures/ or packages/brochure-*/
17
+
18
+ required_validators:
19
+ - command: pnpm bk-lint
20
+ blocking: true
21
+ ---
22
+
23
+ # LIFEAI Brochure Authoring Contract
24
+
25
+ This is the contract every AI engine obeys when generating brochure JSX. The contract is non-negotiable. If you cannot generate output that complies, **stop and ask for clarification rather than emit non-compliant code.**
26
+
27
+ ## The Core Rule
28
+
29
+ Every brochure is a tree composed exclusively of components from `@lifeai/brochure-kit`. Raw HTML elements (`div`, `span`, `section`, etc.) are forbidden in the page tree. There are no exceptions.
30
+
31
+ ```tsx
32
+ // ❌ WRONG
33
+ <div className="flex flex-col gap-4">
34
+ <h1 style={{color: '#2d5a3f'}}>Title</h1>
35
+ <p>Body text...</p>
36
+ </div>
37
+
38
+ // ✅ RIGHT
39
+ <Stack gap="md">
40
+ <Heading level={1} variant="accent">Title</Heading>
41
+ <Prose>Body text...</Prose>
42
+ </Stack>
43
+ ```
44
+
45
+ If you find yourself reaching for a `<div>`, the answer is one of: `<Stack>`, `<Cluster>`, `<Section>`, `<Columns>`, or `<Brochure>`. There is always a kit primitive for what you want.
46
+
47
+ ## The Allowed Components
48
+
49
+ Exactly these. No others.
50
+
51
+ ### Layout primitives
52
+ - `<Brochure>` — root wrapper. Required. Carries `theme`, `pageSize`, `mode`.
53
+ - `<Page>` — explicit page boundary. Use sparingly; prefer Sections.
54
+ - `<Section>` — semantic grouping. Carries `level`, `id`, `affinity`.
55
+ - `<Cluster>` — tightly-coupled children (heading + intro + image). Stays together when possible.
56
+ - `<Stack>` — loose vertical flow. The default container.
57
+ - `<Columns>` — multi-column block. Carries `count`, `gap`.
58
+ - `<Spacer>` — explicit air. Declared in named sizes only.
59
+
60
+ ### Content primitives
61
+ - `<Prose>` — body text. Wraps paragraphs. Required for any flowing copy.
62
+ - `<Heading>` — section heading. Carries `level` (1-6), `variant`.
63
+ - `<Quote>` — pull quote. Carries `attribution`, `variant`.
64
+ - `<Stat>` — single numeric callout. Carries `value`, `label`, `variant`.
65
+ - `<StatRow>` — horizontal band of Stats. Carries `count`.
66
+ - `<DataTable>` — table. Carries `headers`, `rows`, `splitPolicy`.
67
+ - `<List>` — typed list. Carries `kind` (bullet, number, check, none).
68
+ - `<Definition>` — term + definition pair.
69
+
70
+ ### Visual primitives
71
+ - `<Figure>` — image with caption. Carries `src`, `alt`, `caption`, `width`, `height`, `crop`, `bleed`.
72
+ - `<Hero>` — page-anchored hero. Carries `src`, `alt`, `placement`.
73
+ - `<Divider>` — explicit separator. Carries `variant`.
74
+
75
+ ### Meta primitives
76
+ - `<Cover>` — first page, page-locked.
77
+ - `<TableOfContents>` — auto-generated from `<Heading>`s.
78
+ - `<Footnote>` — page-anchored footnote. Carries `id`, `marker`.
79
+
80
+ ## The Allowed HTML (inside `<Prose>` only)
81
+
82
+ Inside `<Prose>`, these inline HTML elements are allowed:
83
+ - `<em>`, `<strong>` — emphasis
84
+ - `<a>` — links (with `href`)
85
+ - `<code>` — inline code
86
+ - `<sub>`, `<sup>` — subscript/superscript
87
+ - `<br>` — line break (use sparingly)
88
+
89
+ Anything else inside `<Prose>` is rejected.
90
+
91
+ ## The Forbidden Patterns
92
+
93
+ These are hard-rejected by the validator. Do not emit them under any circumstance.
94
+
95
+ 1. **Raw layout HTML** — `<div>`, `<span>`, `<section>`, `<article>`, `<aside>`, `<header>`, `<footer>`, `<nav>` outside of `<Prose>`.
96
+ 2. **Inline styles** — `style={{...}}` on any element. Use variant props instead.
97
+ 3. **Color literals** — Hex codes, rgb(), hsl() in JSX. Use theme tokens via variants.
98
+ 4. **Viewport units** — `vh`, `vw`, `vmin`, `vmax` anywhere. Pages have fixed dimensions; viewport units break pagination.
99
+ 5. **Flexbox utility classes** — `flex`, `flex-col`, `justify-*`, `items-*` directly in className. Use kit primitives that handle layout.
100
+ 6. **Tailwind sizing literals** — `w-64`, `h-32`, `min-h-screen`. Use kit props.
101
+ 7. **Empty containers** — `<Stack></Stack>` with no children is rejected. Use `<Spacer>` for explicit air.
102
+ 8. **Nested `<Page>`** — Pages cannot contain Pages.
103
+ 9. **`<Figure>` without dimensions** — Every Figure must declare `width` and `height` (in inches or as a kit named size: `xs`, `sm`, `md`, `lg`, `xl`, `full`, `bleed`).
104
+ 10. **External CSS imports** — No `import './foo.css'` in brochure files. Theming is via tokens.
105
+
106
+ ## The Required Props
107
+
108
+ Every brochure must:
109
+
110
+ 1. Have exactly one `<Brochure>` root wrapper
111
+ 2. Declare `theme` on `<Brochure>` (one of: `prt`, `place-fund`, `zoen`, `evergreen`, `editorial-neutral`)
112
+ 3. Declare `pageSize` on `<Brochure>` (one of: `letter`, `a4`, `legal`, `digest`, `tabloid`)
113
+ 4. Declare `mode` on `<Brochure>` (one of: `read-only`, `cosmetic`, `editorial`, `creative`)
114
+
115
+ ## The Token System
116
+
117
+ All styling derives from `@lifeai/brochure-tokens`. You reference tokens via variant props, never via raw values.
118
+
119
+ ```tsx
120
+ // ✅ Variant references resolve to tokens
121
+ <Heading variant="accent">...</Heading> // → color: token.color.accent
122
+ <Stat variant="emphasis">...</Stat> // → typography.scale.emphasis
123
+ <Stack gap="md">...</Stack> // → spacing.scale.md
124
+ <Figure width="lg" height="md">...</Figure> // → kit-named sizes
125
+
126
+ // ❌ Literal references fail
127
+ <Heading style={{color: '#2d5a3f'}}>...</Heading> // hard-rejected
128
+ <Stack style={{gap: '24px'}}>...</Stack> // hard-rejected
129
+ ```
130
+
131
+ Available variant tokens depend on the theme. Common ones: `default`, `muted`, `accent`, `accent2`, `emphasis`, `serif`, `mono`. The theme file (in `packages/brochure-tokens/src/themes/`) is the authoritative list.
132
+
133
+ ## Pagination Affinities
134
+
135
+ Components declare how they want to paginate. You don't manage page breaks manually except via `<Page>`. The engine does it.
136
+
137
+ | Component | Default affinity |
138
+ |---|---|
139
+ | `<Heading level=1|2>` | `preferTopOfPage` + `keepWithNext` |
140
+ | `<Heading level=3-6>` | `keepWithNext` |
141
+ | `<Cluster>` | `preferKeepTogether` |
142
+ | `<Stack>` | `breakable` |
143
+ | `<Quote>` | `preferKeepTogether` |
144
+ | `<Stat>`, `<StatRow>` | `atomic` (never split) |
145
+ | `<DataTable>` | `splitWithRepeatedHeaders` (min 3 rows per fragment) |
146
+ | `<Figure>` | `keepWithCaption` |
147
+ | `<Hero>` | `preferStandalone` page |
148
+ | `<Footnote>` | sticks to anchor page |
149
+
150
+ You can override per-instance with the `affinity` prop on most components: `affinity="breakable"`, `affinity="keepTogether"`, `affinity="hardBreakBefore"`, `affinity="hardBreakAfter"`, `affinity="preferStandalone"`.
151
+
152
+ ## Worked Example 1: Investor One-Pager (Read-Only Mode)
153
+
154
+ ```tsx
155
+ import {
156
+ Brochure, Cover, Section, Cluster, Stack, Heading, Prose,
157
+ Stat, StatRow, Figure, Footnote
158
+ } from '@lifeai/brochure-kit';
159
+
160
+ export const PrtOnePager = () => (
161
+ <Brochure theme="prt" pageSize="letter" mode="read-only">
162
+ <Cover>
163
+ <Heading level={1} variant="accent">Planetary Regenerative Trust</Heading>
164
+ <Heading level={3} variant="muted">Q3 2026 Fund Update</Heading>
165
+ <Figure
166
+ src="prt-cover.jpg"
167
+ alt="Aerial view of Sky Mesa South Ranch"
168
+ width="bleed"
169
+ height="lg"
170
+ affinity="preferStandalone"
171
+ />
172
+ </Cover>
173
+
174
+ <Section level={1} id="overview">
175
+ <Heading level={2}>Fund Overview</Heading>
176
+ <StatRow count={3}>
177
+ <Stat value="$200M" label="Target raise" variant="emphasis" />
178
+ <Stat value="506(c)" label="Reg D structure" />
179
+ <Stat value="3" label="Investment lanes" />
180
+ </StatRow>
181
+ <Cluster>
182
+ <Heading level={3}>Five Capitals Framework</Heading>
183
+ <Prose>
184
+ PRT operates across the Five Capitals: <strong>Natural, Social,
185
+ Financial, Built, and Human</strong>. Capital flows are gated by
186
+ place-readiness rather than calendar deadlines<Footnote id="fn1" />.
187
+ </Prose>
188
+ </Cluster>
189
+ </Section>
190
+
191
+ <Section level={1} id="lanes">
192
+ <Heading level={2}>Investment Lanes</Heading>
193
+ <Prose>
194
+ Three lanes accept capital with distinct return profiles, hold
195
+ periods, and risk parameters.
196
+ </Prose>
197
+ </Section>
198
+
199
+ <Footnote id="fn1" marker="1">
200
+ Readiness gates are defined per-place by Story of Place methodology and
201
+ reviewed by an independent stewardship council.
202
+ </Footnote>
203
+ </Brochure>
204
+ );
205
+ ```
206
+
207
+ Things to notice:
208
+ - No `<div>` anywhere. Every container is a kit primitive.
209
+ - No styles. Every visual decision is a variant prop.
210
+ - The Figure on the cover declares `width="bleed"` (a kit-named size that resolves to full bleed at PDF time)
211
+ - The Footnote is declared inline and the actual footnote content is at the end; the engine pairs them and places the content on whatever page the anchor lands on.
212
+ - `affinity="preferStandalone"` on the cover Figure ensures the cover image doesn't fight with body content on page 1.
213
+
214
+ ## Worked Example 2: Why-Us Document (Cosmetic Mode)
215
+
216
+ ```tsx
217
+ import {
218
+ Brochure, Cover, Section, Stack, Cluster, Heading, Prose, Quote,
219
+ Figure, List, Definition, Divider
220
+ } from '@lifeai/brochure-kit';
221
+
222
+ export const WhyUsSkyMesa = () => (
223
+ <Brochure theme="place-fund" pageSize="letter" mode="cosmetic">
224
+ <Cover>
225
+ <Heading level={1}>Why Us</Heading>
226
+ <Heading level={3} variant="muted">Sky Mesa South Ranch · Aspen, Colorado</Heading>
227
+ </Cover>
228
+
229
+ <Section level={1}>
230
+ <Heading level={2}>The Land Speaks First</Heading>
231
+ <Prose>
232
+ Before any framework or fund structure, we begin with the question:
233
+ what is this place already trying to become? Sky Mesa South Ranch sits
234
+ in the Roaring Fork watershed, on land with five generations of
235
+ ranching memory and the deep ecological imprint of high-altitude
236
+ montane ecosystems.
237
+ </Prose>
238
+ <Figure
239
+ src="sky-mesa-aerial.jpg"
240
+ alt="Sky Mesa from the eastern ridge"
241
+ caption="Sky Mesa South Ranch, photographed in late summer 2025"
242
+ width="lg"
243
+ height="md"
244
+ />
245
+ </Section>
246
+
247
+ <Divider variant="rule" />
248
+
249
+ <Section level={1}>
250
+ <Heading level={2}>Five Capitals at Sky Mesa</Heading>
251
+ <List kind="check">
252
+ <Definition term="Natural">Watershed restoration, riparian recovery, soil regeneration</Definition>
253
+ <Definition term="Social">Multi-generational ranching community, Indigenous consultation</Definition>
254
+ <Definition term="Financial">PRT Lane B with conservation easement layer</Definition>
255
+ <Definition term="Built">Adaptive reuse of existing ranching infrastructure</Definition>
256
+ <Definition term="Human">On-site stewardship apprenticeships starting Year 1</Definition>
257
+ </List>
258
+ </Section>
259
+
260
+ <Section level={1}>
261
+ <Quote attribution="Bill Reed, AIA LEED">
262
+ Regeneration is not a technology applied to a place. It is a
263
+ relationship a place enters into with the people who tend it.
264
+ </Quote>
265
+ </Section>
266
+ </Brochure>
267
+ );
268
+ ```
269
+
270
+ ## Worked Example 3: Fact Sheet (Read-Only Mode, Dense)
271
+
272
+ ```tsx
273
+ import {
274
+ Brochure, Section, Stack, Heading, Prose,
275
+ DataTable, StatRow, Stat
276
+ } from '@lifeai/brochure-kit';
277
+
278
+ export const FundFactSheet = () => (
279
+ <Brochure theme="prt" pageSize="letter" mode="read-only">
280
+ <Section level={1}>
281
+ <Heading level={1} variant="accent">PRT Fund Fact Sheet</Heading>
282
+ <Heading level={3} variant="muted">As of Q3 2026</Heading>
283
+ </Section>
284
+
285
+ <Section level={2}>
286
+ <Heading level={2}>Performance</Heading>
287
+ <StatRow count={4}>
288
+ <Stat value="$185M" label="Committed capital" />
289
+ <Stat value="$92M" label="Deployed" />
290
+ <Stat value="12" label="Active places" />
291
+ <Stat value="8.4%" label="Net IRR (LTM)" variant="emphasis" />
292
+ </StatRow>
293
+ </Section>
294
+
295
+ <Section level={2}>
296
+ <Heading level={2}>Capital by Lane</Heading>
297
+ <DataTable
298
+ headers={["Lane", "Commitment", "Deployed", "Net IRR"]}
299
+ rows={[
300
+ ["A — Production", "$80M", "$48M", "10.2%"],
301
+ ["B — Place Capital", "$70M", "$32M", "7.8%"],
302
+ ["C — Stewardship", "$35M", "$12M", "5.4%"],
303
+ ]}
304
+ splitPolicy="repeat-headers"
305
+ />
306
+ </Section>
307
+ </Brochure>
308
+ );
309
+ ```
310
+
311
+ ## Pre-Flight Checklist (Run before considering output complete)
312
+
313
+ Before declaring any brochure JSX done, verify:
314
+
315
+ - [ ] Only kit components in the page tree (no raw `<div>`, `<span>`, etc.)
316
+ - [ ] No `style={{}}` attributes anywhere
317
+ - [ ] No color, rgb, hsl literals in JSX
318
+ - [ ] No `vh`, `vw` viewport units
319
+ - [ ] Every `<Figure>` has `width` and `height`
320
+ - [ ] Exactly one `<Brochure>` root
321
+ - [ ] `theme`, `pageSize`, `mode` all set on `<Brochure>`
322
+ - [ ] All Quotes inside `<Quote>` (not raw HTML)
323
+ - [ ] All flowing text inside `<Prose>`
324
+ - [ ] No empty containers
325
+ - [ ] No nested `<Page>`
326
+ - [ ] Run `pnpm bk-lint <file>` — exit code 0
327
+
328
+ If any check fails, fix it before completing. The validator is the contract; this skill is the lookup table.
329
+
330
+ ## When Things Get Hard
331
+
332
+ If you genuinely cannot express something in kit primitives, **stop and surface the gap.** Don't reach for `<div>`. Either:
333
+
334
+ 1. The kit needs a new component (file as a Phase-2 enhancement)
335
+ 2. The content is wrong for this format (push back on the user)
336
+ 3. There's a kit primitive you missed (re-read this skill)
337
+
338
+ The first two are honorable. Reaching for `<div>` is not.
@@ -224,3 +224,7 @@ Provide the advisor with:
224
224
  - Max 2 hours per epic — if exceeded, skip and log `TIMEOUT`
225
225
  - If credential daemon goes down mid-session: write current state to overnight doc, push, exit gracefully
226
226
  - If git push fails: log the failure, attempt rebase, retry once — do not force push
227
+
228
+ ## Capture lessons (exit step)
229
+
230
+ Before the final verdict line, follow `.rdc/guides/lessons-learned-spec.md` § Capture procedure. If this run taught something non-obvious — a first root-cause theory that turned out wrong, the documented/standard path not working, a missing gate or check that cost a round, or a surprising tool/infra behavior — write one `.rdc/lessons/<YYYY-MM-DD>-overnight-<short-slug>.md` per lesson using the schema in that spec. Set `scope` (`simple` | `architectural`) and `status` (`open`, or `applied` if you shipped the fix in this same run, with the commit linked). Commit the lesson file(s) on `develop` alongside the run's other commits, and note "N lessons captured" in your verdict/summary. A run that taught nothing writes nothing — absence is the default.
@@ -250,3 +250,7 @@ Q5. What SSL path?
250
250
  ```
251
251
 
252
252
  Embed all five answers into the infra task description verbatim before handing to the agent.
253
+
254
+ ## Capture lessons (exit step)
255
+
256
+ Before the final verdict line, follow `.rdc/guides/lessons-learned-spec.md` § Capture procedure. If this run taught something non-obvious — a first root-cause theory that turned out wrong, the documented/standard path not working, a missing gate or check that cost a round, or a surprising tool/infra behavior — write one `.rdc/lessons/<YYYY-MM-DD>-plan-<short-slug>.md` per lesson using the schema in that spec. Set `scope` (`simple` | `architectural`) and `status` (`open`, or `applied` if you shipped the fix in this same run, with the commit linked). Commit the lesson file(s) on `develop` alongside the run's other commits, and note "N lessons captured" in your verdict/summary. A run that taught nothing writes nothing — absence is the default.
@@ -84,3 +84,7 @@ direction if given. If advisor cannot resolve, log and skip to next step.
84
84
  - Web search is mandatory — don't just analyze the codebase
85
85
  - Keep the doc under 200 lines — concise, not exhaustive
86
86
  - Unattended: NEVER pause for input; infer and proceed
87
+
88
+ ## Capture lessons (exit step)
89
+
90
+ Before the final verdict line, follow `.rdc/guides/lessons-learned-spec.md` § Capture procedure. If this run taught something non-obvious — a first root-cause theory that turned out wrong, the documented/standard path not working, a missing gate or check that cost a round, or a surprising tool/infra behavior — write one `.rdc/lessons/<YYYY-MM-DD>-preplan-<short-slug>.md` per lesson using the schema in that spec. Set `scope` (`simple` | `architectural`) and `status` (`open`, or `applied` if you shipped the fix in this same run, with the commit linked). Commit the lesson file(s) on `develop` alongside the run's other commits, and note "N lessons captured" in your verdict/summary. A run that taught nothing writes nothing — absence is the default.
@@ -0,0 +1,238 @@
1
+ ---
2
+ name: rdc-brochurify
3
+ version: 0.1.0
4
+ description: |
5
+ Orchestrate a Brochurify job from source ingest through delivered PDF, using six parallel-dispatched typed sub-agents and the convergence loop. Use this skill EVERY TIME the user invokes Brochurify directly via "brochurify this", "make a brochure from", "convert this to a brochure PDF", or "rdc:brochurify". Also runs automatically when a job arrives from the broker via monkey_dispatch. The skill enforces D-001 through D-016 from the brochurify DECISIONS-LOG.
6
+ triggers:
7
+ - "rdc:brochurify"
8
+ - "brochurify this"
9
+ - "make a brochure from"
10
+ - "convert to brochure PDF"
11
+ - "generate brochure from"
12
+ - monkey_dispatch payload with skill="brochurify"
13
+ ---
14
+
15
+ # rdc:brochurify Orchestrator
16
+
17
+ The orchestrator dispatches six waves of typed sub-agents in sequence. Each wave has a clear input contract, an output contract, and a parallelism profile.
18
+
19
+ ## Inputs
20
+
21
+ The orchestrator accepts a job payload:
22
+
23
+ ```json
24
+ {
25
+ "job_id": "uuid",
26
+ "source": {
27
+ "kind": "url" | "html" | "docx" | "md" | "jsx" | "corpus",
28
+ "ref": "https://..." | "file:///path/..." | "<html>..." | { corpus_query }
29
+ },
30
+ "mode": "read-only" | "cosmetic" | "editorial" | "creative",
31
+ "theme": "prt" | "place-fund" | "zoen" | "evergreen" | "editorial-neutral",
32
+ "page_size": "letter" | "a4" | "legal" | "digest" | "tabloid",
33
+ "brief": "optional natural-language brief for editorial/creative modes",
34
+ "org_id": "uuid",
35
+ "user_id": "uuid"
36
+ }
37
+ ```
38
+
39
+ ## Outputs
40
+
41
+ - A PDF in R2 (`brochurify-output` bucket) with a signed URL
42
+ - A completion record in Supabase `brochure_jobs` with:
43
+ - `pdf_r2_key`, `pdf_url`
44
+ - `final_grade`, `page_scores` (jsonb array)
45
+ - `iter` (iteration count reached)
46
+ - `trace` (jsonb log of all 6 waves × iterations)
47
+
48
+ ## The Six Waves
49
+
50
+ ### Wave 1 — Ingest
51
+
52
+ **Goal:** Normalize any source into kit-compliant JSX.
53
+
54
+ **Sub-agent:** `ingest-author` (typed agent with the `lifeai-brochure-author` skill loaded)
55
+
56
+ **Inputs:** raw source from job payload
57
+ **Outputs:** `working/draft.jsx` (kit-compliant JSX) + `working/assets/` (extracted images)
58
+
59
+ **Per-source handling:**
60
+ - `url` — fetch via Playwright (whitelist) or structural-summary mode (open web)
61
+ - `html` — direct ingest, strip scripts/iframes/ads
62
+ - `docx` — pandoc to HTML, then ingest
63
+ - `md` — render to HTML, then ingest
64
+ - `jsx` — pre-built input; skip to validate
65
+ - `corpus` — Creative mode only; corpus reader + Author-Mode-* sub-agent
66
+
67
+ **Failure mode:** if ingest cannot map content to kit primitives, raise a structured error with the unmappable content range and ask the user to clarify.
68
+
69
+ ### Wave 2 — Validate
70
+
71
+ **Goal:** Confirm the JSX passes static and structural validation before render.
72
+
73
+ **Sub-agent:** none — runs `pnpm bk-lint working/draft.jsx` directly
74
+
75
+ **Behavior:**
76
+ - If pass → Wave 3
77
+ - If fail → return errors to Wave 1 agent, retry once
78
+ - If fail twice → escalate to orchestrator: try a different ingest strategy, page-size change, or surface to user
79
+
80
+ **Every failure here writes to `enhancement-log.jsonl`** with:
81
+ - `src: "ingest-author"`
82
+ - `fail_layer: "static"` or `fail_layer: "structural"`
83
+ - The specific rule violated
84
+
85
+ ### Wave 3 — Render
86
+
87
+ **Goal:** Produce a first-iteration PDF and per-page screenshots.
88
+
89
+ **Sub-agent:** none — runs Paged.js via Playwright headless
90
+
91
+ **Process:**
92
+ 1. Build the kit + theme bundle into `working/bundle.html`
93
+ 2. Open with Paged.js polyfill
94
+ 3. Wait for `pagedjs:rendered` event
95
+ 4. Snapshot DOM after pagination → `working/paged.html`
96
+ 5. Per-page screenshot at 150 DPI → `working/pages/page-{N}.png`
97
+ 6. Render to PDF → `working/iter-{i}.pdf`
98
+
99
+ **Failure mode:** if Paged.js fails to converge (rare; usually a kit bug), fall back to print-to-PDF without paged-media polyfill, flag as low-quality iteration, continue.
100
+
101
+ ### Wave 4 — Grade (Vision, Parallel)
102
+
103
+ **Goal:** Score each page against the 7-dimension rubric.
104
+
105
+ **Sub-agent:** `vision-grader` — dispatched **once per page in parallel**.
106
+
107
+ **Per-page inputs:**
108
+ - The page screenshot
109
+ - The source JSX for that page (extracted by walking the paginated DOM)
110
+ - The rubric (R1-R7 with weights and target ranges)
111
+
112
+ **Per-page outputs (structured):**
113
+ ```json
114
+ {
115
+ "page": 3,
116
+ "grade": 82,
117
+ "dimensions": {
118
+ "R1_margin_integrity": 95,
119
+ "R2_bottom_slack": 70,
120
+ "R3_heading_breathing": 85,
121
+ "R4_widows_orphans": 100,
122
+ "R5_image_placement": 80,
123
+ "R6_table_integrity": 100,
124
+ "R7_text_density": 75
125
+ },
126
+ "issues": [
127
+ {"dim": "R2", "desc": "tail gap 1.1in below last paragraph", "fix_hint": "compress paragraph or push next-page content"}
128
+ ]
129
+ }
130
+ ```
131
+
132
+ **Document grade:** `min(page_grades)` per D-013.
133
+
134
+ **Convergence:**
135
+ - Grade ≥ 75 → Wave 6 (Deliver)
136
+ - Grade < 75 AND iter < 10 → Wave 5 (Patch)
137
+ - iter = 10 → Wave 6 with `partial=true` flag
138
+
139
+ ### Wave 5 — Patch (Parallel)
140
+
141
+ **Goal:** Produce a corrected JSX that addresses the issues from Wave 4.
142
+
143
+ **Sub-agent:** `patch-author` — dispatched **once per low-graded page in parallel**.
144
+
145
+ **Mode restrictions:**
146
+ - `read-only` — only break, sizing, spacing patches allowed
147
+ - `cosmetic` — read-only patches + image resize, caption compression, paragraph splits at sentence boundaries
148
+ - `editorial` — cosmetic + paragraph rewrites within 15% character or 25% word reduction
149
+ - `creative` — editorial + free composition (the authoring sub-agent fully active)
150
+
151
+ **Patch types:**
152
+ - `force-break-before` — insert page break before an element
153
+ - `adjust-spacing` — change Stack/Cluster gap variant
154
+ - `resize-figure` — change Figure width/height variant
155
+ - `compress-paragraph` — drop or merge a sentence (cosmetic+ only)
156
+ - `rewrite-paragraph` — full rewrite (editorial+ only)
157
+ - `rebalance-cluster` — split a Cluster onto two pages
158
+ - `change-affinity` — adjust an affinity prop
159
+
160
+ Each patch is applied to `working/draft.jsx`, the validator re-runs, then Wave 3 renders again.
161
+
162
+ **Edit tracking (editorial mode):** every paragraph rewrite is logged with before/after to `working/edits.jsonl`. The completion record includes this log.
163
+
164
+ ### Wave 6 — Deliver
165
+
166
+ **Goal:** Final PDF, signed URL, completion record.
167
+
168
+ **Process:**
169
+ 1. Upload final PDF to R2 with key `brochurify-output/{org_id}/{job_id}.pdf`
170
+ 2. Generate 7-day signed URL
171
+ 3. Update `brochure_jobs` row:
172
+ ```sql
173
+ UPDATE brochure_jobs SET
174
+ status = 'completed',
175
+ iter = $iter,
176
+ current_grade = $grade,
177
+ page_scores = $pageScoresJson,
178
+ pdf_r2_key = $r2Key,
179
+ pdf_url = $signedUrl,
180
+ completed_at = now()
181
+ WHERE id = $jobId;
182
+ ```
183
+ 4. Send SSE event `{type:"complete", url, grade, iter}` to broker
184
+ 5. Append enhancement log entries from this run to `enhancement-log.jsonl`
185
+
186
+ ## Trace Logging
187
+
188
+ Every wave appends to `working/trace.jsonl`:
189
+
190
+ ```jsonl
191
+ {"ts":"...","wave":1,"agent":"ingest-author","iter":1,"status":"start"}
192
+ {"ts":"...","wave":1,"agent":"ingest-author","iter":1,"status":"complete","blocks":127}
193
+ {"ts":"...","wave":2,"iter":1,"status":"complete","errors":0}
194
+ {"ts":"...","wave":3,"iter":1,"status":"complete","pages":8,"render_ms":2340}
195
+ {"ts":"...","wave":4,"iter":1,"page":1,"grade":85,"status":"complete"}
196
+ {"ts":"...","wave":4,"iter":1,"page":2,"grade":68,"status":"complete","issues":2}
197
+ ...
198
+ ```
199
+
200
+ This trace is stored in `brochure_jobs.payload.trace` for forensic review.
201
+
202
+ ## Cost Profile
203
+
204
+ - **Wave 1:** 1 sub-agent call (one model invocation)
205
+ - **Wave 2:** 0 model calls (deterministic validator)
206
+ - **Wave 3:** 0 model calls (deterministic render)
207
+ - **Wave 4:** N parallel model calls (N = page count)
208
+ - **Wave 5:** M parallel model calls (M = pages needing patch; usually 0-3)
209
+ - **Wave 6:** 0 model calls
210
+
211
+ Typical 8-page brochure, 2 iterations: ~1 + 16 + 4 = ~21 model calls total. All on Max plan. Zero per-job API cost.
212
+
213
+ ## Hard Caps
214
+
215
+ - **Max iterations:** 10 (per D-006)
216
+ - **Max wall-clock:** 15 minutes per job
217
+ - **Max page count:** 50 (anything larger is split into multiple jobs)
218
+ - **Max source size:** 5MB raw HTML, 25MB docx, 50MB total assets
219
+
220
+ Exceeding any cap → job fails with structured error; no partial billing.
221
+
222
+ ## Failure Recovery
223
+
224
+ | Failure | Recovery |
225
+ |---|---|
226
+ | Validator fails repeatedly | Try page-size change (Letter → Legal → Digest) before failing job |
227
+ | Vision agent disagrees with itself | Lock grade after 3 iterations of same page; mark "best-effort" |
228
+ | Convergence not reached at iter=10 | Ship best version, flag low-graded pages, log to enhancement |
229
+ | Paged.js render fails | Fall back to direct PDF; flag low-quality iteration |
230
+ | R2 upload fails | Retry 3x then fall back to Supabase storage URL |
231
+
232
+ ## When to invoke
233
+
234
+ Direct user invocation: `rdc:brochurify <source-url-or-path> [--mode] [--theme] [--page-size]`
235
+
236
+ Programmatic invocation: a `monkey_dispatch` job arriving with `skill="brochurify"` and the job payload as `args`.
237
+
238
+ Either path executes the same 6-wave loop. Direct user invocation also returns the trace and the PDF URL to the calling session.