8000 fix: harden CLI UX, browser crash handling, isolated declarations, and CI sharding by jangtrinh · Pull Request #455 · jangtrinh/design-os · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ on:
pull_request:

jobs:
check:
gates-and-shard-1:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
Expand All @@ -16,9 +16,10 @@ jobs:
cache: npm
- run: npm ci
- run: npm run typecheck
- run: npm run typecheck:workspaces
- run: npm run lint
- run: npm run build
- run: npm test
- run: npx vitest run --shard=1/2
- run: npm run proof:native-mobile
# The knowledge-core linter (spec 002 P2) — the "unit tier" for knowledge/.
# Runs the built binary against the repo's own knowledge/ so index/persona/
Expand All @@ -29,6 +30,34 @@ jobs:
# so drift fails here instead of shipping to the gallery.
- run: npm run verify:examples

test-shard-2:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run build
- run: npx vitest run --shard=2/2

# Branch protection on `main` strictly requires the status context `check`.
# Aggregating gates-and-shard-1 and test-shard-2 preserves this contract without
# renaming status checks to `check (1/2)` which would break branch protection.
check:
runs-on: ubuntu-latest
needs: [gates-and-shard-1, test-shard-2]
if: always()
steps:
- name: Verify parallel shards passed
run: |
if [ "${{ needs.gates-and-shard-1.result }}" != "success" ] || [ "${{ needs.test-shard-2.result }}" != "success" ]; then
echo "One or more parallel shards failed: gates-and-shard-1=${{ needs.gates-and-shard-1.result }}, test-shard-2=${{ needs.test-shard-2.result }}"
exit 1
fi
echo "All shards succeeded."

# figma-agent moved to its own repo (github.com/jangtrinh/design-os-figma-plugin) — it
# is no longer an in-repo npm workspace, so it has no job here; its own CI gates it.

Expand Down
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
# Changelog

## 2026-11-16 - CLI UX hardening, isolated declarations, and parallel CI shards

