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
91 changes: 91 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
name: CI
on:
push:
branches: [main]
pull_request:
workflow_dispatch:

permissions:
contents: read

jobs:
tests:
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
python: '3.10'
- os: ubuntu-latest
python: '3.14'
- os: macos-latest
python: '3.12'
- os: windows-latest
python: '3.12'
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
- run: python -m pip install .
- run: python -m unittest discover -s tests -v
- run: python examples/demo.py
distributions:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: python -m pip install build
- run: python -m build
- name: Fresh wheel and sdist installations outside checkout
shell: bash
run: |
python - <<'PY'
import os, pathlib, shutil, subprocess, sys, tarfile, tempfile
repo = pathlib.Path.cwd()
env = dict(os.environ)
env.pop('PYTHONPATH', None)
with tempfile.TemporaryDirectory() as tmp:
root = pathlib.Path(tmp)
source = root / 'source'
source.mkdir()
with tarfile.open(next((repo/'dist').glob('*.tar.gz'))) as archive:
archive.extractall(source, filter='data')
extracted = next(source.iterdir())
assert (extracted/'docs/CONTRACTS.md').is_file()
for kind, artifact in [('wheel', next((repo/'dist').glob('*.whl'))), ('sdist', next((repo/'dist').glob('*.tar.gz')))]:
venv = root / kind
subprocess.run([sys.executable, '-m', 'venv', str(venv)], check=True)
python = venv/'bin/python'
subprocess.run([str(python), '-m', 'pip', 'install', str(artifact)], cwd=root, env=env, check=True)
subprocess.run([str(python), '-I', '-m', 'unittest', 'discover', '-s', str(extracted/'tests'), '-v'], cwd=root, env=env, check=True)
subprocess.run([str(python), '-I', str(extracted/'examples/demo.py')], cwd=root, env=env, check=True)
subprocess.run([str(python), '-I', '-c', 'import locreturn; print(locreturn.__file__)'], cwd=root, env=env, check=True)
PY
- name: Record build provenance and checksums
run: |
python - <<'PY'
import hashlib, json, os, pathlib, platform
files = sorted(pathlib.Path('dist').iterdir())
hashes = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in files}
pathlib.Path('dist/SHA256SUMS').write_text(''.join(f'{h} {n}\n' for n,h in hashes.items()))
manifest = {'repository': os.environ['GITHUB_REPOSITORY'], 'source_commit': os.environ['GITHUB_SHA'], 'run_url': f"https://github.com/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}", 'python': platform.python_version(), 'artifacts': hashes}
pathlib.Path('dist/PROVENANCE.json').write_text(json.dumps(manifest, indent=2)+'\n')
PY
- uses: actions/upload-artifact@v4
with:
name: distributions
path: dist/*
quality-gate:
if: always()
needs: [tests, distributions]
runs-on: ubuntu-latest
steps:
- name: Require every matrix and distribution job
env:
TESTS_RESULT: ${{ needs.tests.result }}
DIST_RESULT: ${{ needs.distributions.result }}
run: test "$TESTS_RESULT" = success && test "$DIST_RESULT" = success
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

## 1.0.0

First supported release: local flat-JSON translation task export, source/context-qualified three-way return planning, explicit per-key conflict review, stale-plan refusal, exclusive new target output and content-bound receipt. Includes 49 acceptance tests, cross-platform CI, source/wheel distribution and a runnable constructed scenario. No hosted service or runtime dependencies.
4 changes: 4 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
include LICENSE README.md CHANGELOG.md
recursive-include docs *.md
recursive-include examples *.json *.py
recursive-include tests *.py
91 changes: 89 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,95 @@

Reconcile an offline translator's JSON return after your source text and local translations have moved on.

**Development in progress.** The first supported release will provide a local, source-aware three-way reconciliation workflow for one flat-JSON locale at a time. Research, input contracts, tests, and independently reviewed implementation are being prepared through pull requests.
`locreturn` snapshots the original source, optional translator context, and target catalog. When a translation returns, it compares that baseline with current files, accepts independent safe edits, and requires explicit decisions for source drift or competing target changes. It writes a new target and a content-bound receipt; it never edits your input catalogs.

This tool is for maintainers who already exchange JSON catalogs outside a translation management system. Weblate, Crowdin, Lokalise, Phrase, Tolgee and BabelEdit are strong alternatives when their broader workflows fit.

MIT licensed. No hosted service or runtime dependency is planned.
## Install

Python 3.10 or newer. Download the wheel from the [public release](https://github.com/waxwingfactor/locreturn/releases/latest), then install it in an isolated environment:

```sh
python3 -m venv .venv
.venv/bin/python -m pip install ./locreturn-1.0.0-py3-none-any.whl
.venv/bin/locreturn --help
```

On Windows, use `.venv\Scripts\python.exe` and `.venv\Scripts\locreturn.exe`. The installed tool has no dependencies, server, credentials, telemetry, or network calls. The release also includes an sdist with docs, examples and tests; building it needs setuptools and wheel.

## Use

Catalogs are **flat JSON objects with string values**. Dots in keys are literal; nested objects, arrays, numbers and JSON comments are unsupported. Use `{}` as the target file for a new locale.

```sh
locreturn pack --source en.json --target fr.json \
--source-locale en --target-locale fr --out job
```

Keep `job/baseline.json` unchanged with the maintainer. Give the translator `job/task.json`. They edit only each entry's `translation`:

```json
{
"source": "Save",
"context": null,
"previous_target": "Sauver",
"translation": "Enregistrer"
}
```

`null` means no proposal; `""` means an intentional empty translation. A translator may omit entries for a partial return. Keys and identity fields cannot change. All ordinary JSON editors work; this is not a CAT or spreadsheet interchange format.

After receiving the task, plan against **current** catalogs:

```sh
locreturn plan --baseline job/baseline.json --returned job/task.json \
--source en.json --target fr.json --out review
```

Review `review/review.txt` and `review/plan.json`. Exit **3** means the plan was written and contains conflicts. Fill every entry of `review/decisions.json`, using a nonempty reason. For example:

```json
{"action": "keep", "text": null, "reason": "Preserve the local reviewer correction"}
```

For a target conflict, choose `keep`, `incoming`, or `custom`. For changed source/context, choose `keep` or `custom` with text reviewed against the current source. Removed source allows only `keep`. The tool never imports stale-source text through an `incoming` decision.

```sh
locreturn apply --baseline job/baseline.json --returned job/task.json \
--source en.json --target fr.json --plan review/plan.json \
--decisions review/decisions.json --out merged
```

When there are no conflicts, omit `--decisions`. Apply recomputes the entire plan and refuses changed inputs or modified plans. Review `merged/target.json` and `merged/receipt.json`, run your application's translation/placeholder checks, then commit the reviewed target through your normal workflow. Every `--out` must be a new directory with an existing parent; there is no overwrite mode.

For semantic context such as “bank: financial account,” add `--context context.json` to **all three commands**. This optional flat key-to-string map participates in source identity. Omitting previously supplied context makes those entries source-changed.

## Behavior and boundaries

| Situation | Result |
|---|---|
| Source/context match; target unchanged since export | Accept the incoming edit |
| Returned target unchanged, missing, or null | Preserve current target |
| Incoming and current target agree | Keep current target |
| Both targets changed differently, including current deletion | Require a target-conflict decision |
| Source text/context changed or source key removed | Block incoming; require review |
| New source key or orphan target | Report and preserve current target; never invent or prune |

Success certifies reconciliation under these rules, **not** completeness, linguistic quality, runtime syntax, or currency of every existing translation. Existing stale targets may be retained. Placeholder checks, ICU/plural interpretation, semantic equivalence, renames, automatic translation, TMS synchronization, nested JSON, and baseline-free imports are outside scope. If meaning changes without source text or context changing, locreturn cannot detect it.

Up to 10,000 combined distinct keys, 1,024 characters per key, 65,536 per value and 32 MiB per input/generated file. Full inputs and plans are held in memory; large catalogs may exceed the generated-file limit and must be split. Local single-writer filesystems are supported; directories may be visible during writing. Ordinary write failures attempt cleanup. A crash/power loss may leave a partial output directory: use output only after exit 0 and create a new directory on retry. Original inputs remain untouched. Hashes detect accidental changes; they do not authenticate a malicious party who can rewrite your trusted baseline.

Exit codes: **0** completed, **2** invalid/unsupported input or I/O failure, **3** plan written with unresolved conflicts. JSON summaries go to stdout and errors to stderr. Input formatting/order changes do not stale a plan; parsed content changes do.

See [contracts and trust boundaries](docs/CONTRACTS.md), [research and positioning](docs/RESEARCH.md), [release verification](docs/VERIFICATION.md), and the [constructed example](examples/demo.py).

## Develop

```sh
python3 -m pip install -e . build
python3 -m unittest discover -s tests -v
python3 examples/demo.py
python3 -m build
```

CI checks Python 3.10/3.14 on Linux, filesystem behavior on macOS/Windows (3.12), and wheel/sdist installation outside the checkout (Linux 3.12). The CLI and v1 JSON schemas are supported interfaces; internal Python modules are not a stable library API. MIT licensed.
48 changes: 48 additions & 0 deletions docs/CONTRACTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Supported workflow and contracts

Version 1 supports one source locale and one target locale per job. The maintainer controls baseline, current catalogs, decisions and execution. The returning file is treated as untrusted data. There is no extraction, translation engine, runtime adapter, server, file discovery, subprocess invocation or network access.

## Inputs

All files are regular UTF-8 JSON, without BOM or comments. Duplicate keys anywhere, nonfinite numeric literals and escaped unpaired Unicode surrogates are rejected. Catalog/context objects contain nonempty string keys and string values only. Keys are opaque; no dot splitting, Unicode normalization or whitespace normalization occurs. Empty values are legal. Locale labels follow a bounded language-tag syntax but are not validated against a registry. Text language is not inferred. Aliases other than hyphen/underscore/case normalization are not resolved.

Resource limits: each file <=32 MiB, each catalog <=10,000 entries, combined distinct source/target keys <=10,000, each key <=1,024 Unicode code points, each text/context <=65,536 code points. Source and target labels differ ignoring case and `_`/`-`. Context keys must exist in the corresponding source catalog. Generated files also have the 32 MiB cap. Parsing/serialization is bounded by file size, not constant-memory or hardened against a hostile operating system.

`pack` creates `locreturn.baseline.v1` with source/target snapshots, source/target locale labels, context, and `job_id`; the ID is SHA-256 of compact, sorted, unescaped UTF-8 JSON of the other fields. The baseline belongs in trusted maintainer storage. Retain it for every outstanding return. Identical semantic input yields the same job identity. Jobs do not contain absolute paths or timestamps.

`task.json` is `locreturn.return.v1`, with the job ID and locale labels and an `entries` object. Each source key has `source`, `context`, `previous_target`, and `translation`. Only `translation` is editable. Null is a skip; strings including empty strings are proposals. A return can omit entries but cannot add/rename them, change metadata, add fields or impersonate another locale/job. Missing entries are `not-returned`. This explicit partial-return contract is useful for incremental batches; it does not establish translation completeness.

## Source-qualified merge

For each key, let B be baseline target, C current target and R returned proposal. Missing targets use an internal null sentinel distinct from the string `""`.

1. Keys outside baseline source are `new-source` or `orphan-target`, retained as currently stored.
2. An absent return entry, null proposal, or R=B is `not-returned`, `skipped`, or `unchanged-return`; keep C.
3. For a changed proposal, removed current source is `source-removed`. Changed source **or context** is `source-changed`. Both require review even if R=C.
4. Otherwise R=C is `already-current`; C=B is `ready`; all other cases are `target-conflict`.

Current target deletion and concurrent addition therefore conflict with divergent incoming changes. There is no delete action or pruning, and no source-key rename inference. New source work needs a new job. Returning unchanged target text cannot explicitly reassert it over a local correction; that case intentionally preserves current text. A maintainer who wishes to change it can edit the current catalog in the normal review workflow.

Every plan row includes baseline/current source, context, target, proposal, status and a source-changed boolean. Preserved entries can still have source drift. The plan is `locreturn.plan.v1`, contains a semantic hash of **every** input, all rows, counts and a content ID. Canonicalization uses Python's JSON encoder with `sort_keys=True`, `ensure_ascii=False`, separators `(',', ':')`, no NaN; it is not a claim of RFC 8785 compatibility.

## Decisions and application

`locreturn.decisions.v1` binds exactly the conflict key set to the plan ID. Each entry has `action`, `text` and `reason`. Keep requires null text; incoming requires null text and is allowed only for target conflict. Custom requires a string and is allowed for target conflict/source-changed. Source-removed allows only keep. Reasons are nonempty after stripping, <=4,096 code points. The generated `unresolved` action is deliberately invalid for apply. Unknown/missing decisions or fields fail.

Decisions are reviewed inputs: editing decisions after planning is expected and their final hash/content is captured in the receipt. The plan itself and **all** original/current/returned/context inputs are recomputed and compared by type-sensitive canonical JSON at apply time. A stale plan must be regenerated; transplanting decisions to another plan is refused. No final target is emitted while any conflict lacks a valid decision.

`apply` emits the complete current target with accepted edits as `target.json`, plus `locreturn.receipt.v1`. The receipt includes job/plan IDs, input hashes, decisions hash and content, resulting semantic catalog hash, changed values/reasons and its own ID. These are content-integrity records, not signatures, authorship certificates or approval by a human reviewer. Keep the plan and input snapshots if later reproduction matters.

## Filesystem and trust boundaries

Input symlinks to regular files are readable. The output leaf is exclusively created; existing paths, including symlink leaves, fail. Parents must exist. All data is validated and all output bytes pre-serialized before creating a directory. The CLI never overwrites input catalogs. Ordinary write failures clean only files created by the invocation and attempt removal of its directory. Successful files are flushed and fsynced individually.

Directory publication is not a power-loss atomic transaction. Output may be visible while populated, or remain partial after abrupt termination/cleanup failure. Use it only after exit 0 and verify both target and receipt; retry with a new directory. There is no in-place apply operation. Hostile concurrent writers, network filesystem guarantees, directory symlink substitution, disk failure recovery and authenticated provenance of incoming translations are outside scope. Do not let multiple processes share an output path or mutate inputs while a command runs. Input content is read once per command; apply emits a separate reviewed result rather than promising to lock a running application's catalogs.

Review output JSON-escapes text in `review.txt` so control codes and multiline values do not spoof terminal rows. Machine-readable files may contain arbitrary legitimate translated text; render it as untrusted text in downstream applications.

## Compatibility and quality

Python >=3.10; CI covers 3.10/3.12/3.14 on three OS families. V1 schemas reject unknown fields and schema versions. CLI commands/schema changes follow semantic versioning; internal Python functions are private. No dependency is imported at runtime outside the standard library. Building an sdist requires setuptools>=77 and wheel; wheel installation can be fully offline.

Run your framework's native format, placeholder, plural, markup and linguistic reviews before committing output. locreturn intentionally leaves strings opaque. Exact source/context equality is a conservative identity condition, not a semantic equivalence engine.
Loading
Loading