From a959f5ea2f9fed3b42eaab312a68b4de65f0dfb0 Mon Sep 17 00:00:00 2001 From: Scott Converse Date: Sun, 22 Nov 2026 10:34:57 -0700 Subject: [PATCH] Build reviewed contracts dataset artifacts for Townlight --- .github/workflows/verify.yml | 14 +- README.md | 16 +- README.txt | 16 +- USER-MANUAL.md | 12 +- USER-MANUAL.txt | 8 +- civicdata/__init__.py | 3 - docs/index.html | 6 +- pyproject.toml | 10 +- .../check-civiccore-placeholder-imports.py | 2 +- scripts/verify-docs.sh | 4 +- scripts/verify-release.sh | 12 +- tests/test_civicdata_foundation.py | 16 +- ...roduction_depth_publication_persistence.py | 4 +- tests/test_public_dataset.py | 96 +++++++++++ tests/test_runtime_foundation.py | 12 +- townlight_data/__init__.py | 3 + .../archive_bundle.py | 0 {civicdata => townlight_data}/ckan_package.py | 4 +- .../data_dictionary.py | 2 +- .../dataset_normalization.py | 0 {civicdata => townlight_data}/main.py | 22 +-- {civicdata => townlight_data}/persistence.py | 4 +- townlight_data/public_dataset.py | 157 ++++++++++++++++++ {civicdata => townlight_data}/public_ui.py | 8 +- .../publication_plan.py | 0 .../redaction_review.py | 0 26 files changed, 354 insertions(+), 77 deletions(-) delete mode 100644 civicdata/__init__.py create mode 100644 tests/test_public_dataset.py create mode 100644 townlight_data/__init__.py rename {civicdata => townlight_data}/archive_bundle.py (100%) rename {civicdata => townlight_data}/ckan_package.py (90%) rename {civicdata => townlight_data}/data_dictionary.py (93%) rename {civicdata => townlight_data}/dataset_normalization.py (100%) rename {civicdata => townlight_data}/main.py (93%) rename {civicdata => townlight_data}/persistence.py (98%) create mode 100644 townlight_data/public_dataset.py rename {civicdata => townlight_data}/public_ui.py (89%) rename {civicdata => townlight_data}/publication_plan.py (100%) rename {civicdata => townlight_data}/redaction_review.py (100%) diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 4d3967d..c90bf47 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -46,15 +46,23 @@ jobs: verify: needs: changes if: needs.changes.outputs.code == 'true' - runs-on: ubuntu-latest + runs-on: windows-latest steps: - uses: actions/checkout@v5 - uses: actions/setup-python@v6 with: python-version: '3.11' - - name: Install CivicCore release wheel - run: python -m pip install https://github.com/CivicSuite/civiccore/releases/download/v0.4.0/civiccore-0.4.0-py3-none-any.whl + - name: Checkout townlight/core + uses: actions/checkout@v5 + with: + repository: townlight/core + ref: 2f6ba9be4a95e3772dc47a3682ac780c5283b626 + path: townlight-core-source + persist-credentials: false + - name: Install townlight core + run: python -m pip install --no-deps ./townlight-core-source - name: Install package run: python -m pip install -e ".[dev]" - name: Run release gate + shell: bash run: bash scripts/verify-release.sh diff --git a/README.md b/README.md index c02f437..1683eb8 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,16 @@ -> **Parked foundation — outside the released Windows suite.** This repository contains exploratory/support code, not a completed Townlight product. It is not installed or supported by Windows 1.8.1.1. Historical examples, package names and dependency pins below describe this foundation and must not be used as current suite installation instructions. Use the [released Windows suite, current modules and acceptance limits](https://townlight.github.io/versions.html). +> Townlight Data 0.2.0 targets the next Windows candidate. Windows 1.9.2.1 does not include Data. # Townlight Data -Townlight Data is the Townlight open-data preparation module. Version 0.1.2 ships the local package, FastAPI runtime, deterministic helper functions, optional database-backed publication workpapers, bearer-token protection for persisted retrieval, tests, release gates, public documentation, and browser-verified sample UI for preparing municipal datasets before human-approved publication. +Townlight Data is the Townlight open-data preparation module. Version 0.2.0 ships the local package, FastAPI runtime, deterministic helper functions, optional database-backed publication workpapers, bearer-token protection for persisted retrieval, tests, release gates, public documentation, and browser-verified sample UI for preparing municipal datasets before human-approved publication. -## Shipping in v0.1.2 +## Windows staff workflow + +In Townlight Data 0.2.0 candidate on Windows Suite full profile, existing Contracts grants let staff select signed agreements and preview only contract ID, title, vendor, start/expiration. An admin explicitly confirms the actual SHA-256 preview before an unattended queue sends to the configured resident Portal. Status states cover selection, hash confirmation, queueing, acknowledgement, correction, and withdrawal. No public link appears until the receiving portal acknowledges. Public outputs include CSV, JSON, and dictionary. Corrections proceed through a new review; withdrawal removes anonymous downloads when delivered. Legacy standalone workpaper APIs remain separate. + +## Standalone workpapers - Dataset field normalization for CKAN-friendly names, date/time hints, and geospatial-review notes. - Data-dictionary draft generation from source schema metadata. @@ -25,17 +29,17 @@ Townlight Data is the Townlight open-data preparation module. Version 0.1.2 ship - Data warehouse storage or long-term operational data storage beyond archive-bundle planning. - Autonomous redaction or automatic exemption decisions. - External connector runtime, approval queues, or Townlight Records exemption-engine integration. -- Staff SSO and role-based publication approvals. v0.1.2 protects persisted retrieval only; broader workflow auth comes later. +- Staff SSO and role-based publication approvals. v0.2.0 protects persisted retrieval only; broader workflow auth comes later. ## Install and run locally -Townlight Data v0.1.2 is pinned to `civiccore==0.4.0`. +Townlight Data v0.2.0 is pinned to `townlight-core==1.3.0.dev2`. ```bash python -m venv .venv . .venv/Scripts/activate # Windows PowerShell: .venv\Scripts\Activate.ps1 python -m pip install -e ".[dev]" -python -m uvicorn civicdata.main:app --host 127.0.0.1 --port 8137 +python -m uvicorn townlight_data.main:app --host 127.0.0.1 --port 8137 ``` Open `http://127.0.0.1:8137/civicdata` for the browser sample and `http://127.0.0.1:8137/docs` for FastAPI docs. diff --git a/README.txt b/README.txt index 978001b..8f09e81 100644 --- a/README.txt +++ b/README.txt @@ -1,10 +1,10 @@ - Parked foundation — outside the released Windows suite. This repository contains exploratory/support code, not a completed Townlight product. It is not installed or supported by Windows 1.8.1.1. Historical examples, package names and dependency pins below describe this foundation and must not be used as current suite installation instructions. Use the released Windows suite, current modules and acceptance limits. +Townlight Data 0.2.0 targets the next Windows candidate. Windows 1.9.2.1 does not include Data. Townlight Data -Townlight Data is the Townlight open-data preparation module. Version 0.1.2 ships the local package, FastAPI runtime, deterministic helper functions, optional database-backed publication workpapers, bearer-token protection for persisted retrieval, tests, release gates, public documentation, and browser-verified sample UI for preparing municipal datasets before human-approved publication. +Townlight Data is the Townlight open-data preparation module. Version 0.2.0 ships the local package, FastAPI runtime, deterministic helper functions, optional database-backed publication workpapers, bearer-token protection for persisted retrieval, tests, release gates, public documentation, and browser-verified sample UI for preparing municipal datasets before human-approved publication. -Shipping in v0.1.2 +Shipping in v0.2.0 - Dataset field normalization for CKAN-friendly names, date/time hints, and geospatial-review notes. - Data-dictionary draft generation from source schema metadata. @@ -23,16 +23,16 @@ Not shipped yet - Data warehouse storage or long-term operational data storage beyond archive-bundle planning. - Autonomous redaction or automatic exemption decisions. - External connector runtime, approval queues, or Townlight Records exemption-engine integration. -- Staff SSO and role-based publication approvals. v0.1.2 protects persisted retrieval only; broader workflow auth comes later. +- Staff SSO and role-based publication approvals. v0.2.0 protects persisted retrieval only; broader workflow auth comes later. Install and run locally -Townlight Data v0.1.2 is pinned to civiccore==0.4.0. +Townlight Data v0.2.0 is pinned to townlight-core==1.3.0.dev2. python -m venv .venv . .venv/Scripts/activate # Windows PowerShell: .venv\Scripts\Activate.ps1 python -m pip install -e ".[dev]" - python -m uvicorn civicdata.main:app --host 127.0.0.1 --port 8137 + python -m uvicorn townlight_data.main:app --host 127.0.0.1 --port 8137 Open http://127.0.0.1:8137/civicdata for the browser sample and http://127.0.0.1:8137/docs for FastAPI docs. @@ -63,3 +63,7 @@ Verification Licensing Code: AGPL-3.0-only, with the TownLight Public Institution Exception for qualifying deployments. See LICENSE and LICENSE-EXCEPTION.md. Documentation is CC BY 4.0 unless otherwise noted. Townlight Data is designed for local municipal operation and does not require outbound runtime calls in the default profile. + +Windows staff workflow + +In Townlight Data 0.2.0 candidate on Windows Suite full profile, existing Contracts grants let staff select signed agreements and preview only contract ID, title, vendor, start/expiration. An admin explicitly confirms the actual SHA-256 preview before an unattended queue sends to the configured resident Portal. Status states cover selection, hash confirmation, queueing, acknowledgement, correction, and withdrawal. No public link appears until the receiving portal acknowledges. Public outputs include CSV, JSON, and dictionary. Corrections proceed through a new review; withdrawal removes anonymous downloads when delivered. Legacy standalone workpaper APIs remain separate. diff --git a/USER-MANUAL.md b/USER-MANUAL.md index c7a6e24..59da5b2 100644 --- a/USER-MANUAL.md +++ b/USER-MANUAL.md @@ -20,7 +20,7 @@ Townlight Data helps a city prepare datasets before they are published to an ope Every dataset still needs staff approval before publication. Staff must confirm the source-system owner, redaction/exemption status, open-data license, retention schedule, and publication target. -### What v0.1.2 does not do +### What v0.2.0 does not do Townlight Data does not publish directly to CKAN, does not host dashboards, does not store a data warehouse, does not make legal exemption decisions, and does not redact records automatically. @@ -28,7 +28,7 @@ Townlight Data does not publish directly to CKAN, does not host dashboards, does ### Runtime -Install with `python -m pip install -e ".[dev]"` and run with `python -m uvicorn civicdata.main:app --host 127.0.0.1 --port 8137`. +Install with `python -m pip install -e ".[dev]"` and run with `python -m uvicorn townlight_data.main:app --host 127.0.0.1 --port 8137`. Set `CIVICDATA_PUBLICATION_DB_URL` to enable SQLAlchemy-backed CKAN package draft and publication-plan records. Set `CIVICDATA_AUTH_TOKEN_ROLES` to a JSON token-to-role map before exposing persisted retrieval. Leave the database variable unset for deterministic stateless operation. @@ -48,12 +48,16 @@ flowchart LR ### Endpoints -The public endpoints are listed in `README.md`. All v0.1.2 endpoints are deterministic and local. They do not perform live connector calls or publish data to external services. Retrieval endpoints require both `CIVICDATA_PUBLICATION_DB_URL` and `CIVICDATA_AUTH_TOKEN_ROLES`. +The public endpoints are listed in `README.md`. All v0.2.0 endpoints are deterministic and local. They do not perform live connector calls or publish data to external services. Retrieval endpoints require both `CIVICDATA_PUBLICATION_DB_URL` and `CIVICDATA_AUTH_TOKEN_ROLES`. ### Dependency contract -Townlight Data depends on `civiccore==0.4.0`. Townlight Core must not import Townlight Data Bridge. +Townlight Data depends on `townlight-core==1.3.0.dev2`. Townlight Core must not import Townlight Data Bridge. ### Verification Run `bash scripts/verify-release.sh` before release. The script checks docs, tests, Ruff, build artifacts, and package metadata. + +## Windows staff workflow + +In Townlight Data 0.2.0 candidate on Windows Suite full profile, existing Contracts grants let staff select signed agreements and preview only contract ID, title, vendor, start/expiration. An admin explicitly confirms the actual SHA-256 preview before an unattended queue sends to the configured resident Portal. Status states cover selection, hash confirmation, queueing, acknowledgement, correction, and withdrawal. No public link appears until the receiving portal acknowledges. Public outputs include CSV, JSON, and dictionary. Corrections proceed through a new review; withdrawal removes anonymous downloads when delivered. Legacy standalone workpaper APIs remain separate. diff --git a/USER-MANUAL.txt b/USER-MANUAL.txt index c39c1a9..985cc59 100644 --- a/USER-MANUAL.txt +++ b/USER-MANUAL.txt @@ -2,6 +2,10 @@ Townlight Data User Manual For staff: Townlight Data prepares municipal datasets for open-data review. It normalizes fields, drafts data dictionaries, prepares CKAN package metadata, flags possible PII/exempt fields, creates archive/publication checklists, and optionally retrieves saved CKAN package/publication-plan workpapers. -Staff must approve every dataset before publication. v0.1.2 does not publish to CKAN, host dashboards, store a data warehouse, redact automatically, or make exemption decisions. +Staff must approve every dataset before publication. v0.2.0 does not publish to CKAN, host dashboards, store a data warehouse, redact automatically, or make exemption decisions. -For IT: install with python -m pip install -e ".[dev]" and run with python -m uvicorn civicdata.main:app --host 127.0.0.1 --port 8137. The package depends on civiccore==0.4.0 and runs locally. Set CIVICDATA_PUBLICATION_DB_URL to enable SQLAlchemy-backed CKAN package draft and publication-plan records. Set CIVICDATA_AUTH_TOKEN_ROLES to a JSON token-to-role map before exposing persisted retrieval. Leave the database variable unset for deterministic stateless operation. +For IT: install with python -m pip install -e ".[dev]" and run with python -m uvicorn townlight_data.main:app --host 127.0.0.1 --port 8137. The package depends on townlight-core==1.3.0.dev2 and runs locally. Set CIVICDATA_PUBLICATION_DB_URL to enable SQLAlchemy-backed CKAN package draft and publication-plan records. Set CIVICDATA_AUTH_TOKEN_ROLES to a JSON token-to-role map before exposing persisted retrieval. Leave the database variable unset for deterministic stateless operation. + +Windows staff workflow + +In Townlight Data 0.2.0 candidate on Windows Suite full profile, existing Contracts grants let staff select signed agreements and preview only contract ID, title, vendor, start/expiration. An admin explicitly confirms the actual SHA-256 preview before an unattended queue sends to the configured resident Portal. Status states cover selection, hash confirmation, queueing, acknowledgement, correction, and withdrawal. No public link appears until the receiving portal acknowledges. Public outputs include CSV, JSON, and dictionary. Corrections proceed through a new review; withdrawal removes anonymous downloads when delivered. Legacy standalone workpaper APIs remain separate. diff --git a/civicdata/__init__.py b/civicdata/__init__.py deleted file mode 100644 index e0060f7..0000000 --- a/civicdata/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Townlight Data v0.1.2 public package.""" - -__version__ = "0.1.2" diff --git a/docs/index.html b/docs/index.html index 9553a3b..50b0908 100644 --- a/docs/index.html +++ b/docs/index.html @@ -3,14 +3,14 @@ -Townlight Data v0.1.2 +Townlight Data v0.2.0 -

