@chemx/starter-kit 26.10.4-235 → 26.10.8-344

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/AGENTS.md +495 -0
  2. package/blueprints/molecule-capsule/m-sample-card.svelte +1 -1
  3. package/blueprints/molecule-capsule/m-sample-card.vue +1 -1
  4. package/cli/audit/ai-slop-detector.js +29 -1
  5. package/cli/audit/ast-visitors.js +116 -1
  6. package/cli/audit/audit-summary.js +30 -0
  7. package/cli/audit/gate-verdict.js +30 -0
  8. package/cli/audit/history.js +47 -10
  9. package/cli/audit/ratchet.js +64 -0
  10. package/cli/audit/rules-predicates.js +200 -0
  11. package/cli/audit/rules-registry.js +25 -0
  12. package/cli/audit-scope.js +44 -0
  13. package/cli/build/detector.js +0 -2
  14. package/cli/commands/cmd-audit.js +58 -11
  15. package/cli/commands/cmd-router.js +38 -1
  16. package/cli/commands/cmd-wrappers.js +322 -0
  17. package/cli/commands-schema.js +101 -9
  18. package/cli/errors/catcher.js +46 -3
  19. package/cli/help.js +41 -0
  20. package/cli/host-shims.js +77 -0
  21. package/cli/index.js +6 -0
  22. package/cli/installer.js +4 -44
  23. package/cli/mcp/antigravity.js +12 -5
  24. package/cli/mcp/call-scope.js +93 -0
  25. package/cli/mcp/index.js +6 -2
  26. package/cli/mcp/manifests.js +32 -26
  27. package/cli/mcp/server.js +26 -27
  28. package/cli/mcp/tools-audit.js +27 -11
  29. package/cli/mcp/tools-search-util.js +1 -10
  30. package/cli/mcp/tools-team-tasks.js +6 -4
  31. package/cli/mcp/tools.js +53 -8
  32. package/cli/navigator-actions.js +1 -1
  33. package/cli/navigator-banner-helpers.js +15 -5
  34. package/cli/navigator-banner.js +2 -9
  35. package/cli/navigator-guide.js +2 -2
  36. package/cli/path-scope.js +1 -1
  37. package/cli/pillars-schema.js +8 -82
  38. package/cli/pillars-wizard.js +56 -44
  39. package/cli/pillars-write-guard.js +52 -0
  40. package/cli/reader-markdown.js +26 -0
  41. package/cli/reader.js +89 -12
  42. package/cli/scaffold-frameworks.js +29 -0
  43. package/cli/scaffold.js +2 -10
  44. package/cli/search-commands.js +96 -0
  45. package/cli/search-db.js +11 -2
  46. package/cli/search-schema.js +22 -9
  47. package/cli/search.js +51 -50
  48. package/cli/team/task-list-view.js +43 -0
  49. package/cli/team/team-commands.js +11 -6
  50. package/cli/team/team-flags.js +1 -0
  51. package/cli/team/team-format.js +4 -2
  52. package/cli/verify.js +33 -15
  53. package/package.json +10 -5
  54. package/cli/audit/autofix.spec.js +0 -85
  55. package/cli/audit/clone-detector.spec.js +0 -46
  56. package/cli/audit/csharp-analyzer.spec.js +0 -216
  57. package/cli/audit/pattern-detector.spec.js +0 -113
  58. package/cli/audit/prompts.spec.js +0 -367
  59. package/cli/audit/rules.spec.js +0 -361
  60. package/cli/audit/social-git.spec.js +0 -71
  61. package/cli/audit/structural-weight.spec.js +0 -116
  62. package/cli/audit-preflight.spec.js +0 -115
  63. package/cli/audit-stages.spec.js +0 -30
  64. package/cli/blast-radius.spec.js +0 -113
  65. package/cli/build/detector.spec.js +0 -81
  66. package/cli/columnar.spec.js +0 -49
  67. package/cli/config/config.spec.js +0 -51
  68. package/cli/config.spec.js +0 -1
  69. package/cli/create.spec.js +0 -291
  70. package/cli/embeddings.spec.js +0 -92
  71. package/cli/errors/errors.spec.js +0 -163
  72. package/cli/exploder.spec.js +0 -99
  73. package/cli/friction-fixes.spec.js +0 -96
  74. package/cli/generator-compact.spec.js +0 -104
  75. package/cli/generator-framework.spec.js +0 -315
  76. package/cli/generator-jig.spec.js +0 -148
  77. package/cli/generator-templates/archetypes/vector-matcher.spec.js +0 -25
  78. package/cli/generator-templates.spec.js +0 -187
  79. package/cli/generator.spec.js +0 -288
  80. package/cli/help.spec.js +0 -109
  81. package/cli/installer.spec.js +0 -72
  82. package/cli/languages.spec.js +0 -65
  83. package/cli/mcp/installer.spec.js +0 -118
  84. package/cli/mcp/server.spec.js +0 -710
  85. package/cli/mcp/tools-project.spec.js +0 -51
  86. package/cli/mutators.spec.js +0 -176
  87. package/cli/navigator-banner.spec.js +0 -68
  88. package/cli/patcher.spec.js +0 -190
  89. package/cli/path-traversal.spec.js +0 -242
  90. package/cli/pillars.spec.js +0 -138
  91. package/cli/polyglot.spec.js +0 -222
  92. package/cli/project-detector.spec.js +0 -123
  93. package/cli/reader-logic.spec.js +0 -160
  94. package/cli/reader-shorthand.spec.js +0 -60
  95. package/cli/search-bulletproof.spec.js +0 -104
  96. package/cli/search-queries-hotspot-graph.spec.js +0 -66
  97. package/cli/search-queries-similar.spec.js +0 -43
  98. package/cli/search.spec.js +0 -294
  99. package/cli/team/team-adversarial-locks.spec.js +0 -176
  100. package/cli/team/team-adversarial-telemetry.spec.js +0 -93
  101. package/cli/team/team-concurrency-stress.spec.js +0 -95
  102. package/cli/team/team-lock-concurrency.spec.js +0 -182
  103. package/cli/team/team-mailbox-empirical.spec.js +0 -191
  104. package/cli/team/team-mailbox.spec.js +0 -93
  105. package/cli/team/team-memory.spec.js +0 -123
  106. package/cli/team/team-multi-model-telemetry.spec.js +0 -80
  107. package/cli/team/team-multiprocess-concurrency.spec.js +0 -193
  108. package/cli/team/team-projects.spec.js +0 -116
  109. package/cli/team/team-release-train.spec.js +0 -91
  110. package/cli/team/team-tasks-asana.spec.js +0 -60
  111. package/cli/team/team-tasks-hierarchy.spec.js +0 -176
  112. package/cli/team/team-vds.spec.js +0 -125
  113. package/cli/team/team-verification-gate.spec.js +0 -280
  114. package/cli/team/team.spec.js +0 -574
  115. package/cli/tesseract.spec.js +0 -55
  116. package/cli/trace.spec.js +0 -92
  117. package/cli/trend.spec.js +0 -51
  118. package/cli/ui-canonical-routes.spec.js +0 -130
  119. package/cli/ui-direct-routes.spec.js +0 -55
  120. package/cli/ui-e2e-verification.spec.js +0 -197
  121. package/cli/ui-filetree.spec.js +0 -175
  122. package/cli/ui-kanban.spec.js +0 -217
  123. package/cli/ui-sse.spec.js +0 -100
  124. package/cli/ui-vbulletin.spec.js +0 -188
  125. package/cli/ui-workbench-dbstudio.spec.js +0 -172
  126. package/cli/ui.spec.js +0 -312
  127. package/cli/verify-lint.spec.js +0 -44
  128. package/cli/verify.spec.js +0 -211
