diff --git a/app/.gitignore b/app/.gitignore index 371e9bd8..ffe0bc2c 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -45,8 +45,9 @@ app.*.map.json /android/app/release # The repository ignores runtime data/ directories. Feature repository source -# and its tests are code, not runtime data, and must be included in fresh -# checkouts. +# and its mirroring tests are code, not runtime data, and must be included in +# fresh checkouts. The test negation is required too: without it every +# `test/**/data/` directory is silently dropped from the candidate. !/lib/**/data/ !/lib/**/data/** !/test/**/data/ diff --git a/app/lib/features/templates/data/template_repository.dart b/app/lib/features/templates/data/template_repository.dart new file mode 100644 index 00000000..da56f5ea --- /dev/null +++ b/app/lib/features/templates/data/template_repository.dart @@ -0,0 +1,84 @@ +import '../../../core/api_gateway.dart'; +import '../domain/template_entry.dart'; + +/// A templates protocol refusal kept separate from transport errors; server +/// error envelopes are propagated unchanged by [ApiGateway]. +class TemplateRepositoryException implements Exception { + const TemplateRepositoryException(this.message); + final String message; + @override + String toString() => message; +} + +/// Template catalogue, definition validation and create-only submission over +/// the application's shared gateway. +/// +/// These are reads plus one explicit submit. No method publishes, runs, +/// overwrites or schedules a pipeline, so merely loading or validating a +/// template can never start work. +class TemplateRepository { + TemplateRepository(this._gateway); + final ApiGateway _gateway; + + /// The server's template catalogue, exactly as `list_templates` returns it. + /// A reply without a `templates` field is the older server answering with no + /// catalogue, which is an empty list rather than an error. + Future> listTemplates() async { + final reply = await _gateway.call('list_templates'); + final templates = reply['templates']; + if (templates == null) return const []; + if (templates is! List) { + throw const TemplateRepositoryException( + 'The server returned no template catalogue.', + ); + } + return List.unmodifiable( + templates.map((entry) { + if (entry is! Map) { + throw const TemplateRepositoryException( + 'The server returned a template that is not an object.', + ); + } + return TemplateEntry.fromJson(Map.from(entry)); + }), + ); + } + + /// Parses one definition source on the server (`validate`) and returns the + /// graph it produced. The source is sent byte-for-byte: no trimming, casing or + /// whitespace changes. A malformed definition rejects with the server's own + /// error; a reply without a graph is refused rather than reported as valid. + Future validate(String source) async { + final reply = await _gateway.call('validate', {'source': source}); + final graph = reply['graph']; + if (graph is! Map) { + throw const TemplateRepositoryException('The server returned no graph.'); + } + return Map.from(graph); + } + + /// Creates a new draft pipeline from [source] (`submit`), create-only. + /// + /// A blank name is refused locally before anything is sent, matching the + /// browser and Android clients; the name that is sent is trimmed. The source + /// is not changed. `create_only` is always true, so an existing pipeline can + /// never be overwritten, and no run is started. + Future submit(String name, String source) async { + final trimmed = name.trim(); + if (trimmed.isEmpty) { + throw const TemplateRepositoryException('Enter a pipeline name.'); + } + final reply = await _gateway.call('submit', { + 'name': trimmed, + 'source': source, + 'create_only': true, + }); + final detail = reply['detail']; + if (detail is! Map) { + throw const TemplateRepositoryException( + 'The server returned no pipeline detail.', + ); + } + return Map.from(detail); + } +} diff --git a/app/lib/features/templates/domain/template_entry.dart b/app/lib/features/templates/domain/template_entry.dart new file mode 100644 index 00000000..6c86bcbf --- /dev/null +++ b/app/lib/features/templates/domain/template_entry.dart @@ -0,0 +1,63 @@ +import '../../../core/api_gateway.dart'; + +/// One template from the server catalogue. +/// +/// The server owns this record: [key], [name], [description], [source] and +/// [scheduled] are read from it verbatim and every other field is kept in +/// [raw], so a later view or round-trip never loses fields this client does not +/// understand yet. Loading a template is a read; it never publishes or runs it. +class TemplateEntry { + const TemplateEntry({ + required this.key, + required this.name, + required this.description, + required this.source, + required this.scheduled, + required this.raw, + }); + + factory TemplateEntry.fromJson(JsonMap json) { + final raw = _frozenMap(json); + return TemplateEntry( + key: _text(raw['key']), + name: _text(raw['name']), + description: _text(raw['description']), + source: _text(raw['source']), + scheduled: raw['scheduled'] == true, + raw: raw, + ); + } + + /// The stable catalogue key the gallery selects on. + final String key; + final String name; + final String description; + + /// The template's complete, untrimmed definition source. + final String source; + + /// Whether the source declares a schedule (the summary's "Includes a schedule"). + final bool scheduled; + + /// Every field the server sent, including fields this client does not model. + /// Deeply unmodifiable: nested maps and lists are copied into read-only + /// collections too, so a view cannot mutate the server reply through it. + final JsonMap raw; + + static String _text(dynamic value) => value == null ? '' : '$value'; + + static JsonMap _frozenMap(Map json) => + Map.unmodifiable( + json.map((key, value) => MapEntry(key, _frozen(value))), + ); + + static dynamic _frozen(dynamic value) { + if (value is Map) { + return _frozenMap(Map.from(value)); + } + if (value is List) { + return List.unmodifiable(value.map(_frozen)); + } + return value; + } +} diff --git a/app/notes/T1a.md b/app/notes/T1a.md new file mode 100644 index 00000000..e8a39fc4 --- /dev/null +++ b/app/notes/T1a.md @@ -0,0 +1,140 @@ +# T1a — template catalogue, validate and create-only submit + +## What changed + +New nonvisual `templates` data/domain slice. One shared file was edited: +`app/.gitignore` re-includes `test/**/data/`, because the repository's runtime +`data/` rule was silently excluding this slice's tests from the candidate. No +other lane's work, `lib/main.dart`, shell, pubspec, `web/`, server or Android +file was touched. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/templates/domain/template_entry.dart` | 63 | Immutable server template; models key/name/description/source/scheduled and keeps every unknown field in deeply read-only `raw` | +| `lib/features/templates/data/template_repository.dart` | 84 | `TemplateRepository(ApiGateway)`: list, validate, create-only submit | +| `test/features/templates/data/template_test_support.dart` | 47 | Recording/refusing fake gateways, server-refusal error, Unicode source fixture | +| `test/features/templates/data/template_list_test.dart` | 165 | Catalogue request shape, field preservation, deep immutability, missing/malformed catalogue | +| `test/features/templates/data/template_create_test.dart` | 147 | Validate/submit envelopes, blank-name gate, missing payloads, verbatim refusals | +| `app/.gitignore` | +4 | Re-includes `test/**/data/` so test files enter the candidate | + +Nothing under `lib/main.dart`, `lib/shell/`, another feature, `pubspec.*`, +`web/`, the Go server or `android/` was changed. No dependency was added. + +## Review findings addressed + +- **Tests could never land (blocking).** `test/features/templates/data/` was + excluded by the repository root rule `data/`; `app/.gitignore` only re-included + `lib/**/data/`. The same negation now covers `test/**/data/`, so these three + test files are untracked-but-visible to git and `git add -n` succeeds. Fixing + the rule (rather than `git add -f`) also protects later `test/**/data/` lanes + such as S1a. No test was moved, so `test/` still mirrors `lib/`. +- **`raw` was only shallowly immutable (advisory).** `TemplateEntry.fromJson` + now deep-copies nested maps/lists into read-only collections, and the listed + test proves nested mutation throws and that the copy does not alias the reply. +- **Malformed-catalogue branches were untested (advisory).** Added tests for a + non-list `templates` value and a non-object catalogue entry, both rejecting + with explicit messages. +- `_text` still stringifies a non-string protocol value with `'$value'`; the + protocol only sends strings, and this matches how the browser would render + such a value, so the behaviour was left unchanged and is documented here + rather than claimed as strict parity. + +## Wire behaviour (mirrors `web/src/repository.js`) + +- `listTemplates()` sends exactly `{"type":"list_templates"}` with no fields and + returns the `templates` catalogue. A reply with no `templates` field is the + older server's empty catalogue (`?? []` in the browser), not a fake template. + Each entry keeps `key`, `name`, `description`, `source`, `scheduled` and all + unknown fields in `TemplateEntry.raw`; the reply list/maps are never mutated. + `raw` is a deep unmodifiable copy: nested unknown maps and lists are copied + into read-only collections, so neither the view nor a later caller can mutate + the server reply through it. +- `listTemplates()` rejects a malformed envelope instead of fabricating + entries: a non-list `templates` throws + `"The server returned no template catalogue."` and a non-object entry throws + `"The server returned a template that is not an object."`. The real server + cannot produce either, but a protocol mistake must not look like an empty or + half-populated catalogue. +- `validate(source)` sends exactly `{"type":"validate","source":}` and + returns the reply's `graph`. A reply without a graph throws + `TemplateRepositoryException("The server returned no graph.")` — the browser's + exact words — rather than reporting a valid definition. +- `submit(name, source)` sends exactly + `{"type":"submit","name":,"source":,"create_only":true}`. + A blank/whitespace-only name is refused locally with + `TemplateRepositoryException("Enter a pipeline name.")` and no gateway call is + made; the accepted name is trimmed. A reply without `detail` throws + `TemplateRepositoryException("The server returned no pipeline detail.")`. +- The source string is never trimmed, normalised or re-encoded: Unicode, tabs, + newlines and significant leading/trailing whitespace arrive unchanged. +- A server refusal is never caught or reworded by the repository. It reaches the + caller as the same gateway error object, so the server's own text is shown. +- The repository exposes only these three operations. It has no publish, run, + schedule or overwrite path, so loading or validating a template cannot start + work or mutate a retained pipeline. + +## Checks actually run + +``` +flutter pub get # Got dependencies +dart format lib/features/templates test/features/templates # clean +flutter analyze # No issues found! (0.9s) +flutter test test/features/templates # 13 passed +flutter test # 76 passed +flutter build web # ✓ Built build/web (15.5s) +git diff --check # clean +git check-ignore / git add -n # tests are no longer ignored +``` + +Tests are part of the candidate, not merely present on disk: + +``` +$ git add -n app/test/features/templates/data/template_list_test.dart \ + app/test/features/templates/data/template_create_test.dart \ + app/test/features/templates/data/template_test_support.dart +add 'app/test/features/templates/data/template_create_test.dart' +add 'app/test/features/templates/data/template_list_test.dart' +add 'app/test/features/templates/data/template_test_support.dart' +exit=0 + +$ git status --porcelain=v1 -uall + M app/.gitignore +?? app/lib/features/templates/data/template_repository.dart +?? app/lib/features/templates/domain/template_entry.dart +?? app/notes/T1a.md +?? app/test/features/templates/data/template_create_test.dart +?? app/test/features/templates/data/template_list_test.dart +?? app/test/features/templates/data/template_test_support.dart +``` + +Focused acceptance coverage: + +- exact `list_templates` request (no fields, one call) and preservation of + modelled plus unknown fields, including nested unknown data; +- listing does not mutate the reply's template list or entry maps; `raw` and + every nested map/list are read-only, and the copy does not alias the reply; +- missing catalogue -> empty list; malformed catalogue -> explicit refusal; +- blank/whitespace name -> refusal with zero gateway calls; +- Unicode/emoji, tab/newline and leading/trailing source whitespace preserved in + both `validate` and `submit`; submit sends only name, source and + `create_only: true`, with the name trimmed; +- missing `graph` and missing `detail` rejected with the browser's exact + messages, with no fabricated graph/detail; +- validate and submit server refusals surface as the identical error object, + not a wrapper. + +## Honest limits + +- **Not wired into a screen.** This branch has no templates screen and the task + owns data/domain only; the manager owns integration. No browser capture was + made because there is no rendered change in this slice. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + The code is plain Dart with no platform-specific code. +- No live server, template catalogue, validate call or submit/creation was + performed. All tests use local fake gateways with no socket, so no real + pipeline was created or run. +- No export-gate workaround, server change or service operation was made; the + pending export-cap fix remains another lane's scope. +- **Not committed.** The stage instruction says not to commit, push or deploy, + so the candidate above is uncommitted in the working tree even though the run + prompt asks to commit a reviewed candidate. Nothing was pushed or deployed. diff --git a/app/test/features/templates/data/template_create_test.dart b/app/test/features/templates/data/template_create_test.dart new file mode 100644 index 00000000..68b82c4b --- /dev/null +++ b/app/test/features/templates/data/template_create_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'validate sends the exact source and returns the server graph', + () async { + final graph = { + 'stages': [ + {'key': 'build', 'type': 'model'}, + ], + 'unknown_graph_field': true, + }; + final gateway = RecordingGateway([ + {'type': 'validated', 'graph': graph}, + ]); + + final result = await TemplateRepository(gateway).validate(source); + + expect(gateway.calls.single.type, 'validate'); + expect(gateway.calls.single.fields, {'source': source}); + expect(gateway.calls.single.fields['source'], source); + expect(result, graph); + }, + ); + + test( + 'validate rejects a reply without a graph instead of faking success', + () async { + for (final reply in [ + {'type': 'validated'}, + {'type': 'validated', 'graph': null}, + ]) { + final gateway = RecordingGateway([reply]); + + await expectLater( + TemplateRepository(gateway).validate(source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no graph.', + ), + ), + ); + } + }, + ); + + test('validate propagates a server refusal verbatim', () async { + const refusal = ServerRefusal('invalid stage "añadir": unknown key'); + final gateway = RefusingGateway(refusal); + + await expectLater( + TemplateRepository(gateway).validate(source), + throwsA(same(refusal)), + ); + expect(gateway.calls, ['validate']); + }); + + test('submit refuses a blank name without sending anything', () async { + for (final name in ['', ' ', '\t\n']) { + final gateway = RecordingGateway([ + { + 'detail': {'id': 1}, + }, + ]); + + await expectLater( + TemplateRepository(gateway).submit(name, source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Enter a pipeline name.', + ), + ), + ); + expect(gateway.calls, isEmpty); + } + }); + + test( + 'submit trims the name, preserves the source and is always create-only', + () async { + final detail = { + 'id': 9, + 'name': 'Release 2', + 'version': 1, + }; + final gateway = RecordingGateway([ + {'type': 'submitted', 'detail': detail}, + ]); + + final result = await TemplateRepository( + gateway, + ).submit(' Release 2 ', source); + + expect(gateway.calls.single.type, 'submit'); + expect(gateway.calls.single.fields, { + 'name': 'Release 2', + 'source': source, + 'create_only': true, + }); + expect(gateway.calls.single.fields.keys, [ + 'name', + 'source', + 'create_only', + ]); + expect(result, detail); + }, + ); + + test( + 'submit rejects a reply without a detail instead of faking success', + () async { + final gateway = RecordingGateway([ + {'type': 'submitted'}, + ]); + + await expectLater( + TemplateRepository(gateway).submit('Release', source), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no pipeline detail.', + ), + ), + ); + }, + ); + + test('submit propagates a server refusal verbatim', () async { + const refusal = ServerRefusal('a pipeline named "Release" already exists'); + final gateway = RefusingGateway(refusal); + + await expectLater( + TemplateRepository(gateway).submit(' Release ', source), + throwsA(same(refusal)), + ); + expect(gateway.calls, ['submit']); + }); +} diff --git a/app/test/features/templates/data/template_list_test.dart b/app/test/features/templates/data/template_list_test.dart new file mode 100644 index 00000000..63cd2e93 --- /dev/null +++ b/app/test/features/templates/data/template_list_test.dart @@ -0,0 +1,165 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/templates/data/template_repository.dart'; + +import 'template_test_support.dart'; + +void main() { + test( + 'list_templates sends only the type and preserves every field', + () async { + final catalogue = [ + { + 'key': 'release', + 'name': 'Release', + 'description': 'Ship a version', + 'source': source, + 'scheduled': true, + 'future_field': { + 'nested': [1, 2, 3], + }, + }, + { + 'key': 'blank', + 'name': '', + 'description': '', + 'source': 'name: empty', + 'scheduled': false, + }, + ]; + final gateway = RecordingGateway([ + {'templates': catalogue}, + ]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(gateway.calls, hasLength(1)); + expect(gateway.calls.single.type, 'list_templates'); + expect(gateway.calls.single.fields, isEmpty); + expect(entries, hasLength(2)); + expect(entries.first.key, 'release'); + expect(entries.first.name, 'Release'); + expect(entries.first.description, 'Ship a version'); + expect(entries.first.source, source); + expect(entries.first.scheduled, isTrue); + expect(entries.first.raw['future_field'], { + 'nested': [1, 2, 3], + }); + expect(entries.last.key, 'blank'); + expect(entries.last.scheduled, isFalse); + expect(entries.last.raw, isNot(contains('missing'))); + }, + ); + + test('list_templates leaves the server reply untouched', () async { + final first = { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'unknown': ['keep', 'me'], + }; + final reply = { + 'templates': [first], + 'usage': {'templates': 1}, + }; + final gateway = RecordingGateway([reply]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(reply['templates'], hasLength(1)); + expect(first, { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'unknown': ['keep', 'me'], + }); + expect(entries.single.raw['unknown'], ['keep', 'me']); + expect( + () => entries.single.raw['name'] = 'changed', + throwsUnsupportedError, + ); + expect(first['name'], 'One'); + }); + + test('list_templates freezes nested unknown data in raw', () async { + final nested = { + 'nested': [1, 2, 3], + }; + final gateway = RecordingGateway([ + { + 'templates': [ + { + 'key': 'one', + 'name': 'One', + 'source': source, + 'scheduled': true, + 'future_field': nested, + }, + ], + }, + ]); + + final entries = await TemplateRepository(gateway).listTemplates(); + final raw = entries.single.raw; + final future = raw['future_field'] as Map; + + expect(() => future['added'] = true, throwsUnsupportedError); + expect(() => (future['nested'] as List).add(4), throwsUnsupportedError); + expect(future['nested'], [1, 2, 3]); + // The unmodifiable copies do not alias the server reply either. + nested['added'] = true; + expect(raw['future_field'], isNot(contains('added'))); + }); + + test('list_templates rejects a catalogue that is not a list', () async { + final gateway = RecordingGateway([ + { + 'templates': {'key': 'not-a-list'}, + }, + ]); + + await expectLater( + TemplateRepository(gateway).listTemplates(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no template catalogue.', + ), + ), + ); + }); + + test( + 'list_templates rejects a catalogue entry that is not an object', + () async { + final gateway = RecordingGateway([ + { + 'templates': ['not-an-entry'], + }, + ]); + + await expectLater( + TemplateRepository(gateway).listTemplates(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned a template that is not an object.', + ), + ), + ); + }, + ); + + test('list_templates treats a reply with no catalogue as empty', () async { + final gateway = RecordingGateway([{}]); + + final entries = await TemplateRepository(gateway).listTemplates(); + + expect(entries, isEmpty); + expect(gateway.calls.single.type, 'list_templates'); + }); +} diff --git a/app/test/features/templates/data/template_test_support.dart b/app/test/features/templates/data/template_test_support.dart new file mode 100644 index 00000000..f4f36500 --- /dev/null +++ b/app/test/features/templates/data/template_test_support.dart @@ -0,0 +1,47 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A recording gateway: it captures every request and answers from [replies]. +class RecordingGateway implements ApiGateway { + RecordingGateway([List replies = const []]) + : _replies = [...replies]; + + final List _replies; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: Map.from(fields))); + return _replies.removeAt(0); + } + + @override + Stream get frames => const Stream.empty(); +} + +/// A gateway that refuses every request with the same server error object. +class RefusingGateway implements ApiGateway { + RefusingGateway(this.refusal); + + final Object refusal; + final List calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(type); + throw refusal; + } + + @override + Stream get frames => const Stream.empty(); +} + +class ServerRefusal implements Exception { + const ServerRefusal(this.message); + final String message; + @override + String toString() => message; +} + +/// A source with Unicode, tabs, newlines and significant leading/trailing +/// whitespace: every request must carry it unchanged. +const source = ' name: "café"\n\tstages:\n - key: "añadir" 😀 \n';