Townlight module

Townlight Data

Open-data preparation for municipalities: normalize fields, draft dictionaries, prepare CKAN metadata, persist optional publication workpapers, protect persisted retrieval with bearer roles, flag redaction review, and assemble retention-aware archive checklists.

v0.1.2 shipping

-

For staff

Use Townlight Data to prepare datasets before publication. Every dataset still needs human review, license confirmation, redaction or exemption clearance, and retention checks.

For IT

Install locally with python -m pip install -e ".[dev]", run python -m uvicorn civicdata.main:app, set CIVICDATA_PUBLICATION_DB_URL for optional persistence, and set CIVICDATA_AUTH_TOKEN_ROLES before exposing persisted retrieval.

Boundaries

No live CKAN publication, BI dashboard, data warehouse, autonomous redaction, or connector runtime ships in v0.1.2.

Dependency

Pinned to civiccore==0.4.0. Townlight Core remains dependency-only; it never imports Townlight Data Bridge.

+

Townlight module

Townlight Data

Open-data preparation for municipalities: normalize fields, draft dictionaries, prepare CKAN metadata, persist optional publication workpapers, protect persisted retrieval with bearer roles, flag redaction review, and assemble retention-aware archive checklists.

0.2.0 Windows candidate

+

For staff

Use Townlight Data to prepare datasets before publication. Every dataset still needs human review, license confirmation, redaction or exemption clearance, and retention checks.

