Files
2026-10-06 09:57:33 +03:30

706 lines
46 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# SKILLS.md — AI Agent Instructions for the Voice-to-Voice FAQ App
> **Audience:** AI coding assistants and agents (Claude Code, Cursor, Copilot, Codex, etc.).
> **Compatible filenames:** keep this file as `SKILLS.md`; copy or symlink it to `CLAUDE.md`, `AGENTS.md`, or `.cursorrules` if your tool expects one of those.
> **Authority:** these rules are binding. If a user request conflicts with them, say so and propose a compliant alternative before writing code.
---
## 1. Project Overview & Rules of Engagement
### 1.1 What this project is
A **Voice-to-Voice FAQ web application** built with **Angular** (standalone components, Signals, `ChangeDetectionStrategy.OnPush`, **zoneless-ready**).
- **Voice mode:** real-time, full-duplex voice with an AI FAQ agent. A Three.js orb reflects five states: `idle`, `listening`, `processing`, `speaking`, `interrupted`. Audio is captured and played as raw PCM through `AudioWorklet` and exchanged over WebSocket.
- **Knowledge base:** a slide-over drawer and full page for uploading FAQ documents (CSV, PDF, JSON, DOCX), tracking `uploading → indexing → active | error`, and editing Q&A pairs in a data grid.
### 1.2 Your role
You are a **Principal Angular & Web Audio Engineer**. You write code that is correct under zoneless change detection, safe on the audio thread, cheap on the main thread, and leak-free. You prefer small, typed, testable units over cleverness.
### 1.3 Mandatory pre-flight (before generating ANY code)
1. **Read** these files in full, in this order:
1. `./docs/SRC_STRUCTURE.md` — where every file goes and who may import whom.
2. `./docs/ARCHITECTURE.md` — state machine, audio pipeline, data contracts.
3. `./docs/DEPENDENCIES.md` — the **only** approved libraries and versions.
2. **If a file is missing or unreadable, stop and tell the user.** Do not guess its contents.
3. **Locate the target path** for every file you will create or edit in `SRC_STRUCTURE.md`. If no suitable location exists, propose one and wait for confirmation instead of inventing a folder.
4. **Reuse before you write.** Search the repo for an existing service, type, util, or component that already does the job. In particular: **HTTP → `HttpService`**, **login/auth → `AuthService` + `authGuard`**, **theme → `ThemeService`** (see §1.7).
5. **State your plan in two or three lines** (files to touch, which rules apply) before the code.
### 1.4 Document precedence
| Question | Authoritative source |
|---|---|
| Where does this file go? What may import what? | `SRC_STRUCTURE.md` |
| Which library or version may I use? | `DEPENDENCIES.md` |
| How should the system behave (states, protocol, data shapes)? | `ARCHITECTURE.md` |
| How should the code be written? | **This file** |
| HTTP, login, or theme changes | **This file §1.7** (`HttpService`, `AuthService`, `ThemeService`) |
If two project documents disagree, `SRC_STRUCTURE.md` wins for paths and `DEPENDENCIES.md` wins for packages. **Report the discrepancy** to the user; do not silently pick one.
### 1.5 Known deltas (these are intentional; do not "fix" them back)
| Topic | Rule in this repo | Do NOT write |
|---|---|---|
| Zoneless provider (Angular 20.2+ incl. 22) | `provideZonelessChangeDetection()` | `provideExperimentalZonelessChangeDetection()` (it does **not exist** in Angular 22) |
| Zoneless provider (Angular 18/19 only) | `provideExperimentalZonelessChangeDetection()` | The stable name, which is not available there |
| Worklet files | `src/assets/worklets/pcm-capture-processor.js` and `pcm-playback-processor.js` | A single `src/assets/audio/pcm-processor.js` |
| Icons | **`@lucide/angular`**, accessed only through `shared/ui/icon` | `lucide-angular` (deprecated, peer-conflicts with Angular 22) |
| CSV parsing | `Papa.parse(file, { preview: N, … })` and chunked streaming | `worker: true` (commonly breaks under bundlers) |
| `standalone` flag | Everything is standalone; on Angular 19+ the flag is the default, so **omit it** | `standalone: false`, NgModules |
| Cleanup | `DestroyRef.onDestroy()` and `effect` `onCleanup` (and `ngOnDestroy` only when a class already implements it) | Treating `untracked()` as a cleanup hook (it is not one) |
**Check the installed Angular major in `package.json` first.** Apply the matching row above.
### 1.6 Scope & dependency discipline
- **Never add a package** that is not in `DEPENDENCIES.md`. If one is needed, explain why and ask first.
- **Never edit** `angular.json`, `package.json`, `tsconfig*.json`, or CI files unless the task requires it; when you do, explain the change.
- **Never refactor unrelated code** while implementing a feature. Mention opportunities instead.
- **Never delete files or tests** to make a build pass.
- Use the path aliases: `@core/*`, `@features/*`, `@shared/*`, `@env/*`.
### 1.7 Mandatory platform services (Http / Auth / Theme)
These three services are the **only** approved way to talk to the backend, authenticate, or change theme. Do not reinvent them, do not inject raw `HttpClient` for API calls, and do not write ad-hoc `localStorage` token or theme logic.
| Need | Use | Never |
|---|---|---|
| Any REST / SSE / file download to the API | `HttpService` (`get` / `post` / `put` / `patch` / `delete` / `getStream` / `downloadFile`) | Direct `HttpClient`, bare `fetch` for API routes, or a second HTTP wrapper |
| Login, session check, route protection | `AuthService.login()`, `AuthService.isAuthenticated()`, `authGuard` | Hand-rolled login POST, reading `access_token` outside these services, custom guards that ignore `AuthService` |
| Dark / light theme init and toggle | `ThemeService` (`initTheme` at app start, `toggleDarkMode()`, `isDarkMode` / `isDarkMode$`) | Direct `document.documentElement` theme writes, independent `localStorage['theme']` writes, duplicate dark-mode subjects |
#### HttpService (canonical HTTP layer)
- **Location:** project HTTP service (typically under a path such as `http-request/http.service` or as defined in `SRC_STRUCTURE.md`). Inject with `inject(HttpService)` in field initializers.
- **Response shape:** every JSON endpoint returns `ApiResult<T>` or `ApiResultArray<T>`:
```ts
export interface ApiResult<T> {
hasError: boolean;
messages: string[];
result: T;
}
```
- **Methods:** `get<T>`, `post<T>`, `put<T>`, `patch<T>`, `delete<T>` → `Observable<ApiResult<T>>`; `getStream<T>` for SSE (auth headers included); `downloadFile` → `Observable<Blob>`.
- **Options (`HttpOptions`):** `params`, `headers`, `skipToast`, `cooldownMs`, `skipHasErrorCheck`. Prefer these flags instead of swallowing toasts in callers.
- **Auth header:** token is read from `localStorage.getItem('access_token')` and attached as `Authorization: Bearer …`. Callers never set the Bearer token themselves unless adding extra headers via `options.headers`.
- **401 handling:** clears token, dismisses modals, toasts an expiry message, navigates to `/login`. Do not re-implement this.
- **Toasts / errors:** success and error messages from `messages[]` are shown via the service's toast layer (with cooldown). Feature code should not duplicate the same toasts for the same response.
- **Base URLs:** use the service's `baseUrl` / `backendUrl` / `apiUrl` / `imagesUrl`. Do not hard-code hostnames in feature code.
Example:
```ts
private readonly http = inject(HttpService);
loadFaq(): void {
this.http.get<FaqDoc[]>('faq/documents').subscribe({
next: (res) => { /* res.result is typed; hasError already handled unless skipHasErrorCheck */ },
error: () => { /* 401 and toast already handled by HttpService */ },
});
}
```
For long-lived streams use `getStream` and tear down with `takeUntilDestroyed` / `AbortController` (the Observable already aborts on unsubscribe).
#### AuthService + authGuard
- **Location:** auth service + `authGuard` (functional `CanActivateFn`).
- **Login:** always `AuthService.login({ username, password, rememberMe })`. On success it stores `access_token` and `username`, updates `currentUserSubject`, then loads permissions and license. Do not POST to `users/login` through `HttpService` from a component and then write tokens yourself.
- **Session check:** `AuthService.isAuthenticated()` (token present). Route protection: add `canActivate: [authGuard]` (or equivalent) — the guard redirects to `/login` when unauthenticated.
- **User stream:** `currentUserSubject` / subscription for username changes. Prefer converting to a signal at the UI edge (`toSignal`) if the component is signal-driven; do not replace the service's subject with a parallel signal store unless migrating the whole auth layer.
- **Logout / token clear:** go through the same paths the service uses (token removal is also done on 401 inside `HttpService`). Do not scatter `localStorage.removeItem('access_token')` in feature components.
#### ThemeService
- **Location:** theme service. Constructor already calls `initTheme()`.
- **Init:** `initTheme()` reads `localStorage.theme`, applies `data-bs-theme` on `document.documentElement`, then reconciles with backend `GET users/get-dark-mode`. Ensure the service is instantiated once at app bootstrap (e.g. inject it in `App` or a root provider) so init runs; do not call `initTheme` from random components.
- **Toggle:** only `ThemeService.toggleDarkMode()`. It flips local state, writes `localStorage`, applies the attribute, and syncs with `POST users/update-dark-mode`. Never toggle theme by only changing a CSS class or only writing localStorage.
- **Read:** `isDarkMode` (sync getter) or `isDarkMode$` (observable). In new signal-based UI, wrap with `toSignal(this.theme.isDarkMode$, { initialValue: this.theme.isDarkMode })` rather than inventing a second theme signal.
#### Agent rules (binding)
1. **HTTP request** → inject and call `HttpService` only.
2. **Login / is-logged-in / protect a route** → `AuthService` + `authGuard` only.
3. **Change or initialize theme** → `ThemeService` only (`initTheme` / `toggleDarkMode`).
4. Do **not** introduce a competing `ApiClient`, `AuthStore`, or `ThemeStore` that bypasses these services.
5. When wrapping these services for signals/OnPush UI, keep a **single writer**: the existing service remains the source of truth; UI adapts with `toSignal` / `computed`, it does not duplicate token or theme storage.
---
## 2. Angular & Zoneless Coding Standards
### 2.1 Signals first
Use the right primitive for the job:
| Need | Use | Not |
|---|---|---|
| UI / component state | `signal()` | `BehaviorSubject`, plain fields mutated in place |
| Derived read-only state | `computed()` | duplicated state kept in sync by hand, `effect()` that writes derived values |
| Derived **but locally overridable** state (e.g., selected row that resets when the list changes) | `linkedSignal()` | `effect()` that resets a signal |
| Async data read from HTTP | `resource()` / `httpResource()` **if the installed Angular version marks them stable or the project already uses them**; otherwise **`HttpService`** + `toSignal()` / subscribe with `takeUntilDestroyed` | Direct `HttpClient`, manual `subscribe()` that sets fields without teardown |
| Component API | `input()`, `input.required()`, `output()`, `model()`, `viewChild()`, `viewChildren()`, `contentChild()` | `@Input()`, `@Output()`, `@ViewChild()` decorators |
| Dependency injection | `inject()` in field initializers | constructor parameter injection |
| Event streams over time (WebSocket messages, SSE, debounced filters) | RxJS `Observable` at the **edge**, converted with `toSignal()` / `takeUntilDestroyed()` | RxJS for plain UI state |
| Side effects reacting to state (DOM, logging, calling the visualizer) | `effect()` / `afterRenderEffect()` | `effect()` to derive state |
> `resource()` and `httpResource()` were experimental in earlier Angular majors. Verify their API stability tag in the installed version before using them; do not assume.
**RxJS is allowed, but only for event streams.** A boolean such as `isDrawerOpen` is a `signal<boolean>`, never a `BehaviorSubject<boolean>`.
#### Single-writer rule
Every piece of state has **exactly one writer**. Expose a read-only view and keep the writable signal private.
```ts
@Injectable({ providedIn: 'root' })
export class VoiceStateStore {
private readonly _voiceState = signal<VoiceState>('idle');
readonly voiceState = this._voiceState.asReadonly();
readonly isMicOpen = computed(() =>
['listening', 'speaking', 'interrupted'].includes(this._voiceState()),
);
/** Only VoiceSessionService may call this. */
_setState(next: VoiceState): void {
this._voiceState.set(next);
}
}
```
- Update objects and arrays **immutably**: `signal.update(list => [...list, item])`. Never mutate the value inside a signal.
- Do not read signals inside `computed()` through `untracked()` to "silence" dependencies; fix the dependency graph instead.
- `effect()` is for side effects only. If you are about to call `.set()` inside an `effect()`, stop and check whether `computed()` or `linkedSignal()` is the right tool.
- Never put a signal write inside a `computed()`.
### 2.2 `ChangeDetectionStrategy.OnPush` is mandatory
**Every component** declares `changeDetection: ChangeDetectionStrategy.OnPush`, with no exceptions (including tiny presentational components, dialogs, and AG Grid cell renderers).
```ts
@Component({
selector: 'app-status-badge',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [AppIconComponent],
template: `
<span class="glass inline-flex items-center gap-2 rounded-full px-3 py-1" [class]="glowClass()">
<app-icon [name]="icon()" />
{{ label() }}
</span>
`,
})
export class StatusBadgeComponent {
readonly state = input.required<VoiceState>();
protected readonly label = computed(() => STATE_LABELS[this.state()]);
protected readonly icon = computed(() => STATE_ICONS[this.state()]);
protected readonly glowClass = computed(() => `glow-${this.state()}`);
}
```
The ESLint rule `@angular-eslint/prefer-on-push-component-change-detection` must stay enabled.
### 2.3 Zoneless safety (code must work with AND without Zone.js)
Assume **Zone.js may be absent**. Under zoneless change detection, a view is re-checked only when something Angular knows about changes: a **signal read in the template is written**, an input changes, an event bound in the template fires, `markForCheck()` is called, or the `async` pipe emits.
**Do:**
- Drive every template update through a **signal write**. A WebSocket callback, `setTimeout`, `requestAnimationFrame`, `Promise.then`, or `addEventListener` callback that changes plain fields will **not** update the screen.
- Use `afterNextRender()` / `afterRenderEffect()` for DOM measurement and canvas setup instead of `ngAfterViewInit` timing tricks.
- Use `DestroyRef`, `takeUntilDestroyed()`, and effect cleanups; they do not depend on Zone.js.
- Use the correct provider for the installed major (see §1.5):
```ts
// app.config.ts: Angular 20.2+ / 22 (this repo)
provideZonelessChangeDetection(),
// Angular 18/19 only: provideExperimentalZonelessChangeDetection(),
// Temporary zone phase only (needs "zone.js" in angular.json polyfills):
// provideZoneChangeDetection({ eventCoalescing: true }),
```
**Do not:**
- `import 'zone.js'` anywhere in application code.
- Depend on `NgZone.onStable`, `NgZone.onMicrotaskEmpty`, `NgZone.isStable`, or `ApplicationRef.isStable` for correctness.
- Call `ChangeDetectorRef.detectChanges()` in hot paths. Prefer a signal write; use `markForCheck()` only for a legacy API that cannot be signal-based.
- Rely on `NgZone.run()` to "make it update". It is a no-op for correctness in zoneless mode.
- Use `fakeAsync()` / `tick()` in new tests (they require Zone.js testing patches). Use Vitest fake timers (`vi.useFakeTimers()`) and `await fixture.whenStable()`.
- Write a signal at frame rate (60 Hz) from the audio or render loop. See §3.3.
### 2.4 Standalone components, directives, and pipes
- Everything is standalone. **No NgModules, ever.** Declare dependencies in `imports: []`.
- Never write `standalone: false`. On Angular 19+ do not add the redundant `standalone: true` either (it is the default); on Angular 18 it **must** be written explicitly.
- Lazy-load features and heavy dependencies (`loadChildren`, `loadComponent`, dynamic `import()`), as listed in `DEPENDENCIES.md` §6.5.
### 2.5 Templates, naming, and style
- Control flow: `@if`, `@for (item of items(); track item.id)`, `@switch`. **No** `*ngIf`, `*ngFor`, `*ngSwitch`.
- Every `@for` has a stable `track` expression (an id, never the index unless the list is static).
- Templates call **signals and `computed()` values only**. No method calls that compute things, no `Date.now()`, no object/array literals in bindings.
- Prefer `class` and `style` bindings over `ngClass` / `ngStyle`. Use `host: { … }` metadata instead of `@HostBinding` / `@HostListener`.
- File naming (matches `angular.json` schematics): `*.component.ts`, `*.directive.ts`, `*.pipe.ts`, `*.service.ts`; route containers are `*.page.ts`; stores are `*.store.ts`. Selector prefix is `app-` (directives: `app`).
- Class members: `protected readonly` for template-only values, `readonly` for public API, `private` for internals.
- `strict` TypeScript and `strictTemplates` are on. No `any` (use `unknown` and narrow). No non-null assertions (`!`) without a comment explaining why it is safe.
- Prefer **discriminated unions** for events and messages (`VoiceEvent`, `ClientMessage`, `ServerMessage`) and handle them with an exhaustive `switch` ending in `assertNever`.
- Style with **Tailwind utilities** and the design tokens in `src/styles/theme.css`. Use the `glass`, `glass-strong`, and `glow-*` utilities. No component CSS files unless unavoidable, and no hard-coded hex colors; use tokens.
- Use **logical** properties (`ms-*`, `me-*`, `ps-*`, `pe-*`, `start-*`, `end-*`) so RTL layouts work. Never `ml-*`, `pr-*`, `left-*`, `right-*` for layout direction.
### 2.6 Icons
Icons come **only** from `shared/ui/icon` (`<app-icon name="mic" />`) backed by the registry `icons.ts` (package `@lucide/angular`). Never import Lucide directly in a feature component. To add an icon, add it to the registry.
### 2.7 Accessibility baseline
- Interactive elements are real `<button>` / `<a>` elements with accessible names.
- Voice state changes are announced via CDK `LiveAnnouncer` or an `aria-live="polite"` region.
- Drawers and dialogs use CDK `Overlay` / `Dialog` with focus trap, `Esc` to close, and focus restoration.
- Never convey state by color alone: pair it with icon + text.
- Honor `prefers-reduced-motion` in animations and in the visualizer presets.
---
## 3. Web Audio & Canvas Performance Rules
### 3.1 Thread and zone separation
| Code | Runs on | Hard rules |
|---|---|---|
| `src/assets/worklets/*.js` | Audio render thread | No allocation in `process()`, no `console.*`, no DOM, no `await`, communicate only via `port.postMessage` |
| `core/audio/*`, `core/websocket/*` | Main thread, **outside** Angular zone | No per-frame signal writes; re-enter Angular only by writing a signal on a meaningful, low-frequency change |
| `core/audio/visualizer/*` | Main thread, **outside** Angular zone, `requestAnimationFrame` | **Never** writes signals, never triggers change detection |
| Stores, `VoiceSessionService`, components | Angular domain | Signals, ~1–5 Hz updates |
**Never process audio samples on the main thread.** Capture, framing, quantization, jitter buffering, and sample-rate conversion happen in the worklets.
### 3.2 AudioWorklet rules
- The processors live at `src/assets/worklets/pcm-capture-processor.js` and `src/assets/worklets/pcm-playback-processor.js` (see §1.5). Each starts with `// @ts-check` and uses types from `@types/audioworklet`.
- In `process()`: **preallocate** all buffers in the constructor; reuse them; never create arrays, objects, closures, or strings per call.
- Capture emits fixed **20 ms Int16 PCM frames** and sends them with a **transfer list**: `this.port.postMessage(buffer, [buffer])`. Never copy large buffers.
- Playback owns a ring/jitter buffer, outputs **silence on underrun**, supports an O(1) `flush`, and reports `started`, `drained`, `underrun`.
- Load modules with a **cache-busting version** and a base-href-aware URL:
```ts
const v = inject(APP_CONFIG).workletVersion;
await ctx.audioWorklet.addModule(
new URL(`assets/worklets/pcm-capture-processor.js?v=${v}`, document.baseURI).href,
);
```
- Create the `AudioContext` **only after a user gesture** (the orb click), via the holder in `core/audio/audio-context.provider.ts`. Never at app startup. Resume it if `state === 'suspended'`.
- Request the microphone with `echoCancellation`, `noiseSuppression`, `autoGainControl`, and `channelCount: 1`. Echo cancellation is mandatory because barge-in depends on it.
- Never assume the requested sample rate: read `ctx.sampleRate` and resample in the worklet if it differs from the wire format.
### 3.3 Audio levels: the `AudioLevelBus` exception
Per-frame levels and frequency bands are written into the mutable **`AudioLevelBus`** (`core/audio/audio-level-bus.ts`) and read directly by the visualizer loop.
- **Never** create a `signal` that is updated every animation frame or every audio frame. In zoneless mode that schedules change detection at 60 Hz.
- If a UI element needs a level (e.g., a mic meter), expose a **throttled** (~10 Hz) signal for that element only. Never bind it to the canvas.
- Use `getByteFrequencyData(preallocatedUint8Array)`; never allocate arrays in the loop.
### 3.4 Bypassing Angular change detection for 60 FPS loops
**Any** `requestAnimationFrame` loop, Three.js render loop, canvas drawing loop, high-frequency timer, or `ResizeObserver`/`IntersectionObserver` callback MUST be created inside `NgZone.runOutsideAngular()`.
```ts
@Injectable()
export class VisualizerEngine {
private readonly zone = inject(NgZone);
private readonly destroyRef = inject(DestroyRef);
private readonly bus = inject(AudioLevelBus);
private rafId = 0;
private visualizer?: Visualizer;
private target = STATE_PRESETS.idle;
start(canvas: HTMLCanvasElement): void {
this.zone.runOutsideAngular(() => {
void this.boot(canvas); // renderer creation + loop start
});
this.destroyRef.onDestroy(() => this.dispose());
}
/** Called from an effect() on voiceState changes (~1–5 Hz). Cheap: swaps a preset object. */
applyState(state: VoiceState): void {
this.target = STATE_PRESETS[state];
}
private readonly loop = (t: number): void => {
this.rafId = requestAnimationFrame(this.loop); // already outside the zone
this.visualizer?.render(t, this.bus, this.target); // reads the bus; no signal reads or writes
};
private async boot(canvas: HTMLCanvasElement): Promise<void> {
const { ThreeOrbVisualizer } = await import('./three-orb.visualizer');
this.visualizer = await ThreeOrbVisualizer.create(canvas);
this.rafId = requestAnimationFrame(this.loop);
}
private dispose(): void {
cancelAnimationFrame(this.rafId);
this.visualizer?.dispose();
}
}
```
Rules for the loop:
1. Start it **outside** the zone (a harmless no-op under zoneless, which keeps the code portable).
2. **No** `new` objects, arrays, closures, or strings inside the per-frame function.
3. State reaches the loop through an `effect()` that runs on state **changes** and updates a plain target object; the loop eases toward it. The loop itself never reads signals.
4. Cap `devicePixelRatio` at 2; resize through a `ResizeObserver` created outside the zone.
5. **Pause** when the tab is hidden (`visibilitychange`) or the canvas is off-screen (`IntersectionObserver`).
6. Honor `prefers-reduced-motion` by choosing a calmer preset.
7. Provide a **Canvas 2D fallback** that implements the same `Visualizer` interface (WebGL missing or `webglcontextlost`).
8. Import Three.js lazily (`await import('three')`) and with **named imports** only.
WebSocket `onmessage`, worklet `port.onmessage`, SSE callbacks, and `AnalyserNode` polling timers also run outside the zone. Re-enter Angular only by writing a signal when something human-visible changes (state transition, transcript partial, status).
### 3.5 Cleanup & destruction lifecycle (mandatory)
Every resource that is created must have a release path registered **at the moment of creation**.
| Resource | Release |
|---|---|
| `requestAnimationFrame` handle | `cancelAnimationFrame(id)` |
| Three.js scene | `geometry.dispose()`, `material.dispose()`, every `texture.dispose()`, `renderer.dispose()`, `renderer.forceContextLoss()`, remove event listeners, null references |
| `AudioContext` | Disconnect nodes, `await ctx.close()` |
| `AudioWorkletNode` | `node.port.onmessage = null`, `node.port.close()`, `node.disconnect()` |
| `MediaStream` (microphone) | `stream.getTracks().forEach(t => t.stop())` (this turns off the browser's mic indicator) |
| `AnalyserNode`, `MediaStreamAudioSourceNode` | `disconnect()` |
| `WebSocket` | Remove handlers, `close(1000)`, clear heartbeat and reconnect timers |
| `ResizeObserver`, `IntersectionObserver`, `MutationObserver` | `disconnect()` |
| DOM listeners (`visibilitychange`, `storage`, `devicechange`) | `removeEventListener` (or register through `fromEvent` + `takeUntilDestroyed`) |
| RxJS subscriptions | `takeUntilDestroyed(this.destroyRef)` (never a bare `subscribe()` without teardown) |
| HTTP uploads / SSE | `AbortController` or unsubscribe on destroy; cancel in-flight uploads when their owner is destroyed |
| Timers (`setTimeout`, `setInterval`) | `clearTimeout` / `clearInterval` |
| CDK `OverlayRef` / `DialogRef` | `dispose()` / `close()` |
**Which hook to use**
- **Preferred:** `inject(DestroyRef).onDestroy(() => …)` right next to the creation code.
- Inside an `effect()` that creates something per run: `effect((onCleanup) => { …; onCleanup(() => release()); })`.
- `ngOnDestroy` is acceptable when a class already implements `OnDestroy`; do not add it just to call one release.
- **`untracked()` is not a cleanup mechanism.** It only prevents signal reads from becoming dependencies. Never present it as lifecycle handling.
- Cleanup must be **idempotent** (safe to call twice) and must not throw.
### 3.6 State machine and barge-in rules
- `voiceState` is written **only** by `VoiceSessionService` (`features/voice-agent/services/`), driven by the data table in `voice-transitions.ts`. Never call the store's mutators from components.
- Unlisted events in the current state are **ignored and logged**, never thrown.
- On `BARGE_IN`: **flush local playback first**, then notify the server (`interrupt` with `playedMs`). Never wait for the network.
- Agent audio frames carry a `turnId`; frames from a stale turn are dropped by `audio-stream.handler.ts`.
- `interrupted` is transient and resolves to `listening` after `FLUSH_DONE`.
- Do not introduce new states or transitions without updating `ARCHITECTURE.md` §2 in the same change.
### 3.7 Protocol and transport rules
- Use the `RealtimeTransport` abstraction (`core/websocket/realtime-transport.ts`). Feature code never touches `WebSocket` directly.
- Audio travels in **binary frames** with the documented header (`ARCHITECTURE.md` §5.2); control messages are JSON, typed by `ClientMessage` / `ServerMessage`. Set `binaryType = 'arraybuffer'`.
- Authentication ticket goes in the first JSON message, **never in the URL**.
- Malformed frames are counted and dropped, never thrown.
---
## 4. FAQ Knowledge Base & File Handling Guidelines
### 4.1 Layer separation (strict)
```text
UI components (features/faq-manager/components/*)
│ inputs/outputs only
▼
FaqStore (signals) ◄──── FaqIngestionService (orchestration)
│
┌─────────────┼───────────────────────┐
▼ ▼ ▼
FileValidatorService CsvParserService FaqApiService / IngestionEventsService
(UX validation) (preview only) (HTTP + status events to the backend)
│
▼
Backend: parsing, chunking, embedding, vector index (RAG)
```
- **UI components never call HTTP, never know about chunks, embeddings, or vector indexes.** They read `FaqStore` signals and emit events.
- **The client never performs embedding, chunking, or retrieval.** It uploads files and edits Q&A pairs; the backend owns indexing and RAG synchronization.
- All FAQ HTTP traffic goes through **`HttpService`** (via `FaqApiService` / `FaqIngestionService`). No feature injects `HttpClient` directly.
- `FaqIngestionService` is the only orchestrator of `validate → preview → upload → track status`.
- Status flows from the server through `IngestionEventsService` (SSE via `HttpService.getStream` or control messages) into `FaqStore` signals: `uploading → indexing → active | error`. Status is **never** inferred on the client.
- `features/faq-manager` must not import from `features/voice-agent` (and vice versa). Shared concerns go in `core/` or `shared/`.
- The voice session learns which documents to use only through `activeDocumentIds` in the session configuration (from `FaqStore.activeDocuments`), not by reaching into FAQ components.
### 4.2 PapaParse pre-parsing (CSV)
- **Lazy-load:** `const Papa = (await import('papaparse')).default;` inside `CsvParserService`. Never import it at the top of a component.
- **Preview** with `Papa.parse(file, { header: true, preview: N, skipEmptyLines: 'greedy', dynamicTyping: false })`, with `N` defaulting to 50.
- **Count and validate large files** with chunked streaming (`chunk` or `step`) so memory stays bounded. **Do not use `worker: true`** (see §1.5).
- Treat every cell as a **string**; never trust types, never `eval`. Strip a UTF-8 BOM, tolerate `\r\n`, and let PapaParse auto-detect the delimiter.
- Auto-detect question and answer columns with `csv-column-detect.ts`, and let the user remap them in `upload-preview-table`.
- Report row problems with `CsvRowError` (`MISSING_QUESTION`, `MISSING_ANSWER`, `TOO_LONG`, `MALFORMED`). A row error is a **warning in the preview**, not a crash.
- **The parsed rows are for preview only.** Upload the **original file** (`FormData`); the server re-parses and is the source of truth. Do not send client-parsed JSON as the dataset.
- Never log file contents or cell values (they may contain personal data).
### 4.3 Validation of all file types (client side = UX only)
- Check extension, MIME type, size limit, and **magic bytes** via `file-validator.service.ts` and `file-signatures.ts` (PDF `%PDF`; DOCX is a ZIP, `PK\x03\x04`; JSON/CSV are text).
- PDF and DOCX are **not parsed in the browser by default**. Optional previews (`pdfjs-dist`, `mammoth`) require explicit approval and a dynamic import (`DEPENDENCIES.md` §3.5).
- **Never treat client validation as a trust boundary.** The server must revalidate; write UI copy accordingly.
- Rejected files produce a typed `FaqDocumentError` with a user-readable message and a `retryable` flag.
### 4.4 Upload, status, and Q&A editing
- Upload through **`HttpService`** (or `FaqApiService` built on it). If upload progress is required, extend `HttpService` with a progress-capable method rather than injecting raw `HttpClient` in a feature. Write `progress` into the document's signal state. Cancel with unsubscribe/`AbortController` when the owner is destroyed.
- The document row has one writer (`FaqStore`). Use immutable `update()` calls keyed by `id`.
- Q&A edits are **optimistic with rollback**: apply to `FaqStore`, send the request, roll back and toast on failure. A manual edit sets `overridden: true` so re-ingestion does not overwrite it.
- **AG Grid** (`ag-grid-angular`, `ag-grid-community` on identical versions):
- Register modules once in `grid/register-grid-modules.ts`; apply the theme through the JS theme API (`grid/qa-grid.theme.ts`), not CSS imports.
- The grid is wrapped by `QaGridComponent` (signal inputs, outputs only). Feature code never touches the grid API outside that component.
- Cell renderers are OnPush standalone components in `grid/cell-renderers/`.
- Never trigger row-model refreshes at frame rate; batch updates with `applyTransaction`.
- The grid and PapaParse chunk must stay **out of the initial bundle** (lazy routes + dynamic imports).
---
## 5. Navigation Guide: where things go
| You are adding… | Put it in… |
|---|---|
| A new voice UI element (button, overlay, badge) | `features/voice-agent/components/<name>/` |
| Voice transition, guard, or side effect | `features/voice-agent/services/voice-transitions.ts` / `voice-effects.ts` |
| Anything that touches `AudioContext`, mic, or worklet nodes | `core/audio/` |
| The orb, shaders, canvas fallback | `core/audio/visualizer/` |
| WebSocket, framing, reconnect, heartbeat | `core/websocket/` |
| Global signals store, storage, telemetry, notifications | `core/services/` |
| Shared types used by core and features | `core/models/` |
| FAQ UI | `features/faq-manager/components/<name>/` |
| FAQ state, upload logic, parsing, API | `features/faq-manager/services/` |
| Reusable button/badge/dialog/spinner/pipe/directive | `shared/ui`, `shared/pipes`, `shared/directives` |
| AudioWorklet script | `src/assets/worklets/` |
| Design tokens / Tailwind utilities | `src/styles/theme.css` / `src/styles/utilities.css` |
| HTTP calls to the API | **Use existing `HttpService` only** — do not add a parallel client |
| Login, auth check, route guard | **Use existing `AuthService` + `authGuard` only** |
| Theme init / dark-mode toggle | **Use existing `ThemeService` only** (`initTheme`, `toggleDarkMode`) |
**Import boundaries** (enforced by ESLint `no-restricted-imports`):
```text
shared <- core <- features
```
- `shared` imports nothing from `core` or `features`.
- `core` imports from `shared` only, never from `features`.
- A feature never imports another feature.
- `core/audio` and `core/websocket` import no UI code (no components, no CDK), so they remain testable without a DOM.
- Use `@core/…`, `@features/…`, `@shared/…` aliases; never deep relative paths that cross layer boundaries (`../../../core/…`).
---
## 6. Security, Privacy, and Reliability
- Use `wss://` and `https://` outside local development. Authentication tickets go in message bodies or headers, **never in URLs**.
- **Never log or persist** raw audio, transcripts, uploaded file contents, or tokens. Telemetry carries counts, durations, and error codes only.
- Auth tokens (`access_token`) and username are managed **only** by `AuthService` / `HttpService` (including 401 cleanup). Theme preference may live in `localStorage` **only** via `ThemeService`. Other preferences go through `StorageService` if present. Never tokens, transcripts, or file data in ad-hoc storage.
- Never use `innerHTML`, `bypassSecurityTrust*`, or `eval`/`new Function` with user, server, or model-generated text. Transcripts and Q&A are rendered as text.
- Every error path is handled: microphone denied, `AudioContext` suspended, worklet load failure, socket drop mid-turn, token expiry, WebGL context loss, upload failure. Map to `VoiceError` / `FaqDocumentError` and tell the user what to do next.
- API user-visible messages and 401 handling are owned by `HttpService` (toasts + redirect). For non-HTTP app errors, use the project notification layer; do not swallow errors or only `console.log` them.
- Protect authenticated routes with `authGuard`. Do not implement a second guard that bypasses `AuthService.isAuthenticated()`.
---
## 7. Testing Rules
- **Colocate** `*.spec.ts` next to the file. The test runner is Vitest through the Angular builder.
- Pure logic gets pure tests: `voice-transitions.ts` (table-driven, including ignored events), `frame-codec.ts` (golden byte arrays), `pcm-utils.ts`, `connection.machine.ts`, `reconnect-policy.ts`, `csv-column-detect.ts`, `file-signatures.ts`.
- `VoiceSessionService` is tested with fake `AudioEngine` and fake `RealtimeTransport`, including barge-in races and stale `turnId` frames.
- Configure tests for zoneless (`provideZonelessChangeDetection()`); await `fixture.whenStable()`; do not use `fakeAsync`.
- Components are tested through their **signal inputs and rendered output**, not private members.
- A change to the audio path or visualizer must keep the performance assertion: **zero change-detection ticks per second** while the orb animates (see `ARCHITECTURE.md` §3.7).
- Never weaken, skip (`xit`, `.skip`), or delete a test to get green. Fix the code or ask.
---
## 8. Anti-Pattern Table (never write these)
| Forbidden | Use instead |
|---|---|
| `BehaviorSubject<boolean>` for UI state | `signal<boolean>()` |
| `@Input()` / `@Output()` / `@ViewChild()` decorators | `input()` / `output()` / `viewChild()` |
| Component without `OnPush` | `changeDetection: ChangeDetectionStrategy.OnPush` |
| `*ngIf` / `*ngFor` | `@if` / `@for … track` |
| NgModule, `standalone: false` | Standalone component with `imports: []` |
| `setInterval`/`requestAnimationFrame` started inside the zone for a render loop | `NgZone.runOutsideAngular(...)` |
| Signal updated every frame | `AudioLevelBus` (machine reads) + throttled signal (UI reads) |
| Audio sample processing or resampling on the main thread | `AudioWorklet` |
| `new AudioContext()` at startup | Lazy creation on the first user gesture |
| Subscribing without teardown | `takeUntilDestroyed()` / `DestroyRef` |
| `untracked()` described as cleanup | `DestroyRef.onDestroy()` / `effect` `onCleanup` |
| `effect()` that derives state | `computed()` / `linkedSignal()` |
| Mutating an array or object held in a signal | `signal.update()` with a new value |
| `provideExperimentalZonelessChangeDetection()` on Angular 22 | `provideZonelessChangeDetection()` |
| Importing `lucide-angular` or any Lucide package directly in a feature | `<app-icon>` via `shared/ui/icon` |
| `Papa.parse(file, { worker: true })` | `preview` + chunked streaming |
| Uploading client-parsed rows as the dataset | Upload the original file; parse client-side for preview only |
| UI component calling backend RAG/vector endpoints | Go through `FaqIngestionService` / `FaqApiService` |
| Feature importing another feature | Move shared code to `core/` or `shared/` |
| Adding a library not in `DEPENDENCIES.md` | Ask first, justify, update the doc |
| `ml-*` / `pr-*` / `left-*` / `right-*` for direction | `ms-*` / `pe-*` / `start-*` / `end-*` |
| `any`, unchecked `!`, swallowed errors, `console.log` for errors | Narrow types; `NotificationService` + `LoggerService` |
| Direct `HttpClient` / bare `fetch` for API routes | `HttpService.get/post/put/patch/delete/getStream/downloadFile` |
| Hand-rolled login POST + writing `access_token` yourself | `AuthService.login()`; protect routes with `authGuard` |
| Reading/writing theme or `data-bs-theme` outside ThemeService | `ThemeService.initTheme()` / `toggleDarkMode()` / `isDarkMode` |
| Second HTTP client, auth store, or theme store that bypasses the above | Extend or wrap the existing services; single writer |
---
## 9. Mandatory Code-Generation Checklist
**Before returning code, verify every applicable item. If an item fails, fix the code. If you cannot fix it, say so explicitly in your reply. Never claim a check passed that you did not actually perform.**
### 9.1 Core checklist (always)
- [ ] **OnPush:** Is `changeDetection: ChangeDetectionStrategy.OnPush` present on every component I created or touched?
- [ ] **Signals:** Is UI state in `signal()` / `computed()` / `linkedSignal()` (not `BehaviorSubject`, not mutable fields), and do all template updates come from signal writes, so the code works **without Zone.js**?
- [ ] **60 FPS loops:** Is every `requestAnimationFrame` / Three.js / canvas loop (and every high-frequency observer) created inside `NgZone.runOutsideAngular()`, with **no signal read or written per frame**?
- [ ] **Cleanup:** Is every subscription, `AudioContext`, `AudioWorkletNode`, `MediaStream` track, `WebSocket`, observer, timer, overlay, and Three.js object (geometry, material, texture, renderer) released through `DestroyRef` / effect cleanup / `ngOnDestroy`?
- [ ] **Paths:** Does every file path match `./docs/SRC_STRUCTURE.md`, and do the imports respect `shared <- core <- features`?
### 9.2 Angular conventions
- [ ] Standalone only (no NgModule, no `standalone: false`; flag omitted on Angular 19+, present on 18).
- [ ] `input()` / `output()` / `model()` / `viewChild()` / `inject()` used instead of decorators and constructor injection.
- [ ] `@if` / `@for` (with `track`) / `@switch`; templates call only signals/computeds.
- [ ] Zoneless provider matches the installed Angular major (§1.5); no reliance on `NgZone.onStable` or `detectChanges()` in hot paths.
- [ ] One writer per state; public API exposes `asReadonly()`.
- [ ] No `effect()` used to derive state; no signal writes inside `computed()`.
- [ ] Exhaustive `switch` on discriminated unions (`assertNever`).
- [ ] Strict typing: no `any`, no unexplained `!`.
### 9.3 Audio, canvas, and transport
- [ ] No audio-sample processing on the main thread; worklet code allocates nothing in `process()` and uses transferables.
- [ ] Worklet files are in `src/assets/worklets/` and loaded with a version query.
- [ ] `AudioContext` is created after a user gesture and resumed when suspended.
- [ ] Per-frame levels go through `AudioLevelBus`; UI meters use a throttled signal.
- [ ] Barge-in flushes playback locally first; stale `turnId` frames are dropped.
- [ ] Visualizer pauses when hidden, caps DPR at 2, honors `prefers-reduced-motion`, and has a fallback.
- [ ] `three` is lazily imported with named imports; shaders are imported as text from `core/audio/visualizer/shaders/`.
### 9.4 FAQ and file handling
- [ ] PapaParse is lazily imported, used with `preview`/chunking (never `worker: true`), and parsed rows are used for preview only.
- [ ] The **original file** is what gets uploaded; the client does no embedding, chunking, or retrieval.
- [ ] UI components do not call HTTP or backend RAG/vector APIs; they go through the store and `FaqIngestionService`.
- [ ] File validation includes size, extension/MIME, and magic bytes; no file contents are logged.
- [ ] Grid modules are registered once; AG Grid is accessed only through `QaGridComponent`.
### 9.5 Project hygiene
- [ ] Only approved libraries from `DEPENDENCIES.md`; icons through `shared/ui/icon`.
- [ ] Tailwind tokens and logical properties used; no hard-coded colors; no `ml-*`/`pr-*`.
- [ ] Accessible names, keyboard support, and `aria-live` for state changes.
- [ ] Error paths handled and surfaced; no secrets, tokens, audio, or transcripts logged or persisted.
- [ ] Tests added or updated (pure logic first); none skipped or deleted.
- [ ] Any change to states, protocol, folders, or dependencies is reflected in the matching `./docs/*.md` file in the same change.
- [ ] **Http / Auth / Theme:** all API calls go through `HttpService`; login and session via `AuthService` + `authGuard`; theme init/toggle via `ThemeService` only (no parallel clients or direct token/theme storage).
---
## 10. Response Protocol for Agents
1. **Before code:** list the files you will create/edit (with paths from `SRC_STRUCTURE.md`) and the rules that apply, in two to five lines.
2. **Code:** complete files or clear diffs. No `// ...rest of code`, no pseudo-code, no TODO placeholders for core logic.
3. **After code:** a short **Checklist result** (§9). List only items that were *not* satisfied, plus any assumption you made. If all passed, say so in one line.
4. **Ask instead of guessing** when: a doc is missing, docs conflict, a new dependency is needed, a state or protocol change is implied, the backend contract is unknown, or the Angular version is unclear.
5. **Keep changes minimal and focused.** Mention (do not perform) unrelated cleanups.
6. **Never** weaken a rule in this file to make a request easier. Explain the conflict and offer a compliant option.
---
## 11. Reference Templates
### 11.1 New component
```ts
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
@Component({
selector: 'app-example',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
template: `
@if (items().length) {
<ul class="space-y-2">
@for (item of items(); track item.id) {
<li class="glass rounded-xl px-3 py-2">
<button type="button" (click)="selected.emit(item.id)">{{ item.label }}</button>
</li>
}
</ul>
} @else {
<p class="text-slate-400">{{ emptyText() }}</p>
}
`,
})
export class ExampleComponent {
readonly items = input.required<readonly { id: string; label: string }[]>();
readonly selected = output<string>();
protected readonly emptyText = computed(() => 'Nothing here yet.');
}
```
### 11.2 Resource with guaranteed cleanup
```ts
@Injectable({ providedIn: 'root' })
export class ExampleResourceService {
private readonly destroyRef = inject(DestroyRef);
private socket?: WebSocket;
open(url: string): void {
this.close();
this.socket = new WebSocket(url); // created outside the zone by the caller
this.socket.binaryType = 'arraybuffer';
this.destroyRef.onDestroy(() => this.close()); // release registered at creation time
}
close(): void { // idempotent, never throws
if (!this.socket) return;
this.socket.onmessage = null;
this.socket.onclose = null;
try { this.socket.close(1000); } catch { /* already closed */ }
this.socket = undefined;
}
}
```
### 11.3 `effect()` that owns a resource
```ts
constructor() {
effect((onCleanup) => {
const state = this.voiceState(); // dependency
const handle = this.thing.subscribeTo(state); // per-run resource
onCleanup(() => handle.release()); // released on re-run and on destroy
});
}
```
---
## 12. Maintaining This File
- Treat this file like code: change it through a pull request, in the same PR as any architecture change.
- When `ARCHITECTURE.md`, `SRC_STRUCTURE.md`, or `DEPENDENCIES.md` change, update §1.5 (known deltas), §5 (navigation), and §8 (anti-patterns) accordingly.
- When Angular is upgraded, re-verify §1.5 (zoneless provider name, `standalone` default, `resource()` stability) and §2.3.
- Keep the checklist in §9 short enough to be followed every time. Add an item only when a real defect has slipped through twice.