### Fixed
- **`ui ontology query` accepts CSS custom-property queries starting with `--`** (#444): `ui ontology query --mu-surface`
and `ui ontology query "--mu-surface"` now resolve as positional query text when no prior positional was given, while
preserving known options (`--dir`, `--area`, `--budget`, `--json`) and rejecting unknown flags alongside positionals
or values.
- **`ui ingest-css-ds` fails closed on inputs with zero custom properties** (#434): when `customProperties` is empty,
the command now exits 1 (`NO_TOKENS_WRITTEN`) without writing an empty `tokens.json` and points to checking `--css`
on `ui designmd extract-tokens`.
- **`package.json` `bin.ui` normalised to `"dist/cli.js"`** (#448): eliminates npm's publish-time `"bin[ui]" script name
was invalid` warning.
- **Headless browser signal-crash fast-fail & sandbox probes**: `openSession` in `src/core/rendered/browser-session.ts`
now detects signal exits (`child.signalCode`, e.g. `SIGABRT` in restricted containers) immediately instead of waiting
out the 20s debugger timeout, and both `tests/rendered-tier.test.ts` and `a11y/tests/has-chrome.ts` probe real
headless launchability before running browser suites.
- **Test isolation & CPU-contention stability** (#447): `tests/memory-autorecord.test.ts` bounds its orphan fixture with
a `.git` directory so `$TMPDIR` ancestry cannot leak a `design/` directory, and the 20,000-deep stack-safety test in
`tests/taste-checks-invisible-surface-edge-cases.test.ts` sets an explicit 30s timeout.

### Changed
- **`declarationMap` and `isolatedDeclarations` enabled on `ease-design/lint` (`tsconfig.dts.json`)**: emits
`dist/types/*.d.ts.map` source maps and enforces TypeScript 7 `isolatedDeclarations` across the public lint surface.
- **Workspace-wide `oxlint` gate and parallelized CI shards**: `npm run lint` now covers `a11y/`, `recall/`, and
`scripts/` with `--deny-warnings --report-unused-disable-directives`, and `.github/workflows/ci.yml` splits Vitest
across two parallel shards while preserving the required `check` status context.

## 2026-11-15 - TypeScript 7 toolchain, erasable syntax, and `ease-design/lint` declarations

### Added
Expand Down
46 changes: 35 additions & 11 deletions a11y/tests/has-chrome.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/
import { existsSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";

let cached: boolean | undefined;

Expand All @@ -17,19 +18,42 @@ export function hasChrome(): boolean {

function detect(): boolean {
// macOS
if (existsSync("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")) return true;
let foundCandidate = existsSync("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
// Windows
for (const p of [
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
]) {
if (existsSync(p)) return true;
if (!foundCandidate) {
for (const p of [
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
]) {
if (existsSync(p)) {
foundCandidate = true;
break;
}
}
}
// Linux / PATH — channel:chrome resolves google-chrome(-stable).
const which = process.platform === "win32" ? "where" : "which";
for (const bin of ["google-chrome", "google-chrome-stable", "chrome"]) {
const r = spawnSync(which, [bin], { encoding: "utf8" });
if (r.status === 0 && r.stdout.trim().length > 0) return true;
if (!foundCandidate) {
const which = process.platform === "win32" ? "where" : "which";
for (const bin of ["google-chrome", "google-chrome-stable", "chrome"]) {
const r = spawnSync(which, [bin], { encoding: "utf8" });
if (r.status === 0 && r.stdout.trim().length > 0) {
foundCandidate = true;
break;
}
}
}
return false;
if (!foundCandidate) return false;

// Verify that Playwright channel 'chrome' can actually launch in this environment
// (guards against unprivileged container sandbox restrictions or broken installs).
const probe = spawnSync(
process.execPath,
[
"--input-type=module",
"-e",
'import { chromium } from "playwright"; const b = await chromium.launch({ channel: "chrome", headless: true }); await b.close();',
],
{ cwd: fileURLToPath(new URL(".", import.meta.url)), encoding: "utf8", timeout: 10_000 },
);
return probe.status === 0;
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
},
"homepage": "https://github.com/jangtrinh/design-os#readme",
"bin": {
"ui": "./dist/cli.js"
"ui": "dist/cli.js"
},
"exports": {
"./lint": {
Expand Down Expand Up @@ -52,7 +52,7 @@
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
"typecheck:workspaces": "npm run typecheck --workspaces",
"lint": "oxlint -c .oxlintrc.json src tests",
"lint": "oxlint -c .oxlintrc.json --deny-warnings --report-unused-disable-directives src tests a11y/cli/src a11y/tests recall/cli/src recall/tests scripts",
"test": "vitest run",
"audit:mutation": "stryker run",
"personas:verify": "node scripts/derive-personas-json.mjs",
Expand Down
6 changes: 3 additions & 3 deletions src/adapters/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const WORKFLOW_VERBS = [
"evidence",
"guidelines",
"init",
] as const satisfies readonly string[];
] as const;

export type WorkflowVerb = (typeof WORKFLOW_VERBS)[number];

Expand Down Expand Up @@ -95,7 +95,7 @@ export const SKILL_NAMES = [
"native-macos-craft",
"native-ios-craft",
"native-ipados-craft",
] as const satisfies readonly string[];
] as const;

export type SkillName = (typeof SKILL_NAMES)[number];

Expand All @@ -109,7 +109,7 @@ export const JOURNEY_NAMES = [
"onboard",
"daily",
"deliver",
] as const satisfies readonly string[];
] as const;

export type JourneyName = (typeof JOURNEY_NAMES)[number];

Expand Down
12 changes: 8 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type { ParsedArgs } from "./core/cli-args.js";
import { errJson } from "./core/output.js";
import type { CommandResult } from "./core/output.js";
import { signatureFor } from "./core/command-signatures.js";
import { findUnknownFlag, unknownFlagMessage } from "./core/flag-guard.js";
import { findUnknownFlag, rescueDashPositional, unknownFlagMessage } from "./core/flag-guard.js";

import { colorCommand } from "./commands/color.js";
import { tokensCommand } from "./commands/tokens.js";
Expand Down Expand Up @@ -275,13 +275,17 @@ function dispatch(args: string[]): number | Promise<number> {
// no-opping. Unresolvable signatures (unknown subcommand, dispatcher without
// a subcommand) fall through to the command's own BAD_ARG handling.
const sig = signatureFor(parsed.command, parsed.subcommand);
const effectiveParsed =
sig !== null && parsed.command === "ontology" && parsed.subcommand === "query"
? rescueDashPositional(parsed, sig.flags.map((f) => f.name))
: parsed;
if (sig !== null) {
const unknown = findUnknownFlag(parsed.flags, sig.flags.map((f) => f.name));
const unknown = findUnknownFlag(effectiveParsed.flags, sig.flags.map((f) => f.name));
if (unknown !== null) {
const msg = unknownFlagMessage(unknown);
const label =
parsed.subcommand !== undefined ? `${parsed.command} ${parsed.subcommand}` : parsed.command;
const res = parsed.json
const res = effectiveParsed.json
? errJson(label, "UNKNOWN_FLAG", msg)
: { exitCode: 1, stderr: `ui: ${msg}\n` };
if (res.stdout !== undefined) stdout.write(res.stdout);
Expand All @@ -305,7 +309,7 @@ function dispatch(args: string[]): number | Promise<number> {
// an unhandled exception that dumps a stack trace to the terminal.
let result: CommandResult | Promise<CommandResult>;
try {
result = cmd.run(parsed) as CommandResult | Promise<CommandResult>;
result = cmd.run(effectiveParsed) as CommandResult | Promise<CommandResult>;
} catch (e) {
return internalError(e);
}
Expand Down
11 changes: 6 additions & 5 deletions src/commands/ingest-css-ds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,8 @@ Error codes:
BAD_JSON extract-tokens.json is not valid JSON, or missing customProperties[]
LEAF_COLLISION Two source custom properties strip to the same token path (D6) — fails
loudly with both source lines rather than merging or suffixing
NO_TOKENS_WRITTEN The input holds custom properties and none became a token (exit 1, nothing
written): the message states how many custom properties were read, every
reason the ledger shows with its count, the five largest selectors that
were not recognised (with their declaration counts) when there are any,
and the next action
NO_TOKENS_WRITTEN The input holds no custom properties, or none became a token (exit 1,
nothing written): the message states the cause and names the next action
WRITE_ERROR An output file could not be written
`;

Expand Down Expand Up @@ -108,6 +105,10 @@ function runIngest(parsed: ParsedArgs): CommandResult {
if (!Array.isArray(customProperties)) {
return err("BAD_JSON", `'${srcPath}' has no customProperties[] array — is this a 'ui designmd extract-tokens' output?`);
}
if (customProperties.length === 0) {
const message = "the input holds no custom properties, so no tokens could be written. Check the --css list given to 'ui designmd extract-tokens'.";
return useJson ? errJson(CMD, "NO_TOKENS_WRITTEN", message) : errText(`ui: ${message}\n`);
}

let result;
try {
Expand Down
8 changes: 5 additions & 3 deletions src/commands/ontology-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import type { ParsedArgs } from "../core/cli-args.js";
import { rescueDashPositional } from "../core/flag-guard.js";
import { okJson } from "../core/output.js";
import type { CommandResult } from "../core/output.js";
import { PendingStoreError } from "../core/owner-rulings/pending-store.js";
Expand All @@ -27,11 +28,12 @@ const STALE = "ONTOLOGY_STALE";

export function runOntologyQuery(parsed: ParsedArgs): CommandResult {
const json = parsed.json;
const ready = prepare(parsed, CMD, KNOWN);
const effective = rescueDashPositional(parsed, KNOWN);
const ready = prepare(effective, CMD, KNOWN);
if (isResult(ready)) return ready;
const text = parsed.positionals.join(" ");
const text = effective.positionals.join(" ");
if (wordsOf(text).length === 0) return fail(CMD, json, "BAD_ARG", `a query needs the task as text with at least one word, for example: ui ontology query ${shellQuote("sign in screen")}`);
const rawBudget = parsed.flags["budget"];
const rawBudget = effective.flags["budget"];
if (rawBudget !== undefined && !/^[1-9][0-9]*$/.test(String(rawBudget))) return fail(CMD, json, "BAD_ARG", `--budget '${String(rawBudget)}' must be a whole number of characters above 0`);
const budget = rawBudget === undefined ? DEFAULT_BUDGET : Number(rawBudget);

Expand Down
2 changes: 1 addition & 1 deletion src/commands/registry-refresh-code-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function refreshCodeSource(registry: Registry, refresh: CodeRefresh): Reg
}
let next: ComponentRecord;
if (held.provenance?.kind === "code") {
const { variants: _held, ...rest } = held; // eslint-disable-line @typescript-eslint/no-unused-vars
const { variants: _held, ...rest } = held;
next = { ...rest, provenance: { ...held.provenance, sourceRef: refresh.code.sourceRef, sha256: refresh.code.sha256 }, markup: refresh.markup, tokensUsed: [...refresh.tokens], ...(refresh.variants.length > 0 && { variants: [...refresh.variants] }) };
} else {
next = { ...held, code: refresh.code, tokensUsed: unionTokens(held.tokensUsed, refresh.tokens) };
Expand Down
1 change: 0 additions & 1 deletion src/core/a11y-checks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ export function checkViewportMetaPresent(html: string): A11yFinding[] {

// ── 4.1.2 / 2.4.4 Icon/emoji controls need an accessible name ──
const ICON_GLYPHS = "×✕✓✔▶◀▲▼☰≡⋮⋯…→←↑↓«»‹›⌄⌃✚+−✖☆★♥♡⚙🔍";
// eslint-disable-next-line no-misleading-character-class
const EMOJI_OR_GLYPH = new RegExp(`^(?:[\\p{Extended_Pictographic}\\uFE0F\\u200D${ICON_GLYPHS}\\s]|[\\u{1F1E6}-\\u{1F1FF}])+$`, "u");

/**
Expand Down
2 changes: 1 addition & 1 deletion src/core/content-checks-landing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,4 @@ export function checkFaviconMissing(html: string): LandingContentFinding[] {
}

/** The three, in the order they are documented. Composed into `allContentChecks`. */
export const landingContentChecks = [checkWindowAlert, checkSeoMetaMissing, checkFaviconMissing] as const;
export const landingContentChecks: readonly ((html: string) => LandingContentFinding[])[] = [checkWindowAlert, checkSeoMetaMissing, checkFaviconMissing];
4 changes: 2 additions & 2 deletions src/core/content-checks-voice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,12 @@ export function checkAphoristicCadence(facts: readonly DesignFact[]): VoiceFindi
}

/** All four, in a stable order. */
export const VOICE_CHECKS = [
export const VOICE_CHECKS: readonly ((facts: readonly DesignFact[]) => VoiceFinding[])[] = [
checkMarketingBuzzword,
checkEmDashOveruse,
checkTheaterSlopPhrase,
checkAphoristicCadence,
] as const;
];

export function checkVoice(facts: readonly DesignFact[]): VoiceFinding[] {
const out: VoiceFinding[] = [];
Expand Down
4 changes: 2 additions & 2 deletions src/core/content-checks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,8 @@ export function checkBareConfirmButton(html: string): ContentFinding[] {
* Adding a check here makes both consumers pick it up automatically (L4 lesson:
* fix mirror drift at the shared layer, not at each copy site).
*/
export const allContentChecks = [
export const allContentChecks: readonly ((html: string) => ContentFinding[])[] = [
checkLoremIpsum, checkPlaceholderCopy, checkPlaceholderName, checkClickHereLink, checkErrorCodeAlone,
checkAllCapsShout, checkExclamationOverload, checkInsensitiveTerms, checkPluralSHack, checkTextInImage,
checkBareConfirmButton, checkDumbPunctuation, ...landingContentChecks,
] as const;
];
2 changes: 1 addition & 1 deletion src/core/extractors/html/css-values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function parseColor(raw: string): ParsedColor | undefined {
const ROOT_PX = 16;

/** `16px`, `1rem`, `1.5em`, `0`. Viewport and percentage units are NOT guessed. */
export function parseLengthPx(raw: string, basePx = ROOT_PX): number | undefined {
export function parseLengthPx(raw: string, basePx: number = ROOT_PX): number | undefined {
const v = raw.trim().toLowerCase();
if (v === "0") return 0;
const m = /^(-?[\d.]+)(px|rem|em|pt)$/.exec(v);
Expand Down
22 changes: 22 additions & 0 deletions src/core/flag-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,25 @@ export function unknownFlagMessage(u: UnknownFlag): string {
const hint = u.suggestion !== undefined ? ` (did you mean '--${u.suggestion}'?)` : "";
return `unknown flag '--${u.flag}'${hint}. Run with -h to see accepted flags.`;
}

/**
* Promote a sole unknown boolean `--<name>` flag to `positionals[0]` when no
* positional was given yet (e.g. `ui ontology query --mu-surface`). Preserves
* unknown-flag rejection when a positional already exists, when a value was
* supplied (`--nope val`), when repeated, or for single-char short flags (`-x`).
*/
export function rescueDashPositional<T extends {
positionals: string[];
flags: Record<string, string | boolean>;
repeatedFlags: Set<string>;
}>(parsed: T, knownFlags: readonly string[]): T {
if (parsed.positionals.length > 0) return parsed;
const allowed = new Set<string>([...GLOBAL_FLAGS, ...knownFlags]);
const unknown = Object.keys(parsed.flags).filter((k) => !allowed.has(k));
if (unknown.length !== 1) return parsed;
const k = unknown[0] as string;
if (k.length <= 1 || parsed.flags[k] !== true || parsed.repeatedFlags.has(k)) return parsed;
const flags = { ...parsed.flags };
delete flags[k];
return { ...parsed, positionals: [`--${k}`], flags };
}
2 changes: 1 addition & 1 deletion src/core/registry-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export function statesToVariants(states: string[]): string[] {
/** Keys permitted at the registry root object (mirrors schema additionalProperties:false).
* Exported (stage-4 N6) so `design-system.ts`'s foreign-registry detection reuses this
* EXACT set — never a second, independently-invented schema. */
export const REGISTRY_ROOT_KEYS = new Set(["version", "components"]);
export const REGISTRY_ROOT_KEYS: Set<string> = new Set(["version", "components"]);

/** Keys permitted on a component record (mirrors schema additionalProperties:false). */
const COMPONENT_ALLOWED_KEYS = new Set([
Expand Down
5 changes: 4 additions & 1 deletion src/core/rendered/browser-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,10 @@ async function waitForDebugger(
const deadline = Date.now() + LAUNCH_TIMEOUT_MS;
let lastError = "browser did not open its debugger port";
while (Date.now() < deadline) {
if (child.exitCode !== null) throw new CdpError(`browser exited immediately (code ${child.exitCode})`);
if (child.exitCode !== null || child.signalCode !== null) {
const detail = child.signalCode !== null ? `signal ${child.signalCode}` : `code ${child.exitCode}`;
throw new CdpError(`browser exited immediately (${detail})`);
}
const port = requestedPort === 0 ? readActivePort(profileDir) : requestedPort;
if (port !== undefined) {
try {
Expand Down
Loading
Loading
0