For IT

Install locally with python -m pip install -e ".[dev]", run python -m uvicorn townlight_data.main:app, set CIVICDATA_PUBLICATION_DB_URL for optional persistence, and set CIVICDATA_AUTH_TOKEN_ROLES before exposing persisted retrieval.

Boundaries

No live CKAN publication, BI dashboard, data warehouse, autonomous redaction, or connector runtime ships in v0.2.0.

Dependency

Pinned to townlight-core==1.3.0.dev2. Townlight Core remains dependency-only; it never imports Townlight Data Bridge.

diff --git a/pyproject.toml b/pyproject.toml index 328f432..216a36e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,8 +3,8 @@ requires = ["hatchling>=1.27.0"] build-backend = "hatchling.build" [project] -name = "civicdata" -version = "0.1.2" +name = "townlight-data" +version = "0.2.0" description = "Townlight Data foundation for open-data normalization, CKAN package drafts, archive bundles, and redaction review." readme = "README.md" requires-python = ">=3.11" @@ -13,7 +13,7 @@ authors = [ { name = "CivicSuite contributors" } ] dependencies = [ - "civiccore==0.4.0", + "townlight-core==1.3.0.dev2", "fastapi>=0.115.0,<1.0.0", "sqlalchemy>=2.0.0,<3.0.0", "uvicorn[standard]>=0.30.0,<1.0.0", @@ -32,11 +32,11 @@ dev = [ testpaths = ["tests"] [tool.hatch.build.targets.wheel] -packages = ["civicdata"] +packages = ["townlight_data"] [tool.hatch.build.targets.sdist] include = [ - "civicdata", + "townlight_data", "scripts", "tests", "README.md", diff --git a/scripts/check-civiccore-placeholder-imports.py b/scripts/check-civiccore-placeholder-imports.py index f57ffe6..706a2ff 100644 --- a/scripts/check-civiccore-placeholder-imports.py +++ b/scripts/check-civiccore-placeholder-imports.py @@ -14,7 +14,7 @@ "search", "verification", ) -SOURCE_ROOT = Path("civicdata") +SOURCE_ROOT = Path("townlight_data") pattern = re.compile(r"^\s*(?:from|import)\s+civiccore\.(" + "|".join(PLACEHOLDERS) + r")\b") violations: list[str] = [] for path in SOURCE_ROOT.rglob("*.py"): diff --git a/scripts/verify-docs.sh b/scripts/verify-docs.sh index b2e678a..9d16e8f 100644 --- a/scripts/verify-docs.sh +++ b/scripts/verify-docs.sh @@ -45,8 +45,8 @@ for file in "${current_files[@]}"; do done done -if ! grep -Fq "civiccore==0.4.0" README.md; then - echo "VERIFY-DOCS: FAILED README.md must mention civiccore==0.4.0" +if ! grep -Fq "townlight-core==1.3.0.dev2" README.md; then + echo "VERIFY-DOCS: FAILED README.md must mention townlight-core==1.3.0.dev2" exit 1 fi if ! grep -Fq "No live CKAN publication" docs/index.html; then diff --git a/scripts/verify-release.sh b/scripts/verify-release.sh index 6986b57..1660b10 100644 --- a/scripts/verify-release.sh +++ b/scripts/verify-release.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -echo "VERIFY-RELEASE: CivicData Bridge v0.1.2" +echo "VERIFY-RELEASE: Townlight Data v0.2.0" PYTHON_CANDIDATES=() if [[ -n "${CIVICDATA_RELEASE_PYTHON:-}" ]]; then @@ -29,13 +29,13 @@ echo "[INFO] python: $PYTHON_BIN" bash scripts/verify-docs.sh "$PYTHON_BIN" scripts/check-civiccore-placeholder-imports.py "$PYTHON_BIN" -m pytest -q -"$PYTHON_BIN" -m ruff check . +"$PYTHON_BIN" -m ruff check townlight_data scripts tests rm -rf dist "$PYTHON_BIN" -m build "$PYTHON_BIN" - <<'PY' from pathlib import Path import hashlib -expected = {"civicdata-0.1.2-py3-none-any.whl", "civicdata-0.1.2.tar.gz"} +expected = {"townlight_data-0.2.0-py3-none-any.whl", "townlight_data-0.2.0.tar.gz"} dist = Path("dist") found = {p.name for p in dist.iterdir() if p.is_file()} missing = expected - found @@ -49,9 +49,9 @@ for name in sorted(expected): print("[PASS] build artifacts and SHA256SUMS") PY "$PYTHON_BIN" - <<'PY' -import civicdata -assert civicdata.__version__ == "0.1.2" -print("[PASS] package version 0.1.2") +import townlight_data +assert townlight_data.__version__ == "0.2.0" +print("[PASS] package version 0.2.0") PY echo "VERIFY-RELEASE: PASSED" diff --git a/tests/test_civicdata_foundation.py b/tests/test_civicdata_foundation.py index 2e047a3..0e49549 100644 --- a/tests/test_civicdata_foundation.py +++ b/tests/test_civicdata_foundation.py @@ -1,14 +1,14 @@ -from civicdata import __version__ -from civicdata.archive_bundle import create_archive_bundle_plan -from civicdata.ckan_package import build_ckan_package_draft -from civicdata.data_dictionary import draft_data_dictionary -from civicdata.dataset_normalization import normalize_field_name, normalize_schema_fields -from civicdata.publication_plan import draft_publication_plan -from civicdata.redaction_review import review_fields_for_publication +from townlight_data import __version__ +from townlight_data.archive_bundle import create_archive_bundle_plan +from townlight_data.ckan_package import build_ckan_package_draft +from townlight_data.data_dictionary import draft_data_dictionary +from townlight_data.dataset_normalization import normalize_field_name, normalize_schema_fields +from townlight_data.publication_plan import draft_publication_plan +from townlight_data.redaction_review import review_fields_for_publication def test_version_is_release_version(): - assert __version__ == "0.1.2" + assert __version__ == "0.2.0" def test_normalize_field_names_and_notes_dates_geospatial_fields(): diff --git a/tests/test_production_depth_publication_persistence.py b/tests/test_production_depth_publication_persistence.py index 281b3eb..39c2f4e 100644 --- a/tests/test_production_depth_publication_persistence.py +++ b/tests/test_production_depth_publication_persistence.py @@ -4,8 +4,8 @@ from fastapi.testclient import TestClient -from civicdata.main import app, _dispose_publication_repository -from civicdata.persistence import PublicationWorkpaperRepository +from townlight_data.main import app, _dispose_publication_repository +from townlight_data.persistence import PublicationWorkpaperRepository client = TestClient(app) diff --git a/tests/test_public_dataset.py b/tests/test_public_dataset.py new file mode 100644 index 0000000..2d106f9 --- /dev/null +++ b/tests/test_public_dataset.py @@ -0,0 +1,96 @@ +import csv +import io +import json + +import pytest + +from townlight_data.public_dataset import PublicField, build_public_dataset + + +def _fields(): + return [ + PublicField(name="id", data_type="integer", description="Row identifier"), + PublicField(name="name", data_type="text", description="Display name"), + ] + + +def test_deterministic_csv_and_json_with_unicode_quoting(): + fields = _fields() + rows = [ + {"id": 1, "name": "Zoë, Jr."}, + {"id": 2, "name": "李雷"}, + ] + first = build_public_dataset(fields, rows) + second = build_public_dataset(fields, rows) + + assert first["dataset.csv"] == second["dataset.csv"] + assert first["dataset.json"] == second["dataset.json"] + + csv_bytes = first["dataset.csv"] + assert isinstance(csv_bytes, bytes) + # Comma-containing unicode value must be quoted (and preserved verbatim). + assert b'"Zo\xc3\xab, Jr."' in csv_bytes + + parsed = list(csv.DictReader(io.StringIO(csv_bytes.decode("utf-8")))) + assert [row["name"] for row in parsed] == ["Zoë, Jr.", "李雷"] + assert [row["id"] for row in parsed] == ["1", "2"] + + json_rows = json.loads(first["dataset.json"]) + assert [row["name"] for row in json_rows] == ["Zoë, Jr.", "李雷"] + + +def test_allowlist_filters_private_fields_and_dictionary_records_source(): + fields = _fields() + rows = [{"id": 7, "name": "Ada", "secret": "top-secret", "email": "a@b.c"}] + + out = build_public_dataset(fields, rows) + csv_bytes = out["dataset.csv"] + json_bytes = out["dataset.json"] + + for token in (b"secret", b"top-secret", b"a@b.c"): + assert token not in csv_bytes + assert token not in json_bytes + + dictionary = json.loads(out["data-dictionary.json"]) + assert isinstance(dictionary, list) + by_name = {entry["field_name"]: entry for entry in dictionary} + assert set(by_name) == {field.name for field in fields} + for field in fields: + entry = by_name[field.name] + assert set(entry.keys()) == { + "field_name", + "source_name", + "data_type", + "description", + "publication_notes", + } + assert entry["field_name"] == field.name + assert entry["data_type"] == field.data_type + assert entry["description"] == field.description + + +def test_rejects_formula_prefixes_and_embedded_cr(): + fields = [PublicField(name="label", data_type="text", description="Label")] + + for bad_value in ("=cmd", "+cmd", "-cmd", "@cmd"): + with pytest.raises(ValueError): + build_public_dataset(fields, [{"label": bad_value}]) + + with pytest.raises(ValueError): + build_public_dataset(fields, [{"label": "line1\rline2"}]) + + +def test_rejects_email_field_bool_integer_and_malformed_date(): + with pytest.raises(ValueError): + build_public_dataset( + [PublicField(name="email", data_type="text", description="email")], + [{"email": "a@b.c"}], + ) + + int_field = PublicField(name="count", data_type="integer", description="Count") + with pytest.raises(ValueError): + build_public_dataset([int_field], [{"count": True}]) + + date_field = PublicField(name="when", data_type="date", description="When") + with pytest.raises(ValueError): + build_public_dataset([date_field], [{"when": "not-a-date"}]) diff --git a/tests/test_runtime_foundation.py b/tests/test_runtime_foundation.py index d4fa584..b2e779e 100644 --- a/tests/test_runtime_foundation.py +++ b/tests/test_runtime_foundation.py @@ -1,7 +1,7 @@ from fastapi.testclient import TestClient -from civicdata import __version__ -from civicdata.main import app +from townlight_data import __version__ +from townlight_data.main import app client = TestClient(app) @@ -23,17 +23,17 @@ def test_health_reports_civiccore_pin(): assert response.status_code == 200 payload = response.json() assert payload["service"] == "civicdata" - assert payload["version"] == "0.1.2" - assert payload["civiccore_version"] == "0.4.0" + assert payload["version"] == "0.2.0" + assert payload["civiccore_version"] == "1.3.0.dev2" def test_public_ui_contains_version_boundaries_and_dependency(): response = client.get("/civicdata") assert response.status_code == 200 text = response.text - assert "Townlight Data v0.1.2" in text + assert "Townlight Data v0.2.0" in text assert "No live CKAN publication" in text - assert "civiccore==0.4.0" in text + assert "townlight-core==1.3.0.dev2" in text def test_api_endpoints_return_deterministic_payloads(): diff --git a/townlight_data/__init__.py b/townlight_data/__init__.py new file mode 100644 index 0000000..10de370 --- /dev/null +++ b/townlight_data/__init__.py @@ -0,0 +1,3 @@ +"""Townlight Data v0.2.0 public package.""" + +__version__ = "0.2.0" diff --git a/civicdata/archive_bundle.py b/townlight_data/archive_bundle.py similarity index 100% rename from civicdata/archive_bundle.py rename to townlight_data/archive_bundle.py diff --git a/civicdata/ckan_package.py b/townlight_data/ckan_package.py similarity index 90% rename from civicdata/ckan_package.py rename to townlight_data/ckan_package.py index bc4f4c3..684ff5f 100644 --- a/civicdata/ckan_package.py +++ b/townlight_data/ckan_package.py @@ -2,8 +2,8 @@ from dataclasses import dataclass -from civicdata.data_dictionary import DictionaryEntry, draft_data_dictionary -from civicdata.redaction_review import RedactionReview, review_fields_for_publication +from townlight_data.data_dictionary import DictionaryEntry, draft_data_dictionary +from townlight_data.redaction_review import RedactionReview, review_fields_for_publication @dataclass(frozen=True) diff --git a/civicdata/data_dictionary.py b/townlight_data/data_dictionary.py similarity index 93% rename from civicdata/data_dictionary.py rename to townlight_data/data_dictionary.py index 6fcd9d0..73d1844 100644 --- a/civicdata/data_dictionary.py +++ b/townlight_data/data_dictionary.py @@ -2,7 +2,7 @@ from dataclasses import dataclass -from civicdata.dataset_normalization import normalize_schema_fields +from townlight_data.dataset_normalization import normalize_schema_fields @dataclass(frozen=True) diff --git a/civicdata/dataset_normalization.py b/townlight_data/dataset_normalization.py similarity index 100% rename from civicdata/dataset_normalization.py rename to townlight_data/dataset_normalization.py diff --git a/civicdata/main.py b/townlight_data/main.py similarity index 93% rename from civicdata/main.py rename to townlight_data/main.py index 5d1a9f3..b0537aa 100644 --- a/civicdata/main.py +++ b/townlight_data/main.py @@ -2,26 +2,26 @@ import os -from civiccore import __version__ as CIVICCORE_VERSION -from civiccore.auth import AuthenticatedPrincipal, authorize_bearer_roles +from townlight_core import __version__ as CIVICCORE_VERSION +from townlight_core.auth import AuthenticatedPrincipal, authorize_bearer_roles from fastapi import Depends, FastAPI, HTTPException, Response from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.responses import HTMLResponse from pydantic import BaseModel -from civicdata import __version__ -from civicdata.archive_bundle import create_archive_bundle_plan -from civicdata.ckan_package import build_ckan_package_draft -from civicdata.data_dictionary import draft_data_dictionary -from civicdata.dataset_normalization import normalize_schema_fields -from civicdata.persistence import ( +from townlight_data import __version__ +from townlight_data.archive_bundle import create_archive_bundle_plan +from townlight_data.ckan_package import build_ckan_package_draft +from townlight_data.data_dictionary import draft_data_dictionary +from townlight_data.dataset_normalization import normalize_schema_fields +from townlight_data.persistence import ( PublicationWorkpaperRepository, StoredCKANPackage, StoredPublicationPlan, ) -from civicdata.public_ui import render_public_lookup_page -from civicdata.publication_plan import draft_publication_plan -from civicdata.redaction_review import review_fields_for_publication +from townlight_data.public_ui import render_public_lookup_page +from townlight_data.publication_plan import draft_publication_plan +from townlight_data.redaction_review import review_fields_for_publication app = FastAPI( diff --git a/civicdata/persistence.py b/townlight_data/persistence.py similarity index 98% rename from civicdata/persistence.py rename to townlight_data/persistence.py index fde2015..863d3da 100644 --- a/civicdata/persistence.py +++ b/townlight_data/persistence.py @@ -7,8 +7,8 @@ import sqlalchemy as sa from sqlalchemy import Engine, create_engine -from civicdata.ckan_package import build_ckan_package_draft -from civicdata.publication_plan import draft_publication_plan +from townlight_data.ckan_package import build_ckan_package_draft +from townlight_data.publication_plan import draft_publication_plan metadata = sa.MetaData() diff --git a/townlight_data/public_dataset.py b/townlight_data/public_dataset.py new file mode 100644 index 0000000..baa48b4 --- /dev/null +++ b/townlight_data/public_dataset.py @@ -0,0 +1,157 @@ +from collections.abc import Iterable, Mapping, Sequence +from csv import QUOTE_ALL, writer +from dataclasses import asdict, dataclass +from datetime import date +from decimal import Decimal, InvalidOperation +from io import StringIO +import json +import re + +from .data_dictionary import draft_data_dictionary +from .redaction_review import review_fields_for_publication + +_FIELD_NAME_RE = re.compile(r'[a-z][a-z0-9_]{0,63}', re.ASCII) +_DECIMAL_RE = re.compile(r'-?(?:0|[1-9][0-9]*)(?:[.][0-9]+)?', re.ASCII) +_DATE_RE = re.compile(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', re.ASCII) +_ALLOWED_TYPES = frozenset({'text', 'integer', 'decimal', 'date'}) +_FORMULA_STARTS = frozenset({'=', '+', '-', '@'}) +_MAX_FIELDS = 32 +_MAX_ROWS = 5000 +_LINE_FEED = chr(10) + + +@dataclass(frozen=True) +class PublicField: + name: str + data_type: str + description: str + + +def build_public_dataset( + fields: Sequence[PublicField], rows: Iterable[Mapping[str, object]] +) -> dict[str, bytes]: + field_list = _validated_fields(fields) + records = _normalized_records(field_list, rows) + return { + 'dataset.csv': _csv_bytes(field_list, records), + 'dataset.json': _json_bytes(records), + 'data-dictionary.json': _dictionary_bytes(field_list), + } + + +def _validated_fields(fields: Sequence[PublicField]) -> list[PublicField]: + field_list = list(fields) + if not field_list: + raise ValueError('Schema must contain at least one field.') + if len(field_list) > _MAX_FIELDS: + raise ValueError(f'Schema cannot exceed {_MAX_FIELDS} fields.') + seen: set[str] = set() + for field in field_list: + if not _FIELD_NAME_RE.fullmatch(field.name): + raise ValueError(f'Invalid field name: {field.name!r}.') + if field.name in seen: + raise ValueError(f'Duplicate field name: {field.name!r}.') + if field.data_type not in _ALLOWED_TYPES: + raise ValueError(f'Invalid data type for {field.name!r}: {field.data_type!r}.') + if not field.description.strip(): + raise ValueError(f'Description required for field {field.name!r}.') + seen.add(field.name) + if not review_fields_for_publication([field.name for field in field_list]).ready_for_publication: + raise ValueError('Review or remove flagged fields before creating a public dataset.') + return field_list + + +def _normalized_records( + fields: Sequence[PublicField], rows: Iterable[Mapping[str, object]] +) -> list[dict[str, object]]: + records: list[dict[str, object]] = [] + for row_number, row in enumerate(rows, start=1): + if row_number > _MAX_ROWS: + raise ValueError(f'Dataset cannot exceed {_MAX_ROWS} rows.') + record: dict[str, object] = {} + for field in fields: + if field.name not in row: + raise ValueError(f'Row {row_number} missing field {field.name!r}.') + record[field.name] = _validated_value(field, row[field.name], row_number) + records.append(record) + return records + + +def _validated_value(field: PublicField, value: object, row_number: int) -> object: + if value is None: + return None + if field.data_type == 'text': + if not isinstance(value, str): + raise ValueError(f'Field {field.name!r} in row {row_number} must be text.') + if _has_formula_prefix(value): + raise ValueError(f'Field {field.name!r} in row {row_number} starts like a formula.') + if any(ord(char) < 32 or ord(char) == 127 for char in value): + raise ValueError(f'Field {field.name!r} in row {row_number} contains a control character.') + return value + if field.data_type == 'integer': + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f'Field {field.name!r} in row {row_number} must be an integer.') + return value + if field.data_type == 'decimal': + return _validated_decimal(field.name, value, row_number) + return _validated_date(field.name, value, row_number) + + +def _validated_decimal(name: str, value: object, row_number: int) -> str: + if not isinstance(value, str) or not _DECIMAL_RE.fullmatch(value): + raise ValueError(f'Field {name!r} in row {row_number} must be a decimal string.') + try: + parsed = Decimal(value) + except InvalidOperation as exc: + raise ValueError( + f'Field {name!r} in row {row_number} must be a decimal string.' + ) from exc + if not parsed.is_finite(): + raise ValueError(f'Field {name!r} in row {row_number} must be finite.') + return value + + +def _validated_date(name: str, value: object, row_number: int) -> str: + if not isinstance(value, str) or not _DATE_RE.fullmatch(value): + raise ValueError(f'Field {name!r} in row {row_number} must be a date string.') + try: + date.fromisoformat(value) + except ValueError as exc: + raise ValueError( + f'Field {name!r} in row {row_number} must be a calendar date.' + ) from exc + return value + + +def _has_formula_prefix(value: str) -> bool: + for char in value: + if char.isspace() or ord(char) < 32 or ord(char) == 127: + continue + return char in _FORMULA_STARTS + return False + + +def _csv_bytes( + fields: Sequence[PublicField], records: list[dict[str, object]] +) -> bytes: + output = StringIO(newline='') + csv_writer = writer(output, lineterminator=_LINE_FEED, quoting=QUOTE_ALL) + csv_writer.writerow([field.name for field in fields]) + for record in records: + csv_writer.writerow([ + '' if record[field.name] is None else record[field.name] for field in fields + ]) + return output.getvalue().encode('utf-8') + + +def _json_bytes(records: list[dict[str, object]]) -> bytes: + return json.dumps(records, ensure_ascii=False, separators=(',', ':')).encode('utf-8') + + +def _dictionary_bytes(fields: Sequence[PublicField]) -> bytes: + source_fields = [ + {'name': field.name, 'type': field.data_type, 'description': field.description} + for field in fields + ] + dictionary = [asdict(entry) for entry in draft_data_dictionary(source_fields)] + return json.dumps(dictionary, ensure_ascii=False, separators=(',', ':')).encode('utf-8') diff --git a/civicdata/public_ui.py b/townlight_data/public_ui.py similarity index 89% rename from civicdata/public_ui.py rename to townlight_data/public_ui.py index a17f8fd..b77645e 100644 --- a/civicdata/public_ui.py +++ b/townlight_data/public_ui.py @@ -26,15 +26,15 @@ def render_public_lookup_page() -> str:

Townlight / Townlight Data

Open-data packages with review gates built in.

-

Townlight Data v0.1.2 helps staff normalize municipal datasets, draft data dictionaries, prepare CKAN-ready package metadata, protect persisted retrieval with bearer roles, and assemble records-retention archive checklists.

-

Shipping v0.1.2

+

Townlight Data v0.2.0 helps staff normalize municipal datasets, draft data dictionaries, prepare CKAN-ready package metadata, protect persisted retrieval with bearer roles, and assemble records-retention archive checklists.

+

Standalone workpapers

What ships

  • Dataset field normalization.
  • Data-dictionary drafting.
  • CKAN package metadata drafts.
  • PII/exemption redaction preflight.
  • Archive-bundle and publication checklists.

Human approval required

Every export must clear staff approval, redaction/exemption review, retention checks, and open-data license confirmation before publication.

-

Boundaries

No live CKAN publication, no BI dashboards, no data warehouse, no long-term storage, no autonomous redaction, and no external connector runtime ships in v0.1.2.

-

Dependency

Pinned to civiccore==0.4.0. Retrieval auth uses CIVICDATA_AUTH_TOKEN_ROLES. Townlight Core remains dependency-only; it never imports from Townlight Data.

+

Boundaries

No live CKAN publication, no BI dashboards, no data warehouse, no long-term storage, no autonomous redaction, and no external connector runtime ships in v0.2.0.

+

Dependency

Pinned to townlight-core==1.3.0.dev2. Retrieval auth uses CIVICDATA_AUTH_TOKEN_ROLES. Townlight Core remains dependency-only; it never imports from Townlight Data.

diff --git a/civicdata/publication_plan.py b/townlight_data/publication_plan.py similarity index 100% rename from civicdata/publication_plan.py rename to townlight_data/publication_plan.py diff --git a/civicdata/redaction_review.py b/townlight_data/redaction_review.py similarity index 100% rename from civicdata/redaction_review.py rename to townlight_data/redaction_review.py