First-use check catches cut-off and overlapping text on crowded web screens (GST-4152) (#4893)

A web build's first-use check now measures its most crowded screens
(most players, longest names, widest numbers) in a real browser and
refuses to send the try-it message while text there is cut off or
painted over other text.

Why: a party game passed a friendly three-player check, then shipped
names cut short and a badge on top of the score once eight people
joined.

Reader action: a web play spec now needs a `full_house` fixture, or
`"none: "`.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=testing
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p1/red-team#2 reader=red-team
Review-Finding: p2/outside-voice#1 reader=outside-voice
Review-Finding: p2/outside-voice#2 reader=outside-voice
Review-Finding: p2/outside-voice#3 reader=outside-voice
Review-Finding: p2/outside-voice#5 reader=outside-voice
Review-Finding: p2/adversarial-native#1 reader=adversarial-native
Review-Finding: p2/adversarial-native#2 reader=adversarial-native
Review-Finding: p2/adversarial-native#4 reader=adversarial-native
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-29 08:47:35 +00:00
1 parent 0b7af8acfd
commit b2e9522b2f
17 files changed
+603 -36

No files matched your search

+3 -1
View File
@@ -18,6 +18,7 @@ export interface AppCliArgs {
waitFor?: string;
waivers?: string;
stateFile?: string;
fullHouse?: boolean;
verbose: boolean;
json: boolean;
}
@@ -44,6 +45,7 @@ export function planApp(a: AppCliArgs): { states: AppState[]; notes: string[]; w
if (!a.within) throw new AppUsageError('NO_WITHIN', '--scope app needs --within <selector>', 'pass --within with the selector of the section you are building');
checkSelector('--within', a.within);
if (a.waitFor !== undefined) checkSelector('--wait-for', a.waitFor);
if (a.fullHouse && a.waitFor === undefined) throw new AppUsageError('FULL_HOUSE_NEEDS_WAIT', '--full-house needs --wait-for <selector>: a crowded screen may hold no list, so readiness is the selector that appears once every item has loaded', 'pass --wait-for with a selector that matches only when the crowded state has rendered');
if (a.urls.length && a.stateFile) throw new AppUsageError('BOTH_TARGETS', '--url and --state-file are two ways to name the states; pass one', 'put every URL in the state file, or drop it');
if (!a.urls.length && !a.stateFile) throw new AppUsageError('NO_TARGET', '--scope app needs --url <url> or --state-file <states.json>', 'pass the URL of each state to measure');
const bad = a.urls.find((u) => !/^https?:\/\/[^/]/.test(u));
@@ -67,7 +69,7 @@ export async function appMain(a: AppCliArgs, io: Io, deps: AppDeps = {}): Promis
io.err(usageLine(e));
return 3;
}
const r = await lintApp({ states: plan.states, within: plan.within, viewports: plan.viewports, waitFor: a.waitFor, waivers: plan.waivers, ...deps });
const r = await lintApp({ states: plan.states, within: plan.within, viewports: plan.viewports, waitFor: a.waitFor, waivers: plan.waivers, fullHouse: a.fullHouse, ...deps });
r.app.notes.unshift(...plan.notes);
for (const line of r.stderr) io.err(line);
if (a.verbose) for (const c of r.app.states) if (c.trace) { try { io.err(`gstack-design-lint: trace ${c.trace}:\n${fs.readFileSync(c.trace, 'utf8')}`); } catch (e) { io.err(`gstack-design-lint: trace ${c.trace} could not be read: ${(e as Error).message}`); } }
+3 -1
View File
@@ -57,6 +57,8 @@ export interface AppOptions {
readyMs?: number;
/** How long the engine waits for the section (or --wait-for) to match; 15000 by default. */
sectionWaitMs?: number;
/** --full-house: the states are crowded to the app's declared limits, so text-clipped and text-overlap run too. */
fullHouse?: boolean;
}
export interface AppCoverage { name: string; url: string; viewport: string; status: 'measured' | 'incomplete'; code: AppCode | 'OK'; matched: number; detail?: string; trace?: string }
@@ -165,7 +167,7 @@ async function lintState(state: AppState, opts: AppOptions, run: Runner, viewpor
}
const first = viewports[0];
const sized = (expression: string, v: Viewport, maxInline = 400_000): RenderStep => ({ kind: 'eval', expression, width: v.width, height: v.height, deviceScaleFactor: 1, mobile: false, maxInline });
const args = (v: Viewport) => JSON.stringify({ within, expect: state.expect ?? null, explicitWait: !!opts.waitFor, readyMs: opts.readyMs ?? READY_MS });
const args = (v: Viewport) => JSON.stringify({ within, expect: state.expect ?? null, explicitWait: !!opts.waitFor, readyMs: opts.readyMs ?? READY_MS, fullHouse: !!opts.fullHouse, waitFor: opts.fullHouse ? opts.waitFor ?? null : null });
const steps: RenderStep[] = [sized(appInstallScript(), first, 10), sized(appProbeScript('P.setup(P)'), first), ...viewports.map((v) => sized(appProbeScript(`P.measure(P, ${args(v)})`), v))];
const sectionWait = opts.sectionWaitMs ?? SECTION_WAIT_MS;
const waitFor = { expression: composedWaitExpression(opts.waitFor ?? within, opts.waitFor ? null : sectionWait), timeoutMs: sectionWait + (opts.waitFor ? 0 : 1_000) };
+140 -4
View File
@@ -34,7 +34,7 @@ export interface AppProbeResult {
export interface AppSetupReport { lostSheets: string[]; lostFonts: string[] }
export interface AppMeasureArgs { within: string; expect: string | null; explicitWait: boolean; readyMs: number }
export interface AppMeasureArgs { within: string; expect: string | null; explicitWait: boolean; readyMs: number; fullHouse?: boolean; waitFor?: string | null }
interface Run { node: Text; el: Element; block: Element; rects: DOMRect[]; top: number; bottom: number; left: number; lineTop: number; lineBottom: number }
@@ -334,6 +334,139 @@ export function glAppOverflow(P: AppProbes, root: Element, vw: number): AppProbe
return inner.slice(0, 3).map((h) => ({ rule: 'section-overflow', sentence: h.sentence + ' (over 1px)', locator: locOf(h.el), measured: h.m, threshold: 1 }));
}
/** The visible text inside root, controls included: each text node with its host element and line boxes. */
export function glAppText(P: AppProbes, root: Element): Array<{ host: Element; text: string; rects: DOMRect[] }> {
const { kids, cparent, shown } = P.H;
const out: Array<{ host: Element; text: string; rects: DOMRect[] }> = [];
const go = (n: Node): void => {
for (const c of kids(n)) {
if (c.nodeType === 3) {
const text = (c.textContent || '').replace(/\s+/g, ' ').trim();
const host = cparent(c);
if (!text || !host) continue;
const rg = document.createRange(); rg.selectNodeContents(c);
const rects = Array.from(rg.getClientRects()).filter((q) => q.width > 0 && q.height > 0);
if (rects.length) out.push({ host, text, rects });
} else if (c.nodeType === 1) {
const e = c as Element;
if (/^(SCRIPT|STYLE|TEMPLATE|NOSCRIPT)$/.test(e.tagName) || e.tagName === 'svg' || !shown(e)) continue;
go(e);
}
}
};
go(root);
return out;
}
/** text-clipped (--full-house only): inside root, an element that clips horizontally (overflow-x hidden or clip) and paints part of its own text past its edge; a visually hidden box (under 4px, or a clip or clip-path) is screen-reader text, never a cut. The innermost 50, so waivers applied later can't hide an unwaived cut behind three waived ones. */
export function glAppClipped(P: AppProbes, root: Element): AppProbeFinding[] {
const { desc, vis, locOf, px, inside } = P.H;
const hits: Array<{ el: Element; sentence: string; m: number }> = [];
for (const el of desc(root)) {
if (!vis(el)) continue;
const cs = getComputedStyle(el);
if (!/hidden|clip/.test(cs.overflowX) || el.scrollWidth <= el.clientWidth + 1) continue;
if (el.clientWidth < 4 || el.clientHeight < 4 || cs.clip !== 'auto' || cs.clipPath !== 'none') continue;
const b = el.getBoundingClientRect();
const left = b.left + el.clientLeft, right = left + el.clientWidth;
let total = 0, hidden = 0;
const words: string[] = [];
for (const t of P.text(P, el)) {
words.push(t.text);
for (const q of t.rects) { total += q.width; hidden += Math.min(q.width, Math.max(0, q.right - right) + Math.max(0, left - q.left)); }
}
if (!total) continue;
const cut = Math.max(hidden, cs.textOverflow === 'ellipsis' ? el.scrollWidth - el.clientWidth : 0);
if (cut <= 1) continue;
const shownPct = Math.max(0, Math.round(100 * (1 - cut / Math.max(total, el.scrollWidth))));
hits.push({ el, sentence: el.tagName.toLowerCase() + ' cuts off its text: ' + shownPct + '% of "' + words.join(' ').slice(0, 40) + '" shows, ' + px(cut) + 'px hidden', m: px(cut) });
}
const inner = hits.filter((h) => !hits.some((o) => o !== h && inside(o.el, h.el)));
return inner.slice(0, 50).map((h) => ({ rule: 'text-clipped', sentence: h.sentence + ' (over 1px)', locator: locOf(h.el), measured: h.m, threshold: 1 }));
}
/** text-overlap (--full-house only): inside root, the line boxes (a glyph box trimmed to its line-height) of two elements, neither inside the other, intersecting by over 2px both ways, where no opaque surface between them hides one. Clipped-away text never counts. A positioned child painted over its parent's own text counts. First 50 pairs, so waivers applied later can't hide an unwaived one. */
export function glAppOverlap(P: AppProbes, root: Element): AppProbeFinding[] {
const { cparent, inside, locOf, px, rgb } = P.H;
const clipBox = (el: Element): { l: number; t: number; r: number; b: number } => {
let l = -Infinity, t = -Infinity, r = Infinity, b = Infinity;
for (let e: Element | null = el; e && e !== document.documentElement; e = cparent(e)) {
const cs = getComputedStyle(e);
if (cs.overflowX === 'visible' && cs.overflowY === 'visible') continue;
const q = e.getBoundingClientRect();
const x0 = q.left + e.clientLeft, y0 = q.top + e.clientTop;
if (cs.overflowX !== 'visible') { l = Math.max(l, x0); r = Math.min(r, x0 + e.clientWidth); }
if (cs.overflowY !== 'visible') { t = Math.max(t, y0); b = Math.min(b, y0 + e.clientHeight); }
}
return { l, t, r, b };
};
const boxes: Array<{ host: Element; text: string; l: number; t: number; r: number; b: number }> = [];
for (const tb of P.text(P, root)) {
const c = clipBox(tb.host);
const lh = parseFloat(getComputedStyle(tb.host).lineHeight);
for (const q of tb.rects) {
const pad = Number.isFinite(lh) && lh < q.height ? (q.height - lh) / 2 : 0;
const box = { host: tb.host, text: tb.text, l: Math.max(q.left, c.l), t: Math.max(q.top + pad, c.t), r: Math.min(q.right, c.r), b: Math.min(q.bottom - pad, c.b) };
if (box.r - box.l > 1 && box.b - box.t > 1) boxes.push(box);
}
if (boxes.length > 2000) break;
}
boxes.sort((a, b) => a.l - b.l);
const covers = (top: Element, stop: Element, o: { l: number; t: number; r: number; b: number }, x: number, y: number): boolean => {
for (let e: Element | null = top; e && e !== stop; e = cparent(e)) {
const cs = getComputedStyle(e);
if (rgb(cs.backgroundColor)[3] < 0.9 && cs.backgroundImage === 'none') continue;
const q = e.getBoundingClientRect();
if (q.left > o.r || q.right < o.l || q.top > o.b || q.bottom < o.t) continue;
const overlay = !!fixedFrom(e, stop);
if (!overlay && q.width * q.height < 4 * (o.r - o.l) * (o.b - o.t)) continue;
const whole = q.left <= o.l + 1 && q.right >= o.r - 1 && q.top <= o.t + 1 && q.bottom >= o.b - 1;
if (!whole && !overlay && cs.position !== 'sticky') continue;
if (!layered(e, stop)) continue;
const hit = document.elementFromPoint(x, y);
if (!hit || hit === e || inside(hit, e)) return true;
}
return false;
};
const fixedFrom = (e: Element, stop: Element): Element | null => {
for (let n: Element | null = e; n && n !== stop; n = cparent(n)) if (getComputedStyle(n).position === 'fixed') return n;
return null;
};
const layered = (e: Element, stop: Element): boolean => {
for (let n: Element | null = e; n && n !== stop; n = cparent(n)) {
const cs = getComputedStyle(n);
if (cs.position !== 'static' || cs.transform !== 'none' || cs.filter !== 'none' || cs.isolation === 'isolate' || parseFloat(cs.opacity) < 1) return true;
}
return false;
};
const positionedBetween = (inner: Element, outer: Element): boolean => {
for (let e: Element | null = inner; e && e !== outer; e = cparent(e)) if (/^(absolute|fixed)$/.test(getComputedStyle(e).position)) return true;
return false;
};
const lca = (a: Element, b: Element): Element => { for (let e: Element | null = a; e; e = cparent(e)) if (inside(b, e)) return e; return root; };
const out: AppProbeFinding[] = [];
const seen = new Set<string>();
for (let i = 0; i < boxes.length && out.length < 50; i++) {
const a = boxes[i];
for (let j = i + 1; j < boxes.length && boxes[j].l < a.r && out.length < 50; j++) {
const b = boxes[j];
if (a.host === b.host) continue;
if (inside(a.host, b.host) && !positionedBetween(a.host, b.host)) continue;
if (inside(b.host, a.host) && !positionedBetween(b.host, a.host)) continue;
const w = Math.min(a.r, b.r) - Math.max(a.l, b.l), h = Math.min(a.b, b.b) - Math.max(a.t, b.t);
if (w <= 2 || h <= 2) continue;
const x = Math.max(a.l, b.l) + w / 2, y = Math.max(a.t, b.t) + h / 2;
const common = lca(a.host, b.host);
if (covers(a.host, common, b, x, y) || covers(b.host, common, a, x, y)) continue;
const key = locOf(a.host) + '|' + locOf(b.host);
if (seen.has(key)) continue;
seen.add(key);
out.push({ rule: 'text-overlap', sentence: '"' + a.text.slice(0, 24) + '" and "' + b.text.slice(0, 24) + '" are painted on top of each other (' + px(w) + 'x' + px(h) + 'px, over 2px)', locator: locOf(a.host), measured: px(Math.min(w, h)), threshold: 2 });
}
}
return out;
}
/** One state at one viewport: wait for the section and a list (or the caller's --wait-for), check the state's expect selector, then every app rule. */
export async function glAppMeasure(P: AppProbes, a: AppMeasureArgs): Promise<AppProbeResult> {
const { qAll, inside, roots, desc } = P.H;
@@ -342,6 +475,7 @@ export async function glAppMeasure(P: AppProbes, a: AppMeasureArgs): Promise<App
let matches: Element[] = [];
let lists: AppList[] = [];
let expectOk = true;
let waitOk = true;
let host: Element | undefined;
const closed = (scope: Element[]): Element | undefined =>
scope.flatMap((s) => desc(s)).find((e) => e.tagName.includes('-') && !e.shadowRoot && !e.children.length && !(e.textContent || '').trim() && e.getBoundingClientRect().height >= 40);
@@ -349,8 +483,9 @@ export async function glAppMeasure(P: AppProbes, a: AppMeasureArgs): Promise<App
matches = outermost(qAll(a.within));
lists = matches.flatMap((m) => P.lists(P, m));
expectOk = !a.expect || qAll(a.expect).length > 0;
waitOk = !a.waitFor || qAll(a.waitFor).length > 0;
host = matches.length && !lists.length ? closed(matches) : undefined;
if (host || (matches.length && (lists.length || a.explicitWait) && expectOk) || Date.now() - t0 > a.readyMs) break;
if (host || (matches.length && (lists.length || a.explicitWait) && expectOk && waitOk) || Date.now() - t0 > a.readyMs) break;
await new Promise((r) => setTimeout(r, 150));
}
const matched = qAll(a.within).length;
@@ -363,15 +498,16 @@ export async function glAppMeasure(P: AppProbes, a: AppMeasureArgs): Promise<App
}
if (host) return { ...base, status: 'incomplete', code: 'CLOSED_SHADOW', detail: '<' + host.tagName.toLowerCase() + '> inside ' + a.within + ' renders a closed shadow root the lint cannot read' };
if (!lists.length && !a.explicitWait) return { ...base, status: 'incomplete', code: 'NOT_READY', detail: 'no list of two or more rows appeared inside ' + a.within + ' within ' + Math.round(a.readyMs / 1000) + 's' };
if (!waitOk) return { ...base, status: 'incomplete', code: 'NOT_READY', detail: 'the --wait-for selector ' + a.waitFor + ' stopped matching at this viewport' };
if (!expectOk) return { ...base, status: 'incomplete', code: 'STATE_MISMATCH', detail: 'the state\'s expect selector ' + a.expect + ' matched nothing after readiness' };
const vw = innerWidth;
const findings: AppProbeFinding[] = [];
for (const l of lists) findings.push(...P.rows(P, l, vw), ...P.after(P, l, matches.find((m) => inside(l.container, m)) || l.container));
for (const m of matches) findings.push(...P.overflow(P, m, vw));
for (const m of matches) findings.push(...P.overflow(P, m, vw), ...(a.fullHouse ? [...P.clipped(P, m), ...P.overlap(P, m)] : []));
return { ...base, status: 'measured', findings };
}
const APP_FNS = { setup: glAppSetup, lists: glAppLists, rows: glAppRows, after: glAppAfter, overflow: glAppOverflow, measure: glAppMeasure };
const APP_FNS = { setup: glAppSetup, lists: glAppLists, rows: glAppRows, after: glAppAfter, overflow: glAppOverflow, text: glAppText, clipped: glAppClipped, overlap: glAppOverlap, measure: glAppMeasure };
export interface AppProbes extends AppFns { H: AppHelpers }
type AppFns = typeof APP_FNS;
+2
View File
@@ -178,6 +178,8 @@ export const RULES: Record<string, RuleMeta> = {
'note-in-row-weight': { tier: 'ask', gate: 'app', title: 'a note inside a row at the name\'s weight (no icon, no surface of its own, lightness within 0.15 and size 0.9 or more of the name\'s), or a note of three lines or more at 1200px and wider', fix: 'mute the note (a lighter ink and a smaller size than the name), or give it an icon or a callout of its own', render: true, app: true },
'small-hit-area': { tier: 'ask', gate: 'app', title: 'a control inside a list row under 32px in either dimension at a phone width (480px or less)', fix: 'make the target 32px or more (padding with a negative margin, or an inset ::before) and keep the visible glyph its size', render: true, app: true },
'section-overflow': { tier: 'ask', gate: 'app', title: 'an element inside the measured section runs past the viewport, or a non-scrolling element overflows its own box', fix: 'let it wrap or shrink (min-width: 0, overflow-wrap: anywhere), or give it a scrolling container', render: true, app: true },
'text-clipped': { tier: 'ask', gate: 'app', title: 'with --full-house, an element that clips sideways (overflow-x hidden or clip) paints part of its own text past its edge, as an ellipsis or a cut', fix: 'let the text wrap or shrink to fit the crowded state, give it a shorter form on purpose, or waive an intended truncation', render: true, app: true },
'text-overlap': { tier: 'ask', gate: 'app', title: 'with --full-house, the painted text of two elements, neither inside the other, overlaps by over 2px both ways with no opaque surface hiding one', fix: 'put the badge or label in the layout flow, or give each item room at the declared limit', render: true, app: true },
// ── The lint's own bookkeeping ──
'waiver': { tier: 'ask', gate: 'waiver', title: 'a waiver the lint refused', fix: 'fix the finding, or waive it with the rule id and a reason about this page' },
'house-style': { tier: 'polish', gate: 'waiver', title: 'more than three rules waived on one page', fix: 'lock the choices into DESIGN.md so later pages inherit them instead of re-arguing them' },
+44
View File
@@ -0,0 +1,44 @@
/**
* first-use-layout — `gstack-first-use layout`: measures the play spec's crowded screens (its full_house state file, frozen
* at start) with gstack-design-lint's app profile under --full-house, so text-clipped and text-overlap run with no model,
* and writes one write-once receipt bound to the build and the frozen files (docs/first-use-check.md). Only those two
* rules decide the receipt's verdict; the app profile's spacing rules stay advice for the builder's own lint runs. decide() in
* first-use.ts only reads the receipts; this module is the only part of the first-use check that starts a browser.
*/
import * as crypto from 'node:crypto';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { parseViewport } from './design-lint/app-input';
import { lintApp, type AppOptions } from './design-lint/render-app';
import { readManifest, type FirstUseError, type LayoutReceipt } from './first-use';
const VERSION_FILE = path.resolve(import.meta.dir, '..', 'VERSION');
export const FULL_HOUSE_RULES = ['text-clipped', 'text-overlap'];
export async function runLayout(dir: string, deps: Pick<AppOptions, 'engine' | 'run' | 'reach'> = {}, now: () => Date = () => new Date()): Promise<{ receipt: LayoutReceipt; file: string } | { error: FirstUseError; nothing?: true }> {
const read = readManifest(dir);
if ('error' in read) return read;
const m = read.manifest, fh = m.full_house;
if (!fh) return { nothing: true, error: { code: 'FIRST_USE_RECORD_INVALID', detail: `this run's play spec has no crowded screens to measure (full_house: ${typeof m.play.full_house === 'string' ? m.play.full_house : 'none'})` } };
const viewports = fh.viewports?.map(parseViewport);
const r = await lintApp({ states: fh.states_parsed, within: fh.within, waitFor: fh.wait_for, viewports, waivers: fh.waivers_parsed, fullHouse: true, ...deps });
let version = 'unknown';
try { version = fs.readFileSync(VERSION_FILE, 'utf8').trim(); } catch { /* not a checkout */ }
const ours = r.findings.filter(f => f.app && FULL_HOUSE_RULES.includes(f.rule));
const open = ours.filter(f => !f.waiver).length;
const verdict = r.app.verdict === 'incomplete' ? 'incomplete' : open ? 'open' : 'clean';
const at = now();
const receipt: LayoutReceipt = {
schema_version: 1, kind: 'first-use-layout', at: at.toISOString(), build_fingerprint: m.build.fingerprint, states_sha256: fh.states_sha256, waivers_sha256: fh.waivers_sha256,
viewports: r.app.viewports, within: fh.within, origins: [...new Set(fh.states_parsed.map(s => { try { return new URL(s.url).origin; } catch { return s.url; } }))], gstack_version: version,
verdict, code: verdict === 'incomplete' ? r.app.code : open ? 'OPEN' : 'OK', open, waived: ours.length - open,
findings: ours.map(f => ({ rule: f.rule, evidence: f.evidence, ...(f.app ? { locator: f.app.locator } : {}), ...(f.waiver ? { waiver: f.waiver } : {}) })),
incomplete: r.app.states.filter(s => s.status === 'incomplete').map(s => ({ state: s.name, viewport: s.viewport, code: s.code, detail: s.detail ?? '' })),
};
const file = path.join(dir, 'layout', `${at.toISOString().replace(/[-:]/g, '')}-${crypto.randomBytes(3).toString('hex')}.json`);
try {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, JSON.stringify(receipt, null, 2) + '\n', { flag: 'wx' });
} catch (e) { return { error: { code: 'FIRST_USE_RECORD_INVALID', detail: `cannot write ${file}: ${(e as Error).message}` } }; }
return { receipt, file };
}
+35 -4
View File
@@ -17,9 +17,15 @@ export interface PlayStep { text: string; writes: string; approved_write?: strin
export type ActionWrites = Omit<PlayStep, 'text'>;
/** Where the steps run: the owner's real setup, or a copy loaded with realistic data (the default), named exactly. */
export interface PlayTarget { kind: 'real' | 'realistic-copy'; name: string; data?: string }
/**
* The crowded screens gstack measures with no model (`gstack-first-use layout`): a design-lint state file whose URLs render
* each screen at the app's declared limits, the section to measure, the selector that appears once it has rendered, the
* limits in one line, and optional viewports and waivers (paths relative to the play spec). `"none: <reason>"` opts out.
*/
export interface FullHouse { states: string; within: string; wait_for: string; limits: string; viewports?: string[]; waivers?: string }
export interface PlaySpec {
links: PlayLink[]; device: string; setup: string; account: string; target: PlayTarget; what: string; start: string; steps: PlayStep[]; action_writes?: ActionWrites[];
controls: string; minutes: number; learn: string; report: string; quirks: string; reply_word: string;
controls: string; minutes: number; learn: string; report: string; quirks: string; reply_word: string; full_house?: FullHouse | string;
}
/** R47's ten parts in order, with the play-spec fields each one reads. */
export const PLAY_PARTS: Array<{ part: string; fields: Array<keyof PlaySpec> }> = [
@@ -42,7 +48,22 @@ const str = (v: unknown) => (typeof v === 'string' ? v.trim() : '');
* empty field is not. A step that writes on the owner's real setup needs `approved_write` naming his approval, and on that
* setup `action_writes` says what each of the five day-one actions writes, under the same rule.
*/
export function checkPlaySpec(raw: unknown): { spec: PlaySpec } | { error: FirstUseError } {
/**
* The play spec's `full_house`: required on a web build (a state file of crowded screens, or `"none: <reason>"`), and
* optional on other platforms, since the layout check reads a DOM; left out, the spec carries none.
*/
function checkFullHouse(v: unknown, platform: string | undefined): { value: FullHouse | string } | { bad: string } {
if (v === undefined) return platform === 'web' ? { bad: 'a web build names its crowded screens (states, within, wait_for, limits) or says "none: <reason>"' } : { value: 'none: not given' };
if (typeof v === 'string') return /^none:\s*\S/i.test(v.trim()) ? { value: v.trim() } : { bad: 'a string full_house must read "none: <reason>"' };
const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
const missing = (['states', 'within', 'wait_for', 'limits'] as const).filter(k => !str(o[k]));
if (missing.length) return { bad: `needs ${missing.join(', ')}` };
if (o.viewports !== undefined && !(Array.isArray(o.viewports) && o.viewports.length && o.viewports.every(x => typeof x === 'string' && /^\d{3,4}x\d{3,4}$/.test(x)))) return { bad: 'viewports must be a list like ["1920x1080"]' };
if (o.waivers !== undefined && !str(o.waivers)) return { bad: 'waivers must be a path' };
return { value: { states: str(o.states), within: str(o.within), wait_for: str(o.wait_for), limits: str(o.limits), ...(o.viewports ? { viewports: o.viewports as string[] } : {}), ...(str(o.waivers) ? { waivers: str(o.waivers) } : {}) } };
}
export function checkPlaySpec(raw: unknown, platform?: string): { spec: PlaySpec } | { error: FirstUseError } {
const o = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;
const bad = new Set<keyof PlaySpec>();
for (const f of TEXT_FIELDS) if (!str(o[f])) bad.add(f);
@@ -59,8 +80,10 @@ export function checkPlaySpec(raw: unknown): { spec: PlaySpec } | { error: First
if (!steps.length || !steps.every(s => !!str(s?.text) && !!str(s?.writes))) bad.add('steps');
const acts = o.action_writes === undefined ? undefined : Array.isArray(o.action_writes) ? o.action_writes as Array<Record<string, unknown>> : [];
if (acts ? acts.length !== 5 || !acts.every(a => !!str(a?.writes)) : kind === 'real') bad.add('action_writes');
if (bad.size) {
const fullHouse = checkFullHouse(o.full_house, platform);
if (bad.size || 'bad' in fullHouse) {
const parts = PLAY_PARTS.filter(p => p.fields.some(f => bad.has(f))).map(p => `${p.part} (${p.fields.filter(f => bad.has(f)).join(', ')})`);
if ('bad' in fullHouse) parts.push(`Full-house layout (full_house: ${fullHouse.bad})`);
return { error: { code: 'FIRST_USE_PLAY_SPEC_INCOMPLETE', detail: `missing or invalid: ${parts.join('; ')}` } };
}
const writesUnapproved = (s: Record<string, unknown>) => !/^none$/i.test(str(s.writes)) && !str(s.approved_write);
@@ -73,6 +96,7 @@ export function checkPlaySpec(raw: unknown): { spec: PlaySpec } | { error: First
target: { kind: kind as PlayTarget['kind'], name: str(t.name), ...(str(t.data) ? { data: str(t.data) } : {}) },
steps: steps.map(s => ({ text: str(s.text), ...writesOf(s) })),
...(acts ? { action_writes: acts.map(writesOf) } : {}),
...(o.full_house !== undefined ? { full_house: fullHouse.value } : {}),
...Object.fromEntries(TEXT_FIELDS.map(f => [f, str(o[f])])) as Omit<PlaySpec, 'links' | 'minutes' | 'target' | 'steps' | 'action_writes'>,
};
return { spec };
@@ -111,7 +135,9 @@ export function renderPlayMessage(d: Decision, now: Date = new Date()): string {
const oldest = Math.min(...d.links.map(l => Date.parse(l.checked_at)));
const ago = Math.max(0, Math.round((now.getTime() - oldest) / 60_000));
const notice = [...d.verdicts.filter(v => v.verdict === 'thin').map(v => `- Step ${v.n} is thin: ${v.line}`),
...d.verdicts.filter(v => v.notice).map(v => `- At step ${v.n} you'll see: ${v.notice}`)];
...d.verdicts.filter(v => v.notice).map(v => `- At step ${v.n} you'll see: ${v.notice}`),
...(d.layout?.findings ?? []).filter(x => x.waiver).map(x => `- On a crowded screen, ${x.rule === 'text-overlap' ? 'overlapping on purpose' : 'cut short on purpose'}: ${x.locator && x.evidence.endsWith(` at ${x.locator}`) ? x.evidence.slice(0, -` at ${x.locator}`.length) : x.evidence} (the builder's reason: ${x.waiver})`)];
const limits = d.layout && m.full_house ? [`**Checked at the limits:** the builder declared them as ${m.full_house.limits}; gstack measured those screens at ${d.layout.viewports.join(' and ')} and found no cut-off or overlapping text${d.layout.waived ? ` beyond the ${d.layout.waived} left on purpose above` : ''}.`, ''] : [];
const held = /^none$/i.test(m.holding.build) ? 'none yet: this is your first build of it.'
: `${m.holding.build}. Known defects in it: ${m.holding.defects}.`;
return [
@@ -119,6 +145,7 @@ export function renderPlayMessage(d: Decision, now: Date = new Date()): string {
`Every link was checked live at ${new Date(oldest).toISOString().slice(11, 16)} UTC, ${ago} min before this message.`, '',
`**What you'll notice:**`, ...(notice.length ? notice : ['- nothing beyond the known quirks above']), '',
`**The build on your device now:** ${held}`, '',
...limits,
`**Checked before it reached you:** an agent from another model family (${m.checker.model}) followed these exact steps on ${targetLabel(m.play.target)}, on a ${platformName[m.build.platform]} ${m.build.platform === 'ios' || m.build.platform === 'android' ? 'device' : 'setup'} like yours. One line per step:`,
...d.verdicts.map(v => `- ${v.n} (${v.verdict}): ${v.line}`),
'',
@@ -153,6 +180,10 @@ export function renderBrief(m: Manifest, dir: string): string {
"- Never send anything as the owner (no messages, mail or posts), and never write to the owner's real setup: a step that writes runs on the copy, except one whose approved_write below names his approval.",
"- Never raise a prompt, a permission dialog or a sign-in on the owner's own machine while he is at it.",
`- What you read is sent to your model provider (${m.checker.family}); stay inside the steps.`, '',
...(m.full_house ? ['## The crowded screens', '',
`The builder declared the app's limits as ${m.full_house.limits}. gstack measures those screens itself for cut-off and overlapping text, so you don't.${m.full_house.waivers_parsed.length ? ' Text the builder leaves cut short or overlapping on purpose (waived):' : ''}`,
...m.full_house.waivers_parsed.map(w => `- ${w.rule} at "${w.locator}": ${w.reason}`),
...(m.full_house.waivers_parsed.length ? ['', 'If one of these leaves the owner unable to tell what is going on when you meet it, say so in that step\'s verdict.'] : []), ''] : []),
'## The exact message the owner will get', '',
'~~~markdown', m.try_text.trimEnd(), '~~~', '',
`## The ${m.steps.length} steps you check (frozen ${m.created_at.slice(0, 10)})`, '',
+50 -7
View File
@@ -22,7 +22,9 @@ import * as os from 'node:os';
import * as path from 'node:path';
import { lineText, parseDayOne, parseOwnerWords, quoteGaps, quoteWhen } from './autoplan-owner-text';
import { resolveStateRoot } from './state-root';
import { checkPlaySpec, renderTryText, type PlaySpec } from './first-use-message';
import { checkPlaySpec, renderTryText, type FullHouse, type PlaySpec } from './first-use-message';
import { AppUsageError, parseStateFile, parseViewport, parseWaiverFile, type AppStateInput, type AppWaiver } from './design-lint/app-input';
import { ruleMeta } from './design-lint/rules/ids';
export const FIRST_USE_ACTIONS = 5;
export const LINK_FRESH_MS = 15 * 60 * 1000;
@@ -46,11 +48,19 @@ export interface FrozenAction { n: number; action: string; frequency: string; fe
export interface FrozenStep { n: number; kind: 'step' | 'action'; text: string; writes: string; approved_write?: string; check?: string; quote?: number }
export interface BuildId { platform: typeof PLATFORMS[number]; commit: string; testflight?: string; deploy?: string }
export interface Holding { build: string; defects: string }
/** The play spec's crowded screens as frozen at start: the parsed states and waivers with the hash of each file's bytes. */
export interface FrozenFullHouse extends FullHouse { states_parsed: AppStateInput[]; waivers_parsed: AppWaiver[]; states_sha256: string; waivers_sha256: string | null }
/** One `gstack-first-use layout` run: design-lint's --full-house verdict on the frozen states, bound to the build and the frozen files. */
export interface LayoutReceipt {
schema_version: 1; kind: 'first-use-layout'; at: string; build_fingerprint: string; states_sha256: string; waivers_sha256: string | null;
viewports: string[]; within: string; origins: string[]; gstack_version: string; verdict: 'clean' | 'open' | 'incomplete'; code: string; open: number; waived: number;
findings: Array<{ rule: string; evidence: string; locator?: string; waiver?: string }>; incomplete: Array<{ state: string; viewport: string; code: string; detail: string }>;
}
export interface Manifest {
schema_version: 2; kind: 'first-use-manifest'; app: string; created_at: string;
source: { path: string; rows_sha256: string }; quotes: FrozenQuote[]; actions: FrozenAction[]; steps: FrozenStep[];
try_text: string; try_sha256: string; build: BuildId & { fingerprint: string }; phone_build?: string; play: PlaySpec; holding: Holding;
builder: { model: string; family: string }; checker: { model: string; family: string };
builder: { model: string; family: string }; checker: { model: string; family: string }; full_house?: FrozenFullHouse;
}
export interface StepResult {
schema_version: 2; kind: 'first-use-result'; step: number; step_text: string; step_kind: FrozenStep['kind']; build_fingerprint: string; at: string;
@@ -162,7 +172,27 @@ function checkHolding(h: Partial<Holding> | undefined): Result<{ holding: Holdin
return { holding: { build, defects } };
}
export interface StartInput { root: string; app: string; planPath: string; build: Partial<BuildId>; phoneBuild?: string; play: unknown; holding: Partial<Holding>; builder: string; checker: string; now?: Date }
/** Reads and parses the play spec's state file and waivers (relative to the play spec), so the layout check measures exactly what start saw. */
function freezeFullHouse(fh: FullHouse, playDir: string): Result<{ frozen: FrozenFullHouse }> {
const read = (rel: string, what: string): Result<{ text: string }> => {
try { return { text: fs.readFileSync(path.resolve(playDir, rel), 'utf8') }; } catch { return fail('FIRST_USE_PLAY_SPEC_INCOMPLETE', `full_house.${what} ${rel} can't be read (paths are relative to the play spec)`); }
};
const states = read(fh.states, 'states');
if ('error' in states) return states;
const waivers = fh.waivers ? read(fh.waivers, 'waivers') : undefined;
if (waivers && 'error' in waivers) return waivers;
try {
(fh.viewports ?? []).forEach(parseViewport);
const parsed = parseStateFile(states.text);
const waived = waivers ? parseWaiverFile(waivers.text, id => !!ruleMeta(id)?.app) : [];
return { frozen: { ...fh, states_parsed: parsed.states, waivers_parsed: waived, states_sha256: sha256(states.text), waivers_sha256: waivers ? sha256(waivers.text) : null } };
} catch (e) {
if (e instanceof AppUsageError) return fail('FIRST_USE_PLAY_SPEC_INCOMPLETE', `full_house: ${e.code}: ${e.message} | fix: ${e.fix}`);
throw e;
}
}
export interface StartInput { root: string; app: string; planPath: string; build: Partial<BuildId>; phoneBuild?: string; play: unknown; playDir?: string; holding: Partial<Holding>; builder: string; checker: string; now?: Date }
/** Freezes the owner's quotes, the steps and the try-it text, and writes the run's manifest once; returns the run directory. */
export function startRun(o: StartInput): Result<{ dir: string; manifest: Manifest }> {
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(o.app)) return fail('FIRST_USE_RECORD_INVALID', '--app must be a lowercase slug like ghome');
@@ -170,8 +200,11 @@ export function startRun(o: StartInput): Result<{ dir: string; manifest: Manifes
try { planText = fs.readFileSync(o.planPath, 'utf8'); } catch { return fail('FIRST_USE_PLAN_UNREADY', `cannot read ${o.planPath}`); }
const frozen = freezeActions(planText);
if ('error' in frozen) return frozen;
const play = checkPlaySpec(o.play);
const play = checkPlaySpec(o.play, o.build.platform);
if ('error' in play) return play;
const fh = play.spec.full_house;
const fullHouse = fh && typeof fh === 'object' ? freezeFullHouse(fh, o.playDir ?? process.cwd()) : undefined;
if (fullHouse && 'error' in fullHouse) return fullHouse;
const build = buildFingerprint(o.build);
if ('error' in build) return build;
const phone = build.platform === 'ios' || build.platform === 'android';
@@ -188,7 +221,8 @@ export function startRun(o: StartInput): Result<{ dir: string; manifest: Manifes
];
const base = { schema_version: 2 as const, kind: 'first-use-manifest' as const, app: o.app, created_at: now.toISOString(),
source: { path: path.resolve(o.planPath), rows_sha256: frozen.rows_sha256 }, quotes: frozen.quotes, actions: frozen.actions, steps,
build, ...(phone ? { phone_build: o.phoneBuild } : {}), play: play.spec, holding: holding.holding, builder: { model: o.builder, family: builder }, checker: { model: o.checker, family: checker } };
build, ...(phone ? { phone_build: o.phoneBuild } : {}), play: play.spec, holding: holding.holding, builder: { model: o.builder, family: builder }, checker: { model: o.checker, family: checker },
...(fullHouse ? { full_house: fullHouse.frozen } : {}) };
const try_text = renderTryText(base);
const manifest: Manifest = { ...base, try_text, try_sha256: sha256(try_text) };
const dir = path.join(o.root, o.app, `${stamp(now)}-${build.fingerprint.slice(0, 8)}`);
@@ -327,7 +361,7 @@ function readDir<T>(dir: string): { rows: T[]; unreadable: string[] } {
const newest = <T extends { at?: string; checked_at?: string }>(rows: T[]) => [...rows].sort((a, b) => (a.at ?? a.checked_at ?? '').localeCompare(b.at ?? b.checked_at ?? '')).at(-1);
export interface StepVerdict { n: number; kind: FrozenStep['kind']; text: string; verdict: Verdict; line: string; notice?: string }
export interface Decision { ok: boolean; reasons: string[]; manifest?: Manifest; passed: number; verdicts: StepVerdict[]; links: LinkReceipt[]; prediction?: Prediction; owner?: OwnerScore }
export interface Decision { ok: boolean; reasons: string[]; manifest?: Manifest; passed: number; verdicts: StepVerdict[]; links: LinkReceipt[]; prediction?: Prediction; owner?: OwnerScore; layout?: LayoutReceipt }
/**
* Whether this run clears the build about to be sent: the same build, unchanged day-one rows and quotes, a newest result
* with intact evidence for every step on the play spec's target, none wrong, broken or needing something an agent could
@@ -377,8 +411,17 @@ export function decide(dir: string, build: Partial<BuildId>, now: Date = new Dat
if (r.verdict !== 'live') reasons.push(`link_down: ${link.url} (status ${r.status || r.error || 'none'})`);
else if (now.getTime() - Date.parse(r.checked_at) > LINK_FRESH_MS) reasons.push(`link_stale: ${link.url} was checked at ${r.checked_at}, over 15 minutes ago`);
}
const fh = m.full_house;
const layoutDir = fh ? readDir<LayoutReceipt>(path.join(dir, 'layout')) : undefined;
if (layoutDir?.unreadable.length) reasons.push(`record_unreadable: layout/${layoutDir.unreadable.join(', layout/')}`);
const layout = fh && layoutDir ? newest(layoutDir.rows.filter(x => x.kind === 'first-use-layout' && x.build_fingerprint === m.build.fingerprint
&& x.states_sha256 === fh.states_sha256 && x.waivers_sha256 === fh.waivers_sha256)) : undefined;
if (fh && !layout) reasons.push(`full_house_unchecked: measure the crowded screens (${fh.limits}) with gstack-first-use layout --run <dir>`);
else if (layout?.verdict === 'open') reasons.push(`full_house_open: ${layout.open} cut-off or overlapping text at the declared limits; first: ${layout.findings.find(x => !x.waiver)?.evidence ?? 'see gstack-first-use layout'}`);
else if (layout?.verdict === 'incomplete') reasons.push(`full_house_incomplete: ${layout.code}: ${layout.incomplete[0] ? `${layout.incomplete[0].state} at ${layout.incomplete[0].viewport} was not measured (${layout.incomplete[0].detail})` : 'nothing was measured'}`);
else if (layout && layout.verdict !== 'clean') reasons.push(`full_house_unchecked: the newest layout record has no clean, open or incomplete verdict (${String(layout.verdict)}); rerun gstack-first-use layout --run <dir>`);
const prediction = readJson<Prediction>(path.join(dir, 'prediction.json'));
if (!prediction) reasons.push('no_predicted_score');
const owner = newest(readDir<OwnerScore>(path.join(dir, 'owner')).rows);
return { ok: reasons.length === 0, reasons, manifest: m, passed, verdicts, links, prediction, owner };
return { ok: reasons.length === 0, reasons, manifest: m, passed, verdicts, links, prediction, owner, ...(layout ? { layout } : {}) };
}