Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "data-toolkit",
"version": "0.8.9",
"version": "0.8.10",
"description": "Extract, tidy, reconcile, analyse, visualise and convert messy data into clean, validated, audit-ready tables and insight briefs \u2014 computed by a deterministic engine that runs on your machine, with no third-party services. From Phronesis Applied.",
"author": {
"name": "Phronesis Applied",
Expand Down
34 changes: 34 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,39 @@
# Changelog

## 0.8.10 — 2026-10-12

- **`data-convert` refuses to write over source drift.** `convert_file` previously blocked only
on contract errors; a mapped source column that was missing or renamed (a sense-check
`error`) still produced output with that column blank. Any sense-check `error` now blocks the
write too: `report["blocked"] = True`, `report["written"] = []`, and a new
`report["blocked_by"]` lists `"contract"` and/or `"sense_check"`. The report is still
produced; `render_report` states the blocking reason(s); the CLI exits 1 when blocked.
- **Date-keyed FX never invents a rate.** With a pinned `fx.rates` table, a row dated before
every pinned rate, or with a blank/unparseable date, was silently converted at the earliest
(or latest) rate. Such cells are now left **blank** and flagged `fx_rate_unresolved`
(severity `warning`, with row and field) in the report's `issues`. Rate selection parses
dates (ISO, DD MMM YYYY, dd/mm/yyyy, Excel serial — via the shared `dataclean.parse_date`)
instead of comparing strings. A single pinned `fx.rate` still applies to every row; a
`fx_convert` with no pinned rate still raises. New helpers `_to_date` and `_fx_resolve`;
`_field` / `apply_map` gain optional `flags=` / `issues=` (defaults unchanged).
- **Stale-FX sense-check parses dates.** The check was a raw string compare and gave the wrong
answer for DD MMM YYYY dates (e.g. `"30 Jun 2026" < "2026-07-01"` is false). Both sides are
now parsed; a `rates` table is judged by its latest `as_of`; an unparseable date raises a new
`fx_date_unparsed` warning instead of passing silently. `--as-of` help clarified.
- **`ingest.read_large_rows(path, sheet=None, cache_dir=None)`** — additive drop-in for
`read_any` on big files: returns `(rows, note)` in the same list-of-rows shape (header first,
missing cells as `""`). `.xlsx`/`.xlsm` go through `read_large` (Parquet cache / streaming);
any other type falls back to `read_any`, so it never raises just because the file is not
Excel. `read_large` itself stays Excel-only.
- Docs: `data-convert` SKILL.md / `conversion-spec.md` (default `flag`, stale rule,
`--as-of` / `run_dates_after` on the call lines, blocking, unresolved FX);
`data-analyse` / `data-tidy` SKILL.md and `large-file-patterns.md` (which reader:
`read_large_rows` vs `read_large`).
- Tests: 4 new engine tests (suite 116 → 120) + extended `convert.py --self-test`.

All changes are backward-compatible at the API level; the behavioural changes are the
blocked write on sense-check errors (exit 1) and blank-plus-flag for unresolvable FX rows.

## 0.8.9 — 2026-10-06

- **Done-when gates added to `data-reconcile`, `data-convert` and `data-visualise`.** A
Expand Down
37 changes: 35 additions & 2 deletions scripts/ingest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
text, so the diversity of inputs lives here and the cleanup pipeline (dataclean.py) stays one
shared path. Used by `data-tidy` (clean tabular data) and `data-extract` (get data
out of documents). Lives at the toolkit-root `scripts/`; skills import it by adding
`../../scripts` to sys.path (run from the skill directory).
`[skill]/../../scripts` (absolute) to sys.path, so commands can run from the work folder.

from ingest import read_any, read_large, read_paste, read_text, list_sheets, list_pdf_tables, ocr_available
from ingest import read_any, read_large, read_large_rows, read_paste, read_text, list_sheets, list_pdf_tables, ocr_available
rows, note = read_any("export.xlsx") # or .csv/.tsv, a .pdf, a .docx, a .msg, a .pptx
rows, note = read_any("book.xlsx", sheet="Q2") # pick a tab in a multi-sheet workbook
df, note = read_large("ledger.xlsx") # 10k+ rows: strategy gate + Parquet cache/stream
rows, note = read_large_rows("ledger.xlsx") # same, but rows shaped like read_any (any ext)
sheets = list_sheets("book.xlsx") # discover tabs (name/size/hidden/empty)
rows, note = read_paste(pasted_text) # markdown / tab / csv-ish pasted table
text, note = read_text("form.pdf") # document -> plain text (OCR fallback)
Expand Down Expand Up @@ -206,6 +207,38 @@ def read_large(path: str, sheet=None, cache_dir=None):
return df, note


def read_large_rows(path: str, sheet=None, cache_dir=None):
"""Drop-in for ``read_any`` on big files → ``(rows, note)`` in the SAME shape as
``read_any`` (list of row lists, header row first), so the rest of the workflow
(``dataclean.detect_header`` / ``profile_table`` / ``analyse``) is unchanged.

``.xlsx``/``.xlsm`` go through ``read_large`` (Parquet cache / streaming when pandas+pyarrow
are installed); a DataFrame result is converted as ``[list(df.columns)] + df.values.tolist()``
with missing cells (None/NaN/NaT) as ``""``. Any other type (``.csv``, ``.pdf`` …) is read
with ``read_any`` — it never raises just because the file is not Excel."""
ext = Path(path).suffix.lower()
if ext not in (".xlsx", ".xlsm"):
rows, note = read_any(path, sheet=sheet)
return rows, note + " (read_large_rows: non-Excel source read directly)"
frame, note = read_large(path, sheet=sheet, cache_dir=cache_dir)
if isinstance(frame, list): # fallback path already returns rows
return frame, note

def _cell(v):
if v is None:
return ""
try:
if v != v: # NaN / NaT
return ""
except (TypeError, ValueError): # pandas.NA refuses bool()
return "" if repr(v) == "<NA>" else v
return v

rows = [[str(c) for c in frame.columns]]
rows += [[_cell(v) for v in rec] for rec in frame.astype(object).values.tolist()]
return rows, note


def read_csv(path: str):
with open(path, "r", encoding="utf-8-sig", errors="replace", newline="") as f:
sample = f.read(4096)
Expand Down
12 changes: 8 additions & 4 deletions skills/data-analyse/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,14 @@ header_rows, note = ingest.read_any(path) # xlsx/csv/pdf/docx/msg; read_past
Multi-tab workbooks: `read_any` raises `SheetSelectionRequired` if several tabs hold data —
list the sheets and ask, don't guess.

For files with 10k+ rows, use `ingest.read_large` instead of `read_any` to avoid OOM. See
`references/large-file-patterns.md` for vectorised operation guidance.

**Done when:** you have `(header_rows, note)` from `read_any` (or `read_large` for 10k+ rows). If `SheetSelectionRequired` was raised, the user has chosen a sheet. `note` has been read for source-quality flags.
For files with 10k+ rows, use `ingest.read_large_rows(path)` instead of `read_any` — a drop-in
that returns the same `(header_rows, note)` shape (Parquet cache / streaming for `.xlsx`; any
other type falls back to `read_any`). `ingest.read_large` is the DataFrame variant and is
**`.xlsx`/`.xlsm` only** (raises on `.csv`); convert its result with
`header, rows = list(df.columns), df.values.tolist()`. See `references/large-file-patterns.md`
for vectorised operation guidance.

**Done when:** you have `(header_rows, note)` from `read_any` (or `read_large_rows` for 10k+ rows). If `SheetSelectionRequired` was raised, the user has chosen a sheet. `note` has been read for source-quality flags.

### 2 — Profile & quality gate
`dataclean.profile_table(header, rows)` / `score_quality(...)` — column types, missing %,
Expand Down
26 changes: 17 additions & 9 deletions skills/data-analyse/references/large-file-patterns.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Large-file patterns — vectorised operations cheat sheet

Use with `ingest.read_large` when a source has **10k+ rows**. Prefer vectorised pandas /
Use with `ingest.read_large_rows` / `ingest.read_large` when a source has **10k+ rows**. Prefer vectorised pandas /
NumPy ops over Python row loops — a 200k-row ledger that finishes in seconds with the
left-hand forms can take minutes (or OOM) with the right-hand forms.

Expand All @@ -12,15 +12,23 @@ left-hand forms can take minutes (or OOM) with the right-hand forms.
| `np.where(df['a'] > 0, 'Y', 'N')` | `df['a'].map(lambda ...)` | `np.where` / boolean assignment beats per-cell Python callables |
| `df.groupby('a').agg({'b': 'sum'})` | `df.groupby('a').apply(custom_func)` | Named aggregations use the fast path; `apply` falls back to Python |

## Scope: `read_large` is Excel-only — CSV goes through `read_any`
## Which reader? `read_large_rows` (drop-in) vs `read_large` (DataFrame)

`ingest.read_large` (the Parquet cache / stream path above) supports **`.xlsx` / `.xlsm` only**.
A large **CSV** is read by `ingest.read_any`, whose single-pass `csv.reader` returns list-of-rows
— fast (a 250k-row CSV ingests in well under a second) and the shape the analyse engine expects.
- **`ingest.read_large_rows(path, sheet=None)` → `(rows, note)`** — the drop-in for `read_any`:
the same list-of-rows shape (header row first), so `dataclean` / `analyse` run unchanged. Excel
goes through the Parquet cache / stream path below; any other type (`.csv`, `.pdf` …) is read
with `read_any`, so it never raises just because the file isn't Excel.
- **`ingest.read_large(path, sheet=None)` → `(DataFrame, note)`** — **`.xlsx` / `.xlsm` only**
(raises `ValueError` on `.csv` and other extensions). Use it when you want pandas for the
vectorised ops above. Without pandas/pyarrow it falls back to `(rows, note)` from `read_xlsx`.
To hand a DataFrame back to the row-based engines:
`header, rows = list(df.columns), df.values.tolist()`.

A large **CSV** is read by `ingest.read_any` (or `read_large_rows`), whose single-pass
`csv.reader` returns list-of-rows — fast (a 250k-row CSV ingests in well under a second).
Ingestion is not the bottleneck at this scale; there is no chunked/pyarrow CSV path today, so a
genuinely memory-bound CSV (millions of rows) should be pre-split or loaded via your own
`pandas.read_csv(chunksize=…)` outside the toolkit. Don't assume `read_large` will take a CSV —
it raises `ValueError` on non-Excel extensions.
`pandas.read_csv(chunksize=…)` outside the toolkit.

## Strategy reminder (`scripts/streaming.py`)

Expand All @@ -35,5 +43,5 @@ low-cardinality object columns) — typically **50–80%** memory reduction.

