adopt-export 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ """Export bundle writer and reader — contracts §11, implementation spec §4.10.
2
+
3
+ The portability promise in executable form: *export → import → export produces
4
+ byte-identical table files*, and every identity in the second export resolves by
5
+ URI alone with no ULID lookup. That property is gate **G0** and Build 0's
6
+ definition of done, condition 2.
7
+
8
+ Invariants this package holds:
9
+
10
+ * **No network.** Nothing here opens a socket.
11
+ * **Writes confined to the target directory.** The writer creates the bundle and
12
+ nothing else; the reader writes only through the `ImportRecords` port.
13
+ * **Runtime-annex tables are excluded by construction**, not by a filter: they
14
+ are not in the canonical manifest, and the manifest is what the writer
15
+ iterates (contracts §12).
16
+ * **No dialect.** This package declares its own storage ports and imports no
17
+ store, so `no-raw-sqlite` holds and a Postgres realization changes nothing
18
+ here.
19
+ """
20
+
21
+ from adopt_export.bundle import (
22
+ BLOBS_DIRNAME,
23
+ MANIFEST_FILENAME,
24
+ SCHEMA_FILENAME,
25
+ TABLE_SUFFIX,
26
+ TABLES_DIRNAME,
27
+ BlobSummary,
28
+ BundleManifest,
29
+ BundleScope,
30
+ TableEntry,
31
+ canonical_json,
32
+ row_object,
33
+ sha256_of_bytes,
34
+ table_relative_path,
35
+ )
36
+ from adopt_export.ports import ExportRecords, ImportRecords
37
+ from adopt_export.reader import apply_bundle, read_bundle
38
+ from adopt_export.roundtrip import table_files, verify_roundtrip
39
+ from adopt_export.writer import write_bundle
40
+
41
+ __all__ = [
42
+ "BLOBS_DIRNAME",
43
+ "MANIFEST_FILENAME",
44
+ "SCHEMA_FILENAME",
45
+ "TABLES_DIRNAME",
46
+ "TABLE_SUFFIX",
47
+ "BlobSummary",
48
+ "BundleManifest",
49
+ "BundleScope",
50
+ "ExportRecords",
51
+ "ImportRecords",
52
+ "TableEntry",
53
+ "apply_bundle",
54
+ "canonical_json",
55
+ "read_bundle",
56
+ "row_object",
57
+ "sha256_of_bytes",
58
+ "table_files",
59
+ "table_relative_path",
60
+ "verify_roundtrip",
61
+ "write_bundle",
62
+ ]
adopt_export/bundle.py ADDED
@@ -0,0 +1,150 @@
1
+ """The bundle layout, its manifest shape, and the canonical rendering rules.
2
+
3
+ Contracts §11. Everything here exists to make one sentence true --
4
+ *export → import → export produces byte-identical table files* -- and that
5
+ sentence is only true if every rendering decision is made in exactly one place.
6
+
7
+ **One JSON rule, at every nesting level:** no ASCII escaping, no spaces, keys
8
+ sorted. Sorting applies to the row object and to anything nested inside a `json`
9
+ column alike, because a rule with an exception is a rule someone applies to the
10
+ outer object and forgets on the inner one -- and the inner one is
11
+ `permitted_outbound_categories`, the only `json` column schema version 3 has.
12
+
13
+ **Timestamps are rendered here, not by pydantic.** `model_dump(mode="json")`
14
+ would emit whatever the library's default happens to be; contracts §1.2 requires
15
+ millisecond precision with a `Z` suffix, and a bundle written before a pydantic
16
+ upgrade must equal one written after it.
17
+
18
+ **There is no `blobs/` directory at schema version 3.** No exportable table
19
+ declares a blob reference -- the only one in the pack is `agent_run.output_ref`,
20
+ which lives in the runtime annex (§12) and is never exported. The manifest still
21
+ carries the `blobs` block, reporting zero, which is what §11's *"present only
22
+ when referenced"* means for this version. Inventing a collection mechanism for a
23
+ source that does not exist would be inventing its bugs too.
24
+ """
25
+
26
+ import datetime as _dt
27
+ import hashlib
28
+ import json as _json
29
+ from pathlib import Path
30
+ from typing import Any, Final
31
+
32
+ from pydantic import BaseModel, ConfigDict
33
+
34
+ from adopt_obs import format_timestamp
35
+
36
+ __all__ = [
37
+ "BLOBS_DIRNAME",
38
+ "MANIFEST_FILENAME",
39
+ "SCHEMA_FILENAME",
40
+ "TABLES_DIRNAME",
41
+ "TABLE_SUFFIX",
42
+ "BlobSummary",
43
+ "BundleManifest",
44
+ "BundleScope",
45
+ "TableEntry",
46
+ "canonical_json",
47
+ "read_text",
48
+ "row_object",
49
+ "sha256_of_bytes",
50
+ "table_relative_path",
51
+ ]
52
+
53
+ MANIFEST_FILENAME: Final[str] = "manifest.json"
54
+ SCHEMA_FILENAME: Final[str] = "export.schema.json"
55
+ TABLES_DIRNAME: Final[str] = "tables"
56
+ BLOBS_DIRNAME: Final[str] = "blobs"
57
+ TABLE_SUFFIX: Final[str] = ".ndjson"
58
+
59
+ #: NDJSON is line-delimited by definition, and the delimiter is pinned to `\n`
60
+ #: so a Windows checkout and a Linux runner produce the same bytes -- the same
61
+ #: reason `adopt_schema.generate` opens its targets with `newline="\n"`.
62
+ LINE_SEPARATOR: Final[str] = "\n"
63
+ ENCODING: Final[str] = "utf-8"
64
+
65
+
66
+ def canonical_json(value: object) -> str:
67
+ """The one rendering. Sorted keys, no spaces, no ASCII escaping."""
68
+ return _json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
69
+
70
+
71
+ def sha256_of_bytes(payload: bytes) -> str:
72
+ return hashlib.sha256(payload).hexdigest()
73
+
74
+
75
+ def table_relative_path(table: str) -> str:
76
+ """`tables/<table>.ndjson`, as it appears in the manifest and on disk."""
77
+ return f"{TABLES_DIRNAME}/{table}{TABLE_SUFFIX}"
78
+
79
+
80
+ def row_object(model: BaseModel) -> dict[str, Any]:
81
+ """One validated row as the JSON object a bundle line carries.
82
+
83
+ Dumped **by alias**, because the alias is the canonical column name: one
84
+ column is called `class`, a Python keyword, whose field is therefore
85
+ `class_`. A bundle carrying `class_` would not validate against
86
+ `export.schema.json`, which is generated from the manifest and names columns.
87
+ """
88
+ return {
89
+ name: format_timestamp(value) if isinstance(value, _dt.datetime) else value
90
+ for name, value in model.model_dump(by_alias=True).items()
91
+ }
92
+
93
+
94
+ class _Strict(BaseModel):
95
+ """Closed by construction: an unknown key in a bundle manifest is a defect."""
96
+
97
+ model_config = ConfigDict(extra="forbid", frozen=True)
98
+
99
+
100
+ class BundleScope(_Strict):
101
+ """The scope a bundle belongs to, **as slugs** so it resolves without ULIDs."""
102
+
103
+ firm: str
104
+ engagement: str
105
+
106
+
107
+ class TableEntry(_Strict):
108
+ name: str
109
+ rows: int
110
+ sha256: str
111
+ #: Columns the manifest has retired at this schema version. Present and empty
112
+ #: rather than omitted, because §11 requires the field to distinguish
113
+ #: "absent" from "null for every row" -- and an absent list says neither.
114
+ omitted_columns: list[str]
115
+
116
+
117
+ class BlobSummary(_Strict):
118
+ count: int
119
+ total_bytes: int
120
+
121
+
122
+ class BundleManifest(_Strict):
123
+ """`manifest.json`, exactly the §11 keys and no others."""
124
+
125
+ export_version: int
126
+ schema_version: int
127
+ scope: BundleScope
128
+ written_by: str
129
+ #: A string, not a datetime: it is rendered once by the writer and compared
130
+ #: as text thereafter. Re-parsing it into a datetime only to render it again
131
+ #: would put a second timestamp format in the round trip.
132
+ written_at: str
133
+ tables: list[TableEntry]
134
+ blobs: BlobSummary
135
+
136
+ def entry_for(self, table: str) -> TableEntry | None:
137
+ return next((entry for entry in self.tables if entry.name == table), None)
138
+
139
+ def to_bytes(self) -> bytes:
140
+ return (canonical_json(self.model_dump()) + LINE_SEPARATOR).encode(ENCODING)
141
+
142
+
143
+ def read_text(path: Path) -> str:
144
+ """Read a bundle file as text without letting the platform rewrite newlines.
145
+
146
+ Decoded from bytes rather than read as text: `Path.read_text` opens in text
147
+ mode, and text mode on Windows turns a `\\r\\n` in a bundle into a `\\n` on
148
+ the way in. A bundle's bytes are the contract, so they are never translated.
149
+ """
150
+ return path.read_bytes().decode(ENCODING)
adopt_export/ports.py ADDED
@@ -0,0 +1,82 @@
1
+ """The two storage ports the bundle writer and reader run on.
2
+
3
+ Declared here rather than imported from `adopt_store`, following the precedent
4
+ `adopt_scope.records` set and CR-34 extended to coverage and freshness:
5
+ `no-raw-sqlite` names `adopt_export` as a source module and import-linter follows
6
+ the chain, so a dependency on `adopt_store` would reach `sqlite3` transitively
7
+ and break the contract. A structural protocol costs one file and keeps this
8
+ package free of any dialect -- which is what makes "the same bundle whichever
9
+ store answered" a property of the writer rather than a coincidence.
10
+
11
+ **The ports fetch and apply rows; they never decide.** Row order, the scope
12
+ refusal, digest verification and the all-or-nothing boundary are all the
13
+ writer's and the reader's. Pushing any of them into a realization would mean the
14
+ byte-identical round-trip was a property of whichever store ran, and the
15
+ round-trip property test would be comparing two callers of one query.
16
+
17
+ **`insert_rows` takes whole validated models, never a column subset.** That is
18
+ deliberate and load-bearing: `identity.covered_cache` is an exportable column,
19
+ and a port that could write *some* columns of `identity` would be the general
20
+ setter `no-covered-cache-write` exists to forbid. Import restores rows exactly as
21
+ a bundle recorded them, into an empty store, or it refuses.
22
+ """
23
+
24
+ from collections.abc import Sequence
25
+ from contextlib import AbstractContextManager
26
+ from typing import Protocol
27
+
28
+ from pydantic import BaseModel
29
+
30
+ __all__ = ["ExportRecords", "ImportRecords"]
31
+
32
+
33
+ class ExportRecords(Protocol):
34
+ """Read-only. No SQL, connection or cursor crosses this boundary."""
35
+
36
+ def firm_slugs(self) -> Sequence[str]:
37
+ """Every `firm.slug` in the store, and the writer decides what to do.
38
+
39
+ Reported rather than resolved because `manifest.json` names **one** firm
40
+ (contracts §11) and refusing is the writer's judgement. A port that
41
+ returned "the" firm slug would have to pick one, and picking one for a
42
+ store holding two produces a bundle labelled with a scope half its rows
43
+ do not belong to -- which nothing downstream can detect.
44
+ """
45
+ ...
46
+
47
+ def engagement_slugs(self) -> Sequence[str]:
48
+ """Every `engagement.slug` in the store. Same argument as `firm_slugs`."""
49
+ ...
50
+
51
+ def table_rows[TModel: BaseModel](
52
+ self, table: str, model_type: type[TModel]
53
+ ) -> Sequence[TModel]:
54
+ """Every row of one table, validated against its generated model.
55
+
56
+ Unordered by contract. The writer sorts by the manifest's primary key,
57
+ so the emitted order is a pure function of (manifest, rows) and identical
58
+ whichever realization answered.
59
+ """
60
+ ...
61
+
62
+
63
+ class ImportRecords(Protocol):
64
+ """Write side. Whole rows only, inside the caller's transaction."""
65
+
66
+ def row_count(self, table: str) -> int:
67
+ """How many rows one table already holds.
68
+
69
+ The reader sums this across every exportable table to decide
70
+ `EXPORT_TARGET_NOT_EMPTY`, and names the first non-empty table in the
71
+ message -- "the store is not empty" sends an operator looking, and
72
+ "`firm` already holds 1 row" tells them what they are about to lose.
73
+ """
74
+ ...
75
+
76
+ def insert_rows(self, table: str, models: Sequence[BaseModel]) -> None:
77
+ """Append whole rows. The model is the column authority, as everywhere else."""
78
+ ...
79
+
80
+ def transaction(self) -> AbstractContextManager[None]:
81
+ """The one boundary the whole import commits or rolls back inside."""
82
+ ...
adopt_export/py.typed ADDED
File without changes
adopt_export/reader.py ADDED
@@ -0,0 +1,238 @@
1
+ """`read_bundle` and `apply_bundle` — the import half of contracts §11.
2
+
3
+ The order of the checks is the contract, not an implementation detail:
4
+
5
+ 1. **Version negotiation first.** An `export_version` outside the supported range
6
+ is refused **naming the range**, because "unsupported" without the range sends
7
+ an integrator to the source and the whole point of pinning `export_version`
8
+ (§1.6, owner decision 12) is that they should not have to go there.
9
+ 2. **Every digest, before any row.** §11 says verified *before any row is
10
+ applied*, and F9.5 says all or nothing. Verifying per table as it is applied
11
+ would satisfy neither: the first table would already be in the store when the
12
+ fourth file turned out to be corrupt.
13
+ 3. **Then the rows**, all inside one transaction against an empty store.
14
+
15
+ **Rows are applied verbatim, not through the facades.** A facade generates ids;
16
+ import must preserve them, because a re-export whose ULIDs differ is not
17
+ byte-identical and every URI in the bundle would resolve to a different row. That
18
+ is also why the applier takes whole validated models: it restores what a bundle
19
+ recorded and computes nothing.
20
+ """
21
+
22
+ import json as _json
23
+ from collections.abc import Sequence
24
+ from pathlib import Path
25
+ from typing import Any, Final
26
+
27
+ from pydantic import BaseModel, ValidationError
28
+
29
+ from adopt_const import (
30
+ EXPORT_NDJSON_MAX_LINE_BYTES,
31
+ MAX_SUPPORTED_EXPORT_VERSION,
32
+ MIN_SUPPORTED_EXPORT_VERSION,
33
+ )
34
+ from adopt_export.bundle import (
35
+ ENCODING,
36
+ MANIFEST_FILENAME,
37
+ BundleManifest,
38
+ read_text,
39
+ sha256_of_bytes,
40
+ table_relative_path,
41
+ )
42
+ from adopt_export.ports import ImportRecords
43
+ from adopt_model import MODEL_FOR_TABLE
44
+ from adopt_obs import AdoptError, ErrorCode, get_logger
45
+ from adopt_schema.manifest import Manifest, canonical_path, load_manifest
46
+
47
+ __all__ = ["EXPORT_COMPAT_FILENAME", "apply_bundle", "read_bundle"]
48
+
49
+ _LOGGER: Final = get_logger("adopt_export")
50
+
51
+ #: Which `schema_version` each `export_version` implies. The two are versioned
52
+ #: independently (§1.6), so the mapping is data rather than an equality anyone
53
+ #: could assume from the fact that both happen to start at 3 (CR-13).
54
+ EXPORT_COMPAT_FILENAME: Final[str] = "export_compat.json"
55
+
56
+
57
+ def _malformed(message: str, hint: str) -> AdoptError:
58
+ return AdoptError(ErrorCode.EXPORT_BUNDLE_MALFORMED, message=message, hint=hint)
59
+
60
+
61
+ def _load_compat(path: Path | None = None) -> dict[str, dict[str, int]]:
62
+ source = path if path is not None else canonical_path().parent / EXPORT_COMPAT_FILENAME
63
+ parsed: Any = _json.loads(source.read_text(encoding=ENCODING))
64
+ return {str(key): dict(value) for key, value in parsed.items()}
65
+
66
+
67
+ def read_bundle(source: Path, *, compat_path: Path | None = None) -> BundleManifest:
68
+ """Parse and validate `manifest.json`, negotiate the version, verify nothing else.
69
+
70
+ Raises:
71
+ AdoptError: ``EXPORT_BUNDLE_MALFORMED`` when the manifest is missing or
72
+ does not match §11. ``EXPORT_VERSION_UNSUPPORTED`` when the bundle's
73
+ `export_version` is outside the supported range or its declared
74
+ `schema_version` is not the one that version implies.
75
+ """
76
+ manifest_path = source / MANIFEST_FILENAME
77
+ if not manifest_path.is_file():
78
+ raise _malformed(
79
+ f"no {MANIFEST_FILENAME} at {source}",
80
+ "A bundle is a directory whose manifest names every file in it. Point "
81
+ "import at the bundle directory, not at its `tables/` subdirectory.",
82
+ )
83
+
84
+ try:
85
+ bundle = BundleManifest.model_validate_json(read_text(manifest_path))
86
+ except ValidationError as error:
87
+ raise _malformed(
88
+ f"{manifest_path} does not match the contracts §11 manifest shape: {error}",
89
+ "The manifest is closed: every key is declared in §11, and an unknown one "
90
+ "is a bundle from a different format rather than a newer version of this one.",
91
+ ) from error
92
+
93
+ if not MIN_SUPPORTED_EXPORT_VERSION <= bundle.export_version <= MAX_SUPPORTED_EXPORT_VERSION:
94
+ raise AdoptError(
95
+ ErrorCode.EXPORT_VERSION_UNSUPPORTED,
96
+ message=f"bundle export_version {bundle.export_version} is outside the supported "
97
+ f"range {MIN_SUPPORTED_EXPORT_VERSION}-{MAX_SUPPORTED_EXPORT_VERSION}",
98
+ hint="Integrators pin `export_version` (contracts §1.6). Read the bundle with "
99
+ "a binary whose supported range includes it; nothing has been applied.",
100
+ )
101
+
102
+ implied = _load_compat(compat_path).get(str(bundle.export_version))
103
+ if implied is not None and implied.get("schema_version") != bundle.schema_version:
104
+ raise AdoptError(
105
+ ErrorCode.EXPORT_VERSION_UNSUPPORTED,
106
+ message=f"export_version {bundle.export_version} implies schema_version "
107
+ f"{implied.get('schema_version')}, and the bundle declares {bundle.schema_version}",
108
+ hint="`schema/export_compat.json` records which schema version each export "
109
+ "version carries. A bundle disagreeing with it was assembled by hand or by "
110
+ "a build that is not this one.",
111
+ )
112
+ return bundle
113
+
114
+
115
+ def _verify_digests(source: Path, bundle: BundleManifest, manifest: Manifest) -> dict[str, bytes]:
116
+ """Every table file, read and digest-checked. Returns the verified bytes.
117
+
118
+ Read once and kept, rather than read now and re-read while applying: a file
119
+ that changed between the two reads would pass the digest check and apply
120
+ something else, which is precisely the substitution the digest exists to
121
+ prevent.
122
+ """
123
+ expected = {name for name, _ in manifest.exportable_tables()}
124
+ declared = {entry.name for entry in bundle.tables}
125
+
126
+ if declared != expected:
127
+ missing = sorted(expected - declared)
128
+ unexpected = sorted(declared - expected)
129
+ raise _malformed(
130
+ "the manifest's table set does not match schema version "
131
+ f"{manifest.schema_version}: missing {missing}, unexpected {unexpected}",
132
+ "Every exportable table produces a file, even when empty (§11), so a missing "
133
+ "entry is a truncated bundle rather than an empty table. An unexpected entry "
134
+ "is a table this schema version does not declare.",
135
+ )
136
+
137
+ verified: dict[str, bytes] = {}
138
+ for entry in bundle.tables:
139
+ path = source / table_relative_path(entry.name)
140
+ if not path.is_file():
141
+ raise _malformed(
142
+ f"the manifest names {entry.name} but {path} does not exist",
143
+ "Every table the manifest lists is present as a file, empty or not.",
144
+ )
145
+ payload = path.read_bytes()
146
+ actual = sha256_of_bytes(payload)
147
+ if actual != entry.sha256:
148
+ raise AdoptError(
149
+ ErrorCode.EXPORT_DIGEST_MISMATCH,
150
+ message=f"{table_relative_path(entry.name)} digests to {actual}, and the "
151
+ f"manifest records {entry.sha256}",
152
+ hint="Nothing has been applied. The bundle is corrupt or was edited after "
153
+ "it was written; re-export rather than repairing the file.",
154
+ )
155
+ verified[entry.name] = payload
156
+ return verified
157
+
158
+
159
+ def _parse_rows(table: str, payload: bytes) -> Sequence[BaseModel]:
160
+ model_type = MODEL_FOR_TABLE[table]
161
+ models: list[BaseModel] = []
162
+ for number, raw in enumerate(payload.decode(ENCODING).split("\n"), 1):
163
+ if not raw:
164
+ continue
165
+ if len(raw.encode(ENCODING)) > EXPORT_NDJSON_MAX_LINE_BYTES:
166
+ raise _malformed(
167
+ f"{table} line {number} is over the {EXPORT_NDJSON_MAX_LINE_BYTES}-byte limit",
168
+ "A line this long is not a row this format can carry. The bundle was not "
169
+ "written by this version.",
170
+ )
171
+ try:
172
+ models.append(model_type.model_validate_json(raw))
173
+ except ValidationError as error:
174
+ raise _malformed(
175
+ f"{table} line {number} does not validate against its generated model: {error}",
176
+ "The generated models are the only validators (contracts §1.4) and they are "
177
+ "closed, so an unknown column is a row from a different schema rather than a "
178
+ "richer version of this one.",
179
+ ) from error
180
+ return models
181
+
182
+
183
+ def apply_bundle(
184
+ records: ImportRecords,
185
+ source: Path,
186
+ *,
187
+ bundle: BundleManifest | None = None,
188
+ manifest: Manifest | None = None,
189
+ compat_path: Path | None = None,
190
+ ) -> BundleManifest:
191
+ """Verify a bundle whole, then apply every row in one transaction.
192
+
193
+ Args:
194
+ records: The write port, over a store already at the current schema version.
195
+ source: The bundle directory.
196
+ bundle: A manifest already read by `read_bundle`; read here if absent.
197
+ manifest: The canonical manifest. Loaded if not supplied.
198
+ compat_path: Override for `schema/export_compat.json`.
199
+
200
+ Raises:
201
+ AdoptError: ``EXPORT_VERSION_UNSUPPORTED``, ``EXPORT_DIGEST_MISMATCH``,
202
+ ``EXPORT_BUNDLE_MALFORMED`` or ``EXPORT_TARGET_NOT_EMPTY``. In every
203
+ case no row has been applied.
204
+ """
205
+ loaded = manifest if manifest is not None else load_manifest()
206
+ read = bundle if bundle is not None else read_bundle(source, compat_path=compat_path)
207
+
208
+ verified = _verify_digests(source, read, loaded)
209
+
210
+ for table_name, _ in loaded.exportable_tables():
211
+ held = records.row_count(table_name)
212
+ if held:
213
+ raise AdoptError(
214
+ ErrorCode.EXPORT_TARGET_NOT_EMPTY,
215
+ message=f"the target store already holds {held} row(s) in {table_name}",
216
+ hint="Import restores a bundle into an empty store and is never a merge: "
217
+ "the bundle carries the ids it was written with, so applying it over "
218
+ "existing rows would collide or silently interleave two histories.",
219
+ )
220
+
221
+ # Parsed before the transaction opens, so a malformed row fails without ever
222
+ # having started a write -- and the store is untouched rather than rolled back.
223
+ parsed = {name: _parse_rows(name, payload) for name, payload in verified.items()}
224
+
225
+ with records.transaction():
226
+ # Foreign-key topological order: `exportable_tables()` is already sorted
227
+ # by it, so a child never lands before its parent.
228
+ for table_name, _ in loaded.exportable_tables():
229
+ records.insert_rows(table_name, parsed[table_name])
230
+
231
+ _LOGGER.info(
232
+ "export.bundle_applied",
233
+ tables=len(read.tables),
234
+ rows=sum(entry.rows for entry in read.tables),
235
+ export_version=read.export_version,
236
+ schema_version=read.schema_version,
237
+ )
238
+ return read
@@ -0,0 +1,69 @@
1
+ """`verify_roundtrip` — the G0 comparison, and where `EXPORT_ROUNDTRIP_UNSTABLE` lives.
2
+
3
+ The comparison is here rather than inside the test for two reasons. It is a
4
+ product statement, not a test convenience: contracts §13 registers
5
+ `EXPORT_ROUNDTRIP_UNSTABLE` as an error the programme raises, and an error code
6
+ whose only caller is an assertion is a code that means nothing to anyone
7
+ receiving it. And a comparison written inline in a test is a comparison nobody
8
+ ever watches fail, which is the same objection the planted-violation discipline
9
+ makes of every other gate here.
10
+
11
+ **Table files only.** `manifest.json` carries `written_at`, which differs
12
+ between two exports by design (PRD F9.2). Comparing it would make G0 fail on
13
+ every run for the one reason that is not a defect.
14
+ """
15
+
16
+ from pathlib import Path
17
+ from typing import Final
18
+
19
+ from adopt_export.bundle import TABLES_DIRNAME
20
+ from adopt_obs import AdoptError, ErrorCode
21
+
22
+ __all__ = ["table_files", "verify_roundtrip"]
23
+
24
+ _FIRST: Final[str] = "first"
25
+ _SECOND: Final[str] = "second"
26
+
27
+
28
+ def table_files(bundle: Path) -> dict[str, bytes]:
29
+ """Every `tables/*.ndjson` in a bundle, by file name, as raw bytes."""
30
+ directory = bundle / TABLES_DIRNAME
31
+ if not directory.is_dir():
32
+ return {}
33
+ return {path.name: path.read_bytes() for path in sorted(directory.iterdir())}
34
+
35
+
36
+ def verify_roundtrip(first: Path, second: Path) -> None:
37
+ """Raise unless two bundles' table files are byte-identical.
38
+
39
+ Args:
40
+ first: The bundle exported from the original store.
41
+ second: The bundle exported from the store the first was imported into.
42
+
43
+ Raises:
44
+ AdoptError: ``EXPORT_ROUNDTRIP_UNSTABLE``, naming the files that differ
45
+ and how -- present in one bundle only, or present in both with
46
+ different bytes.
47
+ """
48
+ left = table_files(first)
49
+ right = table_files(second)
50
+
51
+ differences: list[str] = []
52
+ for name in sorted(set(left) | set(right)):
53
+ if name not in right:
54
+ differences.append(f"{name}: in the {_FIRST} bundle only")
55
+ elif name not in left:
56
+ differences.append(f"{name}: in the {_SECOND} bundle only")
57
+ elif left[name] != right[name]:
58
+ differences.append(
59
+ f"{name}: {len(left[name])} bytes then {len(right[name])} bytes, and they differ"
60
+ )
61
+
62
+ if differences:
63
+ raise AdoptError(
64
+ ErrorCode.EXPORT_ROUNDTRIP_UNSTABLE,
65
+ message="re-export is not byte-identical: " + "; ".join(differences),
66
+ hint="The bundle a client keeps must survive a round trip unchanged. Look for "
67
+ "a rendering that depends on something other than the rows -- a key order, a "
68
+ "timestamp format, a collation -- rather than for a difference in the data.",
69
+ )
adopt_export/writer.py ADDED
@@ -0,0 +1,227 @@
1
+ """`write_bundle` — the export half of contracts §11.
2
+
3
+ Three decisions live here rather than in whichever store answered, and each is
4
+ the reason the byte-identical round trip is testable at all:
5
+
6
+ * **Row order.** The writer sorts by the manifest's primary key over the
7
+ *rendered* values, so the order is byte-wise ascending as §11 requires and is a
8
+ pure function of (manifest, rows). Pushing `ORDER BY` into the realization
9
+ would make the emitted bytes depend on a collation, and the Postgres
10
+ realization would have to reproduce SQLite's exactly, unwritten and untested.
11
+ * **The scope refusal.** `manifest.json` names one firm and one engagement. A
12
+ store holding two is refused before anything is created, because a bundle
13
+ labelled with a scope half its rows do not belong to is not a wrong answer, it
14
+ is a *different referent* -- and nothing downstream can detect it (CR-37).
15
+ * **What counts as exportable.** The writer iterates
16
+ `Manifest.exportable_tables()`. Runtime-annex tables are excluded **by
17
+ construction**: they are not in the canonical manifest at all, so there is no
18
+ filter to forget (contracts §12).
19
+
20
+ The writer opens no socket and writes nothing outside `target`.
21
+ """
22
+
23
+ import datetime as _dt
24
+ from collections.abc import Sequence
25
+ from pathlib import Path
26
+ from typing import Any, Final
27
+
28
+ from adopt_const import EXPORT_NDJSON_MAX_LINE_BYTES, EXPORT_VERSION, SCHEMA_VERSION
29
+ from adopt_export.bundle import (
30
+ ENCODING,
31
+ LINE_SEPARATOR,
32
+ MANIFEST_FILENAME,
33
+ SCHEMA_FILENAME,
34
+ TABLES_DIRNAME,
35
+ BlobSummary,
36
+ BundleManifest,
37
+ BundleScope,
38
+ TableEntry,
39
+ canonical_json,
40
+ row_object,
41
+ sha256_of_bytes,
42
+ table_relative_path,
43
+ )
44
+ from adopt_export.ports import ExportRecords
45
+ from adopt_model import MODEL_FOR_TABLE
46
+ from adopt_obs import AdoptError, Clock, ErrorCode, SystemClock, format_timestamp, get_logger
47
+ from adopt_schema.manifest import Manifest, Table, canonical_path, load_manifest
48
+
49
+ __all__ = ["default_schema_source", "write_bundle"]
50
+
51
+ _LOGGER: Final = get_logger("adopt_export")
52
+
53
+ #: No exportable table at schema version 3 references a blob, so the block is
54
+ #: reported as empty rather than assembled. See `bundle` for the full argument.
55
+ _NO_BLOBS: Final[BlobSummary] = BlobSummary(count=0, total_bytes=0)
56
+
57
+
58
+ def default_schema_source() -> Path:
59
+ """Where `export.schema.json` is read from, beside the manifest it came from.
60
+
61
+ Resolved through `canonical_path()` so the `ADOPT_SCHEMA_MANIFEST` override
62
+ moves both together. A bundle carrying a schema from one checkout and rows
63
+ from another is a bundle that validates against the wrong contract.
64
+ """
65
+ return canonical_path().parent / SCHEMA_FILENAME
66
+
67
+
68
+ def _sole_slug(kind: str, slugs: Sequence[str]) -> str:
69
+ distinct = sorted(set(slugs))
70
+ if len(distinct) == 1:
71
+ return distinct[0]
72
+ if not distinct:
73
+ raise AdoptError(
74
+ ErrorCode.EXPORT_SCOPE_AMBIGUOUS,
75
+ message=f"the store holds no {kind}, and a bundle names one",
76
+ hint="Create the scope before exporting. An empty store has no scope to "
77
+ "record, and a bundle whose scope is guessed is a bundle nothing can trust.",
78
+ )
79
+ raise AdoptError(
80
+ ErrorCode.EXPORT_SCOPE_AMBIGUOUS,
81
+ message=f"the store holds {len(distinct)} {kind}s ({', '.join(distinct)}) "
82
+ f"and contracts §11 names one",
83
+ hint="Export one scope per bundle. Labelling a bundle with one of several "
84
+ "scopes is not a wrong answer but a different referent, and no consumer of "
85
+ "the bundle can detect it.",
86
+ )
87
+
88
+
89
+ def _omitted_columns(table: Table) -> list[str]:
90
+ """Columns the manifest has retired at or below the current schema version.
91
+
92
+ Empty at version 3, and computed rather than hard-coded so it stops being
93
+ empty by itself the first time a column is retired -- which is the only way
94
+ §11's "absent versus null for every row" distinction stays true.
95
+ """
96
+ return sorted(
97
+ column.name
98
+ for column in table.columns
99
+ if column.retired_in_version is not None and column.retired_in_version <= SCHEMA_VERSION
100
+ )
101
+
102
+
103
+ def _sort_key(row: dict[str, Any], primary_key: Sequence[str]) -> tuple[str, ...]:
104
+ """Byte-wise ascending over the rendered primary key (§11).
105
+
106
+ Rendered, not raw: the values compared are the ones about to be written, so
107
+ the file's order and the file's bytes cannot disagree. Every canonical
108
+ primary-key column is a `id`, `slug`, `text` or `ts`, all of which render as
109
+ strings, so this is a total order rather than a best effort.
110
+ """
111
+ return tuple(str(row[column]) for column in primary_key)
112
+
113
+
114
+ def _render_table(table_name: str, table: Table, records: ExportRecords) -> tuple[bytes, int]:
115
+ """One table's file content and its row count. Empty tables render empty."""
116
+ models = records.table_rows(table_name, MODEL_FOR_TABLE[table_name])
117
+ rows = sorted(
118
+ (row_object(model) for model in models),
119
+ key=lambda row: _sort_key(row, table.primary_key),
120
+ )
121
+
122
+ lines: list[str] = []
123
+ for index, row in enumerate(rows):
124
+ line = canonical_json(row)
125
+ encoded = line.encode(ENCODING)
126
+ if len(encoded) > EXPORT_NDJSON_MAX_LINE_BYTES:
127
+ raise AdoptError(
128
+ ErrorCode.EXPORT_BUNDLE_MALFORMED,
129
+ message=f"{table_name} row {index} renders to {len(encoded)} bytes, over the "
130
+ f"{EXPORT_NDJSON_MAX_LINE_BYTES}-byte line limit",
131
+ hint="The reader refuses a line this long, so writing one would produce a "
132
+ "bundle this version cannot import. The row is too large for the format.",
133
+ )
134
+ lines.append(line)
135
+
136
+ content = "".join(line + LINE_SEPARATOR for line in lines)
137
+ return content.encode(ENCODING), len(rows)
138
+
139
+
140
+ def write_bundle(
141
+ records: ExportRecords,
142
+ target: Path,
143
+ *,
144
+ written_by: str,
145
+ manifest: Manifest | None = None,
146
+ clock: Clock | None = None,
147
+ schema_source: Path | None = None,
148
+ ) -> BundleManifest:
149
+ """Write a bundle to ``target`` and return the manifest it recorded.
150
+
151
+ Args:
152
+ records: The read port. Never written through.
153
+ target: The bundle directory. Created if absent; refused if non-empty.
154
+ written_by: Provenance for `manifest.json`, e.g. ``adopt-core/0.3.0``.
155
+ manifest: The canonical manifest. Loaded if not supplied.
156
+ clock: Injected clock; tests pass `ManualClock`.
157
+ schema_source: Where to copy `export.schema.json` from.
158
+
159
+ Raises:
160
+ AdoptError: ``EXPORT_SCOPE_AMBIGUOUS`` when the store does not hold
161
+ exactly one firm and one engagement. ``EXPORT_TARGET_NOT_EMPTY``
162
+ when ``target`` already holds anything. ``EXPORT_BUNDLE_MALFORMED``
163
+ when a row would render past the line limit.
164
+ """
165
+ loaded = manifest if manifest is not None else load_manifest()
166
+ ticking = clock if clock is not None else SystemClock()
167
+
168
+ # Scope first, before anything exists on disk: a refusal that has already
169
+ # created half a bundle leaves a directory an operator has to reason about.
170
+ scope = BundleScope(
171
+ firm=_sole_slug("firm", records.firm_slugs()),
172
+ engagement=_sole_slug("engagement", records.engagement_slugs()),
173
+ )
174
+
175
+ if target.exists() and any(target.iterdir()):
176
+ raise AdoptError(
177
+ ErrorCode.EXPORT_TARGET_NOT_EMPTY,
178
+ message=f"{target} is not empty",
179
+ hint="Export writes a whole bundle or none of one. Point it at a new "
180
+ "directory rather than merging into an existing bundle, whose manifest "
181
+ "would then describe files it did not write.",
182
+ )
183
+
184
+ tables_dir = target / TABLES_DIRNAME
185
+ tables_dir.mkdir(parents=True, exist_ok=True)
186
+
187
+ entries: list[TableEntry] = []
188
+ for table_name, table in loaded.exportable_tables():
189
+ content, count = _render_table(table_name, table, records)
190
+ (target / table_relative_path(table_name)).write_bytes(content)
191
+ entries.append(
192
+ TableEntry(
193
+ name=table_name,
194
+ rows=count,
195
+ sha256=sha256_of_bytes(content),
196
+ omitted_columns=_omitted_columns(table),
197
+ )
198
+ )
199
+
200
+ source = schema_source if schema_source is not None else default_schema_source()
201
+ (target / SCHEMA_FILENAME).write_bytes(source.read_bytes())
202
+
203
+ bundle_manifest = BundleManifest(
204
+ export_version=EXPORT_VERSION,
205
+ schema_version=loaded.schema_version,
206
+ scope=scope,
207
+ written_by=written_by,
208
+ written_at=format_timestamp(_as_utc(ticking.now())),
209
+ tables=entries,
210
+ blobs=_NO_BLOBS,
211
+ )
212
+ # Written last: a manifest present means every file it names is present too,
213
+ # so a reader never has to distinguish a finished bundle from an abandoned one.
214
+ (target / MANIFEST_FILENAME).write_bytes(bundle_manifest.to_bytes())
215
+
216
+ _LOGGER.info(
217
+ "export.bundle_written",
218
+ tables=len(entries),
219
+ rows=sum(entry.rows for entry in entries),
220
+ export_version=EXPORT_VERSION,
221
+ schema_version=loaded.schema_version,
222
+ )
223
+ return bundle_manifest
224
+
225
+
226
+ def _as_utc(moment: _dt.datetime) -> _dt.datetime:
227
+ return moment.astimezone(_dt.UTC)
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.5
2
+ Name: adopt-export
3
+ Version: 0.3.0
4
+ Summary: Export bundle writer and reader; the byte-stable round trip.
5
+ Project-URL: Homepage, https://github.com/onboardux/onboard-core
6
+ Project-URL: Source, https://github.com/onboardux/onboard-core
7
+ Project-URL: Issues, https://github.com/onboardux/onboard-core/issues
8
+ Author: The Adopt Authors
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Requires-Python: >=3.12
13
+ Requires-Dist: adopt-const
14
+ Requires-Dist: adopt-model
15
+ Requires-Dist: adopt-obs
16
+ Requires-Dist: adopt-schema
@@ -0,0 +1,12 @@
1
+ adopt_export/__init__.py,sha256=OEGKN-xXE8QE36WbJX5VowpcuojAVjJMyF6fZJXlGSQ,1892
2
+ adopt_export/bundle.py,sha256=bpCdWoOgiWmMHP3Hqle33zZTLGFmga1MqnyoxZvDYP8,5410
3
+ adopt_export/ports.py,sha256=E5Gbzwx26j1TcT2LJNwonAfC89T6q3X5gMFV01GKn9U,3593
4
+ adopt_export/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ adopt_export/reader.py,sha256=-_tFiTktRDOzgLrUsn6wu-Ks8kPVVDTmgCuPJQx-2Fs,10770
6
+ adopt_export/roundtrip.py,sha256=83524fEU0z0FL44aFhXgLJ10xRZaeTubD6YssxUPgvo,2808
7
+ adopt_export/writer.py,sha256=2yJxsJbGLyqfHW2NIje3RCB0w7RCSpdoinXVp-bEQ4I,9275
8
+ adopt_export-0.3.0.dist-info/METADATA,sha256=aXniGusAXx7N7MSNTQ8Ngw-K0VTvvqhySs03QK_ztOs,555
9
+ adopt_export-0.3.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
10
+ adopt_export-0.3.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
11
+ adopt_export-0.3.0.dist-info/licenses/NOTICE,sha256=2_mgo6v6IM9fAn52L5-wXFpISnC6PVU_geTutoRhbWk,1897
12
+ adopt_export-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,39 @@
1
+ Adopt — Adoption-Phase Platform, shared substrate (`adopt-core`)
2
+ Copyright 2026 The Adopt Authors
3
+
4
+ This product includes software developed by The Adopt Authors.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this file except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Unless required by applicable law or agreed to in writing, software
13
+ distributed under the License is distributed on an "AS IS" BASIS,
14
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ See the License for the specific language governing permissions and
16
+ limitations under the License.
17
+
18
+ --------------------------------------------------------------------------------
19
+ Attribution note
20
+ --------------------------------------------------------------------------------
21
+
22
+ The copyright holder is recorded here as "The Adopt Authors" pending the legal
23
+ entity name. The owner must settle that attribution before the 0.3.0 tag,
24
+ because published package metadata cannot be changed retroactively for a
25
+ release that has already left the machine. The product name itself is settled:
26
+ handoff-index CR-50 keeps `Adopt` distinct from the `onboard` URI namespace.
27
+
28
+ --------------------------------------------------------------------------------
29
+ Third-party dependencies
30
+ --------------------------------------------------------------------------------
31
+
32
+ Every third-party dependency linked into this distribution is permissively
33
+ licensed. The complete list, with licence hash, security status, usage mode,
34
+ owner and re-verification date, is maintained in `licence-verifications.md` and
35
+ enforced by `scripts/licence_gate.py`.
36
+
37
+ Copyleft-licensed tools are invoked as subprocesses only and are never linked
38
+ into this distribution. They are declared in `subprocess-deps.toml` together
39
+ with their invocation sites.