@vectoriox/iox-ui 5.202.1 → 5.204.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/actions-core/index.d.ts +8 -1
  2. package/design-core/index.d.ts +62 -2
  3. package/fesm2022/vectoriox-iox-ui-actions-core.mjs +8 -1
  4. package/fesm2022/vectoriox-iox-ui-actions-core.mjs.map +1 -1
  5. package/fesm2022/vectoriox-iox-ui-design-core.mjs +121 -11
  6. package/fesm2022/vectoriox-iox-ui-design-core.mjs.map +1 -1
  7. package/fesm2022/vectoriox-iox-ui-generation-core.mjs +5443 -293
  8. package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
  9. package/fesm2022/vectoriox-iox-ui.mjs +381 -32
  10. package/fesm2022/vectoriox-iox-ui.mjs.map +1 -1
  11. package/generation-core/index.d.ts +2368 -5
  12. package/index.d.ts +117 -12
  13. package/package.json +1 -1
  14. package/src/actions-core/element-actions.ts +9 -0
  15. package/src/design-core/contrast-audit.ts +93 -11
  16. package/src/design-core/flavor-spec.generated.ts +19 -0
  17. package/src/design-core/image-alt.ts +27 -0
  18. package/src/design-core/public-api.ts +1 -0
  19. package/src/generation-core/audit-site.ts +17 -3
  20. package/src/generation-core/baseline-roles.ts +10 -6
  21. package/src/generation-core/check-free.ts +12 -2
  22. package/src/generation-core/check-layout.ts +3 -2
  23. package/src/generation-core/compose-free.ts +3 -1
  24. package/src/generation-core/compose-layout.ts +1 -1
  25. package/src/generation-core/compose-site.ts +29 -11
  26. package/src/generation-core/critic-calibration.ts +175 -0
  27. package/src/generation-core/critic-prompt.ts +153 -0
  28. package/src/generation-core/critic-rubric.generated.ts +24 -0
  29. package/src/generation-core/critic-sheet.ts +203 -0
  30. package/src/generation-core/critic.ts +175 -0
  31. package/src/generation-core/design-doc-index.ts +58 -0
  32. package/src/generation-core/design-motion.ts +247 -0
  33. package/src/generation-core/design-ops-check.ts +370 -0
  34. package/src/generation-core/design-ops-of.ts +200 -0
  35. package/src/generation-core/design-ops.model.ts +239 -0
  36. package/src/generation-core/design-ops.schema.ts +122 -0
  37. package/src/generation-core/design-ops.ts +361 -0
  38. package/src/generation-core/design-recipes.ts +58 -0
  39. package/src/generation-core/designer-brief.ts +81 -0
  40. package/src/generation-core/designer-direction.ts +248 -0
  41. package/src/generation-core/designer-estimate.ts +171 -0
  42. package/src/generation-core/designer-lessons.generated.ts +653 -0
  43. package/src/generation-core/designer-lessons.ts +153 -0
  44. package/src/generation-core/designer-stop.ts +94 -0
  45. package/src/generation-core/footer-free.ts +23 -2
  46. package/src/generation-core/footer-mix.ts +60 -14
  47. package/src/generation-core/layout-language.ts +2 -0
  48. package/src/generation-core/node-baselines.generated.ts +953 -10
  49. package/src/generation-core/public-api.ts +21 -0
  50. package/src/generation-core/site-spec.generated.ts +82 -10
  51. package/src/generation-core/social-links.ts +370 -0
  52. package/src/generation-core/structure-fingerprint.ts +565 -0
  53. package/src/generation-core/templates.ts +39 -3
  54. package/styles/iox-design.css +26 -1
  55. package/styles/iox-forms.css +22 -0
@@ -110,6 +110,9 @@ export const FREE_STYLE_PROPS: ReadonlyArray<string> = [
110
110
  'fontSize', 'fontWeight', 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'fontStyle',
111
111
  'translateX', 'translateY', 'rotate', 'scaleX', 'scaleY', 'transformOrigin',
112
112
  'clipPath', 'opacity', 'mixBlendMode', 'objectFit', 'borderWidth', 'borderStyle', 'filter', 'backdropFilter',
113
+ // AD0b Batch C — each a builder control both renderers compile: Line Breaks, Wrap, a picture's focus, a sideways
114
+ // row that snaps and where its children stop, a box's soft edges (a word — `maskFade`, never a colour).
115
+ 'whiteSpace', 'textWrap', 'objectPosition', 'scrollSnapType', 'scrollSnapAlign', 'maskFade',
113
116
  ];
114
117
  /** A hover changes position, scale, turn, opacity or a colour token — never layout (Emil: transform / opacity only). */
115
118
  export const FREE_HOVER_PROPS: ReadonlyArray<string> = ['translateX', 'translateY', 'scaleX', 'scaleY', 'rotate', 'opacity', 'color', 'backgroundColor', 'borderColor', 'boxShadow'];
@@ -140,8 +143,15 @@ const columnsOf = (v: unknown) => {
140
143
  };
141
144
  const hasPhoneLayer = (n: FreeNode) => FREE_PHONE_LAYERS.some(bp => Object.keys(n.responsive?.[bp as FreeLayer] ?? {}).length > 0);
142
145
 
146
+ /** How `freeStyleIssues` reads a style map. */
147
+ export interface FreeStyleRules {
148
+ /** The AI designer (ai-designer-plan §2b): it writes the builder's own controls, so ANY property may be named — the
149
+ * type's slots refuse the rest (`assertStyleSlots`) — and every other rule holds. */
150
+ anyProperty?: boolean;
151
+ }
152
+
143
153
  /** One style map against the rules: a known property, one clean value, the look's token where the look owns it. */
