diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e11dc18 --- /dev/null +++ b/.github/workflows/ci.yml @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..5c89cb0 --- /dev/null +++ b/CHANGELOG.md @@ -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. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..f8c1799 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,4 @@ +include LICENSE README.md CHANGELOG.md +recursive-include docs *.md +recursive-include examples *.json *.py +recursive-include tests *.py diff --git a/README.md b/README.md index 30acd6e..e0a4e42 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/CONTRACTS.md b/docs/CONTRACTS.md new file mode 100644 index 0000000..ee4c291 --- /dev/null +++ b/docs/CONTRACTS.md @@ -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. diff --git a/docs/RESEARCH.md b/docs/RESEARCH.md new file mode 100644 index 0000000..27f4b32 --- /dev/null +++ b/docs/RESEARCH.md @@ -0,0 +1,56 @@ +# Opportunity, alternatives and positioning + +Evidence reviewed **2026-10-15**. This is a bounded desk-research assessment by AI agents, not customer discovery interviews, adoption evidence, an exhaustive market census, or proof of universal uniqueness. Sources can change after this date. + +## Documented problem and inferred audience + +[Godot's own translator guide](https://github.com/godotengine/godot-contributing-docs/blob/main/other/translations.rst) warns that delayed offline translation uploads can overwrite other contributors' intervening work. It recommends online Weblate editing. Godot uses PO, which locreturn does not support; the guide establishes a concurrency problem class, not a prospective customer relationship. + +[LiftTrace's contribution guide](https://github.com/TraceApps/lifttrace/blob/main/CONTRIBUTING.md) explains that English text can change under the same JSON key and asks translators to diff against the original version to identify stale translations. It also provides Weblate as a preferred workflow. The current guide includes nested JSON, which is outside locreturn's supported flat scope; it documents source-drift pain without establishing exact format fit. + +[OneTimeSecret issue #2015](https://github.com/onetimesecret/onetimesecret/issues/2015) documents recurring locale JSON conflicts across contributor updates and branch merges, and proposes an existing semantic merge driver. Basic JSON merge is already addressed; this issue is evidence of a problem and an effective alternative, not evidence that locreturn is required. + +**Inference:** a small group maintaining flat JSON catalogs, exchanging files outside a TMS, and continuing copy/target edits during a handoff may benefit from local per-key source-qualified reconciliation. That exact demand remains unvalidated. A generic translation checker, metadata inventory, CSV exporter or JSON merge wrapper was rejected as too crowded and insufficiently differentiated. + +## Three competition checks + +The lead and two independent AI agents searched primary product documentation, open-source repositories and concrete import/merge implementations. Native platforms were checked first, standalone handoff tools second, and semantic merge/versioned synchronization third. The resulting scope combines established ideas into a deliberately small service-free workflow. + +| Alternative | Documented strength | Why choose it / locreturn boundary | +|---|---|---| +| [Weblate offline files](https://docs.weblate.org/en/latest/user/files.html) | Offline exports/imports into changed translations; review, language metadata and conflict policies based on untranslated/translated/approved state | Prefer it for ongoing translator collaboration. This page does not document an exported source+target baseline comparison per returned key. | +| [Crowdin offline translation](https://support.crowdin.com/offline-translation/) and [version management](https://support.crowdin.com/version-management/) | CAT-friendly XLIFF and original formats; project branches and conflict handling | Prefer it for a managed project and translation teams. locreturn avoids service setup and requires its own small JSON return format. | +| [Lokalise offline translation](https://docs.lokalise.com/en/articles/2561895-offline-translation) and [branching](https://docs.lokalise.com/en/articles/3391861-project-branching) | Source verification/retranslation on offline return; per-key branch conflicts | Source validation is established. Prefer it when centralized reviews and branch workflows fit. locreturn hard-blocks changed-source incoming text and compares original/current targets locally. | +| [Phrase branching](https://support.phrase.com/hc/en-us/articles/5856411356316-Branching-Strings) | Base/branch conflict detection and merge strategies | A strong platform alternative, not an absent capability. | +| [Tolgee CLI](https://docs.tolgee.io/tolgee-cli/push-pull-strings) and [branching](https://docs.tolgee.io/platform/branching/overview) | Framework integrations, push/pull conflict modes and project branching | Prefer for hosted/self-hosted localization operations. locreturn has no server or runtime integration. | +| [BabelEdit import/export](https://www.codeandweb.com/babeledit/documentation/import-export) | Multi-language editing and translator CSV round trips | Prefer its editor and broader format support. Import documentation specifies IDs/language columns; it does not describe source+target export-baseline reconciliation. | +| [Trox handoff](https://github.com/thurn/trox) | Protected workbook, identity/placeholder checks; rejects changed source catalogs and canonical CSV edits | Excellent when adopting its Rust/TypeScript localization system. locreturn selectively reconciles independent returned edits against existing flat JSON without adopting that runtime. | +| [LocalizationManager import](https://github.com/nickprotop/LocalizationManager/blob/main/docs/COMMANDS.md) | Format support, backups and CSV imports, with fill-missing or overwrite policies | Good broad resource editor; documented import policy differs from source-qualified baseline comparison. | +| [i18nsmith CSV importer at 44e757f](https://github.com/IMAGINARY9/i18nsmith/blob/44e757feea49c9ffc1f08f04d62f1947f79ad6da/packages/cli/src/commands/translate/csv-handler.ts) | Useful offline CSV handoff and placeholder validation | Inspection found validation against CSV source text and overwrite/fill behavior, without a retained target baseline or current-source comparison in that importer. This does not claim every other command behaves identically. | +| [i1n comparator at 94be41d](https://github.com/Pakvothe/i1n-cli/blob/94be41d5866d6b5d92fa63ad6f432605e71f1b2c/src/shared/push-state.ts) | Real three-way hosted synchronization per namespace/key/language | Inspection found no source-locale argument or cross-language source gate in this comparator. Inference: that comparator alone does not provide locreturn's source-qualified return rule. No claim is made about all server semantics. | +| [git-json-merge](https://github.com/jonatanpedersen/git-json-merge) / Git | Established common-ancestor structured/text merge | Prefer for ordinary branch merges. A target-file merge alone does not compare a separately changed source catalog/context. locreturn implements its own per-entry rules rather than wrapping the command. | +| [Translate Toolkit pomerge](https://docs.translatehouse.org/projects/translate-toolkit/en/latest/commands/pomerge.html) | Applying corrected PO/XLIFF/TMX snippets with configurable fuzzy/blank behavior | Prefer for supported bilingual formats. locreturn handles explicitly paired flat-JSON source/target snapshots. | + +Absence of a feature from one documentation page is not proof that a product cannot do it. None of these checks establish a monopoly on this workflow. If a native platform already fits, introducing another return format adds friction and locreturn may be the wrong choice. + +## Applying Crossing the Chasm selectively + +[Geoffrey Moore's own book page](https://geoffreyamoore.com/book/crossing-the-chasm/) emphasizes target segment, compelling reason, whole product and positioning versus incumbent alternatives. [Moore's Chasm Group article](https://chasmgroup.com/crossing-the-chasm-whats-new-whats-not/) provides the original author's continuing perspective. We apply those ideas to scope and usability, not an invented financial/distribution strategy. + +**Beachhead:** developer-maintainers of small applications with flat JSON catalogs who exchange one locale's human translation file outside a TMS and keep editing during the return interval. Translators need only a JSON editor; maintainers need Python and their existing application checks. + +**Compelling reason:** accept independent safe work while making competing target edits and changed source/context visible before any final catalog is emitted. Reissuing an entire handoff or manually correlating two target histories and two source versions is avoidable within this narrow scope. + +**Market alternative:** manually compare the returned file with current JSON and original source snapshots in an editor/Git. **Product alternative:** adopt Weblate or another TMS for shared state, reviews and offline uploads. Both alternatives are valid and often preferable. + +**Original two-sentence positioning:** For maintainers of small flat-JSON application catalogs who are dissatisfied with manually correlating delayed translator returns and intervening copy corrections, locreturn is a local translation-return reconciler that qualifies every incoming edit against original and current source, context and target text. Unlike adopting a translation management platform for this single handoff, locreturn supplies the complete file-only workflow: a trusted baseline, editable task, per-key review plan, reasoned conflict decisions, stale-plan refusal, a new target and a reproducible content receipt. + +**Whole supported product:** installable wheel/sdist, offline CLI, explicit contracts and limits, error codes, task/decision templates, human review text, complete output, audit receipt, examples, acceptance tests, independently reviewed code and actual release-artifact verification. No reference customers, measured savings or production deployments are claimed. + +## Constructed usage scenarios + +These are invented examples, not observations or endorsements. + +1. An open-source desktop utility sends a French task on Monday. A maintainer corrects one French button while the translator changes another. locreturn accepts the independent change and preserves the local correction; divergent edits to the same button need a decision. +2. English “Save” changes to “Save backup” during translation. The incoming French text is source-changed even if its target matches current French. A reviewer retains current text or writes a custom translation against “Save backup,” with a reason. +3. A key's spelling stays identical but its context changes from a financial bank to a river bank. Supplying updated context blocks stale incoming work. Without updated text or context, no deterministic equality tool can infer the meaning change. diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md new file mode 100644 index 0000000..baba917 --- /dev/null +++ b/docs/VERIFICATION.md @@ -0,0 +1,19 @@ +# Verification and review record + +## Development review, 2026-10-15 + +Two separate AI agents independently reviewed the opportunity and challenged existing alternatives. They are AI-agent assessments, not human reviews or independent GitHub accounts. + +The testing agent wrote 32 adversarial acceptance tests and ran them independently on Python 3.12.13. The lead's suite adds 17 tests, including an exhaustive 64-case target-state table and CLI round trips. All 49 tests passed locally on macOS/Python 3.12 before the implementation PR. + +A separate code/security reviewer read all five source files, ran 192 finite-state cases and 17 CLI probes, and reported one P3 issue: Python equality accepted boolean/number substitutions in a modified plan. The lead changed comparison to canonical JSON bytes; both independent agents verified the regression now fails safely. No blocking findings remained within the supported CLI/single-writer scope. Core file SHA-256 reviewed after the fix: `8e2202007a9c722b23d1975a1b4d48ab699d55f8bbb6acc5791f38557241b352`. + +The tests cover concurrent deletion/addition, empty vs absent targets, source/context drift, unknown and duplicate keys, invalid Unicode, stale input/plan/decisions, output overwrite/symlink refusal, midwrite cleanup, FIFO refusal, resource limits, terminal escaping and relocation. Runtime translation quality is explicitly outside scope. + +## Release process + +The protected main branch requires `quality-gate`, aggregating four OS/Python test jobs (Linux 3.10/3.14, macOS 3.12, Windows 3.12) and Linux 3.12 distribution installation checks. This targets minimum/recent interpreter compatibility and cross-platform filesystem behavior without multiplying every combination. The single maintainer records separate AI-agent review evidence in PR comments and merges only after required checks pass; no human self-approval is represented as independent review. + +CI builds wheel/sdist, installs both outside the checkout in separate fresh environments, runs the full suite and constructed example, and uploads artifacts with a manifest recording source revision and Actions run. Release assets are taken from the passing main-branch CI build, with a SHA-256 checksum file. These provenance records identify the build; they are not third-party signatures. + +Actual post-publication download and installation evidence will be recorded after release in this document and the release notes. A local build or CI artifact alone is not described as a verified public release. diff --git a/examples/demo.py b/examples/demo.py new file mode 100644 index 0000000..e4b6770 --- /dev/null +++ b/examples/demo.py @@ -0,0 +1,61 @@ +"""Constructed offline round trip. Run with the installed product's Python. + +Uses only a temporary directory, creates no persistent project files, performs +no network access. This example demonstrates mechanics, not linguistic advice. +""" + +import json +import subprocess +import sys +import tempfile +from pathlib import Path + + +def main(): + with tempfile.TemporaryDirectory(prefix="locreturn-demo-") as tmp: + root = Path(tmp) + + def write(name, value): + (root / name).write_text(json.dumps(value), encoding="utf-8") + + def read(name): + return json.loads((root / name).read_text(encoding="utf-8")) + + def run(*args, expected=0): + result = subprocess.run([sys.executable, "-m", "locreturn", *args], + cwd=root, text=True, capture_output=True) + if result.returncode != expected: + raise RuntimeError(result.stdout + result.stderr) + print(result.stdout.strip()) + + write("en.json", {"save": "Save", "help": "Help", "cancel": "Cancel"}) + write("fr.json", {"save": "Sauver", "cancel": "Annuler", "orphan": "Retained"}) + run("pack", "--source", "en.json", "--target", "fr.json", "--source-locale", "en", "--target-locale", "fr", "--out", "job") + task = read("job/task.json") + task["entries"]["save"]["translation"] = "Enregistrer" + task["entries"]["help"]["translation"] = "Aide" + write("job/task.json", task) + # A concurrent local correction makes 'save' a real target conflict. + write("fr.json", {"save": "Local correction", "cancel": "Annuler", "orphan": "Retained"}) + common = ["--source", "en.json", "--target", "fr.json", "--baseline", "job/baseline.json", "--returned", "job/task.json"] + run("plan", *common, "--out", "review", expected=3) + run("apply", *common, "--plan", "review/plan.json", "--out", "blocked", expected=2) + if (root / "blocked").exists(): + raise AssertionError("unresolved conflict created final output") + decisions = read("review/decisions.json") + decisions["entries"]["save"] = {"action": "keep", "text": None, "reason": "Constructed reviewer preserves local correction"} + write("review/decisions.json", decisions) + run("apply", *common, "--plan", "review/plan.json", "--decisions", "review/decisions.json", "--out", "merged") + output = read("merged/target.json") + if output != {"save": "Local correction", "help": "Aide", "cancel": "Annuler", "orphan": "Retained"}: + raise AssertionError(output) + # A plan cannot be applied after even an unrelated source edit. + write("en.json", {"save": "Save now", "help": "Help", "cancel": "Cancel"}) + run("apply", *common, "--plan", "review/plan.json", "--decisions", "review/decisions.json", "--out", "stale", expected=2) + if (root / "stale").exists(): + raise AssertionError("stale plan created output") + print("Constructed round trip passed: safe edit, concurrent correction, orphan preservation, unresolved and stale refusal.") + + +if __name__ == "__main__": + main() diff --git a/examples/en.json b/examples/en.json new file mode 100644 index 0000000..9f96203 --- /dev/null +++ b/examples/en.json @@ -0,0 +1 @@ +{"save": "Save", "cancel": "Cancel", "help": "Help"} diff --git a/examples/fr.json b/examples/fr.json new file mode 100644 index 0000000..f14592b --- /dev/null +++ b/examples/fr.json @@ -0,0 +1 @@ +{"save": "Sauver", "cancel": "Annuler", "orphan": "Conserver"} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a4039a3 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,25 @@ +[build-system] +requires = ["setuptools>=77", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "locreturn" +version = "1.0.0" +description = "Source-aware reconciliation for offline JSON translation returns" +readme = "README.md" +requires-python = ">=3.10" +license = "MIT" +license-files = ["LICENSE"] +authors = [{name = "locreturn contributors"}] +dependencies = [] +classifiers = ["Programming Language :: Python :: 3", "Operating System :: OS Independent", "Topic :: Software Development :: Localization"] + +[project.scripts] +locreturn = "locreturn.cli:main" + +[project.urls] +Repository = "https://github.com/waxwingfactor/locreturn" +Issues = "https://github.com/waxwingfactor/locreturn/issues" + +[tool.setuptools.packages.find] +where = ["src"] diff --git a/src/locreturn/__init__.py b/src/locreturn/__init__.py new file mode 100644 index 0000000..2ba5ed5 --- /dev/null +++ b/src/locreturn/__init__.py @@ -0,0 +1,3 @@ +"""The supported public interface is the locreturn CLI; schemas are versioned.""" + +__version__ = "1.0.0" diff --git a/src/locreturn/__main__.py b/src/locreturn/__main__.py new file mode 100644 index 0000000..eb53e2f --- /dev/null +++ b/src/locreturn/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +raise SystemExit(main()) diff --git a/src/locreturn/cli.py b/src/locreturn/cli.py new file mode 100644 index 0000000..b1db539 --- /dev/null +++ b/src/locreturn/cli.py @@ -0,0 +1,69 @@ +"""Command-line interface. No network, subprocesses, or implicit file discovery.""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +from . import __version__ +from . import core +from .files import read_json, review_text, write_bundle + + +def parser() -> argparse.ArgumentParser: + root = argparse.ArgumentParser(description="Reconcile offline JSON translation returns against source and target baselines.") + root.add_argument("--version", action="version", version=f"locreturn {__version__}") + subs = root.add_subparsers(dest="command", required=True) + pack = subs.add_parser("pack", help="create a trusted baseline and an editable translator task") + pack.add_argument("--source-locale", required=True) + pack.add_argument("--target-locale", required=True) + for name in ("pack", "plan", "apply"): + sub = pack if name == "pack" else subs.add_parser(name, help={"plan": "classify a return; exit 3 when conflicts need review", "apply": "verify a reviewed plan and emit a new target catalog"}[name]) + sub.add_argument("--source", type=Path, required=True, help="current flat source JSON") + sub.add_argument("--target", type=Path, required=True, help="current flat target JSON (use {} for a new locale)") + sub.add_argument("--context", type=Path, help="optional current key-to-context JSON") + sub.add_argument("--out", type=Path, required=True, help="new output directory; never overwrites") + if name != "pack": + sub.add_argument("--baseline", type=Path, required=True) + sub.add_argument("--returned", type=Path, required=True, help="edited task JSON") + if name == "apply": + sub.add_argument("--plan", type=Path, required=True, help="reviewed plan.json") + sub.add_argument("--decisions", type=Path, help="completed decisions.json; required when conflicts exist") + return root + + +def run(args: argparse.Namespace) -> tuple[dict, int]: + source, target = read_json(args.source), read_json(args.target) + context = read_json(args.context) if args.context else {} + if args.command == "pack": + baseline, task = core.pack(source, target, args.source_locale, args.target_locale, context) + write_bundle(args.out, {"baseline.json": baseline, "task.json": task}) + return {"command": "pack", "job_id": baseline["job_id"], "entries": len(source)}, 0 + base, returned = read_json(args.baseline), read_json(args.returned) + expected = core.plan(base, returned, source, target, context) + if args.command == "plan": + write_bundle(args.out, {"plan.json": expected, + "decisions.json": core.decision_template(expected), + "review.txt": review_text(expected)}) + return {"command": "plan", "plan_id": expected["plan_id"], + "conflicts": expected["conflicts"], "counts": expected["counts"]}, 3 if expected["conflicts"] else 0 + p = read_json(args.plan) + decisions = read_json(args.decisions) if args.decisions else None + result, receipt = core.apply(p, expected, target, decisions) + write_bundle(args.out, {"target.json": result, "receipt.json": receipt}) + return {"command": "apply", "plan_id": p["plan_id"], "changes": len(receipt["changes"]), + "resolved_conflicts": receipt["resolved_conflicts"], "receipt_id": receipt["receipt_id"]}, 0 + + +def main(argv: list[str] | None = None) -> int: + args = parser().parse_args(argv) + try: + summary, code = run(args) + except (core.Invalid, OSError, ValueError, TypeError, RecursionError) as exc: + # JSON escaped error text avoids raw filenames/control codes on terminals. + print(json.dumps({"error": str(exc)}, ensure_ascii=True), file=sys.stderr) + return 2 + print(json.dumps(summary, ensure_ascii=True, sort_keys=True)) + return code diff --git a/src/locreturn/core.py b/src/locreturn/core.py new file mode 100644 index 0000000..b41c323 --- /dev/null +++ b/src/locreturn/core.py @@ -0,0 +1,234 @@ +"""Pure, deterministic source-qualified three-way reconciliation. + +Missing target values use None internally; catalog values can only be strings. +No normalization, runtime syntax interpretation, or implicit deletion occurs. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from collections import Counter +from typing import Any + +MAX_ENTRIES = 10_000 +MAX_TEXT = 65_536 +MAX_KEY = 1_024 +MAX_FILE = 32 * 1024 * 1024 +CONFLICTS = {"source-changed", "source-removed", "target-conflict"} + + +class Invalid(ValueError): + """A user input violates the supported contract.""" + + +def require(condition: bool, message: str) -> None: + if not condition: + raise Invalid(message) + + +def text(value: Any, label: str, limit: int = MAX_TEXT) -> str: + require(isinstance(value, str), f"{label}: expected a string") + require(len(value) <= limit, f"{label}: exceeds {limit} characters") + require(not any(0xD800 <= ord(c) <= 0xDFFF for c in value), + f"{label}: unpaired Unicode surrogate") + return value + + +def shape(value: Any, keys: set[str], label: str) -> dict: + require(isinstance(value, dict), f"{label}: expected an object") + require(set(value) == keys, f"{label}: expected fields {', '.join(sorted(keys))}") + return value + + +def catalog(value: Any, label: str) -> dict[str, str]: + require(isinstance(value, dict), f"{label}: expected a flat key-to-string JSON object") + require(len(value) <= MAX_ENTRIES, f"{label}: exceeds {MAX_ENTRIES} entries") + for key, val in value.items(): + text(key, f"{label} key", MAX_KEY) + require(bool(key), f"{label}: empty keys are unsupported") + text(val, f"{label} value") + return value + + +def locale(value: Any) -> str: + text(value, "locale", 64) + require(bool(re.fullmatch(r"[A-Za-z]{2,8}(?:[-_][A-Za-z0-9]{1,8})*", value)), + "locale: use a language tag such as en, fr-CA or pt_BR") + return value + + +def canonical(value: Any) -> bytes: + return json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":"), allow_nan=False).encode("utf-8") + + +def digest(value: Any) -> str: + return hashlib.sha256(canonical(value)).hexdigest() + + +def seal(payload: dict, field: str) -> dict: + return {**payload, field: digest(payload)} + + +def check_seal(value: dict, field: str, label: str) -> None: + payload = {k: v for k, v in value.items() if k != field} + require(value[field] == digest(payload), f"{label}: invalid {field}; keep the original trusted file") + + +def contexts(value: Any, source: dict) -> dict: + catalog(value, "context") + require(set(value) <= set(source), "context: keys must exist in source") + return value + + +def pack(source: dict, target: dict, source_locale: str, target_locale: str, + context: dict | None = None) -> tuple[dict, dict]: + catalog(source, "source") + catalog(target, "target") + require(len(set(source) | set(target)) <= MAX_ENTRIES, + f"combined catalog exceeds {MAX_ENTRIES} keys") + locale(source_locale) + locale(target_locale) + require(source_locale.lower().replace("_", "-") != target_locale.lower().replace("_", "-"), + "source and target locales must differ") + context = contexts(context if context is not None else {}, source) + baseline = seal({"schema": "locreturn.baseline.v1", "source_locale": source_locale, + "target_locale": target_locale, "source": source, "target": target, + "context": context}, "job_id") + task = {"schema": "locreturn.return.v1", "job_id": baseline["job_id"], + "source_locale": source_locale, "target_locale": target_locale, + "entries": {k: {"source": source[k], "context": context.get(k), + "previous_target": target.get(k), "translation": None} + for k in sorted(source)}} + return baseline, task + + +def baseline_check(base: Any) -> dict: + shape(base, {"schema", "source_locale", "target_locale", "source", "target", "context", "job_id"}, "baseline") + require(base["schema"] == "locreturn.baseline.v1", "unsupported baseline schema") + rebuilt, _ = pack(base["source"], base["target"], base["source_locale"], + base["target_locale"], base["context"]) + require(base == rebuilt, "baseline: invalid job_id; keep the original trusted file") + return base + + +def returned_check(returned: Any, base: dict) -> dict: + shape(returned, {"schema", "job_id", "source_locale", "target_locale", "entries"}, "return") + require(returned["schema"] == "locreturn.return.v1", "unsupported return schema") + for key in ("job_id", "source_locale", "target_locale"): + require(returned[key] == base[key], f"return: {key} does not match baseline") + entries = returned["entries"] + require(isinstance(entries, dict) and len(entries) <= MAX_ENTRIES, "return: invalid entries object") + require(set(entries) <= set(base["source"]), "return: unknown keys; do not add or rename keys") + for key, row in entries.items(): + shape(row, {"source", "context", "previous_target", "translation"}, "return entry") + for field, expected in (("source", base["source"][key]), + ("context", base["context"].get(key)), + ("previous_target", base["target"].get(key))): + require(row[field] == expected, f"return: modified {field}; edit translation only") + if row["translation"] is not None: + text(row["translation"], "translation") + return returned + + +def plan(base: dict, returned: dict, source: dict, target: dict, + context: dict | None = None) -> dict: + baseline_check(base) + returned_check(returned, base) + catalog(source, "current source") + catalog(target, "current target") + context = contexts(context if context is not None else {}, source) + rows = [] + keys = set(base["source"]) | set(source) | set(target) | set(base["target"]) + require(len(keys) <= MAX_ENTRIES, f"combined catalog exceeds {MAX_ENTRIES} keys") + for key in sorted(keys): + incoming = returned["entries"].get(key, {}).get("translation") + original = base["target"].get(key) + current = target.get(key) + source_changed = (base["source"].get(key) != source.get(key) + or base["context"].get(key) != context.get(key)) + if key not in base["source"]: + status = "new-source" if key in source else "orphan-target" + elif key not in returned["entries"]: + status = "not-returned" + elif incoming is None: + status = "skipped" + elif incoming == original: + status = "unchanged-return" + elif key not in source: + status = "source-removed" + elif source_changed: + status = "source-changed" + elif incoming == current: + status = "already-current" + elif current == original: + status = "ready" + else: + status = "target-conflict" + rows.append({"key": key, "status": status, "source_changed": source_changed, + "base_source": base["source"].get(key), "current_source": source.get(key), + "base_context": base["context"].get(key), "current_context": context.get(key), + "base_target": original, "current_target": current, "incoming": incoming}) + counts = dict(sorted(Counter(r["status"] for r in rows).items())) + return seal({"schema": "locreturn.plan.v1", "job_id": base["job_id"], + "source_locale": base["source_locale"], "target_locale": base["target_locale"], + "inputs": {"baseline": digest(base), "return": digest(returned), + "source": digest(source), "target": digest(target), "context": digest(context)}, + "counts": counts, "conflicts": sum(r["status"] in CONFLICTS for r in rows), + "rows": rows}, "plan_id") + + +def decision_template(p: dict) -> dict: + return {"schema": "locreturn.decisions.v1", "plan_id": p["plan_id"], + "entries": {r["key"]: {"action": "unresolved", "text": None, "reason": ""} + for r in p["rows"] if r["status"] in CONFLICTS}} + + +def apply(p: dict, expected_plan: dict, target: dict, decisions: dict | None = None) -> tuple[dict, dict]: + require(canonical(p) == canonical(expected_plan), + "plan is stale or modified; regenerate and review a new plan") + decisions = decisions if decisions is not None else decision_template(p) + shape(decisions, {"schema", "plan_id", "entries"}, "decisions") + require(decisions["schema"] == "locreturn.decisions.v1", "unsupported decisions schema") + require(decisions["plan_id"] == p["plan_id"], "decisions refer to a different plan") + needed = {r["key"] for r in p["rows"] if r["status"] in CONFLICTS} + require(isinstance(decisions["entries"], dict) and set(decisions["entries"]) == needed, + "decisions must contain exactly every conflict key") + result = dict(target) + changes = [] + for row in p["rows"]: + key, status = row["key"], row["status"] + action, value, reason = "keep", target.get(key), None + if status == "ready": + action, value = "incoming", row["incoming"] + elif status in CONFLICTS: + d = decisions["entries"][key] + shape(d, {"action", "text", "reason"}, "decision") + action = d["action"] + allowed = {"keep"} + if status != "source-removed": + allowed.add("custom") + if status == "target-conflict": + allowed.add("incoming") + require(action in allowed, f"decision action unresolved or disallowed for {status}") + reason = text(d["reason"], "decision reason", 4096) + require(bool(reason.strip()), "decision requires a nonempty review reason") + if action == "custom": + value = text(d["text"], "custom translation") + else: + require(d["text"] is None, "text must be null unless action is custom") + if action == "incoming": + value = row["incoming"] + if action != "keep": + result[key] = value + if result.get(key) != target.get(key): + changes.append({"key": key, "before": target.get(key), "after": result[key], + "action": action, "reason": reason}) + receipt = seal({"schema": "locreturn.receipt.v1", "plan_id": p["plan_id"], + "job_id": p["job_id"], "inputs": p["inputs"], + "decisions_sha256": digest(decisions), "output_sha256": digest(result), + "changes": changes, "resolved_conflicts": len(needed), + "decisions": decisions["entries"]}, "receipt_id") + return result, receipt diff --git a/src/locreturn/files.py b/src/locreturn/files.py new file mode 100644 index 0000000..8e4057d --- /dev/null +++ b/src/locreturn/files.py @@ -0,0 +1,91 @@ +"""Bounded JSON I/O and exclusive bundle output, with no catalog mutation.""" + +from __future__ import annotations + +import json +import os +import stat +from pathlib import Path + +from .core import MAX_FILE, Invalid, require + + +def unique_object(pairs: list) -> dict: + result = {} + for key, value in pairs: + require(key not in result, "JSON contains a duplicate object key") + result[key] = value + return result + + +def invalid_constant(value: str) -> None: + raise Invalid(f"non-finite JSON value is unsupported: {value}") + + +def read_json(path: Path) -> dict: + # Nonblocking open lets us reject FIFOs/devices without waiting for writers. + fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)) + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + require(stat.S_ISREG(info.st_mode), "input must be a regular JSON file") + require(info.st_size <= MAX_FILE, f"input exceeds {MAX_FILE} bytes") + raw = stream.read(MAX_FILE + 1) + require(len(raw) <= MAX_FILE, f"input exceeds {MAX_FILE} bytes") + try: + return json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object, + parse_constant=invalid_constant) + except Invalid: + raise + except (UnicodeError, json.JSONDecodeError, RecursionError, ValueError) as exc: + raise Invalid(f"invalid UTF-8 JSON: {exc.__class__.__name__}") from exc + + +def json_bytes(value: dict) -> bytes: + return (json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True, + allow_nan=False) + "\n").encode("utf-8") + + +def write_bundle(folder: Path, files: dict[str, dict | str]) -> None: + """Pre-serialize every file, then claim a new directory exclusively. + + Single-writer local filesystems are supported. A directory may be visible + while being populated. On ordinary failures remove only files we created. + Never overwrite an existing path, follow an output symlink, or edit inputs. + """ + encoded = {name: value.encode("utf-8") if isinstance(value, str) else json_bytes(value) + for name, value in files.items()} + for value in encoded.values(): + require(len(value) <= MAX_FILE, f"generated file exceeds {MAX_FILE} bytes; use a smaller catalog") + created = [] + folder.mkdir() # exclusive; existing directories, files and symlinks fail + try: + for name, value in encoded.items(): + with (folder / name).open("xb") as stream: + created.append(folder / name) + stream.write(value) + stream.flush() + os.fsync(stream.fileno()) + except BaseException: + for path in reversed(created): + try: + path.unlink() + except OSError: + pass + try: + folder.rmdir() + except OSError: + pass + raise + + +def review_text(p: dict) -> str: + lines = ["locreturn review", f"Plan: {p['plan_id']}", + f"Locale: {p['source_locale']} -> {p['target_locale']}", + f"Conflicts requiring decisions: {p['conflicts']}", + "Counts: " + json.dumps(p["counts"], sort_keys=True), + "Review source, context, and target changes below.", + "Success does not certify translation quality, runtime syntax, or source currency.", ""] + # JSON escaping prevents terminal control codes and misleading multiline rows. + for row in p["rows"]: + lines.append(json.dumps(row, ensure_ascii=True, sort_keys=True)) + return "\n".join(lines) + "\n" diff --git a/tests/test_adversarial.py b/tests/test_adversarial.py new file mode 100644 index 0000000..8aebacc --- /dev/null +++ b/tests/test_adversarial.py @@ -0,0 +1,316 @@ +"""Independent hostile-input and review-integrity acceptance tests. + +These test the public CLI path where possible. They intentionally exercise +boundaries rather than repeating the ordinary reconciliation decision matrix. +""" + +import copy +import io +import json +import os +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest import mock + +from locreturn import cli, core, files + + +class AdversarialAcceptance(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.source = {"hello": "Hello", "empty": "Empty"} + self.target = {"hello": "Bonjour", "orphan": "Preserved"} + self.context = {"hello": "Friendly greeting"} + self.base, self.returned = core.pack( + self.source, self.target, "en", "fr", self.context + ) + self.returned["entries"]["hello"]["translation"] = "Salut" + self.current_source = dict(self.source) + self.current_target = dict(self.target) + self.current_context = dict(self.context) + + def write(self, name, value): + path = self.root / name + path.write_text(json.dumps(value, ensure_ascii=True), encoding="utf-8") + return path + + def run_cli(self, *args): + stdout, stderr = io.StringIO(), io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + code = cli.main(list(map(str, args))) + return code, stdout.getvalue(), stderr.getvalue() + + def input_paths(self): + return { + "source": self.write("source.json", self.current_source), + "target": self.write("target.json", self.current_target), + "context": self.write("context.json", self.current_context), + "baseline": self.write("baseline.json", self.base), + "returned": self.write("returned.json", self.returned), + } + + def make_plan(self): + return core.plan(self.base, self.returned, self.current_source, + self.current_target, self.current_context) + + def apply_cli(self, paths, reviewed_plan, output_name="applied"): + plan_path = self.write("reviewed-plan.json", reviewed_plan) + args = ["apply", "--plan", plan_path, "--out", self.root / output_name] + for name, path in paths.items(): + args.extend(["--" + name, path]) + return self.run_cli(*args) + + def assert_invalid_file(self, raw): + path = self.root / "bad.json" + path.write_bytes(raw) + with self.assertRaises(core.Invalid): + files.read_json(path) + + def test_duplicate_keys_rejected_at_every_depth(self): + for raw in (b'{"a":"one","a":"two"}', + b'{"entries":{"a":{"translation":"x","translation":"y"}}}'): + with self.subTest(raw=raw): + self.assert_invalid_file(raw) + + def test_nonfinite_literals_rejected(self): + for value in ("NaN", "Infinity", "-Infinity"): + with self.subTest(value=value): + self.assert_invalid_file(('{"a":' + value + '}').encode()) + + def test_invalid_encoding_and_json_rejected(self): + for raw in (b'{"a":"\xff"}', b'{"a":}', b'\xef\xbb\xbf{}', b'{'): + with self.subTest(raw=raw): + self.assert_invalid_file(raw) + + def test_extreme_nesting_is_controlled_error(self): + paths = self.input_paths() + paths["source"].write_bytes(b'[' * 3000 + b'0' + b']' * 3000) + code, stdout, stderr = self.apply_cli(paths, self.make_plan()) + self.assertEqual(code, 2) + self.assertEqual(stdout, "") + self.assertIn("error", json.loads(stderr)) + self.assertNotIn("Traceback", stderr) + self.assertFalse((self.root / "applied").exists()) + + def test_catalog_rejects_all_nonstring_values(self): + for value in (None, True, 1, 1.5, [], {}, ["x"]): + with self.subTest(value=value), self.assertRaises(core.Invalid): + core.pack({"a": value}, {}, "en", "fr") + + def test_catalog_rejects_nonobject_top_level(self): + for value in ([], None, "text", 1): + with self.subTest(value=value), self.assertRaises(core.Invalid): + core.pack(value, {}, "en", "fr") + + def test_unpaired_surrogates_rejected_in_keys_and_values(self): + for source in ({"x": "\ud800"}, {"\udfff": "x"}): + with self.subTest(source=repr(source)), self.assertRaises(core.Invalid): + core.pack(source, {}, "en", "fr") + + def test_text_key_and_entry_limits_enforced(self): + candidates = ({"x": "x" * (core.MAX_TEXT + 1)}, + {"x" * (core.MAX_KEY + 1): "x"}, + {"": "x"}, + {str(i): "x" for i in range(core.MAX_ENTRIES + 1)}) + for source in candidates: + with self.subTest(size=len(source)), self.assertRaises(core.Invalid): + core.pack(source, {}, "en", "fr") + + def test_combined_union_limit_enforced(self): + self.current_target = {f"orphan-{i}": "x" for i in range(core.MAX_ENTRIES)} + with self.assertRaises(core.Invalid): + self.make_plan() + + def test_context_keys_must_exist_in_current_source(self): + self.current_context["unknown"] = "context" + with self.assertRaises(core.Invalid): + self.make_plan() + + def test_edited_task_identity_fields_are_rejected(self): + for name, value in (("source", "Different source"), + ("context", "Different context"), + ("previous_target", "Different translation")): + returned = copy.deepcopy(self.returned) + returned["entries"]["hello"][name] = value + with self.subTest(field=name), self.assertRaises(core.Invalid): + core.plan(self.base, returned, self.source, self.target, self.context) + + def test_edited_job_and_locale_are_rejected(self): + for name in ("job_id", "source_locale", "target_locale"): + returned = copy.deepcopy(self.returned) + returned[name] = "tampered" + with self.subTest(field=name), self.assertRaises(core.Invalid): + core.plan(self.base, returned, self.source, self.target, self.context) + + def test_unknown_task_keys_and_fields_are_rejected(self): + for mutation in ("key", "row-field", "top-field"): + returned = copy.deepcopy(self.returned) + if mutation == "key": + returned["entries"]["not-exported"] = copy.deepcopy(returned["entries"]["hello"]) + elif mutation == "row-field": + returned["entries"]["hello"]["extra"] = "ignored?" + else: + returned["extra"] = "ignored?" + with self.subTest(mutation=mutation), self.assertRaises(core.Invalid): + core.plan(self.base, returned, self.source, self.target, self.context) + + def test_context_addition_removal_and_change_invalidate_incoming(self): + for old_context, new_context in (({}, {"hello": "new"}), + ({"hello": "old"}, {}), + ({"hello": "old"}, {"hello": "new"})): + base, returned = core.pack(self.source, self.target, "en", "fr", old_context) + returned["entries"]["hello"]["translation"] = "Salut" + p = core.plan(base, returned, self.source, self.target, new_context) + row = next(row for row in p["rows"] if row["key"] == "hello") + with self.subTest(old=old_context, new=new_context): + self.assertEqual(row["status"], "source-changed") + self.assertTrue(row["source_changed"]) + + def test_returned_source_unicode_is_compared_without_normalizing(self): + self.current_source["hello"] = "Hello\u0301" + p = self.make_plan() + row = next(row for row in p["rows"] if row["key"] == "hello") + self.assertEqual(row["status"], "source-changed") + + def test_untrusted_baseline_edit_without_resealing_fails(self): + self.base["source"]["hello"] = "New meaning" + with self.assertRaises(core.Invalid): + self.make_plan() + + def test_plan_tamper_is_rejected_without_output(self): + p = self.make_plan() + p["rows"][0]["incoming"] = "Injected" + code, _, error = self.apply_cli(self.input_paths(), p) + self.assertEqual(code, 2, error) + self.assertFalse((self.root / "applied").exists()) + + def test_numeric_type_plan_tamper_is_rejected(self): + p = self.make_plan() + # Python's structural equality considers False == 0 and True == 1. + p["conflicts"] = False + code, _, error = self.apply_cli(self.input_paths(), p) + self.assertEqual(code, 2, error) + self.assertFalse((self.root / "applied").exists()) + + def test_every_changed_plan_input_rejects_stale_apply(self): + original_plan = self.make_plan() + for changed in ("source", "target", "context", "returned", "baseline"): + paths = self.input_paths() + value = json.loads(paths[changed].read_text()) + if changed in ("source", "target", "context"): + value["hello"] = "Changed after plan" + elif changed == "returned": + value["entries"]["hello"]["translation"] = "Autre" + else: + value["target"]["hello"] = "Changed after plan" + self.write(paths[changed].name, value) + output_name = "applied-" + changed + code, _, error = self.apply_cli(paths, original_plan, output_name) + with self.subTest(changed=changed): + self.assertEqual(code, 2, error) + self.assertFalse((self.root / output_name).exists()) + + def test_semantic_key_reordering_does_not_stale_plan(self): + p = self.make_plan() + paths = self.input_paths() + paths["source"].write_text('{ "empty": "Empty", "hello": "Hello" }\n') + code, _, error = self.apply_cli(paths, p) + self.assertEqual(code, 0, error) + + def test_existing_output_directory_never_overwritten(self): + out = self.root / "existing" + out.mkdir() + sentinel = out / "target.json" + sentinel.write_bytes(b"keep me") + with self.assertRaises(FileExistsError): + files.write_bundle(out, {"target.json": {"changed": "yes"}}) + self.assertEqual(sentinel.read_bytes(), b"keep me") + + def test_existing_output_file_never_overwritten(self): + out = self.root / "existing" + out.write_bytes(b"keep me") + with self.assertRaises(FileExistsError): + files.write_bundle(out, {"target.json": {}}) + self.assertEqual(out.read_bytes(), b"keep me") + + @unittest.skipUnless(hasattr(os, "symlink"), "symlinks unavailable") + def test_output_symlink_never_followed(self): + existing = self.root / "protected" + existing.mkdir() + out = self.root / "link" + out.symlink_to(existing, target_is_directory=True) + with self.assertRaises(FileExistsError): + files.write_bundle(out, {"target.json": {}}) + self.assertEqual(list(existing.iterdir()), []) + + def test_serialization_failure_creates_no_bundle(self): + out = self.root / "invalid" + with self.assertRaises(ValueError): + files.write_bundle(out, {"first.json": {}, "second.json": {"v": float("nan")}}) + self.assertFalse(out.exists()) + + def test_generated_size_limit_creates_no_bundle(self): + out = self.root / "oversized" + with mock.patch.object(files, "MAX_FILE", 8), self.assertRaises(core.Invalid): + files.write_bundle(out, {"first.json": {"v": "too large"}}) + self.assertFalse(out.exists()) + + def test_midwrite_failure_cleans_only_created_bundle(self): + out = self.root / "failed" + with mock.patch.object(files.os, "fsync", side_effect=OSError("disk failure")): + with self.assertRaises(OSError): + files.write_bundle(out, {"first.json": {}, "second.json": {}}) + self.assertFalse(out.exists()) + + def test_input_size_limit(self): + path = self.write("large.json", {"v": "too large"}) + with mock.patch.object(files, "MAX_FILE", 8), self.assertRaises(core.Invalid): + files.read_json(path) + + def test_directory_input_is_rejected(self): + with self.assertRaises((OSError, core.Invalid)): + files.read_json(self.root) + + @unittest.skipUnless(hasattr(os, "mkfifo"), "FIFOs unavailable") + def test_fifo_input_is_rejected_without_waiting_for_writer(self): + path = self.root / "fifo" + os.mkfifo(path) + with self.assertRaises(core.Invalid): + files.read_json(path) + + def test_terminal_control_characters_are_escaped_in_review(self): + source = {"danger\x1b[2J": "Line\nTwo\t\x1b[2J"} + base, returned = core.pack(source, {}, "en", "fr") + rendered = files.review_text(core.plan(base, returned, source, {})) + self.assertNotIn("\x1b", rendered) + self.assertIn("\\u001b", rendered) + + def test_invalid_input_cli_emits_controlled_error_and_no_output(self): + paths = self.input_paths() + paths["returned"].write_bytes(b'{"a":') + code, stdout, stderr = self.apply_cli(paths, self.make_plan()) + self.assertEqual(code, 2) + self.assertEqual(stdout, "") + self.assertIn("error", json.loads(stderr)) + self.assertNotIn("Traceback", stderr) + self.assertFalse((self.root / "applied").exists()) + + def test_relocated_input_bundle_is_usable(self): + paths = self.input_paths() + relocated = self.root / "relocated" + relocated.mkdir() + moved_paths = {} + for name, path in paths.items(): + destination = relocated / path.name + path.rename(destination) + moved_paths[name] = destination + code, _, error = self.apply_cli(moved_paths, self.make_plan()) + self.assertEqual(code, 0, error) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..bf41945 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,80 @@ +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +class CliTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.cwd = Path(self.tmp.name) + self.write("en.json", {"save": "Save", "cancel": "Cancel"}) + self.write("fr.json", {"save": "Ancien"}) + + def write(self, name, value): + (self.cwd / name).write_text(json.dumps(value), encoding="utf-8") + + def load(self, name): + return json.loads((self.cwd / name).read_text(encoding="utf-8")) + + def cli(self, *args, code=0): + result = subprocess.run([sys.executable, "-m", "locreturn", *args], cwd=self.cwd, + text=True, capture_output=True) + self.assertEqual(result.returncode, code, result.stdout + result.stderr) + return result + + def pack(self): + self.cli("pack", "--source", "en.json", "--target", "fr.json", + "--source-locale", "en", "--target-locale", "fr", "--out", "job") + + def common(self): + return ["--source", "en.json", "--target", "fr.json", "--baseline", "job/baseline.json", "--returned", "job/task.json"] + + def test_end_to_end_review_and_apply(self): + self.pack() + task = self.load("job/task.json") + task["entries"]["save"]["translation"] = "Enregistrer" + task["entries"]["cancel"]["translation"] = "Annuler" + self.write("job/task.json", task) + self.write("fr.json", {"save": "Local correction"}) + self.cli("plan", *self.common(), "--out", "review", code=3) + self.cli("apply", *self.common(), "--plan", "review/plan.json", "--out", "blocked", code=2) + self.assertFalse((self.cwd / "blocked").exists()) + decisions = self.load("review/decisions.json") + decisions["entries"]["save"] = {"action": "keep", "text": None, "reason": "Preserve local correction"} + self.write("review/decisions.json", decisions) + self.cli("apply", *self.common(), "--plan", "review/plan.json", "--decisions", "review/decisions.json", "--out", "merged") + self.assertEqual(self.load("merged/target.json"), {"save": "Local correction", "cancel": "Annuler"}) + self.assertEqual(self.load("fr.json"), {"save": "Local correction"}) + + def test_stale_input_produces_no_output(self): + self.pack() + self.cli("plan", *self.common(), "--out", "review") + self.write("en.json", {"save": "Save now", "cancel": "Cancel"}) + result = self.cli("apply", *self.common(), "--plan", "review/plan.json", "--out", "merged", code=2) + self.assertIn("stale", result.stderr) + self.assertFalse((self.cwd / "merged").exists()) + + def test_existing_output_not_overwritten(self): + self.pack() + before = (self.cwd / "job/task.json").read_bytes() + self.cli("pack", "--source", "en.json", "--target", "fr.json", "--source-locale", "en", "--target-locale", "fr", "--out", "job", code=2) + self.assertEqual(before, (self.cwd / "job/task.json").read_bytes()) + + def test_unsupported_input_fails_without_output(self): + for data in ({"nested": {"key": "value"}}, {"n": 5}, ["array"], {"x": None}, {"x": True}): + self.write("en.json", data) + self.cli("pack", "--source", "en.json", "--target", "fr.json", "--source-locale", "en", "--target-locale", "fr", "--out", "bad", code=2) + self.assertFalse((self.cwd / "bad").exists()) + + def test_help_and_version(self): + self.assertIn("locreturn 1.0.0", self.cli("--version").stdout) + self.assertIn("pack", self.cli("--help").stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_core.py b/tests/test_core.py new file mode 100644 index 0000000..5d4d7a7 --- /dev/null +++ b/tests/test_core.py @@ -0,0 +1,129 @@ +import copy +import itertools +import unittest + +from locreturn import core + + +class MergeTests(unittest.TestCase): + def setup_job(self, old=None, incoming="nouveau", current=None, source="Save", context=None): + old = {} if old is None else {"key": old} + current = {} if current is None else {"key": current} + b, r = core.pack({"key": "Save"}, old, "en", "fr", context) + r["entries"]["key"]["translation"] = incoming + p = core.plan(b, r, {"key": source}, current, context) + return b, r, p, current + + def test_complete_target_three_way_matrix(self): + # Exhaustive missing/empty/nonempty baseline/current/incoming combinations. + values = [None, "", "ancien", "nouveau"] + for original, current, incoming in itertools.product(values, repeat=3): + with self.subTest(original=original, current=current, incoming=incoming): + _, _, p, t = self.setup_job(original, incoming, current) + status = p["rows"][0]["status"] + expected = ("skipped" if incoming is None else + "unchanged-return" if incoming == original else + "already-current" if incoming == current else + "ready" if current == original else "target-conflict") + self.assertEqual(status, expected) + if status != "target-conflict": + result, _ = core.apply(p, p, t) + value = incoming if status == "ready" else current + self.assertEqual(result, {} if value is None else {"key": value}) + + def test_source_drift_precedes_convergence(self): + _, _, p, t = self.setup_job("old", "new", "new", source="Save now") + self.assertEqual(p["rows"][0]["status"], "source-changed") + with self.assertRaises(core.Invalid): + core.apply(p, p, t) + + def test_unchanged_return_keeps_local_even_when_source_changed(self): + _, _, p, t = self.setup_job("old", "old", "local", source="Save now") + self.assertTrue(p["rows"][0]["source_changed"]) + self.assertEqual(core.apply(p, p, t)[0], t) + + def test_custom_resolves_new_source(self): + _, _, p, t = self.setup_job("old", "new", "local", source="Save now") + d = core.decision_template(p) + d["entries"]["key"] = {"action": "custom", "text": "Enregistrer maintenant", "reason": "Reviewed against new source"} + result, receipt = core.apply(p, p, t, d) + self.assertEqual(result["key"], "Enregistrer maintenant") + self.assertEqual(receipt["resolved_conflicts"], 1) + self.assertEqual(receipt["decisions"], d["entries"]) + self.assertEqual(receipt["output_sha256"], core.digest(result)) + + def test_source_changed_disallows_incoming(self): + _, _, p, t = self.setup_job("old", "new", "local", source="Save now") + d = core.decision_template(p) + d["entries"]["key"] = {"action": "incoming", "text": None, "reason": "ignore drift"} + with self.assertRaises(core.Invalid): + core.apply(p, p, t, d) + + def test_target_conflict_choices(self): + for action, value in (("incoming", "new"), ("keep", "local"), ("custom", "reviewed")): + _, _, p, t = self.setup_job("old", "new", "local") + d = core.decision_template(p) + d["entries"]["key"] = {"action": action, "text": "reviewed" if action == "custom" else None, "reason": "Reviewed"} + self.assertEqual(core.apply(p, p, t, d)[0]["key"], value) + + def test_new_and_orphan_keys_preserved(self): + b, r = core.pack({"a": "A"}, {"a": "ancien", "orphan": "keep"}, "en", "fr") + t = {"a": "ancien", "orphan": "keep", "new": "local"} + p = core.plan(b, r, {"a": "A", "new": "New"}, t) + self.assertEqual(core.apply(p, p, t)[0], t) + self.assertEqual(p["counts"], {"new-source": 1, "orphan-target": 1, "skipped": 1}) + + def test_source_removal_requires_keep_decision(self): + b, r = core.pack({"a": "A"}, {"a": "ancien"}, "en", "fr") + r["entries"]["a"]["translation"] = "new" + p = core.plan(b, r, {}, {"a": "local"}) + self.assertEqual(p["rows"][0]["status"], "source-removed") + d = core.decision_template(p) + d["entries"]["a"] = {"action": "keep", "text": None, "reason": "Retain orphan; prune separately"} + self.assertEqual(core.apply(p, p, {"a": "local"}, d)[0], {"a": "local"}) + + def test_partial_return_is_explicitly_supported(self): + b, r = core.pack({"a": "A", "b": "B"}, {}, "en", "fr") + del r["entries"]["b"] + r["entries"]["a"]["translation"] = "Un" + p = core.plan(b, r, b["source"], {}) + self.assertEqual(p["counts"], {"ready": 1, "not-returned": 1}) + self.assertEqual(core.apply(p, p, {})[0], {"a": "Un"}) + + def test_decision_reason_and_exact_scope(self): + _, _, p, t = self.setup_job("old", "new", "local") + good = core.decision_template(p) + good["entries"]["key"] = {"action": "keep", "text": None, "reason": "reviewed"} + variants = [] + for field, value in (("reason", " "), ("text", "unexpected"), ("action", "delete")): + d = copy.deepcopy(good) + d["entries"]["key"][field] = value + variants.append(d) + d = copy.deepcopy(good) + d["entries"]["unknown"] = d["entries"]["key"] + variants.append(d) + d = copy.deepcopy(good) + d["entries"] = {} + variants.append(d) + for d in variants: + with self.subTest(d=d), self.assertRaises(core.Invalid): + core.apply(p, p, t, d) + + def test_semantic_order_stability(self): + b1, r1 = core.pack({"a": "A", "b": "B"}, {}, "en", "fr") + b2, r2 = core.pack({"b": "B", "a": "A"}, {}, "en", "fr") + self.assertEqual(b1, b2) + self.assertEqual(r1, r2) + self.assertEqual(core.plan(b1, r1, b1["source"], {}), core.plan(b2, r2, b2["source"], {})) + + def test_unicode_and_multiline_exact_no_normalization(self): + b, r = core.pack({"a": "Cafe\u0301\n🙂"}, {}, "en", "ar") + r["entries"]["a"]["translation"] = "مرحبا\n🙂" + p = core.plan(b, r, b["source"], {}) + self.assertEqual(core.apply(p, p, {})[0]["a"], "مرحبا\n🙂") + p2 = core.plan(b, r, {"a": "Café\n🙂"}, {}) + self.assertEqual(p2["rows"][0]["status"], "source-changed") + + +if __name__ == "__main__": + unittest.main()