diff --git a/docs/analytics-taxonomy.md b/docs/analytics-taxonomy.md
index df18459..38618b4 100644
--- a/docs/analytics-taxonomy.md
+++ b/docs/analytics-taxonomy.md
@@ -1,117 +1,130 @@
-# đ Taxonomie & ĂvĂ©nements Analytics (Zero-PII & Privacy-First)
+# đ Zero-PII Analytics & Telemetry Taxonomy Contract
-Ce document formalise la structure, les événements et les paramÚtres de télémétrie de **Agentic Android Kernel**.
+This document formalizes the telemetry structure, event taxonomy, and privacy invariants for applications built on the **Agentic Android Delivery Kernel**.
---
-## đĄïž 1. Principes de ConfidentialitĂ© & Ăthique (Zero-PII)
+## đĄïž 1. Privacy Principles & Ethics (Zero-PII)
-L'architecture de télémétrie de Agentic Android Kernel est conçue selon le principe strict du **Privacy by Design** :
+The telemetry architecture of the Agentic Android Delivery Kernel enforces a strict **Privacy by Design** foundation:
-1. **Aucune Donnée Personnelle Identifiable (Zero-PII)** : Les titres de tùches, descriptions, noms propres, adresses emails et contenus saisis par l'utilisateur ne sont **jamais** envoyés dans les événements d'analytics.
-2. **Bucketing / Plages de Valeurs** : Toutes les longueurs de texte et les nombres d'éléments sont regroupés en intervalles discrets (ex: `1-20`, `21-50`, `51-100`, `100+`) pour éviter tout traçage indirect par empreinte textuelle.
-3. **Comportement Hors-Ligne & Robuste** : Si Firebase Analytics n'est pas initialisé ou en mode avion, le tracker encapsule les appels sans aucun crash ni blocage de l'UI (`FirebaseAnalyticsTracker`).
+1. **Zero Personally Identifiable Information (Zero-PII)**: User-generated content, free-form text, titles, notes, personal names, email addresses, and phone numbers are **strictly prohibited** in analytics event parameters.
+2. **Cardinality Control & Bucketing**: All textual lengths, item quantities, and durations must be grouped into discrete intervals (e.g., `1-10`, `11-20`, `21-50`, `50+` or `0`, `1-5`, `6-15`, `16-30`, `30+`) to eliminate indirect user fingerprinting.
+3. **Graceful Degradation & Offline Safety**: If the analytics provider is uninitialized, blocked by network configuration, or in airplane mode, the tracking layer safely encapsulates calls without causing runtime exceptions or blocking the main thread.
---
-## đ 2. PropriĂ©tĂ©s Utilisateur (User Properties)
+## đ 2. Canonical User Properties
-| Clé | Type | Exemples de Valeurs | Description |
+User properties capture macro-level application state without storing individual behavioral profiles:
+
+| Property Key | Type | Example Values | Description |
|---|---|---|---|
-| `access_state` | String | `guest`, `solo`, `duo` | Ătat d'accĂšs actuel (InvitĂ©, ConnectĂ© Solo, JumelĂ© en Duo). |
-| `theme_preference` | String | `light`, `dark`, `system` | Préférence de thÚme d'affichage. |
-| `is_partner_linked` | Boolean | `true`, `false` | Indique si le compte est jumelé à un partenaire. |
-| `active_loads_bucket` | String | `0`, `1-5`, `6-15`, `16-30`, `30+` | Tranche du nombre de charges mentales actives. |
-| `focus_streak_bucket` | String | `0`, `1-3`, `4-7`, `8-14`, `15-30`, `30+` | Série quotidienne de priorisation active. |
+| `access_state` | String | `guest`, `solo`, `duo` | Current access level within the 3-State Access Matrix. |
+| `theme_preference` | String | `light`, `dark`, `system` | Active UI theme preference. |
+| `account_link_state` | String | `anonymous`, `authenticated_solo`, `paired_shared` | Identity and authentication topology. |
+| `active_entities_bucket` | String | `0`, `1-5`, `6-15`, `16-30`, `30+` | Total volume of active domain entities managed by the user. |
+| `engagement_streak_bucket` | String | `0`, `1-3`, `4-7`, `8-14`, `15-30`, `30+` | Daily usage and prioritization streak interval. |
---
-## đ·ïž 3. Catalogue des ĂvĂ©nements par Domaine Fonctionnel
+## đ·ïž 3. Event Taxonomy by Functional Domain
+
+### đ§ A. AI Assistance & Two-Tier Classification
-### đ§ A. Intelligence Artificielle & Classification Two-Tier (Issue #2)
+Telemetry events measuring the accuracy, latency, and user adoption of AI suggestions:
-| Nom de l'ĂvĂ©nement | ParamĂštres | Description |
+| Event Name | Parameters | Description |
|---|---|---|
-| `ai_classification_triggered` | `input_length_bucket` (String : `1-10`, `11-20`, `21-50`, `50+`)
`has_partner_context` (Boolean) | Déclenché lors de l'évaluation cognitive d'une tùche. |
-| `ai_quadrant_suggested` | `source` (String : `heuristic`, `gemini_flash`)
`suggested_quadrant` (String : `do_today`, `schedule`, `delegate`, `park`)
`suggested_area` (String : `self`, `home`, `work`)
`confidence_bucket` (String : `high`, `medium`, `low`) | Ămis lorsqu'une suggestion de quadrant et de domaine de vie est prĂ©sentĂ©e Ă l'utilisateur. |
-| `ai_quadrant_applied` | `quadrant` (String)
`area` (String)
`source` (String)
`time_to_apply_ms` (Long) | Enregistré lorsque l'utilisateur touche le chip de suggestion pour l'appliquer en 1-tap. |
-| `ai_quadrant_dismissed` | `suggested_quadrant` (String)
`manual_selected_quadrant` (String)
`suggested_area` (String, opt)
`manual_selected_area` (String, opt) | Enregistré lorsque l'utilisateur ignore ou remplace la suggestion IA par un choix manuel. |
+| `ai_classification_triggered` | `input_length_bucket` (String: `1-10`, `11-20`, `21-50`, `50+`)
`has_context` (Boolean) | Triggered when cognitive evaluation of an input starts. |
+| `ai_suggestion_presented` | `source` (String: `heuristic`, `cloud_llm`)
`suggested_category` (String)
`suggested_priority` (String)
`confidence_bucket` (String: `high`, `medium`, `low`) | Emitted when an AI recommendation is displayed in the UI. |
+| `ai_suggestion_applied` | `category` (String)
`priority` (String)
`source` (String)
`time_to_apply_ms` (Long) | Recorded when the user applies an AI suggestion with a 1-tap interaction. |
+| `ai_suggestion_dismissed` | `suggested_category` (String)
`manual_override_selected` (String)
`source` (String) | Recorded when the user dismisses or manually overrides the AI recommendation. |
---
-### đ B. Capture Rapide & Gestion des Charges Mentales
+### đ B. Entity Lifecycle & Data Operations
-| Nom de l'ĂvĂ©nement | ParamĂštres | Description |
+Lifecycle events tracking the creation, mutation, and completion of domain entities:
+
+| Event Name | Parameters | Description |
|---|---|---|
-| `quick_capture_submitted` | `char_count_bucket` (String : `1-20`, `21-50`, `51-100`, `100+`)
`has_details` (Boolean) | Soumission d'une pensée depuis la barre d'accueil. |
-| `mental_load_created` | `area` (String : `self`, `home`, `work`)
`quadrant` (String)
`is_shared` (Boolean)
`is_ai_assisted` (Boolean) | Création et sauvegarde d'une nouvelle charge mentale. |
-| `mental_load_updated` | `area` (String)
`quadrant` (String)
`is_shared` (Boolean)
`changed_quadrant` (Boolean)
`changed_area` (Boolean) | Mise à jour des propriétés d'une tùche existante. |
-| `mental_load_deleted` | `area` (String)
`quadrant` (String)
`was_completed` (Boolean)
`was_shared` (Boolean) | Suppression d'une charge mentale. |
-| `task_completed` | `area` (String)
`quadrant` (String)
`is_shared` (Boolean)
`is_voted_today` (Boolean) | Coche / complétion d'une tùche. |
-| `task_reopened` | `area` (String)
`quadrant` (String)
`is_shared` (Boolean) | Réouverture d'une tùche terminée. |
-| `task_filter_applied` | `filter_mode` (String : `all`, `shared`, `personal`, `top3`)
`results_count` (Int) | Application d'un filtre sur la liste des charges. |
+| `quick_capture_submitted` | `char_count_bucket` (String: `1-20`, `21-50`, `51-100`, `100+`)
`has_details` (Boolean) | Rapid thought or item capture from entry surfaces. |
+| `entity_created` | `category` (String)
`priority_tier` (String)
`is_shared` (Boolean)
`is_ai_assisted` (Boolean) | Creation and persistence of a new domain entity. |
+| `entity_updated` | `category` (String)
`changed_category` (Boolean)
`changed_priority` (Boolean)
`is_shared` (Boolean) | Mutation of existing entity attributes. |
+| `entity_deleted` | `category` (String)
`was_completed` (Boolean)
`was_shared` (Boolean) | Entity deletion from local or remote stores. |
+| `entity_completed` | `category` (String)
`priority_tier` (String)
`is_shared` (Boolean) | Marking an entity as resolved or completed. |
+| `entity_reopened` | `category` (String)
`is_shared` (Boolean) | Reopening a previously completed entity. |
+| `entity_filter_applied` | `filter_mode` (String: `all`, `shared`, `personal`, `priority`)
`results_count_bucket` (String) | Filtering entity lists or collection views. |
---
-### đ§ C. Matrice d'Eisenhower & Priorisation Quotidienne
+### đ§ C. Priority Matrix & Workflow State
+
+Events monitoring workflow state transitions and daily prioritization:
-| Nom de l'ĂvĂ©nement | ParamĂštres | Description |
+| Event Name | Parameters | Description |
|---|---|---|
-| `daily_vote_toggled` | `action` (String : `added`, `removed`)
`current_voted_count` (Int : `1` Ă `3`)
`area` (String)
`quadrant` (String) | Ajout ou retrait d'une tĂąche dans le Top 3 quotidien. |
-| `daily_vote_limit_reached` | `max_votes` (Int : `3`)
`active_loads_count` (Int) | Tentative de dépassement de la limite de 3 votes. |
-| `daily_votes_reset` | `previous_voted_count` (Int) | Réinitialisation quotidienne des votes Top 3. |
-| `quadrant_reassigned` | `previous_quadrant` (String, opt)
`target_quadrant` (String)
`area` (String) | Déplacement direct d'une tùche vers un autre quadrant. |
+| `priority_item_toggled` | `action` (String: `added`, `removed`)
`current_priority_count` (Int)
`category` (String) | Adding or removing an item from primary focus. |
+| `priority_limit_reached` | `max_limit` (Int)
`active_items_count` (Int) | User notification when attempting to exceed daily focus caps. |
+| `priority_batch_reset` | `previous_count` (Int) | Scheduled or manual reset of high-priority focus items. |
+| `workflow_state_reassigned` | `previous_state` (String, opt)
`target_state` (String)
`category` (String) | Moving an entity across workflow states or quadrants. |
---
-### đ« D. Espace Duo & Jumelage Partenaire
+### đ« D. Duo Collaboration & Real-Time Sync
-| Nom de l'ĂvĂ©nement | ParamĂštres | Description |
+Telemetry covering shared state, pairing rituals, and collaborative interactions:
+
+| Event Name | Parameters | Description |
|---|---|---|
-| `partner_invite_generated` | `is_regenerated` (Boolean) | Génération d'un code sanctuaire `SANCTUARY-XXXXXX`. |
-| `partner_join_attempted` | `code_format_valid` (Boolean) | Soumission d'un code d'invitation partenaire. |
-| `partner_paired_success` | `method` (String : `sanctuary_code`) | Jumelage réussi des deux profils. |
-| `partner_paired_failed` | `error_reason` (String) | Ăchec de jumelage (code invalide, dĂ©jĂ liĂ©). |
-| `partner_unpaired` | `active_tasks_count` (Int) | Dissociation du partenaire. |
-| `partner_upvote_toggled` | `action` (String)
`area` (String)
`is_completed` (Boolean) | Vote de soutien/priorité sur une tùche partagée. |
-| `partner_ledger_viewed` | `active_dimension` (String)
`total_shared_tasks` (Int) | Consultation du Grand Livre de synergie. |
-| `partner_ledger_dim_changed`| `selected_dimension` (String : `active`, `initiated`, `resolved`)
`user_percentage` (Int)
`partner_percentage` (Int) | Bascule entre les 3 dimensions de charge du couple. |
-| `couple_synergy_viewed` | `focus_streak_days` (Int)
`total_completed_shared` (Int) | Ouverture de la modale de célébration de couple. |
-| `shared_privacy_updated` | `privacy_mode` (String) | Modification de la visibilité des tùches partagées. |
+| `pairing_invite_generated` | `is_regenerated` (Boolean) | Generating a secure pairing or invitation code. |
+| `pairing_join_attempted` | `code_format_valid` (Boolean) | Submitting an invitation code to join a shared workspace. |
+| `pairing_success` | `method` (String: `invite_code`, `qr`, `link`) | Successful establishment of a shared session. |
+| `pairing_failed` | `error_reason` (String) | Pairing error (expired token, mismatched version, already linked). |
+| `pairing_disconnected` | `active_shared_count` (Int) | Unlinking from a shared workspace. |
+| `collaborator_interaction` | `action` (String)
`category` (String)
`is_completed` (Boolean) | Collaborative action or support vote on a shared item. |
+| `shared_ledger_viewed` | `active_dimension` (String)
`total_shared_items` (Int) | Inspecting shared collaboration metrics or ledgers. |
+| `shared_privacy_updated` | `privacy_mode` (String) | Updating visibility or permission rules for shared data. |
---
-### đ E. Authentification, Soft-Gating & ParamĂštres
+### đ E. Authentication, Soft-Gating & System Settings
+
+Core system lifecycle, authentication flows, and accessibility preferences:
-| Nom de l'ĂvĂ©nement | ParamĂštres | Description |
+| Event Name | Parameters | Description |
|---|---|---|
-| `screen_view` | `screen_name` (String)
`screen_class` (String)
`access_state` (String)
`active_loads_count` (Int)
`voted_loads_count` (Int) | Navigation vers un écran. |
-| `sign_in_started` | `source` (String) | Déclenchement de la connexion Google. |
-| `sign_in_success` | *(aucun)* | Connexion réussie. |
-| `sign_in_failed` | `error_type` (String)
`error_message` (String) | Ăchec de connexion Google. |
-| `sign_out` | `previous_access_state` (String) | Déconnexion volontaire de l'utilisateur. |
-| `soft_gate_shown` | `trigger_feature` (String) | Affichage de la boĂźte de dialogue invitant Ă la connexion/jumelage. |
-| `theme_changed` | `new_theme` (String)
`previous_theme` (String, opt) | Changement du mode de thĂšme (Clair / Sombre / SystĂšme). |
-| `gentle_reset_started` | `source` (String) | Lancement de la respiration guidée 4-4-4. |
-| `gentle_reset_completed` | `duration_seconds` (Int : `30`)
`current_streak` (Int) | Complétion d'une session de recentrage zen. |
+| `screen_view` | `screen_name` (String)
`screen_class` (String)
`access_state` (String)
`active_items_bucket` (String) | Screen navigation tracking. |
+| `sign_in_started` | `source` (String) | Initiating an authentication provider flow. |
+| `sign_in_success` | `provider` (String: `google`, `credential`) | Successful identity authentication. |
+| `sign_in_failed` | `error_type` (String)
`error_message` (String) | Authentication failure or cancellation. |
+| `sign_out` | `previous_access_state` (String) | User-initiated sign-out. |
+| `soft_gate_prompt_shown` | `trigger_feature` (String)
`target_state` (String) | Prompting an unauthenticated user to sign in or pair. |
+| `theme_changed` | `new_theme` (String)
`previous_theme` (String, opt) | Theme mode change (Light, Dark, System). |
---
-### đ F. RĂ©currence, ĂchĂ©ances & Rotation AlternĂ©e Duo (Issue #1)
+### đ F. Recurrence, Scheduling & Workload Rotation
+
+Events governing temporal rules, recurring schedules, and collaborative rotation:
-| Nom de l'ĂvĂ©nement | ParamĂštres | Description |
+| Event Name | Parameters | Description |
|---|---|---|
-| `task_due_date_set` | `is_preset` (Boolean)
`preset_type` (String, opt : `today`, `tomorrow`, `weekend`, `next_week`)
`is_recurring` (Boolean)
`days_until_due` (Int, opt) | Définition ou sélection rapide d'une échéance temporelle sur une charge mentale. |
-| `recurring_task_created` | `frequency` (String : `daily`, `weekdays_only`, `weekends_only`, `weekly`, `biweekly`, `monthly`, `yearly`)
`is_duo_rotating` (Boolean)
`has_due_date` (Boolean)
`area` (String) | Création d'une tùche récurrente ou périodique. |
-| `recurring_task_completed` | `frequency` (String)
`cycle_count` (Int)
`is_duo_rotating` (Boolean)
`has_due_date` (Boolean) | Complétion d'un cycle de tùche récurrente et déclenchement automatique du cycle suivant. |
-| `duo_rotation_assigned` | `frequency` (String)
`cycle_count` (Int)
`next_assignee_role` (String : `partner`, `self`)
`days_to_next_due` (Int, opt) | Alternance automatique du responsable de la tĂąche pour le cycle suivant. |
+| `entity_due_date_set` | `is_preset` (Boolean)
`preset_type` (String, opt)
`is_recurring` (Boolean)
`days_until_due_bucket` (String, opt) | Setting a deadline or due date on an entity. |
+| `recurring_rule_created` | `frequency` (String: `daily`, `weekly`, `monthly`, `custom`)
`is_shared_rotating` (Boolean)
`category` (String) | Creating an automated recurrence schedule. |
+| `recurring_cycle_completed` | `frequency` (String)
`cycle_count` (Int)
`is_shared_rotating` (Boolean) | Completing a cycle and generating the next scheduled instance. |
+| `rotation_assigned` | `frequency` (String)
`cycle_count` (Int)
`next_assignee_role` (String: `partner`, `self`, `team`) | Automatic rotation of responsibility across collaborators. |
---
-## đ§Ș 4. Validation & Tests AutomatisĂ©s
+## đ§Ș 4. Automated Verification
-Tous les événements et leurs sérialisations de paramÚtres sont validés dans les tests unitaires :
+All analytics events and parameter bundle builders must be validated with unit tests verifying:
+1. Zero PII parameter keys and value formats.
+2. Proper bucketing of numeric and length inputs.
+3. Safe execution when analytics dependencies are mocked or disabled.
```bash
-./gradlew testDebugUnitTest --tests com.secondbrain.app.data.analytics.AnalyticsTrackerTest
+./gradlew testDebugUnitTest --tests "*AnalyticsTrackerTest*"
```
diff --git a/docs/qa-classification-test-guide.md b/docs/qa-classification-test-guide.md
index 495f6c9..cd76719 100644
--- a/docs/qa-classification-test-guide.md
+++ b/docs/qa-classification-test-guide.md
@@ -1,116 +1,128 @@
-# đ§ Guide de Test & RĂ©fĂ©rentiel de Classification IA (Matrice de ClartĂ© & Domaines de Vie)
+# đ§ QA Test Guide & Two-Tier AI Verification Reference
-Ce document détaille la philosophie de gestion cognitive de **Agentic Android Kernel**, le comportement du moteur hybride **Two-Tier (Heuristique locale + Gemini Flash-Lite)**, ainsi que la **matrice de test exhaustive (les 12 combinaisons)** pour valider les suggestions de quadrants et de domaines de vie.
+This document establishes the quality assurance standards, defect classification matrix, and verification protocols for applications powered by the **Agentic Android Delivery Kernel**, with emphasis on the **Two-Tier Hybrid AI Architecture (Local Heuristics + Cloud LLM)** and the **3-State Access Matrix**.
---
-## đż 1. Philosophie & Vocabulaire Ămotionnel Positif
+## đŠ 1. Defect Severity & Classification Matrix
-Agentic Android Kernel applique les principes de la **Matrice d'Eisenhower** et de la méthode **GTD (Getting Things Done)**, réinterprétés à travers une approche apaisante (*Serene UX*) :
+Persona 6 (Release Manager) and QA engineers qualify all anomalies and regressions using three standard severity tiers:
-* **Zéro Stress / Non-injonction** : L'interface évite les termes anxiogÚnes.
-* **Entraide Duo** : Le terme traditionnel *"Déléguer"* est remplacé par **« Entraide Duo »** et **« à proposer au partenaire »** (*Duo Teamwork / Propose to partner*), valorisant l'interdépendance positive et l'allÚgement partagé de la charge mentale.
-* **Sanctuaire Mental** : Le quadrant *"Ăliminer / Ne pas faire"* est remplacĂ© par **« DĂ©poser au Sanctuaire »** (*Park in Sanctuary*), permettant de consigner une idĂ©e prĂ©cieuse sans s'imposer d'Ă©chĂ©ance ni culpabilitĂ©.
+| Severity | Criteria | Impact | SLA / Resolution Path |
+|---|---|---|---|
+| **P0 · Blocker** | Application crash on launch, fatal exception, database migration corruption, security bypass, or broken primary user flow. | Total blockage or data loss. | Immediate triage, circuit breaker halted, hotfix release. |
+| **P1 · Major** | Functional flow regression without viable workaround, sync failure in Duo state, authentication loop, or AI suggestion failure with no local fallback. | Degraded core functionality. | Blocking for milestone release train; fixed in active sprint. |
+| **P2 · Minor** | Visual glitch, theme token misalignment, animation stutter, minor localization typo, or non-blocking edge-case delay. | Cosmetic or low friction. | Scheduled in standard backlog sprint. |
+
+### đ Bug Report Qualification Checklist
+Before submitting a defect, verify:
+1. **Deterministic Steps to Reproduce**: Minimal step-by-step sequence from a clean application state.
+2. **Environment Specification**: Device model, Android OS version / API level, and build variant (`debug` vs `release`).
+3. **Behavioral Contrast**: Clear statement of Expected Behavior vs Actual Observed Behavior.
+4. **Logcat / Stacktrace**: Clean log snippet isolated to application process, sanitized of any PII.
---
-## đ§ 2. Les 4 Quadrants de la Matrice de ClartĂ©
+## đ§ 2. 3-State Access Matrix QA Protocols
+
+Every feature and data flow must be verified across the 3 fundamental access states:
```
- URGENT (Court Terme) NON-URGENT (Long Terme)
- âââââââââââââââââââââââââââââââââââââŹââââââââââââââââââââââââââââââââââââ
- â ⥠à FAIRE AUJOURD'HUI â đż PLANIFIER & ALIGNER â
- IMPORTANT â âą Haute urgence & Fort impact â âą Fort impact, sĂ©rĂ©nitĂ© â
- (Haute Valeur) â âą ĂchĂ©ance imminente (ce soir) â âą Projets structurants, Self-careâ
- âââââââââââââââââââââââââââââââââââââŒââââââââââââââââââââââââââââââââââââ€
- â đ€ ENTRAIDE DUO â đ DĂPOSER AU SANCTUAIRE â
- NON-IMPORTANT â âą Urgent, faible complexitĂ© â âą Faible urgence & faible impact â
-(Faible Charge) â âą Ă proposer au partenaire â âą IdĂ©e pour plus tard, Wishlist â
- âââââââââââââââââââââââââââââââââââââŽââââââââââââââââââââââââââââââââââââ
+ ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
+ â 3-STATE ACCESS ARCHITECTURE â
+ ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
+ â â â
+ ⌠⌠âŒ
+ âââââââââââââââââ âââââââââââââââââ âââââââââââââââââ
+ â GUEST STATE â â SOLO STATE â â DUO STATE â
+ â 100% Local â â Personal Cloudâ â Shared Sync â
+ âââââââââââââââââ âââââââââââââââââ âââââââââââââââââ
```
-### đ Focus : "Planifier & Aligner" vs "DĂ©poser au Sanctuaire"
+### A. Guest State (Unauthenticated / Offline)
+* **Storage Invariant**: 100% local persistence via Room SQLite.
+* **Network Invariant**: Zero unsolicited cloud database or storage network requests.
+* **Soft-Gating**: Attempting to access cloud synchronization or partner pairing triggers a gentle non-blocking sign-in dialogue without crashing.
-Une distinction fondamentale existe entre ces deux catégories :
+### B. Solo State (Authenticated User)
+* **Namespace Isolation**: Reads and writes are scoped strictly to the authenticated user's private cloud namespace (e.g., `/users/{userId}`).
+* **Telemetry & Settings**: User preferences, theme modes, and Zero-PII analytics operate in personal mode.
-1. **đż Planifier & Aligner (`SCHEDULE` - Quadrant II)** :
- * C'est le **« Quadrant d'or »** de l'efficacité et de la sérénité.
- * Il regroupe les actions fondamentales qui méritent une attention délibérée mais sans panique : bilans de santé, intentions de vie, roadmap stratégique et **self-care actif**.
- * đ *Exemple :* **« Prendre du temps pour moi »** ou **« Prendre rendez-vous mĂ©decin »** sont classĂ©s ici car prendre soin de son Ă©quilibre est une intention **importante** qui doit ĂȘtre planifiĂ©e calmement.
-
-2. **đ DĂ©poser au Sanctuaire (`PARK` - Quadrant IV / Someday-Maybe)** :
- * C'est l'espace pour **libérer son esprit** des pensées sans engagement immédiat.
- * Il accueille les envies d'exploration, curiosités, wishlists ou projets lointains qu'on veut stocker en lieu sûr sans encombrer son champ attentionnel du moment.
- * đ *Exemple :* **« IdĂ©e pour plus tard : tester le yoga aĂ©rien un jour »** ou **« Un jour apprendre Ă jouer du piano »**.
+### C. Duo State (Shared Collaboration)
+* **Shared Workspace**: Real-time bidirectional synchronization scoped to the shared workspace namespace.
+* **Concurrency & Conflicts**: Verified using 2 simultaneous test devices/emulators to validate conflict resolution.
+* **Pairing Lifecycle**: Complete end-to-end verification of pairing generation, code submission, active sync, and clean disconnection.
---
-## đ·ïž 3. Les 3 Domaines de Vie (Areas of Life)
+## ⥠3. Two-Tier Hybrid AI Engine Architecture
-1. **đ§ Pour Soi (`SELF`)** : SantĂ©, mĂ©decine prĂ©ventive, forme physique, sommeil, mĂ©ditation, bien-ĂȘtre, loisirs personnels et dĂ©connexion.
-2. **đĄ Maison (`HOME`)** : Logement, entretien intĂ©rieur/extĂ©rieur, jardinage, bricolage, courses, repas, animaux de compagnie, enfants et logistique familiale.
-3. **đŒ Travail (`WORK`)** : ActivitĂ© professionnelle, gestion de projets, rĂ©unions, fiscalitĂ©/comptabilitĂ©, clients, devis, contrats et stratĂ©gie.
+Applications leveraging the kernel's cognitive assistance implement a Two-Tier hybrid model ensuring high availability, zero latency, and graceful offline degradation:
----
-
-## ⥠4. Architecture Hybride Two-Tier
+```mermaid
+flowchart TD
+ Input[User Text Input] --> Tier1[Tier 1: Local Heuristic Engine]
+ Tier1 -->|< 5ms Latency| FastUI[Instant Suggestion Rendered]
+ Input -->|Debounce 400ms| Tier2[Tier 2: Cloud LLM / Gemini API]
+ Tier2 -->|App Check OK| RefinedUI[Enriched Rationale & Confidence]
+ Tier2 -->|Network Error / 403| Graceful[Silent Fallback: Keep Tier 1 Suggestion]
+```
-1. **Tier 1 â Heuristique Locale (`< 5ms`)** :
- * Analyse déterministe synchrone instantanée avec 0 ms de latence réseau.
- * Tokenisation Unicode stricte (`\p{L}`) pour gérer nativement les accents français (*impÎts*, *santé*, *médecin*) sans faux positifs sur les sous-chaßnes.
- * SuggÚre immédiatement le Quadrant et le Domaine de Vie.
+### Tier 1 â Local Deterministic Classifier (`< 5ms`)
+* **Instant Feedback**: Executes synchronously on the main/background thread with 0 ms network overhead.
+* **Deterministic Tokenization**: Strict Unicode boundary matching (`\p{L}`) handling accents and multilingual tokens without substring false positives.
+* **Guaranteed Fallback**: Always provides an initial category/priority recommendation regardless of connectivity.
-2. **Tier 2 â Gemini 3.5 Flash-Lite via Firebase AI Logic (Asynchrone)** :
- * Déclenché aprÚs une pause de frappe (debounce de 400ms) ou à la perte de focus.
- * Utilise le modÚle `gemini-3.5-flash-lite` via `com.google.firebase:firebase-ai` avec App Check (Play Integrity en production, `DebugAppCheckProvider` sur émulateur).
- * Ăvalue la complexitĂ© cognitive, affine le domaine de vie (`HOME`, `WORK`, `SELF`), enrichit l'explication bienveillante (*rationale*) et ajuste la confiance.
- * **RĂ©silience App Check Ămulateur** : Si le jeton de debug n'est pas whitelistĂ© en environnement local, l'erreur 403 est interceptĂ©e sans polluer Crashlytics, et le Tier 1 heuristique garantit une classification instantanĂ©e et ininterrompue.
+### Tier 2 â Cloud LLM Inference (Gemini Flash via Firebase AI Logic)
+* **Asynchronous Deep Reasoning**: Triggered with debounce (e.g., 400ms after user pauses typing or loses focus).
+* **Structured Output Parsing**: Enforces strict schema validation (JSON / Type-safe response) to prevent hallucinated keys or unparseable payloads.
+* **App Check Security**: Enforces Play Integrity in production and debug providers in local test environments.
+* **Resilience Guarantee**: If network fails, API limits are reached, or App Check returns HTTP 403 on emulators, errors are intercepted cleanly. The Tier 1 local suggestion remains active, and Crashlytics is not spammed.
---
-## đ 5. Matrice de Test ComplĂšte (Les 12 Combinaisons)
-
-Ce tableau fournit les phrases de test canoniques pour valider les 12 combinaisons possibles dans l'interface de saisie (`AddMentalLoadScreen.kt` et `EditMentalLoadSheet.kt`).
+## đ 4. Archetype AI Suggestion & Multi-Category Test Protocol
-### đ§ Domaines : Pour Soi (`SELF`)
+Rather than testing arbitrary domain strings, QA suites should validate the **Architectural Qualification Grid** covering the full permutation of categories and priority tiers:
-| # | Quadrant Attendu | Phrase de Test à Copier-Coller | Déclencheurs / Justification |
-|:---:|---|---|---|
-| **1** | ⥠**à Faire Aujourd'hui** | `Prendre mes antibiotiques et appeler médecin en urgence aujourd'hui` | `urgence`, `aujourd'hui` + `santé`, `médecin` |
-| **2** | đż **Planifier & Aligner** | `Prendre rendez-vous bilan de santĂ© mĂ©decin` *(ou `Prendre du temps pour moi`)* | `santĂ©`, `mĂ©decin`, `rdv`, `temps pour moi` (sans marqueur d'urgence) |
-| **3** | đ€ **Entraide Duo** | `Demander Ă Sam de passer Ă la pharmacie chercher mon ordonnance` | `demander Ă Sam` + `pharmacie`, `ordonnance` |
-| **4** | đ **DĂ©poser au Sanctuaire** | `IdĂ©e pour plus tard : tester le yoga aĂ©rien un jour` | `idĂ©e pour plus tard`, `un jour` + `yoga` |
+| Dimension | Qualification Criteria | Expected Engine Behavior |
+|---|---|---|
+| **Urgent & High Impact** | Immediate deadline, high-risk consequence, crisis action. | Tier 1 & Tier 2 converge on highest immediate priority tier. |
+| **Important & Strategic** | Long-term planning, foundational projects, preventive actions. | Classified as scheduled/deliberate action without panic markers. |
+| **Collaborative / Shared** | Explicit mention of collaborator, delegation, or joint responsibility. | Routed to shared/collaborative workspace or partner suggestion. |
+| **Low-Urgency / Backlog** | Exploratory thoughts, wishlists, future ideas (*"someday-maybe"*). | Parked in low-priority sanctuary/backlog without deadlines. |
----
+### Golden Test Dataset Pattern
+Deterministic unit tests validate the classification engine using parameterized golden datasets:
-### đĄ Domaines : Maison (`HOME`)
+```kotlin
+@Test
+fun verifyCategoryAndPriorityPermutations() {
+ // Assert all permutations of category and priority tiers map correctly
+ // across both Tier 1 heuristic triggers and Tier 2 structured responses.
+}
+```
-| # | Quadrant Attendu | Phrase de Test à Copier-Coller | Déclencheurs / Justification |
-|:---:|---|---|---|
-| **5** | ⥠**à Faire Aujourd'hui** | `Sortir les poubelles et réparer la fuite d'eau ce soir urgent` | `urgent`, `ce soir` + `poubelles`, `fuite`, `eau` |
-| **6** | đż **Planifier & Aligner** | `Tailler la haie et tondre la pelouse ce week-end` | `tailler`, `haie`, `tondre`, `pelouse` |
-| **7** | đ€ **Entraide Duo** | `Demander Ă Sam de faire les courses et acheter du lait` | `demander Ă Sam` + `courses`, `lait` |
-| **8** | đ **DĂ©poser au Sanctuaire** | `IdĂ©e pour plus tard : crĂ©er un potager dans le jardin` | `idĂ©e pour plus tard` + `jardin`, `potager` |
+### Roborazzi Visual Regression UI States
+Visual snapshot tests must capture the 4 canonical states of AI-assisted entry surfaces:
+1. **Empty / Default State**: Unfocused input with placeholder.
+2. **Typing / Tier 1 Fast State**: Instant suggestion chip displayed under input.
+3. **Tier 2 Enriched State**: Refined suggestion with rationale and confidence indicator.
+4. **Offline / Error Fallback**: Clean UI maintaining Tier 1 suggestion with zero error dialogs.
---
-### đŒ Domaines : Travail (`WORK`)
+## đ§Ș 5. Automated Testing Execution & CI Verification
-| # | Quadrant Attendu | Phrase de Test à Copier-Coller | Déclencheurs / Justification |
-|:---:|---|---|---|
-| **9** | ⥠**à Faire Aujourd'hui** | `Déclaration impÎts urgente aujourd'hui avant 18h` | `urgente`, `aujourd'hui`, `avant 18h` + `impÎts`, `déclaration` |
-| **10** | đż **Planifier & Aligner** | `PrĂ©parer la roadmap stratĂ©gique du projet Q4` | `roadmap`, `stratĂ©gique`, `projet`, `q4` |
-| **11** | đ€ **Entraide Duo** | `Demander Ă Sam de relire le devis et le contrat` | `demander Ă Sam` + `devis`, `contrat` |
-| **12** | đ **DĂ©poser au Sanctuaire** | `IdĂ©e pour plus tard : explorer un projet open source un jour` | `idĂ©e pour plus tard`, `explorer`, `un jour` + `projet` |
-
----
+Run the complete verification pipeline locally:
-## đ§Ș 6. VĂ©rification AutomatisĂ©e
+```bash
+# 1. Run unit test suite
+./gradlew testDebugUnitTest --tests "*ClassifierTest*"
-La suite de tests unitaires valide l'intégralité de ces rÚgles :
+# 2. Run full quality airbag (Lint, compilation, tests)
+./scripts/quality-check.sh
-```bash
-./gradlew testDebugUnitTest --tests com.secondbrain.app.data.classifier.HeuristicTaskClassifierTest
+# 3. Validate documentation contracts and byte budgets
+./scripts/validate-docs.sh
```
-
-Test validé : `verify all 12 combinations of AreaOfLife and PriorityQuadrant` dans `HeuristicTaskClassifierTest.kt`.
diff --git a/docs/scripts-reference.md b/docs/scripts-reference.md
index 55a943d..9465973 100644
--- a/docs/scripts-reference.md
+++ b/docs/scripts-reference.md
@@ -6,41 +6,40 @@
---
-## 1. Vision & Architecture : Scripts Atomiques & Composition par Compétences Sémantiques
+## 1. Vision & Architecture: Atomic Scripts & Semantic Skills Composition
-Le projet **Agentic Android Kernel** adopte une architecture d'automatisation stricte basée sur le principe de **responsabilité unique (SRP)** :
+The **Agentic Android Kernel** project enforces a strict automation architecture rooted in the **Single Responsibility Principle (SRP)**:
-1. **Scripts Atomiques (Single Responsibility)** :
- Chaque script dans `scripts/` remplit une **unique fonction déterministe** (ex: valider les contrats documentaires, exécuter les tests de compilation Android, vérifier les rÚgles Firestore, ou téléverser les captures sur Stitch).
-2. **Composition par Compétences Sémantiques & Pipelines (Orchestration)** :
- Les enchaßnements complexes de tùches ne sont pas codés en dur dans de gros scripts monolithiques, mais orchestrés via :
- - Les **Compétences Sémantiques de l'Agent** ([`.agent/skills/`](../.agent/skills/)) pilotées par intentions et commandes (`plan-issue`, `open-pr`, `quality-airbag`, `distribute-local`, `sync-stitch`, `triage-feedback`).
- - Les **Pipelines CI/CD GitHub Actions** ([`.github/workflows/`](../.github/workflows/)) (`delivery-pipeline.yml`).
+1. **Atomic Scripts (Single Responsibility)**:
+ Every script under `scripts/` fulfills a **single deterministic function** (e.g., validating documentation contracts, running Android build sanity checks, testing runtime security guardrails, or uploading screenshots to Stitch).
+2. **Composition via Semantic Skills & Pipelines (Orchestration)**:
+ Complex multi-step workflows are not hardcoded into brittle monolithic scripts, but orchestrated via:
+ - **Agent Semantic Skills** ([`.agent/skills/`](../.agent/skills/)) driven by user intents and slash commands (`plan-issue`, `open-pr`, `quality-airbag`, `distribute-local`, `sync-stitch`, `triage-feedback`).
+ - **GitHub Actions CI/CD Pipelines** ([`.github/workflows/`](../.github/workflows/)) (`delivery-pipeline.yml`).
```mermaid
graph TD
- subgraph SkillsPipelines ["Orchestrateurs (Skills / Pipelines)"]
+ subgraph SkillsPipelines ["Orchestrators (Skills / Pipelines)"]
WF_QC["quality-airbag (/quality-check)"]
WF_DIST["/distribute-local"]
WF_STITCH["/sync-stitch"]
CI_DELIVERY["Delivery Pipeline & Quality Gate (delivery-pipeline.yml)"]
end
- subgraph AtomicScripts ["Scripts Atomiques (scripts/)"]
+ subgraph AtomicScripts ["Atomic Scripts (scripts/)"]
S_VAL["validate-docs.sh"]
S_QC["quality-check.sh"]
- S_RULES["test-firestore-rules.mjs"]
- S_DEPLOY["deploy-firestore-rules.mjs"]
+ S_GUARD["test-runtime-guardrails.mjs"]
+ S_HOOKS["install-hooks.sh"]
S_DIST["deploy-app-distribution.sh"]
S_GEN["generate-screenshots.sh"]
S_STITCH["upload-screenshots.py"]
- S_CLEAN["cleanup-e2e-firestore.mjs"]
S_IDE["inspect-ide.sh"]
end
WF_QC --> S_VAL
WF_QC --> S_QC
- WF_QC --> S_RULES
+ WF_QC --> S_GUARD
WF_STITCH --> S_VAL
WF_STITCH --> S_GEN
@@ -51,130 +50,128 @@ graph TD
CI_DELIVERY --> S_VAL
CI_DELIVERY --> S_QC
- CI_DELIVERY --> S_RULES
+ CI_DELIVERY --> S_GUARD
```
---
-## 2. Répertoire Complet des Scripts
+## 2. Complete Scripts Directory
-| Fichier Script | Langage | Nature | Responsabilité Unique | Déclencheurs / Skills |
+| Script File | Language | Nature | Single Responsibility | Triggers / Skills |
|---|---|---|---|---|
-| [`scripts/validate-docs.sh`](../scripts/validate-docs.sh) | Bash | Atomique | Valide l'intégrité et la conformité des contrats documentaires (`DESIGN.md`, `design-system.md`, `agent.md`, playbooks, skills, rÚgles). | `quality-airbag`, `sync-stitch`, `delivery-pipeline.yml` |
-| [`scripts/quality-check.sh`](../scripts/quality-check.sh) | Bash | Atomique | Exécute la suite Gradle complÚte de compilation Kotlin/Java, Lint Android Debug/Release, et tests unitaires/Robolectric. | `quality-airbag`, `open-pr`, `delivery-pipeline.yml` |
-| [`scripts/test-firestore-rules.mjs`](../scripts/test-firestore-rules.mjs) | Node.js (ESM) | Atomique | Teste localement `firestore.rules` contre 16 assertions de sécurité (moindre privilÚge, isolation couple, absence d'escalade). | `quality-airbag`, CI, Debug Screen |
-| [`scripts/deploy-firestore-rules.mjs`](../scripts/deploy-firestore-rules.mjs) | Node.js (ESM) | Atomique | Déploie et publie `firestore.rules` directement sur Google Cloud / Firebase via l'API REST avec JWT compte de service. | Déploiement manuel sécurisé |
-| [`scripts/deploy-app-distribution.sh`](../scripts/deploy-app-distribution.sh) | Bash | Atomique | Compile l'APK et l'envoie sur Firebase App Distribution avec calcul automatique de version et notes formatées. | `distribute-local`, Déploiement testeurs ad-hoc |
-| [`scripts/generate-screenshots.sh`](../scripts/generate-screenshots.sh) | Bash | Atomique | Exécute les tests d'UI Robolectric/Roborazzi pour générer ou mettre à jour les captures d'écran en local. | `sync-stitch`, Génération des captures Roborazzi |
-| [`scripts/upload-screenshots.py`](../scripts/upload-screenshots.py) | Python 3 | Atomique | Valide et mappe les 10 captures Roborazzi sur les `screen_id` Stitch existants pour mise à jour in-place (zéro hallucination). | `sync-stitch`, `upload-screenshots.py` |
-| [`scripts/cleanup-e2e-firestore.mjs`](../scripts/cleanup-e2e-firestore.mjs) | Node.js (ESM) | Atomique | Purge les documents de sondes de test créés dans la collection Firestore `/users`. | Maintenance et tests de sonde |
-| [`scripts/inspect-ide.sh`](../scripts/inspect-ide.sh) | Bash | Atomique | Exécute le moteur d'inspection complet d'Android Studio / IntelliJ en mode headless avec profil par défaut. | Audit qualité avancé IDE |
+| [`scripts/validate-docs.sh`](../scripts/validate-docs.sh) | Bash | Atomic | Validates structural integrity and byte budget compliance across all architecture contracts (`DESIGN.md`, `design-system.md`, `AGENTS.md`, playbooks, skills, rules). | `quality-airbag`, `sync-stitch`, `delivery-pipeline.yml` |
+| [`scripts/quality-check.sh`](../scripts/quality-check.sh) | Bash | Atomic | Executes the full Gradle suite: Kotlin/Java compilation, Android Lint Debug/Release, unit tests, and Robolectric/Roborazzi UI tests. | `quality-airbag`, `open-pr`, `delivery-pipeline.yml` |
+| [`scripts/test-runtime-guardrails.mjs`](../scripts/test-runtime-guardrails.mjs) | Node.js (ESM) | Atomic | Runs 18 security assertions verifying PoLP tool revocation, `plan-guard.mjs`, and `branch-guard.mjs` path hardening. | `quality-airbag`, CI |
+| [`scripts/install-hooks.sh`](../scripts/install-hooks.sh) | Bash | Atomic | Binds local Git hooks to `.agent/hooks/` and guarantees executable permissions on all hook scripts. | Developer onboarding, setup |
+| [`scripts/deploy-app-distribution.sh`](../scripts/deploy-app-distribution.sh) | Bash | Atomic | Builds the APK and deploys to Firebase App Distribution with monotonic version multiplier (x100) and formatted release notes. | `distribute-local`, Ad-hoc tester release |
+| [`scripts/generate-screenshots.sh`](../scripts/generate-screenshots.sh) | Bash | Atomic | Executes Robolectric/Roborazzi UI tests to record and generate local screenshots in `build/outputs/roborazzi`. | `sync-stitch`, Design System capture update |
+| [`scripts/upload-screenshots.py`](../scripts/upload-screenshots.py) | Python 3 | Atomic | Validates and maps Roborazzi screenshot baselines to Google Stitch `screen_id`s for in-place synchronization. | `sync-stitch`, `upload-screenshots.py` |
+| [`scripts/inspect-ide.sh`](../scripts/inspect-ide.sh) | Bash | Atomic | Executes Android Studio / IntelliJ IDEA code inspection engine in headless mode with default project profiles. | Advanced IDE quality audit |
---
-## 3. Fiches Détaillées par Script
+## 3. Detailed Script Reference Sheets
### 3.1 `scripts/validate-docs.sh`
-* **RÎle** : Gardien de l'intégrité documentaire et de la conformité des contrats d'architecture.
-* **Vérifications effectuées** :
- - Présence de `DESIGN.md`, `design-system.md`, `agent.md`, `README.md`, `README.fr.md`.
- - Présence des rÚgles maßtresses : `agent-lifecycle.md`, `backlog-planner.md`, `git-workflow.md`.
- - Présence des playbooks : `room-migrations.md`, `firestore-security.md`, `roborazzi-export.md`, `compose-theming.md`.
- - Présence des compétences sémantiques : `plan-issue.md`, `open-pr.md`, `quality-airbag.md`, `distribute-local.md`, `triage-feedback.md`, `sync-stitch.md`.
- - Validité du frontmatter YAML dans `DESIGN.md` (`Serene Intellectual`).
-* **Utilisation** :
+* **Role**: Quality gatekeeper for documentation integrity and multi-agent architectural contract compliance.
+* **Checks performed**:
+ - Presence of core contracts: `DESIGN.md`, `design-system.md`, `AGENTS.md`, `agent.md`, `README.md`, `ARCHITECTURE.md`.
+ - Presence and size budgets of master rules: `agent-lifecycle.md`, `backlog-planner.md`, `git-workflow.md`, `firebase-standards.md`.
+ - Presence and size budgets of playbooks: `room-migrations.md`, `roborazzi-export.md`, `compose-theming.md`, `android-standards.md`.
+ - Presence of semantic skills: `plan-issue`, `open-pr`, `quality-airbag`, `sync-stitch`.
+ - Presence and executable flags on hooks: `pre-commit-airbag.sh`, `post-merge-dual-sync.sh`, `branch-guard.mjs`, `plan-guard.mjs`, `pre-invocation-anchor.sh`.
+ - YAML frontmatter validity in `DESIGN.md` (`Serene Intellectual`).
+* **Usage**:
```bash
./scripts/validate-docs.sh
```
-* **Codes de sortie** : `0` (SuccĂšs, 100% validĂ©), `1` (Ăchec, au moins un fichier ou contrat manquant).
+* **Exit Codes**: `0` (Success, 100% validated), `1` (Failure, at least one contract or file missing/over-budget).
---
### 3.2 `scripts/quality-check.sh`
-* **RÎle** : Airbag qualité de compilation et d'analyse statique Android.
-* **Actions exécutées** :
- - Détection et initialisation automatique de `JAVA_HOME` (Android Studio JBR / JDK 21).
- - Exécution de `./gradlew codeSanityCheck --stacktrace` :
- 1. Compilateur Kotlin (checks progressifs & annotations opt-in).
- 2. Compilateur Java (`-Xlint:all`).
- 3. Android Lint Debug & Release (Compose, sécurité, i18n, performance).
- 4. Tests unitaires et tests UI Robolectric (135+ tests).
- 5. Compatibilité Jetifier & AndroidX.
-* **Utilisation** :
+* **Role**: Primary compilation and static analysis airbag for Android.
+* **Actions executed**:
+ - Automatic detection and portable configuration of `JAVA_HOME` (Android Studio JBR / JDK 21).
+ - Execution of `./gradlew codeSanityCheck --stacktrace`:
+ 1. Kotlin compiler checks (progressive mode & opt-in annotations).
+ 2. Java compiler warnings (`-Xlint:all`).
+ 3. Android Lint Debug & Release (Compose, security, i18n, performance).
+ 4. Unit tests and Robolectric/Roborazzi UI tests.
+* **Usage**:
```bash
./scripts/quality-check.sh
```
-* **Rapports générés** :
+* **Generated Reports**:
- `app/build/reports/lint-results-debug.html`
- `app/build/reports/lint-results-release.html`
- `app/build/reports/tests/testDebugUnitTest/index.html`
---
-### 3.3 `scripts/test-firestore-rules.mjs`
-* **RÎle** : Suite de tests de sécurité et de non-régression hors-ligne pour `firestore.rules`.
-* **Vérifications assurées (16 assertions)** :
- - **Suite 1 (Structure)** : `rules_version = '2'`, helpers `isAuthenticated()`, `isCoupleMember()`, `isMemberOfCouple()`.
- - **Suite 2 (AccÚs Moindre PrivilÚge)** : Cloisonnement `/users/{userId}`, `/invites/`, `/pairings/`, `/couples/{coupleId}`, `/loads/{loadId}`, rejet par défaut `allow read, write: if false;`.
- - **Suite 3 (Anti-Régression)** : 0 rÚgle ouverte `if true`, 0 écriture non vérifiée `if request.auth != null`, isolation stricte des sanctuaires de test `SANCTUARY-TEST*`.
-* **Utilisation** :
+### 3.3 `scripts/test-runtime-guardrails.mjs`
+* **Role**: Offline security test suite for runtime guardrails and PoLP persona configurations.
+* **Verifications (18 assertions)**:
+ - **PoLP Tool Access**: Verifies `run_command` is denied/revoked for P1, P2, P3, and P4 personas.
+ - **Plan Guard (`plan-guard.mjs`)**: Rejection of `--no-verify`, `-c core.hooksPath` bypasses, commits on `main`, and pushes to `main`.
+ - **Branch Guard (`branch-guard.mjs`)**: Canonical path hardening preventing write operations to repository files while on `main`.
+* **Usage**:
```bash
- node scripts/test-firestore-rules.mjs
+ node scripts/test-runtime-guardrails.mjs
```
---
-### 3.4 `scripts/deploy-firestore-rules.mjs`
-* **RÎle** : Déploiement programmatique sécurisé des rÚgles Firestore sans dépendre de la CLI Firebase.
-* **Fonctionnement** :
- 1. Lit `service-account.json` et génÚre un JWT signé RSA-SHA256 (scope `cloud-platform datastore`).
- 2. Crée un nouveau ruleset via l'API REST `firebaserules.googleapis.com/v1/projects/{projectId}/rulesets`.
- 3. Met Ă jour la release `projects/{projectId}/releases/cloud.firestore`.
-* **Prérequis** : `service-account.json` valide avec rÎle Firebase Rules Admin.
-* **Utilisation** :
+### 3.4 `scripts/install-hooks.sh`
+* **Role**: Binds local Git hooks to `.agent/hooks/` and guarantees executable permissions.
+* **Actions executed**:
+ - Sets executable permissions on `.agent/hooks/*.sh` and `*.mjs`.
+ - Symlinks standard Git `pre-commit` to `pre-commit-airbag.sh`.
+ - Configures Git `core.hooksPath` to `.agent/hooks`.
+* **Usage**:
```bash
- node scripts/deploy-firestore-rules.mjs
+ ./scripts/install-hooks.sh
```
---
### 3.5 `scripts/deploy-app-distribution.sh`
-* **RĂŽle** : Construction et distribution directe sur Firebase App Distribution depuis le terminal local.
-* **Fonctionnement** :
- 1. Détecte `service-account.json`.
- 2. Calcule la version Git (`versionCode` = nombre total de commits, `versionName` = tag SemVer + commits ahead).
- 3. Formate les notes de version : `v (build ) : `.
- 4. Compile (`assembleDebug` ou `assembleRelease`) et téléverse (`appDistributionUploadDebug` ou `appDistributionUploadRelease`).
- 5. Nettoie les fichiers temporaires `release-notes.txt`.
-* **Arguments & Options** :
- - `[notes]` : Message explicatif pour les testeurs (défaut : message du dernier commit Git).
- - `[variant]` : `release` (défaut) ou `debug`.
- - `--groups, -g` : Groupes de testeurs Firebase ciblés (défaut : `admin, testers`).
-* **Exemples** :
+* **Role**: Direct build and distribution to Firebase App Distribution from the local developer terminal.
+* **Workflow**:
+ 1. Detects `service-account.json`.
+ 2. Calculates Git version metadata (`versionCode` using monotonic multiplier x100, `versionName` with SemVer tag and commits ahead).
+ 3. Formats release notes: `v (build ) : `.
+ 4. Compiles (`assembleDebug` or `assembleRelease`) and uploads (`appDistributionUploadDebug` or `appDistributionUploadRelease`).
+ 5. Cleans up temporary `release-notes.txt` artifacts.
+* **Arguments & Options**:
+ - `[notes]`: User-facing message for testers (default: latest Git commit message).
+ - `[variant]`: `release` (default) or `debug`.
+ - `--groups, -g`: Targeted Firebase tester groups (default: `admin, testers`).
+* **Examples**:
```bash
- # 1. Distribution standard
+ # 1. Standard release distribution
./scripts/deploy-app-distribution.sh
- # 2. Avec notes personnalisées
- ./scripts/deploy-app-distribution.sh "Correction synchronisation duo"
+ # 2. With custom release notes
+ ./scripts/deploy-app-distribution.sh "Fix duo sync state"
- # 3. Release APK pour testeurs internes
+ # 3. Release APK for internal admins
./scripts/deploy-app-distribution.sh "RC v0.2.0" release --groups "admin"
```
---
### 3.6 `scripts/upload-screenshots.py`
-* **RÎle** : Mappage et téléversement déterministe des captures Roborazzi sur les écrans Stitch.
-* **Garanties** :
- - Mappage 1:1 strict entre 10 captures locales (`screenshots/stitch_export/*.png`) et 10 `screen_id` Google Stitch.
- - Mise à jour strictly in-place (interdiction formelle de créer des écrans orphelins).
- - Validation préalable de l'existence et du poids de chaque fichier PNG.
-* **Options CLI** :
- - `--project-id` : ID du projet Stitch (défaut : ``).
- - `--check-only` : Vérifie la présence et le mappage des 10 PNGs sans téléversement.
- - `--dry-run` : Simule l'exécution et affiche les payloads JSON/Base64.
-* **Exemples** :
+* **Role**: Deterministic mapping and upload of Roborazzi UI screenshots to Google Stitch screens.
+* **Guarantees**:
+ - Strict 1:1 mapping between local snapshots (`screenshots/stitch_export/*.png`) and Google Stitch `screen_id`s.
+ - In-place screen updates preventing duplicate or orphaned screens in Stitch.
+ - Pre-validation of PNG file existence and non-zero byte size.
+* **CLI Options**:
+ - `--project-id`: Google Stitch Project ID.
+ - `--check-only`: Verifies presence and mapping of PNG files without uploading.
+ - `--dry-run`: Simulates execution and outputs JSON/Base64 payloads.
+* **Examples**:
```bash
python3 scripts/upload-screenshots.py --check-only
python3 scripts/upload-screenshots.py --dry-run
@@ -183,46 +180,34 @@ graph TD
---
### 3.7 `scripts/generate-screenshots.sh`
-* **RÎle** : Exécute les tests d'UI Robolectric et Roborazzi pour enregistrer et générer localement les captures d'écran de l'application dans `build/outputs/roborazzi`.
-* **Fonctionnement** :
- - Lance `./gradlew recordRoborazziDebug --stacktrace`.
- - Produit les captures d'écran requises pour la validation et la synchronisation du Design System.
-* **Utilisation** :
+* **Role**: Executes Robolectric and Roborazzi UI tests to record and update application screenshots locally in `build/outputs/roborazzi`.
+* **Workflow**:
+ - Executes `./gradlew recordRoborazziDebug --stacktrace`.
+ - Produces verified screenshot assets required for Design System synchronization.
+* **Usage**:
```bash
./scripts/generate-screenshots.sh
```
---
-### 3.8 `scripts/cleanup-e2e-firestore.mjs`
-* **RÎle** : Nettoyage et purge des documents Firestore de sonde créés lors des tests d'authentification ou d'intégrité.
-* **Fonctionnement** :
- - S'authentifie via `service-account.json`.
- - Liste les documents sous `/users` créés par les sondes de test.
- - Supprime chaque document unitairement via l'API REST Firestore.
-* **Utilisation** :
- ```bash
- node scripts/cleanup-e2e-firestore.mjs
- ```
-
----
-
-### 3.9 `scripts/inspect-ide.sh`
-* **RĂŽle** : Inspection headless IntelliJ / Android Studio.
-* **Utilisation** :
+### 3.8 `scripts/inspect-ide.sh`
+* **Role**: Headless IntelliJ IDEA / Android Studio static inspection runner.
+* **Usage**:
```bash
./scripts/inspect-ide.sh
```
---
-## 4. Matrice de Composition (Skills & Pipelines â Scripts & MCP)
+## 4. Composition Matrix (Skills & Pipelines â Scripts & MCP)
-| Skill / Pipeline | Outils Invoqués (dans l'ordre d'exécution) |
+| Skill / Pipeline | Invoked Tools (in execution order) |
|---|---|
-| **`quality-airbag`** (`/quality-check`) | 1. `scripts/validate-docs.sh`
2. `scripts/quality-check.sh`
3. `scripts/test-firestore-rules.mjs` |
-| **`open-pr`** (`/open-pr`) | 1. `scripts/quality-check.sh` (Airbag qualité complet) |
-| **`distribute-local`** (`/distribute-local`) | 1. `scripts/quality-check.sh` (Recommandé)
2. `scripts/deploy-app-distribution.sh` |
+| **`quality-airbag`** (`/quality-check`) | 1. `scripts/validate-docs.sh`
2. `scripts/quality-check.sh`
3. `scripts/test-runtime-guardrails.mjs` |
+| **`open-pr`** (`/open-pr`) | 1. `scripts/quality-check.sh` (Full quality airbag)
2. Walkthrough generation & PR creation |
+| **`distribute-local`** (`/distribute-local`) | 1. `scripts/quality-check.sh` (Recommended)
2. `scripts/deploy-app-distribution.sh` |
| **`sync-stitch`** (`/sync-stitch`) | 1. `scripts/validate-docs.sh`
2. `scripts/generate-screenshots.sh`
3. `scripts/upload-screenshots.py` |
-| **`triage-feedback`** (`/triage-feedback`) | 100% MCP natif (`GitHubMCP` : `search_issues`, `add_issue_comment`, `create_issue`) |
-| **Delivery Pipeline & Quality Gate (`delivery-pipeline.yml`)** | 1. `scripts/validate-docs.sh`
2. `scripts/quality-check.sh` (`./gradlew codeSanityCheck`)
3. Compilation & Firebase App Distribution via Gradle |
+| **`triage-feedback`** (`/triage-feedback`) | 100% native MCP (`GitHubMCP`: `search_issues`, `add_issue_comment`, `create_issue`) |
+| **Delivery Pipeline & Quality Gate (`delivery-pipeline.yml`)** | 1. `scripts/validate-docs.sh`
2. `scripts/quality-check.sh` (`./gradlew codeSanityCheck`)
3. APK build & Firebase App Distribution deployment via Gradle |
+