144
- export function freeStyleIssues(style: FreeStyle | undefined, path: string, ctx: Pick<FreeJudgeContext, 'tokens'>): FreeIssue[] {
154
+ export function freeStyleIssues(style: FreeStyle | undefined, path: string, ctx: Pick<FreeJudgeContext, 'tokens'>, rules: FreeStyleRules = {}): FreeIssue[] {
145
155
  const out: FreeIssue[] = [];
146
156
  const types = new Map(ctx.tokens.map(t => [t.name, t.type]));
147
157
  const say = (code: FreeIssueCode, prop: string, message: string) => out.push({ code, path: `${path}.${prop}`, message });
@@ -149,7 +159,7 @@ export function freeStyleIssues(style: FreeStyle | undefined, path: string, ctx:
149
159
  const v = String(raw).trim();
150
160
  const kind = FREE_TOKEN_PROPS[prop];
151
161
  if (PHYSICAL.test(prop)) { say(FreeIssueCode.Style, prop, 'write sides as start / end (insetInlineStart, marginInlineEnd …) — the site also runs right to left'); continue; }
152
- if (!kind && !FREE_STYLE_PROPS.includes(prop)) { say(FreeIssueCode.Style, prop, 'not a style property this language has'); continue; }
162
+ if (!kind && !rules.anyProperty && !FREE_STYLE_PROPS.includes(prop)) { say(FreeIssueCode.Style, prop, 'not a style property this language has'); continue; }
153
163
  if (!v || UNSAFE.test(v)) { say(FreeIssueCode.Style, prop, 'a value is one plain value — no url(), no ; { } !important'); continue; }
154
164
  if (prop === 'textAlign' && /^(left|right)$/.test(v)) { say(FreeIssueCode.Style, prop, 'start | end | center'); continue; }
155
165
  const win = WINDOW_WIDTH_UNIT.exec(v);
@@ -967,7 +967,8 @@ function uniqueIssues(issues: LayoutIssue[]): LayoutIssue[] {
967
967
  export const LAYOUT_ENTRANCE_MAX_MS = 1200;
968
968
  /** The scale an action starts from, where it is not 1 (iox-ui `buildInteractionKeyframes`; held equal by the spec). */
969
969
  export const ACTION_START_SCALE: Readonly<Record<string, number>> = { scaleIn: 0.8 };
970
- const ENTRANCE_TRIGGERS: ReadonlySet<string> = new Set(['viewportEnter', 'pageLoad', 'sceneLand']);
970
+ /** The triggers an entrance plays under by itself (the designer's motion check reads the same set). */
971
+ export const LAYOUT_ENTRANCE_TRIGGERS: ReadonlySet<string> = new Set(['viewportEnter', 'pageLoad', 'sceneLand']);
971
972
  const EASE_IN = /(^|[\s,(])ease-in(?!-out)/;
972
973
  const EASING_TOKEN = /^(cubic-bezier\(|linear(\(|$)|var\(--)/;
973
974
  const TRANSITION_ALL = /(^|[\s,])all([\s,]|$)/;
@@ -990,7 +991,7 @@ export function auditLayoutMotion(nodes: ReadonlyArray<SerializedNode>): LayoutI
990
991
  const easing = String(a.easing ?? '');
991
992
  if (EASE_IN.test(easing)) add(`${ap}.easing`, 'never ease-in: it starts slow where the eye is watching');
992
993
  else if (moves && !EASING_TOKEN.test(easing)) add(`${ap}.easing`, `"${easing}" is not an easing token — a cubic-bezier, linear or a var()`);
993
- if (moves && ENTRANCE_TRIGGERS.has(String(ix.trigger)) && (a.duration ?? 0) > LAYOUT_ENTRANCE_MAX_MS) add(`${ap}.duration`, `${a.duration}ms — an entrance plays in at most ${LAYOUT_ENTRANCE_MAX_MS}ms`);
994
+ if (moves && LAYOUT_ENTRANCE_TRIGGERS.has(String(ix.trigger)) && (a.duration ?? 0) > LAYOUT_ENTRANCE_MAX_MS) add(`${ap}.duration`, `${a.duration}ms — an entrance plays in at most ${LAYOUT_ENTRANCE_MAX_MS}ms`);
994
995
  const start = ACTION_START_SCALE[String(a.type)];
995
996
  if (start !== undefined && start < LIM.minScale) add(`${ap}.type`, `${a.type} starts at scale ${start} — nothing grows from under ${LIM.minScale}`);
996
997
  }));
@@ -39,6 +39,8 @@ export interface ComposeFreeOptions {
39
39
  /** The site's language: a right-to-left one puts the start side on the right. */
40
40
  locale?: string;
41
41
  rtl?: boolean;
42
+ /** Social links (FV-D10): the owner's stated WhatsApp as a contact form's channel address (`statedWhatsAppHref`). */
43
+ whatsApp?: string;
42
44
  /** The look's pace and easing (`layoutMotionOf`): how long an entrance takes. Default normal, ease-out. */
43
45
  motion?: LayoutSite['motion'];
44
46
  /** A material id as the address and the words of its picture (`ComposeContext.photoSrc` / `photoAlt`). */
@@ -212,7 +214,7 @@ function slotOf(n: FreeNode, id: string, ctx: Ctx): SerializedNode[] {
212
214
  if (!lightbox) throw new ComposeError(`${n.id}: "${slot.ref}" shows no picture a click could open`);
213
215
  return [frame, lightbox];
214
216
  }
215
- case FreeSlotKind.Form: return [composePresetForm(`${id}-form`, slot.ref, ctx.o.owner, locale)];
217
+ case FreeSlotKind.Form: return [composePresetForm(`${id}-form`, slot.ref, ctx.o.owner, locale, ctx.o.whatsApp)];
216
218
  case FreeSlotKind.Accordion: return [composeListAccordion(`${id}-accordion`, slot.ref, ctx.o.listFields?.(slot.ref) ?? [], locale)];
217
219
  case FreeSlotKind.Tabs: return [composeListTabs(`${id}-tabs`, slot.ref, ctx.o.listFields?.(slot.ref) ?? [], locale)];
218
220
  case FreeSlotKind.Quotes: {
@@ -1505,7 +1505,7 @@ function formLayer(id: string, l: LayoutLayer, lc: LayerCtx, ctx: Ctx, path: str
1505
1505
  setStyleProps(intro, { margin: ZERO });
1506
1506
  parts.push(intro);
1507
1507
  }
1508
- const form = composePresetForm(`${id}-form`, f.preset, ctx.p, ctx.site.locale);
1508
+ const form = composePresetForm(`${id}-form`, f.preset, ctx.p, ctx.site.locale, ctx.site.whatsApp);
1509
1509
  const afterSend = LAYOUT_FORM_AFTER_SEND[f.preset];
1510
1510
  if (afterSend) form.props[FORM_AFTER_SEND_TRAIT] = afterSend;
1511
1511
  walkSerialized([form], node => {
@@ -4,7 +4,7 @@ import {
4
4
  columnWordOf, designTokenRows, elementStyleById,
5
5
  } from '@vectoriox/iox-ui/design-core';
6
6
  import { fitSeoText, SEO_DESCRIPTION_MAX, SEO_TITLE_MAX, SeoRawDoc } from '@vectoriox/iox-ui/seo-core';
7
- import { busyWord, channelOpensNewTab, FORM_ACTIONS_ROLE, FORM_CHANNEL_ROLE, FormPresetChannel, FormPresetDef, FormPresetField, formPresetById, FormPresetId, presetFormActions } from '@vectoriox/iox-ui/forms-core';
7
+ import { busyWord, ChannelKind, channelOpensNewTab, channelWords, FORM_ACTIONS_ROLE, FORM_CHANNEL_ROLE, FormPresetChannel, FormPresetDef, FormPresetField, formPresetById, FormPresetId, presetFormActions } from '@vectoriox/iox-ui/forms-core';
8
8
  import {
9
9
  ACCORDION_BIND_PROP, ACCORDION_CONTENT_LIMIT, accordionWords, accordionAnswerOf, accordionItems, accordionQuestionOf, AccordionRole,
10
10
  buildAccordionRecipe, buildCardRecipe, buildCarouselRecipe, buildLightboxRecipe, buildSlideshowRecipe, CardLayout, CardPart, CardRole, CARD_LAYOUTS, CARD_PARTS, CompositeNode,
@@ -20,6 +20,7 @@ import { scrubEntranceStamps } from './text-scroll';
20
20
  import { filmOfPlan } from './film';
21
21
  import { checkFooter, FooterArrange, FooterContext, footerMixOfPlan, FooterNever, footerPattern, footerReferences, FooterRole, stampFooterMix } from './footer-mix';
22
22
  import { FreeFooterContext, freeFooterOrMix, referenceFooterLayout } from './footer-free';
23
+ import { FOLLOW_ROW_FAMILY, statedWhatsAppHref, withFollowRow } from './social-links';
23
24
  import { planWrites, withTypeSignUp } from './footer-sign-up';
24
25
  import {
25
26
  countryLegalFacts, FOOTER_LEGAL_ROLE, FORM_LEGAL_ROLE, formAsksPersonalData, formLegalFacts, LEGAL_PAGE_SETTING, LegalContext, LegalFact, LegalFacts,
@@ -806,7 +807,7 @@ function altBinding(pn: PatternNode, repeater: RepeaterScope | null, ctx: Ctx, i
806
807
  }
807
808
 
808
809
  /** A preset Form's children — the forms-core preset's fields, submit and the WORDS of both state blocks. */
809
- function presetChildren(preset: FormPresetDef, id: string, locale: string | undefined): SerializedNode[] {
810
+ function presetChildren(preset: FormPresetDef, id: string, locale: string | undefined, whatsApp = ''): SerializedNode[] {
810
811
  const fields = preset.fields.map((f, i) => {
811
812
  const props = Object.fromEntries(PRESET_FIELD_PROPS.filter(k => f[k] !== undefined).map(k => [k, f[k]]));
812
813
  assertTraits(FIELD, Object.keys(props));
@@ -820,7 +821,18 @@ function presetChildren(preset: FormPresetDef, id: string, locale: string | unde
820
821
  block.children = [create(`${id}-${n + 1 + i}-0`, TEXT, { content: words })];
821
822
  return block;
822
823
  });
823
- return [...fields, preset.channel ? actionsRow(submit, preset.channel, `${id}-${n}`) : submit, ...blocks];
824
+ const channel = formChannel(preset, locale, whatsApp);
825
+ return [...fields, channel ? actionsRow(submit, channel, `${id}-${n}`, whatsApp) : submit, ...blocks];
826
+ }
827
+
828
+ /**
829
+ * The second channel a preset form keeps beside Send: the preset's own; and when the owner stated a WhatsApp number
830
+ * (social links, FV-D10) the contact form gains "Message us on WhatsApp" too — its address the owner's, never invented.
831
+ */
832
+ function formChannel(preset: FormPresetDef, locale: string | undefined, whatsApp: string): FormPresetChannel | null {
833
+ if (preset.channel) return preset.channel;
834
+ if (!whatsApp || preset.id !== FormPresetId.Contact) return null;
835
+ return { kind: ChannelKind.WhatsApp, label: channelWords(ChannelKind.WhatsApp, locale) };
824
836
  }
825
837
 
826
838
  /**
@@ -828,11 +840,13 @@ function presetChildren(preset: FormPresetDef, id: string, locale: string | unde
828
840
  * `buildFormActionsRow`): the channel's address is the studio's own fact and starts EMPTY — the Publishable gate
829
841
  * reminds the owner (`auditSite`, empty-channel) and the live site leaves it out until it is filled. Never a number written for it.
830
842
  */
831
- function actionsRow(submit: SerializedNode, channel: FormPresetChannel, id: string): SerializedNode {
843
+ function actionsRow(submit: SerializedNode, channel: FormPresetChannel, id: string, whatsApp = ''): SerializedNode {
832
844
  const row = create(`${id}-row`, FIELD_GROUP);
833
845
  row.role = FORM_ACTIONS_ROLE;
834
846
  Object.assign(row.styleProps, { flexWrap: 'wrap', alignItems: 'center', gap: '12px' });
835
- const button = create(`${id}-channel`, BUTTON_BLOCK, { tag: 'a', linkType: LinkType.External, href: '', target: channelOpensNewTab(channel.kind) ? '_blank' : '_self' }, CHANNEL_STYLE);
847
+ // A WhatsApp channel takes the owner's stated number (social links); every other channel starts empty (a reminder).
848
+ const href = channel.kind === ChannelKind.WhatsApp ? whatsApp : '';
849
+ const button = create(`${id}-channel`, BUTTON_BLOCK, { tag: 'a', linkType: LinkType.External, href, target: channelOpensNewTab(channel.kind) ? '_blank' : '_self' }, CHANNEL_STYLE);
836
850
  button.role = FORM_CHANNEL_ROLE;
837
851
  button.children = [create(`${id}-channel-0`, TEXT, { content: channel.label }, BUTTON_LABEL_STYLE)];
838
852
  row.children = [submit, button];
@@ -849,11 +863,11 @@ function composeForm(node: SerializedNode, pn: PatternNode, id: string, ctx: Ctx
849
863
  // A section may give the pattern's form another preset (`form`: Practice's contact page asks to book).
850
864
  const presetId = ctx.section?.form ?? pn.preset;
851
865
  if (pn.c?.length) throw new ComposeError(`${id}: a preset Form takes its fields from the preset, not the pattern`);
852
- stampPresetForm(node, presetId, id, ctx.owner, ctx.plan.locale);
866
+ stampPresetForm(node, presetId, id, ctx.owner, ctx.plan.locale, statedWhatsAppHref(ctx.plan.business?.social));
853
867
  }
854
868
 
855
869
  /** A preset's name, stable form id, after-send steps (iox-cms#84: a contact form emails the owner) and children on a Form node — the ONE stamping `composeSite` and `composeLayout` share. */
856
- function stampPresetForm(node: SerializedNode, presetId: string, id: string, owner: string, locale?: string): void {
870
+ function stampPresetForm(node: SerializedNode, presetId: string, id: string, owner: string, locale?: string, whatsApp = ''): void {
857
871
  // iox-ui#112: the form asks, answers and fails in the site's language.
858
872
  const preset = formPresetById(presetId, locale);
859
873
  if (!preset) throw new ComposeError(`${id}: no form preset "${presetId}" in forms-core`);
@@ -861,13 +875,13 @@ function stampPresetForm(node: SerializedNode, presetId: string, id: string, own
861
875
  setProp(node, 'formId', `${preset.id}-${stableHash(`${owner}/${id}`)}`);
862
876
  const actions = presetFormActions(preset);
863
877
  if (actions) setProp(node, 'actions', actions);
864
- node.children = presetChildren(preset, id, locale);
878
+ node.children = presetChildren(preset, id, locale, whatsApp);
865
879
  }
866
880
 
867
881
  /** A NEW Form stamped from a forms-core preset, exactly as a pattern's preset form is (premium M8: a layout's form layer). */
868
- export function composePresetForm(id: string, presetId: string, owner: string, locale?: string): SerializedNode {
882
+ export function composePresetForm(id: string, presetId: string, owner: string, locale?: string, whatsApp = ''): SerializedNode {
869
883
  const node = create(id, FORM);
870
- stampPresetForm(node, presetId, id, owner, locale);
884
+ stampPresetForm(node, presetId, id, owner, locale, whatsApp);
871
885
  return node;
872
886
  }
873
887
 
@@ -1699,7 +1713,9 @@ interface SectionMotion {
1699
1713
  function composePattern(pattern: SitePattern, id: string, ctx: Ctx, motion: SectionMotion | null = null): SerializedNode {
1700
1714
  if (pattern.node.each) throw new ComposeError(`${id}: a pattern's root cannot be stamped per page`);
1701
1715
  const own: Ctx = { ...ctx, openers: [], shownWhen: [], entrances: [] };
1702
- const node = composeNode(pattern.node, id, null, own);
1716
+ // Social links (FV-D10): a contact section carries the owner's stated links beside its facts (`withFollowRow`).
1717
+ const shaped = pattern.family === FOLLOW_ROW_FAMILY ? withFollowRow(pattern.node, ctx.plan.business?.social) : pattern.node;
1718
+ const node = composeNode(shaped, id, null, own);
1703
1719
  if (!node) throw new ComposeError(`${id}: a pattern's root cannot be optional or a link`);
1704
1720
  wireOpeners(node, own.openers ?? []);
1705
1721
  wireShownWhen(node, own.shownWhen ?? []);
@@ -1929,6 +1945,7 @@ function composeLayoutPage(
1929
1945
  look: { preset: preset.id },
1930
1946
  motion: layoutMotionOf(preset.id),
1931
1947
  sections: layout.sections,
1948
+ ...(statedWhatsAppHref(plan.business?.social) ? { whatsApp: statedWhatsAppHref(plan.business?.social) } : {}),
1932
1949
  };
1933
1950
  const boxShape = (id: string) => {
1934
1951
  const read = parseLayoutPhotoId(id);
@@ -1984,6 +2001,7 @@ function freeOptionsOf(
1984
2001
  listOf: alias => layoutListBinding(alias, plan),
1985
2002
  listFields: alias => fieldsOf(listedContentType(alias, plan)),
1986
2003
  quotes: quoteListOf(plan),
2004
+ ...(statedWhatsAppHref(plan.business?.social) ? { whatsApp: statedWhatsAppHref(plan.business?.social) } : {}),
1987
2005
  ...(readyMade ? {
1988
2006
  readyMade: (at: number, id: string) => {
1989
2007
  const section = page.sections[at];
@@ -0,0 +1,175 @@
1
+ import { AiTokenCounts, AiTokenPrice, costUsd } from './ai-run';
2
+ import { CRITIC_DESIGN_DIMENSIONS, CRITIC_DIMENSIONS, CriticAnswer, criticAnswerIssues, CriticDimension, CriticIssue, CriticIssueCode, criticVerdict } from './critic';
3
+
4
+ /**
5
+ * THE CRITIC'S CALIBRATION (ai-designer-plan §7 AD3, R-H8, R-H22, AD-D3): the critic scores the 12 calibration pages
6
+ * (6 proof pages + 6 J10 generated pages) and is compared with the tester's scores of the same pages. R-H8: every page's
7
+ * design mean within 0.5 of the tester's, or AD4 does not start. AD-D3: if the cheaper critic lands within 0.3 of the
8
+ * dearer one, a round's critic switches to it. R-H22: a near-copy of a reference's structure scores no higher than a
9
+ * distinct page of equal craft. Cost per round from each answer's token counts (or the provider's own figure). Reads
10
+ * RECORDED answers only — the run that records them is the host's (iox-cms); this file never calls a model. Pure.
11
+ */
12
+
13
+ /** R-H8: the largest difference from the tester a page may show. */
14
+ export const CALIBRATION_MAX_ERROR = 0.5;
15
+ /** AD-D3: how close the cheaper critic must stay to the dearer one for a round to switch to it. */
16
+ export const CRITIC_SWITCH_WITHIN = 0.3;
17
+
18
+ export enum CalibrationKind {
19
+ /** A page of the designer-loop proof (law, hotel). */
20
+ Proof = 'proof',
21
+ /** A page the generator built (J10). */
22
+ Generated = 'generated',
23
+ }
24
+
25
+ /** One calibration page and the tester's scores of it (team/runs/…). */
26
+ export interface CalibrationPage {
27
+ id: string;
28
+ kind: CalibrationKind;
29
+ /** The reference it was scored against. */
30
+ reference: string;
31
+ tester: Record<CriticDimension, number>;
32
+ /** The tester's headline as written (a cap included). */
33
+ testerHeadline: number;
34
+ }
35
+
36
+ /** One critic answer as recorded: the page, the model asked, the parsed answer, what each attempt read and wrote. */
37
+ export interface RecordedCritique {
38
+ pageId: string;
39
+ model: string;
40
+ answer: unknown;
41
+ attempts: ReadonlyArray<{ model: string; tokens: AiTokenCounts }>;
42
+ /** The provider's own figure (OpenRouter `usage.cost`), when it gave one. */
43
+ reportedCostUsd?: number;
44
+ }
45
+
46
+ export interface CalibrationRow {
47
+ pageId: string;
48
+ kind: CalibrationKind;
49
+ issues: CriticIssue[];
50
+ /** The critic's and the tester's design means (dimensions 1–7), and their difference (critic − tester). */
51
+ criticMean: number | null;
52
+ testerMean: number;
53
+ error: number | null;
54
+ /** Per dimension, critic − tester (polish included). */
55
+ dimensionErrors: Partial<Record<CriticDimension, number>>;
56
+ criticHeadline: number | null;
57
+ testerHeadline: number;
58
+ /** What the answer cost; null when neither the provider nor the price table could say. */
59
+ costUsd: number | null;
60
+ }
61
+
62
+ export interface ModelCalibration {
63
+ model: string;
64
+ rows: CalibrationRow[];
65
+ /** Pages whose answer the gate refused (they count as misses). */
66
+ invalid: number;
67
+ /** Over the valid answers: the mean of |error| and the largest |error|. */
68
+ meanError: number | null;
69
+ maxError: number | null;
70
+ /** R-H8: every calibration page answered, valid, and within `CALIBRATION_MAX_ERROR`. */
71
+ passes: boolean;
72
+ /** Per dimension, the mean critic − tester (a critic that is always kind on Motion shows here). */
73
+ dimensionBias: Partial<Record<CriticDimension, number>>;
74
+ costPerRoundUsd: number | null;
75
+ totalCostUsd: number | null;
76
+ }
77
+
78
+ /** R-H22: a page that follows a reference's structure against a distinct page of equal craft. */
79
+ export interface LikenessProbe {
80
+ copy: string;
81
+ distinct: string;
82
+ }
83
+
84
+ export interface CalibrationReport {
85
+ models: ModelCalibration[];
86
+ /** AD-D3: the cheaper critic against the dearer, page by page (absent unless both were asked). */
87
+ agreement?: { dearer: string; cheaper: string; meanDifference: number | null; within: boolean };
88
+ /** R-H22, per model: the copy scored no higher than the distinct page. */
89
+ likeness: Array<{ model: string; copy: string; distinct: string; copyHeadline: number | null; distinctHeadline: number | null; passes: boolean }>;
90
+ }
91
+
92
+ export interface CalibrationOptions {
93
+ /** The price of a model, per million tokens — null when unknown. */
94
+ priceOf: (model: string) => AiTokenPrice | null;
95
+ /** The dearer and the cheaper critic, for AD-D3 (`anthropic/claude-opus-5.5`, `anthropic/claude-sonnet-5.5`). */
96
+ compare?: { dearer: string; cheaper: string };
97
+ likenessProbes?: ReadonlyArray<LikenessProbe>;
98
+ }
99
+
100
+ const mean = (values: ReadonlyArray<number>) => (values.length ? values.reduce((a, b) => a + b, 0) / values.length : null);
101
+ const designMeanOf = (scores: Readonly<Record<CriticDimension, number>>) => mean(CRITIC_DESIGN_DIMENSIONS.map(d => scores[d]))!;
102
+
103
+ /** What one recorded answer cost: the provider's figure, else each attempt at its price; null when a price is missing. */
104
+ export function critiqueCostUsd(recorded: Pick<RecordedCritique, 'attempts' | 'reportedCostUsd'>, priceOf: CalibrationOptions['priceOf']): number | null {
105
+ if (recorded.reportedCostUsd !== undefined) return recorded.reportedCostUsd;
106
+ let total = 0;
107
+ for (const a of recorded.attempts) {
108
+ const price = priceOf(a.model);
109
+ if (!price) return null;
110
+ total += costUsd(a.tokens, price);
111
+ }
112
+ return total;
113
+ }
114
+
115
+ function rowOf(page: CalibrationPage, recorded: RecordedCritique | undefined, options: CalibrationOptions): CalibrationRow {
116
+ const testerMean = designMeanOf(page.tester);
117
+ const base = { pageId: page.id, kind: page.kind, testerMean, testerHeadline: page.testerHeadline };
118
+ if (!recorded) {
119
+ return { ...base, issues: [{ code: CriticIssueCode.Shape, path: '', message: 'no recorded answer' }], criticMean: null, error: null, dimensionErrors: {}, criticHeadline: null, costUsd: null };
120
+ }
121
+ const costUsd = critiqueCostUsd(recorded, options.priceOf);
122
+ const issues = criticAnswerIssues(recorded.answer, { reference: page.reference });
123
+ if (issues.length) return { ...base, issues, criticMean: null, error: null, dimensionErrors: {}, criticHeadline: null, costUsd };
124
+ const answer = recorded.answer as CriticAnswer;
125
+ const verdict = criticVerdict(answer);
126
+ const dimensionErrors = Object.fromEntries(CRITIC_DIMENSIONS.map(d => [d, answer.scores[d].score - page.tester[d]])) as Record<CriticDimension, number>;
127
+ return { ...base, issues, criticMean: verdict.designMean, error: verdict.designMean - testerMean, dimensionErrors, criticHeadline: verdict.headline, costUsd };
128
+ }
129
+
130
+ function modelOf(model: string, pages: ReadonlyArray<CalibrationPage>, answers: ReadonlyArray<RecordedCritique>, options: CalibrationOptions): ModelCalibration {
131
+ const rows = pages.map(p => rowOf(p, answers.find(a => a.model === model && a.pageId === p.id), options));
132
+ const valid = rows.filter(r => r.error !== null);
133
+ const errors = valid.map(r => Math.abs(r.error!));
134
+ const costs = rows.map(r => r.costUsd);
135
+ const known = costs.every(c => c !== null);
136
+ const dimensionBias = Object.fromEntries(CRITIC_DIMENSIONS.map(d => [d, mean(valid.map(r => r.dimensionErrors[d]!))])
137
+ .filter(([, v]) => v !== null)) as Partial<Record<CriticDimension, number>>;
138
+ return {
139
+ model,
140
+ rows,
141
+ invalid: rows.length - valid.length,
142
+ meanError: mean(errors),
143
+ maxError: errors.length ? Math.max(...errors) : null,
144
+ passes: valid.length === rows.length && errors.every(e => e <= CALIBRATION_MAX_ERROR),
145
+ dimensionBias,
146
+ costPerRoundUsd: known ? mean(costs as number[]) : null,
147
+ totalCostUsd: known ? (costs as number[]).reduce((a, b) => a + b, 0) : null,
148
+ };
149
+ }
150
+
151
+ /** The calibration of every model that answered, the AD-D3 agreement and the R-H22 probes. */
152
+ export function calibrationReport(pages: ReadonlyArray<CalibrationPage>, answers: ReadonlyArray<RecordedCritique>, options: CalibrationOptions): CalibrationReport {
153
+ const models = [...new Set(answers.map(a => a.model))].map(m => modelOf(m, pages, answers, options));
154
+ const byModel = new Map(models.map(m => [m.model, m]));
155
+ let agreement: CalibrationReport['agreement'];
156
+ const dearer = options.compare && byModel.get(options.compare.dearer);
157
+ const cheaper = options.compare && byModel.get(options.compare.cheaper);
158
+ if (options.compare && dearer && cheaper) {
159
+ const differences = pages.map((p, i) => {
160
+ const a = dearer.rows[i].criticMean;
161
+ const b = cheaper.rows[i].criticMean;
162
+ return a === null || b === null ? null : Math.abs(a - b);
163
+ });
164
+ const both = differences.filter((d): d is number => d !== null);
165
+ const meanDifference = both.length === pages.length ? mean(both) : null;
166
+ agreement = { ...options.compare, meanDifference, within: meanDifference !== null && meanDifference <= CRITIC_SWITCH_WITHIN };
167
+ }
168
+ const likeness = models.flatMap(m => (options.likenessProbes ?? []).map(probe => {
169
+ const headline = (id: string) => m.rows.find(r => r.pageId === id)?.criticHeadline ?? null;
170
+ const copyHeadline = headline(probe.copy);
171
+ const distinctHeadline = headline(probe.distinct);
172
+ return { model: m.model, ...probe, copyHeadline, distinctHeadline, passes: copyHeadline !== null && distinctHeadline !== null && copyHeadline <= distinctHeadline };
173
+ }));
174
+ return { models, agreement, likeness };
175
+ }
@@ -0,0 +1,153 @@
1
+ import { CRITIC_CHANGES, CRITIC_SCORE, CriticAnswer, criticVerdict } from './critic';
2
+ import { CRITIC_RUBRIC_DIMENSIONS, CRITIC_RUBRIC_HEADLINE, CRITIC_RUBRIC_POLISH, CRITIC_RUBRIC_SOURCE } from './critic-rubric.generated';
3
+ import { CaptureBox, CaptureView, CaptureWidth, CritiqueSheet, SheetPair } from './critic-sheet';
4
+
5
+ /**
6
+ * THE CRITIC'S PROMPT (ai-designer-plan §2d, AD3, AD-D18, R-H22): the instructions (stable — cached across rounds) and one
7
+ * round's turn. The rubric is the tester's own (`critic-rubric.generated.ts`, ported from `team/reference-score.md` §2),
8
+ * so the critic and the tester score by the same words; the level rule is said in so many words: as good as the
9
+ * reference, never like it. The turn carries the art direction, the reference's card, the sheet (the reference's views,
10
+ * then ours under the same labels, then crops), the measures, the gate's findings and the last critique. The host turns the picture items into its transport's image
11
+ * blocks (iox-cms: `AiContent`). Pure.
12
+ */
13
+
14
+ /** A block of the instructions; the last stable one carries the cache mark (iox-cms `AiPromptPart`). */
15
+ export interface CriticPromptPart {
16
+ text: string;
17
+ cache?: boolean;
18
+ }
19
+
20
+ /** One item of the round's turn: words, a shot, or a zoomed crop of a shot (the host cuts and enlarges it). `cache` marks
21
+ * the end of the turn's stable prefix (iox-cms: the block's cache mark). */
22
+ export enum CriticContentKind {
23
+ Text = 'text',
24
+ Image = 'image',
25
+ Crop = 'crop',
26
+ }
27
+ export type CriticContent =
28
+ | { kind: CriticContentKind.Text; text: string; cache?: boolean }
29
+ | { kind: CriticContentKind.Image; ref: string; w: number; h: number; cache?: boolean }
30
+ | { kind: CriticContentKind.Crop; ref: string; box: CaptureBox; zoom: number; cache?: boolean };
31
+
32
+ /**
33
+ * How the sheet's pairs are laid out in the turn.
34
+ * - `Cached` (the default): the reference's shots first, every view labelled, ending in the cache mark; then ours under
35
+ * the same labels. The reference does not change between rounds, so from round 2 it is read from the cache (§6b
36
+ * prices it at the cache-hit rate) — a prefix only caches if nothing that changes comes before it.
37
+ * - `Paired`: each view reference then ours, side by side in the turn; nothing after the instructions caches.
38
+ * AD3 calibrates the layout AD4 will run, so the default is the cached one.
39
+ */
40
+ export enum CriticSheetLayout {
41
+ Cached = 'cached',
42
+ Paired = 'paired',
43
+ }
44
+
45
+ /** AD-D18, in the words the critic reads. */
46
+ export const CRITIC_LEVEL_RULE = 'Score the LEVEL, never the likeness. Ask "is this page as good as the reference?", never "does it look '
47
+ + 'like it?". Resemblance earns nothing: a page that borrows the reference\'s arrangement scores no higher than a different page made '
48
+ + 'with the same care, and a page unlike the reference can score 10. The reference and its card show the standard to reach — its '
49
+ + 'precision, its restraint, its finish — not a design to copy.';
50
+
51
+ const WIDTH_WORDS: Readonly<Record<CaptureWidth, string>> = { [CaptureWidth.Laptop]: 'Laptop 1440', [CaptureWidth.Phone]: 'Phone 390' };
52
+ const VIEW_WORDS: Readonly<Record<CaptureView, string>> = {
53
+ [CaptureView.First]: 'the first screen',
54
+ [CaptureView.HeaderOpen]: 'the menu open',
55
+ [CaptureView.HeaderScrolled]: 'the header after scrolling down and up',
56
+ [CaptureView.Down1]: 'one screen down',
57
+ [CaptureView.Down2]: '2.2 screens down',
58
+ [CaptureView.List]: 'a list',
59
+ [CaptureView.Scene25]: 'the Scene at 25%',
60
+ [CaptureView.Scene50]: 'the Scene at 50%',
61
+ [CaptureView.Scene90]: 'the Scene at 90%',
62
+ [CaptureView.Reduced]: 'reduced motion',
63
+ [CaptureView.Footer]: 'the footer',
64
+ [CaptureView.Full]: 'the whole page, scaled down',
65
+ };
66
+ const where = (width: CaptureWidth, view: CaptureView) => `${WIDTH_WORDS[width]} · ${VIEW_WORDS[view]}`;
67
+
68
+ /** The rubric as the critic reads it: each dimension with what it compares, then the headline and the polish rule. */
69
+ export function criticRubricText(): string {
70
+ return [
71
+ `THE RUBRIC (${CRITIC_RUBRIC_SOURCE.file} ${CRITIC_RUBRIC_SOURCE.section}). Score each dimension ${CRITIC_SCORE.min}–${CRITIC_SCORE.max} in half points:`,
72
+ ...CRITIC_RUBRIC_DIMENSIONS.map(d => `${d.n}. ${d.name} ("${d.key}") — compare: ${d.compares}`),
73
+ CRITIC_RUBRIC_HEADLINE,
74
+ `Polish: list every bug you see; each costs ${CRITIC_RUBRIC_POLISH.bugPenalty}. Mark "broken" any a visitor would call broken (a link to `
75
+ + `"page not found", words over words, a cut-off line, a dead button): one broken bug caps the page at ${CRITIC_RUBRIC_POLISH.brokenCap}. `
76
+ + 'The headline is computed from your scores; do not write it.',
77
+ ].join('\n');
78
+ }
79
+
80
+ /** The instructions, stable across rounds and pages (the cache mark is on the last part). */
81
+ export function criticSystem(): CriticPromptPart[] {
82
+ return [
83
+ {
84
+ text: 'You are the critic of an AI designer\'s round. You look at one page of a website — screenshots of OUR page beside the '
85
+ + 'REFERENCE site the owner admires, view by view, then zoomed crops — and you score our page by the rubric below, the one '
86
+ + 'IOX\'s tester scores by. You judge what is on the screenshots, nothing else.',
87
+ },
88
+ { text: CRITIC_LEVEL_RULE },
89
+ { text: criticRubricText() },
90
+ {
91
+ text: [
92
+ 'EVIDENCE: one line per dimension, read off the sheet as a position, a size or a colour — "<reference> sets the hero at '
93
+ + '≈ 100px on paper #FFFFFC; ours sets it at 64px on #F3F0EA". A line with no measurement is refused.',
94
+ `CHANGES: ${CRITIC_CHANGES.min}–${CRITIC_CHANGES.max}, the ones that move the LOWEST score most, at least one aimed at it. Write `
95
+ + 'each as a brief for the designer, in our own terms (what to change, where, by how much). Never name the reference in a '
96
+ + 'brief, and never ask to copy it or make it look like it.',
97
+ 'Answer with the critique object only.',
98
+ ].join('\n'),
99
+ cache: true,
100
+ },
101
+ ];
102
+ }
103
+
104
+ export interface CriticRoundInput {
105
+ /** The page (`law-home`) and its language. */
106
+ page: string;
107
+ locale: string;
108
+ /** The reference's name (`graya-institute`) and its card (team/reference-cards/<name>.md). */
109
+ reference: string;
110
+ referenceCard: string;
111
+ /** The art direction the round works to (AD4); absent in calibration. */
112
+ artDirection?: string;
113
+ /** The measures, one line each (AD2's; the tester's metrics today). */
114
+ measures?: ReadonlyArray<string>;
115
+ /** The gate's findings, one line each. */
116
+ gateFindings?: ReadonlyArray<string>;
117
+ /** The last round's critique, when there was one. */
118
+ lastCritique?: CriticAnswer;
119
+ }
120
+
121
+ /** One round's turn: the stable part (art direction, card, the reference's shots — cached), then the page, ours, the
122
+ * crops, the measures, the gate's findings, the last critique. */
123
+ export function criticRoundContent(input: CriticRoundInput, sheet: CritiqueSheet, layout = CriticSheetLayout.Cached): CriticContent[] {
124
+ const text = (t: string): CriticContent => ({ kind: CriticContentKind.Text, text: t });
125
+ const shot = (s: SheetPair['ours']): CriticContent => ({ kind: CriticContentKind.Image, ref: s.ref, w: s.w, h: s.h });
126
+ const page = text(`OUR PAGE: ${input.page} (${input.locale}). THE REFERENCE: ${input.reference}.`);
127
+ const out: CriticContent[] = [];
128
+ if (input.artDirection) out.push(text(`THE ART DIRECTION:\n${input.artDirection}`));
129
+ out.push(text(`THE REFERENCE'S CARD (its level, in words and numbers — not a design to copy):\n${input.referenceCard}`));
130
+ if (layout === CriticSheetLayout.Cached) {
131
+ out.push(text(`THE REFERENCE, ${input.reference}, view by view:`));
132
+ for (const p of sheet.pairs) out.push(text(`${where(p.width, p.view)} — the reference:`), shot(p.reference));
133
+ out[out.length - 1] = { ...out[out.length - 1], cache: true };
134
+ out.push(page, text('OUR PAGE, the same views:'));
135
+ for (const p of sheet.pairs) out.push(text(`${where(p.width, p.view)} — ours:`), shot(p.ours));
136
+ } else {
137
+ out.unshift(page);
138
+ for (const p of sheet.pairs) out.push(text(`${where(p.width, p.view)} — the reference:`), shot(p.reference), text(`${where(p.width, p.view)} — ours:`), shot(p.ours));
139
+ }
140
+ sheet.crops.forEach((c, i) => {
141
+ const head = `Crop ${i + 1}, ${c.why} (${where(c.width, c.view)}, ×${c.zoom})`;
142
+ if (c.reference) out.push(text(`${head} — the reference:`), { kind: CriticContentKind.Crop, ref: c.reference.ref, box: c.reference.box, zoom: c.zoom });
143
+ out.push(text(`${head} — ours:`), { kind: CriticContentKind.Crop, ref: c.ours.ref, box: c.ours.box, zoom: c.zoom });
144
+ });
145
+ if (input.measures?.length) out.push(text(`THE MEASURES (ours):\n${input.measures.join('\n')}`));
146
+ if (input.gateFindings?.length) out.push(text(`THE GATE'S FINDINGS:\n${input.gateFindings.join('\n')}`));
147
+ if (input.lastCritique) {
148
+ const v = criticVerdict(input.lastCritique);
149
+ out.push(text(`THE LAST ROUND'S CRITIQUE (headline ${v.headline.toFixed(1)}), to see what moved:\n${JSON.stringify(input.lastCritique)}`));
150
+ }
151
+ out.push(text('Score our page.'));
152
+ return out;
153
+ }
@@ -0,0 +1,24 @@
1
+ // GENERATED from iox-ai-guidance team/reference-score.md §2 by scripts/gen-critic-rubric.mjs — do not edit;
2
+ // re-run npm run gen:critic-rubric. The tester's rubric, ported for the AI designer's critic (ai-designer-plan §2d).
3
+ /* eslint-disable */
4
+
5
+ /** Where the rubric came from, and a hash of its section (a changed rubric is a new hash). */
6
+ export const CRITIC_RUBRIC_SOURCE = { file: 'team/reference-score.md', section: '§2', hash: "2556a8f755a1" } as const;
7
+
8
+ /** The eight dimensions in the rubric's order: the key the critic answers under, the name, what is compared. */
9
+ export const CRITIC_RUBRIC_DIMENSIONS: ReadonlyArray<{ readonly n: number; readonly key: string; readonly name: string; readonly compares: string }> = [
10
+ { n: 1, key: "colour", name: "Colour", compares: "ground colour, how much accent and where, dark bands vs grey-black, palette harmony. Numbers: dominant colours, ΔE to the nearest target palette, contrast" },
11
+ { n: 2, key: "type", name: "Type", compares: "the display face's character, hero size ÷ body size, weights, tracking, uppercase use. Numbers: hero px, ratio, families" },
12
+ { n: 3, key: "composition", name: "Composition", compares: "column width, whitespace rhythm, asymmetry and overlap, section variety (two sections in a row on one skeleton = a fault). Numbers: content width, section padding, distinct skeletons per page" },
13
+ { n: 4, key: "imagery", name: "Imagery", compares: "share of the screen that is picture, full-bleed use, crops, on-subject, no empty boxes. Numbers: picture area % per screen" },
14
+ { n: 5, key: "header", name: "Header", compares: "shape, behaviour on scroll, menu (shelves, full screen), how it sits on the opening picture" },
15
+ { n: 6, key: "footer", name: "Footer", compares: "layout, richness (newsletter, social, facts), ground, legal row" },
16
+ { n: 7, key: "motion", name: "Motion & feel", compares: "scroll scenes, reveals, hover, page transitions, smoothness on the phone" },
17
+ { n: 8, key: "polish", name: "Polish (UI bugs)", compares: "overlaps, clipped text, misalignment, broken 390 layout, contrast fails, placeholder text, empty boxes. Each bug −1. Any bug a visitor would call broken caps the whole score at 5. Every bug becomes a GitHub issue" },
18
+ ];
19
+
20
+ /** The headline rule, in the rubric's words. */
21
+ export const CRITIC_RUBRIC_HEADLINE = "Headline = the mean of 1–7, capped by 8. Every score has one sentence of evidence: \"hotelaurelia does X; ours does Y\", with the two crops side by side.";
22
+
23
+ /** The polish row's numbers: what each bug costs, and the cap a bug a visitor would call broken puts on the page. */
24
+ export const CRITIC_RUBRIC_POLISH = { bugPenalty: 1, brokenCap: 5 } as const;