package/AGENTS.md ADDED
@@ -0,0 +1,495 @@
1
+ # Chemical X Molecular Architecture Directives
2
+
3
+ > *"Clean, literate code that reads like poetry to both humans and AI."*
4
+ > Mandatory architectural directives for AI agents operating on this repository. Strictly enforce these standards on every code generation, refactor, and review pass.
5
+
6
+ ---
7
+
8
+ ## ⚡ Quick Agent Reflex Table (Token-Bounded Commands)
9
+ | Standard Reflex | Chemical X (`cx`) Equivalent | Token & Architecture Advantage |
10
+ | :--- | :--- | :--- |
11
+ | `grep -rn "pattern" .` | `cx q -g "pattern"` or `cx q -g "pattern" -l` | Auto-ignores build/vendor; clamps lines to 60 chars or line-only (-l). |
12
+ | `git diff` | `cx d` | Zero-context (`-U0`), auto-collapses to `--stat` if > 80 lines, micro-syncs index. |
13
+ | `git log` | `cx log -n 5` | Single-line compact commit history (~8 tokens/commit). |
14
+ | `find . -name "*.vue"` | `cx f "*.vue"` | Strictly filters by `.gitignore` and ignored dirs. |
15
+ | `cat package.json` | `cx p -s` / `cx p <script>` | Instant single script or dep extraction (~3 tokens vs 300 lines). |
16
+ | `cat <data.json>` | `cx j <file.json>` | Structural schema shape only; collapses repeating arrays. |
17
+ | `cat <file>` / `head <file>` | `cx read <file> --outline` | AST signatures only (~50 tokens vs thousands). |
18
+ | `npm test` / `tsc` | `cx test` / `cx verify` | Silent on success; returns only failing diffs. |
19
+ | Multiple CLI actions | `cx do "<cmd1>" "<cmd2>"` | Executes sequentially in a single warm Node process. |
20
+ | Multiple MCP tool calls | `chemx({ commands: [...] })` | Executes multiple sub-operations in a single agent turn. |
21
+
22
+ ---
23
+
24
+ ## 1. The Molecular Architecture Protocol
25
+
26
+ ### A. Structural Weight, Cognitive Cohesion & Profile Architecture
27
+ - **The Pragmatic Staff Engineer Paradigm (Default)**: Chemical X audits **Structural Weight and Responsibility Density**, not arbitrary mechanical line caps. A cohesive 140-line table, modal, or canvas wrapper where state and layout are naturally co-located is far cleaner and more reliable for LLMs to edit than six fractured micro-files connected by prop-drilling. Slicing cohesive logic into artificial files just to appease a counter is an anti-pattern: *indirection masquerading as modularity*.
28
+ - **Structural Weight Limits (Pragmatic Default)**:
29
+ - **Cyclomatic Complexity**: Max 12 decision points per component/hook.
30
+ - **Hook & State Density**: Max 4 independent hooks/state setters before extracting into a domain hook or reducer.
31
+ - **Render Tree Depth**: Max 4 nesting levels in JSX/templates; nested ternaries are strictly banned in favor of computed descriptor objects.
32
+ - **Prop Surface Area**: Max 7 flat props before grouping into a typed domain entity model.
33
+ - **Line Budget**: Soft warning at 250 lines only if cyclomatic complexity is high.
34
+ - **Atomic-Strict Profile (`--profile=atomic-strict`)**: Opt-in strict mode enforcing 100-line capsule caps and mandatory atomization for teams building foundational design system component primitives.
35
+ - **The Rule of Three for Abstractions**: Premature abstraction is worse than duplication. Do NOT extract an atom or molecule until a pattern is reused across 3+ distinct features, or until it encapsulates isolated behavioral/accessibility requirements.
36
+
37
+ ### B. Table-of-Contents Views
38
+ - Top-level page views MUST NEVER contain hundreds of lines of nested DOM scaffolding.
39
+ - A view template MUST read like a clean, 10 to 20 line declarative Table of Contents assembling self-contained molecules and organisms via named slot templates (`#header`, `#default`, `#modals`).
40
+
41
+ ### C. Crystalline Molecule Capsules
42
+ - Every molecule and organism lives in an isolated, self-contained directory capsule:
43
+ ```
44
+ m-<feature>-card/
45
+ ├── m-<feature>-card.<ext> (< 100 lines: declarative layout & bindings)
46
+ ├── m-<feature>-card.controller.ts (pure reactive state & 2-stage booleans)
47
+ ├── _m-<feature>-card.scss (mixin-only glass styling)
48
+ ├── types.d.ts (pure Props & Emits declarations)
49
+ └── index.ts (clean public entrypoint)
50
+ ```
51
+
52
+ ### D. Anti-Prop-Drilling & Domain State
53
+ - Never pass 10+ props or chained event bubbles across component tiers.
54
+ - Encapsulate shared feature state in dedicated domain composables/hooks, scoped stores, or typed provide/inject.
55
+ - Child components consume state directly from the domain composable and emit minimal, intention-revealing semantic events.
56
+
57
+ ### E. Idiomatic Shorthand Binding
58
+ Use same-name shorthand across all languages; eliminate redundant `key: key` duplication:
59
+ - **JS / TS / Rust Data Structures**: `{ foo, bar }` over `{ foo: foo, bar: bar }`.
60
+ - **Vue 3.4+ & Svelte 5 Templates**: `<Comp :prop />` or `<Comp {prop} />` over `:prop="prop"`.
61
+ - **React / JSX Exception**: Explicit `prop={prop}` (bare `<Comp prop />` coerces to boolean `true`).
62
+
63
+ ### F. Pre-Split Pattern Discovery & Harmonization Protocol
64
+ - **Survey Before Slicing**: Before decomposing any monolithic file or collection of files, the AI must first conduct a cross-file pattern discovery audit across all candidate monoliths.
65
+ - **Identify Recurring Structures**: Map shared UI layouts, duplicate controllers, repeated predicates, common state machines, and mirrored type definitions across files before writing any split code.
66
+ - **Map to Existing Foundations**: Check the design system, shared atom catalog (`x-*`), central composables, and core utilities first. Never invent a bespoke one-off atom or utility if an equivalent foundation exists.
67
+ - **Canonical Extraction First**: Consolidate and extract shared atoms, molecules, or composables once into canonical capsules before splitting consumer monoliths.
68
+ - **Zero Bespoke Pattern Proliferation**: Decompose consumer monoliths by binding directly to the extracted canonical capsules, preventing the proliferation of duplicate, slightly divergent patterns across spliced views.
69
+
70
+ ### G. Component Encapsulation, Semantic Integrity & The Zero-Raw-DOM Scope
71
+ - **Pragmatic Profile (Default)**: Wrapping every native `<button>`, `<input>`, or `<a>` in a trivial single-line atom creates pointless wrapper boilerplate. In Pragmatic mode, native semantic elements are permitted, provided they maintain:
72
+ 1. *Design Token Integrity*: Styled using design tokens, theme utilities, or scoped classes (no hardcoded hex colors or raw style objects).
73
+ 2. *Accessibility Standard*: Native semantic interactive elements (never clickable `<div>` without keyboard roles), valid `type` on buttons, and `aria-label`/alt tags.
74
+ 3. *Security Sanitization*: DOMPurify sanitization on dynamic HTML; no `javascript:` pseudo-protocols.
75
+ - **Atomic-Strict Profile (`--profile=atomic-strict`)**: When building standalone design system libraries, the strict Zero-Raw-DOM rule applies: raw DOM elements are restricted strictly to the Atom tier (`a-*`).
76
+ - **Tab List & Complex Pattern Harmonization**:
77
+ - When repeated elements accumulate behavioral logic, accessibility handling, or styling variants across 3+ places (Rule of Three), extract into a canonical capsule (`m-tab-button`).
78
+
79
+ ### H. AI Agent Codebase Query Machine Protocol
80
+ - **AST & Literal Search First Rule**: AI agents should invoke `cx q "<query>"` for AST symbols or `cx q -g "<pattern>"` for literal text before running broad unthrottled grep. If AST search returns 0 results, check the suggested `cx q -g` fallback before escalating to raw ripgrep.
81
+ - **AST Architecture Intelligence**: Always leverage `pnpm chemx q` to inspect component tiers, exported symbols, props, and hooks with minimal token burn.
82
+ - **Mandatory Blast Radius Pre-Refactor Check**: Prior to modifying any foundational atom (`a-*`), shared molecule, or central composable (`use*`), agents MUST calculate the transitive blast radius (`pnpm chemx q <target> --blast-radius --json` or `chemx({ action: 'q', params: { query: '<target>', blastRadius: true } })`). Never perform blind refactors without mapping direct consumers, transitive dependents, and impacted tiers.
83
+ - **Hybrid RRF Discovery Protocol**: When discovering components, controllers, or state machines without an exact symbol name, agents MUST use hybrid search (`pnpm chemx q "<concept>" --hybrid --json` or `chemx({ action: 'q', params: { query: '<concept>', hybrid: true } })`). This blends BM25 keyword matching and vector cosine similarity via Reciprocal Rank Fusion (RRF), eliminating keyword misses and semantic hallucinations.
84
+ - **Semantic Vector Discovery**: Use `pnpm chemx q "<query>" --semantic --json` for purely conceptual lookups.
85
+ - **Inspect Mode**: Use `pnpm chemx q "<capsule-name>" --inspect` to examine props and hooks without reading entire source files into context.
86
+ - **JSON & Columnar Mode**: Use `pnpm chemx q "<query>" --json` for zero-overhead, machine-readable agent lookups in token-compact columnar format (`cols` and `rows`).
87
+ - **Tier Filtering**: Use `pnpm chemx q "<query>" --tier=molecule` (or `atom`, `organism`, `hook`) to narrow scope instantly.
88
+
89
+ ### I. Capsule Trust-Tier Classification & Audit Escalation
90
+ - **Tier 1 (Pure / Stateless)**: Atoms, formatters, pure validators, and API client wrappers. Agents may trust exported interface contracts without inspecting internal implementation details.
91
+ - **Tier 2 (Stateful / Side-Effecting)**: Auth, payments, data mutation, session lifecycle, and transactional service layers. Declared explicitly in capsule `index.ts` metadata or capsule frontmatter (`trustTier: 2`).
92
+ - **Exemption from Shallow Interface Trust**: Tier 2 capsules are strictly exempted from "agent trusts interface, never reads implementation". Agents must inspect implementation details for state invariants and side-effect guarantees.
93
+ - **Automated Audit Escalation**: Query tools and audits automatically escalate review strictness for Tier 2 capsules, requiring deep verification of state transitions, mutation boundaries, and failure recoverability.
94
+
95
+ ### J. Stateful Class & Shared Instance State Carve-Out
96
+ - **Atomic Unit Protection**: Stateful classes and services holding shared instance state across methods are treated as a single atomic unit.
97
+ - **Prohibition on Method Slicing**: Never split methods sharing internal instance state into isolated files or micro-functions. Atomization must not destroy the cohesive state machine.
98
+ - **Decomposition Protocol**: When approaching file line limits, decompose exclusively by extracting pure, stateless helper functions, mathematical derivations, and boundary validators out of the class into standalone utility capsules, preserving the class methods and instance state together.
99
+
100
+ ### K. The Verification-First Protocol & Zero-Token-Burn Pipeline
101
+ - **Verification First Rule**: AI agents MUST NEVER execute raw, unthrottled `npm test`, `pnpm test`, `vitest`, `tsc --noEmit`, or `npm run build` directly in a bash subshell. Raw shell executions flood the context window with hundreds of lines of passing checkmarks, compiler noise, and bundle asset tables, burning thousands of tokens and causing premature context exhaustion.
102
+ - **MCP Verification Tools First**: Agents MUST invoke the dedicated Chemical X MCP tools or CLI wrappers (`pnpm chemx <subcommand>` or `npx chemx <subcommand>`):
103
+ 1. `chemx_verify` (or `pnpm chemx verify --json` / `npx chemx verify --json`): Runs the full verification pipeline (AST Audit + Typecheck + Tests) and returns a single token-compact status card (~45 tokens if green).
104
+ 2. `chemx_typecheck` (or `pnpm chemx typecheck --json` / `npx chemx typecheck --json`): Runs silent TypeScript typecheck; returns structured diagnostics only if errors exist.
105
+ 3. `chemx_test` (or `pnpm chemx test --json` / `npx chemx test --json`): Runs silent project tests; suppresses passing tests and returns ONLY failing test assertions and stack diffs.
106
+ 4. `chemx_audit_build` (or `pnpm chemx build --json` / `npx chemx build --json`): Runs silent production builds; catalogs diagnostics into TypeScript, Rollup, and style budgets.
107
+ - **Actionable Failure Focus**: If a verification step fails, agents consume the exact failure line and diff, fix the code surgically, and re-verify without ever paying the token penalty of passing checks.
108
+
109
+ ### L. Database-First Swarm Coordination & The Zero-Markdown-Monolith Directive
110
+ - **Database as the Master Source of Truth**: The multi-agent orchestrator and subagents MUST record all milestones, task assignments, status changes, file locks, and architectural contracts directly in `.chemx/index.db` (`agent_tasks`, `file_lock_queue`, `agent_feed`) rather than creating monolithic, multi-thousand-token markdown specification files.
111
+ - **Prohibition on Monolithic Project Markdown Parsing**: Subagents MUST NOT load giant monolithic `PROJECT.md` or status markdown files into context. Subagents query only their assigned task slice and dependencies via `pnpm chemx team task list --agent=@my-id` or MCP `chemx_team_task`, slashing token consumption by 80%+.
112
+ - **Project Markdown as a Generated Read-Only Projection**: If a human-readable `PROJECT.md` is requested, it MUST be generated on-demand as a read-only projection compiled from the database state via `pnpm chemx team status` or export tools.
113
+
114
+ ### M. The Master MCP Tool Protocol & Zero-Permission Dispatch
115
+ - **Master Gateway Rule**: When operating inside environments with per-tool permission controls (e.g. Antigravity, Claude Desktop, Cursor), AI agents MUST invoke the unified master MCP tool `chemx` (or `chemx({ action, params })`) rather than invoking fragmented tool names or dropping down to bash subshells.
116
+ - **Antigravity Tool Mapping**: In Google Antigravity, `chemx` is registered under server name `chemical-x` (`call_mcp_tool` with `ServerName: "chemical-x"`, `ToolName: "chemx"`). Always prioritize this tool for all AST reading, querying, testing, verification, and file operations.
117
+ - **Strict Ban on Fragmented Sub-Tool Calls**: Agents are strictly prohibited from calling individual tool names (such as `chemx_read`, `chemx_audit`, or `chemx_write`) directly when the master gateway tool is available. Every distinct tool name triggers a separate permission confirmation dialog for the user, resulting in severe prompt fatigue. Calling `chemx({ action, params })` or `chemx({ command })` routes through a single authorization point.
118
+ - **One-Time Approval Advantage**: The `chemx` master tool provides a single authorization point for the user. Once approved, all operations (`test`, `build`, `verify`, `typecheck`, `audit`, `check`, `patch`, `write`, `read`, `team`, `q`, `autofix`, `issue`) execute silently in-process with zero terminal confirmation prompts.
119
+ - **In-Band JSON-RPC Communication (Zero Disk Dumps)**: All query, inspection, and verification tools must communicate strictly in-band via MCP `CallToolResult` objects (`content: [{ type: "text", text: "..." }]`). Tools must never dump intermediate text files (.txt/.md) or scratch files to disk for AI consumption.
120
+ - **Command Forwarding Syntax**: Agents may invoke either structured action objects (`chemx({ action: 'test' })`, `chemx({ action: 'build' })`, `chemx({ action: 'audit', params: { path: 'src' } })`) or CLI command strings (`chemx({ command: 'test' })`, `chemx({ command: 'build' })`, `chemx({ command: 'audit src' })`).
121
+ - **Master Action & Parameter Dispatch Matrix**:
122
+ ```typescript
123
+ // Fast Token-Bounded Wrappers & Multi-Action Batching
124
+ chemx({ commands: ['d', 'p -s', 'test'] }); // Multi-command batch in single turn
125
+ chemx({ action: 'd' }); // Zero-context diff (-U0), auto-stat if > 80 lines
126
+ chemx({ action: 'log', params: { limit: 5 } }); // Compact single-line commit history
127
+ chemx({ action: 'p', params: { command: '-s' } }); // Read scripts from package.json
128
+ chemx({ action: 'j', params: { path: 'data.json' } }); // Structural JSON schema shape
129
+ chemx({ action: 'q', params: { query: 'theme', literal: true } }); // Literal ripgrep (-g)
130
+
131
+ // Discovery & Impact Analysis
132
+ chemx({ action: 'q', params: { query: 'a-button', blastRadius: true } });
133
+ chemx({ action: 'q', params: { query: 'button state', semantic: true } });
134
+ chemx({ action: 'q', params: { query: 'useAttentionCardController', hybrid: true } });
135
+
136
+ // Surgical AST Reading & Connections
137
+ chemx({ action: 'read', params: { path: 'src/...', symbol: 'ButtonVariant', connections: true } });
138
+ chemx({ action: 'read', params: { path: 'src/...', outline: true } });
139
+ // Component capsules only: outline + logic skeleton in one call (procedural modules: outline or symbol)
140
+ chemx({ action: 'read', params: { path: 'src/...', outline: true, enrich: true } });
141
+ // Component capsules: outline + logic + forward call trace card
142
+ chemx({ action: 'read', params: { path: 'src/...', outline: true, enrich: true, traceSymbol: 'handleCheckout' } });
143
+ // Component capsules: outline + logic + reverse caller chain card
144
+ chemx({ action: 'read', params: { path: 'src/...', outline: true, enrich: true, backtraceSymbol: 'handleCheckout' } });
145
+
146
+ // Surgical Modification & Rules Check
147
+ chemx({ action: 'patch', params: { path: 'src/...', target: 'oldCode', replacement: 'newCode' } });
148
+ chemx({ action: 'write', params: { path: 'src/...', content: '...' } });
149
+ chemx({ action: 'check', params: { path: 'src/...' } });
150
+
151
+ // Deterministic Parameterized Scaffolding (Universal Jig - 90%+ Token Reduction)
152
+ chemx({ action: 'generate', params: { jig: true, kind: 'service', name: 'payment-gateway', methods: [{ name: 'charge', params: 'amount: number' }] } });
153
+ chemx({ action: 'generate', params: { jig: true, kind: 'route', name: 'api-orders', routes: ['GET /orders', 'POST /orders'] } });
154
+ chemx({ action: 'generate', params: { jig: true, kind: 'store', name: 'session-store' } });
155
+
156
+ // Verification, Targeted Testing & Multi-Agent Swarm
157
+ chemx({ action: 'test', params: { target: 'src/services/payment-gateway.spec.ts' } });
158
+ chemx({ action: 'test', params: { target: 'cli/generator.spec.js', filter: 'jig' } });
159
+ chemx({ action: 'verify' });
160
+ chemx({ action: 'team', params: { action: 'task', subAction: 'claim', taskId: 1, as: '@agent' } });
161
+ chemx({ action: 'team', params: { action: 'task', subAction: 'done', taskId: 1, as: '@agent', force: true } });
162
+ chemx({ action: 'team', params: { action: 'lock', subAction: 'acquire', filePath: 'src/...', agentId: '@agent' } });
163
+ ```
164
+ - **Strict Prohibition on Bash Escalation**: Agents MUST NOT spawn bash subshells (`run_command` with `pnpm chemx ...` or `node cli/...`) when an equivalent in-process `chemx` MCP action exists.
165
+
166
+ ### N. Database-First Navigation, Symbol Connections & The Zero-Native-File-Dump Directive
167
+ - **Database Master Index First**: Before inspecting or modifying any file, AI agents MUST query the SQLite database (`.chemx/index.db`) or the AST Query Machine (`chemx({ action: 'team', params: { action: 'list' } })`, `chemx({ action: 'q', params: { query } })`) rather than exploring the filesystem with broad find or ripgrep commands.
168
+ - **Targeted Symbol-Only Extraction**: AI agents MUST NEVER dump entire source files into context. When an agent needs to inspect a function, hook, interface, or class, it MUST request only that specific symbol: `chemx({ action: 'read', params: { path, symbol: '<name>' } })`.
169
+ - **Read Window Auto-Outline**: Files longer than the chemx read window (100 lines by default), read without a target symbol or slice, automatically render an AST outline to prevent token exhaustion and host buffer spillovers (such as IDE `output.txt` dumps). The read window is a tool budget, not an architecture rule; file size is governed by 1.A.
170
+ - **Enrich Mode (Component Capsules Only)**: When an agent needs both exported signatures AND logic flow for a component capsule, use `enrich: true` with `outline: true`: one response card holds the outline and a compacted logic skeleton, optionally with a forward trace or reverse caller chain (`traceSymbol`, `backtraceSymbol`). The skeleton generator is tuned for components; on procedural modules (services, CLI code, utilities) enrich saves only a few percent over reading the whole file, so use plain `outline: true` or `symbol: '<name>'` there.
171
+ - **Symbol Connection Graph Over Multi-File Dumps**: Rather than reading multiple files to understand imports and consumers, agents MUST request symbol connections: `chemx({ action: 'read', params: { path, symbol: '<name>', connections: true } })` or `chemx({ action: 'q', params: { query, connections: true } })`. This instantly returns the definition, imported dependencies, and caller references in ~45 tokens.
172
+ - **Token-First File Inspection & Native Fallback**: AI agents should prioritize Chemical X AST readers (`cx read --outline` or `cx read --symbol`) to conserve tokens. Dumping raw files burns thousands of tokens and causes premature context exhaustion. If an agent requires exact raw verification or unformatted bytes, native tools (`view_file`, `grep`, `cat`) are permitted as an intentional fallback.
173
+
174
+ ### O. Universal Programmatic File Jig & Closed-Loop Execution Protocol
175
+ - **Deterministic Parameterized Synthesis**: When creating non-UI files (services, API route handlers, state stores, database repositories, utilities, or test specs), AI agents MUST NOT emit hundreds of lines of mechanical boilerplate via raw file writing tools. Agents MUST invoke `chemx generate --jig=<kind>` or `chemx({ action: 'generate', params: { jig: true, kind, name, ... } })`.
176
+ - **The 90%+ Output Token Reduction Thesis**: Passing a 30-50 token structured parameter set replaces 1,000-2,500 output tokens of repetitive TypeScript, imports, error tuples, and test boilerplate.
177
+ - **The Closed-Loop ChemX Execution Cycle**:
178
+ 1. *Generate (Jig)*: Stamp out compliant architecture via `chemx({ action: 'generate', params: { jig: true, ... } })`.
179
+ 2. *Read (Outline)*: Inspect AST shape via `chemx({ action: 'read', params: { path, outline: true } })`.
180
+ 3. *Patch (Surgical Edit)*: Ingest domain logic via `chemx({ action: 'patch', params: { path, target, replacement } })`.
181
+ 4. *Test (Targeted Slice)*: Run isolated unit tests in milliseconds via `chemx({ action: 'test', params: { target: '<spec-path>' } })`.
182
+ 5. *Verify (Full Guard)*: Validate AST score and types via `chemx({ action: 'verify' })`.
183
+
184
+ ---
185
+
186
+ ## 2. Domain-Based Type Architecture & Data Integrity
187
+
188
+ ### A. The Anti-Type-Monolith Rule & Domain-Scoped Capsules
189
+ - Strictly prohibit dumping thousands of unrelated entity types into a single monolithic `types.ts` or `global.d.ts`.
190
+ - Co-locate granular `types/*.d.ts` declaration files directly inside each molecule, organism, or feature directory capsule.
191
+ - Split type files by domain, not by line count: once a file declares entities from more than one domain, decompose it into granular domain files (`session.d.ts`, `auth.d.ts`, `billing.d.ts`). File length follows 1.A; there is no separate type-file line cap.
192
+ - Root `types/*.d.ts` is reserved strictly for universal system primitives (`ResultTuple<T>`, `AsyncDataState<T>`, base envelopes). It never contains domain entity models.
193
+ - Zero runtime logic in type files. Zero implicit `any`.
194
+
195
+ ### B. Discriminated State Unions (Zero Impossible States)
196
+ - Model component and session state as strict discriminated/disjoint unions in domain `types/*.d.ts` rather than multiple conflicting booleans:
197
+ ```typescript
198
+ export type SessionState =
199
+ | { readonly status: 'idle' }
200
+ | { readonly status: 'loading'; readonly progress: number }
201
+ | { readonly status: 'active'; readonly sessionId: string }
202
+ | { readonly status: 'fault'; readonly faultMessage: string };
203
+ ```
204
+
205
+ ### C. Result Tuple Pattern (`toResult`)
206
+ - Avoid nested `try/catch` blocks in async flows. Return Go/Rust-style `[data, error]` tuples with top-of-function early guard clauses:
207
+ ```typescript
208
+ const [data, fetchError] = await toResult(api.fetchEntity(id));
209
+ if (fetchError) {
210
+ handleError(fetchError);
211
+ return;
212
+ }
213
+ initializeEntity(data);
214
+ ```
215
+
216
+ ### D. Zero Synthetic or Mock Data
217
+ - Never generate fake names, synthetic emails (`@gmail.com`), random phone numbers (`555-xxx`), mock license numbers, or fake entity arrays.
218
+ - Return genuine live API data or explicit empty states (`No records found`).
219
+
220
+ ### E. Immutable State Action Boundaries
221
+ - Never mutate deep nested store properties inside child components. State transitions occur strictly through named, traceable store actions.
222
+
223
+ ### F. Runtime API Boundary Guards
224
+ - External API and network payloads must be verified through pure, atomic runtime type guards before ingestion into reactive state.
225
+
226
+ ### G. Backend Schema Ground-Truth Hierarchy
227
+ - **Schema as Single Source of Truth**: Backend database schemas (SQL/Prisma/migrations) and OpenAPI specifications constitute ground truth: domain types are strictly derived views.
228
+ - **Bidirectional Schema Validation**: Domain types and boundary interfaces must be validated against the active schema or OpenAPI contract rather than treated as independently authoritative.
229
+ - **Drift Prevention**: Never hand-craft unvalidated entity definitions. Mismatches in nullability, default values, or field mutations must fail compile-time checks or contract test suites before ingestion.
230
+
231
+ ---
232
+
233
+ ## 3. Control Flow & Self-Documenting Logic
234
+
235
+ ### A. Named Conditions & Two-Stage Composition
236
+ > The `if` never asks a question. The question is asked and named before the branch, and the `if` reads the answer.
237
+
238
+ - Every conditional test is a named boolean: an identifier, its negation, or a call or member access whose name is an assertion (3.F). A raw comparison (`x === y`, `n >= 5`), a truthiness check on a non-boolean (`if (user)`, `if (obj.prop)`), inline compound logic (`a && b`), or a verb-named call (`RE.test(s)`, `fs.existsSync(p)`) inside the test is a violation.
239
+ - Naming is the point, not the ceremony: it forces the question inline code hides (why `<= 0` and not `=== -1`?), and an edit to a named condition changes its definition without touching the branch.
240
+ - **Stage 1** names each atomic concept. **Stage 2** names the decision, only when 2 or more concepts compose; a single comparison gets one name and no wrapper. Guard with early returns.
241
+ ```typescript
242
+ if (hookCount > 5) return; // ❌ the if asks
243
+ const exceedsHookBudget = hookCount > 5; // ✅ the question, named
244
+ if (exceedsHookBudget) return; // the if reads the answer
245
+
246
+ const handleCheckout = () => {
247
+ // Stage 1: atomic concepts (Layer 1/2 predicates from 3.B where they exist)
248
+ const hasSufficientFunds = userBalance >= totalCost;
249
+ const isFormComplete = isAddressValid && hasAcceptedTerms;
250
+ // Stage 2: the decision
251
+ const canCheckout = hasItems(cart) && isFormComplete && hasSufficientFunds && !isProcessing;
252
+ if (!canCheckout) return;
253
+ processPayment();
254
+ };
255
+ ```
256
+ - In React, booleans are pure in-render derivations: never use `useEffect` for computed/derived state.
257
+
258
+ ### B. The Predicate Lexicon & Higher-Order Filter Extraction
259
+ - Named conditions come from three layers. A raw comparison belongs in a named declaration (3.A) or inside a Layer 1 or Layer 2 predicate body, never in a conditional test.
260
+ 1. **Structural primitives** (`lib/is/`: `value`, `collection`, `text`, `fs`, `type`): subject-agnostic and finite (`isAbsent`, `hasItems`, `isNonEmptyString`, `pathExists`). They import nothing, and the set does not grow. Every primitive is a TypeScript type predicate (`(x: unknown): x is string`), never a plain `boolean`, or callers lose narrowing.
261
+ 2. **Domain vocabulary** (`<subsystem>/<domain>-predicates.<ext>`, colocated with the subsystem it describes): built from Layer 1. A condition earns a domain predicate at its 2nd use; a threshold duplicated across files (`score >= 90`) silently disagrees the day one copy changes, so name it once (`isGradeA`). Promote threshold literals in predicate bodies to named constants (`score >= GRADE_A_THRESHOLD`).
262
+ 3. **Decisions**: single-use composites declared at the call site per 3.A. Never extract them: extracting every condition is *indirection masquerading as modularity* (1.A).
263
+ - Before naming a new predicate, search for an existing one (`chemx({ action: 'q', params: { query: '<concept>', semantic: true } })`). A synonym beside an existing predicate (`hasNoItems` beside `isEmpty`) is lexicon rot.
264
+ - Repeated filter conditions are Layer 2 candidates: extract the predicate, compose a named higher-order filter, and keep derivations declarative:
265
+ ```typescript
266
+ // ❌ Bad: inlined multi-clause predicate, repeated per derivation
267
+ const viewsFiles = computed(() => filteredFiles.value.filter(f => f.path.startsWith("src/") && (f.path.includes("views/") || f.tier === "views")));
268
+
269
+ // ✅ Good: domain predicate + named higher-order filter + declarative derivations
270
+ const isTierFile = (file: Capsule, tier: string): boolean => {
271
+ const isSrc = file.path.startsWith("src/");
272
+ if (!isSrc) return false;
273
+ return file.path.includes(`${tier}/`) || file.tier === tier;
274
+ };
275
+ const filterFiles = (tier: string) => filteredFiles.value.filter(f => isTierFile(f, tier));
276
+ const viewsFiles = computed(() => filterFiles("views"));
277
+ const organismsFiles = computed(() => filterFiles("organisms"));
278
+ ```
279
+
280
+ ### C. Single-Action Command Handlers
281
+ - Event handlers are linear, unnested orchestrations of pure atomic verbs:
282
+ ```typescript
283
+ const handleAction = async (id: string) => {
284
+ if (!canProceed.value) return;
285
+ triggerHapticFeedback();
286
+ recordTelemetryMetric('action:trigger', { id });
287
+ await executeServiceCall(id);
288
+ dismissActiveModal();
289
+ };
290
+ ```
291
+
292
+ ### D. Ban on Nested Ternaries in Templates
293
+ - Never use nested ternaries in templates (`a ? (b ? 'x' : 'y') : 'z'`).
294
+ - Extract complex UI display states into dedicated computed descriptor objects returning `{ text: string, color: string }`.
295
+
296
+ ### E. Keyed Map Dispatch Over Monolithic Switch Statements
297
+ - Prohibit monolithic `switch` statements used as procedural dispatch tables or value lookups.
298
+ - When branching performs uniform operations (e.g. mapping string keys to action handlers, CSS classes, prompt builders, or payload converters), extract into an O(1) keyed dictionary or method map (`const Registry = { ... }; Registry[key](...)`).
299
+ - **Branch Chains**: An `if` / `else if` chain of 3 or more branches testing the same subject is a lookup, not a series of decisions. Use a keyed map; do not hoist a named boolean per branch (3.A does not apply to such chains).
300
+ - **Prototype Pollution Guardrail**: Always guard dynamic object key access using `Object.hasOwn(Registry, key)` or `Object.prototype.hasOwnProperty.call(Registry, key)` before invoking mapped methods.
301
+ - **Architectural Benefits**: O(1) lookup over O(N) string branching, eliminates boilerplate syntax duplication, complies with OCP, and isolates unit testing.
302
+
303
+ ### F. Name Quality, Assertion Prefixes & Adjacency
304
+ - **Assertion Prefixes**: A condition name starts with `is`, `are`, `has`, `have`, `can`, `could`, `should`, `would`, `does`, `did`, `needs`, `must`, `allows`, `enables`, `contains`, `includes`, `supports`, `requires`, `exceeds`, `matches`, or `wants`, followed by its subject (`isEscapeChar`, `exceedsHookBudget`). A bare verb callee (`test`, `existsSync`, `includes`, `startsWith`) is not a name: bind its result to one first.
305
+ - **Reject Restatements**: A name built only from the words of its own expression teaches nothing. `isChEqualsBackslash = ch === '\\'` and `isCountGreaterThanFive = count > 5` are rejected; `isEscapeChar = ch === '\\'` adds a domain term and passes. If a condition cannot be named in words absent from the condition itself, it is not yet understood: find out before branching on it.
306
+ - **Adjacency**: Declare a single-use named boolean on the statement immediately before its `if`. Hoist it only when it is referenced 2 or more times in the enclosing function, and then only to a point before its first use. A wall of `const is*` declarations at function top is a readability regression.
307
+ - **No Double Negation**: `if (!isNotFound)` names the wrong side. Name the positive and negate at the point of use.
308
+
309
+ ### G. Explicit Guardrail Aborts (No Silent Failures)
310
+ - Guard clauses in event handlers, mutations, and async flows must never fail silently via bare `return;`.
311
+ - Halting execution requires an explicit contract: return a `ResultTuple` (`return [null, error]`), emit diagnostic logging (`logger.warn(...)`), update a user-facing error state (`state.error = '...'`), or throw a domain invariant.
312
+ - **Exemptions**: Benign lifecycle no-ops (`abortSignal.aborted`, `!isMounted`), optional prop callbacks (`!props.onClick`), debounce/throttle timers, and pure query predicates.
313
+
314
+ ---
315
+
316
+ ## 4. Reactivity, Composables & Hooks
317
+
318
+ ### A. The Molecular Composable Destructuring Contract
319
+ 1. **Safe Destructuring**: Composables must always return plain objects containing individual `ref()`, `computed()`, and pure functions. Never return a raw `reactive()` object.
320
+ 2. **The Shape-Classification Contract**: Return values must classify strictly into three canonical buckets: State (domain data), Status (lifecycle/health info), and Actions (verb-prefixed functions flat at top level). No arbitrary property count ceiling applies. Unclassifiable properties (raw DOM refs, intermediate values, non-verb callbacks), nested action wrappers (`actions: {}`), and cross-hook naming inconsistencies are strictly prohibited. (Note: For stateful service classes holding shared instance state, refer to the Section 1.J carve-out).
321
+ 3. **Standardized Aliasing**: Use standardized names (`data`, `isLoading`, `error`, `execute`) to enable clean concurrent destructuring.
322
+ 4. **Autonomous Lifecycle Teardown**: Side effects (listeners, timers, observers) must be cleaned up automatically using `onScopeDispose()` or effect cleanup functions.
323
+ 5. **Flexible Input Ergonomics**: Accept raw values, refs, or getters interchangeably via `toValue()` / `MaybeRefOrGetter<T>`.
324
+
325
+ ### B. Clean 3-State Async Pipelines
326
+ - Every asynchronous operation follows a predictable state container (`data`, `isLoading`, `error`, `execute`):
327
+ ```typescript
328
+ const { data: items, isLoading, error, execute: loadItems } = useAsyncData(fetchItemsApi);
329
+ const hasItems = computed(() => items.value.length > 0);
330
+ const shouldShowEmptyState = computed(() => !isLoading.value && !hasItems.value && !error.value);
331
+ const shouldShowErrorState = computed(() => !isLoading.value && Boolean(error.value));
332
+ ```
333
+
334
+ ### C. Strict Lexical Declaration Order (TDZ Prevention)
335
+ To eliminate Temporal Dead Zone (TDZ) ReferenceErrors, `<script setup>` and controllers strictly follow this lexical declaration order:
336
+ 1. Composables & Stores (`useRouter()`, `useStore()`)
337
+ 2. Reactive Primitives (`ref()`, `reactive()`)
338
+ 3. Computed State (`computed()`)
339
+ 4. Helper Methods & Actions (`const handleClick = () => { ... }`)
340
+ 5. Watchers (`watch()`, `watchEffect()`)
341
+ 6. Lifecycle Hooks (`onMounted()`, `onUnmounted()`)
342
+ *Mandatory Rule*: Never reference a reactive value, computed property, or helper in an immediate watcher callback before its declaration.
343
+
344
+ ---
345
+
346
+ ## 5. Design System, Styling & UI Performance
347
+
348
+ ### A. The 4-Tier Zero-Inline-Style Rule
349
+ Raw inline `style="..."` attributes are strictly prohibited. Visual styling flows through the standardized 4-tier hierarchy:
350
+ 1. **Level 1 (Atom Props)**: Semantic props on atoms (`:color="brandColor"`, `variant="glass"`, `size="lg"`).
351
+ 2. **Level 2 (Mixins & Utilities)**: Centralized SCSS mixins (`@include glass;`, `@include glass-hover;`) and utility classes.
352
+ 3. **Level 3 (Scoped BEM Classes)**: Scoped classes in component stylesheets referencing design tokens or encapsulating shorthand via `@apply`.
353
+ 4. **Level 4 (Dynamic Root Variables)**: Dynamic runtime coordinates passed exclusively as root CSS custom properties (`:style="{ '--win-x': \`${x}px\`, '--win-y': \`${y}px\` }"`).
354
+
355
+ ### B. The Anti-Tailwind-Soup Directive (Class Decoupling)
356
+ - Prohibit monolithic utility class chains (> 4-5 classes per element) directly inside HTML templates.
357
+ - Long strings of utility shorthand recreate the exact cognitive noise and AI context degradation of inline styles.
358
+ - Decouple visual styling into scoped classes via `@apply` or centralized SCSS mixins (`@include glass;`).
359
+ - Templates must read like a clean, semantic outline rather than an unreadable wall of styling shorthand.
360
+
361
+ ### C. Wrapper Atoms & Explicit Slot Forwarding
362
+ - Never use dynamic slot iteration with `v-for="(_, slot) in $slots"` in wrapper components.
363
+ - Explicitly forward named slots: `<template #<slot-name>="scope"><slot :name="<slot-name>" v-bind="scope || {}" /></template>`.
364
+ - Always wrap default slot in `<template #default="scope"><slot v-bind="scope || {}" /></template>`.
365
+
366
+ ### D. Flat CSS Specificity & Icon Safety
367
+ - Single-depth BEM semantic class naming. Never use `!important` overrides.
368
+ - **FontAwesome SVG Compliance**: Never attach `text-*` utility classes to FontAwesome icons (breaks SVG rendering). Use native `:color` prop or inline CSS.
369
+
370
+ ### E. 60 FPS Non-Blocking UI Offloading
371
+ - Heavy computational operations (parsing, sorting, cryptographic hashing) must be offloaded to Web Workers or chunked micro-batches via `requestIdleCallback`.
372
+
373
+ ---
374
+
375
+ ## 6. Timer & Macro-Task Discipline
376
+
377
+ ### A. Zero `setInterval` in Component & Business Logic
378
+ - Polling with `setInterval` is strictly prohibited.
379
+ - Use `requestAnimationFrame` for animations and physics.
380
+ - Use `videoElement.requestVideoFrameCallback()` for camera/video streams.
381
+ - Use a single shared system clock composable (`useSystemClock()`) for time displays.
382
+ - Use Server-Sent Events or WebSockets for server state sync.
383
+
384
+ ### B. Zero Render-Hack `setTimeout` (Mandatory `nextTick`)
385
+ - Never use `setTimeout(() => { ... }, 0)` to wait for DOM elements to render. Use `await nextTick()` or `watch(..., { flush: 'post' })`.
386
+
387
+ ### C. Self-Cleaning Timer Composables
388
+ - Timers for real-world delays must be managed through self-cleaning composables (`useTimeoutFn`, `useDebounceFn`) that cancel automatically on component unmount via `onScopeDispose` or effect teardown.
389
+
390
+ ---
391
+
392
+ ## 7. Infrastructure, Extensibility & Global Hygiene
393
+
394
+ ### A. Zero-Conditional `debug.log` Proxy
395
+ - Never use `if (import.meta.env.DEV)` or `if (isProd)` checks around logging statements. Use a central `debug` proxy that automatically silences in production while preserving errors.
396
+
397
+ ### B. Typography Hygiene
398
+ - Never use em dashes anywhere in code, copy, markdown, or documentation. Use standard hyphens or colons.
399
+
400
+ ---
401
+
402
+ ## 8. Accessibility & Semantic Integrity
403
+
404
+ ### A. Semantic HTML First
405
+ - Never reach for a generic `<div>` or `<span>` with a click handler where a native element (`<button>`, `<a>`, `<label>`, `<nav>`) already carries the correct behavior and semantics for free.
406
+ - Interactive elements must be genuinely interactive elements. A clickable `<div>` requires manually re-implementing keyboard focus, Enter/Space activation, and role semantics that native elements provide automatically.
407
+
408
+ ### B. Keyboard & Focus Management
409
+ - Every interactive element must be reachable and operable via keyboard alone: Tab to focus, Enter/Space to activate, Esc to dismiss modals and overlays.
410
+ - Modals, drawers, and dropdowns must trap focus while open and return focus to the triggering element on close.
411
+ - Never remove default focus outlines (`outline: none`) without providing a visible, equivalent custom focus state.
412
+
413
+ ### C. ARIA as a Last Resort, Not a First Layer
414
+ - Use ARIA attributes (`aria-label`, `aria-expanded`, `role`) only to fill genuine gaps semantic HTML cannot cover, not as a substitute for correct markup.
415
+ - Every image conveying meaning requires alt text; purely decorative images use `alt=""`.
416
+ - Form inputs require an associated `<label>`, not a placeholder alone.
417
+
418
+ ### D. Color & Motion Safety
419
+ - Text and interactive elements must meet WCAG AA contrast ratios in both light and dark modes; verify new color tokens against both themes, not just one.
420
+ - Respect `prefers-reduced-motion` for non-essential animations and transitions.
421
+
422
+ ---
423
+
424
+ ## 9. Security & Content Safety
425
+
426
+ ### A. Zero Unsanitized HTML Injection
427
+ - Never render user-supplied or externally-fetched content via `v-html`, `dangerouslySetInnerHTML`, or equivalent raw-HTML injection without passing it through a sanitizer (e.g. DOMPurify) first.
428
+ - Treat all externally-fetched content (API responses, user uploads, third-party embeds) as untrusted by default.
429
+
430
+ ### B. Output Encoding & Injection Boundaries
431
+ - Never interpolate user input directly into constructed HTML strings, SQL queries, or shell commands. Use parameterized queries and framework-native escaping.
432
+ - Never build URLs for redirects or API calls by concatenating unvalidated user input; validate against an allowlist.
433
+
434
+ ### C. Secrets & Credential Hygiene
435
+ - Never hardcode API keys, tokens, or credentials in source files, even temporarily during development. Use environment variables or a secrets manager.
436
+ - Never log full request/response payloads that may contain auth tokens, passwords, or PII.
437
+
438
+ ### D. CSRF & Auth Boundaries
439
+ - State-changing requests (POST/PUT/DELETE) must carry CSRF protection appropriate to the framework's convention, not be assumed safe because they're behind a login.
440
+ - Never trust client-side role or permission checks as the sole gate for sensitive actions; the server must re-verify authorization independently.
441
+
442
+ ---
443
+
444
+ ## 10. Testing Discipline
445
+
446
+ ### A. Co-located Test Files
447
+ - Test files live alongside the capsule they cover (`m-<feature>-card.spec.ts` inside the capsule directory), not in a separate parallel test tree that drifts from the source structure.
448
+
449
+ ### B. What Must Be Covered
450
+ - Every exported pure function, composable, and domain type guard requires at least one test exercising its primary path and one exercising a failure/edge path.
451
+ - UI components require at least a render smoke test; interactive components require a test covering their primary user action.
452
+
453
+ ### C. Refactor Discipline
454
+ - When decomposing a file per Section 1, existing tests move and are updated to match the new file boundaries in the same pass; a refactor is not complete until its tests pass against the new structure.
455
+ - Never delete or skip a failing test to unblock a commit; fix the code or the test, or flag the failure explicitly.
456
+
457
+ ### D. No Fake Green
458
+ - Never write a test that trivially passes without exercising real logic (e.g. asserting `true === true`, mocking away the exact behavior under test).
459
+
460
+ ### E. Silent Verification & Zero Passing Noise
461
+ - AI agents executing tests or verifying code MUST invoke `chemx_test` (or `npx chemx test --json`) and `chemx_verify` (or `npx chemx verify --json`).
462
+ - Strictly prohibit executing verbose raw `npm test` or `pnpm test` in the shell: hundreds of passing test markers pollute context. If tests pass, agents consume a ~25-token green acknowledgment; if tests fail, agents consume only the failing test name, assertion message, and diff.
463
+
464
+ ---
465
+
466
+ ## 11. Naming Conventions
467
+
468
+ ### A. Casing
469
+ - Files: kebab-case (`m-user-card.controller.ts`).
470
+ - Variables, functions, composables: camelCase (`isLoading`, `useAsyncData`).
471
+ - Types, interfaces, components: PascalCase (`SessionState`, `UserCard`).
472
+ - Constants meant to be immutable module-level config: SCREAMING_SNAKE_CASE (`MAX_RETRY_COUNT`).
473
+
474
+ ### B. Boolean & Predicate Prefixes
475
+ - Booleans and predicates start with an assertion prefix from 3.F (`isLoading`, `hasItems`, `canCheckout`, `exceedsHookBudget`). Never name a boolean as a bare noun or adjective (`loading`, `valid`) that hides its type at the call site.
476
+
477
+ ### C. Event & Handler Naming
478
+ - Emitted events describe what happened, not what to do (`item-selected`, not `select-item`).
479
+ - Handler functions describe the action taken, prefixed `handle` (`handleCheckout`), matching Section 3.C.
480
+
481
+ ---
482
+
483
+ ## 12. Documentation Discipline
484
+
485
+ ### A. Derived Contract Synchronization
486
+ - Derived contract fields (signatures, parameters, payload structures, return types) in capsule documentation must be extracted directly from `types.d.ts`, never manually duplicated or hand-typed.
487
+ - Any change to `types.d.ts` must automatically propagate to or be validated against the capsule reference documentation.
488
+
489
+ ### B. Mandatory Doc-Touch CI Gate
490
+ - A commit that modifies a capsule's implementation or controller without updating the corresponding documentation prose section must fail CI validation.
491
+ - Refactors and behavioral changes are not complete until documentation accurately reflects updated semantics, mirroring Section 10.C.
492
+
493
+ ### C. "No Fake Doc-Sync" Anti-Pattern
494
+ - Mirroring the "No Fake Green" testing rule in Section 10.D, superficial doc edits (whitespace tweaks, comment formatting, minor typo fixes) made merely to pass CI touch-checks without addressing substantive semantic changes are strictly prohibited.
495
+ - Documentation reviews must verify substantive alignment between code behavior and documented contracts.
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import AButton from '../../atoms/a-button.svelte';
2
+ import AButton from '../atoms/a-button.svelte';
3
3
  import type { MSampleCardProps, SampleCardBadgeDescriptor } from './types';
