Initial commit: Grounded Flutter frontend

A to-do app that doesn't believe you — an enforcement layer rather than a
neutral ledger.

Architecture ported from Autoreceptives/Frontend/Receptive: stacked MVVM with
the mandatory 4-file screen pattern, one ParentViewModel owning the loading /
network / error overlays and the handleError decision tree, one AppDataManager
gateway, dio comms carrying the three identity headers, secure storage with
random-suffixed keys, and a single-chokepoint Navigator. Package root and Dart
package name are both Grounded; org is nya.

The enforcement engine, one unit per formula in utils/:

- DebtEngine      w(class) x severity(d) x decay(t), sublinear severity so old
                  misses cannot swamp the score; abandonment 2x with 30-day
                  decay immunity; late complete retains 30%
- StandingEngine  Good -> Warned -> Grounded -> Lockdown, derived not set;
                  Grounded replaces home with the overdue queue
- CapacityEngine  blocks over-scheduling against p50 of historically completed
                  minutes, with a learned per-category estimation multiplier
- IntegrityEngine session integrity, weekly volume, plyometric contact ceiling
                  and enforced recovery gaps
- ExcuseAnalyser  on-device excuse clustering plus the confrontation copy
- GuardrailEngine distress detection and rationed amnesty
- ToneEngine      all enforcement copy, so the tone cap lives in one place

CommitmentEvent is append-only and is the source of truth rather than the
status field, which is what makes honest history and excuse analysis possible.

Goals contain commitments via parentId, and a task can be run from a
full-screen runner that derives elapsed time from wall-clock so screen-off
cannot lose time. Backgrounding pauses the clock and is counted. The runner is
mirrored into an ongoing notification, with alarm-class full-screen intents
reserved for non-negotiables.

Design language, fonts, icon and native splash are in place; Mason bricks are
retargeted to this project and verified end-to-end.

flutter analyze lib/ reports no errors.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Mfu2gQLSFN21YRBcU2NrTt
This commit is contained in:
alvocool
2026-07-27 09:11:17 +03:00
commit 16bff634b5
315 changed files with 19132 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
# 0.1.0+1
- TODO: Describe initial release.

View File

@@ -0,0 +1 @@
TODO: Add your license here.

View File

@@ -0,0 +1,92 @@
# 🔐 Internal Memory Brick
An advanced **Mason** brick designed for the **Autoreceptive** architecture. It automates the boilerplate for persistent local storage using `flutter_secure_storage` (via `autoreceptiveStorage`), handling JSON serialization for Objects and Lists, and raw storage for Strings.
## 🚀 Purpose
This brick eliminates the manual task of:
1. Generating high-entropy, randomized secure keys.
2. Writing `get` and `set` interfaces in `ConnectInternalMemory`.
3. Implementing JSON encoding/decoding logic in `InternalMemory`.
4. Wrapping calls in `AppDataManager` to maintain the **Repository Pattern**.
---
## 📂 Target Architecture
The brick targets the following specific paths in your project:
* **Interface**: `lib/Autoreceptive/memory/ConnectInternalMemory.dart`
* **Implementation**: `lib/Autoreceptive/memory/InternalMemory.dart`
* **Global Access**: `lib/Autoreceptive/informatics/AppDataManager.dart`
---
## 🛠 Installation
### 1. Register the Brick
From your project root, run:
```bash
mason add internal_memory --path ./bricks/internal_memory
```
### 2. Setup Hooks
The brick uses specialized Dart hooks for smart code injection and auto-formatting.
```bash
cd bricks/internal_memory/hooks && dart pub get && cd ../../../
mason get
```
---
## 📖 Usage Guide
Run the following command and follow the interactive prompts:
```bash
mason make internal_memory
```
### Variable Inputs:
| Variable | Description | Example |
| :--- | :--- | :--- |
| `function_name` | The camelCase name of the feature. | `userProfile` or `orderLocations` |
| `request_object` | The Dart type to store. | `MeDescription`, `String`, or `List<Location>` |
---
## 📋 Logic Breakdown
### 1. High-Entropy Keys
The brick generates a randomized `static const String` key at the **top** of the `InternalMemory` class to prevent key collisions and reverse-engineering:
```dart
static const String USER_PROFILE = "USER_PROFILE_x8H2_9kLp_mQz1";
```
### 2. Intelligent Type Handling
The hook detects the `request_object` type and adjusts the logic:
* **Standard Objects**: Uses `Type.fromJson(jsonDecode(s))` and `jsonEncode(data.toJson())`.
* **Lists**: Uses `.map((item) => Type.fromJson(item)).toList()` for deep serialization.
* **Strings**: Bypasses JSON logic for raw string storage.
### 3. Smart Injection & Spacing
* **Clean Pairs**: In the interface, the getter and setter are injected as a tight block with a double-newline buffer from the previous feature.
* **Auto-Imports**: Automatically adds `import 'dart:convert';` and searches the `lib/` folder to find and add the correct model imports for your Objects.
* **Formatting**: Automatically triggers `dart format` on the `Autoreceptive` folder after injection.
---
## ⚠️ Requirements
* **`autoreceptiveStorage`**: The `InternalMemory` class must have an instance of your secure storage wrapper named `autoreceptiveStorage`.
* **Model Factories**: For Objects and Lists, your models must implement:
* `factory Model.fromJson(Map<String, dynamic> json)`
* `Map<String, dynamic> toJson()`
---
## 🔄 Refreshing Logic
If you update the `post_gen.dart` hook code, always run this to ensure Mason uses the latest version:
```bash
rm -rf .mason && mason get
```
---

