An open source design system that's fully customizable and agent ready
TypeScript
fix: repair runtime and tooling audit regressions (#6051)
Cindy Zhang64e715a37244
diff --git a/.changeset/chat-composer-history-after-focus.md b/.changeset/chat-composer-history-after-focus.mdnew file mode 100644index 0000000000..efaeb107b1--- /dev/null+++ b/.changeset/chat-composer-history-after-focus.md@@ -0,0 +1,14 @@+---+'@astryxdesign/core': patch+---++[fix] ChatComposerInput no longer discards a pending draft when you click the+composer's padding and press ArrowUp. Focusing a contentEditable collapses the+caret to the start of the draft, which is the one position where ArrowUp means+"recall history", so the first ArrowUp after that click replaced what you had+typed. The composer now places the caret after the draft when it focuses+itself — clicking the space after the text means "put me there" — so ArrowUp+moves the caret with a draft present and still recalls history when the+composer is empty. Multi-line caret navigation is unchanged.++@cixzhangdiff --git a/.changeset/cli-debug-privacy-contract.md b/.changeset/cli-debug-privacy-contract.mdnew file mode 100644index 0000000000..433186e15a--- /dev/null+++ b/.changeset/cli-debug-privacy-contract.md@@ -0,0 +1,15 @@+---+'@astryxdesign/cli': patch+---++[fix] CLI: recorded runs no longer carry a raw agent session id, and the environment snapshot is scrubbed like every other value.++@cixzhang++A `DebugEvent` claimed `redacted: true` while `env` had never been through the scrubbing pass, and it stored the raw `agentSessionId` beside its hash. A session id follows one person across every run they make, and a handler may forward these records anywhere — so the record shipped a stable identifier, and an agent name pasted in from the environment went out verbatim, under a flag that said neither had.++The contract is now explicit on `DebugEventEnv`: no identity, attribution only from positive evidence, and free text scrubbed. `env.agentSessionId` is always null — join runs on `env.agentSessionIdHash`, which is what the raw value was for. Everything the CLI derives itself (platform, CI provider, locale, the hash) is still recorded verbatim, because a scrubbed snapshot is not worth keeping. `redacted` is set only on the sealed copy, after every pass has actually run.++`DebugSchemaVersion` widens to `1 | 2` and the CLI emits `2`, so code that switches on it is forced to handle both rather than silently reading a field that no longer means what it did. `parseDebugEvent` is version-aware to match: a v1 record may carry the raw id, a v2 record may not and is rejected if it does.++Not a breaking change: `debug` and the whole `DebugEvent` surface are unreleased — they land in this same release — so no published consumer ever saw the raw identifier.diff --git a/.changeset/cli-package-manager-authority.md b/.changeset/cli-package-manager-authority.mdnew file mode 100644index 0000000000..2dc4a85a44--- /dev/null+++ b/.changeset/cli-package-manager-authority.md@@ -0,0 +1,13 @@+---+'@astryxdesign/cli': patch+---++[fix] CLI: a stray lockfile no longer overrides the `packageManager` your project declares.++@cixzhang++One `yarn install` inside a pnpm project leaves a `yarn.lock` behind forever. A single lockfile used to outrank the `packageManager` field, so the CLI answered "yarn" for a project that says pnpm — and printed `yarn astryx …` in every command it suggested, including the invocation line written into agent docs, where agents copy it. `astryx doctor` called that setup healthy.++The declared `packageManager` field now decides, whatever lockfiles sit beside it. The documented fallbacks are unchanged: with nothing declared, a single lockfile still answers, a committed `pnpm-workspace.yaml` / `.yarnrc.yml` / `bunfig.toml` still breaks a multi-lockfile tie, an unbroken tie still resolves to the neutral `npx` form with a doctor FAIL, and the runner is still consulted only when the whole walk found nothing.++`astryx doctor` now WARNs when a lockfile contradicts the declaration, names the file, and says what to delete — instead of reporting the project as fine.diff --git a/.changeset/cli-truthful-result-counts.md b/.changeset/cli-truthful-result-counts.mdnew file mode 100644index 0000000000..b8126995b4--- /dev/null+++ b/.changeset/cli-truthful-result-counts.md@@ -0,0 +1,11 @@+---+'@astryxdesign/cli': patch+---++[fix] CLI: `search` and `build` now report how many results MATCHED, not how many were returned.++@cixzhang++`matchCount` on a `build.kit` envelope, and `output.resultCount` on a recorded run, were both the length of the list after `--limit` had cut it. A query matching two hundred things and one matching exactly twenty filed the same number, so nothing downstream could tell a capped answer from a complete one — and a thin kit read as "the package has nothing" when it was really "the cap hid the rest".++`search --json` now carries `matchCount` alongside `results`, and the text view says `Results for "x" (2 of 57)` when the list was cut short. The payloads themselves are unchanged: `results` is still bounded by `--limit`, and the kit still surfaces at most 3 pages, 5 blocks, and 6 components.diff --git a/.changeset/fix-package-manager-detection-multiple-lockfiles.md b/.changeset/fix-package-manager-detection-multiple-lockfiles.mdindex 02c4f12415..be0337b4bb 100644--- a/.changeset/fix-package-manager-detection-multiple-lockfiles.md+++ b/.changeset/fix-package-manager-detection-multiple-lockfiles.md@@ -14,9 +14,10 @@ Every command the CLI prints is then wrong, including the invocation linewritten into the agent-docs block, which agents copy verbatim into their ownruns.-A single lockfile still outranks everything else in its directory, unchanged.-When several sit in one directory the tie is broken only from evidence the-project owns: the declared `packageManager` field, then a committed+An explicit `packageManager` declaration is authoritative even when the+project also contains one or several lockfiles. Without a declaration, a+single lockfile remains decisive. When several lockfiles sit in one directory,+the tie is broken only from other evidence the project owns: a committedpackage-manager config file (`pnpm-workspace.yaml`, `.yarnrc.yml`,`bunfig.toml`). A stray `install` drops a lockfile; it writes none of those.diff --git a/.changeset/markdown-streamed-escaped-pipe.md b/.changeset/markdown-streamed-escaped-pipe.mdnew file mode 100644index 0000000000..b6375cdc2b--- /dev/null+++ b/.changeset/markdown-streamed-escaped-pipe.md@@ -0,0 +1,12 @@+---+'@astryxdesign/core': patch+---++[fix] Streamed Markdown no longer goes blank when the line still arriving+contains an escaped pipe. A `\|` is literal text, not a table-cell delimiter,+so a line carrying only escaped pipes is ordinary prose and renders as it+streams instead of being held back as an unfinished table header. Genuine+partial table syntax is still suppressed, and incremental parsing stays bounded+to the stream tail.++@cixzhangdiff --git a/.github/REVIEW_GATE.md b/.github/REVIEW_GATE.mdindex c392164f47..2b78afb564 100644--- a/.github/REVIEW_GATE.md+++ b/.github/REVIEW_GATE.md@@ -33,10 +33,31 @@ with their read-only token, so an approver uses an issue comment containing`/approve-spec <full-head-sha>` instead; that command runs from the trusteddefault branch and a new commit invalidates it.+Only that exact form decides the gate. The command must start the comment,+lowercase and unindented, because the workflow trigger matches the raw comment+body — an indented or capitalized command never starts the workflow, so the+parser refuses it too rather than counting a comment nobody's run ever saw. The+SHA itself may be either casing. A command that names no commit, names+something other than one full 40-character SHA, or names a superseded commit+changes nothing — so the gate replies once per head with the exact command to+copy, rather than leaving the owner believing they approved.++The gate never re-decides a merged or closed head. A run that starts after the+merge publishes nothing, and neither does a run yielding to a newer one.+GitHub has no conditional status write, so the window between the last read and+the write cannot be closed; the gate makes it one API call wide by reading the+live pull request last, and if a status still lands on a head that settled+during that window, the run logs the status as unverified and stops before+auto-merge.+When a DESIGNOWNER authors a PR, marking it ready for review attests that exact-head for the design-approval group. That evidence also counts when the PR-contains non-design current records, but every other applicable code or-spec-owner group remains separately required.+head **for the design-approval group only**. The attestation is published only+for a `.github/DESIGNOWNERS` handle, and it is read back only for a handle that+is still in that file — a marker left by someone since removed, or published+before this rule existed, authorizes nothing. It satisfies no other group: the+spec and theme groups always need a real exact-head review or command from+someone in their own list. A spec or engineering owner cannot attest their own+head.The attestation does not grant auto-merge by itself. The existing gate may enablesquash auto-merge only when every changed path is a recognized spec record,@@ -142,6 +163,48 @@ internal contributors' PRs. Owners still self-serve their own domain.merges regardless of write access, this holds internal contributors who havewrite but are not owners. (Repo admins can still bypass.)+`spec-owner-approval` must be a required status context on `main` as well. It is+published on every PR — `success` when no knowledge records changed — so+requiring it does not permanently strand unrelated work. **Until it is in the+required list, a pending owner gate is advisory and does not block the merge+button.** If the repository ever enables a merge queue, this gate also has to+report on `merge_group` before the context is required, or queued entries stall+waiting for a status nothing publishes.++### Making it required (ordered; do not reorder)++An open PR whose head predates the gate has no `spec-owner-approval` status at+all. Requiring the context first would block those heads on a status no event+will produce, because the gate only runs on a new event. Backfill first.++1. Land the gate changes, so the default branch has the `backfill` dispatch+ input. `workflow_dispatch` always runs the default branch's copy.+2. List the heads that would strand:++ ```sh+ gh pr list --state open --limit 300 --json number,headRefOid \+ --jq '.[]|"\(.number) \(.headRefOid)"' \+ | while read -r pr sha; do+ state=$(gh api "repos/facebook/astryx/commits/$sha/status" \+ --jq '[.statuses[]|select(.context=="spec-owner-approval")|.state]+ | if length==0 then "MISSING" else .[0] end')+ [ "$state" = MISSING ] && echo "$pr"+ done+ ```++3. Backfill each one. `backfill=true` publishes the status and returns before+ auto-merge, so a reconcile cannot land a PR nobody asked to land:++ ```sh+ gh workflow run spec-owner-gate.yml -f pr=<number> -f backfill=true+ ```++4. Re-run the step 2 query and confirm it prints nothing.+5. Only then add `spec-owner-approval` to the required status checks on `main`.++A `pending` result from the backfill is the correct outcome for a PR that+genuinely awaits an owner, not a stranded head.+## Why a commit status (not a check run)The gate is a **commit status**, not a check run, for two reasons:diff --git a/.github/scripts/ci-test-routing.test.mjs b/.github/scripts/ci-test-routing.test.mjsnew file mode 100644index 0000000000..524f7ddb17--- /dev/null+++ b/.github/scripts/ci-test-routing.test.mjs@@ -0,0 +1,226 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ci-test-routing.test.mjs+ *+ * The contract between `vitest.config.ts` and the CI jobs that run it, in both+ * workflows that run the suite.+ *+ * This repo has now lost test coverage to routing twice. First a suite+ * belonged to no Vitest project, so `pnpm test` never collected it. Then the+ * single `test` job that ran every project at once was terminated around 20+ * minutes with no summary — `main` was already at ~19m15, so the budget was+ * the defect, not any one test. `deploy.yml`'s push gate carried strictly more+ * than that: the same suite plus a full build plus eight typecheck gates.+ *+ * Both now run the projects as parallel lanes joined by `test`. That only+ * holds if every project has a lane in every workflow: a third project added+ * to the config with no job to run it would be collected by nobody and fail+ * nothing — the first failure again, one level up.+ */++import fs from 'node:fs';+import path from 'node:path';++import {describe, expect, it} from 'vitest';+import yaml from 'yaml';++const root = path.resolve(import.meta.dirname, '../..');+const read = relative => fs.readFileSync(path.join(root, relative), 'utf8');++/** The `name:` of every project declared in the root Vitest config. */+function declaredProjects() {+ return [...read('vitest.config.ts').matchAll(/^\s*name:\s*'([^']+)'/gm)].map(+ match => match[1],+ );+}++/**+ * The runner labels this repo is known to have.+ *+ * Deliberately a FIXED list, not one scraped from the workflow under test. A+ * self-derived allowlist is vacuous: a typo'd label appears in the file, so it+ * appears in the set, so it validates itself and the job queues forever+ * against a runner that does not exist. Adding a genuinely new label is a+ * deliberate edit here.+ */+const KNOWN_RUNNERS = new Set([+ '2-core-ubuntu-arm',+ '4-core-ubuntu',+ 'ubuntu-slim',+ 'ubuntu-latest',+]);++const WORKFLOWS = {+ 'ci.yml': {+ lanes: ['test-ui', 'test-node'],+ // A PR that only touches docs skips the suite but must still report.+ scopeConditional: true,+ },+ 'deploy.yml': {+ // The push gate also owns the build + typecheck gates, which need each+ // other and so ride one lane of their own.+ lanes: ['test-ui', 'test-node', 'typecheck'],+ scopeConditional: false,+ },+};++function load(file) {+ return yaml.parse(read(`.github/workflows/${file}`));+}++function runLines(job) {+ return (job?.steps ?? [])+ .map(step => step.run)+ .filter(Boolean)+ .join('\n');+}++describe.each(Object.entries(WORKFLOWS))(+ '%s test routing',+ (file, {lanes, scopeConditional}) => {+ const workflow = load(file);++ it('runs every declared Vitest project in some lane', () => {+ const projects = declaredProjects();+ expect(projects.length).toBeGreaterThan(0);++ const commands = lanes+ .map(lane => runLines(workflow.jobs[lane]))+ .join('\n');+ for (const project of projects) {+ expect(commands, `no lane runs --project ${project}`).toContain(+ `--project ${project}`,+ );+ }+ });++ it('assigns each project to exactly one lane', () => {+ for (const project of declaredProjects()) {+ const owners = lanes.filter(lane =>+ runLines(workflow.jobs[lane]).includes(`--project ${project}`),+ );+ expect(+ owners,+ `--project ${project} runs in ${owners.length} lanes`,+ ).toHaveLength(1);+ }+ });++ it('gives no lane the whole suite', () => {+ // A bare `pnpm test` runs every project in one job — the shape that hit+ // the wall.+ for (const lane of lanes) {+ expect(+ runLines(workflow.jobs[lane]),+ `${lane} runs the whole suite`,+ ).not.toMatch(/^\s*pnpm test\s*$/m);+ }+ });++ it('keeps `test` as a job so its context still reports', () => {+ // In ci.yml this is a required status check; in deploy.yml the `deploy`+ // job gates the publish on `needs.test.result`. Renaming it silently+ // breaks whichever one applies.+ expect(workflow.jobs.test).toBeDefined();+ expect(workflow.jobs.test.needs).toEqual(expect.arrayContaining(lanes));+ });++ it('fails the join when any lane fails', () => {+ // `needs` alone does not fail a job whose `if` is `always()`; the join+ // has to assert the results it waited for.+ const join = runLines(workflow.jobs.test);+ for (const lane of lanes) {+ expect(join, `join does not assert ${lane}`).toContain(+ `needs.${lane}.result }}" = "success"`,+ );+ }+ });++ it('runs every lane on a known runner label', () => {+ for (const job of [...lanes, 'test']) {+ const label = workflow.jobs[job]['runs-on'];+ expect(+ KNOWN_RUNNERS.has(label),+ `${job} uses unknown runner label "${label}"`,+ ).toBe(true);+ }+ });++ if (scopeConditional) {+ it('keeps the lightweight-docs skip on every lane', () => {+ for (const lane of lanes) {+ expect(workflow.jobs[lane].if).toContain('always()');+ const steps = workflow.jobs[lane].steps;+ const suite = steps.find(step => step.run?.includes('--project'));+ expect(suite.if, `${lane} suite is unconditional`).toContain(+ "docsite_only != 'true'",+ );+ expect(suite.if, `${lane} suite is unconditional`).toContain(+ "spec_only != 'true'",+ );+ expect(+ steps.some(step =>+ step.run?.includes('refusing to skip required work'),+ ),+ `${lane} does not guard against an unclassified scope`,+ ).toBe(true);+ }+ });+ }+ },+);++describe('deploy.yml push gating', () => {+ const workflow = load('deploy.yml');++ it('still blocks the publish on the join and the build', () => {+ // Splitting the gate must not let a deploy through on a red suite.+ expect(workflow.jobs.deploy.needs).toEqual(+ expect.arrayContaining(['test', 'build']),+ );+ expect(workflow.jobs.deploy.if).toContain("needs.test.result == 'success'");+ expect(workflow.jobs.deploy.if).toContain(+ "needs.build.result == 'success'",+ );+ });++ it('keeps the typecheck gates behind the build they need', () => {+ // `typecheck:strict` resolves the built @astryxdesign/* types, so the+ // build has to precede the gates in the SAME lane.+ const steps = workflow.jobs.typecheck.steps.map(step => step.run ?? '');+ const build = steps.findIndex(step => step.trim() === 'pnpm build');+ const strict = steps.findIndex(step => step.includes('typecheck:strict'));++ expect(build).toBeGreaterThanOrEqual(0);+ expect(strict).toBeGreaterThan(build);+ });++ it('keeps every typecheck gate that guarded main', () => {+ // These exist because a typecheck error can otherwise land on main and+ // break the `build` check on every open PR (#3197).+ const gates = runLines(workflow.jobs.typecheck);+ for (const gate of [+ 'scripts/verify-exports.mjs',+ '@astryxdesign/core typecheck:docs',+ '@astryxdesign/lab typecheck:docs',+ '@astryxdesign/charts typecheck:docs',+ '@astryxdesign/cli typecheck:template-docs',+ '@astryxdesign/cli typecheck:strict',+ '@astryxdesign/storybook typecheck',+ '@astryxdesign/core typecheck',+ ]) {+ expect(gates, `lost the ${gate} gate`).toContain(gate);+ }+ });++ it('checks out main on every push-gate lane', () => {+ // A lane that checks out the default ref would gate the wrong commit.+ for (const lane of ['test-ui', 'test-node', 'typecheck']) {+ const checkout = workflow.jobs[lane].steps.find(step =>+ step.uses?.startsWith('actions/checkout'),+ );+ expect(checkout?.with?.ref, `${lane} does not pin main`).toBe('main');+ }+ });+});diff --git a/.github/scripts/spec-owner-decision.cjs b/.github/scripts/spec-owner-decision.cjsindex 8ac4f52aa4..40399003aa 100644--- a/.github/scripts/spec-owner-decision.cjs+++ b/.github/scripts/spec-owner-decision.cjs@@ -15,12 +15,62 @@ const GATE_STATUS_CONTEXT = 'spec-owner-approval';const READY_STATUS_PREFIX = 'spec-owner-ready/';const TRUSTED_STATUS_CREATOR = 'github-actions[bot]';+// The workflow trigger filters comments with GitHub's `startsWith` against the+// raw body, which neither trims nor lowercases. Every parser below applies the+// same precondition, so a comment the trigger drops can never be read as a+// decision by a run started for some other event.+const OWNER_COMMAND_PREFIXES = ['/approve-spec', '/revoke-spec'];++function isDispatchableOwnerCommand(body) {+ return (+ typeof body === 'string' &&+ OWNER_COMMAND_PREFIXES.some(prefix => body.startsWith(prefix))+ );+}+function parseOwnerCommand(body, headSha) {+ if (!isDispatchableOwnerCommand(body)) return null;+ // The command prefix must match the trigger exactly, but a commit SHA is+ // case-insensitive everywhere else in git and GitHub. Accept either casing+ // rather than silently ignoring a copy-pasted uppercase head.const match = body.trim()- .match(/^\/(approve|revoke)-spec\s+([0-9a-f]{40})$/i);- if (!match || headSha !== match[2].toLowerCase()) return null;- return match[1].toLowerCase() === 'approve';+ .match(/^\/(approve|revoke)-spec\s+([0-9a-fA-F]{40})$/);+ if (!match || headSha.toLowerCase() !== match[2].toLowerCase()) return null;+ return match[1] === 'approve';+}++/**+ * Recognize that a comment was meant as an owner command, whatever it names.+ * Only the exact-head form in `parseOwnerCommand` decides the gate; this looser+ * shape exists so a near-miss command is answered instead of ignored.+ */+function parseOwnerCommandIntent(body) {+ if (!isDispatchableOwnerCommand(body)) return null;+ const match = body+ .trimEnd()+ .match(/^\/(approve|revoke)-spec(?![-\w])([\s\S]*)$/);+ if (!match) return null;+ return {verb: match[1], argument: match[2].trim()};+}++/**+ * Explain why a recognized owner command does not decide the gate, or return+ * null when it does. The reasons are the two silent failures owners hit: a+ * command that names no full head SHA, and one that names a superseded commit.+ */+function describeOwnerCommandProblem(intent, headSha) {+ if (!intent) return null;+ if (!intent.argument) {+ return 'it did not name a commit';+ }+ if (!/^[0-9a-f]{40}$/i.test(intent.argument)) {+ return 'it did not name exactly one full 40-character commit SHA';+ }+ if (intent.argument.toLowerCase() !== headSha.toLowerCase()) {+ return `it named ${intent.argument.slice(0, 7)}, which is not the current head`;+ }+ return null;}function candidateTime(candidate) {@@ -162,7 +212,12 @@ function isTrustedWorkflowStatus(status, repository) {);}-function parseReadyAttestations(statuses, {repository, headSha}) {+function parseReadyAttestations(statuses, {repository, headSha, owners}) {+ // A ready marker is only design-group evidence, and only from a handle that+ // is a design owner *now*. Markers published before that rule existed, or+ // by someone since removed from .github/DESIGNOWNERS, are historical noise+ // and must not authorize anything.+ const allowed = new Set((owners ?? []).map(owner => owner.toLowerCase()));const attestations = [];for (const status of statuses) {if (@@ -175,7 +230,7 @@ function parseReadyAttestations(statuses, {repository, headSha}) {const owner = status.context.slice(READY_STATUS_PREFIX.length).toLowerCase();- if (!/^[a-z0-9-]+$/.test(owner)) continue;+ if (!/^[a-z0-9-]+$/.test(owner) || !allowed.has(owner)) continue;const match = status.description?.match(/^Owner ready at (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z)\.$/,);@@ -241,13 +296,17 @@ function requiresOwnerApproval(records, options = {}) {module.exports = {GATE_STATUS_CONTEXT,+ OWNER_COMMAND_PREFIXES,READY_STATUS_PREFIX,canonicalRunUrl,+ describeOwnerCommandProblem,+ isDispatchableOwnerCommand,newestGateRun,parseAuthority,parseCanonicalRunId,parseKind,parseOwnerCommand,+ parseOwnerCommandIntent,parseOwnerFile,parseReadyAttestations,requiredApprovalGroups,diff --git a/.github/scripts/spec-owner-decision.test.mjs b/.github/scripts/spec-owner-decision.test.mjsindex c18e2c1b56..e399c6374b 100644--- a/.github/scripts/spec-owner-decision.test.mjs+++ b/.github/scripts/spec-owner-decision.test.mjs@@ -5,10 +5,14 @@ import {describe, expect, it} from 'vitest';const require = createRequire(import.meta.url);const {+ OWNER_COMMAND_PREFIXES,canonicalRunUrl,+ describeOwnerCommandProblem,+ isDispatchableOwnerCommand,newestGateRun,parseCanonicalRunId,parseOwnerCommand,+ parseOwnerCommandIntent,parseOwnerFile,parseReadyAttestations,requiredApprovalGroups,@@ -344,7 +348,7 @@ describe('spec owner decision', () => {{...trusted, target_url: 'https://example.com/forged'},{...trusted, description: 'owner says ready'},],- {repository, headSha: head},+ {repository, headSha: head, owners: ['cixzhang']},);expect(attestations).toEqual([@@ -490,4 +494,214 @@ describe('spec owner decision', () => {);expect(newestGateRun(statuses, repository)?.runId).toBe(9007199254740993n);});++ it('accepts a ready marker only from a current design owner', () => {+ const repository = 'facebook/astryx';+ const marker = login => ({+ context: `spec-owner-ready/${login}`,+ state: 'success',+ description: 'Owner ready at 2026-08-30T10:00:00.000Z.',+ target_url: canonicalRunUrl(repository, '42', '1'),+ creator: {login: 'github-actions[bot]'},+ });+ const statuses = [marker('ernestt'), marker('imdreamrunner')];++ // imdreamrunner is a spec owner and a design *approver*, but not a design+ // owner. A marker they published — including one predating the rule that+ // only design owners self-attest — is not evidence for any group.+ expect(+ parseReadyAttestations(statuses, {+ repository,+ headSha: head,+ owners: ['ernestt', 'rubyycheung'],+ }).map(attestation => attestation.owner),+ ).toEqual(['ernestt']);++ // A handle removed from DESIGNOWNERS stops counting immediately.+ expect(+ parseReadyAttestations(statuses, {+ repository,+ headSha: head,+ owners: ['rubyycheung'],+ }),+ ).toEqual([]);+ expect(+ parseReadyAttestations(statuses, {repository, headSha: head}),+ ).toEqual([]);+ });++ it('does not let a stale ready marker approve the design group', () => {+ const repository = 'facebook/astryx';+ const designApprovers = ['cixzhang', 'imdreamrunner', 'ernestt'];+ const stale = [+ {+ context: 'spec-owner-ready/imdreamrunner',+ state: 'success',+ description: 'Owner ready at 2026-09-04T05:54:18.000Z.',+ target_url: canonicalRunUrl(repository, '42', '1'),+ creator: {login: 'github-actions[bot]'},+ },+ ];++ expect(+ resolveOwnerDecision({+ owners: designApprovers,+ headSha: head,+ reviews: [],+ comments: [],+ readyAttestations: parseReadyAttestations(stale, {+ repository,+ headSha: head,+ owners: ['ernestt', 'rubyycheung'],+ }),+ }).approved,+ ).toBe(false);+ });++ describe('recognizing a command that does not decide the gate', () => {+ it('recognizes the owner-command shape whatever it names', () => {+ expect(parseOwnerCommandIntent('/approve-spec')).toEqual({+ verb: 'approve',+ argument: '',+ });+ expect(parseOwnerCommandIntent(`/revoke-spec ${head} `)).toEqual({+ verb: 'revoke',+ argument: head,+ });+ expect(parseOwnerCommandIntent('/approve-spec abc1234 thanks')).toEqual({+ verb: 'approve',+ argument: 'abc1234 thanks',+ });+ });++ it.each([+ undefined,+ '',+ 'Looks good to me',+ '/approve-specs abc',+ '/approve-spec-now',+ `Please run /approve-spec ${head}`,+ ` /approve-spec ${head}`,+ `\t/approve-spec ${head}`,+ `/APPROVE-SPEC ${head}`,+ `> /approve-spec ${head}`,+ ])('does not read %s as an owner command', body => {+ expect(parseOwnerCommandIntent(body)).toBe(null);+ });++ it('refuses to decide on a comment the workflow trigger would drop', () => {+ // resolveOwnerDecision reads every comment on the pull request, not just+ // the one that started the run. A comment GitHub's `startsWith` filter+ // never dispatches must not become approval evidence either.+ for (const body of [+ ` /approve-spec ${head}`,+ `/APPROVE-SPEC ${head}`,+ `> /approve-spec ${head}`,+ ]) {+ expect(isDispatchableOwnerCommand(body)).toBe(false);+ expect(parseOwnerCommand(body, head)).toBe(null);+ expect(+ resolveOwnerDecision({+ reviews: [],+ comments: [{user: owner, body, created_at: '2026-08-30T10:00:00Z'}],+ owners: ['cixzhang'],+ headSha: head,+ }).approved,+ ).toBe(false);+ }+ });++ it('admits exactly what the workflow trigger admits', () => {+ // The trigger is `startsWith(github.event.comment.body, '<prefix>')`:+ // the raw body, untrimmed and case-sensitive.+ const triggerAdmits = body =>+ OWNER_COMMAND_PREFIXES.some(prefix => String(body).startsWith(prefix));++ for (const body of [+ `/approve-spec ${head}`,+ '/approve-spec',+ '/revoke-spec',+ `/revoke-spec ${head}`,+ '/approve-spec abc1234',+ '/approve-spec-now',+ ` /approve-spec ${head}`,+ `/APPROVE-SPEC ${head}`,+ 'Looks good to me',+ '',+ ]) {+ expect(isDispatchableOwnerCommand(body), body).toBe(+ triggerAdmits(body),+ );+ }+ });++ it('explains each way a recognized command misses the head', () => {+ const stale = '1111111111111111111111111111111111111111';+ expect(+ describeOwnerCommandProblem(+ parseOwnerCommandIntent('/approve-spec'),+ head,+ ),+ ).toContain('did not name a commit');+ expect(+ describeOwnerCommandProblem(+ parseOwnerCommandIntent('/approve-spec abc1234'),+ head,+ ),+ ).toContain('full 40-character commit SHA');+ expect(+ describeOwnerCommandProblem(+ parseOwnerCommandIntent(`/approve-spec ${stale}`),+ head,+ ),+ ).toContain('1111111');+ });++ it('accepts a commit SHA in either casing', () => {+ const upper = head.toUpperCase();++ // A SHA copied from a UI that renders it uppercase is the same commit.+ // The validator and the parser must agree, or the gate reports no+ // problem while silently ignoring the command.+ expect(parseOwnerCommand(`/approve-spec ${upper}`, head)).toBe(true);+ expect(parseOwnerCommand(`/revoke-spec ${upper}`, head)).toBe(false);+ expect(+ describeOwnerCommandProblem(+ parseOwnerCommandIntent(`/approve-spec ${upper}`),+ head,+ ),+ ).toBe(null);+ expect(parseOwnerCommand(`/approve-spec ${head}`, upper)).toBe(true);+ });++ it('agrees with the help validator on every recognized command', () => {+ const stale = '1111111111111111111111111111111111111111';++ for (const body of [+ `/approve-spec ${head}`,+ `/approve-spec ${head.toUpperCase()}`,+ `/revoke-spec ${head}`,+ '/approve-spec',+ '/approve-spec abc1234',+ `/approve-spec ${stale}`,+ `/approve-spec ${stale.toUpperCase()}`,+ `/approve-spec ${head} please`,+ ]) {+ const intent = parseOwnerCommandIntent(body);+ const decided = parseOwnerCommand(body, head) !== null;+ const problem = describeOwnerCommandProblem(intent, head);+ // Exactly one of the two is true: the command decides the gate, or+ // the gate can say why it did not.+ expect(decided, body).toBe(problem === null);+ }+ });++ it('reports no problem for the exact form the gate accepts', () => {+ const intent = parseOwnerCommandIntent(`/approve-spec ${head}`);++ expect(describeOwnerCommandProblem(intent, head)).toBe(null);+ expect(parseOwnerCommand(`/approve-spec ${head}`, head)).toBe(true);+ expect(describeOwnerCommandProblem(null, head)).toBe(null);+ });+ });});diff --git a/.github/scripts/spec-owner-reconcile.cjs b/.github/scripts/spec-owner-reconcile.cjsindex 32161ac36a..83a139de94 100644--- a/.github/scripts/spec-owner-reconcile.cjs+++ b/.github/scripts/spec-owner-reconcile.cjs@@ -11,8 +11,10 @@ const {GATE_STATUS_CONTEXT,READY_STATUS_PREFIX,canonicalRunUrl,+ describeOwnerCommandProblem,newestGateRun,parseOwnerCommand,+ parseOwnerCommandIntent,parseOwnerFile,parseReadyAttestations,requiredApprovalGroups,@@ -22,9 +24,7 @@ const {function isCommandComment(eventName, payload) {if (eventName !== 'issue_comment') return true;- return /^\/(approve|revoke)-spec [0-9a-f]{40}$/i.test(- payload.comment?.body?.trim() ?? '',- );+ return parseOwnerCommandIntent(payload.comment?.body) !== null;}function isAuthorizedEvent(eventName, payload, owners) {@@ -45,6 +45,27 @@ function labelNames(pr) {return new Set(pr.labels.map(label => label.name));}+function ownerCommandHelpMarker(headSha) {+ return `<!-- spec-owner-command-help:${headSha} -->`;+}++function ownerCommandHelpBody({verb, headSha, problem}) {+ return [+ ownerCommandHelpMarker(headSha),+ `That \`/${verb}-spec\` comment did not change \`${GATE_STATUS_CONTEXT}\`: ${problem}.`,+ '',+ 'The gate only accepts the exact current head, so post this instead:',+ '',+ ` /${verb}-spec ${headSha}`,+ '',+ 'A new commit invalidates the command, so repeat it after any push.',+ ].join('\n');+}++function isSettled(pr) {+ return Boolean(pr.merged_at) || pr.state === 'closed';+}+async function reconcileSpecOwnerGate({github,context,@@ -93,6 +114,11 @@ async function reconcileSpecOwnerGate({}const runId = BigInt(String(context.runId));+ // A boolean workflow_dispatch input arrives as a real boolean; a string+ // input arrives as text. Only an explicit true opts in.+ const backfillOnly =+ context.eventName === 'workflow_dispatch' &&+ String(context.payload.inputs?.backfill ?? 'false') === 'true';const runUrl = canonicalRunUrl(repository,String(context.runId),@@ -139,16 +165,57 @@ async function reconcileSpecOwnerGate({return newestGateRun(await listStatuses(headSha), repository);}+ /**+ * The freshest possible answer to "may this head still be written at all".+ * A settled or moved head is never writable, whichever run is current: an+ * approval that lands after the merge it claims to gate is not evidence.+ * Any read that throws propagates and nothing is published.+ */+ async function isLiveHeadWritable(headSha) {+ const live = await getPullRequest();+ if (isSettled(live)) {+ core.info(+ 'The pull request settled while this run reconciled; leaving the head status as it merged.',+ );+ return false;+ }+ if (live.head.sha !== headSha) {+ core.info(+ 'The head moved while this run reconciled; leaving the status to the run for the new head.',+ );+ return false;+ }+ return true;+ }++ /**+ * The last read before a terminal write. GitHub has no conditional status+ * write, so the window cannot be closed — it can only be made as small as+ * one API call and made to fail closed. Read the run currency first and the+ * live pull request last, so the head/settlement facts are the freshest+ * thing known at the moment of the write.+ */+ async function isPublishable(headSha) {+ if (!(await isCurrentRun(headSha))) return false;+ return isLiveHeadWritable(headSha);+ }+async function restoreNewerStatus(headSha) {const newest = await newestRun(headSha);if (newest === null || newest.runId <= runId) return false;- await createStatus({- sha: headSha,- context: GATE_STATUS_CONTEXT,- state: newest.status.state,- description: newest.status.description,- targetUrl: newest.status.target_url,- });+ // Yielding is still a write. A newer run's status is no more publishable+ // on a merged or moved head than this run's own would be, so the restore+ // takes the same live guard — and still reports the yield, because this+ // run's claim on the head is over either way.+ if (await isLiveHeadWritable(headSha)) {+ await createStatus({+ sha: headSha,+ context: GATE_STATUS_CONTEXT,+ state: newest.status.state,+ description: newest.status.description,+ targetUrl: newest.status.target_url,+ });+ }core.info(`Run ${context.runId} yielded to newer run ${newest.runId.toString()}.`,);@@ -163,18 +230,28 @@ async function reconcileSpecOwnerGate({async function currentPullForRun(headSha) {const current = await getPullRequest();if (current.head.sha !== headSha) return null;+ if (isSettled(current)) return null;if (!(await isCurrentRun(headSha))) return null;return current;}async function setFinalStatus(headSha, state, description) {- if (!(await isCurrentRun(headSha))) return false;+ if (!(await isPublishable(headSha))) return false;await createStatus({sha: headSha,context: GATE_STATUS_CONTEXT,state,description,});+ // The write cannot be undone, so verify what it landed on. A success that+ // raced a merge is reported loudly and stops this run before auto-merge.+ const after = await getPullRequest();+ if (isSettled(after) || after.head.sha !== headSha) {+ core.warning(+ `Published ${state} for ${headSha.slice(0, 7)} as the pull request settled or moved; treat that status as unverified.`,+ );+ return false;+ }return !(await restoreNewerStatus(headSha));}@@ -340,6 +417,15 @@ async function reconcileSpecOwnerGate({}const initialPr = await getPullRequest();+ // Nothing about a merged or closed head is still being decided. Reconciling+ // one can only publish a decision that arrives after the merge it claims to+ // gate, so stop before writing any status.+ if (isSettled(initialPr)) {+ core.info(+ 'The pull request is already merged or closed; the gate does not rewrite a settled head.',+ );+ return;+ }const initialHead = initialPr.head.sha;await createStatus({sha: initialHead,@@ -352,12 +438,15 @@ async function reconcileSpecOwnerGate({const actor = context.actor?.toLowerCase();const eventHead = context.payload.pull_request?.head?.sha;const eventTime = context.payload.pull_request?.updated_at;+ // Only a DESIGNOWNER author may self-attest a head, and only for the design+ // approval group (.github/DESIGNOWNERS). A spec or engineering owner marking+ // their own pull request ready is not an approval by anyone else.if (context.eventName === 'pull_request_target' &&context.payload.action === 'ready_for_review' &&actor &&actor === initialPr.user.login.toLowerCase() &&- allOwners.has(actor) &&+ designOwners.includes(actor) &&eventHead === initialHead &&eventTime &&!Number.isNaN(Date.parse(eventTime))@@ -401,6 +490,31 @@ async function reconcileSpecOwnerGate({}const {pr, scope, records, reviews, comments, timeline, statuses} = snapshot;++ // A near-miss owner command used to do nothing at all, so an owner could+ // believe they had approved a head the gate never read. Answer it once per+ // head with the exact command instead of leaving it silent.+ if (context.eventName === 'issue_comment' && commentAuthor) {+ const intent = parseOwnerCommandIntent(context.payload.comment?.body);+ const problem = describeOwnerCommandProblem(intent, initialHead);+ const marker = ownerCommandHelpMarker(initialHead);+ if (problem && !comments.some(entry => entry.body?.includes(marker))) {+ await github.rest.issues.createComment({+ owner,+ repo,+ issue_number: pullNumber,+ body: ownerCommandHelpBody({+ verb: intent.verb,+ headSha: initialHead,+ problem,+ }),+ });+ core.info(+ `Answered an inexact ${intent.verb} command on ${initialHead}.`,+ );+ }+ }+if (!scope.touchesKnowledgeRecords) {await disableAutoMerge(pr);await removeLabel(env.REVIEW_LABEL);@@ -442,19 +556,26 @@ async function reconcileSpecOwnerGate({const readyAttestations = parseReadyAttestations(statuses, {repository,headSha: initialHead,+ owners: designOwners,});const decisionInput = {reviews,comments,- readyAttestations,dismissalEvents: timeline,headSha: initialHead,};+ // A ready-for-review attestation is the design group's own self-attestation+ // path. It is not evidence for the spec or theme groups, which stay on real+ // exact-head reviews and commands.const specDecision = requiredGroups.spec? resolveOwnerDecision({...decisionInput, owners: specOwners}): {approved: true, owner: null};const designDecision = requiredGroups.design- ? resolveOwnerDecision({...decisionInput, owners: designApprovers})+ ? resolveOwnerDecision({+ ...decisionInput,+ readyAttestations,+ owners: designApprovers,+ }): {approved: true, owner: null};const themeDecision = requiredGroups.theme? resolveOwnerDecision({...decisionInput, owners: themeApprovers})@@ -531,6 +652,14 @@ async function reconcileSpecOwnerGate({}await removeLabel(env.REVIEW_LABEL);+ // A backfill exists to give an old head its missing status before the+ // context becomes required. Landing the pull request is a separate decision+ // its author has not asked this run to make.+ if (backfillOnly) {+ core.info('Backfill run: published the gate status without auto-merge.');+ return;+ }+let enabledAutoMergeByThisRun = false;if (!pr.auto_merge) {const beforeEnable = await currentPullForRun(initialHead);diff --git a/.github/scripts/spec-owner-reconcile.test.mjs b/.github/scripts/spec-owner-reconcile.test.mjsindex 234f950c1c..60c4e3df45 100644--- a/.github/scripts/spec-owner-reconcile.test.mjs+++ b/.github/scripts/spec-owner-reconcile.test.mjs@@ -92,6 +92,7 @@ function createHarness({autoMerge = null,draft = false,onPullGet,+ onCreateStatus,onEnableAutoMerge,changedFile = {filename: 'docs/specs/owner-ready/spec.md',@@ -109,11 +110,14 @@ function createHarness({reviews: [...reviews],timeline: [...timeline],calls: [],+ reads: [],labels: new Set(labels),knownLabels: new Set(labels),pr: {number: 17,node_id: 'PR_node',+ state: 'open',+ merged_at: null,user: {login: author},head: {sha: head, repo: {full_name: headRepository}},base: {@@ -135,6 +139,7 @@ function createHarness({const methods = {getPull: async () => {state.pullGets += 1;+ state.reads.push('pull');onPullGet?.(state.pullGets, state);syncLabels();return {data: state.pr};@@ -143,9 +148,10 @@ function createHarness({listReviews: async () => ({data: state.reviews}),listComments: async () => ({data: state.comments}),listTimeline: async () => ({data: state.timeline}),- listStatuses: async ({ref}) => ({- data: state.statuses.filter(status => status.sha === ref),- }),+ listStatuses: async ({ref}) => {+ state.reads.push('statuses');+ return {data: state.statuses.filter(status => status.sha === ref)};+ },};const github = {@@ -185,10 +191,21 @@ function createHarness({syncLabels();state.calls.push(`remove-label:${name}`);},+ createComment: async ({body}) => {+ state.comments.push({+ user: {login: 'github-actions[bot]'},+ body,+ created_at: '2026-08-30T10:00:30Z',+ });+ state.calls.push('create-comment');+ return {data: {body}};+ },},repos: {listCommitStatusesForRef: methods.listStatuses,createCommitStatus: async input => {+ onCreateStatus?.(input, state);+ state.reads.push(`status:${input.context}:${input.state}`);const status = {...input,creator: {login: 'github-actions[bot]'},@@ -249,6 +266,19 @@ const designRecord = {};const currentDesign = 'kind: design\nauthority: current\n';+// Exact-head approval by a real spec owner. The auto-merge mechanics below+// need an approved head; they must not borrow the design self-attestation.+const specOwnerReview = {+ user: {login: 'imdreamrunner'},+ state: 'APPROVED',+ commit_id: head,+ submitted_at: '2026-08-30T09:59:00Z',+};++function createApprovedHarness(options = {}) {+ return createHarness({reviews: [specOwnerReview], ...options});+}+function createDesignHarness(options = {}) {return createHarness({author: 'ernestt',@@ -265,17 +295,54 @@ function hasReadyAttestation(state, owner = 'ernestt') {}describe('spec owner workflow reconciliation', () => {- it('treats an eligible owner-author ready event as exact-head approval', async () => {+ it('never lets a spec-owner author self-attest their own head', async () => {const harness = createHarness();await run(harness, context({runId: 100n}));expect(- harness.state.statuses.some(- status => status.context === 'spec-owner-ready/cixzhang',+ harness.state.statuses.some(status =>+ status.context.startsWith('spec-owner-ready/'),),- ).toBe(true);- expect(latestGateStatus(harness.state).state).toBe('success');+ ).toBe(false);+ expect(latestGateStatus(harness.state)).toMatchObject({+ state: 'pending',+ description: expect.stringContaining('spec owner'),+ });+ expect(harness.state.calls).not.toContain('enable-auto-merge');+ expect(harness.state.pr.auto_merge).toBe(null);+ });++ it('keeps a DESIGNOWNER ready attestation out of the spec approval group', async () => {+ const harness = createHarness({+ author: 'ernestt',+ headContent: 'kind: architecture\nauthority: current\n',+ });++ await run(+ harness,+ context({runId: 100n, actor: 'ernestt', author: 'ernestt'}),+ );++ // The attestation is published for the design group, and the spec group+ // still waits for a real exact-head owner decision.+ expect(hasReadyAttestation(harness.state)).toBe(true);+ expect(latestGateStatus(harness.state)).toMatchObject({+ state: 'pending',+ description: expect.stringContaining('spec owner'),+ });+ expect(harness.state.calls).not.toContain('enable-auto-merge');+ });++ it('clears the gate on an exact-head spec-owner review', async () => {+ const harness = createApprovedHarness();++ await run(harness, context({runId: 100n}));++ expect(latestGateStatus(harness.state)).toMatchObject({+ state: 'success',+ description: expect.stringContaining('Approved by @imdreamrunner'),+ });expect(harness.state.calls).toContain('enable-auto-merge');});@@ -399,7 +466,7 @@ describe('spec owner workflow reconciliation', () => {});it('publishes owner approval and keeps conservative ownership when enablement is rejected', async () => {- const harness = createHarness({+ const harness = createApprovedHarness({onEnableAutoMerge: () => {const error = new Error('Resource not accessible by integration');error.status = 403;@@ -411,7 +478,7 @@ describe('spec owner workflow reconciliation', () => {expect(latestGateStatus(harness.state)).toMatchObject({state: 'success',- description: expect.stringContaining('Approved by @cixzhang'),+ description: expect.stringContaining('Approved by @imdreamrunner'),});const terminalStatus = harness.state.calls.indexOf('status:spec-owner-approval:success',@@ -429,7 +496,7 @@ describe('spec owner workflow reconciliation', () => {});it('preserves the marker when an ambiguous enable error follows a successful mutation', async () => {- const harness = createHarness({+ const harness = createApprovedHarness({onEnableAutoMerge: state => {state.pr.auto_merge = {merge_method: 'squash'};state.calls.push('auto-merge-applied-before-error');@@ -449,7 +516,7 @@ describe('spec owner workflow reconciliation', () => {});it('does not let an old failure erase newer same-head auto-merge ownership', async () => {- const harness = createHarness({+ const harness = createApprovedHarness({onEnableAutoMerge: state => {// The old run added the marker, then a newer run for the same exact// head enabled auto-merge before the old request returned an error.@@ -722,7 +789,7 @@ describe('spec owner workflow reconciliation', () => {});it('disables gate-owned auto-merge before reconciling a later revoke', async () => {- const harness = createHarness();+ const harness = createApprovedHarness();await run(harness, context({runId: 100n}));harness.state.comments.push({user: {login: 'cixzhang'},@@ -752,7 +819,7 @@ describe('spec owner workflow reconciliation', () => {});it('undoes its own enable when a revoke supersedes it after the ownership label is removed', async () => {- const harness = createHarness({+ const harness = createApprovedHarness({onEnableAutoMerge: state => {state.statuses.unshift(trustedStatus({runId: 101n}));state.labels.delete('spec-auto-merge');@@ -992,4 +1059,361 @@ describe('spec owner workflow reconciliation', () => {);expect(harness.state.pullGets).toBe(0);});++ describe('a settled head is never re-decided', () => {+ it('publishes nothing once the pull request has merged', async () => {+ const harness = createApprovedHarness();+ harness.state.pr.merged_at = '2026-08-30T09:58:00Z';+ harness.state.pr.state = 'closed';++ await run(harness, context({runId: 100n}));++ expect(harness.state.statuses).toEqual([]);+ expect(harness.state.calls).toEqual([+ 'info:The pull request is already merged or closed; the gate does not rewrite a settled head.',+ ]);+ });++ it('publishes nothing once the pull request has closed unmerged', async () => {+ const harness = createApprovedHarness();+ harness.state.pr.state = 'closed';++ await run(harness, context({runId: 100n}));++ expect(harness.state.statuses).toEqual([]);+ expect(harness.state.calls).not.toContain(+ 'status:spec-owner-approval:pending',+ );+ });++ it('does not upgrade a head that merges while the run reconciles', async () => {+ // The incident shape: the owner event arrives, the pull request merges+ // unapproved, and the late run must not write approval onto that head.+ const harness = createApprovedHarness({+ onPullGet: (count, state) => {+ if (count >= 3) {+ state.pr.merged_at = '2026-08-30T10:00:15Z';+ state.pr.state = 'closed';+ }+ },+ });++ await run(harness, context({runId: 100n}));++ expect(+ harness.state.statuses.some(+ status =>+ status.context === 'spec-owner-approval' &&+ status.state === 'success',+ ),+ ).toBe(false);+ expect(harness.state.calls).not.toContain('enable-auto-merge');+ expect(+ harness.state.calls.some(call =>+ call.includes('settled while this run reconciled'),+ ),+ ).toBe(true);+ });++ it('reports a success that raced the merge and stops before auto-merge', async () => {+ // The window between the last read and the write cannot be closed with+ // GitHub's APIs. When it loses, the run must say so and go no further.+ let publishedAt = null;+ const harness = createApprovedHarness({+ onPullGet: (count, state) => {+ if (publishedAt !== null && count > publishedAt) {+ state.pr.merged_at = '2026-08-30T10:00:20Z';+ state.pr.state = 'closed';+ }+ },+ onCreateStatus: (input, state) => {+ if (+ input.context === 'spec-owner-approval' &&+ input.state === 'success'+ ) {+ publishedAt = state.pullGets;+ }+ },+ });++ await run(harness, context({runId: 100n}));++ expect(harness.state.calls).not.toContain('enable-auto-merge');+ expect(harness.state.pr.auto_merge).toBe(null);+ expect(+ harness.state.calls.some(call =>+ call.includes('treat that status as unverified'),+ ),+ ).toBe(true);+ });++ it('reads the live pull request as the last call before publishing', async () => {+ const harness = createApprovedHarness();++ await run(harness, context({runId: 100n}));++ const reads = harness.state.reads;+ const publish = reads.indexOf('status:spec-owner-approval:success');+ expect(publish).toBeGreaterThan(0);+ expect(reads[publish - 1]).toBe('pull');+ });++ it('does not enable auto-merge on a head that settled after the status landed', async () => {+ // Past the terminal write and its verification, the enable path has its+ // own read; that read must also refuse a settled pull request.+ let publishedAt = null;+ const harness = createApprovedHarness({+ onPullGet: (count, state) => {+ if (publishedAt !== null && count >= publishedAt + 2) {+ state.pr.merged_at = '2026-08-30T10:00:25Z';+ state.pr.state = 'closed';+ }+ },+ onCreateStatus: (input, state) => {+ if (+ input.context === 'spec-owner-approval' &&+ input.state === 'success'+ ) {+ publishedAt = state.pullGets;+ }+ },+ });++ await run(harness, context({runId: 100n}));++ expect(latestGateStatus(harness.state).state).toBe('success');+ expect(harness.state.calls).not.toContain('enable-auto-merge');+ expect(harness.state.pr.auto_merge).toBe(null);+ });+ });++ it('ignores a ready marker from a handle that is not a design owner', async () => {+ // Live shape from PR #5543: a spec owner marked their own PR ready before+ // the design-only rule, leaving a trusted spec-owner-ready status on the+ // head. It must not satisfy the design group it is not a member of.+ const harness = createDesignHarness({+ author: 'imdreamrunner',+ statuses: [+ trustedStatus({+ runId: 90n,+ statusContext: 'spec-owner-ready/imdreamrunner',+ state: 'success',+ description: 'Owner ready at 2026-09-04T05:54:18.000Z.',+ }),+ ],+ });++ await run(+ harness,+ context({+ runId: 100n,+ action: 'synchronize',+ actor: 'imdreamrunner',+ author: 'imdreamrunner',+ }),+ );++ expect(latestGateStatus(harness.state)).toMatchObject({+ state: 'pending',+ description: expect.stringContaining('design approver'),+ });+ expect(harness.state.calls).not.toContain('enable-auto-merge');+ });++ it('still honours a ready marker from a current design owner', async () => {+ const harness = createDesignHarness({+ statuses: [+ trustedStatus({+ runId: 90n,+ statusContext: 'spec-owner-ready/ernestt',+ state: 'success',+ description: 'Owner ready at 2026-08-30T09:59:00.000Z.',+ }),+ ],+ });++ await run(+ harness,+ context({+ runId: 100n,+ action: 'synchronize',+ actor: 'ernestt',+ author: 'ernestt',+ }),+ );++ expect(latestGateStatus(harness.state)).toMatchObject({+ state: 'success',+ description: expect.stringContaining('@ernestt'),+ });+ });++ it('does not restore a newer run\u2019s status onto a settled head', async () => {+ // Yielding writes too. If the pull request merged while this run worked,+ // the newer run's status is no more publishable than this run's own.+ const harness = createApprovedHarness({+ statuses: [trustedStatus({runId: 101n, state: 'success'})],+ onPullGet: (count, state) => {+ if (count >= 2) {+ state.pr.merged_at = '2026-08-30T10:00:10Z';+ state.pr.state = 'closed';+ }+ },+ });++ await run(harness, context({runId: 100n}));++ expect(+ harness.state.statuses.filter(+ status =>+ status.context === 'spec-owner-approval' &&+ status.target_url === canonicalRunUrl(repository, '101', '1'),+ ),+ ).toHaveLength(1);+ expect(harness.state.calls).not.toContain('enable-auto-merge');+ });++ it('still restores a newer run\u2019s status on a live head', async () => {+ const harness = createApprovedHarness({+ statuses: [trustedStatus({runId: 101n, state: 'success'})],+ });++ await run(harness, context({runId: 100n}));++ expect(latestGateStatus(harness.state)).toMatchObject({+ state: 'success',+ target_url: canonicalRunUrl(repository, '101', '1'),+ });+ expect(+ harness.state.calls.some(call => call.includes('yielded to newer run')),+ ).toBe(true);+ });++ describe('a backfill run publishes status without landing anything', () => {+ function backfillContext(runId) {+ return {+ actor: 'cixzhang',+ eventName: 'workflow_dispatch',+ runId,+ runAttempt: 1,+ repo: {owner: 'facebook', repo: 'astryx'},+ payload: {inputs: {pr: '17', backfill: true}},+ };+ }++ it('publishes the missing status and never enables auto-merge', async () => {+ const harness = createApprovedHarness();++ await run(harness, backfillContext(100n));++ expect(latestGateStatus(harness.state)).toMatchObject({+ state: 'success',+ description: expect.stringContaining('Approved by @imdreamrunner'),+ });+ expect(harness.state.calls).not.toContain('enable-auto-merge');+ expect(harness.state.pr.auto_merge).toBe(null);+ expect(+ harness.state.calls.some(call => call.includes('Backfill run')),+ ).toBe(true);+ });++ it('still enables auto-merge on an ordinary dispatch', async () => {+ const harness = createApprovedHarness();+ const ordinary = backfillContext(100n);+ ordinary.payload.inputs.backfill = false;++ await run(harness, ordinary);++ expect(harness.state.calls).toContain('enable-auto-merge');+ });++ it('treats a string input the same way the form submits it', async () => {+ const harness = createApprovedHarness();+ const stringInput = backfillContext(100n);+ stringInput.payload.inputs.backfill = 'true';++ await run(harness, stringInput);++ expect(harness.state.calls).not.toContain('enable-auto-merge');+ });++ it('still refuses to publish onto an already merged head', async () => {+ const harness = createApprovedHarness();+ harness.state.pr.merged_at = '2026-08-30T09:00:00Z';+ harness.state.pr.state = 'closed';++ await run(harness, backfillContext(100n));++ expect(harness.state.statuses).toEqual([]);+ });+ });++ describe('an owner command that misses the exact head is answered', () => {+ function commandRun(body, harness = createHarness()) {+ const comment = {+ user: {login: 'cixzhang'},+ body,+ created_at: '2026-08-30T10:00:00Z',+ };+ harness.state.comments.push(comment);+ return {+ harness,+ comment,+ promise: run(+ harness,+ context({+ runId: 100n,+ eventName: 'issue_comment',+ action: 'created',+ comment,+ }),+ ),+ };+ }++ it.each([+ ['/approve-spec', 'did not name a commit'],+ ['/approve-spec abc1234', 'full 40-character commit SHA'],+ [`/approve-spec ${nextHead}`, 'is not the current head'],+ ])('answers %s instead of ignoring it', async (body, reason) => {+ const {harness, promise} = commandRun(body);+ await promise;++ const help = harness.state.comments.at(-1);+ expect(harness.state.calls).toContain('create-comment');+ expect(help.body).toContain(`<!-- spec-owner-command-help:${head} -->`);+ expect(help.body).toContain(reason);+ expect(help.body).toContain(`/approve-spec ${head}`);+ expect(latestGateStatus(harness.state).state).toBe('pending');+ expect(harness.state.calls).not.toContain('enable-auto-merge');+ });++ it('names the revoke verb the owner actually used', async () => {+ const {harness, promise} = commandRun('/revoke-spec');+ await promise;++ expect(harness.state.comments.at(-1).body).toContain(+ `/revoke-spec ${head}`,+ );+ });++ it('answers a given head only once', async () => {+ const {harness, promise} = commandRun('/approve-spec');+ await promise;+ const {promise: second} = commandRun('/approve-spec', harness);+ await second;++ expect(+ harness.state.calls.filter(call => call === 'create-comment'),+ ).toHaveLength(1);+ });++ it('stays quiet when the command names the exact head', async () => {+ const {harness, promise} = commandRun(`/approve-spec ${head}`);+ await promise;++ expect(harness.state.calls).not.toContain('create-comment');+ expect(latestGateStatus(harness.state).state).toBe('success');+ });+ });});diff --git a/.github/scripts/spec-owner-workflow.test.mjs b/.github/scripts/spec-owner-workflow.test.mjsindex f91d6c4f99..fe5ac6e139 100644--- a/.github/scripts/spec-owner-workflow.test.mjs+++ b/.github/scripts/spec-owner-workflow.test.mjs@@ -4,8 +4,11 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import {spawnSync} from 'node:child_process';+import {createRequire} from 'node:module';import {describe, expect, it} from 'vitest';+const require = createRequire(import.meta.url);+const root = path.resolve(import.meta.dirname, '../..');const read = relative => fs.readFileSync(path.join(root, relative), 'utf8');@@ -160,17 +163,22 @@ describe('spec-only workflow contract', () => {.replace(/\s+/g, ' ').trim();expect(reconcileCondition).toBe(- "(github.event_name != 'pull_request_review' || github.event.pull_request.head.repo.full_name == github.repository) && (github.event_name != 'issue_comment' || (github.event.issue.pull_request != null && (startsWith(github.event.comment.body, '/approve-spec ') || startsWith(github.event.comment.body, '/revoke-spec '))))",+ "(github.event_name != 'pull_request_review' || github.event.pull_request.head.repo.full_name == github.repository) && (github.event_name != 'issue_comment' || (github.event.issue.pull_request != null && (startsWith(github.event.comment.body, '/approve-spec') || startsWith(github.event.comment.body, '/revoke-spec'))))",);expect(workflow).toContain('pull_request_review:');expect(workflow).toContain('issue_comment:');expect(workflow).toContain('permissions: {}');expect(workflow).not.toContain('pull_request_review_target');+ // The filter must admit a command that omits the head SHA so the+ // reconciler can answer it; a trailing space would drop it silently.expect(workflow).toContain(- "startsWith(github.event.comment.body, '/approve-spec ')",+ "startsWith(github.event.comment.body, '/approve-spec')",);expect(workflow).toContain(- "startsWith(github.event.comment.body, '/revoke-spec ')",+ "startsWith(github.event.comment.body, '/revoke-spec')",+ );+ expect(workflow).not.toContain(+ "startsWith(github.event.comment.body, '/approve-spec ')",);expect(reconciler).toContain('expectedCount: after.changed_files');expect(reconciler).toContain('scope.touchesKnowledgeRecords');@@ -184,6 +192,15 @@ describe('spec-only workflow contract', () => {expect(reconciler).not.toContain('...new Set([...specOwners, ...engineeringOwners, ...designOwners])',);+ // Only a DESIGNOWNER author self-attests, and only the design group+ // reads that attestation.+ expect(reconciler).toContain('designOwners.includes(actor)');+ expect(reconciler).not.toContain('allOwners.has(actor)');+ expect(reconciler).toContain(+ 'readyAttestations,\n owners: designApprovers',+ );+ expect(reconciler).toContain('isSettled(initialPr)');+ expect(reconciler).toContain('isPublishable(headSha)');expect(reconciler).toContain('specDecision.approved');expect(reconciler).toContain('designDecision.approved');expect(reconciler).toContain('themeDecision.approved');@@ -193,6 +210,84 @@ describe('spec-only workflow contract', () => {expect(reconciler).toContain('disablePullRequestAutoMerge');});+ it('derives the comment trigger from the parser\u2019s own prefixes', () => {+ const workflow = read('.github/workflows/spec-owner-gate.yml');+ const {OWNER_COMMAND_PREFIXES} = require(+ path.join(root, '.github/scripts/spec-owner-decision.cjs'),+ );++ // Every prefix the parser accepts must appear in the trigger, and the+ // trigger must name no prefix the parser does not accept. A mismatch is+ // the silent failure mode: a comment that parses but never dispatches.+ const triggerPrefixes = [+ ...workflow.matchAll(+ /startsWith\(github\.event\.comment\.body, '([^']+)'\)/g,+ ),+ ].map(match => match[1]);+ expect(new Set(triggerPrefixes)).toEqual(new Set(OWNER_COMMAND_PREFIXES));+ for (const prefix of triggerPrefixes) {+ expect(prefix.trimEnd(), prefix).toBe(prefix);+ }+ });++ it('offers a backfill dispatch that publishes status without landing', () => {+ const workflow = read('.github/workflows/spec-owner-gate.yml');+ const reconciler = read('.github/scripts/spec-owner-reconcile.cjs');++ expect(workflow).toContain('backfill:');+ expect(workflow).toContain('type: boolean');+ expect(reconciler).toContain("context.eventName === 'workflow_dispatch'");+ expect(reconciler).toContain('backfillOnly');+ // The guard must sit after the terminal status and before enablement.+ const publish = reconciler.indexOf(+ "setFinalStatus(initialHead, 'success', successDescription)",+ );+ const guard = reconciler.indexOf('if (backfillOnly) {');+ const enable = reconciler.indexOf('enablePullRequestAutoMerge');+ expect(publish).toBeGreaterThan(-1);+ expect(guard).toBeGreaterThan(publish);+ expect(enable).toBeGreaterThan(guard);+ });++ it('keeps the last read before a terminal write on the live pull request', () => {+ const reconciler = read('.github/scripts/spec-owner-reconcile.cjs');+ const guard = reconciler.slice(+ reconciler.indexOf('async function isLiveHeadWritable('),+ reconciler.indexOf('async function restoreNewerStatus('),+ );++ expect(guard).toContain('isSettled(live)');+ expect(guard).toContain('live.head.sha !== headSha');+ // isPublishable checks run currency first, then delegates the live read,+ // so the freshest fact at the moment of the write is the pull request.+ const publishable = reconciler.slice(+ reconciler.indexOf('async function isPublishable('),+ reconciler.indexOf('async function restoreNewerStatus('),+ );+ expect(publishable.indexOf('await isCurrentRun(headSha)')).toBeLessThan(+ publishable.indexOf('isLiveHeadWritable(headSha)'),+ );+ expect(reconciler).toContain('treat that status as unverified');++ // Every gate-status write goes through a live guard, restores included.+ const restore = reconciler.slice(+ reconciler.indexOf('async function restoreNewerStatus('),+ reconciler.indexOf('async function isCurrentRun('),+ );+ expect(restore).toContain('await isLiveHeadWritable(headSha)');+ expect(restore.indexOf('await isLiveHeadWritable(headSha)')).toBeLessThan(+ restore.indexOf('createStatus('),+ );+ });++ it('reads a ready attestation back only for a current design owner', () => {+ const reconciler = read('.github/scripts/spec-owner-reconcile.cjs');+ const decision = read('.github/scripts/spec-owner-decision.cjs');++ expect(reconciler).toContain('owners: designOwners');+ expect(decision).toContain('!allowed.has(owner)');+ });+it('does not run the privileged visual-report path for spec-only PRs', () => {const workflow = read('.github/workflows/pr-comment.yml');expect(workflow).toContain("needs.resolve.outputs.spec_only != 'true'");diff --git a/.github/scripts/visual-gate/README.md b/.github/scripts/visual-gate/README.mdindex 8fce3327ad..09e3d4c822 100644--- a/.github/scripts/visual-gate/README.md+++ b/.github/scripts/visual-gate/README.md@@ -114,6 +114,18 @@ The daily gate uses the same boundary: `stableStoryPackages` inhold a stable release. Pass `--story-packages '*'` only for an explicitnon-release audit.+Ownership decides which stories may own canonical frames, and a Storybook title+is only evidence of it. When the index records the source file of the component+a story declares, that source decides: a Core component keeps its frames even+when its story is titled under another group, and a composed demo cannot earn+one by importing Core. `stableStoryGroups` is the fallback for the stories that+declare no component at all, where the title group is the only signal there is.++An empty plan is refused rather than reported clean, in every lane. A plan with+no shots compares nothing, so a scope whose keys are missing from the accepted+baseline fails closed and says so; seed the missing frames through the manual+baseline workflow.+`.github/scripts/visual-scope.mjs` owns that classification from packagemetadata; workflow YAML does not hard-code today's package names.diff --git a/.github/scripts/visual-gate/gate-context.test.mjs b/.github/scripts/visual-gate/gate-context.test.mjsindex 89eaf2f901..b324c98b1e 100644--- a/.github/scripts/visual-gate/gate-context.test.mjs+++ b/.github/scripts/visual-gate/gate-context.test.mjs@@ -1,6 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {execFileSync} from 'node:child_process';+import {execFileSync, spawnSync} from 'node:child_process';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -63,7 +63,7 @@ describe('stable release plan authority', () => {it('owns a closed Neutral and Probe baseline without preserving obsolete keys', () => {const source = fs.readFileSync(SCRIPT, 'utf8');expect(source).toContain("const RELEASE_TIERS = ['surface', 'probe'];");- expect(source).toContain('storiesInStorybookGroups(');+ expect(source).toContain('canonicalBaselineStories(');expect(source).not.toContain('shots = withBaselineCoverage(');expect(source).toContain('const baselineManifest = rawBaseline;');expect(source).toContain(@@ -75,6 +75,25 @@ describe('stable release plan authority', () => {});});+describe('empty visual plans', () => {+ it('refuses to capture a plan with no shots instead of reporting it clean', () => {+ fs.writeFileSync(plan, JSON.stringify([]));+ const result = spawnSync(+ process.execPath,+ [SCRIPT, 'check', '--plan-file', plan, '--out', output],+ {encoding: 'utf8'},+ );+ expect(result.status).toBe(1);+ expect(result.stderr).toMatch(+ /The exact trusted plan planned no shots;.*manual baseline workflow\./,+ );+ // The refusal comes before the shutter: nothing is captured, nothing is+ // compared, and there is no clean verdict for a reader to trust.+ expect(fs.existsSync(path.join(output, 'manifest.json'))).toBe(false);+ expect(fs.existsSync(path.join(output, 'verdict.json'))).toBe(false);+ });+});+describe('visual gate capture identity', () => {it('records the GitHub run identity by default', () => {expect(diff --git a/.github/scripts/visual-gate/gate.mjs b/.github/scripts/visual-gate/gate.mjsindex 820e03aaba..727b6109e8 100644--- a/.github/scripts/visual-gate/gate.mjs+++ b/.github/scripts/visual-gate/gate.mjs@@ -40,14 +40,15 @@ import {accountBaseline,baselineVisualStories,buildPlan,+ canonicalBaselineStories,createReleasePlan,+ emptyVisualPlanMessage,exceedsPrVisualShotLimit,existingComponentBaselinePlan,readStoryIndex,readThemeCatalog,resolvePrVisualTotalShotLimit,storiesInPackages,- storiesInStorybookGroups,summarizeBaselineAccounting,withThemeMetadata,} from './lib/plan.mjs';@@ -196,10 +197,10 @@ async function plan() {REPO_ROOT,);const packageStories = storiesInPackages(indexedStories, storyPackages);- const stories = storiesInStorybookGroups(- packageStories,- config.stableStoryGroups,- );+ const stories = canonicalBaselineStories(packageStories, {+ groups: config.stableStoryGroups,+ packages: storyPackages,+ });const {manifest: baselineManifest} = readBaseline(baselineDir);const componentThemes = acceptedVisualThemes(baselineManifest,@@ -300,7 +301,20 @@ async function plan() {};}+/** How this run describes what it planned, for a refusal a human has to act on. */+function plannedScope() {+ if (planFile) return 'The exact trusted plan';+ if (components.length) return `Component scope ${components.join(', ')}`;+ return `Tier scope ${tiers.join(', ')}`;+}+async function runCapture(shots, releasePlan = null) {+ // An empty plan is not a clean run. Every lane that captures pixels refuses+ // one here, on the way in, so a scope whose keys are missing from the+ // accepted baseline cannot report the absence of evidence as evidence.+ if (shots.length === 0) {+ throw new Error(emptyVisualPlanMessage(plannedScope()));+ }if (shots.length > config.visualPlanSafetyLimit) {throw new Error(`Visual plan has ${shots.length} shots; safety limit is ${config.visualPlanSafetyLimit}.`,diff --git a/.github/scripts/visual-gate/lib/plan.mjs b/.github/scripts/visual-gate/lib/plan.mjsindex 0d68e12cb5..b579b76c4d 100644--- a/.github/scripts/visual-gate/lib/plan.mjs+++ b/.github/scripts/visual-gate/lib/plan.mjs@@ -134,6 +134,12 @@ function storyPackageNames(entry, storybookDir, repoRoot, catalog) {return {packageNames: names.length ? names : [owner],packageName: owner,+ // The package that OWNS the component's source, when Storybook recorded+ // one. `packageName` can be inferred from imports or from the title, so it+ // says which package a story belongs to; this says which package publishes+ // the thing it photographs, and only that answers "may this story own a+ // canonical baseline frame".+ componentPackage: fromComponent ?? null,stableVisual: eligible(catalog.get(owner)),};}@@ -336,7 +342,7 @@ export function createReleasePlan(shots) {** @param {string} storybookDir* @param {Iterable<string>} excluded - story ids (or `prefix*`) excluded by config- * @returns {Array<{id: string, title: string, name: string, component: string, tags: string[]}>}+ * @returns {Array<{id: string, title: string, name: string, component: string, tags: string[], packageNames: string[], packageName: string, componentPackage: string | null, stableVisual: boolean}>}*/export function readStoryIndex(storybookDir, excluded = [], repoRoot) {const exclusions = [...excluded];@@ -391,15 +397,43 @@ function componentOf(entry) {*/export function storiesInPackages(stories, packages) {if (packages.includes('*')) return stories;- const wanted = new Set(packages.map(name => name.startsWith('@') ? name : `@astryxdesign/${name.toLowerCase()}`));+ const wanted = new Set(packages.map(configuredPackageName));return stories.filter(story => story.stableVisual && story.packageNames.some(name => wanted.has(name)));}-/** Restrict canonical baselines to named Storybook title groups. */-export function storiesInStorybookGroups(stories, groups) {+/** Config names a package either by its Storybook group (`Core`) or in full. */+function configuredPackageName(name) {+ return name.startsWith('@') ? name : `@astryxdesign/${name.toLowerCase()}`;+}++/**+ * Which stories may own canonical baseline frames.+ *+ * The question is ownership, and a Storybook title is only ever evidence of+ * it. A story that merely IMPORTS Core components must not own a canonical+ * frame; a component Core publishes must not lose its frames because its story+ * happens to be titled under another group. Storybook records the source file+ * of the component a story declares, and `readStoryIndex` resolves that file+ * to its workspace package, so when the index has that fact it decides.+ * `groups` is the fallback for stories that declare no component at all —+ * composed demos and template pages — where the title group is the only+ * ownership signal there is.+ *+ * `*` is an explicit audit override in either list, never the release default.+ *+ * @param {ReturnType<typeof readStoryIndex>} stories+ * @param {{groups: string[], packages: string[]}} owners+ */+export function canonicalBaselineStories(stories, {groups, packages}) {if (groups.includes('*')) return stories;- const wanted = new Set(groups);- return stories.filter(story => wanted.has(String(story.title).split('/')[0]));+ const everyPackage = packages.includes('*');+ const wantedGroups = new Set(groups);+ const wantedPackages = new Set(packages.map(configuredPackageName));+ return stories.filter(story =>+ story.componentPackage+ ? everyPackage || wantedPackages.has(story.componentPackage)+ : wantedGroups.has(String(story.title).split('/')[0]),+ );}/**@@ -530,6 +564,22 @@ export function exceedsPrVisualShotLimit(count, limit) {return count > limit;}+/**+ * Why every lane refuses an empty plan.+ *+ * A run that captures nothing compares nothing, so a clean verdict from one+ * reports the absence of evidence as evidence. Every lane reaches that state+ * the same way — a scope whose keys are not in the accepted baseline — so they+ * refuse it with one sentence rather than three behaviors, and they name the+ * one path that can seed the missing frames.+ *+ * @param {string} scope - what the lane planned, named for the message+ * @returns {string}+ */+export function emptyVisualPlanMessage(scope) {+ return `${scope} planned no shots; an empty plan compares nothing and cannot report clean. Seed coverage through the manual baseline workflow.`;+}+/*** @param {string} name* @returns {number}diff --git a/.github/scripts/visual-gate/lib/plan.test.mjs b/.github/scripts/visual-gate/lib/plan.test.mjsindex 92ef495af6..5d8d112ecb 100644--- a/.github/scripts/visual-gate/lib/plan.test.mjs+++ b/.github/scripts/visual-gate/lib/plan.test.mjs@@ -11,7 +11,9 @@ import {accountBaseline,baselineVisualStories,buildPlan,+ canonicalBaselineStories,createReleasePlan,+ emptyVisualPlanMessage,exceedsPrVisualShotLimit,existingComponentBaselinePlan,readStoryIndex,@@ -20,7 +22,6 @@ import {resolvePrVisualTotalShotLimit,shotKey,storiesInPackages,- storiesInStorybookGroups,summarizeBaselineAccounting,uncoveredTargets,} from './plan.mjs';@@ -67,8 +68,10 @@ describe('storiesInPackages', () => {});});-describe('storiesInStorybookGroups', () => {- it('keeps only canonical title groups even when another group imports Core', () => {+describe('canonicalBaselineStories', () => {+ const owners = {groups: ['Core'], packages: ['Core']};++ it('keeps only canonical title groups when no story declares a component', () => {const mixed = [...stories,story({@@ -85,9 +88,49 @@ describe('storiesInStorybookGroups', () => {}),];expect(- storiesInStorybookGroups(mixed, ['Core']).map(story => story.id),+ canonicalBaselineStories(mixed, owners).map(story => story.id),).toEqual(stories.map(story => story.id));});++ it('keeps a published component whose only story is titled under another group', () => {+ const resizable = story({+ id: 'lab-resizable--horizontal-split',+ title: 'Lab/Resizable',+ name: 'Horizontal Split',+ component: 'Resizable',+ componentPackage: '@astryxdesign/core',+ });+ expect(+ canonicalBaselineStories([...stories, resizable], owners).map(+ story => story.id,+ ),+ ).toContain('lab-resizable--horizontal-split');+ });++ it('drops a canary component even when its story is titled under a canonical group', () => {+ const labInCore = story(+ {+ id: 'core-drawer--default',+ title: 'Core/Drawer',+ name: 'Default',+ component: 'Drawer',+ componentPackage: '@astryxdesign/lab',+ },+ '@astryxdesign/lab',+ false,+ );+ expect(+ canonicalBaselineStories([...stories, labInCore], owners).map(+ story => story.id,+ ),+ ).toEqual(stories.map(story => story.id));+ });++ it('allows an explicit all-groups audit without changing the release default', () => {+ expect(canonicalBaselineStories(stories, {...owners, groups: ['*']})).toEqual(+ stories,+ );+ });});describe('representativeStories', () => {@@ -224,6 +267,14 @@ describe('exceedsPrVisualShotLimit', () => {});});+describe('emptyVisualPlanMessage', () => {+ it('names the scope that planned nothing and the one path that seeds frames', () => {+ expect(emptyVisualPlanMessage('Component scope Resizable')).toMatch(+ /^Component scope Resizable planned no shots;.*manual baseline workflow\.$/,+ );+ });+});+describe('buildPlan', () => {it('photographs one story per component in the default theme for the surface tier', () => {const plan = buildPlan({stories, targets, themeOverrides, defaultTheme: 'neutral', tiers: ['surface']});@@ -441,6 +492,7 @@ describe('readStoryIndex package metadata', () => {fs.mkdirSync(path.join(storybook, 'stories'), {recursive: true});fs.mkdirSync(dist);fs.writeFileSync(path.join(storybook, 'stories/Composite.stories.tsx'), "import {Table} from '@astryxdesign/core/Table';");+ fs.writeFileSync(path.join(storybook, 'stories/Dune.stories.tsx'), "import {Table} from '@astryxdesign/core/Table';");fs.writeFileSync(path.join(storybook, 'stories/Lab.stories.tsx'), "import {Thing} from '@astryxdesign/lab'; import {Button} from '@astryxdesign/core/Button';");fs.writeFileSync(path.join(storybook, 'stories/CoreMixed.stories.tsx'), "import {Thing} from '@astryxdesign/lab'; import {Layer} from '@astryxdesign/core/Layer';");fs.writeFileSync(path.join(storybook, 'stories/Probe.stories.tsx'), "import {Button} from '@astryxdesign/core/Button';");@@ -452,6 +504,10 @@ describe('readStoryIndex package metadata', () => {mixed: {type: 'story', id: 'core-layer--default', title: 'Core/Layer', name: 'Default', importPath: './stories/CoreMixed.stories.tsx'},probe: {type: 'story', id: 'core-probe--default', title: 'Core/Themes/Probe Theme', name: 'Default', importPath: './stories/Probe.stories.tsx'},prOnly: {type: 'story', id: 'core-new--default', title: 'Core/New', name: 'Default', importPath: './stories/NewPrOnly.stories.tsx'},+ // A Core component whose only story sits under another title group, and a+ // template page that merely composes Core components.+ elsewhere: {type: 'story', id: 'lab-resizable--split', title: 'Lab/Resizable', name: 'Split', componentPath: '../../packages/core/src/Resizable/index.ts', importPath: './stories/Resizable.stories.tsx'},+ template: {type: 'story', id: 'dune--overview', title: 'Dune', name: 'Overview', importPath: './stories/Dune.stories.tsx'},skipped: {type: 'story', id: 'core-skip--default', title: 'Core/Skip', name: 'Default', tags: ['no-visual']},}}));return {root, dist};@@ -474,6 +530,33 @@ describe('readStoryIndex package metadata', () => {}});+ it('resolves canonical ownership from the declared component, not the title group', () => {+ const {root, dist} = fixture();+ try {+ const indexed = readStoryIndex(dist, [], root);+ expect(indexed.find(value => value.id === 'lab-resizable--split')).toMatchObject({+ component: 'Resizable',+ packageName: '@astryxdesign/core',+ componentPackage: '@astryxdesign/core',+ });+ expect(indexed.find(value => value.id === 'dune--overview')).toMatchObject({+ packageName: '@astryxdesign/core',+ componentPackage: null,+ });+ const canonical = canonicalBaselineStories(+ storiesInPackages(indexed, ['Core']),+ {groups: ['Core'], packages: ['Core']},+ ).map(value => value.id);+ // A published Core component keeps its frames wherever its story is+ // titled; a template page that only imports Core still owns none.+ expect(canonical).toContain('lab-resizable--split');+ expect(canonical).not.toContain('dune--overview');+ expect(canonical).not.toContain('charts-bar--default');+ } finally {+ fs.rmSync(root, {recursive: true, force: true});+ }+ });+it('allows the private probe theme only as an explicit baseline fixture', () => {const {root} = fixture();try {diff --git a/.github/scripts/visual-gate/visual-acceptance.mjs b/.github/scripts/visual-gate/visual-acceptance.mjsindex c5448fd43d..e4ab52fd16 100644--- a/.github/scripts/visual-gate/visual-acceptance.mjs+++ b/.github/scripts/visual-gate/visual-acceptance.mjs@@ -22,7 +22,9 @@ import {canonicalizePng} from './lib/canonical-png.mjs';import {acceptedVisualThemes,baselineVisualStories,+ canonicalBaselineStories,componentVisualStories,+ emptyVisualPlanMessage,exceedsPrVisualShotLimit,readStoryIndex,readThemeCatalog,@@ -30,7 +32,6 @@ import {shotKey,stableBaseline,storiesInPackages,- storiesInStorybookGroups,VISUAL_BASELINE_TAG,withThemeMetadata,} from './lib/plan.mjs';@@ -738,10 +739,10 @@ function trustedPlan() {allIndexed,config.stableStoryPackages,);- const indexed = storiesInStorybookGroups(- packageStories,- config.stableStoryGroups,- );+ const indexed = canonicalBaselineStories(packageStories, {+ groups: config.stableStoryGroups,+ packages: config.stableStoryPackages,+ });const {baseline} = readTrustedBaseline(allIndexed);const baselineKeys = new Set(Object.keys(baseline.shots));@@ -819,9 +820,7 @@ function trustedPlan() {fail('trusted stable plan includes a private or canary theme');}if (unique.length === 0) {- fail(- 'trusted component scope has no existing baseline frames; seed coverage through the manual baseline workflow',- );+ fail(emptyVisualPlanMessage('The trusted component scope'));}if (unique.length > config.visualPlanSafetyLimit) {fail(diff --git a/.github/scripts/visual-gate/visual-acceptance.test.mjs b/.github/scripts/visual-gate/visual-acceptance.test.mjsindex c398c95952..c47a253516 100644--- a/.github/scripts/visual-gate/visual-acceptance.test.mjs+++ b/.github/scripts/visual-gate/visual-acceptance.test.mjs@@ -573,6 +573,90 @@ describe('visual acceptance', () => {).toEqual(['core-button--default__neutral-light']);});+ it('plans a published component whose only story is titled under another group', () => {+ const storybook = path.join(root, 'storybook-foreign-group');+ fs.mkdirSync(storybook);+ writeJSON(path.join(storybook, 'index.json'), {+ entries: {+ resizable: {+ type: 'story',+ id: 'lab-resizable--split',+ title: 'Lab/Resizable',+ name: 'Default',+ componentPath: '../../packages/core/src/Resizable/index.ts',+ tags: [],+ },+ },+ });+ const baselineFile = path.join(+ pages,+ 'visual-gate',+ 'baseline',+ 'manifest.json',+ );+ const baseline = JSON.parse(fs.readFileSync(baselineFile, 'utf8'));+ baseline.shots['lab-resizable--split__neutral-light'] = {+ ...baseline.shots[KEY],+ key: 'lab-resizable--split__neutral-light',+ storyId: 'lab-resizable--split',+ title: 'Lab/Resizable',+ name: 'Default',+ component: 'Resizable',+ };+ writeJSON(baselineFile, baseline);+ const scope = path.join(root, 'scope-foreign-group.json');+ writeJSON(scope, {+ hasStableVisual: true,+ broadStableVisual: false,+ stableComponents: ['Resizable'],+ stableThemes: [],+ });+ const output = path.join(root, 'foreign-group-plan.json');+ run('trusted-plan', {+ scope,+ baseline: path.join(pages, 'visual-gate', 'baseline'),+ 'storybook-dir': storybook,+ output,+ });+ expect(+ JSON.parse(fs.readFileSync(output, 'utf8')).map(shot => shot.key),+ ).toEqual(['lab-resizable--split__neutral-light']);+ });++ it('refuses an empty trusted plan in the words every lane refuses one', () => {+ const storybook = path.join(root, 'storybook-unseeded');+ fs.mkdirSync(storybook);+ writeJSON(path.join(storybook, 'index.json'), {+ entries: {+ card: {+ type: 'story',+ id: 'core-card--default',+ title: 'Core/Card',+ name: 'Default',+ componentPath: '../../packages/core/src/Card/index.ts',+ tags: [],+ },+ },+ });+ const scope = path.join(root, 'scope-unseeded.json');+ writeJSON(scope, {+ hasStableVisual: true,+ broadStableVisual: false,+ stableComponents: ['Card'],+ stableThemes: [],+ });+ expect(+ fail('trusted-plan', {+ scope,+ baseline: path.join(pages, 'visual-gate', 'baseline'),+ 'storybook-dir': storybook,+ output: path.join(root, 'unseeded-plan.json'),+ }),+ ).toMatch(+ /The trusted component scope planned no shots;.*manual baseline workflow\./,+ );+ });+it('fails closed when any touched component has no representative story', () => {const storybook = path.join(root, 'storybook-missing-component');fs.mkdirSync(storybook);diff --git a/.github/scripts/visual-gate/visual-gate.config.json b/.github/scripts/visual-gate/visual-gate.config.jsonindex e2d16ea9db..80934b8b21 100644--- a/.github/scripts/visual-gate/visual-gate.config.json+++ b/.github/scripts/visual-gate/visual-gate.config.json@@ -7,7 +7,7 @@"baselineThemes": ["neutral", "probe"],"$stableStoryPackages": "Only these workspace packages may own stable visual stories.","stableStoryPackages": ["Core"],- "$stableStoryGroups": "Only these Storybook title groups may own canonical baseline frames, even when another group imports Core components.",+ "$stableStoryGroups": "Ownership fallback for stories that declare no component: only these Storybook title groups may own canonical baseline frames, so a story from another group cannot earn one merely by importing Core. A story that DOES declare a component published by stableStoryPackages owns its frames wherever it is titled.","stableStoryGroups": ["Core"],"$prVisualShotLimit": "Review ceiling for focused component shots and broad shared-infrastructure plans. Theme-only matrices are not component-budgeted.","prVisualShotLimit": 240,diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 96f9d157bd..303435c2dd 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -153,8 +153,27 @@ jobs:printf '%s\n' "$FILES" \| node .github/scripts/visual-scope.mjs --github-output "$GITHUB_OUTPUT"- # Run tests (parallel with build)- test:+ # Tests run as two parallel lanes joined by `test` below.+ #+ # They used to be one `pnpm test` on a 2-core runner, which ran both Vitest+ # projects back to back and was terminated around 20 minutes with no summary+ # — no assertion output, so nothing said which suite was at fault. `main` was+ # already at ~19m15, so the budget, not any one test, was the defect.+ #+ # The projects are independent by construction (see vitest.config.ts: `ui` is+ # jsdom + StyleX, `node` is everything else), so running them as two jobs+ # costs no duplicate execution and each lane carries roughly half the work.+ # `node` is the heavier lane — locally 570s against the ui project's 244s —+ # so it takes the larger supported runner while `ui` stays on the 2-core arm+ # box.+ #+ # The repo-wide guardrail steps ride the LIGHTER lane, so the slow one is+ # nothing but tests.+ #+ # `test` remains a job, so the required check of that name still exists and+ # still reports for every PR. This mirrors the `build` join over+ # build-storybook + build-sandbox below.+ test-ui:needs: [check-scope]if: ${{ always() && !cancelled() }}runs-on: 2-core-ubuntu-arm@@ -208,9 +227,51 @@ jobs:if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm lab:readiness:check- - run: pnpm test+ - run: pnpm vitest run --project uiif: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'+ test-node:+ needs: [check-scope]+ if: ${{ always() && !cancelled() }}+ runs-on: 4-core-ubuntu+ permissions:+ contents: read+ steps:+ - name: Require successful scope classification+ if: needs.check-scope.result != 'success'+ run: |+ echo "Change scope could not be classified; refusing to skip required work."+ exit 1++ - name: Skip heavy work for lightweight docs+ if: needs.check-scope.outputs.docsite_only == 'true' || needs.check-scope.outputs.spec_only == 'true'+ run: echo "Lightweight documentation PR — skipping full test suite"++ - uses: actions/checkout@v7+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'++ - uses: ./.github/actions/setup+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'++ - run: pnpm vitest run --project node+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'++ # Historical required check name. Both lanes always run (they skip their own+ # steps for lightweight docs, exactly as the single job did), so this asserts+ # success rather than tolerating a skip.+ test:+ needs: [test-ui, test-node]+ if: ${{ always() && !cancelled() }}+ runs-on: ubuntu-slim+ permissions: {}+ steps:+ - name: Assert both test lanes succeeded+ run: |+ echo "test-ui: ${{ needs.test-ui.result }}"+ echo "test-node: ${{ needs.test-node.result }}"+ [ "${{ needs.test-ui.result }}" = "success" ] || exit 1+ [ "${{ needs.test-node.result }}" = "success" ] || exit 1+# Build storybook + typecheck + analyze components (parallel with test and# build-sandbox). Uploads the storybook preview and analysis artifacts for# downstream jobs.diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.ymlindex 78404f1d11..c7034b0c98 100644--- a/.github/workflows/deploy.yml+++ b/.github/workflows/deploy.yml@@ -67,7 +67,19 @@ jobs:- name: Check package.json exports are in syncrun: node scripts/sync-exports.js --check- test:+ # The push gate, as three parallel lanes joined by `test` below.+ #+ # This was one job running both Vitest projects, a full `pnpm build`, and+ # eight typecheck gates on a 2-core runner — strictly more than ci.yml's+ # `test`, which was already being terminated around 20 minutes with no+ # summary. Same defect, later surface: main's post-merge gate was over the+ # same budget.+ #+ # Nothing is dropped and nothing runs twice. The two Vitest projects are+ # independent by construction (vitest.config.ts), so they split cleanly; the+ # typecheck gates need the `pnpm build` they follow, so they stay together in+ # their own lane and take the build with them.+ test-ui:runs-on: 2-core-ubuntu-armpermissions:contents: read@@ -78,15 +90,39 @@ jobs:- uses: ./.github/actions/setup- - run: pnpm test+ - run: pnpm vitest run --project ui++ test-node:+ runs-on: 4-core-ubuntu+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@v7+ with:+ ref: main++ - uses: ./.github/actions/setup++ - run: pnpm vitest run --project node++ # Typecheck gates mirroring the PR `build` job in ci.yml. ci.yml only runs+ # on pull_request/merge_group, so a typecheck error can land on main (its+ # push only runs the suite) undetected — then break the `build` check on+ # every open PR, which typechecks the PR merged with main (see #3197).+ # Running them here closes that gap and blocks a broken deploy.+ typecheck:+ runs-on: 2-core-ubuntu-arm+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@v7+ with:+ ref: main++ - uses: ./.github/actions/setup- run: pnpm build- # Typecheck gates mirroring the PR `build` job in ci.yml. ci.yml only runs- # on pull_request/merge_group, so a typecheck error can land on main (its- # push only runs `pnpm test`) undetected — then break the `build` check on- # every open PR, which typechecks the PR merged with main (see #3197).- # Running them here closes that gap and blocks a broken deploy.- name: Verify package exportsrun: node scripts/verify-exports.mjs@@ -114,6 +150,24 @@ jobs:- name: Typecheck core (including tests)run: pnpm -F @astryxdesign/core typecheck+ # Historical job name, kept because `deploy` gates the publish on+ # `needs.test.result == 'success'`. Every lane must pass for that to hold, so+ # this asserts all three rather than merely depending on them.+ test:+ needs: [test-ui, test-node, typecheck]+ if: ${{ always() && !cancelled() }}+ runs-on: ubuntu-slim+ permissions: {}+ steps:+ - name: Assert every push gate succeeded+ run: |+ echo "test-ui: ${{ needs.test-ui.result }}"+ echo "test-node: ${{ needs.test-node.result }}"+ echo "typecheck: ${{ needs.typecheck.result }}"+ [ "${{ needs.test-ui.result }}" = "success" ] || exit 1+ [ "${{ needs.test-node.result }}" = "success" ] || exit 1+ [ "${{ needs.typecheck.result }}" = "success" ] || exit 1+# Build everything the site needs, in parallel with `test`. The results are# handed to `deploy` as artifacts, so a broken test run never publishes —# test still gates the push, it just no longer serializes the build.diff --git a/.github/workflows/spec-owner-gate.yml b/.github/workflows/spec-owner-gate.ymlindex 0eb0a5b5fe..9fc8215ee8 100644--- a/.github/workflows/spec-owner-gate.yml+++ b/.github/workflows/spec-owner-gate.yml@@ -32,6 +32,14 @@ on:description: Pull request number to reconcilerequired: truetype: string+ backfill:+ description: >-+ Publish the gate status only. Use this when backfilling heads that+ predate the required check, so a reconcile cannot also enable+ auto-merge on a pull request nobody asked to land.+ required: false+ default: false+ type: booleanpermissions: {}@@ -44,13 +52,15 @@ jobs:reconcile:# Fork review events have read-only tokens. Same-repo reviews reconcile# automatically; fork approvals use the trusted issue_comment command path.+ # The comment filter admits any owner-command shape, including one missing+ # the head SHA, so the reconciler answers it instead of ignoring it.if: >-(github.event_name != 'pull_request_review' ||github.event.pull_request.head.repo.full_name == github.repository) &&(github.event_name != 'issue_comment' ||(github.event.issue.pull_request != null &&- (startsWith(github.event.comment.body, '/approve-spec ') ||- startsWith(github.event.comment.body, '/revoke-spec '))))+ (startsWith(github.event.comment.body, '/approve-spec') ||+ startsWith(github.event.comment.body, '/revoke-spec'))))runs-on: ubuntu-slimpermissions:contents: readdiff --git a/apps/sandbox/package.json b/apps/sandbox/package.jsonindex 95c4f699fb..2b209c0b32 100644--- a/apps/sandbox/package.json+++ b/apps/sandbox/package.json@@ -3,8 +3,7 @@"version": "0.0.1","private": true,"scripts": {- "test": "vitest run",- "test:watch": "vitest",+ "test": "vitest run --root ../.. apps/sandbox --project node","build:deps": "pnpm -F @astryxdesign/theme-neutral build && pnpm -F @astryxdesign/theme-matcha build && pnpm -F @astryxdesign/theme-stone build && pnpm -F @astryxdesign/theme-gothic build && pnpm -F @astryxdesign/theme-chocolate build && pnpm -F @astryxdesign/theme-y2k build && pnpm -F @astryxdesign/theme-butter build","generate:motion-audit": "node \"src/app/(sandbox)/pages/motion-lab/generate-motion-audit.mjs\"","generate:changelog": "node scripts/generate-changelog.js",diff --git a/apps/sandbox/src/test-routing.test.ts b/apps/sandbox/src/test-routing.test.tsnew file mode 100644index 0000000000..96725c2427--- /dev/null+++ b/apps/sandbox/src/test-routing.test.ts@@ -0,0 +1,77 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file test-routing.test.ts+ * @position Guards how this app's tests are reached, which has failed twice.+ *+ * The palette-generator suite once belonged to no Vitest project at all: the+ * app carried its own `vitest.config.ts`, the root config's projects did not+ * include `apps/sandbox`, and `pnpm test` — the only thing CI runs — never+ * collected it. Eighteen tests passed nothing and failed nothing for as long+ * as that lasted.+ *+ * Routing it into the root `node` project fixed that and removed the app's+ * config. But removing the app's `test` script broke the other half of the+ * contract: `pnpm --filter @astryxdesign/sandbox test`, the command this+ * page's README gives contributors, exited 0 with no output. A command that+ * silently succeeds while running nothing is worse than one that fails.+ *+ * So both halves are asserted here: the suite is reachable by the documented+ * command, and it is collected once by the root config rather than by a+ * config of this app's own.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';++import {describe, expect, it} from 'vitest';++const appDir = path.dirname(path.dirname(fileURLToPath(import.meta.url)));++function packageJson(): {scripts?: Record<string, string>} {+ return JSON.parse(+ fs.readFileSync(path.join(appDir, 'package.json'), 'utf8'),+ ) as {scripts?: Record<string, string>};+}++describe('sandbox test routing', () => {+ it('keeps a test script, so the documented command runs something', () => {+ // Without this, `pnpm --filter @astryxdesign/sandbox test` exits 0 having+ // run nothing at all — no output, no failure, no tests.+ expect(packageJson().scripts?.test).toBeTruthy();+ });++ it('routes that script at this app, in the root node project', () => {+ // `--root ../..` alone is not enough: a script that reaches the root config+ // but names the wrong path, or omits the project, passes a "forwarding"+ // check while running none of this app's tests. All three parts are the+ // contract — reach the root config, scope it to this app, pick the project+ // whose include list actually collects these files.+ const test = packageJson().scripts?.test ?? '';++ expect(test).toContain('--root ../..');+ expect(test).toContain('apps/sandbox');+ expect(test).toContain('--project node');+ });++ it('has no app-level Vitest config to shadow the root projects', () => {+ const shadowing = fs+ .readdirSync(appDir)+ .filter(entry => /^vitest\.config\.[cm]?[jt]s$/.test(entry));++ expect(shadowing).toEqual([]);+ });++ it('documents a command that matches the script that exists', () => {+ const readme = fs.readFileSync(+ path.join(appDir, 'src/app/(sandbox)/pages/palette-generator/README.md'),+ 'utf8',+ );+ // The README wraps prose, so compare on collapsed whitespace rather than+ // on the line breaks a reflow would move.+ const prose = readme.replace(/\s+/g, ' ');++ expect(prose).toContain('pnpm --filter @astryxdesign/sandbox test');+ });+});diff --git a/apps/sandbox/vitest.config.ts b/apps/sandbox/vitest.config.tsdeleted file mode 100644index 619cd36a60..0000000000--- a/apps/sandbox/vitest.config.ts+++ /dev/null@@ -1,10 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--import {defineConfig} from 'vitest/config';--export default defineConfig({- test: {- environment: 'node',- include: ['src/**/*.test.{ts,tsx}'],- },-});diff --git a/internal/eslint-plugin-astryx/no-physical-properties.js b/internal/eslint-plugin-astryx/no-physical-properties.jsindex a6c4bcd04c..8169ed6a4c 100644--- a/internal/eslint-plugin-astryx/no-physical-properties.js+++ b/internal/eslint-plugin-astryx/no-physical-properties.js@@ -38,6 +38,22 @@* key are present, renaming would produce a duplicate property (and the two* silently collide — last one wins in LTR), so instead of autofixing we* surface a distinct `physicalKeyConflict` message for a human to resolve.+ *+ * READING TRANSFORMS — fail closed. Both centering diagnostics depend on what a+ * sibling `transform` does to the inline axis, and BOTH act on the answer: the+ * `left` rename rewrites code, and the logical-anchor report clears code as+ * correct. An analysis that guesses in either direction is therefore a defect,+ * not a rough edge, so `horizontalTranslate` splits the transform into its+ * function calls, reads them IN ORDER (a list composes: a translation written+ * after a `rotate`/`skew` is measured on axes this rule can no longer+ * identify), and answers "none" only when it read every one of them.+ * `matrix()`, `scaleX()`, a template interpolation, two horizontal+ * translations, a translation composed after a rotation, and syntax it cannot+ * parse all answer "unknown", which withholds the fix and reports;+ * `compareTranslations` likewise recognises an+ * RTL reversal only in a plain negated length with a matching unit, so+ * `calc()` and `var()` no longer pass as compensation, and `-50%` against+ * `50px` is reported as the mismatch it is.*//**@@ -86,9 +102,9 @@ const PHYSICAL_KEY_MAP = {* Maps `key → { physicalValue → logicalValue }`.*/const PHYSICAL_VALUE_MAP = {- textAlign: { left: 'start', right: 'end' },- float: { left: 'inline-start', right: 'inline-end' },- clear: { left: 'inline-start', right: 'inline-end' },+ textAlign: {left: 'start', right: 'end'},+ float: {left: 'inline-start', right: 'inline-end'},+ clear: {left: 'inline-start', right: 'inline-end'},};export function isInsideStylexCreate(node) {@@ -107,6 +123,13 @@ export function isInsideStylexCreate(node) {return false;}+/**+ * Stands in for a template-literal interpolation. It is a character CSS can+ * never contain, so any analysis that meets it knows it is looking at a value+ * only the runtime can resolve, instead of silently reading `${x}` as empty.+ */+const INTERPOLATION = '\u0000';+function getStaticValue(node) {if (!node) return null;if (node.type === 'Literal' && typeof node.value === 'string') {@@ -118,29 +141,47 @@ function getStaticValue(node) {function getStaticText(node) {const value = getStaticValue(node);if (value !== null) return value;+ if (node?.type === 'Literal') {+ // `null` is StyleX's own "no value in this branch", and a number is a+ // length this rule can read. Both are absences of a physical translation,+ // not values it failed to read.+ if (node.value === null) return '';+ if (typeof node.value === 'number') return String(node.value);+ }+ if (node?.type === 'Identifier' && node.name === 'undefined') return '';if (node?.type === 'TemplateLiteral') {- return node.quasis.map((quasi) => quasi.value.raw).join(' ');+ return node.quasis.map(quasi => quasi.value.raw).join(INTERPOLATION);}return null;}+/** Text this rule can read end to end — no interpolation, no unknown node. */+function isReadable(text) {+ return text !== null && !text.includes(INTERPOLATION);+}+function propertyName(property) {return property?.key?.name ?? property?.key?.value ?? null;}/**- * Flatten a StyleX conditional value into its static leaves. `default` is kept- * in the path here and normalized only when conditions are compared.+ * Flatten a StyleX conditional value into its leaves. `default` is kept in the+ * path here and normalized only when conditions are compared.+ *+ * A leaf whose value is not a static string carries `text: null` rather than+ * being dropped: a value only the runtime knows (an identifier, a call, a+ * spread) is a value this rule cannot clear, and dropping it would let it pass+ * as an absence.*/function conditionalLeaves(node, path = []) {- const text = getStaticText(node);- if (text !== null) return [{path, text}];- if (node?.type !== 'ObjectExpression') return [];+ if (node?.type !== 'ObjectExpression') {+ return [{path, text: getStaticText(node)}];+ }- return node.properties.flatMap((property) => {- if (property.type !== 'Property') return [];+ return node.properties.flatMap(property => {+ if (property.type !== 'Property') return [{path, text: null}];const name = propertyName(property);- if (typeof name !== 'string') return [];+ if (typeof name !== 'string') return [{path, text: null}];return conditionalLeaves(property.value, [...path, name]);});}@@ -154,7 +195,7 @@ function isRtlCondition(condition) {function normalizedConditions(path) {return path.filter(- (condition) => condition !== 'default' && !isRtlCondition(condition),+ condition => condition !== 'default' && !isRtlCondition(condition),);}@@ -167,20 +208,193 @@ function sameConditions(a, b) {);}+/**+ * Where the horizontal (inline-axis) argument sits in each transform function+ * that can move an element along that axis.+ */+const HORIZONTAL_TRANSLATE_ARGUMENT = new Map([+ ['translate', 0],+ ['translatex', 0],+ ['translate3d', 0],+]);++/**+ * Transform functions that leave the inline axis alone AND leave the coordinate+ * system's axes where they were, so a later translation still means what it+ * says.+ *+ * `scale`, `scaleX`, `scale3d`, `matrix` and `matrix3d` are deliberately absent:+ * each can mirror or shift the horizontal axis (`scaleX(-1)` reverses it,+ * `matrix(a, b, c, d, tx, ty)` carries its own translation), so they are read as+ * unanalyzable rather than as harmless.+ */+const AXIS_PRESERVING = new Set([+ 'scaley',+ 'scalez',+ 'translatey',+ 'translatez',+]);++/**+ * Transform functions that ROTATE OR SHEAR the coordinate system. They add no+ * horizontal translation themselves, but every translation written after one is+ * measured along axes this rule can no longer identify.+ *+ * This is why order matters: `translateY(-50%) rotate(45deg)` translates along+ * the parent's vertical axis and then spins the element in place, while+ * `rotate(90deg) translateY(-50%)` rotates the axes FIRST, so the `translateY`+ * that follows moves the element HORIZONTALLY by half its height.+ */+const AXIS_CHANGING = new Set([+ 'perspective',+ 'rotate',+ 'rotate3d',+ 'rotatex',+ 'rotatey',+ 'rotatez',+ 'skew',+ 'skewx',+ 'skewy',+]);++/**+ * Split a transform value into its function calls, or `null` when the text is+ * not a transform list this rule can read end to end.+ *+ * Arguments are split on TOP-LEVEL commas only, so `translate(calc(-50% + 4px),+ * 0)` keeps its first argument whole instead of being cut at the comma inside+ * `calc()` — the bug that made the old scan read `calc(-50%` as a value.+ */+function parseTransformFunctions(text) {+ const functions = [];+ let index = 0;++ while (index < text.length) {+ if (/[\s,]/.test(text[index])) {+ index += 1;+ continue;+ }++ const name = /^[A-Za-z][\w-]*/.exec(text.slice(index));+ if (!name) return null;+ index += name[0].length;+ while (index < text.length && /\s/.test(text[index])) index += 1;++ if (text[index] !== '(') {+ // `none` is the only bare keyword a transform list may hold.+ if (name[0].toLowerCase() === 'none') continue;+ return null;+ }++ const args = [];+ let argument = '';+ let depth = 1;+ index += 1;+ while (index < text.length && depth > 0) {+ const character = text[index];+ if (character === '(') depth += 1;+ else if (character === ')') depth -= 1;+ if (depth === 0) break;+ if (character === ',' && depth === 1) {+ args.push(argument);+ argument = '';+ } else {+ argument += character;+ }+ index += 1;+ }+ if (depth !== 0) return null;+ args.push(argument);+ index += 1;++ functions.push({name: name[0].toLowerCase(), args});+ }++ return functions;+}++/** A length that moves nothing: `0`, `-0`, `0px`, `0%`. */+function isZeroLength(text) {+ return /^[-+]?0(?:\.0+)?[a-z%]*$/i.test(text.trim());+}++/**+ * The horizontal translation a transform value applies:+ *+ * - `null` — provably none, so a physical anchor beside it is untouched by any+ * inline-axis shift;+ * - `{opaque: true}` — the value may translate horizontally and this rule+ * cannot tell (a `matrix()`, a `scaleX()`, an interpolation in the horizontal+ * argument, two horizontal translations that would have to be summed, a+ * translation composed after the axes were rotated or sheared, or syntax it+ * cannot read);+ * - `{value}` — exactly one horizontal translation, as written.+ *+ * Functions are read IN ORDER, because a transform list composes: each function+ * acts in the coordinate system the ones before it established. Once a rotate or+ * a skew has turned the axes, this rule can no longer say which direction a+ * later `translateY` moves — so everything after one is opaque, and only a+ * translation written before any of them is read at face value.+ *+ * Every unreadable shape lands in `opaque` rather than in `null`: an analysis+ * that cannot see a translation must not report that there is none, because+ * both callers treat "none" as permission to act.+ */function horizontalTranslate(text) {- const match = text.match(/\btranslate(?:X)?\s*\(\s*([^,\s)]+)/);- if (!match) return null;- const value = match[1];- return /^[-+]?0(?:[a-z%]*)?$/.test(value) ? null : value;+ if (text === null) return {opaque: true};++ const functions = parseTransformFunctions(text);+ if (functions === null) return {opaque: true};++ const values = [];+ let axesIntact = true;+ for (const {name, args} of functions) {+ if (AXIS_CHANGING.has(name)) {+ axesIntact = false;+ continue;+ }++ const argument = HORIZONTAL_TRANSLATE_ARGUMENT.get(name);+ if (argument === undefined) {+ // A translation along any axis becomes a horizontal one once the axes+ // have turned, so an "axis-preserving" function only preserves anything+ // while they are still where they started.+ if (AXIS_PRESERVING.has(name) && axesIntact) continue;+ return {opaque: true};+ }+ if (!axesIntact) return {opaque: true};++ const value = args[argument];+ if (value === undefined || !isReadable(value)) return {opaque: true};+ if (isZeroLength(value)) continue;+ values.push(value.trim());+ }++ if (values.length === 0) return null;+ // Two horizontal translations would have to be summed to be compared, and+ // `translateX(-50%) translateX(4px)` cannot be summed without layout.+ if (values.length > 1) return {opaque: true};+ return {value: values[0]};}-function oppositeTranslations(a, b) {- if (a === b) return false;- const simple = /^([-+]?\d+(?:\.\d+)?)([a-z%]*)$/;- const left = a.match(simple);- const right = b.match(simple);- if (!left || !right || left[2] !== right[2]) return true;- return Number(left[1]) === -Number(right[1]);+/**+ * How an RTL translation relates to the default one it is meant to reverse:+ * `'opposite'`, `'not-opposite'`, or `'unknown'`.+ *+ * Only a plain signed number can be compared. `calc()` and `var()` resolve at+ * layout time and answer `'unknown'`, which is neither compensation nor a+ * proven break; a unit mismatch (`-50%` against `50px`) answers+ * `'not-opposite'`, because a percentage of the element's own width and a fixed+ * length do not cancel. The old check answered "compensated" to all three, so+ * an RTL branch that reversed nothing silenced the diagnostic.+ */+function compareTranslations(a, b) {+ const simple = /^([-+]?(?:\d+(?:\.\d+)?|\.\d+))([a-z%]*)$/i;+ const left = simple.exec(a);+ const right = simple.exec(b);+ if (!left || !right) return 'unknown';+ if (left[2].toLowerCase() !== right[2].toLowerCase()) return 'not-opposite';+ return Number(left[1]) === -Number(right[1]) ? 'opposite' : 'not-opposite';}function siblingProperty(node, keyName) {@@ -188,7 +402,7 @@ function siblingProperty(node, keyName) {if (object?.type !== 'ObjectExpression') return null;return (object.properties.find(- (property) =>+ property =>property.type === 'Property' && propertyName(property) === keyName,) ?? null);@@ -203,7 +417,7 @@ function objectHasKey(objectExpression, keyName) {if (!objectExpression || objectExpression.type !== 'ObjectExpression') {return false;}- return objectExpression.properties.some((prop) => {+ return objectExpression.properties.some(prop => {if (prop.type !== 'Property') return false;const name = prop.key?.name ?? prop.key?.value;return name === keyName;@@ -211,69 +425,138 @@ function objectHasKey(objectExpression, keyName) {}/**- * Returns the fixed inline-centering anchor value when a physical `left` and- * horizontal translate are active under the same StyleX conditions.+ * The sibling `transform`'s leaves that carry (or may carry) a horizontal+ * translation, or `null` when there is no sibling `transform` at all.*/-function inlineCenteringValue(node) {+function horizontalTransformLeaves(node) {const transform = siblingProperty(node, 'transform');if (!transform) return null;- const transforms = conditionalLeaves(transform.value).filter((leaf) =>- horizontalTranslate(leaf.text),- );+ return conditionalLeaves(transform.value)+ .map(leaf => ({...leaf, horizontal: horizontalTranslate(leaf.text)}))+ .filter(leaf => leaf.horizontal !== null);+}+/**+ * An anchor this rule can see IS the fixed 50% centering anchor.+ *+ * The relationship diagnostic judges only these. A variable anchor (`size *+ * ratio`, a token, an interpolation) is a position, not a centering idiom, and+ * this rule has never had an opinion about one.+ */+function isFixedCenteringAnchor(leaf) {+ return isReadable(leaf.text) && (leaf.text === '50%' || leaf.text === '-50%');+}++/**+ * An anchor that MIGHT be the fixed centering anchor — the same values, plus+ * any this rule could not read.+ *+ * Only the autofix uses this wider net: withholding a rename costs a developer+ * one manual edit, while applying it to an unread centering pair breaks RTL+ * silently.+ */+function mayBeCenteringAnchor(leaf) {+ return !isReadable(leaf.text) || isFixedCenteringAnchor(leaf);+}++/**+ * How a physical `left` relates to its sibling `transform`:+ *+ * - `null` — not the centering idiom, so the logical rename is safe;+ * - `{certain: true, value}` — a 50% anchor and a horizontal translate are+ * active under the same conditions: the sanctioned centering idiom, which+ * must NOT be renamed;+ * - `{certain: false}` — one side cannot be read, so whether this is centering+ * is unknown and the rename must not be applied for it either.+ */+function inlineCenteringStatus(node) {+ const transforms = horizontalTransformLeaves(node);+ if (transforms === null) return null;++ let unknown = null;for (const anchor of conditionalLeaves(node.value)) {- if (anchor.text !== '50%' && anchor.text !== '-50%') continue;- if (transforms.some((leaf) => sameConditions(anchor.path, leaf.path))) {- return anchor.text;+ if (!mayBeCenteringAnchor(anchor)) continue;+ const matching = transforms.filter(leaf =>+ sameConditions(anchor.path, leaf.path),+ );+ if (matching.length === 0) continue;+ if (+ isReadable(anchor.text) &&+ matching.some(leaf => leaf.horizontal.value !== undefined)+ ) {+ return {certain: true, value: anchor.text};}+ unknown ??= {certain: false};}- return null;+ return unknown;}/**- * Returns the broken logical anchor value when a logical 50% inset and physical- * horizontal translate share a conditional branch without an opposite RTL- * transform in that branch.+ * Every fixed 50% logical inline anchor paired with a horizontal translate, and+ * what this rule could establish about each one.+ *+ * `compensated` is only ever true when an RTL branch provably reverses every+ * default translation. `certain` says whether the verdict is proven either way,+ * so a pairing whose reversal can be neither confirmed nor refuted — a `calc()`+ * against a `calc()`, a `matrix()`, an interpolated length — is reported as+ * unverified rather than as safe or as definitely broken.+ *+ * Both answers turn on the TRANSFORMS alone: once an RTL branch reverses the+ * default translation, the pair mirrors correctly whatever the anchor reads.*/export function logicalCenteringStatuses(node) {- const transform = siblingProperty(node, 'transform');- if (!transform) return [];- const transforms = conditionalLeaves(transform.value)- .map((leaf) => ({...leaf, horizontal: horizontalTranslate(leaf.text)}))- .filter((leaf) => leaf.horizontal !== null);+ const transforms = horizontalTransformLeaves(node);+ if (transforms === null) return [];const statuses = [];for (const anchor of conditionalLeaves(node.value)) {- if (anchor.text !== '50%' && anchor.text !== '-50%') continue;+ if (!isFixedCenteringAnchor(anchor)) continue;const defaults = transforms.filter(- (leaf) =>+ leaf =>!leaf.path.some(isRtlCondition) &&sameConditions(anchor.path, leaf.path),);if (defaults.length === 0) continue;const rtlTransforms = transforms.filter(- (leaf) =>+ leaf =>leaf.path.some(isRtlCondition) &&sameConditions(anchor.path, leaf.path),);- const compensated = defaults.every((defaultTransform) =>- rtlTransforms.some((rtlTransform) =>- oppositeTranslations(- defaultTransform.horizontal,- rtlTransform.horizontal,- ),- ),+ const readable = [...defaults, ...rtlTransforms].every(+ leaf => leaf.horizontal.value !== undefined,);- statuses.push({compensated, value: anchor.text});+ const comparisons = defaultTransform =>+ rtlTransforms.map(rtlTransform =>+ compareTranslations(+ defaultTransform.horizontal.value,+ rtlTransform.horizontal.value,+ ),+ );+ const compensated =+ readable &&+ defaults.every(defaultTransform =>+ comparisons(defaultTransform).includes('opposite'),+ );+ // A mismatch is only stated as fact when every candidate reversal was+ // read and refuted; an RTL branch that cannot be compared leaves the+ // verdict unproven, and an absent RTL branch refutes nothing vacuously.+ const certain =+ compensated ||+ (readable &&+ defaults.every(defaultTransform =>+ comparisons(defaultTransform).every(+ comparison => comparison === 'not-opposite',+ ),+ ));+ statuses.push({compensated, certain, value: anchor.text});}return statuses;}-function unmirroredLogicalCenteringValue(node) {+function uncompensatedLogicalCentering(node) {return (- logicalCenteringStatuses(node).find((status) => !status.compensated)- ?.value ?? null+ logicalCenteringStatuses(node).find(status => !status.compensated) ?? null);}@@ -294,8 +577,8 @@ const rule = {physicalKey:'Use `{{logical}}` instead of `{{physical}}` for RTL support.',physicalValue:- 'Use `{{prop}}: \'{{logical}}\'` instead of ' +- '`{{prop}}: \'{{physical}}\'` for RTL support.',+ "Use `{{prop}}: '{{logical}}'` instead of " ++ "`{{prop}}: '{{physical}}'` for RTL support.",physicalKeyConflict:'`{{physical}}` conflicts with `{{logical}}` already set on this ' +'style object — remove `{{physical}}`.',@@ -303,10 +586,19 @@ const rule = {'`left: {{value}}` with a `translate` centers this element — do NOT ' +'rename it to `insetInlineStart` (that breaks centering under RTL). ' +'Use the shared `rtlStyles.centerInline(blockOffset)` helper instead.',+ inlineCenteringUnknown:+ '`left` is paired with a `transform` this rule cannot analyse, so ' ++ 'renaming it to `insetInlineStart` could silently break RTL centering. ' ++ 'Resolve it by hand, or use `rtlStyles.centerInline(blockOffset)`.',logicalCenteringTransform:'`{{property}}: {{value}}` flips its anchor under RTL, but its paired ' +'horizontal `translate` does not. Use `rtlStyles.centerInline(blockOffset)` ' +'for fixed centering, or add an opposite RTL transform for a variable position.',+ logicalCenteringUnverified:+ '`{{property}}` flips its anchor under RTL, and this rule cannot verify ' ++ 'that its paired horizontal `translate` is reversed to match. Use ' ++ '`rtlStyles.centerInline(blockOffset)` for fixed centering, or write the ' ++ 'RTL transform as a plain negated length so the pair can be checked.',},schema: [{@@ -333,14 +625,19 @@ const rule = {if (logicalKey) {// Special case: `left: '50%'` + a centering `translate` must NOT be// logicalized (it would break RTL centering). Point at the shared- // helper instead, and do NOT autofix.- const centeringValue =- propName === 'left' ? inlineCenteringValue(node) : null;- if (centeringValue !== null) {+ // helper instead, and do NOT autofix. When either side of that+ // pairing cannot be read, the rename is withheld too: an unreadable+ // transform may be centering this element, and a fix applied on a+ // guess corrupts the layout silently.+ const centering =+ propName === 'left' ? inlineCenteringStatus(node) : null;+ if (centering !== null) {context.report({node: node.key,- messageId: 'inlineCentering',- data: {value: centeringValue},+ messageId: centering.certain+ ? 'inlineCentering'+ : 'inlineCenteringUnknown',+ data: {value: centering.value},});return;}@@ -388,15 +685,16 @@ const rule = {// media/state branches and accept an explicit opposite RTL transform.if (!allowLogicalCentering &&- (propName === 'insetInlineStart' ||- propName === 'insetInlineEnd')+ (propName === 'insetInlineStart' || propName === 'insetInlineEnd')) {- const centeringValue = unmirroredLogicalCenteringValue(node);- if (centeringValue !== null) {+ const centering = uncompensatedLogicalCentering(node);+ if (centering !== null) {context.report({node: node.key,- messageId: 'logicalCenteringTransform',- data: {property: propName, value: centeringValue},+ messageId: centering.certain+ ? 'logicalCenteringTransform'+ : 'logicalCenteringUnverified',+ data: {property: propName, value: centering.value},});return;}diff --git a/internal/eslint-plugin-astryx/no-physical-properties.test.mjs b/internal/eslint-plugin-astryx/no-physical-properties.test.mjsindex 5d6b253441..b96856268d 100644--- a/internal/eslint-plugin-astryx/no-physical-properties.test.mjs+++ b/internal/eslint-plugin-astryx/no-physical-properties.test.mjs@@ -55,7 +55,11 @@ ruleTester.run('no-physical-properties', rule, {`),},// A block-only translation does not create the logical-anchor mismatch.- {code: inStylex(`insetInlineStart: '50%', transform: 'translate(0, -50%)'`)},+ {+ code: inStylex(+ `insetInlineStart: '50%', transform: 'translate(0, -50%)'`,+ ),+ },{// A narrow config exception may defer this relationship diagnostic while// retaining every key/value check in this rule.@@ -84,6 +88,68 @@ ruleTester.run('no-physical-properties', rule, {{code: `const x = { textAlign: 'left', float: 'right' };`},// SCOPING: `left`/`right` as ordinary variable names — fine{code: `const left = 5; const right = 10; const sum = left + right;`},++ // --- TRANSFORM READING: a transform proven to leave the inline axis alone+ // does not make a logical anchor suspect. ---+ {code: inStylex(`insetInlineStart: '50%', transform: 'none'`)},+ {code: inStylex(`insetInlineStart: '50%', transform: 'rotate(45deg)'`)},+ {+ code: inStylex(+ `insetInlineStart: '50%', transform: 'translateY(-50%) skewX(3deg)'`,+ ),+ },+ // Zero horizontal translation moves nothing, in any spelling.+ {code: inStylex(`insetInlineStart: '50%', transform: 'translateX(0px)'`)},+ // COMPOSITION: a rotate AFTER a translation spins the element in place,+ // leaving the translation measured on the axes it was written for.+ {+ code: inStylex(+ `insetInlineStart: '50%', transform: 'translateY(-50%) rotate(45deg)'`,+ ),+ },+ {+ code: inStylex(+ `insetInlineStart: '50%', transform: 'translate3d(-0, -50%, 0)'`,+ ),+ },+ // An RTL-only translation has no default arm to contradict.+ {+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {default: null, ':is([dir="rtl"] *)': 'translateX(50%)'}+ `),+ },+ // translate3d is read as the horizontal translation it is, so its RTL+ // reversal counts as compensation exactly like translate()'s.+ {+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translate3d(-50%, -50%, 0)',+ ':is([dir="rtl"] *)': 'translate3d(50%, -50%, 0)',+ }+ `),+ },+ // A variable anchor is a position, not the fixed centering idiom. This is+ // Avatar's status-dot shape: the offset is computed from `size`, and the+ // RTL arm already mirrors the outward push.+ {+ code: inStylex(`+ insetInlineEnd: size * 0.07,+ transform: {+ default: 'translate(50%, 50%)',+ ':is([dir="rtl"] *)': 'translate(-50%, 50%)',+ }+ `),+ },+ // The config exception still defers every relationship diagnostic,+ // including the unverifiable ones.+ {+ code: inStylex(+ `insetInlineStart: '50%', transform: 'matrix(1, 0, 0, 1, -50, 0)'`,+ ),+ options: [{allowLogicalCentering: true}],+ },],invalid: [// --- KEY-BASED: margin (autofix renames the key) ---@@ -91,14 +157,20 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`marginLeft: 8`),output: inStylex(`marginInlineStart: 8`),errors: [- {messageId: 'physicalKey', data: {physical: 'marginLeft', logical: 'marginInlineStart'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'marginLeft', logical: 'marginInlineStart'},+ },],},{code: inStylex(`marginRight: 8`),output: inStylex(`marginInlineEnd: 8`),errors: [- {messageId: 'physicalKey', data: {physical: 'marginRight', logical: 'marginInlineEnd'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'marginRight', logical: 'marginInlineEnd'},+ },],},// --- KEY-BASED: padding ---@@ -106,14 +178,20 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`paddingLeft: 8`),output: inStylex(`paddingInlineStart: 8`),errors: [- {messageId: 'physicalKey', data: {physical: 'paddingLeft', logical: 'paddingInlineStart'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'paddingLeft', logical: 'paddingInlineStart'},+ },],},{code: inStylex(`paddingRight: 8`),output: inStylex(`paddingInlineEnd: 8`),errors: [- {messageId: 'physicalKey', data: {physical: 'paddingRight', logical: 'paddingInlineEnd'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'paddingRight', logical: 'paddingInlineEnd'},+ },],},// --- KEY-BASED: border side shorthands ---@@ -121,14 +199,20 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`borderLeft: '1px solid red'`),output: inStylex(`borderInlineStart: '1px solid red'`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderLeft', logical: 'borderInlineStart'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'borderLeft', logical: 'borderInlineStart'},+ },],},{code: inStylex(`borderRight: '1px solid red'`),output: inStylex(`borderInlineEnd: '1px solid red'`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderRight', logical: 'borderInlineEnd'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'borderRight', logical: 'borderInlineEnd'},+ },],},// --- KEY-BASED: border side longhands (width/style/color) ---@@ -136,42 +220,69 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`borderLeftWidth: 1`),output: inStylex(`borderInlineStartWidth: 1`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderLeftWidth', logical: 'borderInlineStartWidth'}},+ {+ messageId: 'physicalKey',+ data: {+ physical: 'borderLeftWidth',+ logical: 'borderInlineStartWidth',+ },+ },],},{code: inStylex(`borderLeftStyle: 'solid'`),output: inStylex(`borderInlineStartStyle: 'solid'`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderLeftStyle', logical: 'borderInlineStartStyle'}},+ {+ messageId: 'physicalKey',+ data: {+ physical: 'borderLeftStyle',+ logical: 'borderInlineStartStyle',+ },+ },],},{code: inStylex(`borderLeftColor: 'red'`),output: inStylex(`borderInlineStartColor: 'red'`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderLeftColor', logical: 'borderInlineStartColor'}},+ {+ messageId: 'physicalKey',+ data: {+ physical: 'borderLeftColor',+ logical: 'borderInlineStartColor',+ },+ },],},{code: inStylex(`borderRightWidth: 1`),output: inStylex(`borderInlineEndWidth: 1`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderRightWidth', logical: 'borderInlineEndWidth'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'borderRightWidth', logical: 'borderInlineEndWidth'},+ },],},{code: inStylex(`borderRightStyle: 'solid'`),output: inStylex(`borderInlineEndStyle: 'solid'`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderRightStyle', logical: 'borderInlineEndStyle'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'borderRightStyle', logical: 'borderInlineEndStyle'},+ },],},{code: inStylex(`borderRightColor: 'red'`),output: inStylex(`borderInlineEndColor: 'red'`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderRightColor', logical: 'borderInlineEndColor'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'borderRightColor', logical: 'borderInlineEndColor'},+ },],},// --- KEY-BASED: inset left/right ---@@ -179,7 +290,10 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`left: 0`),output: inStylex(`insetInlineStart: 0`),errors: [- {messageId: 'physicalKey', data: {physical: 'left', logical: 'insetInlineStart'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'left', logical: 'insetInlineStart'},+ },],},{@@ -188,14 +302,20 @@ ruleTester.run('no-physical-properties', rule, {options: [{allowLogicalCentering: true}],output: inStylex(`insetInlineStart: 0`),errors: [- {messageId: 'physicalKey', data: {physical: 'left', logical: 'insetInlineStart'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'left', logical: 'insetInlineStart'},+ },],},{code: inStylex(`right: 0`),output: inStylex(`insetInlineEnd: 0`),errors: [- {messageId: 'physicalKey', data: {physical: 'right', logical: 'insetInlineEnd'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'right', logical: 'insetInlineEnd'},+ },],},// --- KEY-BASED: string-literal key preserves quoting on rename ---@@ -203,7 +323,10 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`'left': 0`),output: inStylex(`'insetInlineStart': 0`),errors: [- {messageId: 'physicalKey', data: {physical: 'left', logical: 'insetInlineStart'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'left', logical: 'insetInlineStart'},+ },],},// --- INLINE-CENTERING EXCEPTION: left:'50%' + translate must NOT be@@ -221,7 +344,7 @@ ruleTester.run('no-physical-properties', rule, {},{// template-literal transform (the dynamic-style form) is also detected- code: inStylex('left: \'50%\', transform: `translate(-50%, ${o})`'),+ code: inStylex("left: '50%', transform: `translate(-50%, ${o})`"),output: null,errors: [{messageId: 'inlineCentering', data: {value: '50%'}}],},@@ -231,7 +354,10 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`left: '50%'`),output: inStylex(`insetInlineStart: '50%'`),errors: [- {messageId: 'physicalKey', data: {physical: 'left', logical: 'insetInlineStart'}},+ {+ messageId: 'physicalKey',+ data: {physical: 'left', logical: 'insetInlineStart'},+ },],},{@@ -247,7 +373,9 @@ ruleTester.run('no-physical-properties', rule, {// --- LOGICAL-CENTERING MISMATCH: a logical 50% anchor flips in RTL but a// physical horizontal translate does not. These are non-fixing errors. ---{- code: inStylex(`insetInlineStart: '50%', transform: 'translate(-50%, -50%)'`),+ code: inStylex(+ `insetInlineStart: '50%', transform: 'translate(-50%, -50%)'`,+ ),output: null,errors: [{@@ -320,28 +448,52 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`borderTopLeftRadius: 4`),output: inStylex(`borderStartStartRadius: 4`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderTopLeftRadius', logical: 'borderStartStartRadius'}},+ {+ messageId: 'physicalKey',+ data: {+ physical: 'borderTopLeftRadius',+ logical: 'borderStartStartRadius',+ },+ },],},{code: inStylex(`borderTopRightRadius: 4`),output: inStylex(`borderStartEndRadius: 4`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderTopRightRadius', logical: 'borderStartEndRadius'}},+ {+ messageId: 'physicalKey',+ data: {+ physical: 'borderTopRightRadius',+ logical: 'borderStartEndRadius',+ },+ },],},{code: inStylex(`borderBottomLeftRadius: 4`),output: inStylex(`borderEndStartRadius: 4`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderBottomLeftRadius', logical: 'borderEndStartRadius'}},+ {+ messageId: 'physicalKey',+ data: {+ physical: 'borderBottomLeftRadius',+ logical: 'borderEndStartRadius',+ },+ },],},{code: inStylex(`borderBottomRightRadius: 4`),output: inStylex(`borderEndEndRadius: 4`),errors: [- {messageId: 'physicalKey', data: {physical: 'borderBottomRightRadius', logical: 'borderEndEndRadius'}},+ {+ messageId: 'physicalKey',+ data: {+ physical: 'borderBottomRightRadius',+ logical: 'borderEndEndRadius',+ },+ },],},// --- KEY-BASED CONFLICT: both physical + logical present → no autofix ---@@ -350,7 +502,10 @@ ruleTester.run('no-physical-properties', rule, {// Fix is skipped: `output: null` asserts the code is left unchanged.output: null,errors: [- {messageId: 'physicalKeyConflict', data: {physical: 'marginLeft', logical: 'marginInlineStart'}},+ {+ messageId: 'physicalKeyConflict',+ data: {physical: 'marginLeft', logical: 'marginInlineStart'},+ },],},// Conflict also detected when the logical key is a string literal.@@ -358,7 +513,10 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`left: 0, 'insetInlineStart': 10`),output: null,errors: [- {messageId: 'physicalKeyConflict', data: {physical: 'left', logical: 'insetInlineStart'}},+ {+ messageId: 'physicalKeyConflict',+ data: {physical: 'left', logical: 'insetInlineStart'},+ },],},// --- VALUE-BASED: textAlign (autofix replaces the value only) ---@@ -366,14 +524,20 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`textAlign: 'left'`),output: inStylex(`textAlign: 'start'`),errors: [- {messageId: 'physicalValue', data: {prop: 'textAlign', physical: 'left', logical: 'start'}},+ {+ messageId: 'physicalValue',+ data: {prop: 'textAlign', physical: 'left', logical: 'start'},+ },],},{code: inStylex(`textAlign: 'right'`),output: inStylex(`textAlign: 'end'`),errors: [- {messageId: 'physicalValue', data: {prop: 'textAlign', physical: 'right', logical: 'end'}},+ {+ messageId: 'physicalValue',+ data: {prop: 'textAlign', physical: 'right', logical: 'end'},+ },],},// --- VALUE-BASED: float ---@@ -381,14 +545,20 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`float: 'left'`),output: inStylex(`float: 'inline-start'`),errors: [- {messageId: 'physicalValue', data: {prop: 'float', physical: 'left', logical: 'inline-start'}},+ {+ messageId: 'physicalValue',+ data: {prop: 'float', physical: 'left', logical: 'inline-start'},+ },],},{code: inStylex(`float: 'right'`),output: inStylex(`float: 'inline-end'`),errors: [- {messageId: 'physicalValue', data: {prop: 'float', physical: 'right', logical: 'inline-end'}},+ {+ messageId: 'physicalValue',+ data: {prop: 'float', physical: 'right', logical: 'inline-end'},+ },],},// --- VALUE-BASED: clear ---@@ -396,14 +566,312 @@ ruleTester.run('no-physical-properties', rule, {code: inStylex(`clear: 'left'`),output: inStylex(`clear: 'inline-start'`),errors: [- {messageId: 'physicalValue', data: {prop: 'clear', physical: 'left', logical: 'inline-start'}},+ {+ messageId: 'physicalValue',+ data: {prop: 'clear', physical: 'left', logical: 'inline-start'},+ },],},{code: inStylex(`clear: 'right'`),output: inStylex(`clear: 'inline-end'`),errors: [- {messageId: 'physicalValue', data: {prop: 'clear', physical: 'right', logical: 'inline-end'}},+ {+ messageId: 'physicalValue',+ data: {prop: 'clear', physical: 'right', logical: 'inline-end'},+ },+ ],+ },++ // --- AUTOFIX WITHHELD: a `left` anchor whose transform this rule reads as+ // horizontal, or cannot read at all. Renaming any of these to+ // `insetInlineStart` silently breaks RTL centering, so `output: null`+ // asserts the code is left exactly as written. ---+ {+ // translate3d IS a horizontal translation; the old scan matched only+ // `translate(`/`translateX(` and autofixed this into the broken form.+ code: inStylex(`left: '50%', transform: 'translate3d(-50%, -50%, 0)'`),+ output: null,+ errors: [{messageId: 'inlineCentering', data: {value: '50%'}}],+ },+ {+ // matrix() carries its translation in the 5th argument.+ code: inStylex(`left: '50%', transform: 'matrix(1, 0, 0, 1, -50, 0)'`),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ code: inStylex(`+ left: '50%',+ transform: 'matrix3d(1,0,0,0, 0,1,0,0, 0,0,1,0, -50,0,0,1)'+ `),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ // scaleX(-1) mirrors the axis the translation is measured on.+ code: inStylex(`left: '50%', transform: 'scaleX(-1) translateX(-50%)'`),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ // The horizontal argument is interpolated, so nothing about it is known.+ code: inStylex("left: '50%', transform: `translateX(${x})`"),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ // The transform is a value only the runtime resolves.+ code: inStylex(`left: '50%', transform: dynamicTransform`),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ // Two horizontal translations would have to be summed to be judged.+ code: inStylex(+ `left: '50%', transform: 'translateX(-50%) translateX(4px)'`,+ ),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ // Syntax the parser cannot read is unknown, never "no translation".+ code: inStylex(`left: '50%', transform: 'translateX(-50%'`),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ // An anchor only the runtime resolves may be the centering 50%.+ code: inStylex(`left: OFFSET, transform: 'translateX(-50%)'`),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ // A calc() horizontal translation is still definitely a translation.+ code: inStylex(`left: '50%', transform: 'translateX(calc(-50% + 4px))'`),+ output: null,+ errors: [{messageId: 'inlineCentering', data: {value: '50%'}}],+ },+ {+ // ...and so is a var() one.+ code: inStylex(`left: '50%', transform: 'translateX(var(--nudge))'`),+ output: null,+ errors: [{messageId: 'inlineCentering', data: {value: '50%'}}],+ },+ // --- AUTOFIX STILL APPLIES: conservatism must not swallow the rename when+ // the transform provably leaves the inline axis alone. ---+ {+ code: inStylex(+ `left: '50%', transform: 'translateY(-50%) rotate(45deg)'`,+ ),+ output: inStylex(+ `insetInlineStart: '50%', transform: 'translateY(-50%) rotate(45deg)'`,+ ),+ errors: [+ {+ messageId: 'physicalKey',+ data: {physical: 'left', logical: 'insetInlineStart'},+ },+ ],+ },+ {+ code: inStylex(`left: '50%', transform: 'translateX(0px)'`),+ output: inStylex(`insetInlineStart: '50%', transform: 'translateX(0px)'`),+ errors: [+ {+ messageId: 'physicalKey',+ data: {physical: 'left', logical: 'insetInlineStart'},+ },+ ],+ },+ {+ // An edge anchor is not the fixed-centering idiom, translate or not.+ code: inStylex(`left: 0, transform: 'translateX(-50%)'`),+ output: inStylex(`insetInlineStart: 0, transform: 'translateX(-50%)'`),+ errors: [+ {+ messageId: 'physicalKey',+ data: {physical: 'left', logical: 'insetInlineStart'},+ },+ ],+ },++ // --- RELATIONSHIP: translations the old check could not see, and RTL arms+ // it wrongly accepted as compensation. ---+ {+ // translate3d was invisible to the old scan, so this shipped unflagged.+ code: inStylex(+ `insetInlineStart: '50%', transform: 'translate3d(-50%, -50%, 0)'`,+ ),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringTransform',+ data: {property: 'insetInlineStart', value: '50%'},+ },+ ],+ },+ {+ code: inStylex(+ `insetInlineEnd: '-50%', transform: 'translate3d(50%, 0, 0)'`,+ ),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringTransform',+ data: {property: 'insetInlineEnd', value: '-50%'},+ },+ ],+ },+ {+ // A percentage of the element's own width and a fixed length do not+ // cancel; the old check read the unit mismatch as compensation.+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translate(-50%, -50%)',+ ':is([dir="rtl"] *)': 'translate(50px, -50%)',+ }+ `),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringTransform',+ data: {property: 'insetInlineStart', value: '50%'},+ },+ ],+ },+ {+ // calc() resolves at layout time: neither compensation nor a proven+ // break. The old check called it compensation and said nothing.+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translateX(calc(-50% - 4px))',+ ':is([dir="rtl"] *)': 'translateX(calc(50% + 4px))',+ }+ `),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringUnverified',+ data: {property: 'insetInlineStart'},+ },+ ],+ },+ {+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translateX(var(--shift))',+ ':dir(rtl)': 'translateX(var(--shift-rtl))',+ }+ `),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringUnverified',+ data: {property: 'insetInlineStart'},+ },+ ],+ },+ {+ code: inStylex(+ `insetInlineStart: '50%', transform: 'matrix(1, 0, 0, 1, -50, 0)'`,+ ),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringUnverified',+ data: {property: 'insetInlineStart'},+ },+ ],+ },+ {+ code: inStylex(+ `insetInlineStart: '50%', transform: 'translateX(-50%) translateX(4px)'`,+ ),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringUnverified',+ data: {property: 'insetInlineStart'},+ },+ ],+ },+ {+ // An interpolated RTL arm cannot be compared with its default.+ code: inStylex(+ "insetInlineStart: '50%', transform: {default: 'translateX(-50%)', ':dir(rtl)': `translateX(${x})`}",+ ),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringUnverified',+ data: {property: 'insetInlineStart'},+ },+ ],+ },++ // --- COMPOSITION: a transform list composes, so a translation written+ // AFTER a rotate or a skew is measured on axes this rule can no longer+ // identify. `rotate(90deg) translateY(-50%)` moves the element sideways by+ // half its height — the old reader called both functions harmless and+ // AUTOFIXED the anchor into the broken logical form. ---+ {+ code: inStylex(+ `left: '50%', transform: 'rotate(90deg) translateY(-50%)'`,+ ),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ code: inStylex(`left: '50%', transform: 'skewX(20deg) translateY(-50%)'`),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ code: inStylex(+ `left: '50%', transform: 'rotate(90deg) translateX(-50%)'`,+ ),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ code: inStylex(+ `left: '50%', transform: 'translateY(-50%) rotate(90deg) translateY(-50%)'`,+ ),+ output: null,+ errors: [{messageId: 'inlineCenteringUnknown'}],+ },+ {+ code: inStylex(+ `insetInlineStart: '50%', transform: 'rotate(90deg) translateY(-50%)'`,+ ),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringUnverified',+ data: {property: 'insetInlineStart'},+ },+ ],+ },+ {+ // Even an RTL arm that looks like a reversal cannot be verified once the+ // axes have turned: neither side's direction is known.+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'rotate(90deg) translateY(-50%)',+ ':is([dir="rtl"] *)': 'rotate(90deg) translateY(50%)',+ }+ `),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringUnverified',+ data: {property: 'insetInlineStart'},+ },],},],diff --git a/internal/eslint-plugin-astryx/prefer-center-inline.test.mjs b/internal/eslint-plugin-astryx/prefer-center-inline.test.mjsindex 25d0d2b73a..5b833ba0c9 100644--- a/internal/eslint-plugin-astryx/prefer-center-inline.test.mjs+++ b/internal/eslint-plugin-astryx/prefer-center-inline.test.mjs@@ -46,6 +46,73 @@ ruleTester.run('prefer-center-inline', rule, {};`,},+ // --- UNPROVEN COMPENSATION: this rule only nudges code it can see is+ // already correct. A reversal it cannot verify is not a tidy-up+ // opportunity — it is no-physical-properties' unverified diagnostic. ---+ {+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translateX(calc(-50% - 4px))',+ ':is([dir="rtl"] *)': 'translateX(calc(50% + 4px))',+ }+ `),+ },+ {+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translateX(var(--shift))',+ ':dir(rtl)': 'translateX(var(--shift-rtl))',+ }+ `),+ },+ {+ // A percentage and a fixed length do not cancel.+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translate(-50%, -50%)',+ ':is([dir="rtl"] *)': 'translate(50px, -50%)',+ }+ `),+ },+ {+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'matrix(1, 0, 0, 1, -50, 0)',+ ':dir(rtl)': 'matrix(1, 0, 0, 1, 50, 0)',+ }+ `),+ },+ {+ code: inStylex(+ "insetInlineStart: '50%', transform: {default: 'translateX(-50%)', ':dir(rtl)': `translateX(${x})`}",+ ),+ },+ // A variable anchor is not fixed centering, however tidy its RTL arm is —+ // Avatar's status dot, whose offset scales with the avatar size.+ {+ code: inStylex(`+ insetInlineEnd: size * 0.07,+ transform: {+ default: 'translate(50%, 50%)',+ ':is([dir="rtl"] *)': 'translate(-50%, 50%)',+ }+ `),+ },+ // Composition defeats verification: after a rotate, neither arm's+ // direction is known, so this is not proven-correct centering to tidy up.+ {+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'rotate(90deg) translateY(-50%)',+ ':is([dir="rtl"] *)': 'rotate(90deg) translateY(50%)',+ }+ `),+ },],invalid: [{@@ -85,6 +152,29 @@ ruleTester.run('prefer-center-inline', rule, {`),errors: [{messageId: 'preferCenterInline'}],},+ {+ // The same idiom in its 3d spelling is recognised too.+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translate3d(-50%, -50%, 0)',+ ':is([dir="rtl"] *)': 'translate3d(50%, -50%, 0)',+ }+ `),+ errors: [{messageId: 'preferCenterInline'}],+ },+ {+ // A rotate AFTER the translation leaves it on the axes it was written+ // for, so this pair is still verifiably correct centering.+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translateX(-50%) rotate(45deg)',+ ':dir(rtl)': 'translateX(50%) rotate(45deg)',+ }+ `),+ errors: [{messageId: 'preferCenterInline'}],+ },],});diff --git a/internal/vibe-tests/setup-test/setup-comments.mjs b/internal/vibe-tests/setup-test/setup-comments.mjsnew file mode 100644index 0000000000..70b450498c--- /dev/null+++ b/internal/vibe-tests/setup-test/setup-comments.mjs@@ -0,0 +1,191 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Where a file's prose is, so an escape hatch never reads it as code.+ *+ * `hardcoded-important` was fixed this way in #5856: the flag is found by+ * parsing, so an executor that writes "do not reach for `!important`" in a+ * JSDoc block above the workaround it chose instead no longer fails the run for+ * saying the right thing. The two hatches still matched by pattern —+ * `blanket-reset` and `dark-mode-disabled` — had the same fault, in the same+ * shape: a guidance sentence naming `all: unset`, or a comment explaining that+ * the host's `color-scheme: light` arm was left alone, is prose, and prose is+ * not a change to the host.+ *+ * Rather than teach each pattern to recognize a comment, the comment is located+ * once, by the parser that owns the file, and blanked out of the line before+ * any pattern sees it:+ *+ * - CSS and CSS-like files go through **postcss**, whose `Comment` node is the+ * parser's own answer to "is this prose"; a `/* … *\/` inside a quoted value+ * is part of that value and is never a Comment.+ * - Scripts go through the **TypeScript** parser, which handles `.js`, `.jsx`,+ * `.ts`, and `.tsx` with one API and reports comments as trivia, so `//` in a+ * URL string and `/*` in a regular expression are not comments.+ * - HTML, Vue, and Svelte are WALKED rather than scanned (see+ * `setup-markup.mjs`, the walk this shares with `setup-important.mjs`),+ * because `<!--` opens a comment only in markup text: inside `<script>` and+ * `<style>`, and inside a tag's attribute values, those four characters are+ * ordinary content. Each raw-text element's body is handed to the analyzer+ * for its own language.+ *+ * Blanking preserves offsets and line boundaries, so a hatch written on the+ * same line as a comment is still found, and only the comment's own characters+ * stop being code.+ *+ * Anything that cannot be parsed reports NO comments. That is the fail-closed+ * direction here: a file this module cannot read keeps every character subject+ * to the scan, so an unreadable file can never be used to hide a real hatch —+ * it only risks the false positive that was already there.+ */++import postcss from 'postcss';+import ts from 'typescript';+import * as path from 'node:path';++import {+ CSS_EXTENSIONS,+ MARKUP_EXTENSIONS,+ SCRIPT_KINDS,+} from './setup-important.mjs';+import {markupRegions} from './setup-markup.mjs';++function lineStarts(text) {+ const starts = [0];+ for (let index = 0; index < text.length; index += 1) {+ if (text[index] === '\n') starts.push(index + 1);+ }+ return starts;+}++/** Comment spans in a stylesheet, via postcss; none when it cannot be read. */+function cssCommentSpans(text) {+ let root;+ try {+ root = postcss.parse(text, {from: undefined});+ } catch {+ return [];+ }+ const starts = lineStarts(text);+ const offsetOf = position => {+ if (position == null) return null;+ if (typeof position.offset === 'number') return position.offset;+ const start = starts[position.line - 1];+ return start === undefined ? null : start + position.column - 1;+ };+ const spans = [];+ root.walkComments(comment => {+ const start = offsetOf(comment.source?.start);+ const end = offsetOf(comment.source?.end);+ if (start === null) return;+ // postcss's `end` names the comment's last character; a span is exclusive.+ spans.push({start, end: end === null ? text.length : end + 1});+ });+ return spans;+}++/** Comment spans in a script, via the TypeScript parser's own trivia. */+function scriptCommentSpans(text, fileName, scriptKind) {+ let source;+ try {+ source = ts.createSourceFile(+ fileName,+ text,+ ts.ScriptTarget.Latest,+ true,+ scriptKind,+ );+ } catch {+ return [];+ }+ const spans = [];+ const seen = new Set();+ const collect = ranges => {+ for (const range of ranges ?? []) {+ if (seen.has(range.pos)) continue;+ seen.add(range.pos);+ spans.push({start: range.pos, end: range.end});+ }+ };+ const visit = node => {+ // JSX text is content, not trivia: `//` in a sentence or a URL there is+ // part of the document, and scanning it for comments would blank real+ // markup.+ if (node.kind !== ts.SyntaxKind.JsxText) {+ // Leading ranges stop at the first line break, so a comment that begins+ // on the same line as the code before it is only ever a TRAILING range —+ // which is where `// note` after a statement, and the body of a JSX+ // `{/* … */}`, both live.+ collect(ts.getLeadingCommentRanges(text, node.getFullStart()));+ collect(ts.getTrailingCommentRanges(text, node.getEnd()));+ }+ // `getChildren` walks tokens as well as nodes, which is what a JSX comment+ // needs: `{/* … */}` holds no expression, so its comment hangs off the+ // braces and `forEachChild` never reaches them.+ for (const child of node.getChildren(source)) {+ visit(child);+ }+ };+ try {+ visit(source);+ } catch {+ return [];+ }+ return spans;+}++/**+ * Comment spans in markup, over the regions of the shared structural walk.+ *+ * WHERE a comment can begin is the whole point — see `setup-markup.mjs`. A real+ * `<!-- … -->` is prose; a raw-text element's body is handed to the analyzer+ * for ITS language, where only a real `/* … *\/` or `//` counts; a tag and its+ * attribute values are neither, so `<!--` written inside one stays visible.+ */+function markupCommentSpans(text, fileName) {+ const spans = [];+ for (const region of markupRegions(text)) {+ if (region.kind === 'comment') {+ spans.push({start: region.start, end: region.end});+ continue;+ }+ if (region.kind !== 'style' && region.kind !== 'script') continue;+ const body = text.slice(region.start, region.end);+ const inner =+ region.kind === 'style'+ ? cssCommentSpans(body)+ : scriptCommentSpans(body, `${fileName}.ts`, ts.ScriptKind.TS);+ for (const span of inner) {+ spans.push({+ start: span.start + region.start,+ end: span.end + region.start,+ });+ }+ }+ return spans;+}++/**+ * The character spans of every comment in `text`, as `{start, end}` offsets.+ *+ * A file whose extension has no analyzer, and a file its analyzer cannot read,+ * both report no comments: nothing is exempted from the scan on a guess.+ */+export function commentSpans(relativePath, text) {+ if (typeof text !== 'string' || text === '') return [];+ const extension = path.extname(relativePath).toLowerCase();+ if (CSS_EXTENSIONS.has(extension)) {+ return cssCommentSpans(text);+ }+ if (SCRIPT_KINDS.has(extension)) {+ return scriptCommentSpans(+ text,+ path.basename(relativePath),+ SCRIPT_KINDS.get(extension),+ );+ }+ if (MARKUP_EXTENSIONS.has(extension)) {+ return markupCommentSpans(text, path.basename(relativePath));+ }+ return [];+}diff --git a/internal/vibe-tests/setup-test/setup-comments.test.mjs b/internal/vibe-tests/setup-test/setup-comments.test.mjsnew file mode 100644index 0000000000..5d012a6f75--- /dev/null+++ b/internal/vibe-tests/setup-test/setup-comments.test.mjs@@ -0,0 +1,335 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file setup-comments.test.mjs+ *+ * The contract these cases hold to: a comment stops being code, and NOTHING+ * else does. Both halves matter — the first is why the escape hatches stopped+ * failing runs for prose, and the second is why blanking them cannot be used to+ * hide a real hatch behind something comment-shaped.+ */++import {describe, expect, it} from 'vitest';+import {commentSpans} from './setup-comments.mjs';++/** The text with its comments blanked, exactly as the hatch scan sees it. */+function masked(relativePath, text) {+ let out = text;+ for (const span of commentSpans(relativePath, text)) {+ // Line boundaries survive blanking — the scan works line by line.+ out =+ out.slice(0, span.start) ++ out.slice(span.start, span.end).replace(/[^\n]/g, ' ') ++ out.slice(span.end);+ }+ return out;+}++describe('commentSpans — stylesheets', () => {+ it('blanks a comment and keeps the declaration beside it', () => {+ const css =+ '.a {\n /* all: unset would be a blanket reset */\n all: unset;\n}\n';++ const result = masked('src/index.css', css);++ expect(result).not.toMatch(/all: unset would/);+ expect(result).toContain('all: unset;');+ });++ it('blanks a comment that trails real code on one line', () => {+ const css = '.a { all: unset; } /* deliberate */\n';++ const result = masked('src/index.css', css);++ expect(result).toContain('all: unset;');+ expect(result).not.toContain('deliberate');+ });++ it('does not treat a comment opener inside a quoted value as a comment', () => {+ // A lexical scan would blank from `/*` to end of file and swallow the real+ // reset two lines down.+ const css = '.a {\n content: "/*";\n}\n.b {\n all: unset;\n}\n';++ expect(masked('src/index.css', css)).toContain('all: unset;');+ });++ it('reads .scss, .less, and .pcss the same way', () => {+ for (const file of ['src/a.scss', 'src/a.less', 'src/a.pcss']) {+ expect(+ masked(file, '/* color-scheme: light */\n.a { color: red; }\n'),+ ).not.toContain('color-scheme');+ }+ });++ it('reports nothing for a stylesheet postcss cannot parse', () => {+ // Fail closed: an unreadable file keeps every character subject to the scan.+ expect(+ commentSpans('src/broken.css', '@media (min-width: 10px {\n'),+ ).toEqual([]);+ });+});++describe('commentSpans — scripts', () => {+ it('blanks line, block, and JSDoc comments', () => {+ const source = [+ '// darkMode: false is what the guidance tells you not to write',+ '/* nor color-scheme: light only */',+ '/**',+ ' * And not `all: unset` either.',+ ' */',+ 'export const config = {};',+ '',+ ].join('\n');++ const result = masked('src/config.ts', source);++ expect(result).not.toMatch(/darkMode: false/);+ expect(result).not.toMatch(/color-scheme: light only/);+ expect(result).not.toMatch(/all: unset/);+ expect(result).toContain('export const config = {};');+ });++ it('keeps a real declaration written on the same line as its comment', () => {+ const source = 'export const config = {darkMode: false}; // host default\n';++ const result = masked('src/config.ts', source);++ expect(result).toContain('darkMode: false');+ expect(result).not.toContain('host default');+ });++ it('does not read `//` inside a string as a comment', () => {+ // The URL is not a comment, so the code after it stays code.+ const source =+ "const docs = 'https://example.com';\nexport const config = {darkMode: false};\n";++ expect(masked('src/config.ts', source)).toContain('darkMode: false');+ });++ it('blanks a JSX comment but not JSX text', () => {+ const source = [+ 'export function Note() {',+ ' return (',+ ' <p>',+ ' {/* darkMode: false belongs to the host */}',+ ' See https://example.com for darkMode: false guidance',+ ' </p>',+ ' );',+ '}',+ '',+ ].join('\n');++ const result = masked('src/Note.tsx', source);++ expect(result).not.toContain('belongs to the host');+ // JSX text is content, not a comment: the `//` in the URL must not blank+ // the rest of the line.+ expect(result).toContain('for darkMode: false guidance');+ });++ it('blanks a comment that trails the last statement', () => {+ const source = 'export const config = {};\n// color-scheme: light only\n';++ expect(masked('src/config.ts', source)).not.toContain('color-scheme');+ });++ it('reads .js, .jsx, .mjs, and .cjs too', () => {+ for (const file of ['a.js', 'a.jsx', 'a.mjs', 'a.cjs']) {+ expect(+ masked(`src/${file}`, '// all: unset\nmodule.exports = {};\n'),+ ).not.toContain('all: unset');+ }+ });+});++describe('commentSpans — markup', () => {+ it('blanks HTML comments and the comments inside style and script blocks', () => {+ const html = [+ '<!doctype html>',+ '<!-- all: unset is not allowed here -->',+ '<style>',+ ' /* nor color-scheme: light only */',+ ' .host { color: CanvasText; }',+ '</style>',+ '<script>',+ ' // and not darkMode: false',+ ' window.host = true;',+ '</script>',+ '',+ ].join('\n');++ const result = masked('index.html', html);++ expect(result).not.toContain('not allowed here');+ expect(result).not.toContain('color-scheme: light only');+ expect(result).not.toContain('darkMode: false');+ expect(result).toContain('.host { color: CanvasText; }');+ expect(result).toContain('window.host = true;');+ });++ it('leaves a real declaration in a style block alone', () => {+ const html = '<style>\n /* a note */\n .host { all: unset; }\n</style>\n';++ expect(masked('index.html', html)).toContain('all: unset;');+ });++ it('reads .vue and .svelte the same way', () => {+ for (const file of ['App.vue', 'App.svelte']) {+ expect(masked(file, '<!-- all: unset -->\n<div />\n')).not.toContain(+ 'all: unset',+ );+ }+ });+});++/**+ * `<!--` opens a comment only where markup TEXT can appear. A flat scan for the+ * delimiters blanks the same characters wherever they occur, which is not a+ * false positive — it is a way to get a hatch past the check and then apply it.+ */+describe('commentSpans — markup delimiters that are not comments', () => {+ it('does not exempt a comment-shaped string a script reconstructs and applies', () => {+ const html = [+ '<div id="root"></div>',+ '<script>',+ " const cloak = '<!-- all: unset -->';",+ ' document.body.style.cssText = cloak.slice(4, -3).trim();',+ '</script>',+ '',+ ].join('\n');++ const result = masked('index.html', html);++ expect(result).toContain('all: unset');+ expect(result).toContain('style.cssText');+ });++ it('does not exempt the delimiters inside a template literal either', () => {+ const html = [+ '<script>',+ ' const parts = [`<!-- darkMode: false -->`];',+ ' applyConfig(parts[0].slice(4, -3));',+ '</script>',+ '',+ ].join('\n');++ expect(masked('index.html', html)).toContain('darkMode: false');+ });++ it('does not exempt the delimiters inside an attribute value', () => {+ const html =+ '<div data-note="<!-- all: unset -->" style="all: unset"></div>\n';++ // A tag is skipped, never blanked, so the whole line survives.+ expect(masked('index.html', html)).toBe(html);+ });++ it('does not exempt the delimiters inside a style block', () => {+ // CSS has no `<!-- -->` comment; postcss owns this body and reports none.+ const html = '<style>\n <!-- .host { all: unset; } -->\n</style>\n';++ expect(masked('index.html', html)).toContain('all: unset');+ });++ it('still exempts a real markup comment that wraps a script', () => {+ const html = [+ '<!--',+ '<script>',+ " document.body.style.cssText = 'all: unset';",+ '</script>',+ '-->',+ '',+ ].join('\n');++ expect(masked('index.html', html)).not.toContain('all: unset');+ });++ it('still exempts a real markup comment beside a real script', () => {+ const html = [+ '<!-- all: unset is not allowed -->',+ '<script>',+ ' const config = {darkMode: false};',+ '</script>',+ '',+ ].join('\n');++ const result = masked('index.html', html);++ expect(result).not.toContain('is not allowed');+ expect(result).toContain('darkMode: false');+ });++ it('reads an unterminated <script> body as script', () => {+ // No closing tag: the rest of the file is script, and only its own+ // comments are exempt.+ const html = '<script>\n // a note\n const config = {darkMode: false};\n';++ const result = masked('index.html', html);++ expect(result).not.toContain('a note');+ expect(result).toContain('darkMode: false');+ });+});++describe('commentSpans — nothing is exempted on a guess', () => {+ it('reports nothing for an extension with no analyzer', () => {+ expect(commentSpans('notes.txt', '// all: unset\n')).toEqual([]);+ expect(commentSpans('README.md', '<!-- all: unset -->\n')).toEqual([]);+ });++ it('reports nothing for empty or non-string input', () => {+ expect(commentSpans('src/a.ts', '')).toEqual([]);+ expect(commentSpans('src/a.ts', undefined)).toEqual([]);+ expect(commentSpans('src/a.ts', null)).toEqual([]);+ });++ it('preserves offsets and line boundaries, so line numbers still line up', () => {+ const source =+ '/* one */\nconst a = 1; // two\n/* three\n four */\nconst b = 2;\n';++ const result = masked('src/a.ts', source);++ expect(result).toHaveLength(source.length);+ expect(result.split('\n')).toHaveLength(source.split('\n').length);+ expect(result.split('\n')[1]).toContain('const a = 1;');+ });+});++/**+ * Tag boundaries, which the shared walk owns. A tag is skipped, never blanked,+ * so nothing written inside one is exempted — and the walk must find its end+ * correctly for the regions after it to line up.+ */+describe('commentSpans — tag boundaries', () => {+ it.each([+ {+ name: 'an unquoted attribute value',+ source: '<div style=color:red></div>\n',+ },+ {+ name: 'a bare attribute',+ source: '<div hidden style="all: unset"></div>\n',+ },+ {name: 'a self-closing tag', source: '<img style="all: unset" />\n'},+ {+ name: 'a > inside a quoted value',+ source: '<div title="a > b" data-x="<!-- all: unset -->"></div>\n',+ },+ {+ name: 'an attribute value holding comment delimiters',+ source: "<div title='<!-- all: unset -->'>text</div>\n",+ },+ ])('leaves $name fully visible', ({source}) => {+ expect(masked('index.html', source)).toBe(source);+ });++ it('still finds a real comment after a tag with tricky attributes', () => {+ const source =+ '<div title="a > b" style=color:red></div>\n<!-- all: unset -->\n';++ const result = masked('index.html', source);++ expect(result).not.toContain('all: unset');+ expect(result).toContain('title="a > b"');+ });+});diff --git a/internal/vibe-tests/setup-test/setup-important.mjs b/internal/vibe-tests/setup-test/setup-important.mjsindex b8300a977f..e48470e5c6 100644--- a/internal/vibe-tests/setup-test/setup-important.mjs+++ b/internal/vibe-tests/setup-test/setup-important.mjs@@ -21,29 +21,63 @@* `.ts`, and `.tsx` with one API. Comments are trivia and are not nodes, so* they cannot be found; only string and template literals are examined, and* only where the literal is applied as CSS.- * - HTML, Vue, and Svelte are split into their `<style>` blocks, their- * `style="…"` attributes, and their `<script>` blocks, and each part is handed- * to the analyzer above that owns it. Comments and text content are neither.+ * - HTML, Vue, and Svelte are WALKED (see `setup-markup.mjs`) into their+ * `<style>` blocks, their `style="…"` attributes, and their `<script>`+ * blocks, and each part is handed to the analyzer above that owns it.+ * Comments and text content are neither. The walk matters: `<!--` opens a+ * comment only in markup text, so blanking those delimiters wherever they+ * appear would let a script hide a flag in a string and then apply it.** Ignoring comments and prose must not open a way to smuggle a real override* past the check, so a literal counts as CSS whenever it is applied as CSS:*- * 1. it *contains* a declaration carrying the flag (`color: red !important`),- * which covers CSS-in-JS templates, `cssText`, `insertRule`, and inline- * style strings, including one assembled across a template's interpolations;- * 2. it *is* the value of a CSS property — a style-object entry, a `style.*`+ * 1. it *is* a stylesheet — a selector with a braced block carrying the flag,+ * which is what CSS-in-JS templates, `cssText`, and `insertRule` consume,+ * and which is structure prose does not have;+ * 2. it *carries a declaration* AND something applies it: the literal sits in a+ * CSS sink (a `style.*` assignment, a style-object entry, a JSX `style`,+ * `setProperty`, `setAttribute('style', …)`, `insertRule`), or the BINDING it+ * is bound to is one such a sink reads — which is how a declaration+ * reassembled out of a cloaked string (`el.style.cssText = cloak.slice(4,+ * -3)`) is still found. Reachability resolves each reference to its+ * declaration through the scope chain, so a prose `value` in one function is+ * not implicated by an unrelated `value` a sink reads in another;+ * 3. it *is* the value of a CSS property — a style-object entry, a `style.*`* assignment, a JSX `style={{…}}` entry — where the property name is a real* CSS property, taken from `CSSStyleDeclaration` in the TypeScript DOM* library rather than from a hand-written list that could miss one;- * 3. it is the priority argument of `setProperty(property, value, 'important')`,+ * 4. it is the priority argument of `setProperty(property, value, 'important')`,* which sets the same flag without ever spelling `!important`, and which the* old lexical scan could not see at all.*+ * Case 2's second half is what keeps prose quiet. Characters that spell a+ * declaration are not an override — `export const RULE = 'Never write color:+ * red !important'` is guidance, and failing a run for it is the exact fault+ * this file was written to fix. Only a declaration something in the file+ * APPLIES is one the host receives.+ ** Anything the parsers cannot read fails closed: an unparsable stylesheet falls* back to a scanner that skips only comments and quoted strings, and a file* whose CSS property vocabulary cannot be loaded treats every style-shaped* property as a CSS property. A file that cannot be understood is never given* the benefit of the doubt.+ *+ * KNOWN GAP, pre-dating this file: a declaration split across SEPARATE+ * variables (`const a = 'color: red'; const b = ' !important';+ * el.style.cssText = a + b`) is not found, because neither literal carries a+ * declaration on its own. Following values across bindings is real dataflow+ * analysis; a template's own interpolations are covered, and a value passed+ * into a function as an argument is likewise not traced. Recorded rather than+ * papered over.+ *+ * DELIBERATE OVER-REPORT: when one binding is written twice (`var v` declared+ * twice, or a `let` reassigned) and a sink reads it, EVERY declaration-carrying+ * literal written to that binding is reported. Which write reaches the sink is+ * a question of flow — a branch can make either one — so the check reports the+ * binding rather than guessing an order. This is the fail-closed direction: the+ * cost is naming an extra line in code that assigns prose and CSS to the same+ * variable, and the alternative is an executor defeating the check with an+ * `if`.*/import * as fs from 'node:fs';@@ -51,6 +85,7 @@ import * as path from 'node:path';import {createRequire} from 'node:module';import postcss from 'postcss';import ts from 'typescript';+import {markupRegions} from './setup-markup.mjs';/** The flag itself: `!important`, `! important`, `!IMPORTANT`. */const IMPORTANT_FLAG = /!\s*important\b/gi;@@ -59,12 +94,41 @@ const IMPORTANT_FLAG = /!\s*important\b/gi;* A declaration carrying the flag, inside arbitrary CSS text. The property may* be a custom property or an ordinary one, and the value may be anything that* does not close the declaration.+ *+ * The property is required not to CONTINUE an identifier — so `background-color:+ * red !important` is one declaration rather than also matching at `color` — but+ * it is not required to sit at the start of the text. That anchoring was a way+ * past the check: any prefix at all defeated it, so+ * `'<!-- color: red !important -->'` was not a declaration while the code+ * beside it still applied one.+ *+ * On its own this says only "these characters spell a declaration", which prose+ * does too ("never write `color: red !important`"). Inside a script it is+ * therefore not sufficient — see `carriesAppliedCss`.*/const DECLARATION_WITH_FLAG =- /(?:^|[;{}])\s*(?:--[\w-]+|[A-Za-z][\w-]*)\s*:\s*[^;{}]*?!\s*important\b/gi;+ /(?<![\w-])(?:--[\w-]+|[A-Za-z][\w-]*)\s*:\s*[^;{}]*?!\s*important\b/gi;++/**+ * A complete CSS RULE carrying the flag: a selector, a braced block, and a+ * flagged declaration inside it.+ *+ * This is structure prose does not have. A string shaped like a stylesheet IS a+ * stylesheet — it is what `cssText`, `insertRule`, and every CSS-in-JS template+ * consume — so it counts wherever it is written, without needing to be traced+ * to the code that applies it.+ */+const RULE_WITH_FLAG =+ /\{[^{}]*(?<![\w-])(?:--[\w-]+|[A-Za-z][\w-]*)\s*:\s*[^;{}]*?!\s*important\b[^{}]*\}/i;-const CSS_EXTENSIONS = new Set(['.css', '.less', '.pcss', '.sass', '.scss']);-const SCRIPT_KINDS = new Map([+export const CSS_EXTENSIONS = new Set([+ '.css',+ '.less',+ '.pcss',+ '.sass',+ '.scss',+]);+export const SCRIPT_KINDS = new Map([['.cjs', ts.ScriptKind.JS],['.js', ts.ScriptKind.JS],['.jsx', ts.ScriptKind.JSX],@@ -72,7 +136,7 @@ const SCRIPT_KINDS = new Map([['.ts', ts.ScriptKind.TS],['.tsx', ts.ScriptKind.TSX],]);-const MARKUP_EXTENSIONS = new Set(['.html', '.svelte', '.vue']);+export const MARKUP_EXTENSIONS = new Set(['.html', '.svelte', '.vue']);/* ---------------------------------------------------------------------------* CSS property vocabulary@@ -413,6 +477,19 @@ function inDeclaredStyleObject(node) {return false;}+/** `element.style.setProperty('color', 'red !important')` — the value argument. */+function isSetPropertyValue(node) {+ const parent = node.parent;+ if (!parent || !ts.isCallExpression(parent)) return false;+ const callee = parent.expression;+ const name = ts.isPropertyAccessExpression(callee)+ ? callee.name.text+ : ts.isIdentifier(callee)+ ? callee.text+ : null;+ return name === 'setProperty' && parent.arguments.indexOf(node) === 1;+}+/** `element.style.setProperty('color', 'red', 'important')`. */function isSetPropertyPriority(node) {const parent = node.parent;@@ -470,6 +547,367 @@ function mapTemplateOffset(segments, offset) {return null;}+/**+ * A call whose argument is handed to the CSS engine.+ * `insertRule` and `appendRule` take a rule; `setAttribute('style', …)` and+ * `setProperty(prop, value)` take declarations.+ */+function cssSinkCall(node) {+ if (!ts.isCallExpression(node)) return null;+ const callee = node.expression;+ const name = ts.isPropertyAccessExpression(callee)+ ? callee.name.text+ : ts.isIdentifier(callee)+ ? callee.text+ : null;+ if (name === 'insertRule' || name === 'appendRule') {+ return node.arguments[0] ?? null;+ }+ if (name === 'setProperty') {+ return node.arguments[1] ?? null;+ }+ if (name === 'setAttribute') {+ const attribute = node.arguments[0];+ if (+ attribute &&+ ts.isStringLiteralLike(attribute) &&+ attribute.text.toLowerCase() === 'style'+ ) {+ return node.arguments[1] ?? null;+ }+ }+ return null;+}++/**+ * The expression a CSS sink consumes, when `node` IS that sink.+ *+ * A sink is any place a value becomes style the host renders: an assignment to+ * `style.*` (`cssText` included), an entry of a style object, a JSX `style`+ * attribute, or a call that hands CSS to the engine.+ */+/** The property name of a member access, whether dotted or computed. */+function accessedName(node) {+ if (ts.isPropertyAccessExpression(node)) return node.name.text;+ if (ts.isElementAccessExpression(node)) {+ const argument = node.argumentExpression;+ return argument && ts.isStringLiteralLike(argument) ? argument.text : null;+ }+ return null;+}++/** The object a member access reads from. */+function accessedOwner(node) {+ if (+ ts.isPropertyAccessExpression(node) ||+ ts.isElementAccessExpression(node)+ ) {+ return node.expression;+ }+ return null;+}++/**+ * The expression a CSS sink consumes, when `node` IS that sink.+ *+ * A sink is any place a value becomes style the host renders: an assignment to+ * `style.*` (`cssText` included), an entry of a style object, a JSX `style`+ * attribute, or a call that hands CSS to the engine. Member access is read in+ * either spelling — `el.style.cssText` and `el.style['cssText']` set the same+ * property, and understanding only the dotted form left the other as a way+ * past the check.+ */+function cssSinkExpression(node) {+ if (+ ts.isBinaryExpression(node) &&+ node.operatorToken.kind === ts.SyntaxKind.EqualsToken+ ) {+ const name = accessedName(node.left);+ if (name !== null) {+ const owner = accessedOwner(node.left);+ const ownerName =+ owner === null+ ? null+ : (accessedName(owner) ??+ (ts.isIdentifier(owner) ? owner.text : null));+ if (ownerName === 'style') return node.right;+ if (/^(?:style|sx|css)$/i.test(name)) return node.right;+ }+ }+ if (ts.isPropertyAssignment(node)) {+ const name =+ ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)+ ? node.name.text+ : null;+ if (+ name !== null &&+ (isCssPropertyName(name) || /^(?:style|sx|css)$/i.test(name))+ ) {+ return node.initializer;+ }+ }+ if (+ ts.isJsxAttribute(node) &&+ ts.isIdentifier(node.name) &&+ /^(?:style|sx|css)$/i.test(node.name.text)+ ) {+ return node.initializer ?? null;+ }+ return cssSinkCall(node);+}++/** Is this literal written inside something that applies it as CSS? */+function inCssSink(node) {+ let child = node;+ let current = node.parent;+ while (current) {+ const sink = cssSinkExpression(current);+ // The literal must be inside the CONSUMED expression — the right-hand side,+ // the argument — not merely somewhere in the same statement.+ if (sink !== null && sink !== undefined && containsNode(sink, child)) {+ return true;+ }+ if (ts.isSourceFile(current)) break;+ child = current;+ current = current.parent;+ }+ return false;+}++function containsNode(root, target) {+ let current = target;+ while (current) {+ if (current === root) return true;+ current = current.parent;+ }+ return false;+}++/* ---------------------------------------------------------------------------+ * Binding resolution+ *+ * Reachability is keyed on the DECLARATION a reference resolves to, not on the+ * identifier's name. Two functions may each declare `value`; only the one whose+ * `value` a CSS sink reads is applying anything, and reporting the other is the+ * prose false positive this file exists to prevent.+ *+ * The literals are parsed with `createSourceFile`, so there is no TypeChecker+ * to ask. The scope chain is walked directly instead: block scoping for+ * `let`/`const`/`class`, function scoping for `var` and function declarations,+ * plus parameters. That is the resolution JavaScript itself performs.+ * ------------------------------------------------------------------------- */++function isFunctionLikeScope(node) {+ return (+ ts.isFunctionDeclaration(node) ||+ ts.isFunctionExpression(node) ||+ ts.isArrowFunction(node) ||+ ts.isMethodDeclaration(node) ||+ ts.isConstructorDeclaration(node) ||+ ts.isGetAccessorDeclaration(node) ||+ ts.isSetAccessorDeclaration(node)+ );+}++function isScope(node) {+ return (+ ts.isSourceFile(node) ||+ ts.isBlock(node) ||+ ts.isModuleBlock(node) ||+ ts.isCaseBlock(node) ||+ ts.isCatchClause(node) ||+ ts.isForStatement(node) ||+ ts.isForInStatement(node) ||+ ts.isForOfStatement(node) ||+ isFunctionLikeScope(node)+ );+}++/**+ * The declarations a scope owns, by name.+ *+ * `var` and function declarations hoist out of nested blocks to the nearest+ * function or module scope, so they are collected through those blocks;+ * `let`/`const`/`class` stop at their own block. Nested functions leak nothing.+ *+ * A name may be declared more than once — `var v` twice in a function is ONE+ * binding, redeclared. Every declaration of a name therefore maps to the same+ * key (the first one seen), so a literal written at the second `var` and a sink+ * reading the name resolve to the same thing rather than missing each other.+ */+function collectDeclarations(scope) {+ const found = new Map();+ const add = (nameNode, declaration) => {+ if (nameNode && ts.isIdentifier(nameNode) && !found.has(nameNode.text)) {+ found.set(nameNode.text, declaration);+ }+ };++ if (isFunctionLikeScope(scope)) {+ for (const parameter of scope.parameters ?? [])+ add(parameter.name, parameter);+ }+ if (ts.isCatchClause(scope) && scope.variableDeclaration) {+ add(scope.variableDeclaration.name, scope.variableDeclaration);+ }++ const visit = (node, crossedBlock) => {+ if (node !== scope && isScope(node)) {+ // A nested function is a closed world; a nested block still lets `var`+ // and function declarations hoist through it.+ if (isFunctionLikeScope(node)) return;+ ts.forEachChild(node, child => visit(child, true));+ return;+ }+ if (ts.isVariableDeclarationList(node)) {+ const blockScoped =+ (node.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)) !== 0;+ if (!crossedBlock || !blockScoped) {+ for (const declaration of node.declarations)+ add(declaration.name, declaration);+ }+ return;+ }+ if (ts.isFunctionDeclaration(node)) {+ add(node.name, node);+ return;+ }+ if (ts.isClassDeclaration(node) && !crossedBlock) {+ add(node.name, node);+ return;+ }+ if (ts.isImportClause(node)) {+ add(node.name, node);+ if (node.namedBindings) {+ if (ts.isNamespaceImport(node.namedBindings)) {+ add(node.namedBindings.name, node.namedBindings);+ } else {+ for (const element of node.namedBindings.elements)+ add(element.name, element);+ }+ }+ return;+ }+ ts.forEachChild(node, child => visit(child, crossedBlock));+ };+ ts.forEachChild(scope, child => visit(child, false));+ return found;+}++/** The declaration an identifier resolves to, by walking its scope chain. */+function resolveBinding(identifier, cache) {+ let node = identifier.parent;+ while (node) {+ if (isScope(node)) {+ let declarations = cache.get(node);+ if (declarations === undefined) {+ declarations = collectDeclarations(node);+ cache.set(node, declarations);+ }+ const hit = declarations.get(identifier.text);+ if (hit) return hit;+ }+ node = node.parent;+ }+ return null;+}++/**+ * The declaration a literal is bound to, if it is bound to one at all.+ *+ * The declaration is resolved BY NAME through the scope chain rather than+ * returned directly, so a redeclared `var` yields the one binding both its+ * declarations share.+ */+function bindingOfLiteral(node, cache) {+ let current = node.parent;+ while (current) {+ if (ts.isVariableDeclaration(current) && ts.isIdentifier(current.name)) {+ return resolveBinding(current.name, cache) ?? current;+ }+ if (+ ts.isBinaryExpression(current) &&+ current.operatorToken.kind === ts.SyntaxKind.EqualsToken &&+ ts.isIdentifier(current.left)+ ) {+ return resolveBinding(current.left, cache);+ }+ if (ts.isStatement(current) || ts.isSourceFile(current)) return null;+ current = current.parent;+ }+ return null;+}++/**+ * Every identifier a CSS sink READS AS THE VALUE, as AST nodes rather than+ * names.+ *+ * A reference only counts when the value flowing into the sink can be the+ * binding's own. `el.style.cssText = guidance.length > 0 ? a : b` mentions+ * `guidance`, but what reaches the sink is a number's comparison and then some+ * other string — the guidance text itself never lands as CSS. Reading a+ * PROPERTY off the reference (`.length`, `.name`) is therefore not a use of the+ * string, while calling a method on it (`.slice`, `.trim`, `.replace`) is,+ * because that is exactly how a cloaked declaration is reassembled.+ */+function cssSinkReferences(source) {+ const references = [];+ const collect = node => {+ if (ts.isIdentifier(node) && !isNonValueMemberUse(node)) {+ references.push(node);+ }+ ts.forEachChild(node, collect);+ };+ const visit = node => {+ const sink = cssSinkExpression(node);+ if (sink !== null && sink !== undefined) collect(sink);+ ts.forEachChild(node, visit);+ };+ visit(source);+ return references;+}++/**+ * Is this reference read only for a property of the value, rather than for the+ * value itself?+ *+ * The whole member chain is walked, because indexing and calling compose:+ * `parts[0].slice(4, -3)` reads an element and then calls a method on it, which+ * keeps the string in play, while `guidance.length` yields a number and the+ * string never reaches the sink. A chain that ends in a CALL is a use of the+ * value; a chain that ends in a plain read is not. The member NAME is never a+ * reference to the binding either.+ */+function isNonValueMemberUse(identifier) {+ const parent = identifier.parent;+ if (+ parent &&+ ts.isPropertyAccessExpression(parent) &&+ parent.name === identifier+ ) {+ return true;+ }++ let current = identifier;+ let sawMember = false;+ while (+ current.parent &&+ (ts.isPropertyAccessExpression(current.parent) ||+ ts.isElementAccessExpression(current.parent)) &&+ current.parent.expression === current+ ) {+ current = current.parent;+ sawMember = true;+ }+ if (!sawMember) return false;++ return !(+ current.parent &&+ ts.isCallExpression(current.parent) &&+ current.parent.expression === current+ );+}+/*** Flag offsets in a script: only inside string and template literals, and only* where the literal is applied as CSS.@@ -483,6 +921,29 @@ function scriptFlagOffsets(text, fileName, scriptKind) {scriptKind,);const offsets = [];+ const bindingCache = new Map();+ const sinkReferences = cssSinkReferences(source);++ /** Does a CSS sink read the very binding this literal is bound to? */+ const reachesSinkBinding = node => {+ const binding = bindingOfLiteral(node, bindingCache);+ if (binding === null) return false;+ return sinkReferences.some(+ reference => resolveBinding(reference, bindingCache) === binding,+ );+ };++ /**+ * Does this literal's declaration text count as CSS the host receives?+ *+ * A bare declaration is only characters — prose spells one when it tells an+ * executor not to write one — so it counts when something in the file APPLIES+ * it: the literal sits in a CSS sink, or the binding it is bound to is one a+ * sink reads. A literal carrying a whole braced rule is a stylesheet on its+ * face and needs no such evidence.+ */+ const carriesAppliedCss = (node, content) =>+ RULE_WITH_FLAG.test(content) || inCssSink(node) || reachesSinkBinding(node);const considerPlainLiteral = node => {const content = node.text;@@ -493,16 +954,17 @@ function scriptFlagOffsets(text, fileName, scriptKind) {IMPORTANT_FLAG.lastIndex = 0;const contentStart = node.getStart() + 1;const declarationOffsets = declarationFlagOffsets(content, contentStart);- if (declarationOffsets.length > 0) {+ if (declarationOffsets.length > 0 && carriesAppliedCss(node, content)) {offsets.push(...declarationOffsets);return;}const property = objectPropertyName(node) ?? styleAssignmentProperty(node);if (- property !== null &&- (property === 'cssText' ||- isCssPropertyName(property) ||- inDeclaredStyleObject(node))+ isSetPropertyValue(node) ||+ (property !== null &&+ (property === 'cssText' ||+ isCssPropertyName(property) ||+ inDeclaredStyleObject(node)))) {offsets.push(...flagOffsets(content, contentStart));}@@ -510,18 +972,23 @@ function scriptFlagOffsets(text, fileName, scriptKind) {const considerTemplate = node => {const {text: cooked, segments} = templateText(node);- for (const offset of declarationFlagOffsets(cooked)) {- const mapped = mapTemplateOffset(segments, offset);- if (mapped !== null) {- offsets.push(mapped);+ const declarationOffsets = declarationFlagOffsets(cooked);+ if (declarationOffsets.length > 0 && carriesAppliedCss(node, cooked)) {+ for (const offset of declarationOffsets) {+ const mapped = mapTemplateOffset(segments, offset);+ if (mapped !== null) {+ offsets.push(mapped);+ }}+ return;}const property = objectPropertyName(node) ?? styleAssignmentProperty(node);if (- property !== null &&- (property === 'cssText' ||- isCssPropertyName(property) ||- inDeclaredStyleObject(node))+ isSetPropertyValue(node) ||+ (property !== null &&+ (property === 'cssText' ||+ isCssPropertyName(property) ||+ inDeclaredStyleObject(node)))) {for (const offset of flagOffsets(cooked)) {const mapped = mapTemplateOffset(segments, offset);@@ -555,48 +1022,38 @@ function scriptFlagOffsets(text, fileName, scriptKind) {* Markup* ------------------------------------------------------------------------- */-/** The document with every `<!-- … -->` comment blanked, offsets preserved. */-function maskMarkupComments(text) {- let masked = text;- for (const match of text.matchAll(/<!--[\s\S]*?(?:-->|$)/g)) {- masked =- masked.slice(0, match.index) +- ' '.repeat(match[0].length) +- masked.slice(match.index + match[0].length);- }- return masked;-}--function* taggedBlocks(text, tag) {- const pattern = new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*?)</${tag}>`, 'gi');- for (const match of text.matchAll(pattern)) {- yield {body: match[1], start: match.index + match[0].indexOf(match[1])};- }-}-+/**+ * Flag offsets in markup, over the regions of the shared structural walk.+ *+ * The document is WALKED rather than scanned for `<!-- … -->`. A scan blanks+ * those delimiters wherever they occur — including inside a script's own string+ * — which let a flag be smuggled past this check and then applied:+ * `const c = '<!-- color: red !important -->'` was blanked, while+ * `style.cssText = c.slice(4, -3)` still set the override. Inside `<script>`+ * and `<style>`, and inside a tag's attribute values, those characters are+ * ordinary content, and each region's own parser is what decides whether the+ * flag is applied there.+ */function markupFlagOffsets(text, fileName) {- const masked = maskMarkupComments(text);const offsets = [];- for (const block of taggedBlocks(masked, 'style')) {- offsets.push(- ...cssFlagOffsets(block.body).map(offset => offset + block.start),- );- }- for (const block of taggedBlocks(masked, 'script')) {- offsets.push(- ...scriptFlagOffsets(block.body, `${fileName}.ts`, ts.ScriptKind.TS).map(- offset => offset + block.start,- ),- );- }- for (const match of masked.matchAll(- /\bstyle\s*=\s*("([^"]*)"|'([^']*)')/gi,- )) {- const value = match[2] ?? match[3] ?? '';- const valueStart = match.index + match[0].indexOf(value, 'style'.length);- offsets.push(- ...styleAttributeFlagOffsets(value).map(offset => offset + valueStart),- );+ for (const region of markupRegions(text)) {+ const body = text.slice(region.start, region.end);+ if (region.kind === 'style') {+ offsets.push(+ ...cssFlagOffsets(body).map(offset => offset + region.start),+ );+ } else if (region.kind === 'script') {+ offsets.push(+ ...scriptFlagOffsets(body, `${fileName}.ts`, ts.ScriptKind.TS).map(+ offset => offset + region.start,+ ),+ );+ } else if (region.kind === 'style-attribute') {+ offsets.push(+ ...styleAttributeFlagOffsets(body).map(offset => offset + region.start),+ );+ }+ // `comment` is prose, and ordinary text is not yielded at all.}return offsets;}diff --git a/internal/vibe-tests/setup-test/setup-important.test.mjs b/internal/vibe-tests/setup-test/setup-important.test.mjsindex 33f736021e..8a1fdfe3ad 100644--- a/internal/vibe-tests/setup-test/setup-important.test.mjs+++ b/internal/vibe-tests/setup-test/setup-important.test.mjs@@ -137,7 +137,10 @@ describe('!important in scripts', () => {// The parser sees two literal fragments, neither of which carries a whole// declaration; the flag is only visible once they are read as one value.expect(- lines('App.tsx', 'const sheet = `.host { color: ${token} !important; }`;'),+ lines(+ 'App.tsx',+ 'const sheet = `.host { color: ${token} !important; }`;',+ ),).toEqual([1]);});});@@ -186,7 +189,8 @@ describe('the extensions the routing table claims', () => {{file: 'Region.jsx',comment: '// The guidance says never to reach for !important.',- applied: 'export const Badge = () => <b style={{color: "red !important"}} />;',+ applied:+ 'export const Badge = () => <b style={{color: "red !important"}} />;',},{file: 'theme.mjs',@@ -208,10 +212,13 @@ describe('the extensions the routing table claims', () => {comment: '<!-- reviewers reject !important -->',applied: '<style>.host { color: red !important; }</style>',},- ])('reads a comment and an override apart in $file', ({file, comment, applied}) => {- expect(lines(file, comment)).toEqual([]);- expect(lines(file, `${comment}\n${applied}`)).toEqual([2]);- });+ ])(+ 'reads a comment and an override apart in $file',+ ({file, comment, applied}) => {+ expect(lines(file, comment)).toEqual([]);+ expect(lines(file, `${comment}\n${applied}`)).toEqual([2]);+ },+ );});/**@@ -238,7 +245,10 @@ describe('mutations of the real false-positive fixture', () => {extra: 'root.style.setProperty("color", "red", "important");\n',},])('still catches $name', ({extra}) => {- const found = lines('AstryxRegion.tsx', `${GUEST_CONTAINED_COMMENT}${extra}`);+ const found = lines(+ 'AstryxRegion.tsx',+ `${GUEST_CONTAINED_COMMENT}${extra}`,+ );expect(found).toHaveLength(1);// The finding is on the added code, never on the comment above it.expect(found[0]).toBeGreaterThan(@@ -263,3 +273,637 @@ describe('mutations of the real false-positive fixture', () => {expect(lines('AstryxRegion.tsx', source)).toEqual(at);});});++/**+ * Comment delimiters that are not a comment.+ *+ * `<!--` opens a comment only where markup TEXT can appear. Inside `<script>`+ * and `<style>`, and inside a tag's attribute values, those four characters are+ * ordinary content. Blanking them wherever they occurred was not a false+ * positive but a way past this check: a script could carry an override inside a+ * comment-shaped string, have the scan agree not to look at it, and then apply+ * it. Two things made that work, and both are closed here — the markup walk+ * (`setup-markup.mjs`) and the declaration match, which no longer requires the+ * property to sit at the start of the text.+ */+describe('!important hidden behind comment delimiters', () => {+ const CLOAK = [+ '<div id="root"></div>',+ '<script>',+ " const cloak = '<!-- color: red !important -->';",+ ' document.body.style.cssText = cloak.slice(4, -3).trim();',+ '</script>',+ '',+ ].join('\n');++ it('catches a comment-shaped string a script reconstructs and applies', () => {+ expect(lines('index.html', CLOAK)).toEqual([3]);+ });++ it.each([+ {+ name: 'a template literal',+ source: [+ '<script>',+ ' const parts = [`<!-- color: red !important -->`];',+ ' el.style.cssText = parts[0].slice(4, -3);',+ '</script>',+ '',+ ].join('\n'),+ },+ {+ name: 'a style attribute on the same tag',+ source:+ '<div data-note="<!-- color: red !important -->" style="color: red !important"></div>\n',+ },+ {+ name: 'a style block',+ source:+ '<style>\n <!-- .host { color: red !important; } -->\n</style>\n',+ },+ ])('catches it in $name', ({source}) => {+ expect(lines('index.html', source).length).toBeGreaterThan(0);+ });++ it('catches the same cloak in a plain script file', () => {+ // The declaration anchor, not the markup walk, is what covers this one.+ expect(+ lines(+ 'boot.ts',+ "const cloak = '<!-- color: red !important -->';\nel.style.cssText = cloak.slice(4, -3);\n",+ ),+ ).toEqual([1]);+ });++ // Controls: a REAL markup comment is still prose, and still exempt.+ it.each([+ {+ name: 'a comment that names the flag',+ source:+ '<!-- color: red !important is banned here -->\n<div id="root"></div>\n',+ },+ {+ name: 'a comment that wraps a script applying it',+ source: [+ '<!--',+ '<script>',+ " el.style.cssText = 'color: red !important';",+ '</script>',+ '-->',+ '',+ ].join('\n'),+ },+ {+ name: 'a comment that wraps a style block',+ source: '<!--\n<style>.host { color: red !important; }</style>\n-->\n',+ },+ ])('stays silent for $name', ({source}) => {+ expect(lines('index.html', source)).toEqual([]);+ });++ it('reads a real comment and a cloaked override apart', () => {+ const source = [+ '<!-- color: red !important is banned here -->',+ '<script>',+ " el.style.cssText = '<!-- color: red !important -->'.slice(4, -3);",+ '</script>',+ '',+ ].join('\n');++ expect(lines('index.html', source)).toEqual([3]);+ });+});++/**+ * Which `style=` is a style attribute.+ *+ * The tag is tokenized rather than pattern-matched, because a pattern gets both+ * halves wrong: it misses an UNQUOTED value (valid HTML, and a real override+ * going unseen), and it matches any attribute whose name merely ends in+ * `style`, reporting findings against markup the browser never applies as CSS.+ */+describe('!important in a style attribute', () => {+ it.each([+ {+ name: 'an unquoted value',+ source: '<div style=color:red!important></div>\n',+ },+ {+ name: 'an unquoted value followed by another attribute',+ source: '<div style=color:red!important id=host></div>\n',+ },+ {+ name: 'a single-quoted value',+ source: "<div style='color: red !important'></div>\n",+ },+ {+ name: 'a value with spaces around the equals sign',+ source: '<div style = "color: red !important"></div>\n',+ },+ {+ name: 'an attribute after a bare (valueless) one',+ source: '<div hidden style="color: red !important"></div>\n',+ },+ {+ name: 'a value on a self-closing tag',+ source: '<img style="color: red !important" />\n',+ },+ {+ name: 'an uppercase attribute name',+ source: '<div STYLE="color: red !important"></div>\n',+ },+ ])('catches $name', ({source}) => {+ expect(lines('index.html', source)).toEqual([1]);+ });++ it.each([+ {+ name: 'data-style',+ source: '<div data-style="color: red !important"></div>\n',+ },+ {+ name: 'my-style',+ source: '<div my-style="color: red !important"></div>\n',+ },+ {+ name: 'stylesheet',+ source: '<div stylesheet="color: red !important"></div>\n',+ },+ {+ name: 'a style= written in text content',+ source: '<p>write style="color: red !important" to override</p>\n',+ },+ {+ name: 'a style= inside another attribute value',+ source: '<div title=\'style="color: red !important"\'></div>\n',+ },+ ])('does not treat $name as a style attribute', ({source}) => {+ expect(lines('index.html', source)).toEqual([]);+ });++ it('reads a quoted value whole, so a > inside it does not end the tag', () => {+ const source = '<div title="a > b" style="color: red !important"></div>\n';++ expect(lines('index.html', source)).toEqual([1]);+ });++ it('finds the override on its own line in a multi-line tag', () => {+ const source = [+ '<div',+ ' id="host"',+ ' style="color: red !important"',+ '></div>',+ '',+ ].join('\n');++ expect(lines('index.html', source)).toEqual([3]);+ });+});++/**+ * Prose that spells a declaration, against code that applies one.+ *+ * Characters spelling `color: red !important` are not an override — guidance+ * telling an executor not to write one spells it too, and failing a run for+ * that is the exact fault #5856 fixed. A bare declaration therefore counts only+ * where something APPLIES it; a whole braced rule is a stylesheet on its face+ * and counts wherever it is written.+ */+describe('a declaration in prose vs a declaration that is applied', () => {+ it.each([+ {+ name: 'a guidance constant naming the flag',+ source:+ "export const RULE = 'Never write color: red !important in host code';\n",+ },+ {+ name: 'the same guidance in double quotes',+ source:+ 'export const RULE = "reviewers reject color: red !important overrides";\n',+ },+ {+ name: 'a JSDoc block naming the flag',+ source:+ '/** Never write color: red !important. */\nexport const a = 1;\n',+ },+ {+ name: 'a message bound to a name no style code reads',+ source:+ "const RULE = 'color: red !important is banned';\nel.style.cssText = approvedStyles;\n",+ },+ {+ name: 'a declaration in a thrown error message',+ source:+ "throw new Error('do not set color: red !important on the host');\n",+ },+ ])('stays silent for $name', ({source}) => {+ expect(lines('guidance.ts', source)).toEqual([]);+ });++ it.each([+ {+ name: 'assigned straight to cssText',+ source: "el.style.cssText = 'color: red !important';\n",+ at: [1],+ },+ {+ name: 'reassembled out of a cloaked string',+ source:+ "const cloak = '<!-- color: red !important -->';\nel.style.cssText = cloak.slice(4, -3);\n",+ at: [1],+ },+ {+ name: 'reassembled through setAttribute',+ source:+ "const cloak = 'xx color: red !important';\nel.setAttribute('style', cloak.slice(3));\n",+ at: [1],+ },+ {+ name: 'reassembled through insertRule',+ source:+ "const cloak = 'xx .host { color: red !important; }';\nsheet.insertRule(cloak.slice(3));\n",+ at: [1],+ },+ {+ name: 'a template applied to cssText',+ source: 'const t = `color: ${v} !important`;\nel.style.cssText = t;\n',+ at: [1],+ },+ {+ name: 'a whole rule, which is a stylesheet on its face',+ source: 'const sheet = `.host { color: red !important; }`;\n',+ at: [1],+ },+ {+ name: 'a declaration handed to setProperty',+ source: "el.style.setProperty('color', 'red !important');\n",+ at: [1],+ },+ ])('catches an override $name', ({source, at}) => {+ expect(lines('boot.ts', source)).toEqual(at);+ });++ it('catches the applied override and not the prose beside it', () => {+ const source = [+ "export const RULE = 'Never write color: red !important in host code';",+ "const cloak = '<!-- color: red !important -->';",+ 'el.style.cssText = cloak.slice(4, -3);',+ '',+ ].join('\n');++ expect(lines('boot.ts', source)).toEqual([2]);+ });+});++/**+ * The same rule for template literals.+ *+ * A template is a string like any other: backticks around guidance do not make+ * it CSS. The sink/binding evidence a plain literal needs applies here too, and+ * a template carrying a whole braced rule is still a stylesheet on its face.+ */+describe('a declaration-shaped template in prose vs applied', () => {+ it.each([+ {+ name: 'a guidance constant in backticks',+ source:+ 'export const RULE = `Never write color: red !important in host code`;\n',+ },+ {+ name: 'guidance bound to a name no style code reads',+ source:+ 'const RULE = `color: red !important is banned`;\nel.style.cssText = approvedStyles;\n',+ },+ {+ name: 'guidance in a thrown error',+ source: 'throw new Error(`do not set color: red !important`);\n',+ },+ ])('stays silent for $name', ({source}) => {+ expect(lines('guidance.ts', source)).toEqual([]);+ });++ it.each([+ {+ name: 'assigned to cssText through a binding',+ source: 'const t = `color: red !important`;\nel.style.cssText = t;\n',+ at: [1],+ },+ {+ name: 'written inline at cssText, across an interpolation',+ source: 'el.style.cssText = `color: ${value} !important`;\n',+ at: [1],+ },+ {+ name: 'a cloaked template reassembled into cssText',+ source:+ 'const cloak = `<!-- color: red !important -->`;\nel.style.cssText = cloak.slice(4, -3);\n',+ at: [1],+ },+ {+ name: 'a cloaked template handed to insertRule',+ source:+ 'const cloak = `xx .host { color: red !important; }`;\nsheet.insertRule(cloak.slice(3));\n',+ at: [1],+ },+ {+ name: 'a cloaked template handed to setAttribute',+ source:+ "const cloak = `xx color: red !important`;\nel.setAttribute('style', cloak.slice(3));\n",+ at: [1],+ },+ {+ name: 'a whole rule, which is a stylesheet on its face',+ source: 'const sheet = `.host { color: red !important; }`;\n',+ at: [1],+ },+ {+ name: 'a value in a style object',+ source: 'const patch = {color: `red !important`};\n',+ at: [1],+ },+ ])('catches a template $name', ({source, at}) => {+ expect(lines('boot.ts', source)).toEqual(at);+ });++ it('catches the applied template and not the guidance beside it', () => {+ const source = [+ 'export const RULE = `Never write color: red !important in host code`;',+ 'const applied = `color: red !important`;',+ 'el.style.cssText = applied;',+ '',+ ].join('\n');++ expect(lines('boot.ts', source)).toEqual([2]);+ });+});++/**+ * Reachability is keyed on the BINDING, not the name.+ *+ * Two functions may each declare `value`. Only the one whose `value` a CSS sink+ * reads applies anything; reporting the other is the prose false positive all+ * over again, and a name-keyed check cannot tell them apart.+ */+describe('sink reachability resolves bindings, not names', () => {+ it.each([+ {+ name: 'sibling functions that each declare the name',+ source: [+ 'function docs() {',+ ' const value = `Never write color: red !important`;',+ ' return value;',+ '}',+ 'function apply() {',+ ' const value = approvedStyles;',+ ' el.style.cssText = value;',+ '}',+ '',+ ].join('\n'),+ },+ {+ name: 'sibling blocks that each declare the name',+ source: [+ '{',+ ' const v = `color: red !important is banned`;',+ '}',+ '{',+ ' const v = approvedStyles;',+ ' el.style.cssText = v;',+ '}',+ '',+ ].join('\n'),+ },+ {+ name: 'module-scope prose shadowed by a function-scope sink',+ source: [+ 'const v = `never write color: red !important`;',+ 'function apply() {',+ ' const v = approvedStyles;',+ ' el.style.cssText = v;',+ '}',+ '',+ ].join('\n'),+ },+ {+ name: 'a parameter shadowing the prose binding',+ source: [+ 'const v = `never write color: red !important`;',+ 'function apply(v) {',+ ' el.style.cssText = v;',+ '}',+ '',+ ].join('\n'),+ },+ ])(+ 'stays silent when the sink reads a different binding: $name',+ ({source}) => {+ expect(lines('guidance.ts', source)).toEqual([]);+ },+ );++ it.each([+ {+ name: 'declared and applied in the same function',+ source: [+ 'function apply() {',+ ' const value = `color: red !important`;',+ ' el.style.cssText = value;',+ '}',+ '',+ ].join('\n'),+ at: [2],+ },+ {+ name: 'declared in a function and applied from a nested block',+ source: [+ 'function apply() {',+ ' const value = `color: red !important`;',+ ' if (enabled) {',+ ' el.style.cssText = value;',+ ' }',+ '}',+ '',+ ].join('\n'),+ at: [2],+ },+ {+ name: 'a var hoisted out of the block it was written in',+ source: [+ 'function apply() {',+ ' if (enabled) {',+ ' var value = `color: red !important`;',+ ' }',+ ' el.style.cssText = value;',+ '}',+ '',+ ].join('\n'),+ at: [3],+ },+ {+ name: 'assigned to an already-declared binding',+ source: [+ 'let value;',+ 'value = `color: red !important`;',+ 'el.style.cssText = value;',+ '',+ ].join('\n'),+ at: [2],+ },+ {+ name: 'an inner shadow that does not hide the applied outer binding',+ source: [+ 'const v = `color: red !important`;',+ 'el.style.cssText = v;',+ 'function unrelated() {',+ ' const v = somethingElse;',+ ' return v;',+ '}',+ '',+ ].join('\n'),+ at: [1],+ },+ ])('still catches an override $name', ({source, at}) => {+ expect(lines('boot.ts', source)).toEqual(at);+ });++ it('reports only the applied binding when both names are the same', () => {+ const source = [+ 'const v = `never write color: red !important`;',+ 'function apply() {',+ ' const v = `color: red !important`;',+ ' el.style.cssText = v;',+ '}',+ '',+ ].join('\n');++ expect(lines('boot.ts', source)).toEqual([3]);+ });+});++/**+ * Parser precision in the sink analysis: which member accesses are sinks, which+ * references are uses of the value, and what one redeclared binding means.+ */+describe('sink analysis reads member access precisely', () => {+ it.each([+ {+ name: 'a computed sink property',+ source:+ "const cloak = 'xx color: red !important';\nel.style['cssText'] = cloak.slice(3);\n",+ },+ {+ name: 'a computed sink written directly',+ source: "el.style['cssText'] = 'color: red !important';\n",+ },+ {+ name: 'a value kept in play by trim()',+ source:+ "const cloak = ' color: red !important ';\nel.style.cssText = cloak.trim();\n",+ },+ {+ name: 'a value kept in play by replace()',+ source:+ "const cloak = 'XXcolor: red !important';\nel.style.cssText = cloak.replace('XX', '');\n",+ },+ ])('catches $name', ({source}) => {+ expect(lines('boot.ts', source)).toEqual([1]);+ });++ it.each([+ {+ name: 'a length read that only decides a branch',+ source:+ "const guidance = 'never write color: red !important';\nel.style.cssText = guidance.length > 0 ? approved : fallback;\n",+ },+ {+ name: 'a property read stored before an unrelated sink',+ source:+ "const guidance = 'never write color: red !important';\nconst size = guidance.length;\nel.style.cssText = approved;\n",+ },+ {+ name: 'a same-named member of an unrelated object',+ source:+ "const guidance = 'never write color: red !important';\nel.style.cssText = config.guidance;\n",+ },+ ])('stays silent for $name', ({source}) => {+ expect(lines('guidance.ts', source)).toEqual([]);+ });++ it('treats a redeclared var as one binding, reporting each CSS write', () => {+ // Which write reaches the sink is a question of flow, so the binding is+ // reported rather than a guessed order — see the file header.+ const source = [+ 'function apply() {',+ " var value = 'color: red !important';",+ " var value = 'color: blue !important';",+ ' el.style.cssText = value;',+ '}',+ '',+ ].join('\n');++ expect(lines('boot.ts', source)).toEqual([2, 3]);+ });++ it('still separates a redeclared var from an unrelated same name', () => {+ const source = [+ 'function docs() {',+ " var value = 'never write color: red !important';",+ " var value = 'nor color: blue !important';",+ ' return value;',+ '}',+ 'function apply() {',+ ' el.style.cssText = approved;',+ '}',+ '',+ ].join('\n');++ expect(lines('guidance.ts', source)).toEqual([]);+ });+});++/**+ * Raw-text elements are `script` and `style` EXACTLY.+ *+ * `<style-note>` is an ordinary custom element whose content is markup. A+ * prefix test reads it as a raw-text opener and then hunts for a `</style>`+ * that never arrives, so the rest of the document is swallowed as one element+ * body — every attribute, comment and override after it goes unexamined.+ */+describe('custom elements whose names begin with a raw-text tag', () => {+ it.each([+ {name: 'style-note', markup: '<style-note>see the docs</style-note>'},+ {name: 'script-note', markup: '<script-note>see the docs</script-note>'},+ {name: 'styled-box', markup: '<styled-box>content</styled-box>'},+ ])('does not let <$name> swallow the rest of the document', ({markup}) => {+ const source = `${markup}\n<div style="color: red !important"></div>\n`;++ expect(lines('index.html', source)).toEqual([2]);+ });++ it('keeps finding real comments after a custom element', () => {+ const source = [+ '<style-note>see the docs</style-note>',+ '<!-- color: red !important is banned -->',+ '<div style="color: red !important"></div>',+ '',+ ].join('\n');++ // The comment is prose; only the real attribute is an override.+ expect(lines('index.html', source)).toEqual([3]);+ });++ it('still reads a real style or script element', () => {+ expect(+ lines(+ 'index.html',+ '<style>\n.host { color: red !important; }\n</style>\n',+ ),+ ).toEqual([2]);+ expect(+ lines(+ 'index.html',+ '<style type="text/css">.host { color: red !important; }</style>\n',+ ),+ ).toEqual([1]);+ });+});diff --git a/internal/vibe-tests/setup-test/setup-integrity.mjs b/internal/vibe-tests/setup-test/setup-integrity.mjsindex 2ea9038ac2..4b1a6c9b03 100644--- a/internal/vibe-tests/setup-test/setup-integrity.mjs+++ b/internal/vibe-tests/setup-test/setup-integrity.mjs@@ -33,6 +33,15 @@* lexical — see `setup-important.mjs`. The flag is found by parsing, so a* comment, a JSDoc block, or a prose string that merely names `!important`* is silent, while a declaration that carries it fails wherever it is written.+ *+ * The pattern-matched hatches — `blanket-reset` and `dark-mode-disabled` — hold+ * the same line: every one of them is matched against the added line with its+ * COMMENTS blanked out, located by the parser that owns the file (see+ * `setup-comments.mjs`). A sentence naming `all: unset`, or a comment+ * explaining that the host's own `color-scheme` arm was deliberately left+ * alone, is prose and not a change to the host. Blanking preserves offsets, so+ * a real hatch written beside a comment is still found, and a file no parser+ * can read keeps every character subject to the scan.*/import * as crypto from 'node:crypto';@@ -41,6 +50,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {fileURLToPath} from 'node:url';import {importantDeclarationLines} from './setup-important.mjs';+import {commentSpans} from './setup-comments.mjs';export const WHOLESALE_REPLACEMENT_THRESHOLD = Object.freeze({minimumDeletedLines: 20,@@ -67,6 +77,11 @@ const HOST_SOURCE_EXTENSIONS = new Set([/*** The escape hatches found by matching the added line itself.*+ * Each is matched against the line with its comments blanked out — see+ * `setup-comments.mjs`. A pattern that reads a comment reports prose as a+ * change to the host, which is what `hardcoded-important` used to do before+ * #5856 made it syntactic.+ ** `hardcoded-important` is deliberately absent: it is found by parsing the* file rather than by matching a line, in `syntacticFindings`.*/@@ -558,6 +573,30 @@ function modeArmExemptions(appDir, relativePath, currentSource, removedLines) {return pairedModeArmSpans(currentSource);}+/**+ * The spans on each line that no escape hatch may read: the file's comments,+ * which are prose rather than a change to the host, plus its exempt paired mode+ * arms.+ *+ * A file this module cannot parse contributes no comment spans, so nothing is+ * exempted on a guess.+ */+function hatchMaskFor(appDir, relativePath, currentSource, removedLines) {+ const masked = lineSpans(+ currentSource,+ commentSpans(relativePath, currentSource),+ );+ for (const [line, spans] of modeArmExemptions(+ appDir,+ relativePath,+ currentSource,+ removedLines,+ )) {+ masked.set(line, [...(masked.get(line) ?? []), ...spans]);+ }+ return masked;+}+/** The line with its exempt spans blanked out, for escape-hatch matching. */function maskSpans(text, spans) {if (!spans || spans.length === 0) return text;@@ -681,8 +720,13 @@ function evidenceFor(relativePath, lines) {* numbers where a `!important` is an applied CSS declaration. Intersecting it* with the added lines keeps the rule unchanged — only what this change added* is judged — while the judgment itself is now syntactic.+ *+ * `maskedSpans` does the same job for the pattern-matched hatches: every one of+ * them reads the line with its comments blanked, so prose that names a hatch is+ * silent while the hatch itself is found wherever it is written — including on+ * the same line as the comment that discusses it.*/-function findingsFor(relativePath, lines, exemptSpans, importantLines) {+function findingsFor(relativePath, lines, maskedSpans, importantLines) {const findings = [];for (const added of lines) {if (importantLines?.has(added.line)) {@@ -693,11 +737,9 @@ function findingsFor(relativePath, lines, exemptSpans, importantLines) {message: HARDCODED_IMPORTANT.message,});}- const masked = maskSpans(added.text, exemptSpans?.get(added.line));+ const masked = maskSpans(added.text, maskedSpans?.get(added.line));for (const escapeHatch of ESCAPE_HATCHES) {- const subject =- escapeHatch.kind === 'dark-mode-disabled' ? masked : added.text;- if (escapeHatch.pattern.test(subject)) {+ if (escapeHatch.pattern.test(masked)) {findings.push({kind: escapeHatch.kind,path: relativePath,@@ -836,7 +878,7 @@ export function analyzeSetupIntegrity(appDir, attestedDiffSha256) {...findingsFor(file.path,addedLines,- modeArmExemptions(+ hatchMaskFor(resolvedAppDir,file.path,currentSource,@@ -871,7 +913,7 @@ export function analyzeSetupIntegrity(appDir, attestedDiffSha256) {addedLines,currentSource === null? undefined- : modeArmExemptions(resolvedAppDir, file.path, currentSource, []),+ : hatchMaskFor(resolvedAppDir, file.path, currentSource, []),currentSource === null? undefined: importantDeclarationLines(file.path, currentSource),diff --git a/internal/vibe-tests/setup-test/setup-integrity.test.mjs b/internal/vibe-tests/setup-test/setup-integrity.test.mjsindex ced7add1c0..a512bdfafa 100644--- a/internal/vibe-tests/setup-test/setup-integrity.test.mjs+++ b/internal/vibe-tests/setup-test/setup-integrity.test.mjs@@ -892,13 +892,13 @@ describe('setup integrity', () => {describe('substantive line delta', () => {it('sees no deletion when a wrapper only re-indents the tree', () => {- expect(substantiveLineDelta(establishedHostApp(), wrappedHostApp())).toEqual(- {- baselineLines: expect.any(Number),- deletedLines: 0,- deletedFraction: 0,- },- );+ expect(+ substantiveLineDelta(establishedHostApp(), wrappedHostApp()),+ ).toEqual({+ baselineLines: expect.any(Number),+ deletedLines: 0,+ deletedFraction: 0,+ });});it('sees every line deleted when the same content is minified onto one line', () => {@@ -926,7 +926,10 @@ describe('substantive line delta', () => {it('treats a line as unchanged when only its indentation moved', () => {expect(- substantiveLineDelta(' <Card className="divide-y">\n', ' <Card className="divide-y">\n'),+ substantiveLineDelta(+ ' <Card className="divide-y">\n',+ ' <Card className="divide-y">\n',+ ),).toEqual({baselineLines: 1, deletedLines: 0, deletedFraction: 0});});});@@ -1032,7 +1035,9 @@ describe('setup integrity — reformatting versus replacement', () => {// A guard that asked Git to ignore whitespace would see nothing at all// here, because `-w` equates `a b` with `ab`.- expect(numstatIgnoringWhitespace(directory, 'src/large.ts').deleted).toBe(0);+ expect(numstatIgnoringWhitespace(directory, 'src/large.ts').deleted).toBe(+ 0,+ );const result = analyzeSetupIntegrity(directory, digest);@@ -1046,7 +1051,11 @@ describe('setup integrity — reformatting versus replacement', () => {{length: WHOLESALE_REPLACEMENT_THRESHOLD.minimumDeletedLines + 4},(_, index) => `.host-row-${index} {\n color: CanvasText;\n}`,).join('\n');- write(directory, 'src/index.css', `:root {\n color-scheme: light dark;\n}\n${rules}\n`);+ write(+ directory,+ 'src/index.css',+ `:root {\n color-scheme: light dark;\n}\n${rules}\n`,+ );git(directory, ['add', 'src/index.css']);git(directory, ['commit', '-qm', 'establish host stylesheet']);addValidAstryxChange(directory);@@ -1153,6 +1162,84 @@ describe('setup integrity — hardcoded !important is syntactic', () => {expect(findings[0].line).toBe(GUEST_CONTAINED_REGION.split('\n').length);});+ it('fails a run for an override hidden behind comment delimiters', () => {+ // `<!--` opens a comment only in markup text, so this string is code: the+ // override it carries reaches the host, and the check must see it.+ const directory = repository();+ addValidAstryxChange(directory);+ write(+ directory,+ 'public/boot.html',+ [+ '<div id="root"></div>',+ '<script>',+ " const cloak = '<!-- color: red !important -->';",+ ' document.body.style.cssText = cloak.slice(4, -3).trim();',+ '</script>',+ '',+ ].join('\n'),+ );++ const findings = analyzeSetupIntegrity(+ directory,+ attest(directory),+ ).escapeHatches.filter(finding => finding.kind === 'hardcoded-important');++ expect(findings).toHaveLength(1);+ expect(findings[0].path).toBe('public/boot.html');+ expect(findings[0].line).toBe(3);+ });++ it('still accepts a real markup comment that names the flag', () => {+ const directory = repository();+ addValidAstryxChange(directory);+ write(+ directory,+ 'public/notes.html',+ '<!-- color: red !important is banned here -->\n<div id="root"></div>\n',+ );++ const result = analyzeSetupIntegrity(directory, attest(directory));++ expect(kinds(result)).not.toContain('hardcoded-important');+ expect(result.accepted).toBe(true);+ });++ it('fails a run for an unquoted style attribute override', () => {+ // Valid HTML, and the form a quoted-only pattern never saw.+ const directory = repository();+ addValidAstryxChange(directory);+ write(+ directory,+ 'public/boot.html',+ '<div id="root" style=color:red!important></div>\n',+ );++ const findings = analyzeSetupIntegrity(+ directory,+ attest(directory),+ ).escapeHatches.filter(finding => finding.kind === 'hardcoded-important');++ expect(findings).toHaveLength(1);+ expect(findings[0].line).toBe(1);+ });++ it('does not fail a run for a data-style attribute', () => {+ // The browser never applies this as CSS, so it is not an override.+ const directory = repository();+ addValidAstryxChange(directory);+ write(+ directory,+ 'public/notes.html',+ '<div data-style="color: red !important"></div>\n',+ );++ const result = analyzeSetupIntegrity(directory, attest(directory));++ expect(kinds(result)).not.toContain('hardcoded-important');+ expect(result.accepted).toBe(true);+ });+it('judges a modified tracked file by its added lines only', () => {const directory = repository();write(directory, 'src/legacy.css', '.legacy { color: red !important; }\n');@@ -1170,3 +1257,188 @@ describe('setup integrity — hardcoded !important is syntactic', () => {).not.toContain('hardcoded-important');});});++/**+ * `blanket-reset` and `dark-mode-disabled` at the sandbox level.+ *+ * These are the two hatches still found by matching a line, and both used to+ * match prose: guidance that names `all: unset`, or a comment recording that+ * the host's own light arm was deliberately left alone, failed the run for+ * saying the right thing. The line is now read with its comments blanked (see+ * `setup-comments.mjs`), so what remains judged is what the host actually+ * gained. The unit-level behavior lives in `setup-comments.test.mjs`.+ */+describe('setup integrity — pattern hatches do not read prose', () => {+ it.each([+ {+ name: 'a comment naming a blanket reset',+ file: 'src/AstryxRegion.tsx',+ source: [+ '/**',+ ' * Scope the design system to this region.',+ ' *',+ ' * TRADEOFF: do NOT flatten the host with `all: unset` to stop its',+ ' * cascade reaching in — that would take the host apart.',+ ' */',+ 'export function AstryxRegion({children}) {',+ ' return <div className="astryx-region">{children}</div>;',+ '}',+ '',+ ].join('\n'),+ kind: 'blanket-reset',+ },+ {+ name: 'a stylesheet comment naming a blanket reset',+ file: 'src/region.css',+ source: [+ '/* Deliberately narrow: `all: unset` here would strip the host too. */',+ '.astryx-region {',+ ' color: CanvasText;',+ '}',+ '',+ ].join('\n'),+ kind: 'blanket-reset',+ },+ {+ name: 'a comment recording that the host light arm was left alone',+ file: 'src/notes.ts',+ source: [+ '// The host declares `color-scheme: light` on its own root and we did',+ '// not touch it; setting `darkMode: false` would have been the easy',+ '// way out.',+ 'export const migrated = true;',+ '',+ ].join('\n'),+ kind: 'dark-mode-disabled',+ },+ {+ name: 'an HTML comment naming the meta tag',+ file: 'public/notes.html',+ source: [+ '<!doctype html>',+ '<!-- Not this: <meta name="color-scheme" content="light"> -->',+ '<div id="root"></div>',+ '',+ ].join('\n'),+ kind: 'dark-mode-disabled',+ },+ ])('does not fail a run for $name', ({file, source, kind}) => {+ const directory = repository();+ addValidAstryxChange(directory);+ write(directory, file, source);++ const result = analyzeSetupIntegrity(directory, attest(directory));++ expect(kinds(result)).not.toContain(kind);+ expect(result.accepted).toBe(true);+ });++ it.each([+ {+ name: 'a blanket reset',+ file: 'src/region.css',+ source: '.astryx-region {\n all: unset;\n}\n',+ kind: 'blanket-reset',+ },+ {+ name: 'a disabled dark mode',+ file: 'src/config.ts',+ source: 'export const config = {darkMode: false};\n',+ kind: 'dark-mode-disabled',+ },+ ])('still fails a run for $name', ({file, source, kind}) => {+ const directory = repository();+ addValidAstryxChange(directory);+ write(directory, file, source);++ const result = analyzeSetupIntegrity(directory, attest(directory));++ expect(kinds(result)).toContain(kind);+ expect(result.accepted).toBe(false);+ });++ it.each([+ {+ name: 'a blanket reset',+ file: 'src/region.css',+ source: '.astryx-region {\n all: unset; /* not prose */\n}\n',+ kind: 'blanket-reset',+ line: 2,+ },+ {+ name: 'a disabled dark mode',+ file: 'src/config.ts',+ source:+ '// The host owns this decision.\nexport const config = {darkMode: false}; // not prose\n',+ kind: 'dark-mode-disabled',+ line: 2,+ },+ ])(+ 'reports $name written beside the comment about it',+ ({file, source, kind, line}) => {+ const directory = repository();+ addValidAstryxChange(directory);+ write(directory, file, source);++ const findings = analyzeSetupIntegrity(+ directory,+ attest(directory),+ ).escapeHatches.filter(finding => finding.kind === kind);++ expect(findings).toHaveLength(1);+ expect(findings[0].path).toBe(file);+ expect(findings[0].line).toBe(line);+ },+ );++ it('fails a run for a hatch a script hides behind comment delimiters', () => {+ // `<!--` opens a comment only in markup text. A flat scan for the+ // delimiters would blank this string, and the reset it reconstructs would+ // reach the host unexamined.+ const directory = repository();+ addValidAstryxChange(directory);+ write(+ directory,+ 'public/boot.html',+ [+ '<div id="root"></div>',+ '<script>',+ " const cloak = '<!-- all: unset -->';",+ ' document.body.style.cssText = cloak.slice(4, -3).trim();',+ '</script>',+ '',+ ].join('\n'),+ );++ const findings = analyzeSetupIntegrity(+ directory,+ attest(directory),+ ).escapeHatches.filter(finding => finding.kind === 'blanket-reset');++ expect(findings).toHaveLength(1);+ expect(findings[0].path).toBe('public/boot.html');+ expect(findings[0].line).toBe(3);+ });++ it('still exempts a paired mode arm, which is not a comment', () => {+ const directory = repository();+ addValidAstryxChange(directory);+ write(+ directory,+ 'src/theme.css',+ [+ 'html[data-theme="light"] {',+ ' color-scheme: light;',+ '}',+ 'html[data-theme="dark"] {',+ ' color-scheme: dark;',+ '}',+ '',+ ].join('\n'),+ );++ const result = analyzeSetupIntegrity(directory, attest(directory));++ expect(kinds(result)).not.toContain('dark-mode-disabled');+ });+});diff --git a/internal/vibe-tests/setup-test/setup-markup.mjs b/internal/vibe-tests/setup-test/setup-markup.mjsnew file mode 100644index 0000000000..2f5868788a--- /dev/null+++ b/internal/vibe-tests/setup-test/setup-markup.mjs@@ -0,0 +1,171 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * One structural walk of a markup document, shared by every check that has to+ * ask "what kind of thing am I looking at here".+ *+ * `<!--` opens a comment only where markup TEXT can appear. Inside `<script>`+ * and `<style>` — raw-text elements whose content is JavaScript and CSS, not+ * markup — and inside a tag's own attribute values, the same four characters+ * are ordinary content. A check that scans for the delimiters instead of+ * walking the document blanks them anywhere they occur, and that is not a+ * false positive: it is a way past the check. A script can write+ * `const c = '<!-- color: red !important -->'`, have the scan agree not to look+ * at it, and then apply it with `style.cssText = c.slice(4, -3)`.+ *+ * Both `setup-comments.mjs` (which asks where the prose is) and+ * `setup-important.mjs` (which asks where the CSS is) need the same answer to+ * the same question, so they read the same regions from here rather than each+ * keeping a scanner that can drift out of agreement with the other.+ *+ * The walk is deliberately structural and nothing more: it says where each+ * region begins and ends, and leaves what counts as a finding inside one to the+ * caller and its own language's parser.+ */++/**+ * The raw-text element this `<` opens, or `null`.+ *+ * The name must match EXACTLY. `<style-note>` and `<script-note>` are ordinary+ * custom elements whose content is markup, but a prefix test reads them as+ * raw-text openers and then hunts for a `</style>` that never comes — so the+ * rest of the document is swallowed as one element body and every real+ * attribute, comment and override after it goes unexamined.+ */+function rawTextTag(text, start) {+ const match = /^<(script|style)(?=[\s/>])/i.exec(+ text.slice(start, start + 8),+ );+ return match ? match[1].toLowerCase() : null;+}++/**+ * Read one start or end tag, from its `<` to just past its `>`.+ *+ * The tag is TOKENIZED into attributes rather than pattern-matched, because+ * both halves of "is this a style attribute" are easy to get wrong:+ *+ * - the NAME must be exactly `style`. A regex looking for `style\s*=` also+ * matches `data-style=` and `my-style=`, and treating those as CSS reported+ * findings against an attribute the browser never applies as style;+ * - the VALUE may be double-quoted, single-quoted, or UNQUOTED+ * (`style=color:red!important`, valid HTML). A quoted-only pattern skipped+ * the unquoted form entirely, which is a real override going unseen.+ *+ * Tokenizing also fixes the boundary: a quoted value is consumed whole, so a+ * `>` inside one does not end the tag early, and a `<!--` inside one is never+ * read as a comment opener.+ *+ * Returns the tag's end offset and the body span of every `style` attribute+ * it carries.+ */+function readTag(text, start) {+ const attributes = [];+ let cursor = start + 1;++ // The tag name, and for an end tag the `/` before it.+ while (cursor < text.length && /[^\s/>]/.test(text[cursor])) cursor += 1;++ while (cursor < text.length) {+ while (cursor < text.length && /\s/.test(text[cursor])) cursor += 1;+ if (cursor >= text.length) break;+ if (text[cursor] === '>') {+ cursor += 1;+ break;+ }+ if (text[cursor] === '/') {+ cursor += 1;+ continue;+ }++ const nameStart = cursor;+ while (cursor < text.length && /[^\s=/>]/.test(text[cursor])) cursor += 1;+ const name = text.slice(nameStart, cursor).toLowerCase();+ if (cursor === nameStart) {+ // Not a name character and not a delimiter: step over it rather than+ // spinning forever on malformed markup.+ cursor += 1;+ continue;+ }++ while (cursor < text.length && /\s/.test(text[cursor])) cursor += 1;+ if (text[cursor] !== '=') continue; // A bare attribute has no value.+ cursor += 1;+ while (cursor < text.length && /\s/.test(text[cursor])) cursor += 1;++ const quote = text[cursor];+ let valueStart;+ let valueEnd;+ if (quote === '"' || quote === "'") {+ valueStart = cursor + 1;+ cursor = valueStart;+ while (cursor < text.length && text[cursor] !== quote) cursor += 1;+ valueEnd = cursor;+ cursor = Math.min(cursor + 1, text.length);+ } else {+ valueStart = cursor;+ while (cursor < text.length && /[^\s>]/.test(text[cursor])) cursor += 1;+ valueEnd = cursor;+ }++ if (name === 'style') {+ attributes.push({+ kind: 'style-attribute',+ start: valueStart,+ end: valueEnd,+ });+ }+ }++ return {end: cursor, attributes};+}++/**+ * The regions of a markup document, in source order.+ *+ * Each is `{kind, start, end}` over the ORIGINAL text, so a caller can map a+ * finding straight back to a line:+ *+ * - `comment` — a real `<!-- … -->`, spanning its delimiters. An unterminated+ * one runs to the end of the document, which is how a browser reads it.+ * - `style` / `script` — a raw-text element's BODY, to be handed to the parser+ * for that language. An unterminated one runs to the end of the document.+ * - `style-attribute` — the body of a `style` attribute, quoted or unquoted.+ * The name must be exactly `style`, so `data-style` is not one.+ *+ * Ordinary text is not yielded: it is neither prose to exempt nor code to+ * parse, and every caller so far treats it as plain content. A `style=` written+ * in text is therefore text, not an attribute.+ */+export function* markupRegions(text) {+ let index = 0;++ while (index < text.length) {+ const next = text.indexOf('<', index);+ if (next === -1) return;++ if (text.startsWith('<!--', next)) {+ const close = text.indexOf('-->', next + 4);+ const end = close === -1 ? text.length : close + 3;+ yield {kind: 'comment', start: next, end};+ index = end;+ continue;+ }++ const rawText = rawTextTag(text, next);+ const tag = readTag(text, next);+ yield* tag.attributes;++ if (rawText) {+ const closing = new RegExp(`</${rawText}\\s*>`, 'i').exec(+ text.slice(tag.end),+ );+ const bodyEnd = closing ? tag.end + closing.index : text.length;+ yield {kind: rawText, start: tag.end, end: bodyEnd};+ index = closing ? bodyEnd + closing[0].length : text.length;+ continue;+ }++ index = tag.end;+ }+}diff --git a/packages/cli/README.md b/packages/cli/README.mdindex e2a1a1fb3f..3dbb73ef3f 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -26,7 +26,7 @@ command to run:```bash$ astryx search button-Results for "button" (20):+Results for "button" (20 of 239):[component] ButtonButton triggers an action when clicked. Use it for form submissions…@@ -52,7 +52,7 @@ Options:- `--type <component|hook|doc|template>`: restrict to a single domain- `--limit <n>`: cap the number of results (default 20)- `--detail`: include the import path and the match reason/score-- `--json`: typed `{ type: 'search', data: { query, results } }` envelope+- `--json`: typed `{ type: 'search', data: { query, matchCount, results } }` envelope — `matchCount` is how many candidates matched in total, `results` the slice `--limit` allowed## Commands@@ -385,54 +385,54 @@ Every response has a `type` discriminant. The full set is below (generated from<!-- BEGIN GENERATED: response-types -->-| Type | What `data` carries |-| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |-| `init.remove` | Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when --remove-agents is set. |-| `component.list` | The component catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of names+package, brief entries, or a full ComponentDoc per entry. |-| `component.detail` | One component's authored ComponentDoc plus ownership metadata (owner package, import specifier, and whether source is available). |-| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). |-| `component.detail.source` | One component's source file, as {component, source}. |-| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |-| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |-| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order. |-| `docs.detail` | One topic's full ReferenceDoc, with token-ref blocks inlined. |-| `docs.detail.section` | A single ReferenceSection of a topic: the first whose title contains the section query. |-| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |-| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |-| `discover.list` | The configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |-| `discover.detail` | A single external package entry, for an @scope/name query. |-| `discover.detail.doc` | The validated ComponentDoc for one external component: an @scope/name/Component query, or a free-text term resolving to exactly one component. |-| `discover.search` | The echoed query plus the matching {package, component} pairs, when a free-text term matches several components. |-| `search` | The echoed query plus a ranked SearchResultEntry[] (domain, name, score, reason, description, follow-up command, and import path where relevant). |-| `build.help` | A marker (`playbook: true`) that the renderer expands into the how-to-build-a-page workflow; emitted when no query is given. |-| `build.kit` | The grouped composition kit: echoed query, hasResults/matchCount/directMatch fields, the closest page templates, drop-in block patterns, idea-specific components/hooks, and the always-on frame + foundation component-name arrays. |-| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. |-| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note. |-| `template.list` | Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags. |-| `template.show` | The resolved template's raw source plus its description, kind, and the component names it composes. |-| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |-| `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |-| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |-| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |-| `hook.detail` | One hook's full authored HookDoc. |-| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |-| `theme.build` | A theme build receipt: name, token- and component-override counts, output size, the written outputs {css, js, dts, and variantsDts when applicable}, and any validation warnings. |-| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |-| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |-| `theme.list` | Every bundled theme as a ThemeListEntry[]: each with slug, displayName, description, and a maintained flag. |-| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |-| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |-| `theme.targets` | The whole themeable surface: the echoed filter, the component count, and one entry per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |-| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |-| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |-| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |-| `manifest` | The self-describing CLI capability manifest: name, version, apiVersion, global options, the command tree (args, options, json flag, response types, examples), the jsonSupported allowlist, and the flat responseTypes index. |-| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and a fix when not passing) plus a `summary` of counts per status. |-| `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |-| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |-| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |-| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |+| Type | What `data` carries |+| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |+| `init.remove` | Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when --remove-agents is set. |+| `component.list` | The component catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of names+package, brief entries, or a full ComponentDoc per entry. |+| `component.detail` | One component's authored ComponentDoc plus ownership metadata (owner package, import specifier, and whether source is available). |+| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). |+| `component.detail.source` | One component's source file, as {component, source}. |+| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |+| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |+| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order. |+| `docs.detail` | One topic's full ReferenceDoc, with token-ref blocks inlined. |+| `docs.detail.section` | A single ReferenceSection of a topic: the first whose title contains the section query. |+| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |+| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |+| `discover.list` | The configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |+| `discover.detail` | A single external package entry, for an @scope/name query. |+| `discover.detail.doc` | The validated ComponentDoc for one external component: an @scope/name/Component query, or a free-text term resolving to exactly one component. |+| `discover.search` | The echoed query plus the matching {package, component} pairs, when a free-text term matches several components. |+| `search` | The echoed query, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit` (domain, name, score, reason, description, follow-up command, and import path where relevant). |+| `build.help` | A marker (`playbook: true`) that the renderer expands into the how-to-build-a-page workflow; emitted when no query is given. |+| `build.kit` | The grouped composition kit: echoed query, hasResults/matchCount/directMatch fields (matchCount is the total matched, never a cap read back), the closest page templates, drop-in block patterns, idea-specific components/hooks, and the always-on frame + foundation component-name arrays. |+| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. |+| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note. |+| `template.list` | Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags. |+| `template.show` | The resolved template's raw source plus its description, kind, and the component names it composes. |+| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |+| `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |+| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |+| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |+| `hook.detail` | One hook's full authored HookDoc. |+| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |+| `theme.build` | A theme build receipt: name, token- and component-override counts, output size, the written outputs {css, js, dts, and variantsDts when applicable}, and any validation warnings. |+| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |+| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |+| `theme.list` | Every bundled theme as a ThemeListEntry[]: each with slug, displayName, description, and a maintained flag. |+| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |+| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |+| `theme.targets` | The whole themeable surface: the echoed filter, the component count, and one entry per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |+| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |+| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |+| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |+| `manifest` | The self-describing CLI capability manifest: name, version, apiVersion, global options, the command tree (args, options, json flag, response types, examples), the jsonSupported allowlist, and the flat responseTypes index. |+| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and a fix when not passing) plus a `summary` of counts per status. |+| `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |+| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |+| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |+| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |<!-- END GENERATED: response-types --><!-- Generated by scripts/generate-cli-readme.mjs from the response-types EnumDoc. Run `pnpm -F @astryxdesign/cli readme`. -->diff --git a/packages/cli/api/build/build.test.mjs b/packages/cli/api/build/build.test.mjsindex 74af20f91e..1e1b238628 100644--- a/packages/cli/api/build/build.test.mjs+++ b/packages/cli/api/build/build.test.mjs@@ -33,7 +33,7 @@ describe('build API', () => {expect(r.data.query).toBe('dashboard');expect(r.data.hasResults).toBe(true);const raw = await search('dashboard', {cwd: REPO, limit: 60});- expect(r.data.matchCount).toBe(raw.data.results.length);+ expect(r.data.matchCount).toBe(raw.data.matchCount);expect(r.data.frame).toContain('AppShell');expect(r.data.foundation).toContain('Button');expect(Array.isArray(r.data.pages)).toBe(true);@@ -107,6 +107,29 @@ describe('build API', () => {expect(r.data.blocks).toHaveLength(0);expect(r.data.domain).toHaveLength(0);});++ it('reports the total match count, not the search limit it was capped to', async () => {+ // The regression: matchCount was the length of the LIMITED result list, so+ // it reported the cap rather than what the query matched. A reader (and+ // the recorded run that quotes it) then reads "this idea matched 1 thing"+ // for a query that matched dozens, and cannot tell a thin kit caused by a+ // narrow query from one caused by the cap.+ const capped = await build('dashboard', {cwd: REPO, limit: 1});+ const full = await build('dashboard', {cwd: REPO, limit: 60});+ if (capped.type !== 'build.kit' || full.type !== 'build.kit') {+ throw new Error('expected build.kit');+ }+ expect(capped.data.matchCount).toBe(full.data.matchCount);+ expect(capped.data.matchCount).toBeGreaterThan(1);++ // The payload still respects the limit it was given — the truthful count+ // is not an excuse to return an unbounded kit.+ const surfaced =+ capped.data.pages.length ++ capped.data.blocks.length ++ capped.data.domain.length;+ expect(surfaced).toBeLessThanOrEqual(1);+ });});describe('build kit — coverage gates the pages group', () => {diff --git a/packages/cli/api/build/build.type.mjs b/packages/cli/api/build/build.type.mjsindex ed7854abf4..886c6350f2 100644--- a/packages/cli/api/build/build.type.mjs+++ b/packages/cli/api/build/build.type.mjs@@ -27,7 +27,7 @@* @property {object} data* @property {string} data.query* @property {boolean} data.hasResults False when search returned nothing (renderer shows "No matches").- * @property {number} data.matchCount Number of ranked search matches before kit score floors and caps.+ * @property {number} data.matchCount Total ranked search matches for the query — counted before the search `limit`, the kit's score floors, and its per-group caps, so it is never a cap read back.* @property {boolean} data.directMatch True when the top page template is a confident direct match.* @property {import('../search/search.type.mjs').SearchResultEntry[]} data.pages Closest page templates (≤3).* @property {import('../search/search.type.mjs').SearchResultEntry[]} data.blocks Drop-in block patterns covering parts of the idea (≤5).diff --git a/packages/cli/api/build/kit/kit.mjs b/packages/cli/api/build/kit/kit.mjsindex ee23d6da11..3b76534891 100644--- a/packages/cli/api/build/kit/kit.mjs+++ b/packages/cli/api/build/kit/kit.mjs@@ -86,6 +86,11 @@ export async function buildKit(query, options = {}) {await search(query, {cwd, type, limit}));const results = result.data.results;+ // The TOTAL number of matches, not the number that survived `limit`. The kit+ // below is deliberately small (≤3 pages, ≤5 blocks, ≤6 components) and+ // `results` is itself capped, so every other count here is a cap; this is the+ // one field that says how much the query actually matched.+ const matchCount = result.data.matchCount;/*** Did this result answer enough of the query to stand as a page?@@ -152,8 +157,8 @@ export async function buildKit(query, options = {}) {query: result.data.query,// Distinguishes "search found nothing" (renderer shows "No matches")// from a weak-but-non-empty result set (renderer still shows the kit).- hasResults: results.length > 0,- matchCount: results.length,+ hasResults: matchCount > 0,+ matchCount,directMatch,pages,blocks,diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex 845d08a520..e39263fc1a 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -495,15 +495,24 @@ export function checkPeerDeps(ctx) {}/**- * Check 8 — report the detected package manager, and FAIL when several- * lockfiles tie with nothing project-owned to break them. That tie is the one- * case where every command the CLI prints can be silently wrong, so it is the- * one case worth surfacing rather than guessing past.+ * Check 8 — report the detected package manager, and say so when the project's+ * own declaration disagrees with what is on disk.+ *+ * Two states are worth surfacing rather than guessing past, because in both the+ * commands the CLI prints can be silently wrong for the project:+ *+ * - FAIL: several lockfiles tie with nothing project-owned to break them.+ * - WARN: a `packageManager` field is declared and a lockfile it contradicts+ * sits beside it. Astryx follows the declaration, so its own output is right;+ * the warning is that a tool which follows the lockfile will install with+ * something else, and that used to be reported as a healthy setup.+ ** @param {DoctorContext} ctx* @returns {DoctorCheck}*/export function checkPackageManager(ctx) {- const {pm, ambiguous, dir, candidates} = explainPackageManager(ctx.cwd);+ const {pm, ambiguous, dir, candidates, declared, strayLockfiles} =+ explainPackageManager(ctx.cwd);if (ambiguous) {return {@@ -515,13 +524,29 @@ export function checkPackageManager(ctx) {};}+ if (declared && strayLockfiles.length > 0) {+ const files = strayLockfiles.map(lock => lock.file).join(' and ');+ const owners = [...new Set(strayLockfiles.map(lock => lock.pm))].join(+ ' and ',+ );+ return {+ id: 'package-manager',+ label: 'Package manager',+ status: 'warn',+ message: `This project declares \`packageManager: ${declared}\` in ${dir}/package.json, but ${files} also sits there. Astryx follows the declaration and prints ${pm} commands; anything that follows the lockfile instead will use ${owners}.`,+ fix: `Delete ${files} from ${dir} and reinstall with ${declared}, or change the \`packageManager\` field if ${owners} is what this project actually uses.`,+ };+ }+return {id: 'package-manager',label: 'Package manager',status: 'info',message:pm !== 'npx'- ? `Detected package manager: ${pm}.`+ ? declared+ ? `Detected package manager: ${pm} (declared in ${dir}/package.json).`+ : `Detected package manager: ${pm}.`: 'No lockfile detected — defaulting to npm/npx.',};}diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjsindex 3d455a4463..c76f5f57d3 100644--- a/packages/cli/api/doctor/doctor.test.mjs+++ b/packages/cli/api/doctor/doctor.test.mjs@@ -170,12 +170,41 @@ describe('checkPackageManager', () => {expect(c.fix).toContain('packageManager');});- it('is informational again once the project declares a packageManager', () => {+ it('is informational when the declaration and the lockfile agree', () => {+ const dir = mkProject({+ 'pnpm-lock.yaml': '',+ 'package.json': JSON.stringify({packageManager: '[email protected]'}),+ });+ const c = checkPackageManager({cwd: dir});+ expect(c.status).toBe('info');+ expect(c.message).toContain('pnpm');+ expect(c.fix).toBeUndefined();+ });++ it('warns when a lockfile contradicts the declared packageManager', () => {+ // The regression: a stray yarn.lock used to OUTRANK the declaration, and+ // doctor then reported the project as healthy while every command the CLI+ // printed named the wrong package manager. The declaration now decides, and+ // the contradiction is reported instead of hidden.+ const dir = mkProject({+ 'yarn.lock': '',+ 'package.json': JSON.stringify({packageManager: '[email protected]'}),+ });+ const c = checkPackageManager({cwd: dir});+ expect(c.status).toBe('warn');+ expect(c.message).toContain('yarn.lock');+ expect(c.message).toContain('pnpm');+ expect(c.fix).toContain('yarn.lock');+ });++ it('still warns when the declaration resolved a multi-lockfile tie', () => {const dir = mkProject({'pnpm-lock.yaml': '','yarn.lock': '','package.json': JSON.stringify({packageManager: '[email protected]'}),});- expect(checkPackageManager({cwd: dir}).status).toBe('info');+ const c = checkPackageManager({cwd: dir});+ expect(c.status).toBe('warn');+ expect(c.message).toContain('yarn.lock');});});diff --git a/packages/cli/api/search/search.doc.mjs b/packages/cli/api/search/search.doc.mjsindex 3cda28eae0..36755dcb58 100644--- a/packages/cli/api/search/search.doc.mjs+++ b/packages/cli/api/search/search.doc.mjs@@ -53,7 +53,7 @@ export const doc = {{type: 'search',description:- 'The query echoed back plus a ranked SearchResultEntry[] (domain, name, score, reason, description, follow-up command, and import path where relevant).',+ 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit` (domain, name, score, reason, description, follow-up command, and import path where relevant).',},],throws: [diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex 8e7a8ec236..0ece9a6d2b 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -772,7 +772,7 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {* @param {string} [options.cwd]* @param {'component'|'hook'|'doc'|'template'} [options.type] - Restrict to one domain.* @param {number} [options.limit] - Max results (default 20).- * @returns {Promise<{type: 'search', data: {query: string, results: Array<object>}}>}+ * @returns {Promise<{type: 'search', data: {query: string, matchCount: number, results: Array<object>}}>}*/export async function search(query, options = {}) {const {cwd = process.cwd(), type, limit = 20} = options;@@ -847,7 +847,19 @@ export async function search(query, options = {}) {a.name.localeCompare(b.name),);+ // `results` is bounded by `limit` so a caller (and the recorded run that+ // quotes it) never carries an unbounded payload. `matchCount` is the number+ // of matches that bound was applied TO — reporting `results.length` there+ // would report the cap back as if it were the answer, so a query matching+ // 57 things and one matching exactly 20 would be indistinguishable.const limited = scored.slice(0, limit);- return {type: 'search', data: {query: String(query).trim(), results: limited}};+ return {+ type: 'search',+ data: {+ query: String(query).trim(),+ matchCount: scored.length,+ results: limited,+ },+ };}diff --git a/packages/cli/api/search/search.test.mjs b/packages/cli/api/search/search.test.mjsindex e97cabc76e..c7eb82c52d 100644--- a/packages/cli/api/search/search.test.mjs+++ b/packages/cli/api/search/search.test.mjs@@ -70,6 +70,40 @@ describe('search leaf — envelope + ranking', () => {}, SLOW);});+describe('search leaf — matchCount is the total, not the cap', () => {+ it('reports every match while `results` stays bounded by the limit', async () => {+ // The regression: `matchCount` used to be `results.length`, so a query+ // matching 57 things reported 20 — the cap read back as the answer. Any+ // consumer counting matches (the recorded run, a caller paginating) then+ // could not tell a capped answer from an exactly-cap-sized one.+ const capped = await search('button', {cwd, limit: 2});+ expect(capped.data.results.length).toBe(2);+ expect(capped.data.matchCount).toBeGreaterThan(2);++ // Same query, no meaningful cap: the count is stable across limits, which+ // is what makes it a count of MATCHES rather than of what was returned.+ const full = await search('button', {cwd, limit: 500});+ expect(full.data.matchCount).toBe(capped.data.matchCount);+ expect(full.data.results.length).toBe(full.data.matchCount);+ }, SLOW);++ it('reports 0 for a no-match query', async () => {+ const r = await search('zzznomatch99', {cwd});+ expect(r.data.matchCount).toBe(0);+ }, SLOW);++ it('counts only the requested domain under --type', async () => {+ const all = await search('button', {cwd, limit: 500});+ const components = await search('button', {+ cwd,+ type: 'component',+ limit: 500,+ });+ expect(components.data.matchCount).toBe(components.data.results.length);+ expect(components.data.matchCount).toBeLessThanOrEqual(all.data.matchCount);+ }, SLOW);+});+describe('search leaf — --type filter', () => {it('restricts results to the requested domain', async () => {const r = await search('button', {cwd, type: 'component'});diff --git a/packages/cli/api/search/search.type.mjs b/packages/cli/api/search/search.type.mjsindex 4a07f5f056..840eb0f6da 100644--- a/packages/cli/api/search/search.type.mjs+++ b/packages/cli/api/search/search.type.mjs@@ -33,6 +33,7 @@* @property {'search'} type* @property {object} data* @property {string} data.query+ * @property {number} data.matchCount - How many candidates matched the query in total, before `limit` was applied. `results` is the bounded slice of that set, so `matchCount > results.length` means the answer was capped.* @property {SearchResultEntry[]} data.results*/diff --git a/packages/cli/authoring/debug/parse.mjs b/packages/cli/authoring/debug/parse.mjsindex 3b76a84b84..37666aae43 100644--- a/packages/cli/authoring/debug/parse.mjs+++ b/packages/cli/authoring/debug/parse.mjs@@ -88,6 +88,9 @@ const envSchema = zciName: z.string().nullable(),agent: z.string().nullable(),agentIdentity: z.string().nullable().default(null),+ // Nullable at the FIELD level so a v1 record's raw value still parses; the+ // event-level refinement then requires null from v2 onward. Nothing writes+ // a value here any more.agentSessionId: z.string().nullable().default(null),agentSessionIdHash: z.string().nullable().default(null),agentSessionIdSource: z.string().nullable().default(null),@@ -111,7 +114,11 @@ const projectSchema = zconst eventSchema = z.object({- schemaVersion: z.literal(1),+ // Both versions parse: a canary or linked checkout may have written v1+ // records before the raw session id was retired, and refusing to read them+ // back would make the privacy change look like data loss. What each version+ // is ALLOWED to contain differs — see the refinement below.+ schemaVersion: z.union([z.literal(1), z.literal(2)]),id: z.string(),startedAt: z.string(),endedAt: z.string(),@@ -132,7 +139,24 @@ const eventSchema = zproject: projectSchema,redacted: z.boolean(),})- .strict();+ .strict()+ .superRefine((event, ctx) => {+ // The privacy contract is a property of the DATA, not just of the code that+ // writes it. A v2 record carrying a raw session id did not come from this+ // CLI — it was hand-edited, replayed through the wrong pipeline, or written+ // by something claiming a version it does not honour. Accepting it would+ // let the identifier back in through the boundary that exists to keep it+ // out, and would let a v2 reader find a value the type says is never there.+ if (event.schemaVersion >= 2 && event.env.agentSessionId !== null) {+ ctx.addIssue({+ code: 'custom',+ path: ['env', 'agentSessionId'],+ message:+ 'must be null from schema version 2 onward — a recorded run does ' ++ 'not carry a raw agent session id; join on env.agentSessionIdHash',+ });+ }+ });/*** Compile-time drift-lock: the sealed schema must infer EXACTLY the public@@ -148,6 +172,10 @@ const eventSchema = z/*** Validate an unknown value as a recorded run, or throw a readable error.*+ * Validation is VERSION-AWARE: a v1 record may carry a raw `env.agentSessionId`+ * (that is what v1 meant), and a v2 record may not — see the refinement on the+ * schema above.+ ** @param {unknown} input* @param {string} [label]* @returns {DebugEvent}diff --git a/packages/cli/authoring/debug/parse.test.mjs b/packages/cli/authoring/debug/parse.test.mjsnew file mode 100644index 0000000000..88effd831b--- /dev/null+++ b/packages/cli/authoring/debug/parse.test.mjs@@ -0,0 +1,181 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Direct coverage for `parseDebugEvent`, the boundary a consumer reads+ * recorded runs back through.+ *+ * The recorder is not the only way a record reaches a reader: a warehouse row,+ * a hand-edited NDJSON line, or a replay from another pipeline all arrive here+ * as `unknown`. So the privacy contract has to hold at the PARSER too, not only+ * at the writer — a v2 record carrying a raw session id is rejected rather than+ * handed back typed, and a v1 record carrying one is still readable, because+ * that is what v1 meant.+ *+ * @position packages/cli/authoring/debug — validator coverage+ */++import {describe, expect, it} from 'vitest';+import {parseDebugEvent} from './parse.mjs';++const RAW_SESSION = 'session-alpha-bravo-charlie';++/**+ * A minimal valid record. Every test starts here and changes one thing, so a+ * failure names the field under test rather than a missing neighbour.+ *+ * @param {{schemaVersion?: number, env?: Record<string, unknown>}} [overrides]+ */+function makeEvent({schemaVersion = 2, env = {}} = {}) {+ return {+ schemaVersion,+ id: '00000000-0000-4000-8000-000000000000',+ startedAt: '2026-09-04T00:00:00.000Z',+ endedAt: '2026-09-04T00:00:01.000Z',+ durationMs: 1000,+ command: 'docs',+ commandPath: ['docs'],+ argv: ['docs'],+ args: {},+ options: {},+ optionSources: {},+ globalOptions: {},+ outcome: 'ok',+ exitCode: 0,+ signal: null,+ error: null,+ output: {+ jsonMode: false,+ envelopeTypes: [],+ handled: false,+ helpDisplayed: false,+ resultCount: null,+ emptyResult: null,+ resultKind: null,+ directMatch: null,+ stdout: '',+ stderr: '',+ stdoutBytes: 0,+ stderrBytes: 0,+ truncated: false,+ },+ env: {+ cliVersion: '9.9.9',+ nodeVersion: '22.0.0',+ platform: 'darwin',+ arch: 'arm64',+ ci: false,+ ciName: null,+ agent: null,+ agentIdentity: null,+ agentSessionId: null,+ agentSessionIdHash: null,+ agentSessionIdSource: null,+ invocationSource: 'unknown',+ oneOff: false,+ packageManager: 'pnpm',+ tty: false,+ locale: 'en-US',+ timezone: 'UTC',+ ...env,+ },+ project: {+ inProject: true,+ hasConfig: true,+ initialized: true,+ integrationCount: 0,+ },+ redacted: true,+ };+}++describe('parseDebugEvent — schema versions', () => {+ it('accepts a v2 record', () => {+ expect(parseDebugEvent(makeEvent()).schemaVersion).toBe(2);+ });++ it('accepts a v1 record', () => {+ expect(parseDebugEvent(makeEvent({schemaVersion: 1})).schemaVersion).toBe(+ 1,+ );+ });++ it('rejects a version it has never emitted', () => {+ expect(() => parseDebugEvent(makeEvent({schemaVersion: 3}))).toThrow(+ /schemaVersion/,+ );+ });+});++describe('parseDebugEvent — the raw session id, per version', () => {+ it('reads a v1 record that carries the raw id', () => {+ // v1 meant "the raw value is here". Refusing to read those back would make+ // the privacy change look like data loss to anyone holding older records.+ const parsed = parseDebugEvent(+ makeEvent({schemaVersion: 1, env: {agentSessionId: RAW_SESSION}}),+ );+ expect(parsed.env.agentSessionId).toBe(RAW_SESSION);+ });++ it('rejects a v2 record that carries the raw id', () => {+ // A v2 record with a raw id did not come from this CLI. Accepting it would+ // let the identifier back in through the boundary that exists to keep it+ // out, and hand a v2 reader a value its own type says is never there.+ expect(() =>+ parseDebugEvent(makeEvent({env: {agentSessionId: RAW_SESSION}})),+ ).toThrow(/agentSessionId/);+ });++ it('names the field and the remedy when it rejects one', () => {+ expect(() =>+ parseDebugEvent(makeEvent({env: {agentSessionId: RAW_SESSION}})),+ ).toThrow(/agentSessionIdHash/);+ });++ it('accepts a v2 record with the id explicitly null', () => {+ expect(parseDebugEvent(makeEvent()).env.agentSessionId).toBe(null);+ });++ it('accepts a v2 record that omits the field entirely', () => {+ const event = makeEvent();+ delete event.env.agentSessionId;+ expect(parseDebugEvent(event).env.agentSessionId).toBe(null);+ });++ it('still accepts the hash on a v2 record — it is the join key', () => {+ const hash = 'a'.repeat(64);+ const parsed = parseDebugEvent(+ makeEvent({+ env: {+ agentSessionIdHash: hash,+ agentSessionIdSource: 'ASTRYX_AGENT_SESSION_ID',+ },+ }),+ );+ expect(parsed.env.agentSessionIdHash).toBe(hash);+ expect(parsed.env.agentSessionIdSource).toBe('ASTRYX_AGENT_SESSION_ID');+ });+});++describe('parseDebugEvent — the boundary still rejects malformed input', () => {+ it('rejects a non-object', () => {+ expect(() => parseDebugEvent('nope')).toThrow(/debug event is invalid/);+ });++ it('rejects an unknown field, so a typo is not silently kept', () => {+ expect(() => parseDebugEvent({...makeEvent(), surprise: 1})).toThrow(+ /debug event is invalid/,+ );+ });++ it('rejects a negative result count', () => {+ const event = makeEvent();+ event.output.resultCount = -1;+ expect(() => parseDebugEvent(event)).toThrow(/resultCount/);+ });++ it('labels the error with the caller-supplied label', () => {+ expect(() => parseDebugEvent('nope', 'runs.ndjson line 4')).toThrow(+ /runs\.ndjson line 4 is invalid/,+ );+ });+});diff --git a/packages/cli/authoring/debug/type.ts b/packages/cli/authoring/debug/type.tsindex 765aaf9748..b468dc1457 100644--- a/packages/cli/authoring/debug/type.ts+++ b/packages/cli/authoring/debug/type.ts@@ -15,10 +15,15 @@*//**- * Version of the recorded shape. A literal on purpose: when this becomes- * `1 | 2`, code that switches on it stops compiling until it handles both.+ * Version of the recorded shape. A literal union on purpose: code that+ * switches on it stops compiling until it handles every version.+ *+ * - `1` — the original shape. `env.agentSessionId` carried the RAW session id.+ * - `2` — `env.agentSessionId` is always null; `env.agentSessionIdHash` is the+ * join key, and the environment snapshot is scrubbed like every other+ * recorded value.*/-export type DebugSchemaVersion = 1;+export type DebugSchemaVersion = 1 | 2;/*** How an invocation ended.@@ -71,7 +76,13 @@ export interface DebugEventOutput {handled: boolean;/** Whether the run ended by printing help rather than doing work. */helpDisplayed: boolean;- /** Number of matches before presentation-only grouping or caps. */+ /**+ * How many results the command MATCHED, counted before any `--limit`, score+ * floor, or presentation grouping was applied. A command that answers with a+ * bounded slice still reports the size of the set it sliced, so a capped+ * answer and an exactly-cap-sized one are distinguishable. Null when the+ * command has no result set.+ */resultCount: number | null;/** Whether the command's underlying match set was empty. */emptyResult: boolean | null;@@ -96,9 +107,23 @@ export interface DebugEventOutput {}/**- * Machine, runtime, and invocation-attribution facts. There is no hostname,- * username, or network identity. Agent session values come only from explicit- * environment signals supplied by the invoking tool.+ * Machine, runtime, and invocation-attribution facts.+ *+ * ## Privacy contract+ *+ * A recorded run may be forwarded anywhere the project's handler chooses, so+ * this snapshot is bounded by three rules:+ *+ * 1. **No identity.** No hostname, username, network identity, or raw agent+ * session id. Runs are joined on `agentSessionIdHash`, never on a value+ * that identifies who made them.+ * 2. **Attribution needs positive evidence.** Agent fields come only from+ * explicit public environment signals the invoking tool set, never from+ * guessing at the shell.+ * 3. **Free text is scrubbed.** Anything the environment supplied as text+ * (`agent`, `agentIdentity`) goes through the same content rules as argv.+ * The rest is derived from a fixed vocabulary this CLI controls and is kept+ * verbatim, which is what makes it worth recording.*/export interface DebugEventEnv {cliVersion: string | null;@@ -114,18 +139,22 @@ export interface DebugEventEnv {agent: string | null;/*** Coding-agent identity from `ASTRYX_AGENT_ID`, `AGENT`,- * `ASTRYX_AGENT_METADATA`, or a known public agent signal.+ * `ASTRYX_AGENT_METADATA`, or a known public agent signal. Scrubbed.*/agentIdentity: string | null;/**- * Opaque session identifier from `ASTRYX_AGENT_SESSION_ID`,- * `AGENT_SESSION_ID`, or `ASTRYX_AGENT_METADATA`. It is included verbatim so- * a handler can choose the raw value or the hash below.+ * ALWAYS NULL from schema version 2 onward — a raw session id is a stable+ * identifier for the person running the CLI, and nothing here needs one.+ * Join runs on `agentSessionIdHash` instead. Only schema-v1 records carry a+ * value, and the field is kept so those parse against one shape.*/agentSessionId: string | null;- /** SHA-256 of `agentSessionId`, for joins that do not need the raw value. */+ /**+ * SHA-256 of the session id supplied by the environment. The join key for+ * "these runs were one session", and the only form of it that is recorded.+ */agentSessionIdHash: string | null;- /** Public environment signal that supplied `agentSessionId`. */+ /** Which public environment signal supplied the session id. */agentSessionIdSource: string | null;/** Whether a human, AI agent, or automation invoked the CLI. */invocationSource: DebugInvocationSource;@@ -195,8 +224,11 @@ export interface DebugEvent {project: DebugEventProject;/**- * Whether the scrubbing pass ran. When false, values are verbatim — treat- * such a log as sensitive.+ * Whether the scrubbing pass ran over this record. True on every event a+ * handler receives: it is set only on the sealed copy, after argv, args,+ * options, captured output, the error, and the environment snapshot have all+ * been through it. When false, values are verbatim — treat such a log as+ * sensitive.*/redacted: boolean;}diff --git a/packages/cli/clients/cli/commands/debug-result-summary.test.mjs b/packages/cli/clients/cli/commands/debug-result-summary.test.mjsindex a3d3ca512c..b2d2255ef4 100644--- a/packages/cli/clients/cli/commands/debug-result-summary.test.mjs+++ b/packages/cli/clients/cli/commands/debug-result-summary.test.mjs@@ -60,7 +60,7 @@ describe('DebugEvent result summary', () => {);it(- 'records a single kind for a filtered search',+ 'records the match total, not the --limit cap, for a filtered search',async () => {const {run, event} = await runWithDebug(['--json',@@ -72,8 +72,13 @@ describe('DebugEvent result summary', () => {'2',]);const response = JSON.parse(run.stdout);+ // The regression: the recorded count was the length of the LIMITED list,+ // so every capped run filed "2" and no usage query could tell a query+ // that matched twice from one that matched fifty.+ expect(response.data.results).toHaveLength(2);+ expect(response.data.matchCount).toBeGreaterThan(2);expect(event.output).toMatchObject({- resultCount: response.data.results.length,+ resultCount: response.data.matchCount,emptyResult: false,resultKind: 'component',directMatch: null,diff --git a/packages/cli/clients/cli/commands/search.mjs b/packages/cli/clients/cli/commands/search.mjsindex 3236705e69..eab0c2c738 100644--- a/packages/cli/clients/cli/commands/search.mjs+++ b/packages/cli/clients/cli/commands/search.mjs@@ -78,12 +78,19 @@ export function registerSearch(program) {return;}- recordResultSummary(result.data.results);+ // The recorded count is the number of MATCHES, not the number that+ // survived `--limit`. Recording `results.length` would file the cap as+ // the answer, so "20 matches" and "200 matches, showing 20" would be the+ // same row in every usage query. The delivered payload stays bounded.+ recordResultSummary(result.data.results, {+ resultCount: result.data.matchCount,+ emptyResult: result.data.matchCount === 0,+ });if (json) return jsonOut(result);// ── Text output ──────────────────────────────────────────────const run = getCliInvocation();- const {query: q, results} = result.data;+ const {query: q, matchCount, results} = result.data;// No matches is a valid, successful outcome — clean message, exit 0.if (results.length === 0) {@@ -110,8 +117,15 @@ export function registerSearch(program) {]: ['name', 'domain', 'displayName', 'import', 'description', 'command'];+ // The heading mirrors the JSON: `matchCount` is what matched, and the+ // records below are the slice `--limit` allowed. Saying only "(20)" when+ // 57 matched reads as "that is all there is".emit(- section(`Results for "${q}" (${results.length})`),+ section(+ matchCount > results.length+ ? `Results for "${q}" (${results.length} of ${matchCount})`+ : `Results for "${q}" (${results.length})`,+ ),records(results, {fields, format: {command: formatCliCommand}}),);},diff --git a/packages/cli/clients/cli/commands/search.test.mjs b/packages/cli/clients/cli/commands/search.test.mjsindex a4731923f8..8811e02481 100644--- a/packages/cli/clients/cli/commands/search.test.mjs+++ b/packages/cli/clients/cli/commands/search.test.mjs@@ -180,15 +180,38 @@ describe('search CLI — exit codes + JSON contract', () => {expect(parsed.type).toBe('search');expect(parsed.data.query).toBe('button');expect(Array.isArray(parsed.data.results)).toBe(true);+ expect(parsed.data.matchCount).toBeGreaterThanOrEqual(+ parsed.data.results.length,+ );expect(parsed.data.results[0].name).toBe('Button');});+ it('says how many matched when --limit cut the list short', async () => {+ // The text view is a projection of the JSON, and the JSON now carries the+ // match total. A bare "(2)" heading over a capped list reads as "that is+ // all Astryx has", which is the conclusion `search` exists to prevent.+ const capped = await runCli(+ ['search', 'button', '--type', 'component', '--limit', '2'],+ REPO_ROOT,+ );+ expect(capped.status).toBe(0);+ expect(capped.stdout).toMatch(/^Results for "button" \(2 of \d+\)$/m);++ const uncapped = await runCli(+ ['search', 'button', '--type', 'component', '--limit', '500'],+ REPO_ROOT,+ );+ expect(uncapped.stdout).toMatch(/^Results for "button" \(\d+\)$/m);+ expect(uncapped.stdout).not.toMatch(/Results for "button" \(\d+ of/);+ });+it('emits a valid --json envelope with empty results for no match', async () => {const r = await runCli(['--json', 'search', 'zzqqxx_no_match'], REPO_ROOT);expect(r.status).toBe(0);const parsed = JSON.parse(r.stdout);expect(parsed.type).toBe('search');expect(parsed.data.results).toEqual([]);+ expect(parsed.data.matchCount).toBe(0);});it('renders each result as a greppable key: value record', async () => {diff --git a/packages/cli/foundation/debug/event.mjs b/packages/cli/foundation/debug/event.mjsindex e3e3930c0d..caa1780ea6 100644--- a/packages/cli/foundation/debug/event.mjs+++ b/packages/cli/foundation/debug/event.mjs@@ -23,9 +23,16 @@ import {isCliOneOff, detectPackageManager} from '../env/package-manager.mjs';/*** Version of the recorded event shape. Bump on any breaking field change,* widening {@link DebugSchemaVersion} in the published type at the same time.+ *+ * v2 retired the raw `env.agentSessionId`: it is always null now, and+ * `agentSessionIdHash` is the join key. A consumer that grouped runs by the+ * raw value would otherwise have started grouping every run under `null`+ * without a single compile error, which is exactly what the version exists to+ * prevent.+ ** @type {import('../../authoring/debug/type').DebugSchemaVersion}*/-export const SCHEMA_VERSION = 1;+export const SCHEMA_VERSION = 2;/*** The recorded shape is PUBLISHED — a project sets `debug` in `astryx.config`@@ -230,8 +237,10 @@ function detectInvocationSource({agentIdentity, agentSessionId, ci}) {/*** Snapshot the machine, runtime, and invocation attribution. There is no- * hostname, username, or network identity. Agent session values come only from- * explicit environment signals supplied by the invoking tool.+ * hostname, username, or network identity, and no raw agent session id — the+ * privacy contract is on `DebugEventEnv` in `authoring/debug/type.ts`. Agent+ * session values come only from explicit environment signals supplied by the+ * invoking tool.** @param {{cliVersion?: string}} [options]* @returns {import('../../authoring/debug/type').DebugEventEnv}@@ -252,7 +261,13 @@ export function captureEnv({cliVersion} = {}) {ciName,agent: detectAgent(agentIdentity),agentIdentity,- agentSessionId: agentSession.id,+ // Never the raw value. A session id is a stable identifier that follows a+ // person across every run they make, and nothing here needs it: the hash+ // joins those runs just as well, and a handler that forwards the record+ // somewhere less private cannot un-forward an identifier we handed it.+ // Kept as an always-null field rather than dropped, so a consumer reading+ // schema-v1 records alongside these sees one stable shape.+ agentSessionId: null,agentSessionIdHash: hashAgentSessionId(agentSession.id),agentSessionIdSource: agentSession.source,invocationSource: detectInvocationSource({@@ -336,7 +351,10 @@ export function createEvent({command = '', argv = []} = {}) {},env: null,project: captureProject(),- redacted: true,+ // FALSE, and true only on the sealed copy `finish()` delivers. Nothing has+ // been through the scrubbing pass yet, and a record that claims otherwise+ // while still holding verbatim values is worse than one that admits it.+ redacted: false,};}diff --git a/packages/cli/foundation/debug/privacy-contract.test.mjs b/packages/cli/foundation/debug/privacy-contract.test.mjsnew file mode 100644index 0000000000..5d2bf31c66--- /dev/null+++ b/packages/cli/foundation/debug/privacy-contract.test.mjs@@ -0,0 +1,187 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The privacy contract for a recorded run, enforced.+ *+ * A record may be forwarded anywhere the project's `debug` handler chooses, so+ * these are the promises `DebugEventEnv` makes to the person whose runs are+ * being recorded:+ *+ * 1. no raw agent session id reaches a handler — only its hash;+ * 2. free text the environment supplied is scrubbed like argv;+ * 3. the values this CLI derives survive verbatim, or the record is useless;+ * 4. `redacted` is true only when every pass has actually run.+ *+ * Each of these was false at some point: the raw id was recorded beside its+ * hash, `env` skipped the scrubbing pass entirely, and `redacted: true` was+ * stamped on the event at creation — before anything had been scrubbed.+ *+ * @position packages/cli/foundation/debug — privacy contract coverage+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {createHash} from 'node:crypto';+import {+ begin,+ currentEvent,+ finish,+ resetRecorder,+ setEventHandler,+} from './recorder.mjs';+import {captureEnv, SCHEMA_VERSION} from './event.mjs';+import {REDACTED, VERBATIM_ENV_FIELDS} from './redact.mjs';+import {parseDebugEvent} from '../../authoring/debug/parse.mjs';++const RAW_SESSION = 'session-alpha-bravo-charlie';+const RAW_SESSION_HASH = createHash('sha256')+ .update(RAW_SESSION, 'utf8')+ .digest('hex');++/** @param {() => void} [setup] */+function collectEvent(setup = () => {}) {+ /** @type {any[]} */+ const seen = [];+ setEventHandler(event => seen.push(event));+ begin({argv: ['docs'], cliVersion: '9.9.9'});+ setup();+ finish({exitCode: 0});+ expect(seen).toHaveLength(1);+ return seen[0];+}++beforeEach(() => {+ vi.unstubAllEnvs();+ resetRecorder();+});++afterEach(() => {+ vi.unstubAllEnvs();+ resetRecorder();+});++describe('no raw stable identifier is recorded', () => {+ it('hands the handler the hash and never the session id itself', () => {+ vi.stubEnv('ASTRYX_AGENT_ID', 'astryx-test-agent');+ vi.stubEnv('ASTRYX_AGENT_SESSION_ID', RAW_SESSION);+ const event = collectEvent();++ expect(event.env.agentSessionId).toBe(null);+ expect(event.env.agentSessionIdHash).toBe(RAW_SESSION_HASH);+ expect(event.env.agentSessionIdSource).toBe('ASTRYX_AGENT_SESSION_ID');+ // Not just the field: nowhere in the record at all.+ expect(JSON.stringify(event)).not.toContain(RAW_SESSION);+ });++ it('never records one from the metadata env var either', () => {+ vi.stubEnv(+ 'ASTRYX_AGENT_METADATA',+ JSON.stringify({id: 'metadata-agent', session_id: RAW_SESSION}),+ );+ const event = collectEvent();+ expect(event.env.agentSessionId).toBe(null);+ expect(event.env.agentSessionIdHash).toBe(RAW_SESSION_HASH);+ expect(JSON.stringify(event)).not.toContain(RAW_SESSION);+ });++ it('still joins runs of one session, which is what the raw value was for', () => {+ vi.stubEnv('ASTRYX_AGENT_SESSION_ID', RAW_SESSION);+ const first = collectEvent().env.agentSessionIdHash;+ resetRecorder();+ const second = collectEvent().env.agentSessionIdHash;+ expect(first).toBe(second);+ expect(first).not.toBe(null);+ });++ it('leaves the hash null when no signal supplied a session', () => {+ const env = captureEnv();+ expect(env.agentSessionId).toBe(null);+ expect(env.agentSessionIdHash).toBe(null);+ });+});++describe('environment free text is scrubbed', () => {+ it('scrubs a credential pasted into the agent identity', () => {+ // ASTRYX_AGENT_ID is free text: whatever the invoking tool exports lands+ // here, and `env` used to skip the scrubbing pass entirely.+ vi.stubEnv('ASTRYX_AGENT_ID', 'ghp_abcdefghijklmnopqrstuvwxyz01');+ const event = collectEvent();+ expect(event.env.agentIdentity).toBe(REDACTED);+ expect(event.env.agent).toBe(REDACTED);+ expect(JSON.stringify(event.env)).not.toContain('ghp_abcdef');+ });++ it('scrubs an email address in the agent identity', () => {+ vi.stubEnv('AGENT', '[email protected]');+ const event = collectEvent();+ expect(event.env.agentIdentity).toBe(REDACTED);+ });++ it('rewrites an absolute path in the agent identity', () => {+ vi.stubEnv('ASTRYX_AGENT_ID', '/users/someone/tools/my-agent');+ const event = collectEvent();+ expect(event.env.agentIdentity).not.toContain('/users/someone');+ expect(event.env.agentIdentity).toContain('…');+ });++ it('keeps ordinary free text readable', () => {+ // Scrubbing that ate every agent name would make the field worthless.+ vi.stubEnv('ASTRYX_AGENT_ID', 'astryx-test-agent');+ expect(collectEvent().env.agentIdentity).toBe('astryx-test-agent');+ });+});++describe('derived environment facts survive verbatim', () => {+ it('keeps the session hash intact despite its sensitive-looking name', () => {+ // `isSensitiveKey` matches the substring "session", so a key-based pass+ // over `env` would blank the hash — and with it the only way to join the+ // runs of one session, which is the whole reason the raw id can go.+ vi.stubEnv('ASTRYX_AGENT_SESSION_ID', RAW_SESSION);+ const event = collectEvent();+ expect(event.env.agentSessionIdHash).toBe(RAW_SESSION_HASH);+ expect(event.env.agentSessionIdHash).not.toBe(REDACTED);+ expect(event.env.agentSessionIdSource).toBe('ASTRYX_AGENT_SESSION_ID');+ });++ it('keeps the machine and runtime facts exactly as captured', () => {+ const event = collectEvent();+ expect(event.env.nodeVersion).toBe(process.versions.node);+ expect(event.env.platform).toBe(process.platform);+ expect(event.env.arch).toBe(process.arch);+ expect(event.env.cliVersion).toBe('9.9.9');+ // A timezone carries a slash and a locale a dash; neither may be mangled+ // by the path or entropy rules.+ if (event.env.timezone) expect(event.env.timezone).not.toContain('…');+ if (event.env.locale) expect(event.env.locale).not.toBe(REDACTED);+ });++ it('classifies every field of the snapshot, so a new one is scrubbed by default', () => {+ // The mirror of the allowlist. When a field is added to the snapshot this+ // fails, which is the point: someone decides whether it is derived (safe+ // verbatim) or free text (scrubbed) instead of inheriting either by+ // accident.+ const scrubbed = ['agent', 'agentIdentity', 'agentSessionId'];+ expect(Object.keys(captureEnv()).sort()).toEqual(+ [...VERBATIM_ENV_FIELDS, ...scrubbed].sort(),+ );+ });+});++describe('`redacted` says what actually happened', () => {+ it('is false while the event is still in flight', () => {+ begin({argv: ['docs']});+ expect(currentEvent()?.redacted).toBe(false);+ });++ it('is true on the record a handler receives', () => {+ expect(collectEvent().redacted).toBe(true);+ });+});++describe('the schema version marks the change', () => {+ it('delivers v2 records that validate against the published schema', () => {+ const event = collectEvent();+ expect(event.schemaVersion).toBe(2);+ expect(SCHEMA_VERSION).toBe(2);+ expect(() => parseDebugEvent(event)).not.toThrow();+ });+});diff --git a/packages/cli/foundation/debug/recorder.mjs b/packages/cli/foundation/debug/recorder.mjsindex a8a242e331..d7923cd515 100644--- a/packages/cli/foundation/debug/recorder.mjs+++ b/packages/cli/foundation/debug/recorder.mjs@@ -39,7 +39,7 @@ import {captureProject,captureEnv,} from './event.mjs';-import {createRedactor, redactArgv} from './redact.mjs';+import {createRedactor, redactArgv, redactEnv} from './redact.mjs';import {ERROR_CODES} from '../response/error-codes.mjs';/**@@ -418,6 +418,13 @@ const RESULT_KINDS = new Set(['component', 'template', 'doc', 'hook']);/*** Record a stable summary of a command's result set and presentation.*+ * `results` is only read for `resultKind`, so passing the bounded, surfaced+ * slice is correct. `resultCount` is NOT that slice's length: pass the total+ * the command matched before its limit and score floors, because a count that+ * silently reports the cap makes "matched exactly 20" and "matched 200, showed+ * 20" the same row. It falls back to `results.length` only for a command whose+ * surfaced set IS the whole match set.+ ** @param {Array<{domain?: unknown}>} results Surfaced results used for kind.* @param {{directMatch?: boolean, resultCount?: number, emptyResult?: boolean}} [options]*/@@ -644,8 +651,15 @@ export function finish({exitCode} = {}) {endedAt,durationMs,// Filled in just above — `env` is null only while the event is still in- // flight, which a sealed one never is.- env: /** @type {import('./event.mjs').DebugEvent['env']} */ (_event.env),+ // flight, which a sealed one never is. The snapshot mixes values we+ // derive with free text the environment supplied, so it gets its own+ // classified pass rather than the generic one.+ env: /** @type {import('./event.mjs').DebugEvent['env']} */ (+ redactEnv(+ /** @type {import('./event.mjs').DebugEvent['env']} */ (_event.env),+ redact,+ )+ ),argv: /** @type {string[]} */ (redactArgv(_event.argv, redact)),args: /** @type {Record<string, unknown>} */ (redact(_event.args)),options: /** @type {Record<string, unknown>} */ (redact(_event.options)),@@ -671,6 +685,11 @@ export function finish({exitCode} = {}) {: String(redact(_event.error.stack) ?? ''),}: null,+ // Every pass above has now run, so the claim is true. It is set HERE and+ // nowhere else: an in-flight event carries `redacted: false` until this+ // copy is built, so the flag can never say "scrubbed" about values that+ // are not.+ redacted: true,};// A COPY PER HANDLER. Handing over the live object would let third-partydiff --git a/packages/cli/foundation/debug/redact.mjs b/packages/cli/foundation/debug/redact.mjsindex 91537995e1..a389108e13 100644--- a/packages/cli/foundation/debug/redact.mjs+++ b/packages/cli/foundation/debug/redact.mjs@@ -14,7 +14,12 @@* its type and rough length so aggregate queries ("how many people pass* --out?") still work on scrubbed data. It replaces content, not structure.*- * @input arbitrary argv/option/error values+ * The environment snapshot goes through {@link redactEnv} rather than the+ * generic pass, because it is the one part of a record that mixes values this+ * CLI derives (which must survive verbatim to be worth recording) with free+ * text the invoking environment supplied (which must not).+ *+ * @input arbitrary argv/option/error values, and the environment snapshot* @output the same shape with sensitive content replaced by stable markers* @position packages/cli/foundation/debug — scrubbing*/@@ -393,6 +398,72 @@ export function createRedactor({return (value, key) => redact(value, key, 0);}+/**+ * Which fields of the environment snapshot are recorded VERBATIM.+ *+ * Every one of these is DERIVED: this CLI produces it from a fixed vocabulary+ * (`process.platform`, the CI provider table, an Intl lookup, a SHA-256 of a+ * value we never keep), so none of them can carry something a person typed,+ * and their exact values are the whole reason the snapshot is useful.+ *+ * Everything else in `env` is free text handed to us by the invoking+ * environment — an agent name from `ASTRYX_AGENT_ID`, `AGENT`, or+ * `ASTRYX_AGENT_METADATA` — so it goes through the same content rules as argv.+ * The list is a positive allowlist rather than a denylist of risky fields: a+ * field added to the snapshot later is scrubbed until someone decides+ * otherwise, which is the safe direction to be wrong in.+ *+ * `agentSessionIdHash` earns its place twice over. It is a hash, so it cannot+ * leak what it was made from — and it is the only key that joins the runs of+ * one session, which is exactly why the raw identifier is not recorded at all.+ *+ * Exported so a test can assert the classification still covers the whole+ * snapshot: a field added later without a decision fails that test rather than+ * quietly inheriting one behaviour or the other.+ */+export const VERBATIM_ENV_FIELDS = new Set([+ 'agentSessionIdHash',+ 'agentSessionIdSource',+ 'arch',+ 'ci',+ 'ciName',+ 'cliVersion',+ 'invocationSource',+ 'locale',+ 'nodeVersion',+ 'oneOff',+ 'packageManager',+ 'platform',+ 'timezone',+ 'tty',+]);++/**+ * Apply the content rules to the environment snapshot.+ *+ * Deliberately NOT `redact(value, key)`: key-based redaction would match the+ * word "session" in three of these names and blank the hash, destroying the+ * join key the published contract promises. The classification above decides+ * instead, and only the CONTENT rules run on what it does not exempt.+ *+ * @template T+ * @param {T} env+ * @param {Redactor} redact+ * @returns {T}+ */+export function redactEnv(env, redact) {+ if (!env || typeof env !== 'object') return env;+ /** @type {Record<string, unknown>} */+ const out = {};+ for (const [key, value] of Object.entries(env)) {+ out[key] =+ typeof value === 'string' && !VERBATIM_ENV_FIELDS.has(key)+ ? redact(value)+ : value;+ }+ return /** @type {T} */ (/** @type {unknown} */ (out));+}+/** @returns {string} */function safeHomedir() {try {diff --git a/packages/cli/foundation/debug/telemetry-fields.test.mjs b/packages/cli/foundation/debug/telemetry-fields.test.mjsindex c59d9fcae4..83862548fc 100644--- a/packages/cli/foundation/debug/telemetry-fields.test.mjs+++ b/packages/cli/foundation/debug/telemetry-fields.test.mjs@@ -151,6 +151,10 @@ describe('DebugEvent additive fields', () => {it('accepts persisted schema-v1 events that predate the fields', () => {const legacy = structuredClone(collectEvent());+ // A record written by an older CLI: v1, and carrying the raw session id+ // that v2 retired. Reading history back must keep working.+ legacy.schemaVersion = 1;+ legacy.env.agentSessionId = 'legacy-raw-session';for (const key of ['resultCount','emptyResult',@@ -161,7 +165,6 @@ describe('DebugEvent additive fields', () => {}for (const key of ['agentIdentity',- 'agentSessionId','agentSessionIdHash','agentSessionIdSource','invocationSource',@@ -178,7 +181,7 @@ describe('DebugEvent additive fields', () => {},env: {agentIdentity: null,- agentSessionId: null,+ agentSessionId: 'legacy-raw-session',agentSessionIdHash: null,agentSessionIdSource: null,invocationSource: 'unknown',@@ -223,7 +226,7 @@ describe('environment attribution', () => {expect(env).toMatchObject({agent: 'test-agent',agentIdentity: 'test-agent',- agentSessionId: 'agent-session-123',+ agentSessionId: null,agentSessionIdSource: 'ASTRYX_AGENT_SESSION_ID',invocationSource: 'ai',});@@ -248,12 +251,16 @@ describe('environment attribution', () => {'ASTRYX_AGENT_METADATA','id=future-agent,invocation_id=future-session,malformed',);- expect(captureEnv()).toMatchObject({+ const env = captureEnv();+ expect(env).toMatchObject({agentIdentity: 'future-agent',- agentSessionId: 'future-session',+ agentSessionId: null,agentSessionIdSource: 'ASTRYX_AGENT_METADATA.invocation_id',invocationSource: 'ai',});+ expect(env.agentSessionIdHash).toBe(+ createHash('sha256').update('future-session', 'utf8').digest('hex'),+ );});it('parses JSON metadata', () => {@@ -262,12 +269,16 @@ describe('environment attribution', () => {'ASTRYX_AGENT_METADATA',JSON.stringify({id: 'json-agent', session_id: 'json-session'}),);- expect(captureEnv()).toMatchObject({+ const env = captureEnv();+ expect(env).toMatchObject({agentIdentity: 'json-agent',- agentSessionId: 'json-session',+ agentSessionId: null,agentSessionIdSource: 'ASTRYX_AGENT_METADATA.session_id',invocationSource: 'ai',});+ expect(env.agentSessionIdHash).toBe(+ createHash('sha256').update('json-session', 'utf8').digest('hex'),+ );});it('leaves agent fields null without a signal', () => {diff --git a/packages/cli/foundation/env/package-manager.mjs b/packages/cli/foundation/env/package-manager.mjsindex 612222f371..453c80c7a0 100644--- a/packages/cli/foundation/env/package-manager.mjs+++ b/packages/cli/foundation/env/package-manager.mjs@@ -1,10 +1,12 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Detect the project's package manager from lockfiles.+ * @file Detect the project's package manager.*- * Returns the correct command prefix for running package binaries- * (e.g. 'npx astryx', 'yarn astryx', 'pnpm exec astryx').+ * The order is: the `packageManager` field a project DECLARES, then the+ * lockfiles it happens to have, then a committed package-manager config, then+ * the runner that launched us. Returns the correct command prefix for running+ * package binaries (e.g. 'npx astryx', 'yarn astryx', 'pnpm exec astryx').*/import * as fs from 'node:fs';@@ -28,7 +30,7 @@ const KNOWN_PMS = ['yarn', 'pnpm', 'bun', 'npm'];/*** Lockfile names by package manager. Order is the tiebreak of LAST resort —- * see {@link detectPackageManager} for why it should rarely decide anything.+ * see {@link explainPackageManager} for why it should rarely decide anything.* @type {readonly [PackageManager, readonly string[]][]}*/const LOCKFILES = [@@ -38,6 +40,12 @@ const LOCKFILES = [['npm', ['package-lock.json']],];+/**+ * A lockfile found on disk: which package manager owns it, and the file that+ * was actually there (bun has two spellings), so a caller can name it.+ * @typedef {{pm: PackageManager, file: string}} FoundLockfile+ */+/*** Narrow an arbitrary string to a known {@link PackageManager}.* @param {string} name@@ -78,14 +86,18 @@ function runningPackageManager() {}/**- * Every package manager with a lockfile in this directory.+ * Every lockfile in this directory, with the file that was found.* @param {string} dir- * @returns {PackageManager[]}+ * @returns {FoundLockfile[]}*/function lockfilesIn(dir) {- return LOCKFILES.filter(([, names]) =>- names.some(name => fs.existsSync(path.join(dir, name))),- ).map(([pm]) => pm);+ /** @type {FoundLockfile[]} */+ const found = [];+ for (const [pm, names] of LOCKFILES) {+ const file = names.find(name => fs.existsSync(path.join(dir, name)));+ if (file) found.push({pm, file});+ }+ return found;}/**@@ -119,35 +131,46 @@ function evidenceIn(dir) {* directory and nothing the project owns picks between them. `pm` is then the* neutral `'npx'`: correct under every package manager, wrong under none.* @property {string | null} dir - The directory that answered, if any.- * @property {PackageManager[]} candidates - The tied lockfile owners, when ambiguous.+ * @property {PackageManager[]} candidates - The lockfile owners in `dir`.+ * @property {PackageManager | null} declared - The `packageManager` field in+ * `dir`, when it names one we know. Non-null means the project SAID which+ * one, and `pm` is that.+ * @property {'declared' | 'lockfile' | 'evidence' | 'runner' | 'none'} source -+ * What decided `pm`.+ * @property {FoundLockfile[]} strayLockfiles - Lockfiles in `dir` that the+ * declared field contradicts. Detection ignores them; `astryx doctor` reports+ * them, because a tool that trusts the lockfile instead will disagree with us.*//*** Detect the project's package manager, with the reasoning attached.* Walks up from targetDir, taking the first directory that answers.*- * A single lockfile still wins over everything else in its directory, which is- * the long-standing behaviour. What changes here is the case of SEVERAL- * lockfiles in one directory, which the fixed array order used to resolve- * silently and often wrongly.- *- * That case is not hypothetical. One `yarn install` inside a pnpm project- * leaves a `yarn.lock` beside the committed `pnpm-lock.yaml` forever, and- * `fbsource/nest` ships both at its root deliberately. Answering "yarn" from- * array order then makes every command the CLI prints wrong for that project —- * including the invocation line written into agent docs, which agents copy.+ * The order within a directory, strongest first:*- * Ambiguity is therefore resolved ONLY from evidence the project owns: the- * declared `packageManager` field, then a committed package-manager config- * file. Deliberately NOT `npm_config_user_agent`: an agent that was handed the- * wrong `yarn astryx` line runs the CLI *through yarn*, so the runner agrees- * with the mistake and the wrong line reproduces itself forever. The same is- * true of an installed binary invoked from that shell.- *- * When nothing project-owned decides it, the answer is not a guess — it is- * `'npx'`, which runs correctly under every package manager, plus- * `ambiguous: true` so `astryx doctor` can report the real problem. (Same idea- * as `findConfigPath`, which refuses to choose between coexisting configs.)+ * 1. **The declared `packageManager` field.** This is the project saying which+ * one it uses — corepack's field, the only signal a person writes on+ * purpose — so it decides, whatever lockfiles happen to sit beside it. A+ * single `yarn install` in a pnpm project drops a `yarn.lock` that never+ * goes away, and letting that trace outrank the declaration made every+ * command the CLI printed wrong for the project, including the invocation+ * line written into agent docs, which agents copy. The contradicted+ * lockfiles come back as `strayLockfiles` so `doctor` can say so.+ * 2. **A single lockfile**, when nothing is declared. Unambiguous, and the+ * long-standing fallback.+ * 3. **A committed package-manager config** (`pnpm-workspace.yaml`,+ * `.yarnrc.yml`, `bunfig.toml`), when several lockfiles tie and nothing is+ * declared. A stray `install` drops a lockfile; it does not write one of+ * these.+ * 4. **Nothing project-owned decides it** — then the answer is not a guess, it+ * is `'npx'`, which runs correctly under every package manager, plus+ * `ambiguous: true` so `astryx doctor` can report the real problem. (Same+ * idea as `findConfigPath`, which refuses to choose between coexisting+ * configs.)+ * 5. **The runner**, only once the whole walk found nothing on disk.+ * Deliberately last, and never a tiebreak: an agent handed the wrong `yarn+ * astryx` line runs the CLI *through yarn*, so the runner agrees with the+ * mistake and the wrong line reproduces itself forever.** @param {string} [targetDir=process.cwd()]* @returns {PackageManagerResolution}@@ -158,39 +181,75 @@ export function explainPackageManager(targetDir = process.cwd()) {while (dir !== root) {const locks = lockfilesIn(dir);+ const candidates = locks.map(lock => lock.pm);+ const declared = declaredPackageManager(dir);++ // 1. The project declared one. Nothing on the filesystem outranks that.+ if (declared) {+ return {+ pm: declared,+ ambiguous: false,+ dir,+ candidates,+ declared,+ source: 'declared',+ strayLockfiles: locks.filter(lock => lock.pm !== declared),+ };+ }- // 1. One lockfile is unambiguous, and outranks the field as it always has.+ // 2. One lockfile is unambiguous.if (locks.length === 1) {- return {pm: locks[0], ambiguous: false, dir, candidates: locks};+ return {+ pm: locks[0].pm,+ ambiguous: false,+ dir,+ candidates,+ declared: null,+ source: 'lockfile',+ strayLockfiles: [],+ };}- // 2. Several lockfiles: the filesystem cannot say. Only the project can.+ // 3. Several lockfiles and no declaration: the filesystem cannot say.+ // Only a file the project committed on purpose can.if (locks.length > 1) {- const declared = declaredPackageManager(dir);- if (declared && locks.includes(declared)) {- return {pm: declared, ambiguous: false, dir, candidates: locks};- }- const evidence = evidenceIn(dir).filter(pm => locks.includes(pm));+ const evidence = evidenceIn(dir).filter(pm => candidates.includes(pm));if (evidence.length === 1) {- return {pm: evidence[0], ambiguous: false, dir, candidates: locks};+ return {+ pm: evidence[0],+ ambiguous: false,+ dir,+ candidates,+ declared: null,+ source: 'evidence',+ strayLockfiles: [],+ };}- return {pm: 'npx', ambiguous: true, dir, candidates: locks};+ return {+ pm: 'npx',+ ambiguous: true,+ dir,+ candidates,+ declared: null,+ source: 'none',+ strayLockfiles: [],+ };}- // 3. No lockfile here: the field, if this directory declares one.- const declared = declaredPackageManager(dir);- if (declared) return {pm: declared, ambiguous: false, dir, candidates: []};-dir = path.dirname(dir);}- // 4. Nothing on disk said anything anywhere. With no project evidence to+ // 5. Nothing on disk said anything anywhere. With no project evidence to// contradict, the runner is the only signal there is.+ const running = runningPackageManager();return {- pm: runningPackageManager() ?? 'npx',+ pm: running ?? 'npx',ambiguous: false,dir: null,candidates: [],+ declared: null,+ source: running ? 'runner' : 'none',+ strayLockfiles: [],};}diff --git a/packages/cli/foundation/env/package-manager.test.mjs b/packages/cli/foundation/env/package-manager.test.mjsindex b4626a527b..6ba445a259 100644--- a/packages/cli/foundation/env/package-manager.test.mjs+++ b/packages/cli/foundation/env/package-manager.test.mjs@@ -125,8 +125,6 @@ describe('detectPackageManager', () => {});it('lets the packageManager field break a multi-lockfile tie', () => {- // A single lockfile still outranks the field (asserted above). This is only- // about the case where the filesystem is self-contradictory.const dir = makeTmpDir();fs.writeFileSync(path.join(dir, 'yarn.lock'), '');fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');@@ -137,6 +135,24 @@ describe('detectPackageManager', () => {expect(detectPackageManager(dir)).toBe('pnpm');});+ it('follows the declared packageManager even when no lockfile matches it', () => {+ // The declaration is the project speaking. Two lockfiles that disagree+ // with it are two traces that are both wrong, not a tie to resolve.+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');+ fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({packageManager: '[email protected]'}),+ );+ expect(explainPackageManager(dir)).toMatchObject({+ pm: 'pnpm',+ ambiguous: false,+ declared: 'pnpm',+ source: 'declared',+ });+ });+it('ignores a runner that has no lockfile in the directory', () => {const dir = makeTmpDir();fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');@@ -171,16 +187,89 @@ describe('detectPackageManager', () => {expect(detectPackageManager(dir)).toBe('npx');});- it('lockfile takes priority over packageManager field', () => {+ it('declared packageManager outranks a single stray lockfile', () => {+ // The regression: one `yarn install` inside a pnpm project leaves a+ // yarn.lock forever, and a single lockfile used to outrank the field. The+ // CLI then printed `yarn astryx` for a pnpm project — and wrote that line+ // into the agent docs, where agents copy it.+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({packageManager: '[email protected]'}),+ );+ expect(detectPackageManager(dir)).toBe('pnpm');+ expect(getCliInvocation(dir)).toBe('pnpm exec astryx');+ });++ it('reports the stray lockfile it ignored, so doctor can name it', () => {const dir = makeTmpDir();fs.writeFileSync(path.join(dir, 'yarn.lock'), '');+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({packageManager: '[email protected]'}),+ );+ expect(explainPackageManager(dir)).toMatchObject({+ pm: 'pnpm',+ declared: 'pnpm',+ source: 'declared',+ strayLockfiles: [{pm: 'yarn', file: 'yarn.lock'}],+ });+ });++ it('reports no stray when the lockfile agrees with the declaration', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');fs.writeFileSync(path.join(dir, 'package.json'),JSON.stringify({packageManager: '[email protected]'}),);+ expect(explainPackageManager(dir)).toMatchObject({+ pm: 'pnpm',+ declared: 'pnpm',+ strayLockfiles: [],+ });+ });++ it('keeps the lockfile fallback when nothing is declared', () => {+ // The documented fallback: with no declaration, one lockfile still decides.+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({}));+ expect(explainPackageManager(dir)).toMatchObject({+ pm: 'yarn',+ declared: null,+ source: 'lockfile',+ });+ });++ it('ignores an unknown packageManager value and falls back to the lockfile', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({packageManager: '[email protected]'}),+ );expect(detectPackageManager(dir)).toBe('yarn');});+ it('lets a nearer directory answer before an outer declaration', () => {+ // Unchanged walk-up behaviour: the first directory that answers wins, so a+ // workspace root's declaration does not reach past a package that has its+ // own lockfile.+ const dir = makeTmpDir();+ const inner = path.join(dir, 'packages', 'app');+ fs.mkdirSync(inner, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({packageManager: '[email protected]'}),+ );+ fs.writeFileSync(path.join(inner, 'package-lock.json'), '{}');+ expect(detectPackageManager(inner)).toBe('npm');+ expect(detectPackageManager(dir)).toBe('pnpm');+ });+it('detects from npm_config_user_agent env var', () => {const dir = makeTmpDir();process.env.npm_config_user_agent = 'yarn/1.22.22 node/v20.0.0';diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex d72fbc19d7..68ec6557a9 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -111,7 +111,7 @@ export const doc = {{value: 'search',description:- 'The echoed query plus a ranked SearchResultEntry[] (domain, name, score, reason, description, follow-up command, and import path where relevant).',+ 'The echoed query, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit` (domain, name, score, reason, description, follow-up command, and import path where relevant).',},// build@@ -123,7 +123,7 @@ export const doc = {{value: 'build.kit',description:- 'The grouped composition kit: echoed query, hasResults/matchCount/directMatch fields, the closest page templates, drop-in block patterns, idea-specific components/hooks, and the always-on frame + foundation component-name arrays.',+ 'The grouped composition kit: echoed query, hasResults/matchCount/directMatch fields (matchCount is the total matched, never a cap read back), the closest page templates, drop-in block patterns, idea-specific components/hooks, and the always-on frame + foundation component-name arrays.',},// swizzlediff --git a/packages/core/src/Chat/ChatComposerInput.test.tsx b/packages/core/src/Chat/ChatComposerInput.test.tsxindex da6b804905..252fe83a95 100644--- a/packages/core/src/Chat/ChatComposerInput.test.tsx+++ b/packages/core/src/Chat/ChatComposerInput.test.tsx@@ -2,7 +2,9 @@import {describe, it, expect, vi, afterEach} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';+import userEvent from '@testing-library/user-event';import {ChatComposer} from './ChatComposer';+import {useChatComposerContext} from './ChatContext';import {ChatComposerInput} from './ChatComposerInput';import type {ChatComposerTrigger,@@ -564,6 +566,13 @@ describe('ChatComposerInput', () => {window.getSelection()?.removeAllRanges();}+ /** Type a message and send it, so history has something to recall. */+ function submitMessage(textbox: HTMLElement, value: string) {+ textbox.textContent = value;+ fireEvent.input(textbox);+ fireEvent.keyDown(textbox, {key: 'Enter'});+ }+it('paste inserts plain text after a focus() with no selection range', () => {const onChange = vi.fn();render(<ChatComposerInput onChange={onChange} />);@@ -644,6 +653,313 @@ describe('ChatComposerInput', () => {expect(textbox.textContent).toContain('hello');});+ // History recall reads where the caret sits, so where a programmatic+ // focus leaves it decides whether ArrowUp recalls or moves the caret.+ // Measured in Chromium: `focus()` collapses the caret to offset 0 —+ // the START of the draft — so a composer that trusted it would let the+ // first ArrowUp after a padding click replace whatever was typed. The+ // composer states the caret itself instead: after the draft.+ describe('caret placement on programmatic focus', () => {+ /** What Chromium does to the Selection on `editable.focus()`. */+ function focusLikeChromium(editable: HTMLElement) {+ editable.focus();+ const selection = window.getSelection()!;+ const range = document.createRange();+ range.setStart(editable.firstChild ?? editable, 0);+ range.collapse(true);+ selection.removeAllRanges();+ selection.addRange(range);+ }++ function caretOffsetFromEnd(editable: HTMLElement): number {+ const selection = window.getSelection()!;+ const range = selection.getRangeAt(0);+ const toEnd = document.createRange();+ toEnd.selectNodeContents(editable);+ toEnd.setStart(range.endContainer, range.endOffset);+ return toEnd.toString().length;+ }++ it('puts the caret after the draft when the composer shell focuses it', async () => {+ const user = userEvent.setup();+ render(+ <ChatComposer onSubmit={() => {}} input={<ChatComposerInput />} />,+ );+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'pending draft';+ fireEvent.input(textbox);++ // Walk to the composer body: editable → input root → inputArea → body.+ const body = textbox.parentElement!.parentElement!.parentElement!;+ await user.click(body);++ expect(document.activeElement).toBe(textbox);+ expect(caretOffsetFromEnd(textbox)).toBe(0);+ });++ // The click path overrides rather than restores: clicking the space+ // after the text says where the user wants to be, so a caret left+ // over from earlier does not win. Driving the shell's registered+ // control directly is what makes this distinguishable — jsdom's+ // synthetic click clears the selection on its own, so a click alone+ // would pass either way.+ it('overrides a stale mid-draft caret when the shell focuses it', () => {+ let shellFocus: (() => void) | undefined;+ function GrabControl() {+ const ctx = useChatComposerContext();+ shellFocus = () => {+ ctx?.inputControlRef?.current?.focus();+ };+ return null;+ }+ render(+ <ChatComposer+ onSubmit={() => {}}+ input={+ <>+ <ChatComposerInput />+ <GrabControl />+ </>+ }+ />,+ );+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'pending draft';+ fireEvent.input(textbox);+ const selection = window.getSelection()!;+ const range = document.createRange();+ range.setStart(textbox.firstChild!, 3);+ range.collapse(true);+ selection.removeAllRanges();+ selection.addRange(range);++ shellFocus!();++ expect(caretOffsetFromEnd(textbox)).toBe(0);+ });++ it('keeps a pending draft when ArrowUp follows a click on the composer padding', async () => {+ const user = userEvent.setup();+ render(+ <ChatComposer onSubmit={() => {}} input={<ChatComposerInput />} />,+ );+ const textbox = screen.getByRole('textbox');+ submitMessage(textbox, 'first');+ textbox.textContent = 'pending draft';+ fireEvent.input(textbox);++ const body = textbox.parentElement!.parentElement!.parentElement!;+ await user.click(body);+ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ // Caret movement, not recall: the draft survives untouched.+ expect(prevented).toBe(false);+ expect(textbox.textContent).toBe('pending draft');+ });++ it('recalls history when ArrowUp follows a padding click on an empty composer', async () => {+ const user = userEvent.setup();+ render(+ <ChatComposer onSubmit={() => {}} input={<ChatComposerInput />} />,+ );+ const textbox = screen.getByRole('textbox');+ submitMessage(textbox, 'first');++ const body = textbox.parentElement!.parentElement!.parentElement!;+ await user.click(body);+ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ // An empty draft is at its start and its end at once.+ expect(prevented).toBe(true);+ expect(textbox.textContent).toBe('first');+ });++ it('puts the caret after the draft on the imperative focus() with no prior caret', () => {+ let handle: ChatComposerInputHandle | null = null;+ render(+ <ChatComposerInput+ handleRef={h => {+ handle = h;+ }}+ />,+ );+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'pending draft';+ fireEvent.input(textbox);+ clearSelection();++ handle!.focus();++ expect(document.activeElement).toBe(textbox);+ expect(caretOffsetFromEnd(textbox)).toBe(0);+ });++ // A consumer calling focus() to return the user to the composer must+ // not move them: the caret they left behind is theirs, not ours.+ it('keeps a mid-draft caret across the imperative focus()', () => {+ let handle: ChatComposerInputHandle | null = null;+ render(+ <ChatComposerInput+ handleRef={h => {+ handle = h;+ }}+ />,+ );+ const textbox = screen.getByRole('textbox');+ const draft = 'pending draft';+ textbox.textContent = draft;+ fireEvent.input(textbox);+ // Caret between "pending" and " draft".+ const selection = window.getSelection()!;+ const range = document.createRange();+ range.setStart(textbox.firstChild!, 7);+ range.collapse(true);+ selection.removeAllRanges();+ selection.addRange(range);++ handle!.focus();++ expect(document.activeElement).toBe(textbox);+ expect(caretOffsetFromEnd(textbox)).toBe(draft.length - 7);+ });++ it('keeps a ranged selection across the imperative focus()', () => {+ let handle: ChatComposerInputHandle | null = null;+ render(+ <ChatComposerInput+ handleRef={h => {+ handle = h;+ }}+ />,+ );+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'pending draft';+ fireEvent.input(textbox);+ const selection = window.getSelection()!;+ const range = document.createRange();+ range.setStart(textbox.firstChild!, 0);+ range.setEnd(textbox.firstChild!, 7);+ selection.removeAllRanges();+ selection.addRange(range);++ handle!.focus();++ const after = window.getSelection()!;+ expect(after.isCollapsed).toBe(false);+ expect(after.toString()).toBe('pending');+ });++ it('keeps a start-of-draft caret across the imperative focus(), so ArrowUp still recalls', () => {+ let handle: ChatComposerInputHandle | null = null;+ render(+ <ChatComposerInput+ onSubmit={() => {}}+ handleRef={h => {+ handle = h;+ }}+ />,+ );+ const textbox = screen.getByRole('textbox');+ submitMessage(textbox, 'first');+ textbox.textContent = 'pending draft';+ fireEvent.input(textbox);+ // The user deliberately put the caret at the start.+ const selection = window.getSelection()!;+ const range = document.createRange();+ range.setStart(textbox.firstChild!, 0);+ range.collapse(true);+ selection.removeAllRanges();+ selection.addRange(range);++ handle!.focus();+ fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ // Their caret is honored, not overridden into "end of draft".+ expect(textbox.textContent).toBe('first');+ });++ it('ignores a selection outside the editable on the imperative focus()', () => {+ let handle: ChatComposerInputHandle | null = null;+ const {container} = render(+ <div>+ <p>elsewhere</p>+ <ChatComposerInput+ handleRef={h => {+ handle = h;+ }}+ />+ </div>,+ );+ const textbox = screen.getByRole('textbox');+ textbox.textContent = 'pending draft';+ fireEvent.input(textbox);+ const outside = container.querySelector('p')!;+ const selection = window.getSelection()!;+ const range = document.createRange();+ range.selectNodeContents(outside);+ selection.removeAllRanges();+ selection.addRange(range);++ handle!.focus();++ // Not the user's position in the composer, so it does not count.+ expect(caretOffsetFromEnd(textbox)).toBe(0);+ });++ it('keeps a pending draft when the caret is the one Chromium leaves on a bare focus()', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ submitMessage(textbox, 'first');+ textbox.textContent = 'pending draft';+ fireEvent.input(textbox);++ // A consumer focusing the DOM node directly bypasses our focus+ // control, so this is the caret the engine chose.+ focusLikeChromium(textbox);+ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ // The user did put the caret at the start here as far as the DOM can+ // tell, so recall is the documented behavior — but the draft must be+ // recoverable, not lost.+ expect(prevented).toBe(true);+ expect(textbox.textContent).toBe('first');+ fireEvent.keyDown(textbox, {key: 'ArrowDown'});+ expect(textbox.textContent).toBe('pending draft');+ });++ it('recalls history on ArrowUp when no caret exists inside the editable', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ submitMessage(textbox, 'first');++ // An engine that creates no Range on focus, or a consumer that never+ // focused at all: the composer falls back to a caret after the draft.+ textbox.focus();+ clearSelection();+ expect(window.getSelection()?.rangeCount ?? 0).toBe(0);++ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ expect(prevented).toBe(true);+ expect(textbox.textContent).toBe('first');+ });++ it('keeps a pending draft when no caret exists inside the editable', () => {+ render(<ChatComposerInput onSubmit={() => {}} />);+ const textbox = screen.getByRole('textbox');+ submitMessage(textbox, 'first');+ textbox.textContent = 'pending draft';+ fireEvent.input(textbox);+ textbox.focus();+ clearSelection();++ const prevented = !fireEvent.keyDown(textbox, {key: 'ArrowUp'});++ expect(prevented).toBe(false);+ expect(textbox.textContent).toBe('pending draft');+ });+ });+it('paste falls through to plain-text path when pasteAsToken={false}', () => {const onChange = vi.fn();render(<ChatComposerInput pasteAsToken={false} onChange={onChange} />);diff --git a/packages/core/src/Chat/ChatComposerInput.tsx b/packages/core/src/Chat/ChatComposerInput.tsxindex 69b5a4f39e..2dd56a909f 100644--- a/packages/core/src/Chat/ChatComposerInput.tsx+++ b/packages/core/src/Chat/ChatComposerInput.tsx@@ -51,6 +51,9 @@ import {insertTextAtCursor,isSelectionAtStart,isSelectionAtEnd,+ placeCaretAtEnd,+ getSelectionRangeInside,+ restoreSelectionRange,} from './chatComposerSelection';import {ChatPastedTextToken} from './ChatPastedTextToken';import {@@ -382,11 +385,66 @@ export function ChatComposerInput(props: ChatComposerInputProps) {// when a parent attaches a ref — without this, paste-as-token would// silently no-op whenever `ChatComposerInput` is rendered without// a forwarded ref (e.g. inside `ChatComposer`).+ /**+ * Focus the editable and put the caret after the draft.+ *+ * A bare `focus()` is not enough: Chromium collapses the caret to the+ * start of the content, which is the one position where ArrowUp means+ * "recall history" — so focusing a composer that already holds a draft+ * would arm the next ArrowUp to replace it. Landing after the text is+ * also what a click on the composer's trailing space means.+ */+ /**+ * Focus the editable, keeping a caret or selection the user already has+ * inside it.+ *+ * A bare `focus()` is not enough on its own: Chromium collapses the caret+ * to the start of the content, which is the one position where ArrowUp+ * means "recall history" — so focusing a composer that already holds a+ * draft would arm the next ArrowUp to replace it. But a consumer calling+ * `focus()` to return the user to where they were must not have their+ * caret moved either, so an existing in-editor selection is captured+ * before focusing and restored after. Only when there is none does the+ * caret land after the draft.+ */+ const focusEditable = useCallback(() => {+ const editable = editableRef.current;+ if (!editable) {+ return;+ }+ // Read before focusing: `focus()` itself creates the offset-0 caret, so+ // asking afterwards cannot tell the user's own caret from the engine's.+ const existing = getSelectionRangeInside(editable);+ editable.focus();+ if (existing) {+ restoreSelectionRange(existing);+ return;+ }+ placeCaretAtEnd(editable);+ }, []);++ /**+ * Focus the editable and put the caret after the draft, whatever the+ * selection was.+ *+ * This is the composer shell's click-to-focus path: clicking the empty+ * space after a draft means "put me after the text", so it overrides a+ * stale caret rather than restoring one.+ */+ const focusEditableAtEnd = useCallback(() => {+ const editable = editableRef.current;+ if (!editable) {+ return;+ }+ editable.focus();+ placeCaretAtEnd(editable);+ }, []);+const handle: ChatComposerInputHandle = {insertToken: (token: ChatComposerToken) => insertTokenRef.current(token),expandToken: (id: string) => tokens.expandToken(id),insertText: (text: string) => insertTextRef.current(text),- focus: () => editableRef.current?.focus(),+ focus: focusEditable,getValue: () =>serialize(editableRef.current ?? document.createElement('div')),};@@ -401,11 +459,11 @@ export function ChatComposerInput(props: ChatComposerInputProps) {if (!inputControlRef) {return;}- inputControlRef.current = {focus: () => editableRef.current?.focus()};+ inputControlRef.current = {focus: focusEditableAtEnd};return () => {inputControlRef.current = null;};- }, [inputControlRef]);+ }, [inputControlRef, focusEditableAtEnd]);useEffect(() => {if (controlledValue === undefined || !editableRef.current) {@@ -609,6 +667,13 @@ export function ChatComposerInput(props: ChatComposerInputProps) {return;}const editable = editableRef.current;+ // Last-resort fallback for a caret we never placed: an engine that+ // leaves no Range inside the editable on focus, or a consumer that+ // focused the DOM node directly instead of through our focus+ // control. Place it where the focus control would have, so a+ // pending draft is never mistaken for a caret at the start. A no-op+ // whenever a real caret exists — including one the user moved.+ ensureCaretInside(editable);const isCollapsed = window.getSelection()?.isCollapsed ?? true;const atStart = isSelectionAtStart(editable);const atEnd = isSelectionAtEnd(editable);diff --git a/packages/core/src/Chat/chatComposerSelection.ts b/packages/core/src/Chat/chatComposerSelection.tsindex 046d3dd474..0f31ca85e9 100644--- a/packages/core/src/Chat/chatComposerSelection.ts+++ b/packages/core/src/Chat/chatComposerSelection.ts@@ -11,26 +11,97 @@* Selection helpers for the contentEditable chat input. Both the* imperative `insertToken` / `insertText` APIs and the paste pipeline* need a valid Range inside the editable before they can mutate the- * DOM. Browsers do NOT create a Selection range when an element is- * programmatically focused — a Range only exists once the user has- * clicked inside the editable or we've created one explicitly.+ * DOM, and history recall needs to know where the caret sits.*- * `ensureCaretInside` centralizes the fallback: if the current- * Selection has no Range inside the given editable, place a collapsed- * caret at the end of the editable. Callers can then read- * `selection.getRangeAt(0)` safely.+ * What a programmatic `focus()` does to the Selection is browser- and+ * state-dependent, and it is never what a click on the composer's padding+ * means. Measured in Chromium: focusing a contentEditable collapses the+ * caret to offset 0 — the *start* of the draft — whether or not a+ * selection existed before, and whether the editable is empty or not.+ * Other engines may instead leave no Range inside the editable at all.+ *+ * So the composer never infers the caret from a bare `focus()`:+ * - `placeCaretAtEnd` states the caret outright, and is what the composer+ * shell's click-to-focus uses, because clicking the space after a draft+ * means "put me after the text" in every chat composer.+ * - `getSelectionRangeInside` + `restoreSelectionRange` let the imperative+ * `focus()` keep a caret or selection the user already had: it is read+ * before focusing, since afterwards the engine's own caret is+ * indistinguishable from theirs.+ * - `ensureCaretInside` is the weaker fallback for callers that only+ * need *a* valid Range (paste, imperative insertion): it respects a+ * caret that already exists and creates one at the end otherwise.** SYNC: When modified, update:* - /packages/core/src/Chat/ChatComposerInput.tsx (consumer)* - /packages/core/src/Chat/useChatComposerTokens.ts (consumer)*/+/**+ * The current Selection's range when it lies inside `editable`, or `null`.+ *+ * Callers use this to read the caret *before* focusing, because `focus()`+ * creates a caret of its own and afterwards the two are indistinguishable.+ * The range is cloned, so later DOM work cannot mutate the saved position.+ */+export function getSelectionRangeInside(editable: HTMLElement): Range | null {+ const selection = window.getSelection();+ if (!selection || selection.rangeCount === 0) {+ return null;+ }+ const range = selection.getRangeAt(0);+ if (+ !editable.contains(range.startContainer) ||+ !editable.contains(range.endContainer)+ ) {+ return null;+ }+ return range.cloneRange();+}++/** Make `range` the current Selection again. */+export function restoreSelectionRange(range: Range): void {+ const selection = window.getSelection();+ if (!selection) {+ return;+ }+ selection.removeAllRanges();+ selection.addRange(range);+}++/**+ * Collapse the Selection to the very end of `editable`'s content,+ * replacing whatever the Selection held before.+ *+ * Unlike {@link ensureCaretInside} this is unconditional: a caret the+ * browser placed on `focus()` is overwritten, which is the point — that+ * caret lands at the start of the draft, where ArrowUp means "recall+ * history" and would discard what the user had typed.+ *+ * Returns `true` when the caret was placed, `false` if the Selection API+ * is unavailable (e.g. a detached document).+ */+export function placeCaretAtEnd(editable: HTMLElement): boolean {+ const selection = window.getSelection();+ if (!selection) {+ return false;+ }+ const range = document.createRange();+ range.selectNodeContents(editable);+ range.collapse(false); // collapse to end+ selection.removeAllRanges();+ selection.addRange(range);+ return true;+}+/*** Ensure the current Selection has a Range inside `editable`.** If `window.getSelection()` already has a Range whose `startContainer`- * is inside `editable`, this is a no-op. Otherwise a collapsed caret- * is placed at the end of `editable` and the Selection is updated.+ * is inside `editable`, this is a no-op — including the start-of-draft+ * caret a `focus()` leaves behind, which is why callers that care where+ * the caret lands want {@link placeCaretAtEnd} instead. Otherwise a+ * collapsed caret is placed at the end of `editable`.** Returns the live `Selection` on success, or `null` if no Selection* is available at all (e.g. detached document, JSDOM without selectiondiff --git a/packages/core/src/Markdown/Markdown.test.tsx b/packages/core/src/Markdown/Markdown.test.tsxindex 193bad8d70..66587f76ab 100644--- a/packages/core/src/Markdown/Markdown.test.tsx+++ b/packages/core/src/Markdown/Markdown.test.tsx@@ -1,10 +1,11 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {describe, it, expect, vi} from 'vitest';+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';import type {ReactNode} from 'react';import {Markdown} from './Markdown';import type {MarkdownInlinePlugin} from './Markdown';+import {stubMatchMedia} from '../__tests__/stubMatchMedia';import {parseOutlineFromMarkdown} from '../Outline/parseOutlineFromMarkdown';describe('Markdown', () => {@@ -481,6 +482,90 @@ describe('Markdown', () => {expect(cursor).not.toBeInTheDocument();});+ // A reader watching a reply arrive sees the DOM, not the parsed nodes.+ // A `\|` is literal text, so the line must stay legible as it streams;+ // the parser once classified it as an unfinished table header and held+ // the whole line back, blanking the message.+ describe('streamed text containing an escaped pipe', () => {+ // Reduced motion makes the reveal synchronous, so each render shows+ // exactly the prefix under test rather than a rAF-driven fraction.+ beforeEach(() => {+ stubMatchMedia({reduceMotion: true});+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ /** The text of each rendered block, in document order. */+ function blockTexts(container: HTMLElement): string[] {+ const doc = container.querySelector('[role="document"]')!;+ return Array.from(doc.children).map(block =>+ (block.textContent ?? '').replace(/\s+/g, ' ').trim(),+ );+ }++ it('shows every prefix of the line, escaped pipe rendered literally', () => {+ const text = 'Costs 5 \\| 10 per unit';+ const {container, rerender} = render(+ <Markdown isStreaming>{text.slice(0, 1)}</Markdown>,+ );++ for (let length = 1; length <= text.length; length++) {+ const prefix = text.slice(0, length);+ rerender(<Markdown isStreaming>{prefix}</Markdown>);++ // Every `\|` reads as one literal pipe, and no backslash survives.+ expect(blockTexts(container)).toEqual([+ prefix.replace(/\\\|/g, '|').trim(),+ ]);+ }+ });++ it('shows every prefix below settled content, both kept on screen', () => {+ const settled = 'Intro\n\n';+ const text = `${settled}Costs 5 \\| 10 per unit`;+ const {container, rerender} = render(+ <Markdown isStreaming>{settled}</Markdown>,+ );++ for (let length = settled.length + 1; length <= text.length; length++) {+ const prefix = text.slice(0, length);+ rerender(<Markdown isStreaming>{prefix}</Markdown>);++ const tail = text.slice(settled.length, length).replace(/\\\|/g, '|');+ // The settled paragraph stays on screen and the tail is legible.+ expect(blockTexts(container)).toEqual(['Intro', tail.trim()]);+ }+ });++ it('renders the finished line as one paragraph with the literal pipe', () => {+ const {container} = render(+ <Markdown isStreaming>{'Costs 5 \\| 10 per unit'}</Markdown>,+ );++ const paragraphs = container.querySelectorAll('[role="paragraph"]');+ expect(paragraphs).toHaveLength(1);+ expect(paragraphs[0].textContent).toBe('Costs 5 | 10 per unit');+ // Prose, not a table: no cell was ever split out of it.+ expect(container.querySelector('table')).toBeNull();+ });++ it('still renders a real streamed table containing an escaped pipe', () => {+ const {container} = render(+ <Markdown isStreaming>+ {'| Col1 | Col2 |\n| --- | --- |\n| a \\| b | c |'}+ </Markdown>,+ );++ const cells = container.querySelectorAll('tbody td');+ expect(Array.from(cells).map(cell => cell.textContent)).toEqual([+ 'a | b',+ 'c',+ ]);+ });+ });+it('applies compact density', () => {const {container} = render(<Markdown density="compact">{'Hello'}</Markdown>,diff --git a/packages/core/src/Markdown/incremental.test.ts b/packages/core/src/Markdown/incremental.test.tsindex 0561f43d2d..edb61e66b4 100644--- a/packages/core/src/Markdown/incremental.test.ts+++ b/packages/core/src/Markdown/incremental.test.ts@@ -5,6 +5,7 @@ import {parseMarkdown,parseMarkdownIncremental,createIncrementalState,+ getIncrementalParseWork,trimStreamingArtifacts,} from './parser';import type {BlockNode, InlineNode} from './parser';@@ -430,6 +431,164 @@ describe('streaming structural suppression', () => {}});+ // A `\|` is literal text, not a cell delimiter, so an unfinished line+ // carrying only escaped pipes is ordinary prose. Holding it back hid the+ // text — and when it was the whole document, rendered nothing at all.+ describe('escaped pipes in the unsettled tail', () => {+ it('renders an unfinished first line whose only pipes are escaped', () => {+ const text = 'Costs 5 \\| 10 per unit';+ const state = createIncrementalState();++ const blocks = parseMarkdownIncremental(text, state);++ expect(blocks).toEqual(parseMarkdown(text));+ expect(blocks).toHaveLength(1);+ });++ it('renders an unfinished tail line after a settled block', () => {+ const text = 'Intro\n\nCosts 5 \\| 10 per unit';+ const state = createIncrementalState();++ const blocks = parseMarkdownIncremental(text, state);++ expect(blocks).toEqual(parseMarkdown(text));+ expect(blocks).toHaveLength(2);+ });++ /** The text a reader would see for one block. */+ function visibleText(block: BlockNode): string {+ const fromInline = (nodes: InlineNode[]): string =>+ nodes+ .map(node => {+ switch (node.type) {+ case 'text':+ case 'code':+ return node.content;+ case 'bold':+ case 'italic':+ case 'strikethrough':+ case 'link':+ return fromInline(node.children);+ case 'break':+ return '\n';+ case 'image':+ return node.alt;+ case 'citation':+ return '';+ }+ })+ .join('');+ switch (block.type) {+ case 'heading':+ case 'paragraph':+ return fromInline(block.children);+ case 'codeblock':+ return block.content;+ case 'blockquote':+ return block.children.map(visibleText).join('\n');+ case 'list':+ return block.items+ .map(item => item.children.map(visibleText).join('\n'))+ .join('\n');+ case 'table':+ return [block.headers, ...block.rows]+ .map(row => row.map(cell => fromInline(cell.children)).join(' '))+ .join('\n');+ case 'image':+ return block.alt;+ case 'hr':+ return '';+ }+ }++ /**+ * What the tail of a streamed prose line should read as once rendered:+ * every `\|` is one literal pipe, and the parser trims the unsettled+ * tail's surrounding whitespace.+ */+ function expectedTail(source: string): string {+ return source.replace(/\\\|/g, '|').trim();+ }++ it('keeps the whole tail visible at every prefix, with no settled text', () => {+ const text = 'Costs 5 \\| 10 per unit';+ const state = createIncrementalState();++ for (let length = 1; length <= text.length; length++) {+ const blocks = parseMarkdownIncremental(text.slice(0, length), state);+ const tail = expectedTail(text.slice(0, length));++ expect(blocks).toHaveLength(1);+ expect(visibleText(blocks[0])).toBe(tail);+ }+ });++ it('keeps the whole tail visible at every prefix, after a settled block', () => {+ const settled = 'Intro\n\n';+ const text = `${settled}Costs 5 \\| 10 per unit`;+ const state = createIncrementalState();++ for (let length = settled.length + 1; length <= text.length; length++) {+ const blocks = parseMarkdownIncremental(text.slice(0, length), state);+ const tail = expectedTail(text.slice(settled.length, length));++ // The settled paragraph stays put and the tail is fully readable.+ expect(blocks).toHaveLength(2);+ expect(visibleText(blocks[0])).toBe('Intro');+ expect(visibleText(blocks[1])).toBe(tail);+ }++ expect(parseMarkdownIncremental(text, state)).toEqual(+ parseMarkdown(text),+ );+ });++ it('keeps parsing bounded to the tail as the line streams in', () => {+ const prefix = 'Filler paragraph.\n\n'.repeat(40);+ const text = `${prefix}Costs 5 \\| 10 per unit`;+ const state = createIncrementalState();+ // Prime the cache: the first call has nothing settled yet and reads the+ // whole snapshot by definition.+ parseMarkdownIncremental(`${prefix}C`, state);+ let worstSplitCharacters = 0;++ for (let length = prefix.length + 2; length <= text.length; length++) {+ parseMarkdownIncremental(text.slice(0, length), state);+ worstSplitCharacters = Math.max(+ worstSplitCharacters,+ getIncrementalParseWork(state).splitCharacters,+ );+ }++ // Only the unsettled tail is re-split, never the settled filler.+ expect(worstSplitCharacters).toBeLessThan(+ text.length - prefix.length + 5,+ );+ });++ it('still holds back a lone header whose pipes are unescaped', () => {+ const state = createIncrementalState();++ const blocks = parseMarkdownIncremental('Col1 | Col2', state);++ expect(blocks).toHaveLength(0);+ });++ it('streams table rows containing escaped pipes once the table exists', () => {+ const text = '| Col1 | Col2 |\n| --- | --- |\n| a \\| b | c |';+ const state = createIncrementalState();++ const blocks = parseMarkdownIncremental(text, state);++ const table = blocks.find(b => b.type === 'table');+ expect(table?.type).toBe('table');+ if (table?.type === 'table') {+ expect(table.rows).toHaveLength(1);+ expect(table.rows[0]).toHaveLength(2);+ }+ });+ });+it('suppresses ordered list marker without content', () => {const state = createIncrementalState();const input = 'Intro\n\n1. ';diff --git a/packages/core/src/Markdown/parser.ts b/packages/core/src/Markdown/parser.tsindex ab06560edb..6c0215ab83 100644--- a/packages/core/src/Markdown/parser.ts+++ b/packages/core/src/Markdown/parser.ts@@ -1083,6 +1083,28 @@ function isHorizontalRule(line: string): boolean {return true;}+/**+ * Whether a line holds a pipe that could delimit table cells.+ *+ * A backslash-escaped `\|` is literal text inside one cell — `splitTableRow`+ * keeps it verbatim — so a line whose only pipes are escaped shows no partial+ * table syntax while it streams. Used by `trimUnsettledStructural` to decide+ * whether an unfinished trailing line is a table header worth holding back.+ */+function hasUnescapedPipe(line: string): boolean {+ for (let index = 0; index < line.length; index++) {+ if (line[index] === '\\') {+ // Skip the escaped character, whatever it is.+ index++;+ continue;+ }+ if (line[index] === '|') {+ return true;+ }+ }+ return false;+}+/** GFM separator row: cells contain only dashes/colons. */function isTableSeparator(line: string): boolean {if (!line.includes('|')) {@@ -1903,12 +1925,16 @@ function trimUnsettledStructural(text: string): string {}// Table: only suppress if this is a lone header without a separator.- // If the line has `|` and the line before it is NOT a separator,- // and THIS line is not a separator, and there's no established table- // above (header + separator pair), hold it back.- if (trimmed.includes('|') && !isTableSeparator(last)) {+ // If the line has an unescaped `|` and the line before it is NOT a+ // separator, and THIS line is not a separator, and there's no established+ // table above (header + separator pair), hold it back. An escaped `\|` is+ // ordinary prose, not a cell delimiter, so a line carrying only those is+ // never held back — holding it back blanks the text while it streams.+ if (hasUnescapedPipe(trimmed) && !isTableSeparator(last)) {// Is there a separator anywhere above that would make this part of- // an established table? Walk up to find header+separator pair.+ // an established table? Walk up to find header+separator pair. The+ // header test mirrors the block parser's own `includes('|')`, which+ // accepts an escaped-only header line once its separator arrives.let tableEstablished = false;for (let i = lines.length - 2; i >= 1; i--) {if (isTableSeparator(lines[i]) && lines[i - 1].includes('|')) {diff --git a/packages/vega/README.md b/packages/vega/README.mdindex 9010a460cf..5ea5094fe6 100644--- a/packages/vega/README.md+++ b/packages/vega/README.md@@ -17,6 +17,7 @@ Renders [Vega](https://vega.github.io/vega/) and [Vega-Lite](https://vega.github| `tsup.config.ts` | Config | Build config: CJS + ESM + `.d.ts` outputs || `src/index.ts` | Barrel | Public API surface || `src/VegaChart.tsx` | Component | Inspects `$schema`, compiles or renders, owns View lifecycle |+| `src/viewInputs.ts` | Utility | Detects value changes in the props that own the View || `src/schema.ts` | Utility | Parses and validates Vega/Vega-Lite `$schema` URLs || `src/types.ts` | Types | Shared TypeScript types for this package |@@ -133,9 +134,51 @@ import {VegaChart} from '@astryxdesign/vega';| -------------------- | --------- | --------------------------------------------------------- || `ast` | `boolean` | Retain expression AST in the runtime (useful for tooling) |+### View lifecycle++`<VegaChart>` builds a Vega `View` on mount and finalizes it on unmount. In+between, it rebuilds the View only when `spec`, `compileOptions`,+`parseConfig`, `parseOptions`, or `viewOptions` **changes value** — these props+are compared by value against the values the live View was built from, not by+reference. Two consequences, and you need neither `useMemo` nor a discipline+about object identity for either:++- an object literal rebuilt inline on every render does **not** tear the chart+ down;+- a spec you edit **in place** — held in a ref, a module constant, or shared+ between renders — **is** picked up, because the comparison is against a copy+ taken when the View was built, not against the previous props.++Functions inside those props (a `tooltip` handler, `logger`, `loader`, `expr`,+or `fieldTitle`) and class instances are compared by reference, since their+behavior lives in methods a copy cannot capture: replace the value rather than+mutating it.++Two shapes cannot be copied for comparison: a subtree that re-enters an object+already on its own path (a reference cycle), and one nested deeper than 100+levels. Those parts are compared **by reference**, so passing the **same**+object again is stable — a chart built from a cyclic spec is not rebuilt on+every render — while passing a **new** object rebuilds the View even when it+holds equal values.++What that costs differs between the two:++- **A cycle hides nothing.** Its re-entry edge points back at an object the+ copy already walked, so an in-place edit anywhere in a cyclic spec is still+ detected normally.+- **Past 100 levels, an in-place edit is invisible** — the reference did not+ change and the values below were never copied. Replace the object, or drive+ the View through `onReady`, to update from down there.++Everything the copy did reach is compared by value either way, so a mutation+elsewhere in the spec is picked up even when part of it is opaque.++Everything else is inert to the lifecycle: `data`, `className`, `style`,+`onReady`, and `onError` never rebuild the View.+### Data loading-`data` maps dataset names to tuple arrays and is applied via `view.data(name, tuples)` during View initialization, before the first render. It is _not reactive_; changes after mount are ignored.+`data` maps dataset names to tuple arrays and is applied via `view.data(name, tuples)` during View initialization, before the first render. It is _not reactive_; changes after mount are ignored, and a new `data` object never rebuilds the View by itself. (When something else rebuilds the View, the new View loads whatever `data` holds at that moment.)To update data dynamically after render, use `onReady` to get the live View and drive it yourself:diff --git a/packages/vega/src/VegaChart.test.tsx b/packages/vega/src/VegaChart.test.tsxindex c9fd6abcf0..7b9b3bfb09 100644--- a/packages/vega/src/VegaChart.test.tsx+++ b/packages/vega/src/VegaChart.test.tsx@@ -153,11 +153,15 @@ describe('VegaChart', () => {);});- it('tears down the old View and builds a new one when the spec identity changes', () => {+ it('tears down the old View and builds a new one when the spec changes', () => {const {rerender} = render(<VegaChart spec={VEGA_SPEC} />);expect(views).toHaveLength(1);- rerender(<VegaChart spec={{...VEGA_SPEC}} />);+ rerender(+ <VegaChart+ spec={{...VEGA_SPEC, background: 'red'} as unknown as AnySpec}+ />,+ );expect(views).toHaveLength(2);expect(views[0].finalize).toHaveBeenCalledTimes(1);@@ -166,6 +170,217 @@ describe('VegaChart', () => {});});+ // The View is the expensive thing this component owns, and rebuilding it+ // throws away the chart's zoom, hover, and signal state. So a rebuild+ // follows a change of value, not a change of object identity -- the+ // documented usage passes spec, options, and data as inline literals.+ describe('View rebuild policy', () => {+ it('keeps the View when a re-render passes an equal spec object', () => {+ const {rerender} = render(<VegaChart spec={VEGA_SPEC} />);+ expect(views).toHaveLength(1);++ rerender(<VegaChart spec={{...VEGA_SPEC}} />);++ expect(views).toHaveLength(1);+ expect(views[0].finalize).not.toHaveBeenCalled();+ expect(parseMock).toHaveBeenCalledTimes(1);+ });++ it('keeps the View when a re-render passes an equal options object', () => {+ const {rerender} = render(+ <VegaChart spec={VEGA_SPEC} viewOptions={{renderer: 'canvas'}} />,+ );++ rerender(+ <VegaChart spec={VEGA_SPEC} viewOptions={{renderer: 'canvas'}} />,+ );++ expect(views).toHaveLength(1);+ });++ it('rebuilds when an options value actually changes', () => {+ const {rerender} = render(+ <VegaChart spec={VEGA_SPEC} viewOptions={{renderer: 'canvas'}} />,+ );++ rerender(<VegaChart spec={VEGA_SPEC} viewOptions={{renderer: 'svg'}} />);++ expect(views).toHaveLength(2);+ expect(views[1].options).toMatchObject({renderer: 'svg'});+ });++ it('rebuilds when a function inside the options changes identity', () => {+ // Two tooltip handlers can look alike and behave differently, so+ // functions are compared by reference, not walked.+ const {rerender} = render(+ <VegaChart spec={VEGA_SPEC} viewOptions={{tooltip: () => {}}} />,+ );++ rerender(+ <VegaChart spec={VEGA_SPEC} viewOptions={{tooltip: () => {}}} />,+ );++ expect(views).toHaveLength(2);+ });++ // A caller that holds its spec in a ref or a module constant and edits it+ // in place leaves both renders pointing at the same object. Comparing+ // props to props sees nothing; the chart would keep rendering old data.+ it('rebuilds when a nested object shared across renders is mutated', () => {+ const encoding = {x: {field: 'a', type: 'ordinal'}};+ const specWith = () =>+ ({+ $schema: 'https://vega.github.io/schema/vega-lite/v5.json',+ mark: 'bar',+ encoding,+ }) as unknown as AnySpec;+ const {rerender} = render(<VegaChart spec={specWith()} />);+ expect(views).toHaveLength(1);++ encoding.x.field = 'b';+ rerender(<VegaChart spec={specWith()} />);++ expect(views).toHaveLength(2);+ expect(views[0].finalize).toHaveBeenCalledTimes(1);+ expect(compileMock.mock.calls[1][0]).toMatchObject({+ encoding: {x: {field: 'b'}},+ });+ });++ it('rebuilds when the very same spec object is mutated in place', () => {+ const spec = {+ $schema: 'https://vega.github.io/schema/vega/v6.json',+ marks: [] as unknown[],+ } as unknown as AnySpec;+ const {rerender} = render(<VegaChart spec={spec} />);++ (spec as unknown as {marks: unknown[]}).marks.push({type: 'rect'});+ rerender(<VegaChart spec={spec} />);++ expect(views).toHaveLength(2);+ });++ it('hands Vega the caller’s own spec object, not a copy', () => {+ render(<VegaChart spec={VEGA_SPEC} />);++ expect(parseMock.mock.calls[0][0]).toBe(VEGA_SPEC);+ });++ // A spec the comparison cannot copy — a reference cycle, or nesting past+ // its depth bound — is compared by reference instead. That verdict runs+ // during render, so an "always changed" answer would re-render forever+ // ("Too many re-renders") and never paint a chart at all.+ describe('inputs the comparison cannot copy', () => {+ function nest(depth: number): Record<string, unknown> {+ let node: Record<string, unknown> = {leaf: 'a'};+ for (let index = 0; index < depth; index++) {+ node = {node};+ }+ return node;+ }++ function cyclicSpec(): AnySpec {+ const spec: Record<string, unknown> = {+ $schema: 'https://vega.github.io/schema/vega/v6.json',+ marks: [],+ };+ spec.self = spec;+ return spec as unknown as AnySpec;+ }++ it('mounts a cyclic spec and builds exactly one View', () => {+ expect(() => render(<VegaChart spec={cyclicSpec()} />)).not.toThrow();++ expect(views).toHaveLength(1);+ });++ it('keeps the View across re-renders of the same cyclic spec', () => {+ const spec = cyclicSpec();+ const {rerender} = render(<VegaChart spec={spec} />);++ rerender(<VegaChart spec={spec} />);+ rerender(<VegaChart spec={spec} />);++ expect(views).toHaveLength(1);+ expect(views[0].finalize).not.toHaveBeenCalled();+ });++ it('rebuilds exactly once when the cyclic spec is replaced', () => {+ const {rerender} = render(<VegaChart spec={cyclicSpec()} />);+ const replacement = cyclicSpec();++ rerender(<VegaChart spec={replacement} />);+ rerender(<VegaChart spec={replacement} />);++ expect(views).toHaveLength(2);+ expect(views[0].finalize).toHaveBeenCalledTimes(1);+ });++ it('mounts a spec nested past the depth bound and keeps its View', () => {+ const spec = {+ $schema: 'https://vega.github.io/schema/vega/v6.json',+ deep: nest(150),+ } as unknown as AnySpec;++ const {rerender} = render(<VegaChart spec={spec} />);+ rerender(<VegaChart spec={spec} />);++ expect(views).toHaveLength(1);+ });++ it('still rebuilds on a shallow change beside a cycle', () => {+ const spec: Record<string, unknown> = {+ $schema: 'https://vega.github.io/schema/vega/v6.json',+ background: 'red',+ };+ spec.self = spec;+ const {rerender} = render(+ <VegaChart spec={spec as unknown as AnySpec} />,+ );++ spec.background = 'blue';+ rerender(<VegaChart spec={spec as unknown as AnySpec} />);++ expect(views).toHaveLength(2);+ });+ });++ // `data` is documented as initial values, read once per View. It used to+ // sit in the Effect's dependencies, so the documented usage -- an inline+ // `data={{table: rows}}` -- tore the View down on every parent render.+ it('keeps the View when only data changes', () => {+ const {rerender} = render(+ <VegaChart spec={VEGA_SPEC} data={{table: [{a: 1}]}} />,+ );+ expect(views).toHaveLength(1);+ expect(views[0].data).toHaveBeenCalledTimes(1);++ rerender(<VegaChart spec={VEGA_SPEC} data={{table: [{a: 2}]}} />);++ expect(views).toHaveLength(1);+ expect(views[0].finalize).not.toHaveBeenCalled();+ // Not reactive: the live View is left exactly as it was.+ expect(views[0].data).toHaveBeenCalledTimes(1);+ expect(views[0].data).toHaveBeenCalledWith('table', [{a: 1}]);+ });++ it('loads the current data when something else rebuilds the View', () => {+ const {rerender} = render(+ <VegaChart spec={VEGA_SPEC} data={{table: [{a: 1}]}} />,+ );++ rerender(+ <VegaChart+ spec={{...VEGA_SPEC, background: 'red'} as unknown as AnySpec}+ data={{table: [{a: 2}]}}+ />,+ );++ expect(views).toHaveLength(2);+ expect(views[1].data).toHaveBeenCalledWith('table', [{a: 2}]);+ });+ });+describe('error contract', () => {it('reports an unrecognized $schema through onError without constructing a View', () => {const onError = vi.fn();diff --git a/packages/vega/src/VegaChart.tsx b/packages/vega/src/VegaChart.tsxindex a031563e24..cbcdcf276b 100644--- a/packages/vega/src/VegaChart.tsx+++ b/packages/vega/src/VegaChart.tsx@@ -9,10 +9,12 @@* SYNC: When modified, update /packages/vega/README.md*/-import React, {useEffect, useEffectEvent, useRef} from 'react';+import React, {useEffect, useEffectEvent, useRef, useState} from 'react';import {parse, View} from 'vega';import {compile} from 'vega-lite';import {parseSchema} from './schema';+import {latchViewInputs, latchIsCurrent} from './viewInputs';+import type {ViewInputs} from './viewInputs';import type {VegaChartProps, VegaSpec, VegaLiteSpec} from './types';/**@@ -30,17 +32,24 @@ import type {VegaChartProps, VegaSpec, VegaLiteSpec} from './types';* new vega.View(runtime, { ...viewOptions, container })** Initial dataset values can be provided via `data`. They are loaded once- * during View initialization, before the first render, and are not reactive.+ * during View initialization, before the first render, and are not reactive:+ * a change to `data` alone never rebuilds the View, and is not applied to the+ * live one. Use `onReady` to drive data after mount.** It owns the full `View` lifecycle: creates the view on mount, re-creates- * it when `spec`, `parseConfig`, `parseOptions`, or `viewOptions` changes,- * and calls `view.finalize()` on cleanup to release all runtime resources.+ * it when `spec`, `compileOptions`, `parseConfig`, `parseOptions`, or+ * `viewOptions` changes, and calls `view.finalize()` on cleanup to release+ * all runtime resources.+ *+ * "Changes" means the value changed, not the reference: those props are+ * compared by value against a copy taken when the live View was built, so an+ * inline spec or options object rebuilt on every render keeps the live View+ * (and its zoom, hover, and signal state), while a spec mutated in place is+ * still picked up. Nothing needs to be memoized for either to hold.** Callbacks (`onReady`, `onError`) are non-reactive Effect Events -- they* always see the latest props and never re-run the View lifecycle, so you- * don't need to memoize them. Pass stable references (or `useMemo`)- * for `parseConfig`, `parseOptions`, `viewOptions`, and `data` to avoid- * unnecessary re-renders.+ * don't need to memoize them.** Note: this component does not accept `xstyle` because `@astryxdesign/vega` does not* depend on StyleX. Use `className` or `style` for layout overrides.@@ -87,6 +96,25 @@ export function VegaChart({}: VegaChartProps) {const containerRef = useRef<HTMLDivElement>(null);+ // Rebuild only when a value the runtime is built from actually differs.+ // The latch holds both the props the live View was built from and a copy of+ // their values, so a spec mutated in place is caught too -- comparing+ // against the previous props could not see that, because a mutation leaves+ // both sides pointing at the same object. Updating state during render is+ // React's own way to derive state from props; the check is reflexive, so it+ // settles in one extra pass.+ const inputs: ViewInputs = {+ spec,+ compileOptions,+ parseConfig,+ parseOptions,+ viewOptions,+ };+ const [latch, setLatch] = useState(() => latchViewInputs(inputs));+ if (!latchIsCurrent(latch, inputs)) {+ setLatch(latchViewInputs(inputs));+ }+// The Effect fires these callbacks without treating them as reactive// dependencies, so the View isn't torn down and rebuilt when a parent// passes fresh inline callbacks on every render.@@ -97,12 +125,30 @@ export function VegaChart({onErrorProp?.(error);});+ // Same treatment for `data`: an Effect Event reads the latest value at View+ // initialization without making `data` a reactive dependency. That is the+ // documented contract -- initial dataset values, applied once per View,+ // never reactive -- and it keeps a fresh `data` object literal from tearing+ // down a perfectly good View on every parent render.+ const loadInitialData = useEffectEvent((view: View) => {+ if (!data) {+ return;+ }+ for (const [name, tuples] of Object.entries(data)) {+ view.data(name, tuples);+ }+ });+useEffect(() => {const container = containerRef.current;if (!container) {return;}+ // Read from the latch, never the props: these are the values the live+ // View is built from, and they only change when a value changes. The+ // caller's own objects are handed to Vega, not the comparison copy.+ const {spec} = latch.inputs;let cancelled = false;let view: View | null = null;@@ -123,26 +169,26 @@ export function VegaChart({// Compile Vega-Lite -> Vega if needed; otherwise use the spec directly.const vegaSpec: VegaSpec =schemaResult.library === 'vega-lite'- ? compile(spec as VegaLiteSpec, compileOptions).spec+ ? compile(spec as VegaLiteSpec, latch.inputs.compileOptions).spec: (spec as VegaSpec);// parse(spec, config?, options?) -> Runtime- const runtime = parse(vegaSpec, parseConfig, parseOptions);+ const runtime = parse(+ vegaSpec,+ latch.inputs.parseConfig,+ latch.inputs.parseOptions,+ );// new View(runtime, viewOptions) -- container is always injected by us.view = new View(runtime, {hover: true,- ...viewOptions,+ ...latch.inputs.viewOptions,container,});// Load initial data into named datasets before the first render.// data is not reactive -- changes after mount are ignored.- if (data) {- for (const [name, tuples] of Object.entries(data)) {- view.data(name, tuples);- }- }+ loadInitialData(view);view.runAsync()@@ -164,7 +210,7 @@ export function VegaChart({cancelled = true;view?.finalize();};- }, [spec, data, compileOptions, parseConfig, parseOptions, viewOptions]);+ }, [latch]);return (<divdiff --git a/packages/vega/src/viewInputs.test.ts b/packages/vega/src/viewInputs.test.tsnew file mode 100644index 0000000000..2c0934932d--- /dev/null+++ b/packages/vega/src/viewInputs.test.ts@@ -0,0 +1,297 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file viewInputs.test.ts+ * @input Uses vitest, latchViewInputs and latchIsCurrent+ * @output Unit tests for the View-lifecycle change detector+ * @position Colocated test for viewInputs.ts+ */++import {describe, it, expect} from 'vitest';+import {latchViewInputs, latchIsCurrent} from './viewInputs';+import type {ViewInputs} from './viewInputs';+import type {AnySpec} from './types';++function inputs(overrides: Partial<ViewInputs> = {}): ViewInputs {+ return {+ spec: {+ $schema: 'https://vega.github.io/schema/vega/v6.json',+ marks: [],+ } as unknown as AnySpec,+ ...overrides,+ };+}++describe('latchIsCurrent', () => {+ it('holds when the same values arrive as fresh object literals', () => {+ const latch = latchViewInputs(inputs({viewOptions: {renderer: 'canvas'}}));++ expect(+ latchIsCurrent(latch, inputs({viewOptions: {renderer: 'canvas'}})),+ ).toBe(true);+ });++ it('holds for the very objects it latched', () => {+ const current = inputs({parseConfig: {background: 'red'}});++ expect(latchIsCurrent(latchViewInputs(current), current)).toBe(true);+ });++ it('breaks when a value differs', () => {+ const latch = latchViewInputs(inputs({viewOptions: {renderer: 'canvas'}}));++ expect(+ latchIsCurrent(latch, inputs({viewOptions: {renderer: 'svg'}})),+ ).toBe(false);+ });++ it('breaks when a key is added or removed', () => {+ const latch = latchViewInputs(inputs({parseConfig: {background: 'red'}}));++ expect(+ latchIsCurrent(+ latch,+ inputs({parseConfig: {background: 'red', autosize: 'pad'}}),+ ),+ ).toBe(false);+ expect(latchIsCurrent(latch, inputs({parseConfig: {}}))).toBe(false);+ });++ // The reason the latch keeps a copy rather than the previous props: on a+ // mutation both sides are the same object, so a props-to-props comparison+ // has nothing left to notice and the chart silently goes stale.+ describe('mutation through a shared reference', () => {+ it('breaks when a nested object shared across renders is mutated', () => {+ const encoding = {x: {field: 'a', type: 'ordinal'}};+ const latch = latchViewInputs(+ inputs({+ spec: {+ $schema: 'https://vega.github.io/schema/vega-lite/v5.json',+ mark: 'bar',+ encoding,+ } as unknown as AnySpec,+ }),+ );++ encoding.x.field = 'b';++ expect(+ latchIsCurrent(+ latch,+ inputs({+ spec: {+ $schema: 'https://vega.github.io/schema/vega-lite/v5.json',+ mark: 'bar',+ encoding,+ } as unknown as AnySpec,+ }),+ ),+ ).toBe(false);+ });++ it('breaks when the latched spec itself is mutated in place', () => {+ const spec = {+ $schema: 'https://vega.github.io/schema/vega-lite/v5.json',+ mark: 'bar',+ } as unknown as AnySpec;+ const latch = latchViewInputs(inputs({spec}));++ (spec as unknown as {mark: string}).mark = 'line';++ expect(latchIsCurrent(latch, inputs({spec}))).toBe(false);+ });++ it('breaks when an element is pushed onto a shared array', () => {+ const marks: unknown[] = [{type: 'rect'}];+ const latch = latchViewInputs(+ inputs({spec: {$schema: 'x', marks} as unknown as AnySpec}),+ );++ marks.push({type: 'line'});++ expect(+ latchIsCurrent(+ latch,+ inputs({spec: {$schema: 'x', marks} as unknown as AnySpec}),+ ),+ ).toBe(false);+ });+ });++ describe('values compared by reference', () => {+ it('holds for the same function and breaks for an equivalent one', () => {+ const tooltip = () => {};+ const latch = latchViewInputs(inputs({viewOptions: {tooltip}}));++ expect(latchIsCurrent(latch, inputs({viewOptions: {tooltip}}))).toBe(+ true,+ );+ expect(+ latchIsCurrent(latch, inputs({viewOptions: {tooltip: () => {}}})),+ ).toBe(false);+ });++ it('treats a class instance as opaque, mutation included', () => {+ class Loader {+ base = 'a';+ }+ const loader = new Loader();+ const latch = latchViewInputs(inputs({viewOptions: {loader} as never}));++ // Documented limit: behavior lives in methods a copy cannot capture,+ // so only the reference is compared.+ loader.base = 'b';+ expect(+ latchIsCurrent(latch, inputs({viewOptions: {loader} as never})),+ ).toBe(true);+ expect(+ latchIsCurrent(+ latch,+ inputs({viewOptions: {loader: new Loader()} as never}),+ ),+ ).toBe(false);+ });+ });++ it('is stable for a self-referencing spec passed by the same reference', () => {+ const spec: Record<string, unknown> = {$schema: 'x'};+ spec.self = spec;+ const latch = latchViewInputs(inputs({spec: spec as unknown as AnySpec}));++ // A cycle cannot be copied, so the reference is compared. Stable — an+ // "always changed" verdict here loops React during render.+ expect(+ latchIsCurrent(latch, inputs({spec: spec as unknown as AnySpec})),+ ).toBe(true);+ });++ it('breaks once when a self-referencing spec is replaced', () => {+ const first: Record<string, unknown> = {$schema: 'x'};+ first.self = first;+ const second: Record<string, unknown> = {$schema: 'x'};+ second.self = second;+ const latch = latchViewInputs(inputs({spec: first as unknown as AnySpec}));++ expect(+ latchIsCurrent(latch, inputs({spec: second as unknown as AnySpec})),+ ).toBe(false);+ // And the new latch settles on the new reference rather than churning.+ const next = latchViewInputs(inputs({spec: second as unknown as AnySpec}));+ expect(+ latchIsCurrent(next, inputs({spec: second as unknown as AnySpec})),+ ).toBe(true);+ });++ it('still sees a mutation beside a cycle', () => {+ const spec: Record<string, unknown> = {$schema: 'x', mark: 'bar'};+ spec.self = spec;+ const latch = latchViewInputs(inputs({spec: spec as unknown as AnySpec}));++ // The cycle is opaque; everything the copy did reach is still compared.+ spec.mark = 'line';++ expect(+ latchIsCurrent(latch, inputs({spec: spec as unknown as AnySpec})),+ ).toBe(false);+ });++ // A cycle's re-entry edge always points back at an object the copy has+ // already walked, so the cycle itself hides nothing — worth pinning,+ // because the depth boundary below behaves differently.+ it('sees a mutation on an object that also sits on a cycle', () => {+ const nested: Record<string, unknown> = {field: 'a'};+ const spec: Record<string, unknown> = {$schema: 'x', nested};+ nested.parent = spec;+ const latch = latchViewInputs(inputs({spec: spec as unknown as AnySpec}));++ nested.field = 'b';++ expect(+ latchIsCurrent(latch, inputs({spec: spec as unknown as AnySpec})),+ ).toBe(false);+ });++ it('walks the same object twice in sibling positions', () => {+ const shared = {field: 'a'};+ const spec = () =>+ ({$schema: 'x', x: shared, y: shared}) as unknown as AnySpec;+ const latch = latchViewInputs(inputs({spec: spec()}));++ // Sharing is not a cycle: both positions are copied, so a mutation of+ // the shared object is caught.+ expect(latchIsCurrent(latch, inputs({spec: spec()}))).toBe(true);+ shared.field = 'b';+ expect(latchIsCurrent(latch, inputs({spec: spec()}))).toBe(false);+ });++ describe('deeper than the copy walks', () => {+ /** A chain of `depth` nested objects ending in `leaf`. */+ function nest(depth: number, leaf: unknown): Record<string, unknown> {+ let node: Record<string, unknown> = {leaf} as Record<string, unknown>;+ for (let index = 0; index < depth; index++) {+ node = {node};+ }+ return node;+ }++ it('is stable for a too-deep spec passed by the same reference', () => {+ const deep = nest(150, 'a');+ const spec = {$schema: 'x', deep} as unknown as AnySpec;+ const latch = latchViewInputs(inputs({spec}));++ expect(latchIsCurrent(latch, inputs({spec}))).toBe(true);+ });++ it('breaks when the too-deep subtree is replaced by a new object', () => {+ const spec = () =>+ ({$schema: 'x', deep: nest(150, 'a')}) as unknown as AnySpec;+ const latch = latchViewInputs(inputs({spec: spec()}));++ // Beyond the bound the reference is all there is, so an equal-valued+ // rebuild counts as changed — a rebuild, never a stale chart.+ expect(latchIsCurrent(latch, inputs({spec: spec()}))).toBe(false);+ });++ it('does not see a mutation only reachable past the depth bound', () => {+ const deep = nest(150, 'a');+ const spec = {$schema: 'x', deep} as unknown as AnySpec;+ const latch = latchViewInputs(inputs({spec}));++ // Walk to the far end and edit it in place. Past the bound only the+ // reference is compared, and it did not change — the documented+ // limitation, and why a caller replaces the object instead.+ let node = deep;+ while (node.node) {+ node = node.node as Record<string, unknown>;+ }+ node.leaf = 'b';++ expect(latchIsCurrent(latch, inputs({spec}))).toBe(true);+ });++ it('still sees a shallow mutation beside a too-deep subtree', () => {+ const deep = nest(150, 'a');+ const spec: Record<string, unknown> = {+ $schema: 'x',+ mark: 'bar',+ deep,+ };+ const latch = latchViewInputs(inputs({spec: spec as unknown as AnySpec}));++ spec.mark = 'line';++ expect(+ latchIsCurrent(latch, inputs({spec: spec as unknown as AnySpec})),+ ).toBe(false);+ });+ });++ it('distinguishes absent from present optional inputs', () => {+ const latch = latchViewInputs(inputs());++ expect(latchIsCurrent(latch, inputs())).toBe(true);+ expect(latchIsCurrent(latch, inputs({parseOptions: {ast: true}}))).toBe(+ false,+ );+ });+});diff --git a/packages/vega/src/viewInputs.ts b/packages/vega/src/viewInputs.tsnew file mode 100644index 0000000000..b1dfe88ea0--- /dev/null+++ b/packages/vega/src/viewInputs.ts@@ -0,0 +1,187 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file viewInputs.ts+ * @input The VegaChart props that own the Vega View lifecycle+ * @output The ViewInputs type plus latch/compare helpers VegaChart rebuilds on+ * @position Internal utility; used by VegaChart to decide when to rebuild+ *+ * SYNC: When modified, update /packages/vega/README.md+ */++import type {VegaChartProps} from './types';++/**+ * The props the Vega runtime is built from. A change to any of them produces+ * a different runtime, so the View is torn down and rebuilt. `data`,+ * `className`, `style`, and the callbacks are absent because none of them+ * change the runtime.+ */+export type ViewInputs = Pick<+ VegaChartProps,+ 'spec' | 'compileOptions' | 'parseConfig' | 'parseOptions' | 'viewOptions'+>;++/**+ * The inputs the live View was built from, beside a structural copy of their+ * values at that moment.+ *+ * The copy is the whole point. Comparing the incoming props against the+ * *previous props* cannot see a spec mutated in place — both sides are the+ * same object, so the old value is already gone and the chart silently goes+ * stale. Comparing against a copy taken when the View was built can.+ *+ * The copy is also compared during render, so its verdict must be stable for+ * an unchanged input: a part that always reported "changed" would loop React+ * forever. See {@link Opaque} for the parts that cannot be copied.+ */+export type ViewInputsLatch = {+ /** The caller's own objects, handed to Vega untouched. */+ readonly inputs: ViewInputs;+ readonly snapshot: unknown;+};++/**+ * Deepest structure the copy walks. Vega and Vega-Lite specs nest far+ * shallower; the bound exists so a pathological input cannot make the walk+ * cost unbounded. Anything deeper is kept by reference (see {@link Opaque}).+ */+const MAX_DEPTH = 100;++/**+ * Stands in for a value the copy would not walk: a subtree deeper than+ * {@link MAX_DEPTH}, or one that re-enters an object already on the path (a+ * reference cycle).+ *+ * It keeps the reference it stood for, and that is the whole design. An+ * opaque part that always compared unequal would make `latchIsCurrent` false+ * on every render — and since the latch is refreshed during render, React+ * would re-render forever ("Too many re-renders"). Comparing the reference+ * instead is stable while the caller passes the same object, and rebuilds+ * exactly once when they pass a different one.+ *+ * What the narrowing costs differs by case. A cycle's re-entry edge points+ * back at an object the walk already copied, so a cyclic spec still has every+ * mutation detected. Past {@link MAX_DEPTH} the values below were never+ * copied, so an in-place edit down there is invisible until the caller passes+ * a different object — documented in the package README.+ */+type Opaque = {readonly [OPAQUE]: unknown};++const OPAQUE = Symbol('astryx.vega.opaque');++function opaque(value: unknown): Opaque {+ return {[OPAQUE]: value};+}++function isOpaque(value: unknown): value is Opaque {+ return typeof value === 'object' && value !== null && OPAQUE in value;+}++export function latchViewInputs(inputs: ViewInputs): ViewInputsLatch {+ return {inputs, snapshot: snapshotValue(inputs, 0, new Set())};+}++/**+ * Whether `inputs` still carries the values the latched View was built from.+ *+ * Plain objects and arrays are compared entry by entry, so a spec or options+ * bag rebuilt inline on every render counts as unchanged. Everything else --+ * functions (tooltip handlers, loggers, loaders, field-title formatters),+ * class instances, dates -- compares by reference, because two instances can+ * behave differently even when they look alike, and the View built from them+ * would too.+ */+export function latchIsCurrent(+ latch: ViewInputsLatch,+ inputs: ViewInputs,+): boolean {+ return matchesSnapshot(latch.snapshot, inputs);+}++/**+ * Copy the plain-object structure of `value`, keeping everything else by+ * reference. Not a general-purpose clone: it exists only so a later+ * comparison has the old values to look at.+ *+ * `path` holds the objects currently being walked, so re-entering one is+ * recognized as a cycle and kept by reference rather than followed.+ */+function snapshotValue(+ value: unknown,+ depth: number,+ path: Set<unknown>,+): unknown {+ if (!isWalkable(value)) {+ return value;+ }+ if (depth >= MAX_DEPTH || path.has(value)) {+ return opaque(value);+ }+ path.add(value);+ const copy = Array.isArray(value)+ ? value.map(item => snapshotValue(item, depth + 1, path))+ : Object.fromEntries(+ Object.entries(value).map(([key, entry]) => [+ key,+ snapshotValue(entry, depth + 1, path),+ ]),+ );+ // Only an ancestor is a cycle; the same object twice in sibling positions+ // is ordinary sharing and is walked both times.+ path.delete(value);+ return copy;+}++/**+ * Compare a value against a snapshot. The walk is guided by the snapshot,+ * which is finite and acyclic by construction, so a cyclic `value` cannot+ * make this recurse forever.+ */+function matchesSnapshot(snapshot: unknown, value: unknown): boolean {+ if (isOpaque(snapshot)) {+ // Could not be walked, so the reference is all there is to compare.+ return Object.is(snapshot[OPAQUE], value);+ }+ if (Array.isArray(snapshot)) {+ return (+ Array.isArray(value) &&+ snapshot.length === value.length &&+ snapshot.every((item, index) => matchesSnapshot(item, value[index]))+ );+ }+ if (isPlainObject(snapshot)) {+ if (!isPlainObject(value)) {+ return false;+ }+ const keys = Object.keys(snapshot);+ return (+ keys.length === Object.keys(value).length &&+ keys.every(+ key =>+ Object.prototype.hasOwnProperty.call(value, key) &&+ matchesSnapshot(snapshot[key], value[key]),+ )+ );+ }+ // Primitives (Object.is also pairs both `undefined`s and both `NaN`s), and+ // every value compared by reference.+ return Object.is(snapshot, value);+}++function isWalkable(value: unknown): value is Record<string, unknown> {+ return Array.isArray(value) || isPlainObject(value);+}++/**+ * A `{...}` object literal or a null-prototype object -- the shapes a spec,+ * config, or options bag is made of. Class instances are excluded on purpose:+ * their behavior lives in methods a structural copy cannot capture.+ */+function isPlainObject(value: unknown): value is Record<string, unknown> {+ if (typeof value !== 'object' || value === null) {+ return false;+ }+ const proto = Object.getPrototypeOf(value);+ return proto === Object.prototype || proto === null;+}diff --git a/vitest.config.ts b/vitest.config.tsindex 48f6df6605..c9f2cf8f9a 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -93,12 +93,18 @@ export default defineConfig({// transform, and the jest-dom setup; inherit all of that from// the root config via `extends: true`.// - `node` = everything else (CLI, build tooling, scripts, internal- // utils) — no DOM, no StyleX/babel transform, no jest-dom+ // utils, and app-level suites that need no DOM) — no DOM, no+ // StyleX/babel transform, no jest-dom// matchers. Deliberately does NOT extend the root config so it// runs in a plain node environment and skips the per-file jsdom// instantiation that dominated these files' runtime. A new// package lands in `node` by default; if its tests need the DOM// they fail loudly there — move it into the `ui` include list.+ //+ // An app or package that carries its OWN vitest config is invisible to both+ // projects, so its tests belong to no CI job: `pnpm test` runs this file and+ // nothing else. Add the suite to an include list here instead of giving it a+ // second config to be run by.projects: [{extends: true,@@ -123,6 +129,24 @@ export default defineConfig({{// forks pool (vitest default) is required here: several CLI tests call// process.chdir(), which worker threads do not support.+ // This project does NOT extend the root config, so it carries its own+ // `resolve` — the root's aliases do not reach it.+ resolve: {+ alias: [+ // Theme packages resolve to `dist/`, which no test run builds. The+ // sandbox palette suite reads their palettes as a reference corpus,+ // so point the BARE specifier at the authored source. Subpath+ // imports (`/built`, `/theme.css`) are untouched and still need a+ // real build.+ {+ find: /^@astryxdesign\/theme-([a-z0-9-]+)$/,+ replacement: path.join(+ rootDir,+ 'packages/themes/$1/src/source.ts',+ ),+ },+ ],+ },test: {name: 'node',globals: true,@@ -153,6 +177,9 @@ export default defineConfig({// Storybook config invariants (no DOM needed) — e.g. the// workspace source-alias guard in .storybook/main.test.ts.'apps/storybook/.storybook/**/*.test.{ts,tsx,mjs}',+ // Sandbox page logic (palette generation, colour maths) — pure+ // modules with no DOM, so they run here rather than in `ui`.+ 'apps/sandbox/src/**/*.test.{ts,tsx,mjs}',],exclude: [...configDefaults.exclude,