4
4
 
5
5
  let {
@@ -1,6 +1,6 @@
1
1
  <script setup lang="ts">
2
2
  import { computed } from 'vue';
3
- import AButton from '../../atoms/a-button.vue';
3
+ import AButton from '../atoms/a-button.vue';
4
4
  import type { MSampleCardProps, SampleCardBadgeDescriptor } from './types';
5
5
 
6
6
  const props = withDefaults(defineProps<MSampleCardProps>(), {
@@ -73,10 +73,38 @@ const normalizeWords = (text) => {
73
73
  .filter((w) => w.length > 1 && !STOP_WORDS.has(w));
74
74
  };
75
75
 
76
+ // A line-based scan cannot tell a comment from a string that quotes one. Walk the line
77
+ // up to the match and track quote state: if a quote is still open at that offset, the
78
+ // match sits inside a string literal and is describing the pattern, not committing it.
79
+ // Lines that are wholly a comment short-circuit, so apostrophes in prose cannot open a
80
+ // phantom string and suppress a real finding.
81
+ const COMMENT_LINE_START = /^\s*(?:\/\/|#|\*|--)/;
82
+
83
+ const isInsideStringLiteral = (lineText, matchIndex) => {
84
+ if (matchIndex <= 0) return false;
85
+ if (COMMENT_LINE_START.test(lineText)) return false;
86
+
87
+ let quote = null;
88
+ for (let i = 0; i < matchIndex; i += 1) {
89
+ const ch = lineText[i];
90
+ if (ch === '\\') {
91
+ i += 1;
92
+ continue;
93
+ }
94
+ if (quote) {
95
+ if (ch === quote) quote = null;
96
+ } else if (ch === '"' || ch === "'" || ch === '`') {
97
+ quote = ch;
98
+ }
99
+ }
100
+ return quote !== null;
101
+ };
102
+
76
103
  export const checkSlopTextPatterns = (content, lines, relativePath, violations) => {
77
104
  lines.forEach((lineText, idx) => {
78
105
  for (const pat of CONVERSATIONAL_PATTERNS) {
79
- if (pat.regex.test(lineText)) {
106
+ const hit = pat.regex.exec(lineText);
107
+ if (hit && !isInsideStringLiteral(lineText, hit.index)) {
80
108
  const meta = RULE_REGISTRY[pat.rule];
81
109
  violations.push({
82
110
  filePath: relativePath,