View File

@@ -0,0 +1,11 @@
name: internal_memory
description: Generates Secure Storage logic with JSON serialization and AppDataManager sync.
version: 0.1.0+1
vars:
function_name:
type: string
prompt: "🖋️ What is the function name? (e.g., myDescription)"
request_object:
type: string
prompt: "📦 What is the Object type to store? (e.g., MeDescription)"

View File

@@ -0,0 +1,186 @@
import 'dart:io';
import 'dart:convert';
import 'dart:math';
import 'package:mason/mason.dart';
import 'package:yaml/yaml.dart';
void run(HookContext context) async {
final logger = context.logger;
final String functionName = context.vars['function_name'] ?? '';
final String requestObject = context.vars['request_object'] ?? '';
final cName = functionName.camelCase;
final pName = functionName.pascalCase;
final uName = functionName.snakeCase.toUpperCase();
final secureKeyValue = _generateSecureKey(uName);
String projectName = 'your_project';
final pubspecFile = File('pubspec.yaml');
if (pubspecFile.existsSync()) {
final doc = loadYaml(pubspecFile.readAsStringSync());
projectName = doc['name'] ?? projectName;
}
final bool isList = requestObject.startsWith('List<');
final bool isString = requestObject.toLowerCase() == 'string';
String baseType = requestObject;
if (isList) {
baseType = requestObject.substring(5, requestObject.length - 1);
}
final files = [
'lib/Grounded/memory/ConnectInternalMemory.dart',
'lib/Grounded/memory/InternalMemory.dart',
'lib/Grounded/informatics/AppDataManager.dart'
];
String? importLine;
String? importFileName;
if (!isString) {
final result = await _findClassData(baseType, projectName);
importLine = result?['line'];
importFileName = result?['fileName'];
}
// --- Implementation Logic ---
String getLogic = "";
String setLogic = "";
if (isString) {
getLogic = "return await groundedStorage.read(key: $uName) ?? '';";
setLogic = "await groundedStorage.write(key: $uName, value: data);";
} else if (isList) {
getLogic = '''
final dataString = await groundedStorage.read(key: $uName);
if (dataString != null && dataString.isNotEmpty) {
return (jsonDecode(dataString) as List)
.map((item) => $baseType.fromJson(item))
.toList();
}
return [];''';
setLogic = '''
final jsonString = jsonEncode(data.map((item) => item.toJson()).toList());
await groundedStorage.write(key: $uName, value: jsonString);''';
} else {
getLogic = '''
final jsonString = await groundedStorage.read(key: $uName);
if (jsonString != null && jsonString.isNotEmpty) {
return $baseType.fromJson(jsonDecode(jsonString));
}
return $baseType();''';
setLogic = '''
await groundedStorage.write(key: $uName, value: jsonEncode(data.toJson()));''';
}
// --- 1. ConnectInternalMemory (No space between the pair) ---
final interfaceCode = " Future<$requestObject> get$pName();\n Future set$pName($requestObject data);";
await _inject(files[0], interfaceCode, logger, importLine: importLine, importFileName: importFileName, duplicateCheck: "get$pName()");
// --- 2. InternalMemory (Key spacing at TOP) ---
final String keyLine = '\n\n static const String $uName = "$secureKeyValue";\n';
final String methods = '''
@override
Future<$requestObject> get$pName() async {
$getLogic
}
@override
Future set$pName($requestObject data) async {
$setLogic
}''';
await _injectInternalMemory(files[1], keyLine, methods, logger, importLine: importLine, importFileName: importFileName, duplicateCheck: "get$pName()");
// --- 3. AppDataManager ---
final String wrapper = '''
@override
Future<$requestObject> get$pName() async {
return await connectInternalMemory.get$pName();
}
@override
Future set$pName($requestObject data) async {
return await connectInternalMemory.set$pName(data);
}''';
await _inject(files[2], wrapper, logger, importLine: importLine, importFileName: importFileName, duplicateCheck: "get$pName()");
// --- 4. Format ---
try {
await Process.run('dart', ['format', 'lib/Grounded/']);
} catch (_) {}
logger.success('✨ Internal Memory synced with corrected spacing.');
}
String _generateSecureKey(String base) {
final random = Random.secure();
final values = List<int>.generate(12, (i) => random.nextInt(256));
return "${base}_${base64Url.encode(values).replaceAll('=', '').substring(0, 16)}";
}
Future<Map<String, String>?> _findClassData(String className, String projectName) async {
final dir = Directory('lib');
if (!dir.existsSync()) return null;
for (var f in dir.listSync(recursive: true)) {
if (f is File && f.path.endsWith('.dart')) {
final content = await f.readAsString();
if (content.contains('class $className')) {
return {
'line': "import 'package:$projectName/${f.path.replaceFirst('lib/', '')}';",
'fileName': f.path.split('/').last,
};
}
}
}
return null;
}
Future<void> _inject(String path, String content, Logger logger, {String? importLine, String? importFileName, String? duplicateCheck}) async {
final file = File(path);
if (!await file.exists()) return;
String fileContent = await file.readAsString();
if (duplicateCheck != null && fileContent.contains(duplicateCheck)) return;
if (importLine != null && importFileName != null && !fileContent.contains(importFileName)) {
fileContent = "$importLine\n$fileContent";
}
final lastBrace = fileContent.lastIndexOf('}');
if (lastBrace != -1) {
// Inject with double newlines between previous content and new content
fileContent = fileContent.substring(0, lastBrace).trimRight() + '\n\n$content\n' + fileContent.substring(lastBrace);
await file.writeAsString(fileContent);
}
}
Future<void> _injectInternalMemory(String path, String keyLine, String methods, Logger logger, {String? importLine, String? importFileName, String? duplicateCheck}) async {
final file = File(path);
if (!await file.exists()) return;
String content = await file.readAsString();
if (duplicateCheck != null && content.contains(duplicateCheck)) return;
if (importLine != null && importFileName != null && !content.contains(importFileName)) {
content = "$importLine\n$content";
}
if (!content.contains("import 'dart:convert';")) {
content = "import 'dart:convert';\n$content";
}
// Inject Key at the top with forced extra spacing
final classStart = content.indexOf('{');
if (classStart != -1) {
content = content.substring(0, classStart + 1) + "$keyLine" + content.substring(classStart + 1);
}
// Inject Methods at the bottom
final lastBrace = content.lastIndexOf('}');
if (lastBrace != -1) {
content = content.substring(0, lastBrace).trimRight() + "\n\n$methods\n" + content.substring(lastBrace);
}
await file.writeAsString(content);
}

View File

@@ -0,0 +1,8 @@
name: internal_memory_hooks
description: Hooks for internal_memory.
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
mason: ^0.1.0-dev.51
yaml: ^3.1.2