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

7
packages/commons_core/.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/
# Avoid committing pubspec.lock for library packages; see
# https://dart.dev/guides/libraries/private-files#pubspeclock.
pubspec.lock

View file

@ -0,0 +1,3 @@
## 1.0.0
- Initial version.

View file

@ -0,0 +1,39 @@
<!--
This README describes the package. If you publish this package to pub.dev,
this README's contents appear on the landing page for your package.
For information about how to write a good package README, see the guide for
[writing package pages](https://dart.dev/tools/pub/writing-package-pages).
For general information about developing packages, see the Dart guide for
[creating packages](https://dart.dev/guides/libraries/create-packages)
and the Flutter guide for
[developing packages and plugins](https://flutter.dev/to/develop-packages).
-->
TODO: Put a short description of the package here that helps potential users
know whether this package might be useful for them.
## Features
TODO: List what your package can do. Maybe include images, gifs, or videos.
## Getting started
TODO: List prerequisites and provide or point to information on how to
start using the package.
## Usage
TODO: Include short and useful examples for package users. Add longer examples
to `/example` folder.
```dart
const like = 'sample';
```
## Additional information
TODO: Tell users more about the package: where to find more information, how to
contribute to the package, how to file issues, what response they can expect
from the package authors, and more.

View file

@ -0,0 +1,30 @@
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.
include: package:lints/recommended.yaml
# Uncomment the following section to specify additional rules.
# linter:
# rules:
# - camel_case_types
# analyzer:
# exclude:
# - path/to/excluded/files/**
# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints
# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options

View file

@ -0,0 +1,11 @@
/// Generic local-first commons engine primitives.
///
/// Pure Dart, Flutter-free. Holds only what is surely shared across apps built
/// on the engine (ids, clocks, value types, identity). No seed-specific code.
library;
export 'src/clock/hlc.dart';
export 'src/crypto/random_bytes.dart';
export 'src/identity/identity_service.dart';
export 'src/ids/id_gen.dart';
export 'src/value/quantity.dart';

View file

@ -0,0 +1,100 @@
import 'package:equatable/equatable.dart';
/// A Hybrid Logical Clock timestamp (Kulkarni et al.).
///
/// Combines a physical wall-clock component ([millis]) with a monotonic
/// [counter] and a [nodeId] tiebreaker. It is the `updated_at` stamp on every
/// mutable row and drives last-writer-wins merges across devices, staying
/// monotonic even when the wall clock jumps backwards.
///
/// [pack] produces a fixed-width, lexicographically-sortable string so it can
/// be stored in a `TEXT` column and ordered with a plain SQL `ORDER BY`.
class Hlc extends Equatable implements Comparable<Hlc> {
const Hlc({
required this.millis,
required this.counter,
required this.nodeId,
});
/// The initial clock for [nodeId], before any event.
const Hlc.zero(String nodeId) : this(millis: 0, counter: 0, nodeId: nodeId);
/// Physical time in milliseconds since the Unix epoch.
final int millis;
/// Logical counter, bumped when two events share the same [millis].
final int counter;
/// Stable identifier of the node/device that issued this stamp.
final String nodeId;
static const _millisDigits = 15; // good until year ~5138
static const _counterDigits = 5; // 99999 events within one millisecond
/// Issues the next local timestamp given the current wall clock [wallMillis].
///
/// Monotonic: if the wall clock is behind our last stamp, we keep our
/// [millis] and bump the [counter] instead of moving time backwards.
Hlc localEvent(int wallMillis) {
final newMillis = millis > wallMillis ? millis : wallMillis;
final newCounter = newMillis == millis ? counter + 1 : 0;
return Hlc(millis: newMillis, counter: newCounter, nodeId: nodeId);
}
/// Merges an incoming [remote] stamp with the current wall clock, producing
/// the next local timestamp (used when receiving a peer's write).
Hlc receiveEvent(Hlc remote, int wallMillis) {
final newMillis = [
millis,
remote.millis,
wallMillis,
].reduce((a, b) => a > b ? a : b);
final int newCounter;
if (newMillis == millis && newMillis == remote.millis) {
newCounter = (counter > remote.counter ? counter : remote.counter) + 1;
} else if (newMillis == millis) {
newCounter = counter + 1;
} else if (newMillis == remote.millis) {
newCounter = remote.counter + 1;
} else {
newCounter = 0;
}
return Hlc(millis: newMillis, counter: newCounter, nodeId: nodeId);
}
/// A fixed-width, lexicographically-sortable encoding: `millis:counter:node`.
String pack() {
final m = millis.toString().padLeft(_millisDigits, '0');
final c = counter.toString().padLeft(_counterDigits, '0');
return '$m:$c:$nodeId';
}
/// Parses a string produced by [pack].
factory Hlc.parse(String packed) {
final parts = packed.split(':');
if (parts.length < 3) {
throw FormatException('Not a packed HLC: "$packed"');
}
return Hlc(
millis: int.parse(parts[0]),
counter: int.parse(parts[1]),
// nodeId may itself contain ':', so re-join the remainder.
nodeId: parts.sublist(2).join(':'),
);
}
@override
int compareTo(Hlc other) {
final byMillis = millis.compareTo(other.millis);
if (byMillis != 0) return byMillis;
final byCounter = counter.compareTo(other.counter);
if (byCounter != 0) return byCounter;
return nodeId.compareTo(other.nodeId);
}
@override
String toString() => pack();
@override
List<Object?> get props => [millis, counter, nodeId];
}

View file

@ -0,0 +1,18 @@
import 'dart:math';
import 'dart:typed_data';
/// Returns [length] cryptographically-random bytes.
///
/// Defaults to [Random.secure]. A seeded [Random] may be injected in tests for
/// reproducibility never do that in production code, as it is not secure.
Uint8List randomBytes(int length, {Random? random}) {
if (length < 0) {
throw ArgumentError.value(length, 'length', 'must be non-negative');
}
final rng = random ?? Random.secure();
final out = Uint8List(length);
for (var i = 0; i < length; i++) {
out[i] = rng.nextInt(256);
}
return out;
}

View file

@ -0,0 +1,24 @@
import 'dart:math';
import 'dart:typed_data';
import '../crypto/random_bytes.dart';
/// Creates the user's root identity secret.
///
/// One identity == one Duniter/Ğ1-style root seed. From it the app will later
/// *derive* a secp256k1 subkey for Nostr transport and expose a printable
/// recovery QR. This service only produces the seed bytes; derivation and
/// backup are separate, later stories (see docs/design/backup-and-recovery.md).
class IdentityService {
IdentityService({Random? random}) : _random = random;
/// Injected only in tests (seeded, reproducible). Production uses a CSPRNG.
final Random? _random;
/// Length of the root seed in bytes (256-bit).
static const int rootSeedLengthBytes = 32;
/// Generates a fresh root seed the ONE secret the user backs up.
Uint8List generateRootSeed() =>
randomBytes(rootSeedLengthBytes, random: _random);
}

View file

@ -0,0 +1,16 @@
import 'package:uuid/uuid.dart';
/// Generates client-side, time-sortable row identifiers (UUIDv7).
///
/// Every mutable row in the model is keyed by a client-generated UUIDv7
/// never an auto-increment (which would collide across peers). UUIDv7 embeds a
/// millisecond timestamp in its most-significant bits, so lexical order
/// approximates creation order, which suits CRDT sync and time-ordered queries.
class IdGen {
IdGen({Uuid? uuid}) : _uuid = uuid ?? const Uuid();
final Uuid _uuid;
/// A fresh UUIDv7 string, e.g. `018f1a2b-...-7...-...`.
String newId() => _uuid.v7();
}

View file

@ -0,0 +1,67 @@
import 'package:equatable/equatable.dart';
/// Coarse groups used by the UI to suggest relevant [QuantityKind]s for a
/// species/family. Purely presentational never forces a choice.
enum QuantityGroup { informal, plantForm, precise }
/// A stable, extensible, i18n vocabulary for *rough, human* seed amounts.
///
/// Values go deliberately beyond kitchen measures: seeds are counted in the
/// forms the plant gives them (a cob, a pod, a flower head). The display label
/// is localized from [name] so the enum name is the stable storage key and
/// must never be renumbered or reused (see data-model §5 migration rules).
enum QuantityKind {
// Informal / generic
aFew(QuantityGroup.informal),
some(QuantityGroup.informal),
plenty(QuantityGroup.informal),
handful(QuantityGroup.informal),
pinch(QuantityGroup.informal),
jar(QuantityGroup.informal),
packet(QuantityGroup.informal),
// Plant-form natural units
cob(QuantityGroup.plantForm),
head(QuantityGroup.plantForm),
pod(QuantityGroup.plantForm),
ear(QuantityGroup.plantForm),
fruit(QuantityGroup.plantForm),
bulb(QuantityGroup.plantForm),
tuber(QuantityGroup.plantForm),
seedHead(QuantityGroup.plantForm),
bunch(QuantityGroup.plantForm),
// Precise
grams(QuantityGroup.precise),
count(QuantityGroup.precise);
const QuantityKind(this.group);
final QuantityGroup group;
}
/// A quantity held or moved: a qualitative [kind], plus an optional [precise]
/// amount (grams / seed count) and an optional free-text [label] for rough
/// amounts no [kind] captures. Shared value type used by both Lot and Movement.
class Quantity extends Equatable {
const Quantity({required this.kind, this.precise, this.label});
final QuantityKind kind;
/// Optional precise amount, meaningful for [QuantityGroup.precise] kinds.
final double? precise;
/// Optional free text ("half a jam jar") when no [kind] fits well.
final String? label;
bool get isPrecise => precise != null;
Quantity copyWith({QuantityKind? kind, double? precise, String? label}) {
return Quantity(
kind: kind ?? this.kind,
precise: precise ?? this.precise,
label: label ?? this.label,
);
}
@override
List<Object?> get props => [kind, precise, label];
}

View file

@ -0,0 +1,21 @@
name: commons_core
description: >-
Generic local-first commons engine primitives (identity, clocks, value types).
Pure Dart, Flutter-free. No seed-specific code. See
../../docs/design/core-domain-boundary.md.
version: 0.1.0
publish_to: none
environment:
sdk: ^3.11.5
resolution: workspace
dependencies:
uuid: ^4.5.0
equatable: ^2.0.5
meta: ^1.15.0
dev_dependencies:
lints: ^6.0.0
test: ^1.25.6

View file

@ -0,0 +1,91 @@
import 'package:commons_core/commons_core.dart';
import 'package:test/test.dart';
void main() {
group('Hlc', () {
test('round-trips through pack/parse', () {
const h = Hlc(millis: 1720000000000, counter: 7, nodeId: 'node-a');
expect(Hlc.parse(h.pack()), h);
});
test('parse tolerates a nodeId containing colons', () {
const h = Hlc(millis: 42, counter: 1, nodeId: 'a:b:c');
expect(Hlc.parse(h.pack()), h);
});
test('packed form sorts lexically in timestamp order', () {
const older = Hlc(millis: 100, counter: 9, nodeId: 'z');
const newer = Hlc(millis: 200, counter: 0, nodeId: 'a');
expect(older.pack().compareTo(newer.pack()), lessThan(0));
});
test('packed counter breaks ties within the same millisecond', () {
const a = Hlc(millis: 100, counter: 1, nodeId: 'n');
const b = Hlc(millis: 100, counter: 2, nodeId: 'n');
expect(a.pack().compareTo(b.pack()), lessThan(0));
});
group('localEvent', () {
test(
'advances millis and resets counter when wall clock moves forward',
() {
const clock = Hlc(millis: 100, counter: 4, nodeId: 'n');
final next = clock.localEvent(200);
expect(next.millis, 200);
expect(next.counter, 0);
},
);
test('bumps counter when wall clock is unchanged', () {
const clock = Hlc(millis: 100, counter: 4, nodeId: 'n');
final next = clock.localEvent(100);
expect(next.millis, 100);
expect(next.counter, 5);
});
test('stays monotonic when the wall clock runs backwards', () {
const clock = Hlc(millis: 100, counter: 4, nodeId: 'n');
final next = clock.localEvent(50); // clock skew
expect(next.millis, 100);
expect(next.counter, 5);
expect(next.compareTo(clock), greaterThan(0));
});
});
group('receiveEvent', () {
test('takes the max millis and bumps beyond both counters on a tie', () {
const local = Hlc(millis: 100, counter: 2, nodeId: 'local');
const remote = Hlc(millis: 100, counter: 5, nodeId: 'remote');
final merged = local.receiveEvent(remote, 100);
expect(merged.millis, 100);
expect(merged.counter, 6);
expect(merged.nodeId, 'local'); // identity stays local
});
test('adopts a remote future timestamp and continues its counter', () {
const local = Hlc(millis: 100, counter: 2, nodeId: 'local');
const remote = Hlc(millis: 300, counter: 1, nodeId: 'remote');
final merged = local.receiveEvent(remote, 120);
expect(merged.millis, 300);
expect(merged.counter, 2);
});
test('resets counter when the wall clock leads everything', () {
const local = Hlc(millis: 100, counter: 2, nodeId: 'local');
const remote = Hlc(millis: 150, counter: 9, nodeId: 'remote');
final merged = local.receiveEvent(remote, 400);
expect(merged.millis, 400);
expect(merged.counter, 0);
});
});
test('compareTo orders by millis, then counter, then nodeId', () {
const a = Hlc(millis: 1, counter: 0, nodeId: 'a');
const b = Hlc(millis: 1, counter: 0, nodeId: 'b');
const c = Hlc(millis: 1, counter: 1, nodeId: 'a');
const d = Hlc(millis: 2, counter: 0, nodeId: 'a');
final sorted = [d, c, b, a]..sort();
expect(sorted, [a, b, c, d]);
});
});
}

View file

@ -0,0 +1,37 @@
import 'dart:math';
import 'package:commons_core/commons_core.dart';
import 'package:test/test.dart';
void main() {
group('IdentityService', () {
test('generates a 32-byte root seed', () {
final seed = IdentityService().generateRootSeed();
expect(seed.length, IdentityService.rootSeedLengthBytes);
expect(seed.length, 32);
});
test('two seeds from a secure RNG differ', () {
final service = IdentityService();
expect(service.generateRootSeed(), isNot(service.generateRootSeed()));
});
test('is reproducible with an injected seeded RNG (test-only)', () {
// `equals` does element-wise comparison on the byte lists.
final s1 = IdentityService(random: Random(1)).generateRootSeed();
final s2 = IdentityService(random: Random(1)).generateRootSeed();
expect(s1, equals(s2));
});
});
group('randomBytes', () {
test('returns the requested length', () {
expect(randomBytes(16).length, 16);
expect(randomBytes(0).length, 0);
});
test('rejects negative lengths', () {
expect(() => randomBytes(-1), throwsArgumentError);
});
});
}

View file

@ -0,0 +1,35 @@
import 'package:commons_core/commons_core.dart';
import 'package:test/test.dart';
void main() {
group('IdGen', () {
final idGen = IdGen();
test('produces well-formed UUIDv7 strings', () {
final id = idGen.newId();
// 8-4-4-4-12 hex groups.
expect(
id,
matches(
RegExp(
r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
),
),
);
// Version nibble is 7.
expect(id.split('-')[2][0], '7');
});
test('never collides across many calls', () {
final ids = List.generate(5000, (_) => idGen.newId());
expect(ids.toSet().length, ids.length);
});
test('is time-sortable: later ids sort after earlier ones', () async {
final earlier = idGen.newId();
await Future<void>.delayed(const Duration(milliseconds: 3));
final later = idGen.newId();
expect(earlier.compareTo(later), lessThan(0));
});
});
}

View file

@ -0,0 +1,47 @@
import 'package:commons_core/commons_core.dart';
import 'package:test/test.dart';
void main() {
group('Quantity', () {
test('value equality ignores object identity', () {
const a = Quantity(kind: QuantityKind.pod, precise: 12, label: 'a bag');
const b = Quantity(kind: QuantityKind.pod, precise: 12, label: 'a bag');
expect(a, b);
expect(a.hashCode, b.hashCode);
});
test('isPrecise reflects the presence of a precise amount', () {
expect(
const Quantity(kind: QuantityKind.grams, precise: 5).isPrecise,
isTrue,
);
expect(const Quantity(kind: QuantityKind.aFew).isPrecise, isFalse);
});
test('copyWith overrides only the given fields', () {
const q = Quantity(kind: QuantityKind.cob, precise: 2);
final q2 = q.copyWith(kind: QuantityKind.ear);
expect(q2.kind, QuantityKind.ear);
expect(q2.precise, 2);
});
});
group('QuantityKind', () {
test('enum names are stable storage keys', () {
// Guards against accidental renames these strings live in the DB.
expect(QuantityKind.pod.name, 'pod');
expect(QuantityKind.cob.name, 'cob');
expect(QuantityKind.head.name, 'head');
expect(QuantityKind.packet.name, 'packet');
expect(QuantityKind.handful.name, 'handful');
expect(QuantityKind.grams.name, 'grams');
expect(QuantityKind.count.name, 'count');
});
test('every kind belongs to a group', () {
for (final kind in QuantityKind.values) {
expect(QuantityGroup.values, contains(kind.group));
}
});
});
}