KrazyKitty commited on
Commit
a490f0e
·
verified ·
1 Parent(s): 44bf405

Create DATA LAB private review package

Browse files
README.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pretty_name: KRAZYKITTY // DATA LAB
4
+ tags:
5
+ - data-provenance
6
+ - dataset-documentation
7
+ - preprocessing
8
+ - data-quality
9
+ - evaluation
10
+ - privacy
11
+ - reproducibility
12
+ ---
13
+
14
+ # KRAZYKITTY // DATA LAB
15
+
16
+ **Status: research documentation and workflow toolkit — no dataset is published here.**
17
+
18
+ DATA LAB is KrazyKitty's evidence-first workspace for studying how datasets should be sourced,
19
+ reviewed, transformed, documented, and evaluated before they are allowed near a training or
20
+ benchmark pipeline.
21
+
22
+ This repository contains dataset-card templates, provenance schemas, deterministic preprocessing
23
+ tools, evaluation guidance, and review gates. It does **not** contain a corpus, benchmark examples,
24
+ training rows, scraped content, or a claim that any source is approved for KittyLM.
25
+
26
+ ## Research tracks
27
+
28
+ | Track | Purpose | Current state |
29
+ |---|---|---|
30
+ | Source provenance | Bind each source to identity, version, integrity, licence, and allowed use | Working templates and validator |
31
+ | Licensing, privacy, consent | Require explicit permission and data-risk review before processing | Documented gate |
32
+ | Preprocessing experiments | Compare deterministic text transformations without hiding exclusions | Working local reference workflow |
33
+ | Data quality | Measure duplication, encoding, language, structure, contamination, and coverage | Measurement plan |
34
+ | Evaluation resources | Version benchmark inputs and separate test integrity from model claims | Documentation and Collection candidates |
35
+ | Dataset cards | Make intended use, composition, limitations, and governance visible | Reusable templates |
36
+
37
+ ## Repository map
38
+
39
+ - [`docs/PROVENANCE.md`](docs/PROVENANCE.md) — evidence model and source lineage
40
+ - [`docs/LICENSE_PRIVACY_CONSENT.md`](docs/LICENSE_PRIVACY_CONSENT.md) — release-blocking review
41
+ - [`docs/DATA_QUALITY.md`](docs/DATA_QUALITY.md) — quality dimensions and reporting rules
42
+ - [`docs/EVALUATION.md`](docs/EVALUATION.md) — benchmark governance and contamination controls
43
+ - [`templates/dataset-card-template.md`](templates/dataset-card-template.md) — corpus-oriented card
44
+ - [`templates/evaluation-card-template.md`](templates/evaluation-card-template.md) — evaluation-set card
45
+ - [`schemas/source-manifest.schema.json`](schemas/source-manifest.schema.json) — machine-readable contract
46
+ - [`workflows/validate_manifest.py`](workflows/validate_manifest.py) — standard-library validator
47
+ - [`workflows/preprocess_text.py`](workflows/preprocess_text.py) — deterministic, approval-gated text reference flow
48
+ - [`experiments/README.md`](experiments/README.md) — experiment record contract
49
+
50
+ ## Reproducible workflow
51
+
52
+ 1. Create a source manifest from the schema and keep its decision `proposed`.
53
+ 2. Record canonical source URLs, versions, licences, redistribution terms, integrity hashes,
54
+ privacy review, consent or other lawful basis, and intended use.
55
+ 3. Review the source outside the preprocessing program. Automated checks do not grant permission.
56
+ 4. Change the manifest to `approved` only after the named reviewers have approved every source.
57
+ 5. Run `python workflows/validate_manifest.py manifest.json`.
58
+ 6. Run the reference preprocessing experiment against only the files listed in that manifest.
59
+ 7. Store the exact command, source revision, manifest hash, environment, counts, exclusions, and
60
+ output hashes in an experiment record.
61
+ 8. Publish data only through a separate release decision with a complete dataset card.
62
+
63
+ ## Non-goals and safeguards
64
+
65
+ - Public availability is not treated as consent or permission for model training.
66
+ - A licence label is not accepted without checking scope, attribution, redistribution, and
67
+ downstream restrictions.
68
+ - The reference preprocessing tool is not a privacy scrubber, copyright detector, toxicity
69
+ classifier, or quality oracle.
70
+ - Personally identifiable, sensitive, confidential, or revoked material is release-blocking until
71
+ reviewed and resolved.
72
+ - Benchmark test content must not enter training mixtures.
73
+ - Raw and processed data remain outside this repository unless a later, separately approved
74
+ dataset release explicitly permits them.
75
+
76
+ ## Relationship to KittyLM
77
+
78
+ DATA LAB can produce reviewed methods and provenance records that KittyLM may use in the future.
79
+ It does not imply that KittyLM has an approved training dataset, completed data pipeline, or
80
+ published model weights.
81
+
82
+ ## Licence
83
+
84
+ The documentation, schemas, and original workflow code in this repository are proposed for release
85
+ under Apache-2.0. That licence does not apply to any third-party source described by a manifest.
86
+ Every source retains its own rights and restrictions.
docs/DATA_QUALITY.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data quality research plan
2
+
3
+ Quality is multidimensional and purpose-dependent. A single score must not replace the underlying
4
+ measurements or review decisions.
5
+
6
+ ## Required dimensions
7
+
8
+ | Dimension | Example evidence | Common failure |
9
+ |---|---|---|
10
+ | Integrity | content digest, byte count, decode errors | silent truncation or corruption |
11
+ | Duplication | exact and near-duplicate rates by source and split | evaluation leakage |
12
+ | Structure | parse success, field completeness, document boundaries | merged or fragmented records |
13
+ | Language | versioned detector plus manual sample | dialect and code-switch misclassification |
14
+ | Content quality | transparent heuristics and rejection counts | opaque quality score |
15
+ | Privacy | detector results plus human review | identifiers missed by automation |
16
+ | Safety | category definitions, sample review, subgroup counts | context-blind filtering |
17
+ | Coverage | domain, time, language, geography, and format distribution | hidden sampling bias |
18
+ | Contamination | train/eval overlap checks and hash strategy | benchmark memorisation |
19
+ | Reproducibility | fixed inputs, code revision, configuration, hashes | irreproducible `latest` snapshot |
20
+
21
+ ## Reporting rules
22
+
23
+ - Report absolute counts and rates.
24
+ - Break results down by source and split; aggregates can hide failures.
25
+ - Record every exclusion reason and overlapping filter count.
26
+ - Version detectors and thresholds, and retain calibration evidence.
27
+ - Use deterministic sampling for manual review and record the sampling method.
28
+ - Publish known blind spots and uncertainty.
29
+ - Never call a source clean, safe, representative, or unbiased without scoped evidence.
docs/EVALUATION.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluation resources and benchmark governance
2
+
3
+ Evaluation data requires the same provenance discipline as training data plus stronger controls
4
+ against contamination and answer leakage.
5
+
6
+ ## Resource record
7
+
8
+ For each benchmark or evaluation set, record:
9
+
10
+ - canonical repository, paper, version, revision, and licence;
11
+ - intended task, population, language, and domain;
12
+ - metric definitions, aggregation, uncertainty, and known limitations;
13
+ - access or gating terms and whether examples may be redistributed;
14
+ - contamination risk and separation controls;
15
+ - prompt, decoding, scoring, and harness versions;
16
+ - sample exclusions and failure-handling policy.
17
+
18
+ ## Evaluation rules
19
+
20
+ - Keep evaluation inputs out of training and prompt-development mixtures.
21
+ - Do not publish gated or leakage-sensitive examples in screenshots, logs, or documentation.
22
+ - Pin benchmark revisions and harness code.
23
+ - Prefer deterministic or independently auditable metrics.
24
+ - Report confidence intervals or run-to-run variation when stochasticity matters.
25
+ - Separate capability, safety, robustness, efficiency, and user-experience claims.
26
+ - Record failures and invalid runs; never silently discard them.
27
+ - Treat model-graded metrics as measurements from a named, versioned judge, not objective truth.
28
+
29
+ ## Example evaluation families
30
+
31
+ The research Collections nominate real external resources for study. Inclusion in a Collection is
32
+ not permission to copy, train on, redistribute, or reveal their contents. Their current licences,
33
+ gates, cards, and contamination guidance must be reviewed at the time of use.
docs/LICENSE_PRIVACY_CONSENT.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensing, privacy, and consent gate
2
+
3
+ This gate runs before preprocessing. Passing technical validation does not satisfy it.
4
+
5
+ ## Licensing review
6
+
7
+ - Identify the actual rights holder or authorised publisher.
8
+ - Save the exact licence text or canonical licence URL and reviewed version.
9
+ - Separate access permission, copying, transformation, training, redistribution, and commercial-use
10
+ permissions; they are not interchangeable.
11
+ - Record attribution, notice, share-alike, field-of-use, and deletion obligations.
12
+ - Check whether dataset terms conflict with licences embedded in individual records.
13
+ - Treat missing, custom, ambiguous, or conflicting terms as `pending` or `rejected`.
14
+
15
+ ## Privacy and sensitive-data review
16
+
17
+ - Determine whether records contain direct or indirect personal identifiers.
18
+ - Assess sensitive categories, vulnerable populations, private communications, and location data.
19
+ - Document collection context, reasonable expectations, retention, access controls, and deletion.
20
+ - Use data minimisation: retain only what is necessary for the approved research purpose.
21
+ - Test redaction and removal procedures, but do not treat automated detection as complete.
22
+ - Keep raw review material out of public repositories and logs.
23
+
24
+ ## Consent and lawful basis
25
+
26
+ Consent must be specific enough for the intended use, recorded, revocable where applicable, and
27
+ separable from mere public visibility. If another lawful basis is proposed, record the jurisdiction,
28
+ scope, reasoning, reviewer, and any required impact assessment. Legal uncertainty remains a stop
29
+ condition for publication.
30
+
31
+ ## Approval rule
32
+
33
+ A manifest may move to `approved` only when:
34
+
35
+ - all sources have `permission_status: approved`;
36
+ - privacy review is `passed`;
37
+ - consent or another documented lawful basis is non-empty;
38
+ - redistribution is explicitly allowed or the outputs are configured not to redistribute source
39
+ content;
40
+ - a named reviewer and UTC approval timestamp are present;
41
+ - unresolved notes contain no release-blocking issue.
42
+
43
+ The reference validator checks that these fields exist. It cannot determine whether the legal or
44
+ ethical judgment is correct.
docs/PROVENANCE.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Source provenance and lineage
2
+
3
+ Provenance is the evidence chain that explains what material was considered, where it came from,
4
+ which exact version was reviewed, what permission applies, how it was transformed, and why the
5
+ result is suitable for a stated research purpose.
6
+
7
+ ## Minimum source record
8
+
9
+ Every source must identify:
10
+
11
+ - a stable `source_id` and human-readable title;
12
+ - canonical publisher and HTTPS location;
13
+ - version, snapshot date, or immutable revision;
14
+ - retrieval time and SHA-256 digest of the reviewed local artifact;
15
+ - licence identifier, licence URL, and redistribution decision;
16
+ - privacy and sensitive-data review state;
17
+ - consent, contract, public-interest, or other applicable lawful basis;
18
+ - allowed purpose, restrictions, attribution, and retention requirements;
19
+ - reviewer identity, decision time, and review notes.
20
+
21
+ `unknown` and `pending` are valid research states. They are not approval states.
22
+
23
+ ## Lineage record
24
+
25
+ Each preprocessing run should bind:
26
+
27
+ 1. source-manifest digest;
28
+ 2. code repository revision;
29
+ 3. executable command and configuration;
30
+ 4. runtime and dependency versions;
31
+ 5. input and output digests;
32
+ 6. accepted, rejected, duplicate, and error counts;
33
+ 7. split assignment method and seed, if any;
34
+ 8. every filter with its version and decision rule;
35
+ 9. a sample-based manual review record;
36
+ 10. known limitations and unresolved risks.
37
+
38
+ ## Versioning rules
39
+
40
+ - Never overwrite a released manifest or processed artifact in place.
41
+ - Treat source changes, licence changes, filter changes, and split changes as new versions.
42
+ - Prefer immutable revisions and content digests over mutable `latest` URLs.
43
+ - Preserve withdrawal and correction records instead of erasing history.
44
+ - Record whether downstream deletion is possible when a source is withdrawn.
45
+
46
+ ## Evidence language
47
+
48
+ - **Verified** — directly observed and bound to evidence in the current review.
49
+ - **Proposed** — designed or nominated but not approved or executed.
50
+ - **Unknown** — required evidence is missing or cannot currently be established.
51
+ - **Rejected** — reviewed and not authorised for the stated purpose.
52
+ - **Withdrawn** — previously considered or approved, then removed from future use.
experiments/README.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Preprocessing experiment records
2
+
3
+ No preprocessing experiment has been executed or claimed by this repository package.
4
+
5
+ A future record must use an ID such as `DATA-EXP-0001` and contain:
6
+
7
+ - question and falsifiable hypothesis;
8
+ - approval state and source-manifest SHA-256;
9
+ - exact source and code revisions;
10
+ - command, configuration, Python/dependency versions, OS, and locale;
11
+ - input/output SHA-256 values;
12
+ - document, byte, character, token, duplicate, rejection, and error counts;
13
+ - filter order, thresholds, versions, and exclusion reasons;
14
+ - deterministic sampling and split method;
15
+ - privacy/licensing reviewer and decision reference;
16
+ - results, limitations, failures, and follow-up decision.
17
+
18
+ Do not edit a completed record to make a result look cleaner. Append a correction or create a new
19
+ experiment ID.
schemas/source-manifest.schema.json ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "urn:krazykitty:data-lab:source-manifest:1.0",
4
+ "title": "KRAZYKITTY DATA LAB source manifest",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": ["schema_version", "dataset_id", "decision", "sources"],
8
+ "properties": {
9
+ "schema_version": {"const": "1.0"},
10
+ "dataset_id": {"type": "string", "minLength": 1},
11
+ "decision": {
12
+ "type": "object",
13
+ "additionalProperties": false,
14
+ "required": ["status", "reviewed_by", "reviewed_at", "notes"],
15
+ "properties": {
16
+ "status": {"enum": ["proposed", "approved", "rejected", "withdrawn"]},
17
+ "reviewed_by": {"type": ["string", "null"]},
18
+ "reviewed_at": {"type": ["string", "null"], "format": "date-time"},
19
+ "notes": {"type": "array", "items": {"type": "string"}}
20
+ }
21
+ },
22
+ "sources": {
23
+ "type": "array",
24
+ "items": {
25
+ "type": "object",
26
+ "additionalProperties": false,
27
+ "required": [
28
+ "source_id",
29
+ "title",
30
+ "publisher",
31
+ "canonical_url",
32
+ "version",
33
+ "retrieved_at",
34
+ "content_path",
35
+ "sha256",
36
+ "license",
37
+ "privacy",
38
+ "use"
39
+ ],
40
+ "properties": {
41
+ "source_id": {"type": "string", "pattern": "^[a-z0-9][a-z0-9._-]*$"},
42
+ "title": {"type": "string", "minLength": 1},
43
+ "publisher": {"type": "string", "minLength": 1},
44
+ "canonical_url": {"type": "string", "format": "uri", "pattern": "^https://"},
45
+ "version": {"type": "string", "minLength": 1},
46
+ "retrieved_at": {"type": "string", "format": "date-time"},
47
+ "content_path": {"type": "string", "minLength": 1},
48
+ "sha256": {"type": "string", "pattern": "^[a-f0-9]{64}$"},
49
+ "license": {
50
+ "type": "object",
51
+ "additionalProperties": false,
52
+ "required": ["identifier", "url", "permission_status", "redistribution", "attribution"],
53
+ "properties": {
54
+ "identifier": {"type": "string", "minLength": 1},
55
+ "url": {"type": "string", "format": "uri", "pattern": "^https://"},
56
+ "permission_status": {"enum": ["pending", "approved", "rejected"]},
57
+ "redistribution": {"enum": ["allowed", "restricted", "prohibited", "unknown"]},
58
+ "attribution": {"type": "string"}
59
+ }
60
+ },
61
+ "privacy": {
62
+ "type": "object",
63
+ "additionalProperties": false,
64
+ "required": ["review_status", "contains_personal_data", "consent_or_lawful_basis", "notes"],
65
+ "properties": {
66
+ "review_status": {"enum": ["pending", "passed", "failed"]},
67
+ "contains_personal_data": {"type": ["boolean", "null"]},
68
+ "consent_or_lawful_basis": {"type": "string"},
69
+ "notes": {"type": "array", "items": {"type": "string"}}
70
+ }
71
+ },
72
+ "use": {
73
+ "type": "object",
74
+ "additionalProperties": false,
75
+ "required": ["purpose", "allowed", "restrictions"],
76
+ "properties": {
77
+ "purpose": {"type": "string", "minLength": 1},
78
+ "allowed": {"type": "boolean"},
79
+ "restrictions": {"type": "array", "items": {"type": "string"}}
80
+ }
81
+ }
82
+ }
83
+ }
84
+ }
85
+ }
86
+ }
templates/dataset-card-template.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: <reviewed-spdx-identifier-or-other>
3
+ pretty_name: <dataset-display-name>
4
+ language:
5
+ - <language-tag>
6
+ tags:
7
+ - <purpose-tag>
8
+ ---
9
+
10
+ # Dataset Card for `<dataset-id>`
11
+
12
+ > **Template only. Replace every angle-bracket field and remove this notice before release.**
13
+
14
+ ## Summary
15
+
16
+ - **Version:** `<immutable-version>`
17
+ - **Status:** `<proposed | approved-for-private-research | released | withdrawn>`
18
+ - **Maintainer:** `<responsible-owner>`
19
+ - **Canonical source manifest:** `<path-or-immutable-link-and-sha256>`
20
+ - **Release decision:** `<approval-record>`
21
+
22
+ Describe what the dataset contains and what evidence supports that description. Do not promote a
23
+ planned collection or processing pipeline into a released dataset claim.
24
+
25
+ ## Intended uses
26
+
27
+ ### Supported
28
+
29
+ - `<specific, evidence-backed research use>`
30
+
31
+ ### Out of scope
32
+
33
+ - `<use not evaluated or not permitted>`
34
+
35
+ ## Source data and provenance
36
+
37
+ For every source, provide the publisher, canonical URL, version/revision, retrieval date, integrity
38
+ digest, licence, permission scope, privacy review, consent or lawful basis, and transformation
39
+ lineage. Link to a machine-readable manifest without exposing private paths or source content.
40
+
41
+ ## Processing
42
+
43
+ Record the exact code revision, configuration, command, dependency lock, input/output hashes,
44
+ filter versions, exclusion counts, deduplication method, and split assignment.
45
+
46
+ ## Composition and splits
47
+
48
+ Report records, bytes, characters, tokens (with tokenizer version), languages, domains, time range,
49
+ formats, source mixture, missing values, duplicates, and rejection counts for every split.
50
+
51
+ ## Licensing, privacy, and consent
52
+
53
+ Explain the licence analysis, attribution, redistribution rights, privacy controls, sensitive-data
54
+ review, consent or other lawful basis, retention, withdrawal, and deletion process.
55
+
56
+ ## Quality and validation
57
+
58
+ Provide scoped measurements, manual-review sampling, contamination checks, known blind spots, and
59
+ unresolved issues. Avoid unsupported labels such as clean, safe, or representative.
60
+
61
+ ## Limitations and risks
62
+
63
+ Document sampling bias, detector limitations, temporal limits, language/domain gaps, harmful
64
+ content, privacy residuals, contamination risk, and inappropriate downstream uses.
65
+
66
+ ## Reproducibility
67
+
68
+ Provide immutable source, code, configuration, environment, and artifact identifiers sufficient for
69
+ an authorised reviewer to reproduce the release.
70
+
71
+ ## Changes and withdrawal
72
+
73
+ Maintain an append-only version history with corrections, removals, licence changes, and downstream
74
+ notification requirements.
templates/evaluation-card-template.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Evaluation Resource Card for `<resource-id>`
2
+
3
+ > **Template only. This file contains no benchmark examples or answers.**
4
+
5
+ ## Identity
6
+
7
+ - **Task:** `<task-definition>`
8
+ - **Version/revision:** `<immutable-id>`
9
+ - **Canonical repository and paper:** `<links>`
10
+ - **Licence and access terms:** `<reviewed-terms>`
11
+ - **Gating or leakage restrictions:** `<restrictions>`
12
+
13
+ ## Population and scope
14
+
15
+ Define languages, domains, time range, difficulty, participant or source population, and what the
16
+ resource does not measure.
17
+
18
+ ## Protocol
19
+
20
+ Pin prompts, tools, retrieval index, system policy, model/checkpoint, tokenizer, decoding,
21
+ environment, seeds, retries, timeouts, and scoring harness.
22
+
23
+ ## Metrics
24
+
25
+ For every metric, define inputs, formula, aggregation, uncertainty, invalid-run handling, and the
26
+ claim it can and cannot support.
27
+
28
+ ## Integrity and contamination
29
+
30
+ Document split separation, train/eval overlap checks, answer-access controls, test-set secrecy, and
31
+ how public traces or screenshots avoid revealing restricted examples.
32
+
33
+ ## Limitations
34
+
35
+ Document construct validity, annotation disagreement, judge bias, saturation, temporal drift,
36
+ contamination risk, subgroup gaps, and cost constraints.
37
+
38
+ ## Reporting checklist
39
+
40
+ - [ ] Exact revision and harness recorded
41
+ - [ ] Licence and gating terms rechecked
42
+ - [ ] No restricted example or answer exposed
43
+ - [ ] Invalid and failed runs counted
44
+ - [ ] Confidence or run-to-run variation reported where relevant
45
+ - [ ] Capability, safety, robustness, and efficiency reported separately
templates/source-manifest-template.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "1.0",
3
+ "dataset_id": "<proposed-dataset-id>@<version>",
4
+ "decision": {
5
+ "status": "proposed",
6
+ "reviewed_by": null,
7
+ "reviewed_at": null,
8
+ "notes": [
9
+ "Template only. This manifest does not describe or approve a real dataset."
10
+ ]
11
+ },
12
+ "sources": [
13
+ {
14
+ "source_id": "<stable-source-id>",
15
+ "title": "<source-title>",
16
+ "publisher": "<publisher-or-rights-holder>",
17
+ "canonical_url": "https://<canonical-source-location>",
18
+ "version": "<immutable-version-or-revision>",
19
+ "retrieved_at": "<UTC-RFC3339-timestamp>",
20
+ "content_path": "<relative-reviewed-file-path>",
21
+ "sha256": "<lowercase-sha256-of-reviewed-file>",
22
+ "license": {
23
+ "identifier": "<SPDX-or-reviewed-custom-identifier>",
24
+ "url": "https://<canonical-licence-location>",
25
+ "permission_status": "pending",
26
+ "redistribution": "unknown",
27
+ "attribution": "<required-attribution>"
28
+ },
29
+ "privacy": {
30
+ "review_status": "pending",
31
+ "contains_personal_data": null,
32
+ "consent_or_lawful_basis": "",
33
+ "notes": []
34
+ },
35
+ "use": {
36
+ "purpose": "<specific-research-purpose>",
37
+ "allowed": false,
38
+ "restrictions": []
39
+ }
40
+ }
41
+ ]
42
+ }
tests/test_workflows.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import sys
6
+ import tempfile
7
+ import unittest
8
+ from pathlib import Path
9
+
10
+ WORKFLOWS = Path(__file__).resolve().parents[1] / "workflows"
11
+ sys.path.insert(0, str(WORKFLOWS))
12
+
13
+ from preprocess_text import run_preprocessing # noqa: E402
14
+ from validate_manifest import validate_manifest # noqa: E402
15
+
16
+
17
+ def approved_manifest(content: bytes) -> dict[str, object]:
18
+ return {
19
+ "schema_version": "1.0",
20
+ "dataset_id": "synthetic-test@1",
21
+ "decision": {
22
+ "status": "approved",
23
+ "reviewed_by": "test-reviewer",
24
+ "reviewed_at": "2026-10-11T00:00:00Z",
25
+ "notes": ["Synthetic unit-test fixture only."],
26
+ },
27
+ "sources": [
28
+ {
29
+ "source_id": "synthetic-one",
30
+ "title": "Synthetic unit-test text",
31
+ "publisher": "DATA LAB tests",
32
+ "canonical_url": "https://example.invalid/synthetic-one",
33
+ "version": "1",
34
+ "retrieved_at": "2026-10-11T00:00:00Z",
35
+ "content_path": "input.txt",
36
+ "sha256": hashlib.sha256(content).hexdigest(),
37
+ "license": {
38
+ "identifier": "CC0-1.0",
39
+ "url": "https://creativecommons.org/publicdomain/zero/1.0/",
40
+ "permission_status": "approved",
41
+ "redistribution": "allowed",
42
+ "attribution": "",
43
+ },
44
+ "privacy": {
45
+ "review_status": "passed",
46
+ "contains_personal_data": False,
47
+ "consent_or_lawful_basis": "Synthetic text created by the test.",
48
+ "notes": [],
49
+ },
50
+ "use": {
51
+ "purpose": "Workflow unit test",
52
+ "allowed": True,
53
+ "restrictions": [],
54
+ },
55
+ }
56
+ ],
57
+ }
58
+
59
+
60
+ class ManifestTests(unittest.TestCase):
61
+ def test_approved_manifest_is_valid(self) -> None:
62
+ self.assertEqual(validate_manifest(approved_manifest(b"hello\n")), [])
63
+
64
+ def test_traversal_path_is_rejected(self) -> None:
65
+ manifest = approved_manifest(b"hello\n")
66
+ manifest["sources"][0]["content_path"] = "../outside.txt" # type: ignore[index]
67
+ self.assertTrue(any("safe" in error for error in validate_manifest(manifest)))
68
+
69
+ def test_approval_requires_privacy_gate(self) -> None:
70
+ manifest = approved_manifest(b"hello\n")
71
+ manifest["sources"][0]["privacy"]["review_status"] = "pending" # type: ignore[index]
72
+ self.assertTrue(any("privacy" in error for error in validate_manifest(manifest)))
73
+
74
+
75
+ class PreprocessingTests(unittest.TestCase):
76
+ def test_output_is_deterministic_and_contains_no_absolute_path(self) -> None:
77
+ content = "Synthetic text. \r\n\r\n\r\nSecond line.\r\n".encode()
78
+ with tempfile.TemporaryDirectory() as temp_dir:
79
+ root = Path(temp_dir)
80
+ input_root = root / "input"
81
+ input_root.mkdir()
82
+ (input_root / "input.txt").write_bytes(content)
83
+ manifest_path = root / "manifest.json"
84
+ manifest_path.write_text(json.dumps(approved_manifest(content)), encoding="utf-8")
85
+
86
+ report_a = run_preprocessing(manifest_path, input_root, root / "out-a")
87
+ report_b = run_preprocessing(manifest_path, input_root, root / "out-b")
88
+
89
+ records_a = (root / "out-a" / "records.jsonl").read_bytes()
90
+ records_b = (root / "out-b" / "records.jsonl").read_bytes()
91
+ self.assertEqual(records_a, records_b)
92
+ self.assertEqual(report_a, report_b)
93
+ self.assertNotIn(str(root).encode(), records_a)
94
+ self.assertEqual(report_a["counts"]["accepted_records"], 1)
95
+
96
+ def test_proposed_manifest_cannot_run(self) -> None:
97
+ content = b"synthetic\n"
98
+ with tempfile.TemporaryDirectory() as temp_dir:
99
+ root = Path(temp_dir)
100
+ input_root = root / "input"
101
+ input_root.mkdir()
102
+ (input_root / "input.txt").write_bytes(content)
103
+ manifest = approved_manifest(content)
104
+ manifest["decision"]["status"] = "proposed" # type: ignore[index]
105
+ manifest_path = root / "manifest.json"
106
+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
107
+ with self.assertRaisesRegex(ValueError, "approved"):
108
+ run_preprocessing(manifest_path, input_root, root / "out")
109
+
110
+
111
+ if __name__ == "__main__":
112
+ unittest.main()
workflows/preprocess_text.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run a deterministic, approval-gated reference text preprocessing experiment.
2
+
3
+ This tool is not a privacy scrubber, rights evaluator, or dataset release mechanism. It processes
4
+ only UTF-8 files explicitly named in an approved DATA LAB source manifest.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import hashlib
11
+ import json
12
+ import tempfile
13
+ import unicodedata
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from validate_manifest import load_manifest, validate_manifest
18
+
19
+
20
+ def sha256_bytes(value: bytes) -> str:
21
+ return hashlib.sha256(value).hexdigest()
22
+
23
+
24
+ def normalize_text(text: str, unicode_form: str) -> str:
25
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
26
+ if unicode_form != "none":
27
+ text = unicodedata.normalize(unicode_form, text)
28
+ lines = [line.rstrip() for line in text.split("\n")]
29
+ normalized: list[str] = []
30
+ blank_count = 0
31
+ for line in lines:
32
+ if line:
33
+ blank_count = 0
34
+ normalized.append(line)
35
+ else:
36
+ blank_count += 1
37
+ if blank_count <= 2:
38
+ normalized.append("")
39
+ return "\n".join(normalized).strip() + "\n"
40
+
41
+
42
+ def split_for_digest(digest: str) -> str:
43
+ bucket = int(digest[:8], 16) % 10_000
44
+ if bucket < 8_000:
45
+ return "train"
46
+ if bucket < 9_000:
47
+ return "validation"
48
+ return "test"
49
+
50
+
51
+ def _atomic_json(path: Path, value: Any) -> None:
52
+ path.parent.mkdir(parents=True, exist_ok=True)
53
+ with tempfile.NamedTemporaryFile(
54
+ "w", encoding="utf-8", dir=path.parent, delete=False, newline="\n"
55
+ ) as handle:
56
+ json.dump(value, handle, ensure_ascii=False, indent=2, sort_keys=True)
57
+ handle.write("\n")
58
+ temporary = Path(handle.name)
59
+ temporary.replace(path)
60
+
61
+
62
+ def _atomic_jsonl(path: Path, values: list[dict[str, Any]]) -> None:
63
+ path.parent.mkdir(parents=True, exist_ok=True)
64
+ with tempfile.NamedTemporaryFile(
65
+ "w", encoding="utf-8", dir=path.parent, delete=False, newline="\n"
66
+ ) as handle:
67
+ for value in values:
68
+ handle.write(json.dumps(value, ensure_ascii=False, sort_keys=True) + "\n")
69
+ temporary = Path(handle.name)
70
+ temporary.replace(path)
71
+
72
+
73
+ def run_preprocessing(
74
+ manifest_path: Path,
75
+ input_root: Path,
76
+ output_root: Path,
77
+ *,
78
+ unicode_form: str = "NFC",
79
+ min_characters: int = 1,
80
+ ) -> dict[str, Any]:
81
+ manifest_path = manifest_path.resolve()
82
+ input_root = input_root.resolve()
83
+ output_root = output_root.resolve()
84
+
85
+ manifest = load_manifest(manifest_path)
86
+ errors = validate_manifest(manifest)
87
+ if errors:
88
+ raise ValueError("manifest validation failed: " + "; ".join(errors))
89
+ if manifest["decision"]["status"] != "approved":
90
+ raise ValueError("preprocessing requires decision.status='approved'")
91
+ if output_root == input_root or output_root.is_relative_to(input_root):
92
+ raise ValueError("output directory must be outside the input directory")
93
+ if min_characters < 1:
94
+ raise ValueError("min_characters must be at least 1")
95
+
96
+ records: list[dict[str, Any]] = []
97
+ seen_content: set[str] = set()
98
+ rejected = {"duplicate": 0, "too_short": 0}
99
+ source_summaries: list[dict[str, Any]] = []
100
+
101
+ for source in sorted(manifest["sources"], key=lambda item: item["source_id"]):
102
+ relative_path = Path(*source["content_path"].split("/"))
103
+ candidate = input_root / relative_path
104
+ if candidate.is_symlink():
105
+ raise ValueError(f"symlink input is not allowed: {source['content_path']}")
106
+ resolved = candidate.resolve(strict=True)
107
+ if not resolved.is_relative_to(input_root):
108
+ raise ValueError(f"input escapes root: {source['content_path']}")
109
+ raw = resolved.read_bytes()
110
+ raw_digest = sha256_bytes(raw)
111
+ if raw_digest != source["sha256"]:
112
+ raise ValueError(f"SHA-256 mismatch for {source['source_id']}")
113
+ try:
114
+ text = raw.decode("utf-8", errors="strict")
115
+ except UnicodeDecodeError as exc:
116
+ raise ValueError(f"UTF-8 decode failed for {source['source_id']}: {exc}") from exc
117
+
118
+ normalized = normalize_text(text, unicode_form)
119
+ content_digest = sha256_bytes(normalized.encode("utf-8"))
120
+ if len(normalized.strip()) < min_characters:
121
+ rejected["too_short"] += 1
122
+ continue
123
+ if content_digest in seen_content:
124
+ rejected["duplicate"] += 1
125
+ continue
126
+ seen_content.add(content_digest)
127
+ record = {
128
+ "id": content_digest,
129
+ "source_id": source["source_id"],
130
+ "split": split_for_digest(content_digest),
131
+ "text": normalized,
132
+ }
133
+ records.append(record)
134
+ source_summaries.append(
135
+ {
136
+ "source_id": source["source_id"],
137
+ "input_sha256": raw_digest,
138
+ "output_sha256": content_digest,
139
+ "input_bytes": len(raw),
140
+ "output_characters": len(normalized),
141
+ "split": record["split"],
142
+ }
143
+ )
144
+
145
+ records.sort(key=lambda item: (item["source_id"], item["id"]))
146
+ manifest_digest = sha256_bytes(manifest_path.read_bytes())
147
+ report = {
148
+ "schema_version": "1.0",
149
+ "dataset_id": manifest["dataset_id"],
150
+ "manifest_sha256": manifest_digest,
151
+ "settings": {
152
+ "unicode_form": unicode_form,
153
+ "min_characters": min_characters,
154
+ "deduplication": "exact normalized UTF-8 SHA-256",
155
+ "split_assignment": "SHA-256 bucket 80/10/10",
156
+ },
157
+ "counts": {
158
+ "manifest_sources": len(manifest["sources"]),
159
+ "accepted_records": len(records),
160
+ "rejected_duplicate": rejected["duplicate"],
161
+ "rejected_too_short": rejected["too_short"],
162
+ },
163
+ "sources": source_summaries,
164
+ "warnings": [
165
+ "This reference workflow does not establish privacy, copyright, safety, or data quality."
166
+ ],
167
+ }
168
+ output_root.mkdir(parents=True, exist_ok=True)
169
+ _atomic_jsonl(output_root / "records.jsonl", records)
170
+ _atomic_json(output_root / "report.json", report)
171
+ return report
172
+
173
+
174
+ def main() -> int:
175
+ parser = argparse.ArgumentParser(description=__doc__)
176
+ parser.add_argument("--manifest", required=True, type=Path)
177
+ parser.add_argument("--input", required=True, type=Path, dest="input_root")
178
+ parser.add_argument("--output", required=True, type=Path, dest="output_root")
179
+ parser.add_argument("--unicode-form", choices=("none", "NFC", "NFKC"), default="NFC")
180
+ parser.add_argument("--min-characters", type=int, default=1)
181
+ args = parser.parse_args()
182
+
183
+ try:
184
+ report = run_preprocessing(
185
+ args.manifest,
186
+ args.input_root,
187
+ args.output_root,
188
+ unicode_form=args.unicode_form,
189
+ min_characters=args.min_characters,
190
+ )
191
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
192
+ print(f"FAILED: {exc}")
193
+ return 1
194
+
195
+ print(json.dumps(report["counts"], sort_keys=True))
196
+ return 0
197
+
198
+
199
+ if __name__ == "__main__":
200
+ raise SystemExit(main())
workflows/validate_manifest.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate a DATA LAB source manifest without external dependencies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import re
8
+ from datetime import datetime
9
+ from pathlib import Path, PurePosixPath
10
+ from typing import Any
11
+ from urllib.parse import urlparse
12
+
13
+ SHA256_RE = re.compile(r"^[a-f0-9]{64}$")
14
+ SOURCE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
15
+ DECISIONS = {"proposed", "approved", "rejected", "withdrawn"}
16
+ PERMISSIONS = {"pending", "approved", "rejected"}
17
+ REDISTRIBUTION = {"allowed", "restricted", "prohibited", "unknown"}
18
+ PRIVACY_STATES = {"pending", "passed", "failed"}
19
+
20
+
21
+ def _is_https(value: Any) -> bool:
22
+ if not isinstance(value, str):
23
+ return False
24
+ parsed = urlparse(value)
25
+ return parsed.scheme == "https" and bool(parsed.netloc)
26
+
27
+
28
+ def _is_utc_timestamp(value: Any) -> bool:
29
+ if not isinstance(value, str) or not value.endswith("Z"):
30
+ return False
31
+ try:
32
+ datetime.fromisoformat(value.removesuffix("Z") + "+00:00")
33
+ except ValueError:
34
+ return False
35
+ return True
36
+
37
+
38
+ def _is_safe_relative_path(value: Any) -> bool:
39
+ if not isinstance(value, str) or not value.strip() or "\\" in value:
40
+ return False
41
+ path = PurePosixPath(value)
42
+ return not path.is_absolute() and ".." not in path.parts and "." not in path.parts
43
+
44
+
45
+ def validate_manifest(data: Any) -> list[str]:
46
+ """Return human-readable validation errors; an empty list means valid."""
47
+ errors: list[str] = []
48
+ if not isinstance(data, dict):
49
+ return ["manifest root must be a JSON object"]
50
+
51
+ if data.get("schema_version") != "1.0":
52
+ errors.append("schema_version must be '1.0'")
53
+ if not isinstance(data.get("dataset_id"), str) or not data["dataset_id"].strip():
54
+ errors.append("dataset_id must be a non-empty string")
55
+
56
+ decision = data.get("decision")
57
+ if not isinstance(decision, dict):
58
+ errors.append("decision must be an object")
59
+ decision = {}
60
+ status = decision.get("status")
61
+ if status not in DECISIONS:
62
+ errors.append(f"decision.status must be one of {sorted(DECISIONS)}")
63
+ if not isinstance(decision.get("notes"), list) or not all(
64
+ isinstance(note, str) for note in decision.get("notes", [])
65
+ ):
66
+ errors.append("decision.notes must be an array of strings")
67
+ if status == "approved":
68
+ if not isinstance(decision.get("reviewed_by"), str) or not decision["reviewed_by"].strip():
69
+ errors.append("approved manifest requires decision.reviewed_by")
70
+ if not _is_utc_timestamp(decision.get("reviewed_at")):
71
+ errors.append("approved manifest requires a UTC decision.reviewed_at ending in Z")
72
+
73
+ sources = data.get("sources")
74
+ if not isinstance(sources, list):
75
+ errors.append("sources must be an array")
76
+ return errors
77
+
78
+ seen_ids: set[str] = set()
79
+ for index, source in enumerate(sources):
80
+ prefix = f"sources[{index}]"
81
+ if not isinstance(source, dict):
82
+ errors.append(f"{prefix} must be an object")
83
+ continue
84
+
85
+ source_id = source.get("source_id")
86
+ if not isinstance(source_id, str) or not SOURCE_ID_RE.fullmatch(source_id):
87
+ errors.append(f"{prefix}.source_id must use lowercase letters, digits, dot, underscore, or hyphen")
88
+ elif source_id in seen_ids:
89
+ errors.append(f"{prefix}.source_id is duplicated: {source_id}")
90
+ else:
91
+ seen_ids.add(source_id)
92
+
93
+ for field in ("title", "publisher", "version"):
94
+ if not isinstance(source.get(field), str) or not source[field].strip():
95
+ errors.append(f"{prefix}.{field} must be a non-empty string")
96
+ if not _is_https(source.get("canonical_url")):
97
+ errors.append(f"{prefix}.canonical_url must be an HTTPS URL")
98
+ if not _is_utc_timestamp(source.get("retrieved_at")):
99
+ errors.append(f"{prefix}.retrieved_at must be a UTC timestamp ending in Z")
100
+ if not _is_safe_relative_path(source.get("content_path")):
101
+ errors.append(f"{prefix}.content_path must be a safe POSIX-style relative path")
102
+ if not isinstance(source.get("sha256"), str) or not SHA256_RE.fullmatch(source["sha256"]):
103
+ errors.append(f"{prefix}.sha256 must be a lowercase 64-character SHA-256 digest")
104
+
105
+ licence = source.get("license")
106
+ if not isinstance(licence, dict):
107
+ errors.append(f"{prefix}.license must be an object")
108
+ licence = {}
109
+ if not isinstance(licence.get("identifier"), str) or not licence["identifier"].strip():
110
+ errors.append(f"{prefix}.license.identifier must be non-empty")
111
+ if not _is_https(licence.get("url")):
112
+ errors.append(f"{prefix}.license.url must be an HTTPS URL")
113
+ if licence.get("permission_status") not in PERMISSIONS:
114
+ errors.append(f"{prefix}.license.permission_status is invalid")
115
+ if licence.get("redistribution") not in REDISTRIBUTION:
116
+ errors.append(f"{prefix}.license.redistribution is invalid")
117
+
118
+ privacy = source.get("privacy")
119
+ if not isinstance(privacy, dict):
120
+ errors.append(f"{prefix}.privacy must be an object")
121
+ privacy = {}
122
+ if privacy.get("review_status") not in PRIVACY_STATES:
123
+ errors.append(f"{prefix}.privacy.review_status is invalid")
124
+ if privacy.get("contains_personal_data") not in (True, False, None):
125
+ errors.append(f"{prefix}.privacy.contains_personal_data must be true, false, or null")
126
+ if not isinstance(privacy.get("notes"), list) or not all(
127
+ isinstance(note, str) for note in privacy.get("notes", [])
128
+ ):
129
+ errors.append(f"{prefix}.privacy.notes must be an array of strings")
130
+
131
+ use = source.get("use")
132
+ if not isinstance(use, dict):
133
+ errors.append(f"{prefix}.use must be an object")
134
+ use = {}
135
+ if not isinstance(use.get("purpose"), str) or not use["purpose"].strip():
136
+ errors.append(f"{prefix}.use.purpose must be non-empty")
137
+ if not isinstance(use.get("allowed"), bool):
138
+ errors.append(f"{prefix}.use.allowed must be a boolean")
139
+ if not isinstance(use.get("restrictions"), list) or not all(
140
+ isinstance(item, str) for item in use.get("restrictions", [])
141
+ ):
142
+ errors.append(f"{prefix}.use.restrictions must be an array of strings")
143
+
144
+ if status == "approved":
145
+ if licence.get("permission_status") != "approved":
146
+ errors.append(f"{prefix} is not approved by the licensing review")
147
+ if privacy.get("review_status") != "passed":
148
+ errors.append(f"{prefix} has not passed privacy review")
149
+ if not isinstance(privacy.get("consent_or_lawful_basis"), str) or not privacy[
150
+ "consent_or_lawful_basis"
151
+ ].strip():
152
+ errors.append(f"{prefix} lacks consent or another documented lawful basis")
153
+ if use.get("allowed") is not True:
154
+ errors.append(f"{prefix}.use.allowed must be true for an approved manifest")
155
+
156
+ return errors
157
+
158
+
159
+ def load_manifest(path: Path) -> dict[str, Any]:
160
+ data = json.loads(path.read_text(encoding="utf-8"))
161
+ if not isinstance(data, dict):
162
+ raise ValueError("manifest root must be an object")
163
+ return data
164
+
165
+
166
+ def main() -> int:
167
+ parser = argparse.ArgumentParser(description=__doc__)
168
+ parser.add_argument("manifest", type=Path)
169
+ args = parser.parse_args()
170
+
171
+ try:
172
+ data = load_manifest(args.manifest)
173
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
174
+ print(f"INVALID: {exc}")
175
+ return 2
176
+
177
+ errors = validate_manifest(data)
178
+ if errors:
179
+ print("INVALID")
180
+ for error in errors:
181
+ print(f"- {error}")
182
+ return 1
183
+
184
+ print(f"VALID: {data['dataset_id']} ({data['decision']['status']})")
185
+ return 0
186
+
187
+
188
+ if __name__ == "__main__":
189
+ raise SystemExit(main())