## Optional deps

`pyarrow` + `pandas` are optional. Without them `ingest.read_large` falls back to a
direct openpyxl read and warns that large files may OOM. See `README.md#mode--environment-compatibility`.
`pyarrow` + `pandas` are optional. Without them `ingest.read_large` / `read_large_rows` fall back to a
direct openpyxl read and warn that large files may OOM. See `README.md#mode--environment-compatibility`.
26 changes: 19 additions & 7 deletions skills/data-convert/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ clean result.
> **Two jobs, often combined:**
> 1. **Contract mapping** — map a source onto *another system's* import contract (columns, order,
> types, required fields). Unmapped sources are reported; required-but-missing rows follow
> `rules.on_missing_required` (`flag` / `exclude` / `error`) — never invent values.
> `rules.on_missing_required` (`flag` / `exclude` / `error`; default `flag`) — never invent values.
> 2. **Structural reshape** — `unpivot` (wide→long), `pivot` (long→wide), `flatten`/`nest`
> (JSON↔table), `split` (one file→many by a key), `union` (many→one with column alignment).

Expand Down Expand Up @@ -51,23 +51,33 @@ or the field list), and the user has confirmed the proposed mapping before any f
`convert_[name].md` in the working folder). If one does, **do not blind-run it**:
1. Load it (`load_spec`) and read its **Mapping** + **Expected source**.
2. **Sense-check today's source against it** (`sense_check(spec, header, rows)` /
`convert.py <src> --card card.md --check-only`).
`convert.py <src> --card card.md --check-only`), passing the run's as-of date —
`sense_check(spec, header, rows, run_dates_after="30 Jun 2026")` / `--as-of "30 Jun 2026"`
(ISO or DD MMM YYYY; the date the conversion must be current for, e.g. the period end).
3. **Flag any discrepancy to the user** — a mapped column missing/renamed, a new column, a
required field now empty, or a **stale pinned rate** — and let them decide: proceed / adjust /
regenerate. Never apply over drift silently.
regenerate. Never apply over drift silently. **Stale rule:** a pinned rate is "old" when its
`as_of` (for a `rates` table, the latest `as_of`) is earlier than the run's as-of date; both
dates are parsed, never compared as text.

