mirror of
https://github.com/nexu-io/open-design.git
synced 2026-06-01 03:14:35 +07:00
* feat(runtimes): register AMR (vela) as an ACP stdio agent
AMR is the vela CLI's ACP runtime mode. `vela agent run --runtime opencode`
speaks ACP JSON-RPC over stdio (see vela's
`specs/current/runtime/manual-agent-run-openrouter.md`); per
`docs/new-agent-runtime-acp.md` we expose it through the same `streamFormat:
'acp-json-rpc'` transport that already powers Hermes, Devin, Kimi, etc.
The new `defs/amr.ts` is the entire wiring — `buildArgs` returns
`['agent', 'run', '--runtime', 'opencode']`, `fetchModels` reuses
`detectAcpModels`, and the fallback list seeds the OpenRouter ids vela's
e2e baseline uses. `executables.ts`/`app-config.ts`/`metadata.ts` get the
matching `VELA_BIN`/`VELA_LINK_URL`/`VELA_RUNTIME_KEY`/`VELA_OPENCODE_BIN`
allowlist + install/docs URLs, so users can configure the per-agent env in
Settings without leaking into other adapters.
Coverage: `tests/fixtures/fake-vela.mjs` is a minimal ACP stub that returns
the documented `initialize` / `session/new` / `session/set_model` /
`session/prompt` shapes; `tests/amr-acp-integration.test.ts` spawns it via
`child_process.spawn` and drives a full turn through `attachAcpSession` and
`detectAcpModels`, so the ACP transport contract for AMR is end-to-end
verified locally even before a real `vela` binary is installed.
Validated:
- pnpm guard
- pnpm typecheck (all workspace projects)
- pnpm --filter @open-design/daemon test (2881/2881)
Deferred: real OpenRouter-backed turn through a built `vela` binary —
the runtime def needs no changes for that path, only `VELA_RUNTIME_KEY`
and `VELA_LINK_URL` in env (or Settings).
* fix(runtimes/amr): pin a concrete default model and bare openai ids
End-to-end validation against a freshly-built `vela` (nexu-io/vela@main)
+ OpenRouter surfaced two contract details the first AMR runtime def
got wrong:
1. vela rejects `session/prompt` with `session/set_model must be called
before session/prompt`. attachAcpSession in apps/daemon/src/acp.ts
skips set_model whenever the picked model is the synthetic 'default'
id, so AMR's fallback list must NOT include DEFAULT_MODEL_OPTION. The
def now ships a concrete `gpt-5.4-mini` as both `fetchModels`'
default option and `fallbackModels[0]`, which makes attachAcpSession
always send a real `session/set_model` for AMR turns.
2. `vela --runtime opencode` auto-prepends `openai/` to whatever modelId
it forwards to opencode's openai provider. With OpenRouter-style ids
like `openai/gpt-5.4-mini`, opencode receives the double-prefixed
`openai/openai/gpt-5.4-mini` and replies `ProviderModelNotFoundError`.
The new fallback list ships the bare ids opencode's openai registry
actually knows about (gpt-5.4, gpt-5.4-mini, gpt-5.4-fast, etc.).
Stub + tests:
- tests/fixtures/fake-vela.mjs now enforces the set_model gate the same
way real vela does, so a regression that silently goes back to
model: 'default' would surface as a fatal error in tests instead of a
hidden production failure.
- tests/amr-acp-integration.test.ts pins both contracts: no 'default' /
no 'openai/' prefix in fallbackModels, and a negative case that
asserts session/prompt fails when no model is set.
Adds `apps/daemon/scripts/verify-amr-real-vela.mjs` — a small dev-time
runner that drives `attachAcpSession` against a real `vela` binary and
prints the daemon's chat events, so future protocol drift can be checked
against an actual OpenRouter call.
Verified locally: `vela agent run --runtime opencode` + OpenRouter
returns the prompted string ("AMR-E2E-PASS") through the full daemon
pipeline; daemon test suite stays 2883/2883.
* fix(runtimes/amr): substitute concrete model when chat run sends 'default'
A plugin-driven AMR run from the UI surfaced a real-world hole in the
prior commit:
json-rpc id 3: session/set_model must be called before session/prompt
The Default-design-router plugin (and any caller that doesn't pin a
real model) sends `model: 'default'` straight through, which the AMR
runtime def cannot accept — vela rejects `session/prompt` without
`session/set_model` and attachAcpSession skips set_model whenever
model === 'default'. Just leaving DEFAULT_MODEL_OPTION out of the
adapter's `fallbackModels` is not enough: the chat-run handler in
server.ts still forwarded 'default' verbatim.
This adds `resolveModelForAgent(def, resolved, env?)` as the
single source of truth for the substitution:
1. If the caller picked a real id, pass it through.
2. Else, if `def.defaultModelEnvVar` is set and the daemon process
env has a non-empty value for it, return that (operator escape
hatch — see below).
3. Else, if the def's `fallbackModels` does NOT contain a 'default'
id, return `fallbackModels[0].id`.
4. Else, return the original value (the historic shape — defs that
list 'default' themselves are untouched).
AMR sets `defaultModelEnvVar: 'VELA_DEFAULT_MODEL'`, so when
opencode's openai-provider registry deprecates `gpt-5.4-mini`
upstream, an operator can swap the fallback id without a code change
by exporting `VELA_DEFAULT_MODEL=gpt-5.5` before launching tools-dev
/ od. Worth noting the env var must live in the daemon's `process.env`
(Settings-UI per-agent env values only reach the spawned child, not
the daemon's resolver) — the new field's docblock spells this out.
Coverage:
- `tests/runtimes/resolve-model.test.ts` — 8 unit tests covering all
four resolver branches plus the env-override happy path / fallback /
ignore-when-user-picked-a-real-id case.
- `pnpm --filter @open-design/daemon typecheck` clean.
* chore(runtimes/amr): move AMR to the top of the base agent list
So `AMR (vela)` shows up first in the agent picker / status views,
ahead of claude / codex. Pure ordering change; no behavior delta.
* feat(amr): Sign-in / Sign-out button on the AMR Settings card
The first half of the AMR work assumed the operator would set
VELA_RUNTIME_KEY / VELA_LINK_URL on the daemon process and never
surfaced login state to users. This adds the missing UX so a fresh
install can drive the full path from Settings:
- GET /api/integrations/vela/status reads ~/.vela/config.json
for the active profile and returns { loggedIn, profile, user }
(without leaking the runtime/control keys themselves).
- POST /api/integrations/vela/login spawns `vela login` once
(409 if one is already in flight). The vela CLI opens the user's
browser to the device-authorization page itself — Open Design
only needs to kick the subprocess off.
- POST /api/integrations/vela/logout removes ~/.vela/config.json
so the next status read returns logged-out.
`AmrAgentCard` is a dedicated agent-card component for AMR because
the existing `<button>` row can't host an interactive sub-control
(nested interactive elements). It polls /status after a login click
until the daemon reports loggedIn=true (or 5 minutes elapse), and
exposes a Sign-out action on hover. Other adapters (claude, codex,
hermes, …) keep their existing `<button>` card.
i18n: 8 new keys (settings.amrLogin / Logout / LoggingIn / etc.)
added to en + zh-CN. Other locales spread `en` and inherit the
English copy until translations land.
Coverage:
- `tests/integrations/vela.test.ts` pins the config.json reader
against a tmp HOME — including the negative case where a profile
has user info but no runtimeKey (still logged-out), and the
secret-leak guard ("rt-secret-*" must not appear in the projection
payload).
- `tests/components/AmrAgentCard.test.tsx` covers all four UI
states (logged-out, logging-in, logged-in, logging-out) plus the
click-propagation invariant the divergent card was built to keep.
`pnpm --filter @open-design/daemon test` 2901 / 2901 passing.
`pnpm --filter @open-design/web test` 1719 / 1719 passing.
`pnpm typecheck` + `pnpm guard` clean.
Dev script side-effects: `apps/daemon/scripts/verify-amr-real-vela.mjs`
no longer requires both VELA_RUNTIME_KEY and VELA_LINK_URL — if
VELA_PROFILE is set, the vela CLI is allowed to resolve credentials
from `~/.vela/config.json`. Added the two AMR `.mjs` fixtures to
`scripts/guard.ts` allowlist with the executable-fixture / dev-runner
rationale.
* fix(connection-test): substitute model for AMR before attachAcpSession
The chat-run path in server.ts already routes the requested model through
`resolveModelForAgent` so AMR / vela (whose CLI demands an explicit
`session/set_model` before `session/prompt`) gets the def's first
concrete fallback id when the chat run ships `model: 'default'`.
`connectionTest.ts` was wiring `attachAcpSession({ ..., model: model ?? null })`
directly, which made the Test Connection button on the AMR Settings
card deadlock with the same `session/set_model must be called before
session/prompt` error the chat-run path already handles — surfaced as a
permanent "Testing connection…" spinner in the UI.
Reuse the same helper here so Test Connection mirrors chat-run behavior.
* test(amr): three-layer end-to-end coverage for the AMR login + turn flow
The PR up to this point shipped runtime + UI code with unit-level Vitest
coverage. This commit adds the cross-layer regression net the live demo
relied on:
1. apps/daemon/tests/integrations/vela.routes.test.ts (HTTP, Vitest)
Spins up the real daemon Express app via `startServer({port:0,...})`,
persists `agentCliEnv.amr.VELA_BIN = <fake>` into app-config.json,
and exercises every /api/integrations/vela/* endpoint against the
extended fake-vela stub:
- status reads ~/.vela/config.json under various states
- login spawns the fake, waits for config.json to appear, returns
pid + startedAt + profile
- 409 already-running guard with the stub's delay knob
- logout removes the file (idempotent)
- secrets (runtimeKey / controlKey) never leak in the projection
- login → status round-trip flips loggedIn=false → true
2. e2e/tests/amr/turn.test.ts (tools-dev orchestrated, Vitest)
Boots a namespaced daemon + web pair through `createSmokeSuite`,
inlines a self-contained fake `vela` binary that handles BOTH
`vela login` (writes ~/.vela/config.json) and
`vela agent run --runtime opencode` (ACP stdio with the
`session/set_model must precede session/prompt` gate the real binary
enforces), then drives a complete /api/runs lifecycle for
`agentId: 'amr', model: 'default'` and asserts the assistant message
captures the fake's streamed text. This is the test that would have
surfaced today's plugin-default-model regression (the `set_model
before prompt` error) at PR time instead of demo time.
3. e2e/ui/amr-login-pill.test.ts (Playwright)
Mocks /api/agents + /api/integrations/vela/{status,login,logout}
to drive the Settings AMR card through the full Sign in → Signed in
→ Sign out cycle. Pins the AmrLoginPill polling contract and the
aria-label semantics (the pill's accessible name is "Sign out" once
logged in, regardless of which label the hover-state text shows).
fake-vela.mjs extensions:
- Handles `vela login` argv by writing
~/.vela/config.json for the active VELA_PROFILE and exiting 0 —
mirrors real vela's on-disk side-effect without the device-auth
loop.
- FAKE_VELA_LOGIN_DELAY_MS knob so route tests can observe the
in-flight state of the spawn lifecycle.
- FAKE_VELA_LOGIN_USER_EMAIL / _USER_PLAN to assert the surfaced
user fields end-to-end.
Validated:
- `pnpm guard` + `pnpm typecheck` (all workspace projects)
- `pnpm --filter @open-design/daemon test`: 2998 / 2998 passing,
including the new 8-test integration suite.
- `cd e2e && pnpm test tests/amr`: 1 / 1 passing.
- `cd e2e && pnpm exec playwright test ui/amr-login-pill.test.ts`:
1 / 1 passing (6.7s).
* feat(amr): package native cli and refine login ui
* feat(amr): wire vela cli beta packaging
* docs(amr): document vela ci packaging review
* docs(amr): refine vela ci integration review
* fix(ci): refresh nix pnpm dependency hashes
* fix(pack): clean up Vela CLI packaging
* fix(pack): bundle Vela CLI support files
* fix(amr): recover login attempts from stale auth state
* test: expand AMR and automations coverage
* fix(amr): address review follow-ups
* test(web): align tasks fixtures with contracts
* fix(daemon): type wildcard route params
* fix(ci): refresh PR merge validation
* fix(amr): clear env credentials on logout
* feat(settings): inline local CLI model configuration
* fix(amr): recognize daemon env credentials
* [codex] Fix Vela companion packaging (#2979)
* Fix Vela companion packaging
* Update Nix pnpm dependency hashes
* [codex] Surface AMR account failures (#2980)
* fix: surface AMR account failures
* fix: cover AMR recovery error guidance
* chore: bump beta base version to 0.8.1 (#2990)
* Fix AMR profile and packaged runtime review issues
* Detect packaged AMR OpenCode companion tree
* feat(web): polish AMR frontend flows
* Polish AMR onboarding card
* fix: read AMR login state from dot-amr config (#3048)
* test: tighten AMR credential and packaging coverage
* test: restore AMR executable test env helper
* [codex] Fix packaged mac Dock identity and AMR label (#3076)
* Fix packaged mac sidecar Dock identity
* Rename AMR assistant label
* Fix AMR live models and dot-amr login state (#3073)
* fix: read AMR login state from dot-amr config
* fix: load live AMR models before runs
* fix: point AMR onboarding link to production wallet
* fix: address AMR model review feedback
* fix: persist live AMR model fallback
* [codex] Fix AMR link catalog model ids (#3088)
* Fix packaged mac sidecar Dock identity
* Rename AMR assistant label
* Fix AMR link catalog model ids
* Fix AMR model normalization typecheck
* Use live AMR model for default runs
* fix: polish AMR runtime settings UI
* Accelerate AMR startup defaults (#3092)
* Surface AMR insufficient balance wallet URL (#3099)
* fix(web): polish onboarding controls (#3112)
* fix(web): show CLI scan loading state
* Avoid duplicate AMR wallet recharge links (#3117)
* Avoid duplicate AMR wallet recharge links
* Use Vela CLI 0.0.3 test package
* chore(nix): refresh pnpm deps hash
* Fix AMR wallet guidance display
---------
Co-authored-by: open-design-bot[bot] <282769551+open-design-bot[bot]@users.noreply.github.com>
* chore(pack): pin Vela CLI 0.0.3-test.1 (#3127)
* chore(nix): refresh pnpm deps hash
* chore(pack): pin Vela CLI 0.0.3
* chore(nix): refresh pnpm deps hash
* fix(web): suppress AMR exit 130 fallback (#3136)
* feat(web): nudge users to hosted AMR on model/auth/quota failures (#3083)
* feat(web): nudge users to hosted AMR on model/auth/quota failures
When a non-AMR agent run fails with an auth / quota / upstream model
error, surface an inline nudge under the error pill linking to Open
Design's hosted AMR gateway (https://open-design.ai/amr). The nudge
fires `surface_view` (element=run_failed_toast) on impression and
`ui_click` (element=go_amr) on the link.
Also teach the daemon to classify CLI-agent auth/quota/upstream failures
(Claude Code, codex, ...) into specific API error codes
(AGENT_AUTH_REQUIRED / RATE_LIMITED / UPSTREAM_UNAVAILABLE) instead of
the generic AGENT_EXECUTION_FAILED, so both the error message and the
nudge key off accurate codes. AMR's own runs are excluded from the
nudge — they keep the dedicated sign-in / recharge affordances.
* feat(web): rework failed-run AMR guidance into per-case error UI
Replace the single inline nudge with a per-case failed-run experience
driven by the run's error code + agent:
- The error card is now neutral gray (was red) and always carries a
retry button; it is driven by the persisted per-message error event so
it survives a reload.
- Non-AMR agent hitting a model/auth/quota wall: a theme-color promotion
card under the error card offers "switch to AMR & retry" — switches the
run to AMR, opens Settings on the AMR card, and auto-retries once the
account signs in (ProjectView polls vela login status, independent of
the Settings pill lifecycle, with success / 5-min-timeout / unmount
exits).
- AMR agent unauthorized: clearer copy + an "authorize & retry" button.
- AMR agent out of balance: clearer copy + a "top up" button to the AMR
wallet, with manual retry.
- Settings AMR card: when opened from the nudge, it scrolls into view and
pulses, and an authorize-button coachmark (a fake hand cursor that
rises in and dismisses on hover) points at the sign-in control when not
yet authorized.
analytics: surface_view (run_failed_toast) on the promotion card and
ui_click (go_amr) on its action are retained. i18n adds chat.amrCard.*
and chat.amrError.* (en / zh-CN / zh-TW translated; other locales fall
back to en) and drops the old chat.amrErrorGuidance keys.
* fix(daemon): require status context for numeric service-failure codes
Per review on #3083: the model-service classifier matched bare HTTP
status numbers (`500`, `502`, `429`, `401`), so ordinary CLI output like
`line 500`, `read 502 bytes`, or `exit code 401` could be misclassified
as a provider outage / auth wall and wrongly surface the AMR nudge. Now
a status number only counts when it carries explicit context (`HTTP 500`,
`status 503`, `code: 401`, `502 Bad Gateway`); textual provider phrases
(overloaded, bad gateway, service unavailable, rate limit, …) are
unchanged. Adds fixtures proving unrelated numeric output stays null.
* fix(web): keep error pill for failed runs ChatPane's card doesn't cover
Per review on #3083: the per-message gray error pill was suppressed for
every persisted error status event, but ChatPane only renders the
replacement top-level error card for `retryableAssistantMessage` (the
last failed assistant). So a failed turn that is no longer last (after a
follow-up) or an older failed run in history showed neither the pill nor
the card — its error detail vanished, undercutting reload/history
survival. ChatPane now passes `errorCardOwnerId` (the assistant id whose
error the card represents); AssistantMessage suppresses only that one
pill and keeps rendering StatusPill for all other error events.
* fix(daemon): don't treat a process exit code as an HTTP status
Follow-up to review on #3083: the status-context helper accepted a bare
`code` prefix, so `exit code 401` / `process exited with code 429` still
matched and got classified as AGENT_AUTH_REQUIRED / RATE_LIMITED (the
very `exit code 401` case the comment calls out as noise). `code` now
only counts when qualified (`status code` / `error code` / `response
code`) or punctuation-bound (`code: 401`); bare `exit code N` no longer
matches. Adds fixtures for exit-code lines returning null.
* chore(web): translate AMR card / error keys for 16 remaining locales
PR #3083 added 10 new `chat.amrCard.*` / `chat.amrError.*` keys but only
provided en/zh-CN/zh-TW translations; the other 16 locales fell back to
English. Translate the card title/body, three chips, primary CTA, and
the AMR self-error (auth / balance) messages and buttons for ar, de,
es-ES, fa, fr, hu, id, it, ja, ko, pl, pt-BR, ru, th, tr, uk.
* fix(amr): address review feedback on #2355
Targeted fixes for the unresolved review threads on #2355. Each fix
includes / updates a focused test.
- runtimes/executables.ts: `packagedVelaOpenCodeCompanionTree` now
verifies the inner `opencode` executable exists + is runnable, not
just the directory. This closes the false-positive availability path
that let `detectAgents()` surface AMR as available even when the
packaged companion was empty / partially copied (mrcfps, 4 threads).
- runtimes/executables.ts: `resolveAmrOpenCodeExecutable` now prefers
the bundled `<OD_RESOURCE_ROOT>/bin/libexec/opencode/opencode` over a
stale `opencode` on the user's PATH, so packaged AMR builds can't be
hijacked by a global installation.
- web/EntryShell.tsx: when the Local CLI scan returns an available
agent and the previously-selected agent is AMR, switch the selection
to the first available local agent so the runtime and persisted
agent agree before Continue.
- server.ts (model-probe branch): for AMR, check `readVelaLoginStatus`
BEFORE rejecting on an empty live-model catalog — a signed-out user
was getting `AMR_MODEL_UNAVAILABLE` ("choose a model") instead of
the correct `AMR_AUTH_REQUIRED` (sign-in affordance).
- server.ts (default model fallback): if the user asked for the AMR
agent default and the cached id is no longer in the FRESH catalog,
fall back to `liveModels[0]` from the probe instead of rejecting the
run as `AMR_MODEL_UNAVAILABLE`.
- integrations/vela.ts: route `vela login` through
`createCommandInvocation` so an npm/Node-style `vela.cmd` / `.bat`
shim on Windows gets the correct `cmd.exe /d /s /c …` wrapping with
verbatim args (matches `execAgentFile` / chat-run spawning).
- tools/pack/src/linux.ts: in containerized Linux builds, bind-mount
the host directory of `OPEN_DESIGN_VELA_CLI_BIN` and rewrite the env
to the container-side path. The host path was being passed in as-is
even though the default container only mounts /project, /tools-pack
and cache/home — `copyOptionalVelaCliBinary` saw a missing path.
Deferred (out of scope for this PR):
- `od amr status/login/logout/cancel` CLI subcommands (AGENTS.md
UI/CLI dual-track rule, server.ts:5763) — sizable surface; tracked
for a separate focused PR.
- Strict `--require-vela-cli` for Windows + mac-x64 beta builds:
prematurely blocked — `@powerformer/vela-cli` only publishes the
`darwin-arm64` platform binary today; adding the flag elsewhere
would fail the builds. Revisit once win/x64/linux binaries ship.
* fix(amr): hoist sendAmrAccountFailure above the AMR catalog preflight (TDZ)
The new signed-out AMR branch in the catalog preflight at server.ts:10875
calls `sendAmrAccountFailure(...)` to emit AMR_AUTH_REQUIRED, but the
const declaration sat ~100 lines below at the outer function scope. Because
`const` is TDZ-aware, that branch would have thrown `ReferenceError:
Cannot access 'sendAmrAccountFailure' before initialization` for the
exact users it tries to help — defeating the original intent.
Hoist the helper to just above the AMR preflight block so it's available
to every AMR code path in this function. Behavior elsewhere is unchanged.
Also rerun the daemon test suite: `launch.test.ts > resolveAgentLaunch
uses packaged built-in Vela for AMR` was creating the
`<resourceRoot>/bin/libexec/opencode/` companion *directory* only, but
this PR's earlier tightening of `packagedVelaOpenCodeCompanionTree`
also requires the inner `opencode` executable. Add it to that fixture
to match the new contract; the test was a sibling of the executables /
env-and-detection fixtures already updated in 13fc4f4.
Addresses #2355 review (mrcfps, 2026-05-28).
* feat(web): add hover cancel for AMR login (#3158)
* feat(web): add hover cancel for AMR login
* fix(web): don't bounce AmrLoginPill back to 'Signing in…' after local cancel
Both codex-connector (P2) and looper (CHANGES_REQUESTED) on this PR
flagged the same race in the new local-cancel path: `handleCancelLogin`
dispatches `notifyAmrLoginStatusChanged('login-canceled')` immediately
after `/login/cancel` returns, but the `AMR_LOGIN_STATUS_EVENT` listener
unconditionally re-enters `refresh()` and then restarts polling
whenever `/api/integrations/vela/status` still reports
`loginInFlight: true`.
That is a real race because the daemon's `cancelVelaLogin()` only sends
SIGTERM (escalating to SIGKILL after `LOGIN_CANCEL_KILL_GRACE_MS` =
2000 ms) and keeps the child in `activeLoginProcs` until it actually
exits — so the first `/status` read after a successful cancel can
legally still come back as in-flight. Under that window the pill flips
back to 'Signing in…' and can later surface the timeout/error path even
though the user already canceled, defeating the behavior promised in
the PR description.
Fix the listener instead of every dispatch site: in the
`login-canceled` branch, after the local reset (stopPolling +
setPending(null) + clear refs), optimistically mark every subscribed
pill instance as not-in-flight (`setStatus((c) => c ? { ...c,
loginInFlight: false } : c)`) and `return` — skip the
refresh-and-reconcile branch below entirely. The next explicit refresh
(component mount, user interaction, or a `status-changed` event) will
pick up the daemon's confirmed state once the child has actually
exited.
Add a focused regression test that holds `/api/integrations/vela/status`
at `loginInFlight: true` even after a successful `/login/cancel`,
asserting that the pill stays at the Canceled → Authorize sequence and
never bounces back to 'Signing in…'. This test fails on the pre-fix
listener and passes on the new behavior; existing
'cancels an in-flight AMR sign-in…' and 'reconciles late AMR browser
completion to Signed in after local cancel' tests continue to pass.
Addresses review feedback on #3158 (chatgpt-codex-connector, nettee).
---------
Co-authored-by: lefarcen <935902669@qq.com>
---------
Co-authored-by: a1chzt <chizblank@gmail.com>
Co-authored-by: Amy <1184569493@qq.com>
Co-authored-by: Mason <jinmeihong0201@gmail.com>
Co-authored-by: Caprika <56862773+alchemistklk@users.noreply.github.com>
Co-authored-by: open-design-bot[bot] <282769551+open-design-bot[bot]@users.noreply.github.com>
942 lines
32 KiB
TypeScript
942 lines
32 KiB
TypeScript
import { readFile, readdir } from "node:fs/promises";
|
|
import path from "node:path";
|
|
|
|
import { checkDesignSystemManifests } from "./check-design-system-manifests.ts";
|
|
import { checkDesignSystemPackageQuality } from "./check-design-system-package-quality.ts";
|
|
import { checkDesignSystemComponentFixtureReport } from "./check-components-fixtures.ts";
|
|
import { checkDesignSystemFlagParity } from "./check-design-system-flag-parity.ts";
|
|
import { checkComponentsManifestExtraction } from "./check-components-manifest-extraction.ts";
|
|
import {
|
|
checkDesignSystemA1RequiredTokens,
|
|
checkDesignSystemA2DefaultsParity,
|
|
checkDesignSystemA2RequiredTokens,
|
|
checkDesignSystemBSlotRequiredTokens,
|
|
checkDesignSystemTokenFixtureSync,
|
|
checkDesignSystemUnknownTokens,
|
|
} from "./check-tokens-fixture-sync.ts";
|
|
import { collectCssHardcodedColorMatches, cssWideAndSpecialColorKeywords, realNamedColors } from "./style-policy.ts";
|
|
|
|
const repoRoot = path.resolve(import.meta.dirname, "..");
|
|
const allowedE2eScripts = new Set([
|
|
"e2e/scripts/playwright.ts",
|
|
"e2e/scripts/release-smoke.ts",
|
|
"e2e/scripts/visual-report.ts",
|
|
]);
|
|
|
|
type GuardCheck = {
|
|
name: string;
|
|
run: () => Promise<boolean>;
|
|
};
|
|
|
|
function toRepositoryPath(filePath: string): string {
|
|
return path.relative(repoRoot, filePath).split(path.sep).join("/");
|
|
}
|
|
|
|
const residualExtensions = new Set([".js", ".mjs", ".cjs"]);
|
|
|
|
const residualSkippedDirectories = new Set([
|
|
".agents",
|
|
".astro",
|
|
".claude",
|
|
".claude-sessions",
|
|
".codex",
|
|
".cursor",
|
|
".git",
|
|
".od",
|
|
".od-e2e",
|
|
".opencode",
|
|
".task",
|
|
".tmp",
|
|
".vite",
|
|
"dist",
|
|
"node_modules",
|
|
"out",
|
|
]);
|
|
|
|
const residualAllowedExactPaths = new Set([
|
|
// esbuild config entrypoints are executed directly by Node before package
|
|
// dist output exists.
|
|
"packages/agui-adapter/esbuild.config.mjs",
|
|
"packages/contracts/esbuild.config.mjs",
|
|
"packages/diagnostics/esbuild.config.mjs",
|
|
"packages/download/esbuild.config.mjs",
|
|
"packages/host/esbuild.config.mjs",
|
|
"packages/platform/esbuild.config.mjs",
|
|
"packages/plugin-runtime/esbuild.config.mjs",
|
|
"packages/registry-protocol/esbuild.config.mjs",
|
|
"packages/sidecar/esbuild.config.mjs",
|
|
"packages/sidecar-proto/esbuild.config.mjs",
|
|
// Maintainer utility scripts ported from the media branch. They are
|
|
// executed directly by Node and are not loaded by the app runtime.
|
|
"scripts/import-prompt-templates.mjs",
|
|
"scripts/postinstall.mjs",
|
|
"apps/packaged/esbuild.config.mjs",
|
|
// Browser service workers must be served as JavaScript files.
|
|
"apps/web/public/od-notifications-sw.js",
|
|
// PostCSS loads Tailwind through a web-local .mjs compatibility config entry.
|
|
"apps/web/postcss.config.mjs",
|
|
"scripts/bake-html-ppt-examples.mjs",
|
|
"scripts/scaffold-html-ppt-skills.mjs",
|
|
"scripts/sync-hyperframes-skill.mjs",
|
|
"scripts/verify-media-models.mjs",
|
|
// AMR (vela) verifier: ad-hoc dev runner that imports the daemon's compiled
|
|
// `dist/acp.js` and drives a real `vela agent run` against a live model.
|
|
// Kept as .mjs so it can be invoked directly via Node without any transform.
|
|
"apps/daemon/scripts/verify-amr-real-vela.mjs",
|
|
// Fake `vela agent run --runtime opencode` ACP stdio stub used by the AMR
|
|
// integration tests. The Vitest test spawns it via `child_process.spawn`,
|
|
// which needs a directly-executable file (shebang + .mjs).
|
|
"apps/daemon/tests/fixtures/fake-vela.mjs",
|
|
"tools/dev/bin/tools-dev.mjs",
|
|
"tools/dev/esbuild.config.mjs",
|
|
"tools/pack/bin/tools-pack.mjs",
|
|
"tools/pack/esbuild.config.mjs",
|
|
"tools/serve/bin/tools-serve.mjs",
|
|
"tools/serve/esbuild.config.mjs",
|
|
"tools/pack/resources/mac/notarize.cjs",
|
|
// electron-builder hook path; CJS compatibility entry used by tools-pack desktop builds.
|
|
"tools/pack/resources/web-standalone-after-pack.cjs",
|
|
]);
|
|
|
|
const residualAllowedPathPrefixes = [
|
|
"apps/daemon/dist/",
|
|
"apps/web/.next/",
|
|
"apps/web/out/",
|
|
"generated/",
|
|
"e2e/playwright-report/",
|
|
"e2e/reports/html/",
|
|
"e2e/reports/playwright-html-report/",
|
|
"e2e/reports/test-results/",
|
|
"e2e/ui/.od-data/",
|
|
"e2e/ui/reports/playwright-html-report/",
|
|
"e2e/ui/reports/test-results/",
|
|
"e2e/ui/test-results/",
|
|
// Vendored upstream HyperFrames helper scripts (design template).
|
|
"design-templates/hyperframes/scripts/",
|
|
// Vendored upstream Last30Days runtime helper used by the engine (design template).
|
|
"design-templates/last30days/scripts/lib/vendor/",
|
|
// Vendored upstream html-ppt runtime assets (lewislulu/html-ppt-skill, design template).
|
|
"design-templates/html-ppt/assets/",
|
|
"test-results/",
|
|
"vendor/",
|
|
];
|
|
|
|
const residualAllowedPathPatterns: RegExp[] = [
|
|
// Vendored upstream Zara template runtimes — one design template per template,
|
|
// name prefix `html-ppt-zhangzara-` (zarazhangrui/beautiful-html-templates).
|
|
// Only the vendored deck-stage runtime asset is allowlisted; any other
|
|
// JavaScript under these design-template directories must still be converted
|
|
// to TypeScript or explicitly listed in `residualAllowedExactPaths`.
|
|
/^design-templates\/html-ppt-zhangzara-[^/]+\/assets\/deck-stage\.js$/,
|
|
// Bundled example/skill plugins copy the upstream skill's `assets/`
|
|
// and `references/` directories verbatim so the daemon's preview
|
|
// surface can render the baked HTML without staging detours. Those
|
|
// assets are vendored runtime, never project-owned code, and must
|
|
// not be retypecasted to TypeScript.
|
|
/^plugins\/_official\/examples\/[^/]+\/(assets|references)\/.+$/,
|
|
];
|
|
|
|
function isResidualAllowedPath(repositoryPath: string): boolean {
|
|
if (residualAllowedExactPaths.has(repositoryPath)) return true;
|
|
if (residualAllowedPathPrefixes.some((prefix) => repositoryPath.startsWith(prefix))) return true;
|
|
return residualAllowedPathPatterns.some((pattern) => pattern.test(repositoryPath));
|
|
}
|
|
|
|
function isResidualSkippedDirectoryName(directoryName: string): boolean {
|
|
return (
|
|
residualSkippedDirectories.has(directoryName) || directoryName === ".next" || directoryName.startsWith(".next-")
|
|
);
|
|
}
|
|
|
|
async function collectResidualJavaScript(directory: string): Promise<string[]> {
|
|
const entries = await readdir(directory, { withFileTypes: true });
|
|
const residualFiles: string[] = [];
|
|
|
|
for (const entry of entries) {
|
|
const fullPath = path.join(directory, entry.name);
|
|
const repositoryPath = toRepositoryPath(fullPath);
|
|
|
|
if (entry.isDirectory()) {
|
|
if (isResidualSkippedDirectoryName(entry.name) || isResidualAllowedPath(`${repositoryPath}/`)) {
|
|
continue;
|
|
}
|
|
|
|
residualFiles.push(...(await collectResidualJavaScript(fullPath)));
|
|
continue;
|
|
}
|
|
|
|
if (!entry.isFile() || !residualExtensions.has(path.extname(entry.name))) {
|
|
continue;
|
|
}
|
|
|
|
if (isResidualAllowedPath(repositoryPath)) {
|
|
continue;
|
|
}
|
|
|
|
residualFiles.push(repositoryPath);
|
|
}
|
|
|
|
return residualFiles;
|
|
}
|
|
|
|
async function checkResidualJavaScript(): Promise<boolean> {
|
|
const residualFiles = await collectResidualJavaScript(repoRoot);
|
|
|
|
if (residualFiles.length > 0) {
|
|
console.error("Residual project-owned JavaScript files found:");
|
|
for (const filePath of residualFiles) {
|
|
console.error(`- ${filePath}`);
|
|
}
|
|
console.error("Convert these files to TypeScript or add a documented generated/vendor/output allowlist entry.");
|
|
return false;
|
|
}
|
|
|
|
console.log("Residual JavaScript check passed: project-owned code is TypeScript-only.");
|
|
return true;
|
|
}
|
|
|
|
const sourcePackageManifestRootPaths = ["package.json", "e2e/package.json"];
|
|
const sourcePackageManifestScopedDirectories = ["apps", "packages", "tools"];
|
|
const packageDependencySections = [
|
|
"dependencies",
|
|
"devDependencies",
|
|
"peerDependencies",
|
|
"optionalDependencies",
|
|
];
|
|
const packageManagerOverridePaths = ["pnpm.overrides", "overrides", "resolutions"];
|
|
const exactVersionPattern = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
const exactNpmAliasPattern = /^npm:(?:@[^/]+\/)?[^@]+@\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
|
|
type DependencySpecViolation = {
|
|
filePath: string;
|
|
fieldPath: string;
|
|
name: string;
|
|
spec: unknown;
|
|
reason: string;
|
|
};
|
|
|
|
type DependencySpecStats = {
|
|
exact: number;
|
|
manifests: number;
|
|
total: number;
|
|
workspace: number;
|
|
};
|
|
|
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|
|
|
|
function isAllowedDependencySpec(spec: string): boolean {
|
|
return spec === "workspace:*" || exactVersionPattern.test(spec) || exactNpmAliasPattern.test(spec);
|
|
}
|
|
|
|
function dependencySpecReason(spec: string): string {
|
|
if (spec.startsWith("workspace:") && spec !== "workspace:*") {
|
|
return "workspace dependencies must use exactly workspace:*";
|
|
}
|
|
|
|
return "dependency specs must be exact versions like 1.2.3 or workspace:*";
|
|
}
|
|
|
|
function dependencySpecFieldValue(value: unknown): string {
|
|
return typeof value === "string" ? value : JSON.stringify(value);
|
|
}
|
|
|
|
async function collectScopedPackageManifestPaths(scopeDirectory: string): Promise<string[]> {
|
|
const scopeRoot = path.join(repoRoot, scopeDirectory);
|
|
const entries = await readdir(scopeRoot, { withFileTypes: true });
|
|
const manifestPaths: string[] = [];
|
|
|
|
for (const entry of entries) {
|
|
if (!entry.isDirectory()) continue;
|
|
|
|
const packageDirectory = path.join(scopeRoot, entry.name);
|
|
const packageEntries = await readdir(packageDirectory, { withFileTypes: true });
|
|
if (packageEntries.some((packageEntry) => packageEntry.isFile() && packageEntry.name === "package.json")) {
|
|
manifestPaths.push(`${scopeDirectory}/${entry.name}/package.json`);
|
|
}
|
|
}
|
|
|
|
return manifestPaths;
|
|
}
|
|
|
|
async function collectSourcePackageManifestPaths(): Promise<string[]> {
|
|
const scopedManifestPaths = (
|
|
await Promise.all(sourcePackageManifestScopedDirectories.map((scope) => collectScopedPackageManifestPaths(scope)))
|
|
).flat();
|
|
|
|
return [...sourcePackageManifestRootPaths, ...scopedManifestPaths].sort();
|
|
}
|
|
|
|
function getPackageJsonField(packageJson: Record<string, unknown>, fieldPath: string): unknown {
|
|
let current: unknown = packageJson;
|
|
for (const part of fieldPath.split(".")) {
|
|
if (!isRecord(current)) return undefined;
|
|
current = current[part];
|
|
}
|
|
return current;
|
|
}
|
|
|
|
function checkDependencySpecRecord(
|
|
record: Record<string, unknown>,
|
|
filePath: string,
|
|
fieldPath: string,
|
|
violations: DependencySpecViolation[],
|
|
stats: DependencySpecStats,
|
|
): void {
|
|
for (const [name, spec] of Object.entries(record).sort(([left], [right]) => left.localeCompare(right))) {
|
|
if (isRecord(spec)) {
|
|
checkDependencySpecRecord(spec, filePath, `${fieldPath}.${name}`, violations, stats);
|
|
continue;
|
|
}
|
|
|
|
stats.total += 1;
|
|
if (typeof spec !== "string") {
|
|
violations.push({
|
|
filePath,
|
|
fieldPath,
|
|
name,
|
|
spec,
|
|
reason: "dependency specs must be strings",
|
|
});
|
|
continue;
|
|
}
|
|
|
|
if (spec === "workspace:*") {
|
|
stats.workspace += 1;
|
|
continue;
|
|
}
|
|
|
|
if (isAllowedDependencySpec(spec)) {
|
|
stats.exact += 1;
|
|
continue;
|
|
}
|
|
|
|
violations.push({
|
|
filePath,
|
|
fieldPath,
|
|
name,
|
|
spec,
|
|
reason: dependencySpecReason(spec),
|
|
});
|
|
}
|
|
}
|
|
|
|
async function checkPackageDependencySpecs(): Promise<boolean> {
|
|
const manifestPaths = await collectSourcePackageManifestPaths();
|
|
const violations: DependencySpecViolation[] = [];
|
|
const stats: DependencySpecStats = {
|
|
exact: 0,
|
|
manifests: manifestPaths.length,
|
|
total: 0,
|
|
workspace: 0,
|
|
};
|
|
|
|
for (const manifestPath of manifestPaths) {
|
|
const packageJson = JSON.parse(await readFile(path.join(repoRoot, manifestPath), "utf8")) as Record<string, unknown>;
|
|
|
|
for (const section of packageDependencySections) {
|
|
const value = packageJson[section];
|
|
if (value === undefined) continue;
|
|
if (!isRecord(value)) {
|
|
violations.push({
|
|
filePath: manifestPath,
|
|
fieldPath: section,
|
|
name: section,
|
|
spec: value,
|
|
reason: "dependency sections must be objects",
|
|
});
|
|
continue;
|
|
}
|
|
|
|
checkDependencySpecRecord(value, manifestPath, section, violations, stats);
|
|
}
|
|
|
|
for (const overridePath of packageManagerOverridePaths) {
|
|
const value = getPackageJsonField(packageJson, overridePath);
|
|
if (value === undefined) continue;
|
|
if (!isRecord(value)) {
|
|
violations.push({
|
|
filePath: manifestPath,
|
|
fieldPath: overridePath,
|
|
name: overridePath,
|
|
spec: value,
|
|
reason: "package-manager override sections must be objects",
|
|
});
|
|
continue;
|
|
}
|
|
|
|
checkDependencySpecRecord(value, manifestPath, overridePath, violations, stats);
|
|
}
|
|
}
|
|
|
|
if (violations.length > 0) {
|
|
console.error("Package dependency spec violations found:");
|
|
for (const violation of violations) {
|
|
console.error(
|
|
`- ${violation.filePath} ${violation.fieldPath}.${violation.name}=${dependencySpecFieldValue(violation.spec)} -> ${violation.reason}`,
|
|
);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
console.log(
|
|
`Package dependency spec check passed: ${stats.manifests} package.json files, ${stats.exact} exact specs, ${stats.workspace} workspace:* specs.`,
|
|
);
|
|
return true;
|
|
}
|
|
|
|
const testLayoutScopedDirectories = ["apps", "packages", "tools"];
|
|
const testLayoutSkippedDirectories = new Set([".next", ".od-data", "dist", "node_modules", "out", "reports", "test-results"]);
|
|
|
|
function isTestFile(fileName: string): boolean {
|
|
return /\.test\.tsx?$/.test(fileName);
|
|
}
|
|
|
|
function expectedTestPath(repositoryPath: string): string {
|
|
const [scope, project, ...relativeParts] = repositoryPath.split("/");
|
|
if (!testLayoutScopedDirectories.includes(scope ?? "") || project == null || relativeParts.length === 0) {
|
|
return repositoryPath;
|
|
}
|
|
|
|
const normalizedRelativeParts = relativeParts[0] === "src" ? relativeParts.slice(1) : relativeParts;
|
|
return [scope, project, "tests", ...normalizedRelativeParts].join("/");
|
|
}
|
|
|
|
function isAllowedScopedTestPath(repositoryPath: string): boolean {
|
|
const [scope, project, directory] = repositoryPath.split("/");
|
|
return testLayoutScopedDirectories.includes(scope ?? "") && project != null && directory === "tests";
|
|
}
|
|
|
|
async function collectTestLayoutViolations(directory: string): Promise<string[]> {
|
|
const entries = await readdir(directory, { withFileTypes: true });
|
|
const violations: string[] = [];
|
|
|
|
for (const entry of entries) {
|
|
const fullPath = path.join(directory, entry.name);
|
|
|
|
if (entry.isDirectory()) {
|
|
if (testLayoutSkippedDirectories.has(entry.name)) {
|
|
continue;
|
|
}
|
|
|
|
violations.push(...(await collectTestLayoutViolations(fullPath)));
|
|
continue;
|
|
}
|
|
|
|
if (!entry.isFile() || !isTestFile(entry.name)) {
|
|
continue;
|
|
}
|
|
|
|
const repositoryPath = toRepositoryPath(fullPath);
|
|
if (!isAllowedScopedTestPath(repositoryPath)) {
|
|
violations.push(repositoryPath);
|
|
}
|
|
}
|
|
|
|
return violations;
|
|
}
|
|
|
|
async function checkTestLayout(): Promise<boolean> {
|
|
const violations = (
|
|
await Promise.all(
|
|
testLayoutScopedDirectories.map((directory) => collectTestLayoutViolations(path.join(repoRoot, directory))),
|
|
)
|
|
).flat();
|
|
|
|
if (violations.length > 0) {
|
|
console.error("Test files under apps/, packages/, and tools/ must live in tests/ sibling to src/:");
|
|
for (const violation of violations) {
|
|
console.error(`- ${violation} -> ${expectedTestPath(violation)}`);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
console.log("Test layout check passed: apps/packages/tools tests live in sibling tests directories.");
|
|
return true;
|
|
}
|
|
|
|
const e2ePackageJsonPath = path.join(repoRoot, "e2e", "package.json");
|
|
const e2eSkippedDirectories = new Set([".od-data", "node_modules", "reports", "test-results"]);
|
|
const e2eAllowedScripts = [
|
|
"test",
|
|
"test:ui:critical",
|
|
"test:ui:extended",
|
|
"typecheck",
|
|
];
|
|
|
|
async function collectRepositoryFiles(directory: string, skippedDirectoryNames = new Set<string>()): Promise<string[]> {
|
|
const entries = await readdir(directory, { withFileTypes: true });
|
|
const files: string[] = [];
|
|
|
|
for (const entry of entries) {
|
|
const fullPath = path.join(directory, entry.name);
|
|
if (entry.isDirectory()) {
|
|
if (skippedDirectoryNames.has(entry.name)) continue;
|
|
files.push(...(await collectRepositoryFiles(fullPath, skippedDirectoryNames)));
|
|
continue;
|
|
}
|
|
if (entry.isFile()) files.push(toRepositoryPath(fullPath));
|
|
}
|
|
|
|
return files;
|
|
}
|
|
|
|
async function checkE2eLayout(): Promise<boolean> {
|
|
const violations: string[] = [];
|
|
const packageJson = JSON.parse(await readFile(e2ePackageJsonPath, "utf8")) as {
|
|
scripts?: Record<string, unknown>;
|
|
};
|
|
const scriptNames = Object.keys(packageJson.scripts ?? {}).sort();
|
|
if (scriptNames.join("\0") !== e2eAllowedScripts.join("\0")) {
|
|
violations.push(
|
|
`e2e/package.json scripts must be exactly ${e2eAllowedScripts.join(", ")} (found: ${scriptNames.join(", ")})`,
|
|
);
|
|
}
|
|
|
|
const e2eRoot = path.join(repoRoot, "e2e");
|
|
for (const repositoryPath of await collectRepositoryFiles(e2eRoot, e2eSkippedDirectories)) {
|
|
if (
|
|
repositoryPath === "e2e/package.json" ||
|
|
repositoryPath === "e2e/tsconfig.json" ||
|
|
repositoryPath === "e2e/vitest.config.ts" ||
|
|
repositoryPath === "e2e/playwright.config.ts" ||
|
|
repositoryPath === "e2e/playwright.visual.config.ts" ||
|
|
repositoryPath === "e2e/AGENTS.md"
|
|
) {
|
|
continue;
|
|
}
|
|
|
|
if (repositoryPath.startsWith("e2e/specs/")) {
|
|
if (!/\.spec\.ts$/.test(repositoryPath)) {
|
|
violations.push(`${repositoryPath} -> e2e specs must be *.spec.ts`);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (repositoryPath.startsWith("e2e/tests/")) {
|
|
if (!/\.test\.ts$/.test(repositoryPath)) {
|
|
violations.push(`${repositoryPath} -> e2e tests must be *.test.ts`);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (repositoryPath.startsWith("e2e/ui/")) {
|
|
const relativePath = repositoryPath.slice("e2e/ui/".length);
|
|
if (relativePath.includes("/") || !/\.test\.ts$/.test(repositoryPath)) {
|
|
violations.push(`${repositoryPath} -> e2e UI files must be flat Playwright *.test.ts files under ui/`);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (repositoryPath.startsWith("e2e/resources/")) {
|
|
const relativePath = repositoryPath.slice("e2e/resources/".length);
|
|
if (relativePath.includes("/") || !/\.ts$/.test(repositoryPath)) {
|
|
violations.push(`${repositoryPath} -> e2e resources must be flat TypeScript files under resources/`);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (repositoryPath.startsWith("e2e/lib/")) {
|
|
if (!/\.ts$/.test(repositoryPath)) {
|
|
violations.push(`${repositoryPath} -> e2e lib files must be TypeScript`);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (repositoryPath.startsWith("e2e/scripts/")) {
|
|
if (!allowedE2eScripts.has(repositoryPath)) {
|
|
violations.push(`${repositoryPath} -> e2e scripts must be an approved package-owned entrypoint`);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
violations.push(`${repositoryPath} -> e2e source files must live in specs/, tests/, ui/, resources/, lib/, or approved scripts`);
|
|
}
|
|
|
|
if (violations.length > 0) {
|
|
console.error("E2E package layout violations found:");
|
|
for (const violation of violations) console.error(`- ${violation}`);
|
|
return false;
|
|
}
|
|
|
|
console.log("E2E layout check passed: Vitest, Playwright UI, resources, lib, and scripts stay in their lanes.");
|
|
return true;
|
|
}
|
|
|
|
const webTestSkippedDirectories = new Set([".od-data", "reports", "test-results"]);
|
|
|
|
async function checkWebTestLayout(): Promise<boolean> {
|
|
const violations: string[] = [];
|
|
const webTestsRoot = path.join(repoRoot, "apps", "web", "tests");
|
|
|
|
for (const repositoryPath of await collectRepositoryFiles(webTestsRoot, webTestSkippedDirectories)) {
|
|
if (repositoryPath.startsWith("apps/web/tests/vitest/") || repositoryPath.startsWith("apps/web/tests/playwright/")) {
|
|
violations.push(`${repositoryPath} -> web tests should stay lightweight under apps/web/tests/ without vitest/playwright nesting`);
|
|
continue;
|
|
}
|
|
|
|
if (/\.(spec|test)\.tsx?$/.test(repositoryPath) && !/\.test\.tsx?$/.test(repositoryPath)) {
|
|
violations.push(`${repositoryPath} -> web Vitest test files must be *.test.ts or *.test.tsx`);
|
|
}
|
|
}
|
|
|
|
if (violations.length > 0) {
|
|
console.error("Web test layout violations found:");
|
|
for (const violation of violations) console.error(`- ${violation}`);
|
|
return false;
|
|
}
|
|
|
|
console.log("Web test layout check passed: web tests stay lightweight and Vitest-only.");
|
|
return true;
|
|
}
|
|
|
|
const toolsRootAllowlist = new Map<string, "directory" | "file">([
|
|
// Keep top-level tools intentionally small. `tools/launcher` was an incoming
|
|
// Windows shim experiment from PR #683 and is not an active repo boundary.
|
|
["AGENTS.md", "file"],
|
|
["dev", "directory"],
|
|
["pack", "directory"],
|
|
["serve", "directory"],
|
|
]);
|
|
|
|
async function checkToolsLayout(): Promise<boolean> {
|
|
const toolsRoot = path.join(repoRoot, "tools");
|
|
const entries = await readdir(toolsRoot, { withFileTypes: true });
|
|
const seen = new Set<string>();
|
|
const violations: string[] = [];
|
|
|
|
for (const entry of entries) {
|
|
const expected = toolsRootAllowlist.get(entry.name);
|
|
const repositoryPath = `tools/${entry.name}${entry.isDirectory() ? "/" : ""}`;
|
|
|
|
if (expected == null) {
|
|
violations.push(`${repositoryPath} -> tools/ top-level entries are allowlisted; expected only AGENTS.md, dev/, pack/, and serve/`);
|
|
continue;
|
|
}
|
|
|
|
seen.add(entry.name);
|
|
if (expected === "directory" && !entry.isDirectory()) {
|
|
violations.push(`${repositoryPath} -> expected tools/${entry.name}/ to be a directory`);
|
|
}
|
|
if (expected === "file" && !entry.isFile()) {
|
|
violations.push(`${repositoryPath} -> expected tools/${entry.name} to be a file`);
|
|
}
|
|
}
|
|
|
|
for (const [entryName, expected] of toolsRootAllowlist) {
|
|
if (!seen.has(entryName)) {
|
|
violations.push(`tools/${entryName}${expected === "directory" ? "/" : ""} -> required tools boundary is missing`);
|
|
}
|
|
}
|
|
|
|
if (violations.length > 0) {
|
|
console.error("Tools layout violations found:");
|
|
for (const violation of violations) console.error(`- ${violation}`);
|
|
return false;
|
|
}
|
|
|
|
console.log("Tools layout check passed: tools/ top-level entries match the active boundary allowlist.");
|
|
return true;
|
|
}
|
|
|
|
const stylePolicySkippedDirectories = new Set([
|
|
".next",
|
|
".od-data",
|
|
"dist",
|
|
"node_modules",
|
|
"out",
|
|
"reports",
|
|
"test-results",
|
|
]);
|
|
|
|
const stylePolicySourcePrefixes = ["apps/web/app/", "apps/web/src/"];
|
|
const stylePolicyHardcodedColorEnforcedPrefixes = ["scripts/guard-style-policy-fixtures/"];
|
|
const stylePolicyCheckedDirectoryPrefixes = [
|
|
...new Set([...stylePolicySourcePrefixes, ...stylePolicyHardcodedColorEnforcedPrefixes]),
|
|
];
|
|
const stylePolicyExtensions = new Set([".css", ".ts", ".tsx"]);
|
|
const tailwindDefaultColorNames = [
|
|
"slate",
|
|
"gray",
|
|
"zinc",
|
|
"neutral",
|
|
"stone",
|
|
"red",
|
|
"orange",
|
|
"amber",
|
|
"yellow",
|
|
"lime",
|
|
"green",
|
|
"emerald",
|
|
"teal",
|
|
"cyan",
|
|
"sky",
|
|
"blue",
|
|
"indigo",
|
|
"violet",
|
|
"purple",
|
|
"fuchsia",
|
|
"pink",
|
|
"rose",
|
|
"white",
|
|
"black",
|
|
].join("|");
|
|
const tailwindDefaultPaletteClassPrefixes = [
|
|
"bg",
|
|
"text",
|
|
"border(?:-(?:x|y|s|e|t|r|b|l))?",
|
|
"divide",
|
|
"placeholder",
|
|
"marker",
|
|
"from",
|
|
"via",
|
|
"to",
|
|
"ring(?:-offset)?",
|
|
"outline",
|
|
"decoration",
|
|
"(?:inset-|text-|drop-)?shadow",
|
|
"accent",
|
|
"caret",
|
|
"fill",
|
|
"stroke",
|
|
].join("|");
|
|
const defaultTailwindPaletteClassPattern = new RegExp(
|
|
`\\b(?:${tailwindDefaultPaletteClassPrefixes})-(?:${tailwindDefaultColorNames})(?:-\\d{2,3})?\\b`,
|
|
"g",
|
|
);
|
|
|
|
const hardcodedColorPattern = new RegExp(
|
|
`#[0-9a-fA-F]{3,8}\\b|rgba?\\([^)]*\\)|hsla?\\([^)]*\\)|(?<quote>['"])\\s*(?<named>${realNamedColors.join("|")}|transparent|currentColor|currentcolor|inherit|initial|unset|revert)\\s*\\k<quote>`,
|
|
"g",
|
|
);
|
|
|
|
type StylePolicyAllowlistEntry = {
|
|
pathPattern: RegExp;
|
|
valuePattern: RegExp;
|
|
reason: string;
|
|
};
|
|
|
|
const hardcodedColorAllowlist: StylePolicyAllowlistEntry[] = [
|
|
{
|
|
pathPattern: /^apps\/web\/src\/index\.css$/,
|
|
valuePattern: /^(?:#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\))$/,
|
|
reason: "global token definitions, shadows, overlays, and retained migration inventory live in the CSS source of truth",
|
|
},
|
|
{
|
|
pathPattern: /^apps\/web\/src\/components\/(?:AgentIcon|PaletteTweaks|PetSettings|SettingsDialog)\.tsx$/,
|
|
valuePattern: /^(?:#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\))$/,
|
|
reason: "brand accents, user accent choices, and legacy token fallbacks are classified as Phase 1 migration inventory",
|
|
},
|
|
{
|
|
pathPattern: /^apps\/web\/src\/components\/(?:SketchEditor|SketchPreview|NewProjectPanel)\.tsx$/,
|
|
valuePattern: /^(?:#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\)|['\"](?:none|currentColor|currentcolor|transparent)['\"])$/,
|
|
reason: "sketch/canvas data and SVG illustrations keep narrow hardcoded color exceptions until their migration slice",
|
|
},
|
|
{
|
|
pathPattern: /^apps\/web\/src\/components\/(?:FileViewer|ManualEditPanel)\.tsx$/,
|
|
valuePattern: /^(?:#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\))$/,
|
|
reason: "user-authored file, inspect, and editable style colors are handled by the file/viewer migration slice",
|
|
},
|
|
{
|
|
pathPattern: /^apps\/web\/src\/components\/(?:MemorySection|MemoryModelInline|MemoryToast)\.tsx$/,
|
|
valuePattern: /^(?:#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\))$/,
|
|
reason: "memory UI legacy color fallbacks are classified as Phase 1 migration inventory",
|
|
},
|
|
{
|
|
pathPattern: /^apps\/web\/tests\//,
|
|
valuePattern: /.*/,
|
|
reason: "tests and fixtures may assert rejected colors explicitly",
|
|
},
|
|
];
|
|
|
|
type StylePolicyViolation = {
|
|
filePath: string;
|
|
lineNumber: number;
|
|
match: string;
|
|
reason: string;
|
|
};
|
|
|
|
function lineNumberForIndex(source: string, index: number): number {
|
|
return source.slice(0, index).split("\n").length;
|
|
}
|
|
|
|
function isStylePolicySource(repositoryPath: string): boolean {
|
|
return stylePolicySourcePrefixes.some((prefix) => repositoryPath.startsWith(prefix));
|
|
}
|
|
|
|
function isHardcodedColorEnforcedPath(repositoryPath: string): boolean {
|
|
return stylePolicyHardcodedColorEnforcedPrefixes.some((prefix) => repositoryPath.startsWith(prefix));
|
|
}
|
|
|
|
function isHardcodedColorAllowlisted(repositoryPath: string, match: string): boolean {
|
|
const normalizedMatch = match.trim();
|
|
const unquotedMatch = normalizedMatch.replace(/^['"]|['"]$/g, "");
|
|
if (cssWideAndSpecialColorKeywords.has(unquotedMatch.toLowerCase())) return true;
|
|
|
|
return hardcodedColorAllowlist.some(
|
|
(entry) => entry.pathPattern.test(repositoryPath) && entry.valuePattern.test(normalizedMatch),
|
|
);
|
|
}
|
|
|
|
function addStylePolicyViolation(
|
|
violations: StylePolicyViolation[],
|
|
repositoryPath: string,
|
|
source: string,
|
|
index: number,
|
|
match: string,
|
|
reason: string,
|
|
): void {
|
|
violations.push({
|
|
filePath: repositoryPath,
|
|
lineNumber: lineNumberForIndex(source, index),
|
|
match,
|
|
reason,
|
|
});
|
|
}
|
|
|
|
function collectStylePolicyViolationsFromSource(repositoryPath: string, source: string): StylePolicyViolation[] {
|
|
const violations: StylePolicyViolation[] = [];
|
|
|
|
if (isStylePolicySource(repositoryPath)) {
|
|
for (const match of source.matchAll(defaultTailwindPaletteClassPattern)) {
|
|
violations.push({
|
|
filePath: repositoryPath,
|
|
lineNumber: lineNumberForIndex(source, match.index ?? 0),
|
|
match: match[0],
|
|
reason: "default Tailwind palette classes must use Open Design token utilities instead",
|
|
});
|
|
}
|
|
}
|
|
|
|
if (isStylePolicySource(repositoryPath) || isHardcodedColorEnforcedPath(repositoryPath)) {
|
|
if (repositoryPath.endsWith(".css") && isHardcodedColorEnforcedPath(repositoryPath)) {
|
|
for (const match of collectCssHardcodedColorMatches(source)) {
|
|
const value = match.value;
|
|
if (value === undefined || isHardcodedColorAllowlisted(repositoryPath, value)) continue;
|
|
|
|
addStylePolicyViolation(
|
|
violations,
|
|
repositoryPath,
|
|
source,
|
|
match.index,
|
|
value,
|
|
"unregistered hardcoded UI colors must use Open Design tokens or an explicit allowlist entry",
|
|
);
|
|
}
|
|
} else {
|
|
for (const match of source.matchAll(hardcodedColorPattern)) {
|
|
const value = match[0];
|
|
if (isHardcodedColorAllowlisted(repositoryPath, value)) continue;
|
|
if (!isHardcodedColorEnforcedPath(repositoryPath)) continue;
|
|
|
|
addStylePolicyViolation(
|
|
violations,
|
|
repositoryPath,
|
|
source,
|
|
match.index ?? 0,
|
|
value,
|
|
"unregistered hardcoded UI colors must use Open Design tokens or an explicit allowlist entry",
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
return violations;
|
|
}
|
|
|
|
async function collectStylePolicyViolations(directory: string): Promise<StylePolicyViolation[]> {
|
|
const entries = await readdir(directory, { withFileTypes: true });
|
|
const violations: StylePolicyViolation[] = [];
|
|
|
|
for (const entry of entries) {
|
|
const fullPath = path.join(directory, entry.name);
|
|
if (entry.isDirectory()) {
|
|
if (stylePolicySkippedDirectories.has(entry.name)) continue;
|
|
violations.push(...(await collectStylePolicyViolations(fullPath)));
|
|
continue;
|
|
}
|
|
|
|
if (!entry.isFile() || !stylePolicyExtensions.has(path.extname(entry.name))) continue;
|
|
|
|
const repositoryPath = toRepositoryPath(fullPath);
|
|
if (!isStylePolicySource(repositoryPath) && !isHardcodedColorEnforcedPath(repositoryPath)) continue;
|
|
|
|
violations.push(...collectStylePolicyViolationsFromSource(repositoryPath, await readFile(fullPath, "utf8")));
|
|
}
|
|
|
|
return violations;
|
|
}
|
|
|
|
async function repositoryDirectoryExists(repositoryPath: string): Promise<boolean> {
|
|
const parentPath = path.join(repoRoot, path.dirname(repositoryPath));
|
|
const directoryName = path.basename(repositoryPath);
|
|
const entries = await readdir(parentPath, { withFileTypes: true });
|
|
|
|
return entries.some((entry) => entry.name === directoryName && entry.isDirectory());
|
|
}
|
|
|
|
async function collectStylePolicyViolationsFromCheckedPaths(): Promise<StylePolicyViolation[]> {
|
|
const violations: StylePolicyViolation[] = [];
|
|
|
|
for (const repositoryPrefix of stylePolicyCheckedDirectoryPrefixes) {
|
|
const repositoryDirectory = repositoryPrefix.replace(/\/$/, "");
|
|
if (!(await repositoryDirectoryExists(repositoryDirectory))) continue;
|
|
|
|
violations.push(...(await collectStylePolicyViolations(path.join(repoRoot, repositoryDirectory))));
|
|
}
|
|
|
|
return violations;
|
|
}
|
|
|
|
async function checkStylePolicy(): Promise<boolean> {
|
|
const violations = await collectStylePolicyViolationsFromCheckedPaths();
|
|
|
|
if (violations.length > 0) {
|
|
console.error("Style policy violations found:");
|
|
for (const violation of violations) {
|
|
console.error(`- ${violation.filePath}:${violation.lineNumber} \`${violation.match}\` -> ${violation.reason}`);
|
|
}
|
|
console.error("Use Open Design token utilities/CSS variables or add a narrow allowlist entry with a reason.");
|
|
return false;
|
|
}
|
|
|
|
console.log("Style policy check passed: Tailwind palette classes and enforced hardcoded UI colors stay token-first.");
|
|
return true;
|
|
}
|
|
|
|
const checks: GuardCheck[] = [
|
|
{ name: "residual JavaScript", run: checkResidualJavaScript },
|
|
{ name: "package dependency specs", run: checkPackageDependencySpecs },
|
|
{ name: "test layout", run: checkTestLayout },
|
|
{ name: "e2e layout", run: checkE2eLayout },
|
|
{ name: "web test layout", run: checkWebTestLayout },
|
|
{ name: "tools layout", run: checkToolsLayout },
|
|
{ name: "style policy", run: checkStylePolicy },
|
|
{ name: "design system manifests", run: checkDesignSystemManifests },
|
|
{ name: "design system package quality", run: checkDesignSystemPackageQuality },
|
|
{ name: "design system component fixture report", run: checkDesignSystemComponentFixtureReport },
|
|
{ name: "design system token-fixture sync", run: checkDesignSystemTokenFixtureSync },
|
|
{ name: "design system A1 required tokens", run: checkDesignSystemA1RequiredTokens },
|
|
{ name: "design system A2 required tokens", run: checkDesignSystemA2RequiredTokens },
|
|
{ name: "design system B-slot required tokens", run: checkDesignSystemBSlotRequiredTokens },
|
|
{ name: "design system unknown token allowlist", run: checkDesignSystemUnknownTokens },
|
|
{ name: "design system A2 defaults parity", run: checkDesignSystemA2DefaultsParity },
|
|
{ name: "design system flag parity", run: checkDesignSystemFlagParity },
|
|
{ name: "design system component manifest extraction", run: checkComponentsManifestExtraction },
|
|
];
|
|
|
|
const results: boolean[] = [];
|
|
for (const check of checks) {
|
|
try {
|
|
results.push(await check.run());
|
|
} catch (error) {
|
|
console.error(`Guard check failed unexpectedly: ${check.name}`);
|
|
console.error(error);
|
|
results.push(false);
|
|
}
|
|
}
|
|
|
|
if (results.some((passed) => !passed)) {
|
|
process.exitCode = 1;
|
|
}
|