Comprehensive pwE Documentation (v1.0.56+232)
pwE (Pray With Me) is a flagship global production application built on Flutter 3.50 / Dart 3.14, designed to guide the user through the ancient practice of Lectio Divina (Prayerful Reading) in strict harmony with Catholic Doctrine, the Magisterium of the Church, and official copyright licensing from Edições CNBB. Download free on the Google Play Store (177 countries) ↗, visit the official showcase at pwe.jhhsolutions.dev ↗, launch the Web App at pwe.jhhsolutions.dev/app ↗, and explore the ADRs and real code slices in github.com/evslopes/pwe-architecture-showcase ↗.
Project Principles and Pillars
Developed under strict architectural and design standards (as defined in the official theme in lib/core/theme/app_theme.dart), pwE is sustained by three fundamental pillars:
† Doctrinal Fidelity
All meditations, prayers, and reflections proposed by the AI rigorously follow the Catholic Magisterium. No heretical, secular, or technological terminology is exposed to the user in the meditation experience.
🔒 Absolute Privacy
Prayer is intimacy. With the Edge LLM engine, AI processing can occur entirely locally on the user's device, ensuring absolute privacy of the soul's data.
📱 Immersive Design
Use of refined mechanics (such as progressive scroll reveal and haptic hold gestures) to eliminate distractions and guide the user through the liturgical stages.
Clean Architecture & DDD
To ensure that the business logic is independent of database technologies, frameworks, or third-party APIs, pwE adopts a layered structure based on Clean Architecture and Domain-Driven Design (DDD).
Architectural Layers
The separation of concerns ensures ease of maintenance and high coverage of unit tests:
-
Domain Layer (Domain): Contains pure business rules (
Entities,UseCases, and defined contracts). See the Lectio Divina entity inlectio_session.dart:// lib/features/lectio_divina/domain/entities/lectio_session.dart class LectioSession { final String id; final DateTime date; final String passage; final String emotion; final String meditation; final String prayer; final String contemplationResolution; final int streakDays; const LectioSession({ required this.id, required this.date, required this.passage, required this.emotion, required this.meditation, required this.prayer, required this.contemplationResolution, required this.streakDays, }); } -
Data Layer (Data): Contains the infrastructure (
Models,DataSources, and concrete repository implementations as inllm_remote_datasource.dart):// lib/features/lectio_divina/data/datasources/llm_remote_datasource.dart abstract class LlmRemoteDataSource { Future<MeditationModel> generateMeditation(MeditationRequestModel request); } class LlmRemoteDataSourceImpl implements LlmRemoteDataSource { final ApiClient apiClient; LlmRemoteDataSourceImpl({required this.apiClient}); @override Future<MeditationModel> generateMeditation(MeditationRequestModel request) async { final response = await apiClient.post( '/v1/spiritual-advisor/meditate', data: request.toJson(), ); return MeditationModel.fromJson(response.data); } } -
Presentation Layer (Presentation): Contains the user interface (Widgets and Pages) and complex state management based on **Bloc** (decomposed into 10 specialized Sub-BLoCs in
lectio_divina/presentation/bloc/sub_blocs/):// lib/features/lectio_divina/presentation/bloc/sub_blocs/lectio_session/lectio_session_bloc.dart class LectioSessionBloc extends Bloc<LectioSessionEvent, LectioSessionState> { final GetGuidedMeditation getGuidedMeditation; final SaveSession saveSession; LectioSessionBloc({ required this.getGuidedMeditation, required this.saveSession, }) : super(LectioInitial()) { on<StartSessionEvent>(_onStartSession); on<AdvanceToStepEvent>(_onAdvanceToStep); on<CompleteSessionEvent>(_onCompleteSession); } void _onStartSession(StartSessionEvent event, Emitter<LectioSessionState> emit) { emit(LectioInProgress(step: LectioStep.reading, passage: event.passage)); } }
All services, repositories, use cases, and blocs are registered in isolated feature containers and orchestrated in injection_container.dart through the **GetIt** package:
// lib/core/di/injection_container.dart
final sl = GetIt.instance;
Future<void> init() async {
// Features - Lectio Divina (Sub-BLoCs)
sl.registerFactory(() => LectioSessionBloc(getGuidedMeditation: sl(), saveSession: sl()));
// Use cases
sl.registerLazySingleton(() => GetGuidedMeditation(sl()));
sl.registerLazySingleton(() => SaveSession(sl()));
// Repositories
sl.registerLazySingleton<IARepository>(() => IARepositoryImpl(remoteDataSource: sl()));
// Data sources
sl.registerLazySingleton<LlmRemoteDataSource>(() => LlmRemoteDataSourceImpl(apiClient: sl()));
// External (Core)
sl.registerLazySingleton(() => ApiClient());
}
Immersive Lectio Divina Flow
Lectio Divina in pwE consolidates the four classic stages into a continuous view using the CustomScrollView mechanic, eliminating screen fatigue:
Lectio (Reading)
The user carefully reads the sacred text of the day (daily liturgy) or inputs/scans a desired passage.
Meditatio (Meditation)
The app suggests meditation points through AI, connecting the sacred text to faith analogies and experiences.
Oratio (Prayer)
The user responds to the Word in the form of supplication, adoration, or thanksgiving, with prompts based on the Psalms.
Contemplatio (Contemplation)
The user makes a practical life resolution and keeps the prayer in the silence of their Spiritual Notebook.
Focused UI Components
These UI elements create an atmosphere of introspection in immersive_reading_page.dart:
- ProgressiveTextReveal: Hides future segments using blur until the user scrolls or interacts with the text, helping them focus on the current reading.
- HoldToSaveButton: Requires pressing the button for 2 continuous seconds with haptic feedback to ensure intent to advance steps, preventing accidental clicks in the silence of prayer.
- ThinkingFeedback: Displays rotating motivational and spiritual messages while the AI processes the prompt (e.g., "Uniting your prayer to the heavenly choirs...").
Below is a practical example of implementing the HoldToSaveButton, with haptic logic and gradual time fill in Flutter:
// lib/features/lectio_divina/presentation/widgets/hold_to_save_button.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class HoldToSaveButton extends StatefulWidget {
final VoidCallback onTrigger;
final String label;
const HoldToSaveButton({Key? key, required this.onTrigger, required this.label}) : super(key: key);
@override
_HoldToSaveButtonState createState() => _HoldToSaveButtonState();
}
class _HoldToSaveButtonState extends State<HoldToSaveButton> with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
);
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
HapticFeedback.heavyImpact();
widget.onTrigger();
_controller.reset();
}
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onLongPressStart: (_) {
HapticFeedback.mediumImpact();
_controller.forward();
},
onLongPressEnd: (_) {
if (_controller.status != AnimationStatus.completed) {
_controller.reverse();
}
},
child: AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Container(
height: 56,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.amber.shade700, width: 1.5),
gradient: LinearGradient(
colors: [Colors.amber.shade800, Colors.amber.shade900],
stops: [0.0, _controller.value],
),
),
child: Center(
child: Text(
_controller.value > 0 ? 'Mantenha pressionado... ${(_controller.value * 100).toInt()}%' : widget.label,
style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
),
),
);
},
),
);
}
}
Maturity System (Fading Scaffolding)
In order not to overwhelm the user and to encourage autonomous prayer, pwE implements the innovative strategy of Fading Scaffolding. The AI adapts the level of verbosity and depth of its prompts according to the spiritual progress of the faithful.
The Three Stages of Maturity
Beginner
Detailed pedagogical guidance. The AI teaches the meaning of each stage and provides detailed illustrative analogies for beginners in the practice.
Practitioner
Focus on faith provocations. Eliminates academic introductions and proposes direct points of personal questioning and application in daily charity.
Contemplative
Minimalism and Silence. The AI provides a maximum of two inspiring lines based on the tradition of the Church Fathers, encouraging interior silence.
Evolution occurs naturally with the streak count. However, the user can manually set their maturity level in the settings if they want stronger guidance or prefer contemplative silence immediately.
Zero Invasion & Privacy: Edge LLM
One of the biggest differentiators of pwE is its ability to operate 100% autonomously and privately. Thanks to the Edge LLM engine, prayers written in the intimacy of the room never need to leave the smartphone.
Local Inference Technical Specifications
- Model Used: Gemma 4 (2B class) optimized and quantized for mobile devices.
- Engine: Based on the **LiteRT-LM** library running on fast and efficient native method channels (`MethodChannel`). Managed by
llm_local_datasource.dart. - Minimum Hardware: Smartphones with 4GB of free RAM, GPU/NPU graphics acceleration support, and ~1.3GB of free space for the quantized model.
- Privacy Visual Indicator: Whenever the AI is processed locally, the app displays a Golden Shield, certifying the isolation of the processing.
Below is the practical implementation of LlmLocalDataSourceImpl, demonstrating native invocation and automatic fallback to the cloud in case of error:
// lib/features/lectio_divina/data/datasources/llm_local_datasource.dart
import 'package:flutter/services.dart';
import 'package:pwe/features/lectio_divina/data/models/meditation_model.dart';
import 'package:pwe/features/lectio_divina/data/models/meditation_request_model.dart';
import 'package:pwe/features/lectio_divina/data/datasources/llm_remote_datasource.dart';
abstract class LlmLocalDataSource {
Future<MeditationModel> generateMeditation(MeditationRequestModel request);
}
class LlmLocalDataSourceImpl implements LlmLocalDataSource {
static const MethodChannel _channel = MethodChannel('pwe.app/gemma-inference');
final LlmRemoteDataSource remoteFallback;
final bool isGemmaEnabled;
LlmLocalDataSourceImpl({
required this.remoteFallback,
required this.isGemmaEnabled,
});
@override
Future<MeditationModel> generateMeditation(MeditationRequestModel request) async {
if (!isGemmaEnabled) {
return remoteFallback.generateMeditation(request);
}
try {
final String? response = await _channel.invokeMethod<String>(
'executeGemmaInference',
{
'prompt': request.toPrompt(),
'max_tokens': 200,
'temperature': 0.3,
},
);
if (response == null || response.isEmpty) {
throw PlatformException(code: 'EMPTY_RESPONSE', message: 'Gemma local retornou vazio.');
}
return MeditationModel.fromLocalText(response, request.passage);
} catch (e) {
// Fallback transparente em caso de indisponibilidade ou falha de inferência local
return remoteFallback.generateMeditation(request);
}
}
}
If the local model is not found or if the device does not support inference, the app makes a transparent and secure transition to the cloud API (Gemini), ensuring the continuity of the Lectio Divina without interruptions.
Bible Passage Capture via Photo (OCR)
In addition to typing passages and the dynamically collected daily liturgy, pwE allows instant capture of printed biblical texts using local visual artificial intelligence.
OCR Architecture & Mechanics
Integrating **Google ML Kit Vision**, the process is entirely offline and agile:
1. Capture & Edit
The user photographs the excerpt from the physical Bible and edits the image (crop and rotate) in the pre-processing screen to focus exclusively on the liturgical text.
2. Text Extraction
OCR processing extracts the sentences with precision, applying automatic spelling and punctuation refinement for fluid reading.
3. Remote Identification
The recognized excerpt is sent to the biblical context analyzer, which automatically detects the corresponding book, chapter, and verse.
Below is the practical example of integration with the ML Kit OCR for offline extraction of biblical text from physical pages of the Bible:
// lib/features/lectio_divina/data/datasources/ocr_local_datasource.dart
import 'dart:io';
import 'package:google_ml_kit/google_ml_kit.dart';
abstract class OcrLocalDataSource {
Future<String> extractTextFromImage(File imageFile);
}
class OcrLocalDataSourceImpl implements OcrLocalDataSource {
final TextRecognizer _textRecognizer = GoogleMlKit.vision.textRecognizer();
@override
Future<String> extractTextFromImage(File imageFile) async {
final inputImage = InputImage.fromFile(imageFile);
try {
final RecognizedText recognizedText = await _textRecognizer.processImage(inputImage);
// Filtra e limpa o texto para remover ruídos e marcas indesejadas do reconhecimento
String rawText = recognizedText.text;
return _refineBiblicalText(rawText);
} catch (e) {
throw Exception('Erro ao processar imagem via ML Kit OCR: ${e.toString()}');
}
}
String _refineBiblicalText(String input) {
return input
.replaceAll('\n', ' ')
.replaceAll(RegExp(r'\s+'), ' ')
.trim();
}
void dispose() {
_textRecognizer.close();
}
}
Integration Contracts & API (Swagger)
pwE follows the highest software architecture standards in the market for both its local and cloud connections. Below, explore the interactive, code-oriented documentation for the main endpoints and platform channels in the ecosystem.
Sends the text of the Holy Scripture (whether via direct typing, daily liturgy, or captured locally by OCR) and the spiritual-affective state of the faithful to the cloud AI spiritual advisor. The response is formulated strictly under the guidelines of the Magisterium and Fading Scaffolding maturity.
Body Parameters (JSON)
| Parameter | Type | Description |
|---|---|---|
| passage* required | string | The complete biblical text of the verse or chapter selected for meditation. |
| emotion | string | Emotional state of the faithful (e.g., "anxious", "grateful", "troubled") to contextualize the pastoral response. |
| maturity_level* required | string | App progress level that defines the verbosity and depth (beginner, practitioner, contemplative). |
import 'package:pwe/core/network/api_client.dart';
import 'package:pwe/features/lectio_divina/data/models/meditation_request.dart';
import 'package:pwe/features/lectio_divina/data/models/meditation_response.dart';
final apiClient = GetIt.I<ApiClient>();
final request = MeditationRequest(
passage: "O Senhor é o meu pastor, nada me faltará. Em verdes pastagens me faz repousar. (Salmo 22, 1-2)",
emotion: "ansioso",
maturityLevel: MaturityLevel.beginner,
);
final Either<Failure, MeditationResponse> result =
await apiClient.post('/v1/spiritual-advisor/meditate', data: request.toJson());
result.fold(
(failure) => print('Erro espiritual/rede: ${failure.message}'),
(meditation) => print('Meditação gerada: ${meditation.guidance}'),
);
curl -X POST "https://api.pwe.app/v1/spiritual-advisor/meditate" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer SEU_TOKEN_AQUI" \
-d '{
"passage": "O Senhor é o meu pastor, nada me faltará. (Salmo 22, 1)",
"emotion": "ansioso",
"maturity_level": "beginner"
}'
{
"passage": "O Senhor é o meu pastor, nada me faltará. Em verdes pastagens me faz repousar. Conduz-me junto às águas refrescantes, restaura as forças de minha alma. (Salmo 22, 1-3)",
"emotion": "ansioso",
"maturity_level": "beginner"
}
{
"status": "success",
"data": {
"passage_reference": "Salmo 22, 1-3",
"maturity_applied": "beginner",
"spiritual_guidance": "Meu filho em Cristo, a ansiedade tenta turvar as águas da tua alma, mas o Bom Pastor te convida ao repouso no Seu amor. Diante da agitação do mundo, lembra-te de que Ele tem o controle absoluto de todas as coisas. Entrega-Lhe as tuas preocupações no silêncio da oração. Nas palavras de São Padre Pio: 'Reze, espere e não se preocupe. A preocupação é inútil. Deus é misericordioso e ouvirá sua oração.' Que o teu coração descanse hoje na certeza da Providência Divina.",
"reflection_points": [
"Como você tem buscado as 'verdes pastagens' da oração no meio das tribulações cotidianas?",
"De que maneira a entrega confiante ao Bom Pastor pode acalmar a tempestade da sua ansiedade hoje?",
"Faça um ato de fé simples: 'Jesus, eu confio em Vós, mesmo quando não vejo o caminho.'"
]
}
}
Consumes the official API to load the liturgical texts of the Roman Catholic Church valid for the current date or an optional date. Returns First Reading, Responsorial Psalm, Second Reading (if any), and Gospel to support Lectio Divina in a structured way.
Parameters da Query (Request URL)
| Parameter | Type | Description |
|---|---|---|
| date | string | Target date in ISO-8601 YYYY-MM-DD format. Default is current server date. |
| translation | string | Desired translation and Bible version (e.g., cnbb, ave_maria, jerusalem). Default: cnbb. |
import 'package:pwe/features/lectio_divina/domain/repositories/liturgy_repository.dart';
import 'package:pwe/features/lectio_divina/domain/entities/liturgical_day.dart';
final liturgyRepo = GetIt.I<LiturgyRepository>();
final Either<Failure, LiturgicalDay> result =
await liturgyRepo.getTodayLiturgy(translation: 'cnbb');
result.fold(
(failure) => print('Erro ao coletar liturgia: ${failure.message}'),
(liturgy) => print('Evangelho do dia (${liturgy.reference}): ${liturgy.content}'),
);
curl -X GET "https://api.pwe.app/v1/liturgy/today?translation=cnbb" \
-H "Accept: application/json"
{
"date": "2026-05-21",
"liturgical_season": "Tempo Pascal",
"liturgical_color": "Branco",
"celebration": "Quinta-feira da 7ª Semana da Páscoa",
"readings": {
"first_reading": {
"reference": "Atos 22, 30; 23, 6-11",
"title": "Paulo testemunha em Jerusalém e é enviado a Roma",
"content": "Naqueles dias, querendo saber com certeza de que os judeus o acusavam, o comandante soltou Paulo e mandou reunir os sumos sacerdotes e todo o conselho dos anciãos..."
},
"psalm": {
"reference": "Salmo 15 (16)",
"response": "Guardai-me, ó Deus, porque em vós me refugio!",
"verses": [
"Preservai-me, ó Deus, porque em vós me refugio! Eu digo ao Senhor: 'Vós sois o meu Deus'.",
"Ó Senhor, vós sois a minha herança e o meu cálice; nas vossas mãos está o meu destino."
]
},
"evangelho": {
"reference": "João 17, 20-26",
"title": "Que eles sejam um em nós, para que o mundo creia",
"content": "Naquele tempo, Jesus levantou os olhos ao céu e rezou, dizendo: 'Não rogo somente por eles, mas também por aqueles que vão creer em mim pela sua palavra...'"
}
}
}
Native platform communication channel (MethodChannel) to asynchronously delegate the processing of Large Language Model inference (Gemma 2B quantized via LiteRT-LM) to 100% isolated and offline execution on the user's smartphone. Ensures sovereignty and absolute privacy.
Input Arguments (Method Call)
| Argument | Type | Description |
|---|---|---|
| prompt* required | string | Prompt containing the passage and strict Catholic context to feed into local Gemma. |
| max_tokens | int | Limit of tokens to be generated by the model. Default: 150. |
| temperature | double | Decoder thermal randomness factor. Default: 0.3. |
import 'package:flutter/services.dart';
const MethodChannel _channel = MethodChannel('pwe.app/gemma-inference');
Future<String?> generateLocalGuidance({
required String prompt,
int maxTokens = 150,
double temperature = 0.3,
}) async {
try {
final String? result = await _channel.invokeMethod<String>(
'executeGemmaInference',
{
'prompt': prompt,
'max_tokens': maxTokens,
'temperature': temperature,
},
);
return result;
} on PlatformException catch (e) {
print("Erro na inferência local Gemma: ${e.message}");
return null;
}
}
package com.pwe.app.inference
import android.content.Context
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import com.google.mediapipe.tasks.genai.llminference.LlmInference
class GemmaInferencePlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
private lateinit var channel: MethodChannel
private var llmInference: LlmInference? = null
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(binding.binaryMessenger, "pwe.app/gemma-inference")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method == "executeGemmaInference") {
val prompt = call.argument<String>("prompt") ?: ""
val maxTokens = call.argument<Int>("max_tokens") ?: 150
val temp = call.argument<Double>("temperature") ?: 0.3
try {
// Inferência executada localmente de forma isolada
val response = llmInference?.generateResponse(prompt)
result.success(response)
} catch (e: Exception) {
result.error("GENAI_ERROR", e.localizedMessage, null)
}
} else {
result.notImplemented()
}
}
}
{
"prompt": "Contexto: Atue como um orientador espiritual católico fiel ao Magistério da Igreja. Passagem: João 17, 20-26. Gere 2 pontos curtos de meditação.",
"max_tokens": 150,
"temperature": 0.3
}
{
"status": "success",
"engine": "LiteRT-LM (Gemma 2B)",
"inference_time_ms": 342,
"result": "1. Unidade na Caridade: Jesus roga ao Pai por nossa unidade como sinal visível da Sua missão divina. Rezemos pela coesão da Igreja hoje.\n2. O Amor Divino em Nós: A oração de Cristo pede que o amor com que o Pai O amou habite em nós. Deixemo-nos possuir por esse amor no silêncio da Contemplatio."
}
Architecture Decisions (ADRs 0001–0079)
pwE maintains 79 formal Architecture Decision Records (docs/adr/0001..0079), ensuring complete technical traceability from foundation through our global Google Play Store Go-Live (Nov 2, 2026) and Day-2 operations:
Status: Accepted | Objective: Separate domain purity from infrastructure agents and isolate DI scopes.
The Domain layer contains zero imports from Flutter or Firebase. All 8 features (auth, lectio_divina, onboarding, profile, recollection, settings, subscription, support) and security_vault manage their own isolated containers in GetIt.
Status: Accepted | Objective: 100% on-device inference and semantic search with zero spiritual data leaks.
Native platform channels (MethodChannel / EventChannel in Android Kotlin JNI and iOS Swift C API) run Gemma 4 E2B with a memory concurrency mutex, paired with on-device vectorization via TFLite (all-MiniLM-L6-v2, 384 dimensions, WordPiece, and Mean Pooling).
Status: Accepted | Objective: Eliminate monolithic coupling and UI state race conditions.
Permanent removal of the legacy monolithic LectioBloc and segregation into 10 specialized Sub-BLoCs across the prayer journey (LectioSessionBloc, DailyLiturgyBloc, ExegesisBloc, PrayerJournalBloc, AiOratioBloc, PassageDiscoveryBloc, ModelDownloadBloc, among others), powering 236 automated test suites (1,430+ tests).
Status: Accepted | Objective: Full user data sovereignty and Apple/Google store compliance.
Any call to remote cloud models requires prior explicit consent. The UI visually highlights local processing via the Golden Shield and offers a classic contemplative Lectio Divina mode completely without AI.
Status: Accepted | Objective: Absolute protection of private prayers and Spiritual Notebook entries.
Local Hive persistence and per-field Cloud Firestore sync are encrypted with AES-256-GCM, 96-bit random IVs, PBKDF2 key derivation, hardware key anchoring (Android Keystore / iOS Keychain), and an optional user passphrase vault (wrapped:v3), protecting 190+ active production vaults.
Status: Accepted | Objective: Balance on-demand screen protection with digital evangelization.
Implements ScreenSecurityService to dynamically toggle FLAG_SECURE at runtime without restarting the app, paired with SacredShareService to render high-definition sacred art cards (SacredShareCard, pixelRatio: 3.0) for WhatsApp and Instagram Stories.
Status: Accepted | Objective: Global scale at Zero Cost (FinOps Free Tier) and continuous theological quality auditing.
The daily Cloud Run Job publishes static JSONs (liturgies/{lang}/{date}.json), precomputed audio, and Sacred Icons to Google Cloud Storage Static CDN with CORS-safe JSON API resolution, keeping daily Firestore reads at just 4.11% of the free-tier quota. For AI, LangfuseService (OTLP v4) verifies a 100% theological orthodoxy score.
Status: Accepted | Objective: Cross-platform commercial parity (Android, iOS, Web) and 100% CI quota savings.
Integrates native RevenueCat SDK and REST API v1 on Web (/app), accompanied by the custom CLI tool/pwe_local_deploy.dart that builds signed .aab bundles and publishes directly to the Google Play Publisher API v3 (native OAuth2 JWT RS256) and Firebase Hosting in ~3 minutes from the local workstation.
Status: Accepted | Objective: Autonomous 4-pillar governance and physical hardware runtime inspection.
Orchestrates 18 specialist subagents in .agents/agents/, including perf-validator integrated with Marionette and Dart MCP for live BLoC state verification and PSS memory profiling, alongside the Master Technical Documentation Suite.
Status: Accepted | Objective: Publicly expose Staff-level architectural decisions and real code slices with zero risk of leaking proprietary IP.
Implements the tool/sync_showcase.dart CLI orchestrator that exports a strict Allowlist (69 ADRs, 8 C4/Sequence/State specs, 18-agent governance docs, and 20 real Clean Code Slices + tests across 5 domains) to github.com/evslopes/pwe-architecture-showcase ↗, protected by a deterministic Redaction Engine (16 rules) and a post-generation Security Leak Scanner (13 forbidden patterns).
Status: Accepted | Objective: Eliminate tester binary staleness across Closed Testing tracks and instrument privacy-safe contemplative funnels.
Synchronizes atomic promotion across internal, alpha, and dedicated closed tracks via Google Play API v3 paired with VersionGovernanceBanner on Firebase Remote Config — preventing premature lockouts during the ~72h human review queue while consolidating zero-PII GA4 funnel telemetry.
Status: Accepted | Objective: Global financial accessibility, Google Play regulatory compliance, and 177-country Production launch.
Introduces tool/pwe_monetization_sync.dart provisioning 54 localized store listings (3 plans × 18 languages) across 174 countries using Purchasing Power Parity (PPP) and a 30-day non-renewing prepaidBasePlanType; enforces surgical manifest cleanup (tools:node="remove" for AD_ID, READ_PHONE_STATE, STORAGE), physical-device video validation of FOREGROUND_SERVICE_DATA_SYNC on Android 14+, and official Production Go-Live on November 2, 2026.
Status: Accepted | Objective: Instant offline resilience with zero blocking network gates and zero lost prayer drafts.
Implements a network Circuit Breaker, transactional offline Outbox queue, 22 bundled sacred .ttf fonts (eliminating cold-start HTTP font fetches), atomic auto-save of Oratio/Contemplatio drafts, and an offline deterministic Roman General Calendar Computus engine.
Status: Accepted | Objective: Silence external notifications during prayer and accurately measure silent readers without FinOps write bloat.
Integrates native Android 15+ AutomaticZenRule / ZenPolicy and iOS 16+ Focus Filters guarded by a 4-layer Zero-Orphaned-DND recovery protocol so system notifications always restore cleanly. Introduces FinOps-safe Nominal Liturgical Presence (<= 1 write/day) after production data showed 58.3% of users pray daily as silent Missal readers.
Status: Accepted | Objective: Executable contracts before code, fluid on-device AI UX, and $0/month unified SRE observability.
Establishes 16 formal SPEC-* contracts verified across 236 TDD suites; native EventChannel token streaming on Gemma 4 LiteRT-LM, on-device Echoes of Grace synthesis, two-column Biblical OCR, and a 30-scenario Dogmatic LLM Eval across the 73-book Canon; plus pwe_production_monitor.dart and native isolation of 84 Firebase Test Lab bots via Settings.System("firebase.test.lab").
Status: Accepted | Objective: Zero-friction contemplative first launch and end-to-end deterministic 18-language parity.
Implements single-door A1 → A2 progressive onboarding opening straight into Visio Divina contemplation; disables Play Feature Delivery language splitting (enableSplit = false + locales_config.xml) preserving all 18 ARB catalogs with universal English fallback; and parallelizes daily-liturgy-worker across all 18 languages on GCS Static CDN.
Status: Accepted | Objective: Eradicate client-side AI secrets, de-monolithize Presentation, and share a single pure-Dart engine across App and AOT Worker.
Monotonic prayer streak hardening (ADR 0070), contextual notification governance (ADR 0071), serverless Cloud Run proxy verified with Firebase App Check and Firestore Allowlists (ADR 0072), Presentation de-monolithization and DI purity (ADR 0073), unified 100% pure-Dart AOT liturgical engine (ADR 0074), and strict debug isolation of Marionette with WebP sacred icons (ADR 0075).
Status: Accepted | Objective: Pastoral communion, uncontaminated forensic observability, official CNBB licensing, and Flutter 3.50 / Dart 3.14 upgrade.
Zero-Loss late guest account linking (ADR 0076), O(Δ) delta sync and 3-layer bench segregation in the 360° monitor with privacy-first UTM / Play Install Referrer attribution (ADR 0077), canonical Pray With All / Integrated Journey vocabulary audited across 1,013+ ARB keys (ADR 0078), formal copyright licensing signed with Edições CNBB (ADR 0079), and coordinated upgrade to Flutter 3.50.0, Dart 3.14.0, google_sign_in v7 (Credential Manager), and FlutterFire v7 backed by 260 TDD suites (1,778+ tests).
Refactoring History (Logs)
Follow the technical logs of major evolutions and engineering improvements applied to the project (found in docs/refactor/).
Downloading a 1.3GB model is critical on mobile networks. The refactoring implemented:
- Partitioned Download: Use of stable buffers to avoid OOM during local writing.
- Integrity Validation: SHA256 hash calculation post-download before extraction.
- GlobalDownloadTracker: A widget that floats above the entire application showing the progress percentage, allowing the user to navigate or pray while the download completes in the background.
The raw ML Kit processor captured graphical noise from edges and shadows of physical Bible pages. The refactoring introduced:
- Adaptive Thresholding Binarization: Fast conversion of the captured photo to high-contrast black and white via native Canvas before submitting it to OCR.
- Lexical Correction Algorithm: A local micro-parser that crosses the captured text with common liturgical expressions to correct subtle character recognition failures.
Troubleshooting
Interactive section for engineers and testers to quickly resolve common environment and build issues in the pwE project.
Errors occur when the Gradle Wrapper or Android Gradle Plugin does not match the required SDK level. To update to a stable and recommended version:
# Navigate to the project's android directory
cd android
# Update the Gradle Wrapper to the compatible stable version (e.g., 8.13)
./gradlew wrapper --gradle-version 8.13
Also make sure that the gradle-wrapper.properties file has the distribution link correctly configured for the stable version in HTTPS.
To ensure that the model's binary file `.litertlm` (~1.3GB) was not corrupted during the user's opt-in download, the app validates the SHA256 hash.
If loading fails continuously, confirm the signature configured in your Firebase Remote Config dashboard:
# Expected variables in Remote Config
enable_gemma_local: true
gemma_model_sha256: "COLOCAR_HASH_SHA256_REAL_DO_MODELO_AQUI"
gemma_model_download_url: "https://seu-cdn-seguro.com/models/gemma-2b-it.litertlm"
If the hash differs, the `GemmaLocalDataSource` will reject local initialization and immediately trigger the fallback to Gemini in the cloud for safety.
When running unit and state integration tests in BLoC (e.g., `lectio_session_bloc_test.dart`), make sure to inject mocked use cases via **Mockito** or **Mocktail** and register in test GetIt to avoid calling real network APIs.
# Run all unit tests of the project cleanly
flutter test --coverage
Context and Container Diagram (C4 Model)
This C4 model diagram details the high-level integrations of the pwE ecosystem (Android, iOS, and Web) with on-device AI engines and cloud-native services.
graph TB
User((Catholic Faithful))
pwE["pwE App (Android, iOS & Web /app)"]
subgraph OnDevice ["Edge AI & On-Device Security"]
Gemma["LiteRT-LM (Gemma 4 E2B) + TFLite BERT 384d"]
Vault["Hive AES-256-GCM + Keystore/Keychain"]
MLKit["Google ML Kit - Offline Bible OCR"]
end
subgraph Cloud_Ecosystem ["Cloud Ecosystem & Observability"]
GCS["GCS Static CDN (>98% Liturgy & Icon Offload)"]
Firebase["Firebase: Auth, Encrypted Firestore, Remote Config, FCM"]
Gemini["7-Model Gemini Staircase + Langfuse REST v2"]
Worker["Daily Cloud Run Job (CNBB / LitCal v5)"]
RevCat["RevenueCat (Native SDK + Web REST v1)"]
end
User -->|Practices Lectio Divina| pwE
pwE -->|100% Local Inference & RAG| Gemma
pwE -->|Persists Spiritual Notebook| Vault
pwE -->|Scans Physical Bible| MLKit
pwE -->|Fetches Liturgy & Sacred Audio| GCS
pwE -->|Syncs & Governs Version| Firebase
pwE -->|AI Fallback & Theological Scores| Gemini
pwE -->|Benefactor Tier| RevCat
Worker -->|Publishes JSONs & Icons| GCS
Session Sequence Diagram
Visualize the complete lifecycle of a prayer session, tracking data and command traffic through the software layers.
sequenceDiagram
autonumber
participant U as User
participant UI as Presentation (Bloc/UI)
participant D as Domain (UseCases)
participant R as Data (Repositories/DS)
participant IA as AI (Gemini/Gemma)
participant B as DB (Firestore/Hive)
U->>UI: Starts Session (Selects Emotion)
UI->>D: SuggestPassageUseCase(emotion)
D->>R: IARepository.getSuggestion()
R->>IA: Prompt (Spiritual Advisor Context)
IA-->>R: Passage Suggestion + Reason
R-->>D: DailyPassage Suggestion
D-->>UI: LectioInProgress(suggestedPassage)
U->>UI: Reads & Starts Lectio
UI->>U: Displays Scripture Text
U->>UI: Advances to Meditatio
UI->>D: GetGuidedMeditationUseCase(passage)
D->>R: IARepository.getMeditationPoints()
R->>IA: Prompt (Magisterium-aligned Meditatio)
IA-->>R: Concrete Meditation Points
R-->>D: MeditationPoints
D-->>UI: LectioInProgress(guidingPrompt)
U->>UI: Advances to Oratio & Writes Prayer
UI->>D: GetPrayerPromptUseCase()
D->>R: IARepository.getPrayerInspiration()
R->>IA: Prompt based on Catholic Tradition
IA-->>R: Prayer Inspiration
R-->>D: PrayerPrompt
D-->>UI: LectioInProgress(prayerPrompt)
U->>UI: Writes Resolution (Contemplatio)
U->>UI: Completes Session (HoldToSaveButton)
UI->>D: SaveSessionUseCase(session)
D->>R: SessionRepository.save()
R->>B: Persists locally & in cloud (AES-256-GCM)
B-->>R: Success
R-->>D: Success
D-->>UI: LectioCompleted
UI->>U: Displays Streak Celebration Screen
State Machine: LectioSessionBloc
Rigorous management of states and asynchronous screen flows in pwE using the Event, State, and decoupled Sub-BLoCs triad.
stateDiagram-v2
[*] --> LectioInitial: Feature Initialization
LectioInitial --> LectioInProgress_Lectio: StartSessionEvent
state LectioInProgress {
[*] --> LectioInProgress_Lectio
LectioInProgress_Lectio --> LectioInProgress_Meditatio: AdvanceToStep(1)
LectioInProgress_Meditatio --> LectioInProgress_Oratio: AdvanceToStep(2)
LectioInProgress_Oratio --> LectioInProgress_Contemplatio: AdvanceToStep(3)
LectioInProgress_Contemplatio --> [*]: CompleteSessionEvent
}
LectioInProgress --> LectioCompleted: Session Saved Successfully
LectioInProgress --> LectioError: Failure (API/Network/DB)
LectioError --> LectioInitial: Reset / Retry
LectioCompleted --> [*]
Folder Structure and Clean Architecture Mapping
The directory tree of the pwE repository reflects strict layer boundaries, domain isolation, and the automation suite:
Folder Tree (v1.0.56+232 · Flutter 3.50 / Dart 3.14)
lib/ # 513 .dart files · 16 SDD Specs · 260 TDD Suites (1,778+ tests)
├── core/ # Agnostic Subpackages, Shared Pure-Dart Engine & Offline Outbox
│ ├── di/ # GetIt Orchestration (injection_container.dart)
│ ├── error/ # Functional Failures & Exceptions (Either)
│ ├── liturgy/ # Shared Liturgical Engine for App & AOT Worker (ADR 0074)
│ ├── network/ # Zero-Key Proxy (App Check), GCS CDN & Langfuse OTLP v4
│ ├── routes/ # 16 Declarative Sacred Routes (GoRouter 18)
│ ├── security/ # AES-256-GCM, Keystore/Keychain & ScreenSecurity
│ └── theme/ # Sacred Design System + 22 Bundled Offline .ttf Fonts
├── features/ # 8 Isolated Domain Modules + Security Vault
│ ├── lectio_divina/ # Main Domain of Prayerful Reading & Official CNBB Credits
│ │ ├── data/ # Models, RepositoriesImpl & DataSources (Local/Remote)
│ │ ├── domain/ # Pure Entities, Contracts & UseCases
│ │ └── presentation/ # 10 Decoupled Sub-BLoCs (16 BLoCs total) & Widgets
│ ├── auth/ # Google Sign-In v7 (Credential Manager), Apple & Zero-Loss Guest
│ ├── onboarding/ # Progressive Visio Divina (A1→A2) & Sovereign AI Choice
│ ├── profile/ # Maturity (Fading Scaffolding) & Spiritual Notebook
│ ├── recollection/ # Interior Recollection Mode Mt 6:6 (ZenPolicy / Focus)
│ ├── preferences/ # Typographic Preferences, Theme & 18 ARB Locales
│ ├── security_vault/ # Optional Passphrase Key Vault (wrapped:v3)
│ ├── subscription/ # Mission Friends / Pray With All (RevenueCat v11 + 174 PPP Regions)
│ └── support/ # Pastoral Care & Remote Version Governance
├── l10n/ # 18 ARB Catalogs × 1,013+ Audited Keys (enableSplit=false)
└── main.dart # True Local-First Bootstrap (0 ms) & Anti-Bot Shield