### 3. Apply (deterministic)
```python
spec = load_spec("convert_gl_to_journal.md") # or a dict you just built + confirmed
report = convert_file(spec, "gl_export.xlsx", "journal_import.csv")
report = convert_file(spec, "gl_export.xlsx", "journal_import.csv",
run_dates_after="30 Jun 2026") # the run's as-of date (stale-FX check)
print(render_report(report, name=spec["name"]))
```
Or one-shot from the CLI:
`python scripts/convert.py gl_export.xlsx --card convert_gl_to_journal.md -o journal_import.csv`
`python scripts/convert.py gl_export.xlsx --card convert_gl_to_journal.md -o journal_import.csv --as-of "30 Jun 2026"`

The engine reads the source (any format via the shared `ingest`), runs any reshape ops, maps to
the target contract, and writes the target format (`csv` / `json` / `xlsx`). It reports rows
in/out, the **sense-check**, unmapped source columns and required-but-missing target fields.
**Nothing is written** (`report["blocked"]`, CLI exit code 1) when the sense-check or the contract
has an `error` — e.g. a mapped source column that is missing or renamed, which would otherwise be
written blank; the report still lists why. With a date-keyed `fx.rates` table, a row dated
before every pinned rate (or with a blank/unparseable date) is left **blank and flagged**
(`fx_rate_unresolved`), never converted at a guessed rate.

