feat(block1): inventory walking skeleton + first quick-add slice

Stand up the Tanemaki monorepo and the first end-to-end vertical slice of
Block 1 (offline, encrypted inventory): add a seed → see it in a categorized,
searchable list → it persists → reopen and it's still there.

Architecture (state management like G1nkgo, adapted to Tane's reality):
- flutter_bloc (Cubit-first), but the encrypted Drift DB is the single source
  of truth; cubits stream from repositories (no hydrated_bloc/Hive, which would
  write plaintext at rest).
- get_it composition root; go_router; slang i18n (ES/EN, Weblate-friendly JSON).

Workspace & core:
- pub workspace: packages/commons_core (pure Dart) + apps/app_seeds (Flutter).
- commons_core primitives: UUIDv7 IdGen, Hybrid Logical Clock, Quantity value
  type (+ plant-aware QuantityKind), IdentityService root-seed stub.

Data & security:
- Drift schemaVersion=1 with all 10 Block-1 tables + common CRDT columns
  (HLC updated_at, last_author, tombstones); Movement append-only.
- SQLCipher via an injectable executor that refuses to open a plaintext DB;
  DB key + root seed in the OS keystore (separate secrets).
- Exported drift_schema_v1.json + migration scaffold.

Tests (near-TDD; nothing merges without tests):
- commons_core units (24), Drift migration test, "no plaintext at rest"
  security guard (runs where SQLCipher is present, skips otherwise),
  repository, widget, full quick-add flow, file-reopen persistence, and a
  no-hardcoded-strings i18n guard. GitLab CI: format + analyze + test + coverage.

Follow-on Block-1 stories (item detail/edit, species catalog, germination UI)
and all of Block 2 remain out of scope.
This commit is contained in:
vjrj 2026-07-07 15:16:14 +02:00
parent 57c0eeadaf
commit 040f15a898
131 changed files with 19855 additions and 20 deletions

View file

@ -0,0 +1,37 @@
import 'dart:io';
import 'package:commons_core/commons_core.dart';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:tane/data/variety_repository.dart';
import 'package:tane/db/database.dart';
/// Proves the "reopen and it's still there" half of the sprint's definition of
/// done at the persistence layer, on a real on-disk file (unencrypted here so
/// it runs on any host encryption at rest is covered by no_plaintext_test).
void main() {
test('a seed survives closing and reopening the database file', () async {
final dir = await Directory.systemTemp.createTemp('tane_persist');
addTearDown(() => dir.delete(recursive: true));
final file = File(p.join(dir.path, 'inventory.sqlite'));
var db = AppDatabase(NativeDatabase(file));
await VarietyRepository(
db,
idGen: IdGen(),
nodeId: 'n',
).addQuickVariety(label: 'Persisted tomato');
await db.close();
db = AppDatabase(NativeDatabase(file));
final items = await VarietyRepository(
db,
idGen: IdGen(),
nodeId: 'n',
).watchInventory().first;
await db.close();
expect(items.map((i) => i.label), ['Persisted tomato']);
});
}

View file

@ -0,0 +1,76 @@
import 'dart:typed_data';
import 'package:commons_core/commons_core.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/data/variety_repository.dart';
import 'package:tane/db/database.dart';
import 'package:tane/db/enums.dart';
import '../support/test_support.dart';
void main() {
late AppDatabase db;
late VarietyRepository repo;
setUp(() {
db = newTestDatabase();
repo = newTestRepository(db);
});
tearDown(() => db.close());
test(
'addQuickVariety persists a variety that appears in the stream',
() async {
await repo.addQuickVariety(
label: 'Grandma tomato',
category: 'Solanaceae',
);
final items = await repo.watchInventory().first;
expect(items.single.label, 'Grandma tomato');
expect(items.single.category, 'Solanaceae');
},
);
test(
'a quantity creates a Lot and a photo creates an encrypted-BLOB Attachment',
() async {
final id = await repo.addQuickVariety(
label: 'Maize',
quantity: const Quantity(kind: QuantityKind.cob),
photoBytes: Uint8List.fromList([1, 2, 3]),
);
final lot = await db.select(db.lots).getSingle();
expect(lot.varietyId, id);
expect(lot.quantityKind, 'cob');
final attachment = await db.select(db.attachments).getSingle();
expect(attachment.parentType, ParentType.variety);
expect(attachment.parentId, id);
expect(attachment.kind, AttachmentKind.photo);
expect(attachment.bytes, [1, 2, 3]);
},
);
test(
'stream is ordered by category then label and excludes soft-deleted rows',
() async {
await repo.addQuickVariety(label: 'Bean', category: 'Fabaceae');
await repo.addQuickVariety(label: 'Apple', category: 'Rosaceae');
await repo.addQuickVariety(label: 'Almond', category: 'Rosaceae');
final items = await repo.watchInventory().first;
expect(items.map((i) => i.label), ['Bean', 'Almond', 'Apple']);
},
);
test('writes stamp a monotonic HLC into updated_at', () async {
await repo.addQuickVariety(label: 'First');
await repo.addQuickVariety(label: 'Second');
final rows = await db.select(db.varieties).get();
final stamps = rows.map((r) => r.updatedAt).toList()..sort();
// Distinct, parseable, ordered HLC stamps.
expect(stamps.toSet().length, 2);
expect(() => stamps.map(Hlc.parse).toList(), returnsNormally);
});
}

View file

@ -0,0 +1,21 @@
import 'package:drift_dev/api/migrations_native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/db/database.dart';
import 'schema/schema.dart';
void main() {
late SchemaVerifier verifier;
setUpAll(() {
verifier = SchemaVerifier(GeneratedHelper());
});
test('freshly created database matches the exported schema v1', () async {
// Guards that `createAll` stays in sync with drift_schemas/drift_schema_v1.json.
final schema = await verifier.schemaAt(1);
final db = AppDatabase(schema.newConnection());
await verifier.migrateAndValidate(db, 1);
await db.close();
});
}

View file

@ -0,0 +1,80 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:tane/db/database.dart';
import 'package:tane/db/encrypted_executor.dart';
/// Security regression guard for "no plaintext at rest, ever" (CLAUDE.md).
///
/// Writes a Variety whose label is a unique sentinel, then reads the raw
/// database file bytes and asserts the sentinel does NOT appear proving
/// SQLCipher actually encrypted the data.
///
/// Requires a real SQLCipher library. On a host without it (no
/// `libsqlcipher.so`), the test is skipped with a clear reason; CI installs
/// SQLCipher so the guard runs there. It also runs on-device via integration
/// tests.
void main() {
test('sentinel label is absent from the raw encrypted DB file', () async {
const sentinel = 'GRANDMA_TOMATO_SENTINEL_9f3a1c';
const keyHex =
'00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff';
final dir = await Directory.systemTemp.createTemp('tane_enc_test');
final file = File(p.join(dir.path, 'inventory.sqlite'));
addTearDown(() => dir.delete(recursive: true));
final db = AppDatabase(openEncryptedExecutor(file, keyHex));
try {
await db
.into(db.varieties)
.insert(
VarietiesCompanion.insert(
id: 'sentinel-row',
label: sentinel,
createdAt: 0,
updatedAt: '0',
lastAuthor: 'test',
),
);
} on Object catch (e) {
// SQLCipher not available in this environment (e.g. dev host without
// libsqlcipher). Skip rather than pass silently.
markTestSkipped('SQLCipher unavailable, cannot verify encryption: $e');
await db.close();
return;
}
await db.close();
final bytes = await file.readAsBytes();
expect(
_containsAscii(bytes, sentinel),
isFalse,
reason: 'Label leaked as plaintext — SQLCipher encryption is not active.',
);
// Sanity: a real SQLCipher file does not start with the plain-SQLite header.
expect(
_containsAscii(bytes.sublist(0, 16), 'SQLite format 3'),
isFalse,
reason: 'File has a plaintext SQLite header — not encrypted.',
);
});
}
bool _containsAscii(Uint8List haystack, String needle) {
final n = needle.codeUnits;
if (n.isEmpty || haystack.length < n.length) return false;
for (var i = 0; i <= haystack.length - n.length; i++) {
var match = true;
for (var j = 0; j < n.length; j++) {
if (haystack[i + j] != n[j]) {
match = false;
break;
}
}
if (match) return true;
}
return false;
}

View file

@ -0,0 +1,21 @@
// dart format width=80
// GENERATED BY drift_dev, DO NOT MODIFY.
// ignore_for_file: type=lint,unused_import
//
import 'package:drift/drift.dart';
import 'package:drift/internal/migrations.dart';
import 'schema_v1.dart' as v1;
class GeneratedHelper implements SchemaInstantiationHelper {
@override
GeneratedDatabase databaseForVersion(QueryExecutor db, int version) {
switch (version) {
case 1:
return v1.DatabaseAtV1(db);
default:
throw MissingSchemaException(version, versions);
}
}
static const versions = const [1];
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,23 @@
import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import 'package:sqlite3/open.dart';
/// Host test setup: point package:sqlite3 at the system SQLite so in-memory
/// Drift databases (migration/widget tests) load on Linux CI/dev machines,
/// where only `libsqlite3.so.0` may be present. The encrypted executor
/// overrides its own isolate to SQLCipher separately, so this does not affect
/// the on-disk encryption tests.
Future<void> testExecutable(FutureOr<void> Function() testMain) async {
if (Platform.isLinux) {
open.overrideFor(OperatingSystem.linux, () {
try {
return DynamicLibrary.open('libsqlite3.so');
} on ArgumentError {
return DynamicLibrary.open('libsqlite3.so.0');
}
});
}
await testMain();
}

View file

@ -0,0 +1,30 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
/// Enforces the golden rule "user-facing strings are NEVER hardcoded". Scans
/// lib/ for `Text('literal')` / `Text("literal")` with an alphabetic literal
/// all UI text must come from slang (`t.`). Variables like `Text(item.label)`
/// and symbols like `Text('?')` are allowed.
void main() {
test('no hardcoded Text() string literals in lib/', () {
final textLiteral = RegExp('''Text\\(\\s*['"][A-Za-z]''');
final offenders = <String>[];
for (final entity in Directory('lib').listSync(recursive: true)) {
if (entity is! File || !entity.path.endsWith('.dart')) continue;
if (entity.path.contains('/i18n/') || entity.path.endsWith('.g.dart')) {
continue; // generated / translation sources
}
if (textLiteral.hasMatch(entity.readAsStringSync())) {
offenders.add(entity.path);
}
}
expect(
offenders,
isEmpty,
reason: 'Hardcoded Text() literals found (use t.…): $offenders',
);
});
}

View file

@ -0,0 +1,41 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/security/secret_store.dart';
import 'package:tane/security/secure_key_store.dart';
class InMemorySecretStore implements SecretStore {
final Map<String, String> _values = {};
int writeCount = 0;
@override
Future<String?> read(String key) async => _values[key];
@override
Future<void> write(String key, String value) async {
_values[key] = value;
writeCount++;
}
}
void main() {
group('SecureKeyStore', () {
test('creates a 256-bit (64 hex char) db key on first run', () async {
final keys = SecureKeyStore(store: InMemorySecretStore());
final key = await keys.databaseKeyHex();
expect(key, matches(RegExp(r'^[0-9a-f]{64}$')));
});
test('reuses the same db key across calls (created once)', () async {
final store = InMemorySecretStore();
final keys = SecureKeyStore(store: store);
final first = await keys.databaseKeyHex();
final second = await keys.databaseKeyHex();
expect(second, first);
expect(store.writeCount, 1);
});
test('db key and root seed are independent secrets', () async {
final keys = SecureKeyStore(store: InMemorySecretStore());
expect(await keys.databaseKeyHex(), isNot(await keys.rootSeedHex()));
});
});
}

View file

@ -0,0 +1,56 @@
import 'package:commons_core/commons_core.dart';
import 'package:drift/native.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/data/variety_repository.dart';
import 'package:tane/db/database.dart';
import 'package:tane/i18n/strings.g.dart';
import 'package:tane/state/inventory_cubit.dart';
/// A fresh in-memory database for host tests (unencrypted; encryption is
/// verified separately in the SQLCipher-only security test).
AppDatabase newTestDatabase() => AppDatabase(NativeDatabase.memory());
/// Unmounts the widget tree *inside* the test and drains the zero-duration
/// timer Drift schedules when its stream subscription is cancelled. Without
/// this, flutter_test reports "a Timer is still pending after disposal". Call
/// at the end of any widget test that mounts an [InventoryCubit].
Future<void> disposeTree(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump(const Duration(milliseconds: 10));
}
VarietyRepository newTestRepository(
AppDatabase db, {
String nodeId = 'test-node',
}) => VarietyRepository(db, idGen: IdGen(), nodeId: nodeId);
/// Wraps [child] with the providers a screen expects (repository, inventory
/// cubit) plus i18n and Material localizations, pinned to [locale].
Widget wrapScreen({
required VarietyRepository repository,
required Widget child,
AppLocale locale = AppLocale.en,
}) {
LocaleSettings.setLocaleSync(locale);
return TranslationProvider(
child: RepositoryProvider.value(
value: repository,
child: BlocProvider(
create: (_) => InventoryCubit(repository),
child: MaterialApp(
locale: locale.flutterLocale,
supportedLocales: AppLocaleUtils.supportedLocales,
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
home: child,
),
),
),
);
}

View file

@ -0,0 +1,78 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/db/database.dart';
import 'package:tane/i18n/strings.g.dart';
import 'package:tane/ui/inventory_list_screen.dart';
import '../support/test_support.dart';
void main() {
late AppDatabase db;
setUp(() => db = newTestDatabase());
tearDown(() => db.close());
testWidgets('shows the empty state when there are no seeds', (tester) async {
final repo = newTestRepository(db);
await tester.pumpWidget(
wrapScreen(repository: repo, child: const InventoryListScreen()),
);
await tester.pumpAndSettle();
expect(find.text('No seeds yet. Tap + to add your first.'), findsOneWidget);
await disposeTree(tester);
});
testWidgets(
'renders seeds from the repository grouped under their category',
(tester) async {
final repo = newTestRepository(db);
await repo.addQuickVariety(
label: 'Grandma tomato',
category: 'Solanaceae',
);
await tester.pumpWidget(
wrapScreen(repository: repo, child: const InventoryListScreen()),
);
await tester.pumpAndSettle();
expect(find.text('Grandma tomato'), findsOneWidget);
expect(find.text('Solanaceae'), findsOneWidget); // category header
await disposeTree(tester);
},
);
testWidgets('search filters the visible list', (tester) async {
final repo = newTestRepository(db);
await repo.addQuickVariety(label: 'Tomato');
await repo.addQuickVariety(label: 'Bean');
await tester.pumpWidget(
wrapScreen(repository: repo, child: const InventoryListScreen()),
);
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('inventory.search')), 'bea');
await tester.pumpAndSettle();
expect(find.text('Bean'), findsOneWidget);
expect(find.text('Tomato'), findsNothing);
await disposeTree(tester);
});
testWidgets('renders in Spanish when the locale is es', (tester) async {
final repo = newTestRepository(db);
await tester.pumpWidget(
wrapScreen(
repository: repo,
child: const InventoryListScreen(),
locale: AppLocale.es,
),
);
await tester.pumpAndSettle();
expect(find.text('Inventario'), findsOneWidget);
await disposeTree(tester);
});
}