**Done when:** `report["sense_check"]` is clean (or every discrepancy has been flagged to the
user and resolved), the target file is written, and the report's unmapped-column /
Expand Down Expand Up @@ -97,7 +107,8 @@ on that. When a conversion needs a live value (e.g. a USD→GBP rate):
decides** whether to apply it (confirm-first);
- the value is **pinned into the card** (`fx: {pair, rate, as_of, source}`) and applied by the
engine as a **recorded constant**, so a re-run is deterministic and auditable;
- refreshing is a deliberate act — the sense-check flags a pinned rate that's old for the run.
- refreshing is a deliberate act — the sense-check flags a pinned rate that's old for the run
(its `as_of` is earlier than the run's `--as-of` date).

Fetching a public rate is a public lookup, not egress of the user's data — the dataset never
leaves. Never send the actual rows to an external service to "convert" them.
Expand All @@ -121,7 +132,8 @@ Ready-made example contracts: `references/contracts/journal-import.md`,
## Safety
- **Deterministic & human-in-the-loop** — the engine applies a confirmed spec; it never invents a
value. Output is a **draft for review**, not a posting or an upload — a person submits it.
- **Never blind-applies** — a drifted source is flagged, not force-converted.
- **Never blind-applies** — a drifted source is flagged, not force-converted: a missing or
renamed mapped column blocks the write.

## Files

Expand Down
17 changes: 11 additions & 6 deletions skills/data-convert/references/conversion-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,13 @@ user's intent, confirm it, then `convert_file(spec, in, out)`.
"as_of": "2026-07-15", "source": "<url>" }`, or a **date-keyed table** for per-row conversion
by transaction date: `{ "pair": "USD/GBP", "rates": [ {"as_of":"2026-01-01","rate":"0.80"},
{"as_of":"2026-06-01","rate":"0.75"} ] }` — with `compute:"fx_convert"` setting `on_date` to
the row's date column (the latest rate whose `as_of` ≤ the row date is used). The engine
**never fetches** — the agent fetches on the user's instruction, the user approves, and it's
recorded here.
the row's date column (the latest rate whose `as_of` ≤ the row date is used; dates are parsed
— ISO, DD MMM YYYY, dd/mm/yyyy — never compared as text). A row dated **before every pinned
rate**, or with a blank/unparseable date, is left **blank and flagged** (`fx_rate_unresolved`)
— never converted at the nearest rate. The engine **never fetches** — the agent fetches on the
user's instruction, the user approves, and it's recorded here. **Stale rule:** pass the run's
as-of date (`run_dates_after=` / CLI `--as-of`); a pinned `as_of` (for a table, the latest one)
earlier than that date is flagged `stale_fx`.
- **standing_rules** — a string list of user confirm-first rules to preserve across sessions.
`render_card` always emits them as a **Standing rules** section so later agents do not have to
rediscover policy from chat history.
Expand Down Expand Up @@ -163,9 +167,10 @@ Beyond `required`, a target column can carry validators; violations surface in t

## How it's reported

- **Sense-check** (run against the card before applying): a mapped source column missing/renamed,
a new column, an expected column gone, or a **stale pinned rate** → surfaced to the user; the
engine does **not** auto-apply over drift.
- **Sense-check** (run against the card before applying): a mapped source column missing/renamed
(`error`), a new column, an expected column gone, or a **stale pinned rate** (`warn`) →
surfaced to the user; the engine does **not** auto-apply over drift — any sense-check `error`
**blocks the write** (`report["blocked"]`, CLI exit 1) and the report says why.
- **Contract issues**: a required target field unmapped → `error`; a required field blank on a
row → handled by `on_missing_required` (`flag` / `exclude` / `error`); a
validator violation (`allowed`/`pattern`/`max_len`/`check`) → `error`; a source column the
Expand Down
Loading
Loading