View file

@ -0,0 +1,51 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/app.dart';
import 'package:tane/i18n/strings.g.dart';
import '../support/test_support.dart';
void main() {
testWidgets(
'quick-add: empty label errors; filling it saves and lists the seed',
(tester) async {
LocaleSettings.setLocaleSync(AppLocale.en);
final db = newTestDatabase();
addTearDown(db.close);
final repo = newTestRepository(db);
await tester.pumpWidget(
TranslationProvider(child: TaneApp(repository: repo)),
);
await tester.pumpAndSettle();
// Starts empty.
expect(
find.text('No seeds yet. Tap + to add your first.'),
findsOneWidget,
);
// Open the quick-add sheet.
await tester.tap(find.byKey(const Key('inventory.addFab')));
await tester.pumpAndSettle();
// Saving with an empty label surfaces the validation message.
await tester.tap(find.byKey(const Key('quickAdd.save')));
await tester.pumpAndSettle();
expect(find.text('Give it a name'), findsOneWidget);
// Enter a name and save.
await tester.enterText(
find.byKey(const Key('quickAdd.labelField')),
'Grandma tomato',
);
await tester.tap(find.byKey(const Key('quickAdd.save')));
await tester.pumpAndSettle();
// Sheet closed and the seed shows in the list.
expect(find.byKey(const Key('quickAdd.labelField')), findsNothing);
expect(find.text('Grandma tomato'), findsOneWidget);
await disposeTree(tester);
},
);
}