From 02a21eb97f4519a4b12fc31526d6023ae223b875 Mon Sep 17 00:00:00 2001 From: Marat K Date: Thu, 3 Dec 2026 09:57:51 +0100 Subject: [PATCH 1/6] Prepare the Java 0.9 candidate and verify installed consumers Bind candidate builds to the PR source and ABI 2 core. Exercise nested verbatim edits and collect generated documentation for review in CI. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci.yml | 142 ++++++++++++++++-- .../workflows/native-distribution-check.yml | 26 +++- .github/workflows/native-distribution.yml | 18 ++- .github/workflows/release.yml | 10 +- .../workflows/windows-gnu-cabi-candidate.yml | 45 ++++-- Cargo.toml | 7 +- build.gradle.kts | 2 +- ci/host-consumer/build.gradle.kts | 48 ++++++ ci/host-consumer/settings.gradle.kts | 1 + .../src/main/java/consumer/Smoke.java | 31 ++++ ci/test_cabi_gnullvm_notices.py | 72 +++++++++ crates/cabi/Cargo.toml | 2 +- .../java/lang/ktav/internal/NativeLoader.java | 2 +- .../main/java/lang/ktav/pure/EditSplice.java | 78 +++++----- lib/src/test/java/lang/ktav/Backend.java | 28 ++++ .../test/java/lang/ktav/EditValueTest.java | 96 +++++++++++- lib/src/test/java/lang/ktav/PureApiTest.java | 4 +- .../java/lang/ktav/PureInsertValueTest.java | 21 +++ root-docs/CHANGELOG/source-edit09/body-1.md | 18 +-- root-docs/CHANGELOG/unreleased/body-1.md | 12 +- root-docs/README/editing-cookbook/body-1.md | 6 +- root-docs/README/pure-backend/body-1.md | 6 +- root-docs/README/quick-start/body-1.md | 12 +- root-docs/README/runtime-support/body-1.md | 6 +- root-docs/README/source-edit-status/body-1.md | 6 +- scripts/cabi_gnullvm_notices.py | 37 ++++- scripts/check_publish_metadata.py | 6 +- scripts/metadata-fixtures/module-good.json | 2 +- scripts/metadata-fixtures/pom-good.xml | 2 +- 29 files changed, 622 insertions(+), 124 deletions(-) create mode 100644 ci/host-consumer/build.gradle.kts create mode 100644 ci/host-consumer/settings.gradle.kts create mode 100644 ci/host-consumer/src/main/java/consumer/Smoke.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b2f0874..625bc1a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,18 +14,44 @@ env: CARGO_TERM_COLOR: always jobs: + # ------------------------------------------------------------------ + # Unchanged drift guard from a clean checkout: the committed artifacts + # must stay byte-identical to the root-docs/ source units. This job + # NEVER relaxes during release preparation; the regenerated candidate + # artifacts travel separately (docs job below) until a maintainer + # reviews and commits them. + # ------------------------------------------------------------------ + docs-check: + name: Docs (byte-identical drift guard) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '24' + cache: 'npm' + - run: npm ci + - name: Generated docs are byte-identical to their source units + run: node scripts/build-docs.mjs --check + # ------------------------------------------------------------------ # README/CHANGELOG/CONTRIBUTING/SECURITY (all three languages) are - # generated by @ktav-lang/polydoc from the root-docs/ unit trees. This - # job fails when a committed artifact drifts from its source — which is - # what a hand-edit of the artifact looks like. Fix the source and - # re-run the generator; never patch the artifact. + # generated by @ktav-lang/polydoc from the root-docs/ unit trees. + # During the 0.9.0 release-candidate preparation the source units are + # edited first, so this job runs the STOCK generator (never a hand + # edit of artifacts) and delivers the regenerated files as a + # NON-PRIVILEGED artifact for review: no git write, no token with + # write access, no publication. The drift report travels inside the + # artifact; a maintainer reviews it and commits the regenerated files + # explicitly. # ------------------------------------------------------------------ docs: - name: Docs (generated markdown) + name: Docs (stock generator artifact delivery) runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: actions/setup-node@v4 with: @@ -35,13 +61,43 @@ jobs: - name: Install Node dependencies run: npm ci - - name: Generated docs are byte-identical to their source units - run: node scripts/build-docs.mjs --check + - name: Regenerate docs with the stock generator + run: node scripts/build-docs.mjs + + - name: Report drift against the committed artifacts + run: | + set -euo pipefail + mkdir -p docs-delivery + { + git diff --stat -- README.md CHANGELOG.md docs + echo + git diff -- README.md CHANGELOG.md docs || true + } > docs-delivery/drift.diff + head -50 docs-delivery/drift.diff || true + + - uses: actions/upload-artifact@v4 + with: + name: generated-docs + path: | + README.md + CHANGELOG.md + docs/CONTRIBUTING.md + docs/SECURITY.md + docs/ru/README.ru.md + docs/ru/CHANGELOG.ru.md + docs/ru/CONTRIBUTING.ru.md + docs/ru/SECURITY.ru.md + docs/zh/README.zh.md + docs/zh/CHANGELOG.zh.md + docs/zh/CONTRIBUTING.zh.md + docs/zh/SECURITY.zh.md + docs-delivery/drift.diff + if-no-files-found: error # ------------------------------------------------------------------ # Build native library + run Java tests in one job per OS. The test # suite hardcodes both paths (cabi at `target/release/...`, spec at - # `spec/versions/0.8/tests`) — no env wiring needed. + # `spec/versions/0.9/tests`) — no env wiring needed. # ------------------------------------------------------------------ test: name: ${{ matrix.os }} / JDK ${{ matrix.jdk }} @@ -82,10 +138,12 @@ jobs: with open('Cargo.lock', 'rb') as source: packages = tomllib.load(source)['package'] core = [package for package in packages if package['name'] == 'ktav'] - expected_source = 'git+https://github.com/ktav-lang/rust?rev=8b6b45ffbd9e50e1588e8ab6b1ae5d422bbe8910#8b6b45ffbd9e50e1588e8ab6b1ae5d422bbe8910' + expected_source = 'git+https://github.com/ktav-lang/rust?rev=c1d569f60b7f64fe94b5f022082a52c0bcac194e#c1d569f60b7f64fe94b5f022082a52c0bcac194e' if len(core) != 1 or core[0].get('source') != expected_source: raise SystemExit(f'expected exactly one ktav from pinned git revision; found {core!r}') - print('generated lockfile resolves ktav from the pinned core revision') + if core[0].get('version') != '0.9.0': + raise SystemExit(f"expected ktav core 0.9.0; found {core[0].get('version')!r}") + print('generated lockfile resolves ktav 0.9.0 from the pinned core revision') PY - name: Verify required native ABI symbols @@ -121,6 +179,62 @@ jobs: path: lib/build/reports/tests/test retention-days: 7 + # ------------------------------------------------------------------ + # Install the REAL candidate package (0.9.0) into a host consumer via + # publishToMavenLocal — no external publish, no secrets. The consumer + # build resolves ONLY the installed artifact, requires the exact + # 0.9.0 coordinate, and runs it end to end (parse/edit/round-trip). + # ------------------------------------------------------------------ + install-consumer: + name: install real package into a host consumer (no publish) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + - uses: gradle/actions/setup-gradle@v4 + - name: Install the candidate package into an isolated maven repo + run: > + ./gradlew :lib:publishToMavenLocal + -Dmaven.repo.local="$RUNNER_TEMP/maven-local" --no-daemon --stacktrace + - name: Installed 0.9.0 artifact is exactly the built jar + run: | + set -euo pipefail + repo="$RUNNER_TEMP/maven-local" + pom="$repo/io/github/ktav-lang/ktav/0.9.0/ktav-0.9.0.pom" + jar="$repo/io/github/ktav-lang/ktav/0.9.0/ktav-0.9.0.jar" + test -s "$pom" + test -s "$jar" + python3 - "$pom" <<'PY' + import sys + import xml.etree.ElementTree as ET + pom = ET.parse(sys.argv[1]).getroot() + ns = {"m": "http://maven.apache.org/POM/4.0.0"} + assert pom.findtext("m:version", namespaces=ns) == "0.9.0", "installed POM is not 0.9.0" + expected = {("net.java.dev.jna", "jna"): {None, "compile"}, + ("com.fasterxml.jackson.core", "jackson-core"): {"runtime"}} + deps = pom.find("m:dependencies", ns) + seen = set() + for dep in (deps if deps is not None else []): + key = (dep.findtext("m:groupId", namespaces=ns), dep.findtext("m:artifactId", namespaces=ns)) + assert key in expected, "unexpected dependency in installed POM: %s" % (key,) + assert dep.findtext("m:scope", namespaces=ns) in expected[key], "unexpected scope for %s" % (key,) + seen.add(key) + assert seen == set(expected), "installed POM dependency set differs: %s" % (seen,) + print("installed 0.9.0 POM verified: exact version, known dependency set") + PY + # The installed jar must be byte-identical to the jar this + # candidate just built — not a stale 0.8.1 leftover. + test "$(sha256sum < "$jar" | cut -d' ' -f1)" = "$(sha256sum < lib/build/libs/ktav-0.9.0.jar | cut -d' ' -f1)" + echo "installed jar is byte-identical to the built candidate jar" + - name: Host consumer resolves and runs the installed package via the project wrapper + run: > + ./gradlew -p ci/host-consumer verifyResolved run + -Dmaven.repo.local="$RUNNER_TEMP/maven-local" + -PinstalledRepo="$RUNNER_TEMP/maven-local" --no-daemon --stacktrace + lint-rust: name: rust clippy + fmt runs-on: ubuntu-latest @@ -215,7 +329,7 @@ jobs: - name: Direct Java run with explicit jars env: KTAV_LIB_PATH: /nonexistent/ktav-native-guard - run: java -cp "lib/build/libs/ktav-0.8.1.jar:lib/build/libs/ktav-0.8.1-pure-check.jar" lang.ktav.PureSmokeMain + run: java -cp "lib/build/libs/ktav-0.9.0.jar:lib/build/libs/ktav-0.9.0-pure-check.jar" lang.ktav.PureSmokeMain # ------------------------------------------------------------------ # CI-only verification of the GENERATED POM and Gradle Module @@ -371,10 +485,12 @@ jobs: with open('Cargo.lock', 'rb') as source: packages = tomllib.load(source)['package'] core = [package for package in packages if package['name'] == 'ktav'] - expected_source = 'git+https://github.com/ktav-lang/rust?rev=8b6b45ffbd9e50e1588e8ab6b1ae5d422bbe8910#8b6b45ffbd9e50e1588e8ab6b1ae5d422bbe8910' + expected_source = 'git+https://github.com/ktav-lang/rust?rev=c1d569f60b7f64fe94b5f022082a52c0bcac194e#c1d569f60b7f64fe94b5f022082a52c0bcac194e' if len(core) != 1 or core[0].get('source') != expected_source: raise SystemExit(f'expected exactly one ktav from pinned git revision; found {core!r}') - print('generated lockfile resolves ktav from the pinned core revision') + if core[0].get('version') != '0.9.0': + raise SystemExit(f"expected ktav core 0.9.0; found {core[0].get('version')!r}") + print('generated lockfile resolves ktav 0.9.0 from the pinned core revision') PY - name: Empty-input tests against the real debug artifact diff --git a/.github/workflows/native-distribution-check.yml b/.github/workflows/native-distribution-check.yml index 2975544..4de12d8 100644 --- a/.github/workflows/native-distribution-check.yml +++ b/.github/workflows/native-distribution-check.yml @@ -7,7 +7,31 @@ permissions: contents: read jobs: + # Bind the exact PR HEAD commit (not the synthetic merge commit): the + # distribution below must be built from the reviewed candidate source. + bind-source: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - name: Checked-out source is the exact PR head commit + run: | + expected="${{ github.event.pull_request.head.sha }}" + test -n "$expected" || { echo 'pull request head SHA is unavailable' >&2; exit 1; } + actual="$(git rev-parse HEAD)" + test "$actual" = "$expected" || { echo "checkout HEAD $actual != expected PR head $expected" >&2; exit 1; } + echo "candidate source bound to $actual" + native-distribution: + needs: bind-source uses: ./.github/workflows/native-distribution.yml with: - source-ref: b252ccfaed66505952ad63a99663e8b6ff530d62 + # Current candidate HEAD: the PR's exact head commit, verified by + # bind-source and by the rev-parse guards inside the reusable + # workflow. The historical 0.8.1 binding source + # b252ccfaed66505952ad63a99663e8b6ff530d62 stays valid as a + # historical proof in past runs/releases; it must not be reused as + # the 0.9.0 candidate source. + source-ref: ${{ github.event.pull_request.head.sha }} diff --git a/.github/workflows/native-distribution.yml b/.github/workflows/native-distribution.yml index 8fe2d80..987ad7e 100644 --- a/.github/workflows/native-distribution.yml +++ b/.github/workflows/native-distribution.yml @@ -146,12 +146,19 @@ jobs: with: tool: cargo-zigbuild - - name: Verify published Rust core provenance + - name: Verify candidate core git provenance shell: bash run: | set -euo pipefail + # The 0.9.0 candidate consumes the core STRICTLY from the pinned + # git revision (it is not published on crates.io). Verify the + # exact git-source URL, the exact full resolved SHA, and the + # core package version in the lockfile that the --locked builds + # below actually use — identity of the built source without any + # invented registry checksum. + grep -F 'rev = "c1d569f60b7f64fe94b5f022082a52c0bcac194e"' Cargo.toml \ + || { echo 'workspace does not pin the reviewed core revision' >&2; exit 1; } cargo generate-lockfile - cargo update -p ktav --precise 0.8.1 python3 - <<'PY' import tomllib with open('Cargo.lock', 'rb') as source: @@ -160,14 +167,13 @@ jobs: if len(core) != 1: raise SystemExit('expected exactly one ktav core') expected = { - 'version': '0.8.1', - 'source': 'registry+https://github.com/rust-lang/crates.io-index', - 'checksum': '7140dfe2fa6c320e74768cd6a637828c2d26f81746254f4fcd805f3993bd3fd5', + 'version': '0.9.0', + 'source': 'git+https://github.com/ktav-lang/rust?rev=c1d569f60b7f64fe94b5f022082a52c0bcac194e#c1d569f60b7f64fe94b5f022082a52c0bcac194e', } for field, value in expected.items(): if core[0].get(field) != value: raise SystemExit(f'ktav {field} mismatch: {core[0].get(field)!r}') - print('published ktav 0.8.1 core provenance verified') + print('candidate ktav 0.9.0 core resolved from the exact pinned git revision') PY - uses: taiki-e/install-action@v2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 96fa4ed..23542bc 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,7 +26,7 @@ jobs: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail - test "$GITHUB_REF_NAME" = v0.8.1 || { echo 'tag does not match package version' >&2; exit 1; } + test "$GITHUB_REF_NAME" = v0.9.0 || { echo 'tag does not match package version' >&2; exit 1; } target="$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_REF_NAME" --jq '.sha')" test "$target" = "$GITHUB_SHA" || { echo 'tag does not match the built commit' >&2; exit 1; } accepted="$(gh run list --repo "$GITHUB_REPOSITORY" --workflow ci.yml \ @@ -73,7 +73,7 @@ jobs: run: | set -euo pipefail bash scripts/check-publish-metadata.sh - for jar in ktav-0.8.1.jar ktav-0.8.1-sources.jar lib-maven-javadoc-0.8.1-javadoc.jar; do + for jar in ktav-0.9.0.jar ktav-0.9.0-sources.jar lib-maven-javadoc-0.9.0-javadoc.jar; do test -s "lib/build/libs/$jar" || { echo "missing JAR: $jar" >&2; exit 1; } done @@ -81,9 +81,9 @@ jobs: with: name: jars path: | - lib/build/libs/ktav-0.8.1.jar - lib/build/libs/ktav-0.8.1-sources.jar - lib/build/libs/lib-maven-javadoc-0.8.1-javadoc.jar + lib/build/libs/ktav-0.9.0.jar + lib/build/libs/ktav-0.9.0-sources.jar + lib/build/libs/lib-maven-javadoc-0.9.0-javadoc.jar if-no-files-found: error # ------------------------------------------------------------------ diff --git a/.github/workflows/windows-gnu-cabi-candidate.yml b/.github/workflows/windows-gnu-cabi-candidate.yml index dfc63c9..4a9af54 100644 --- a/.github/workflows/windows-gnu-cabi-candidate.yml +++ b/.github/workflows/windows-gnu-cabi-candidate.yml @@ -4,7 +4,7 @@ on: workflow_call: inputs: source-ref: - description: Exact reviewed original 0.8.1 source + description: Exact candidate source commit (historical 0.8.1 proof keeps its own default) required: true type: string workflow_dispatch: @@ -73,8 +73,11 @@ jobs: raise SystemExit('unexpected Java candidate source') source = Path('crates/cabi/src/lib.rs') original = source.read_bytes() - if hashlib.sha256(original).hexdigest() != '366ac4117d41bcd765443bb6b1218093082112d49cb27da85be08f5025b12e30': + historical = os.environ['SOURCE_REF'] == 'b252ccfaed66505952ad63a99663e8b6ff530d62' + if historical and hashlib.sha256(original).hexdigest() != '366ac4117d41bcd765443bb6b1218093082112d49cb27da85be08f5025b12e30': raise SystemExit('original Java C ABI source differs') + if not historical: + (Path(os.environ['RUNNER_TEMP']) / 'cabi-gnullvm-original-source.sha256').write_text(hashlib.sha256(original).hexdigest() + '\n', encoding='utf-8') stage = Path(os.environ['RUNNER_TEMP']) / 'cabi-gnullvm-tools' overlay = ['crates/cabi/build.rs', 'crates/cabi/src/lib.rs'] baseline = {name: hashlib.sha256(Path(name).read_bytes()).hexdigest() if Path(name).is_file() else None for name in overlay} @@ -94,10 +97,14 @@ jobs: changed.update(subprocess.check_output(['git', 'ls-files', '--others', '--exclude-standard', '--', *protected], text=True).splitlines()) if changed != set(overlay): raise SystemExit('Java candidate changed protected source beyond notice metadata') - lock = Path('ci/java-windows-gnu.lock').read_bytes() - if hashlib.sha256(lock).hexdigest() != 'a7066ecc92727ae12c3905cbf1a2b73266da609773356f725e931682381b7a8b': - raise SystemExit('reviewed Java lock differs') - Path('Cargo.lock').write_bytes(lock) + if historical: + lock = Path('ci/java-windows-gnu.lock').read_bytes() + if hashlib.sha256(lock).hexdigest() != 'a7066ecc92727ae12c3905cbf1a2b73266da609773356f725e931682381b7a8b': + raise SystemExit('reviewed Java lock differs') + Path('Cargo.lock').write_bytes(lock) + # New candidate: no historical lock bytes are reused; Cargo.lock + # is generated after the toolchain step and bound by strict + # git provenance in the "Prepare locked ..." step below. record = {name: {'baseline_sha256': baseline[name], 'compiled_sha256': hashlib.sha256(Path(name).read_bytes()).hexdigest()} for name in overlay} (Path(os.environ['RUNNER_TEMP']) / 'cabi-gnullvm-source-overlay.json').write_text(json.dumps(record, sort_keys=True, indent=2) + '\n', encoding='utf-8') - uses: actions/setup-python@v5 @@ -128,8 +135,26 @@ jobs: import tomllib from pathlib import Path core = [item for item in tomllib.loads(Path('Cargo.lock').read_text())['package'] if item['name'] == 'ktav'] - if len(core) != 1 or core[0]['version'] != '0.8.1' or core[0]['checksum'] != '7140dfe2fa6c320e74768cd6a637828c2d26f81746254f4fcd805f3993bd3fd5': - raise SystemExit('original registry core identity differs') + if len(core) != 1: + raise SystemExit('expected exactly one ktav core') + if os.environ['SOURCE_REF'] == 'b252ccfaed66505952ad63a99663e8b6ff530d62': + if core[0]['version'] != '0.8.1' or core[0]['checksum'] != '7140dfe2fa6c320e74768cd6a637828c2d26f81746254f4fcd805f3993bd3fd5': + raise SystemExit('original registry core identity differs') + else: + if 'rev = "c1d569f60b7f64fe94b5f022082a52c0bcac194e"' not in Path('Cargo.toml').read_text(): + raise SystemExit('workspace does not pin the reviewed core revision') + subprocess.run(['cargo', 'generate-lockfile'], check=True) + core = [item for item in tomllib.loads(Path('Cargo.lock').read_text())['package'] if item['name'] == 'ktav'] + if len(core) != 1: + raise SystemExit('expected exactly one ktav core') + expected = {'version': '0.9.0', 'source': 'git+https://github.com/ktav-lang/rust?rev=c1d569f60b7f64fe94b5f022082a52c0bcac194e#c1d569f60b7f64fe94b5f022082a52c0bcac194e'} + for field, value in expected.items(): + if core[0].get(field) != value: + raise SystemExit(f'candidate core git provenance differs: {field}={core[0].get(field)!r}') + evidence = Path(os.environ['RUNNER_TEMP']) / 'cabi-gnullvm-evidence' + evidence.mkdir(parents=True, exist_ok=True) + (evidence / 'core-provenance.json').write_text(json.dumps({'source': expected['source'], 'version': expected['version']}, sort_keys=True) + '\n', encoding='utf-8') + print('candidate ktav 0.9.0 core resolved from the exact pinned git revision') evidence = Path(os.environ['RUNNER_TEMP']) / 'cabi-gnullvm-evidence' subprocess.run([sys.executable, 'scripts/prepare_cabi_notices.py', str(evidence)], check=True) for name in ['LICENSE-MIT', 'LICENSE-APACHE']: @@ -183,7 +208,7 @@ jobs: raise SystemExit('candidate compiler missing') evidence = root / 'cabi-gnullvm-evidence' (evidence / 'compiler-version.txt').write_bytes(subprocess.check_output([str(compiler), '--version'])) - record = {'source_ref': os.environ['SOURCE_REF'], 'tooling_ref': os.environ['GITHUB_SHA'], 'target': os.environ['CABI_TARGET'], 'sdk_archive_sha256': checksum.hexdigest(), 'sdk_source': url, 'notice_overlay': json.loads((root / 'cabi-gnullvm-source-overlay.json').read_text(encoding='utf-8')), 'coverage': 'Original Java 0.8.1 C ABI GNU candidate; separate host-language consumers required before production integration. No historical asset clearance.'} + record = {'source_ref': os.environ['SOURCE_REF'], 'tooling_ref': os.environ['GITHUB_SHA'], 'target': os.environ['CABI_TARGET'], 'sdk_archive_sha256': checksum.hexdigest(), 'sdk_source': url, 'core_git_source': (None if os.environ['SOURCE_REF'] == 'b252ccfaed66505952ad63a99663e8b6ff530d62' else 'git+https://github.com/ktav-lang/rust?rev=c1d569f60b7f64fe94b5f022082a52c0bcac194e#c1d569f60b7f64fe94b5f022082a52c0bcac194e'), 'notice_overlay': json.loads((root / 'cabi-gnullvm-source-overlay.json').read_text(encoding='utf-8')), 'coverage': ('Original Java 0.8.1 C ABI GNU candidate; separate host-language consumers required before production integration. No historical asset clearance.' if os.environ['SOURCE_REF'] == 'b252ccfaed66505952ad63a99663e8b6ff530d62' else 'Java 0.9.0 candidate C ABI GNU build from git-pinned core c1d569f60b7f64fe94b5f022082a52c0bcac194e; separate host-language consumers required before production integration. No historical asset clearance.')} (evidence / 'source-provenance.json').write_text(json.dumps(record, sort_keys=True, indent=2) + '\n', encoding='utf-8') key = 'CARGO_TARGET_' + os.environ['CABI_TARGET'].upper().replace('-', '_') + '_LINKER' flags = ['-C', 'target-feature=+crt-static', '-C', 'link-arg=-Wl,-Map,' + (evidence / 'native-link.map').as_posix(), '-C', 'link-arg=-Wl,--reproduce=' + (root / 'cabi-gnullvm-link.tar').as_posix()] @@ -293,7 +318,7 @@ jobs: raise SystemExit('candidate changed the reviewed Cargo lock') result = {'target': os.environ['CABI_TARGET'], 'binary_sha256': hashlib.sha256(binary.read_bytes()).hexdigest(), 'map_sha256': hashlib.sha256(link_map.read_bytes()).hexdigest(), 'machine': int(os.environ['CABI_MACHINE']), 'imports': imports, 'exports': [name.decode('ascii') for name in exports], 'sdk_legal_files': len(legal), 'coverage': 'Actual PE/input identity; source-bound runtime/resource verification is recorded separately in native-runtime-verification.json.'} (evidence / 'native-verification.json').write_text(json.dumps(result, sort_keys=True, indent=2) + '\n', encoding='utf-8') - subprocess.run([sys.executable, '-I', 'scripts/cabi_gnullvm_notices.py', 'verify', str(evidence), str(binary), os.environ['CABI_TARGET']], check=True) + subprocess.run([sys.executable, '-I', 'scripts/cabi_gnullvm_notices.py', 'verify', str(evidence), str(binary), os.environ['CABI_TARGET'], os.environ['SOURCE_REF']], check=True) - name: Load the actual x64 C ABI with SDK paths removed if: matrix.target == 'x86_64-pc-windows-gnullvm' shell: python diff --git a/Cargo.toml b/Cargo.toml index 3accd2c..d02c3bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,15 +3,16 @@ resolver = "2" members = ["crates/cabi"] [workspace.package] -version = "0.8.1" +version = "0.9.0" edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/ktav-lang/java" rust-version = "1.71" [workspace.dependencies] -# Подготовка 0.9: immutable core pin с source-edit и ABI 2; пакет ещё не опубликован. -ktav = { git = "https://github.com/ktav-lang/rust", rev = "8b6b45ffbd9e50e1588e8ab6b1ae5d422bbe8910" } +# 0.9.0 candidate: immutable core pin with source-edit and ABI 2; the core is +# consumed strictly from this exact git revision (it is not on crates.io yet). +ktav = { git = "https://github.com/ktav-lang/rust", rev = "c1d569f60b7f64fe94b5f022082a52c0bcac194e" } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } indexmap = "2" diff --git a/build.gradle.kts b/build.gradle.kts index da8b03a..6351d0e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,7 +4,7 @@ plugins { allprojects { group = "io.github.ktav-lang" - version = "0.8.1" + version = "0.9.0" } subprojects { diff --git a/ci/host-consumer/build.gradle.kts b/ci/host-consumer/build.gradle.kts new file mode 100644 index 0000000..7b0ea67 --- /dev/null +++ b/ci/host-consumer/build.gradle.kts @@ -0,0 +1,48 @@ +// Host consumer for the installed candidate: resolves the REAL +// io.github.ktav-lang:ktav package from the ISOLATED install repo that +// the CI job published with publishToMavenLocal (never the repo's own +// :lib project, never the default ~/.m2). The exact 0.9.0 coordinate +// is required, so any other installed version fails the resolution +// instead of silently substituting 0.8.1. +plugins { + application +} + +repositories { + mavenLocal() + mavenCentral() +} + +dependencies { + implementation("io.github.ktav-lang:ktav:0.9.0") +} + +application { + mainClass.set("consumer.Smoke") +} + +// Prove the resolved ktav artifact IS the freshly installed 0.9.0 +// candidate jar from the isolated repo: exact version and file located +// inside the repo directory passed via -PinstalledRepo. +tasks.register("verifyResolved") { + doLast { + val installedRepo = providers.gradleProperty("installedRepo").orNull + ?: throw GradleException("pass -PinstalledRepo=") + val repoRoot = java.nio.file.Path.of(installedRepo).toAbsolutePath().normalize() + configurations.named("runtimeClasspath").get() + .resolvedConfiguration.resolvedArtifacts.forEach { artifact -> + val id = artifact.moduleVersion.id + println("resolved: " + id + " -> " + artifact.file) + if (id.group == "io.github.ktav-lang" && id.name == "ktav") { + if (id.version != "0.9.0") { + throw GradleException("installed ktav version is not 0.9.0: " + id.version) + } + val file = artifact.file.toPath().toAbsolutePath().normalize() + if (!file.startsWith(repoRoot)) { + throw GradleException( + "resolved ktav artifact is outside the isolated install repo: " + file) + } + } + } + } +} diff --git a/ci/host-consumer/settings.gradle.kts b/ci/host-consumer/settings.gradle.kts new file mode 100644 index 0000000..898c1c1 --- /dev/null +++ b/ci/host-consumer/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "ktav-host-consumer" diff --git a/ci/host-consumer/src/main/java/consumer/Smoke.java b/ci/host-consumer/src/main/java/consumer/Smoke.java new file mode 100644 index 0000000..6c53828 --- /dev/null +++ b/ci/host-consumer/src/main/java/consumer/Smoke.java @@ -0,0 +1,31 @@ +package consumer; + +import lang.ktav.Ktav; +import lang.ktav.Value; + +/** + * End-to-end run of the INSTALLED package (resolved from mavenLocal, + * zero repo classpath): parse, edit, and round-trip a document, and + * report the loaded library version. Confirms the host consumer gets + * the working 0.9.0 candidate — not a stale 0.8.1 artifact. + */ +public final class Smoke { + + public static void main(String[] args) { + String source = "service: web\nport: 8080\n"; + Value parsed = Ktav.loads(source); + if (parsed == null) { + throw new AssertionError("installed package failed to parse"); + } + String edited = Ktav.editValue(source, "port", new Value.Int("9090")); + if (!"service: web\nport: 9090\n".equals(edited)) { + throw new AssertionError("unexpected edit result: " + edited); + } + String roundTrip = Ktav.dumps(Ktav.loads(edited)); + if (!edited.equals(roundTrip)) { + throw new AssertionError("round-trip mismatch: " + roundTrip); + } + System.out.println("installed ktav package works; native version: " + + Ktav.nativeVersion()); + } +} diff --git a/ci/test_cabi_gnullvm_notices.py b/ci/test_cabi_gnullvm_notices.py index e126160..b44d0ea 100644 --- a/ci/test_cabi_gnullvm_notices.py +++ b/ci/test_cabi_gnullvm_notices.py @@ -56,6 +56,78 @@ def test_unknown_target_and_repeated_augmentation_are_rejected(self): with self.assertRaisesRegex(ValueError, 'unexpected C ABI runtime'): MODULE.augment(bundle, self.profile(), target) + def provenance(self, evidence, **fields): + record = {'source_ref': 'b252ccfaed66505952ad63a99663e8b6ff530d62', + 'sdk_archive_sha256': MODULE.SDK_SHA} + record.update(fields) + (evidence / 'source-provenance.json').write_text( + __import__('json').dumps(record), encoding='utf-8') + + def candidate_core_lock(self, evidence, source=MODULE.CANDIDATE_CORE, version='0.9.0'): + evidence.joinpath('core-provenance.json').write_text( + __import__('json').dumps({'source': source, 'version': version}, sort_keys=True), + encoding='utf-8') + + def test_historical_binding_accepts_only_exact_legacy_source(self): + with tempfile.TemporaryDirectory() as temporary: + evidence = Path(temporary) + self.provenance(evidence) + self.assertTrue(MODULE.source_binding( + __import__('json').loads((evidence / 'source-provenance.json').read_text()), + evidence, MODULE.HISTORICAL_SOURCE)) + self.provenance(evidence, core_git_source=MODULE.CANDIDATE_CORE) + self.assertFalse(MODULE.source_binding( + __import__('json').loads((evidence / 'source-provenance.json').read_text()), + evidence, MODULE.HISTORICAL_SOURCE)) + + def test_candidate_requires_independently_passed_exact_source(self): + declared = 'c' * 40 + other = 'a' * 40 + with tempfile.TemporaryDirectory() as temporary: + evidence = Path(temporary) + self.provenance(evidence, source_ref=declared) + self.assertFalse(MODULE.source_binding( + __import__('json').loads((evidence / 'source-provenance.json').read_text()), + evidence, declared)) + self.provenance(evidence, source_ref=declared, core_git_source=MODULE.CANDIDATE_CORE) + self.assertFalse(MODULE.source_binding( + __import__('json').loads((evidence / 'source-provenance.json').read_text()), + evidence, other)) + self.candidate_core_lock(evidence) + self.assertTrue(MODULE.source_binding( + __import__('json').loads((evidence / 'source-provenance.json').read_text()), + evidence, declared)) + + def test_candidate_rejects_unverified_or_drifting_lock_identity(self): + declared = 'c' * 40 + with tempfile.TemporaryDirectory() as temporary: + evidence = Path(temporary) + self.provenance(evidence, source_ref=declared, core_git_source=MODULE.CANDIDATE_CORE) + self.assertFalse(MODULE.source_binding( + __import__('json').loads((evidence / 'source-provenance.json').read_text()), + evidence, declared)) + self.candidate_core_lock(evidence, source='git+https://example.invalid/rust?rev=' + declared + '#' + declared) + self.assertFalse(MODULE.source_binding( + __import__('json').loads((evidence / 'source-provenance.json').read_text()), + evidence, declared)) + self.candidate_core_lock(evidence, version='0.8.1') + self.assertFalse(MODULE.source_binding( + __import__('json').loads((evidence / 'source-provenance.json').read_text()), + evidence, declared)) + self.candidate_core_lock(evidence) + self.assertTrue(MODULE.source_binding( + __import__('json').loads((evidence / 'source-provenance.json').read_text()), + evidence, declared)) + + def test_malformed_source_refs_are_rejected(self): + for bogus in ['z' * 40, 'short', 12345, None]: + with tempfile.TemporaryDirectory() as temporary: + evidence = Path(temporary) + record = {'source_ref': bogus, 'sdk_archive_sha256': MODULE.SDK_SHA} + (evidence / 'source-provenance.json').write_text( + __import__('json').dumps(record), encoding='utf-8') + self.assertFalse(MODULE.source_binding(record, evidence, MODULE.HISTORICAL_SOURCE)) + def test_source_hash_and_original_notice_changes_are_rejected(self): raw = b'/* Copyright fixture. Permission fixture. */\nint value;\n' item = {'source': 'fixture', 'path': 'fixture.c', 'sha256': hashlib.sha256(raw).hexdigest(), 'source_notices': ['/* Copyright fixture. Permission fixture. */']} diff --git a/crates/cabi/Cargo.toml b/crates/cabi/Cargo.toml index ac19b97..b5ac7e0 100644 --- a/crates/cabi/Cargo.toml +++ b/crates/cabi/Cargo.toml @@ -9,7 +9,7 @@ rust-version.workspace = true publish = false [package.metadata.ktav] -spec-version = "0.8.1" +spec-version = "0.9.0" [lib] name = "ktav_cabi" diff --git a/lib/src/main/java/lang/ktav/internal/NativeLoader.java b/lib/src/main/java/lang/ktav/internal/NativeLoader.java index b2ef70a..2f76328 100644 --- a/lib/src/main/java/lang/ktav/internal/NativeLoader.java +++ b/lib/src/main/java/lang/ktav/internal/NativeLoader.java @@ -31,7 +31,7 @@ public final class NativeLoader { /** Version of {@code ktav_cabi} this build expects. Bump per release. */ - static final String LIB_VERSION = "0.8.1"; + static final String LIB_VERSION = "0.9.0"; private static final String RELEASE_BASE = "https://github.com/ktav-lang/java/releases/download/v"; diff --git a/lib/src/main/java/lang/ktav/pure/EditSplice.java b/lib/src/main/java/lang/ktav/pure/EditSplice.java index 164f0ae..92aee7a 100644 --- a/lib/src/main/java/lang/ktav/pure/EditSplice.java +++ b/lib/src/main/java/lang/ktav/pure/EditSplice.java @@ -227,7 +227,7 @@ private static String standalonePair(String key, Value value, String indent, Str } String normalized = rendered; if (normalized.endsWith("\n")) normalized = normalized.substring(0, normalized.length() - 1); - String out = reindentInsert(normalized, indent, eol); + String out = reindentInsert(normalized, indent, eol, false); return out; } @@ -926,7 +926,26 @@ private static Planned planValue(Value replacement, PlanCtx pc) { throw EditError.unsupported( "replacement is not representable: " + e.getMessage()); } - return new Planned(reindent(rendered, pc.indent, pc.eol), false); + if (rendered.endsWith("\n")) { + rendered = rendered.substring(0, rendered.length() - 1); + } + // Block compound body: the pretty root OBJECT render omits the + // container braces, so they are re-introduced with the body one + // level under the target pair line; the root ARRAY render + // already carries its own "[" / "]" and is only re-indented. + // Verbatim data lines are never re-indented (Rust 1f7c717 + // parity). + if (replacement instanceof Value.Obj) { + return new Planned( + "{" + pc.eol + + reindentInsert(rendered, pc.indent + " ", + pc.eol, true) + + pc.eol + pc.indent + "}", + false); + } + return new Planned( + reindentInsert(rendered, pc.indent, pc.eol, true), + false); } return new Planned(scalarBody(replacement), false); } @@ -1030,35 +1049,6 @@ private static Plan blockReplacement(Value replacement, PlanCtx pc, return new Plan(b0, "", "", p.body); } - /** Pretty render re-indented under the target's indent; verbatim block interiors untouched. */ - private static String reindent(String doc, String indent, String eol) { - StringBuilder out = new StringBuilder(doc.length()); - boolean inVerbatim = false; - String[] lines = doc.split("\n", -1); - for (int i = 0; i < lines.length; i++) { - String line = lines[i]; - if (line.startsWith(" ")) { - line = line.substring(4); - } - boolean verbatimOpen = line.endsWith("(("); - boolean verbatimClose = trim(line).equals("))"); - if (i > 0) { - out.append(eol); - boolean skipPrefix = inVerbatim || line.isEmpty(); - if (!skipPrefix) { - out.append(indent); - } - } - out.append(line); - if (verbatimOpen) { - inVerbatim = true; - } else if (verbatimClose) { - inVerbatim = false; - } - } - return out.toString(); - } - // ── Line helpers ──────────────────────────────────────────────────── private static String lineIndent(byte[] b, int pos) { @@ -1300,27 +1290,41 @@ private static int[] scanExponent(String s, int from) { return scanDecPart(s, i); } - private static String reindentInsert(String doc, String indent, String eol) { + private static String reindentInsert(String doc, String indent, + String eol, boolean prefixFirst) { StringBuilder out = new StringBuilder(doc.length()); boolean inVerbatim = false; String[] lines = doc.split("\n", -1); for (int i = 0; i < lines.length; i++) { String line = lines[i]; int leading = 0; - while (leading < line.length() && line.charAt(leading) == ' ') leading++; + while (leading < line.length() && line.charAt(leading) == ' ') { + leading++; + } String trimmed = line.substring(leading); boolean closingMarker = inVerbatim && trim(line).equals("))"); boolean opens = !inVerbatim && trimmed.endsWith("(("); - if (i > 0) out.append(eol); + if (i > 0) { + out.append(eol); + } if (closingMarker) { out.append(indent).append(line); inVerbatim = false; } else if (inVerbatim) { out.append(line); + } else if (i == 0 && !prefixFirst) { + out.append(line); + if (opens) { + inVerbatim = true; + } } else { - if (i == 0) out.append(line); - else out.append(indent).append(line); - if (opens) inVerbatim = true; + if (!line.isEmpty()) { + out.append(indent); + } + out.append(line); + if (opens) { + inVerbatim = true; + } } } return out.toString(); diff --git a/lib/src/test/java/lang/ktav/Backend.java b/lib/src/test/java/lang/ktav/Backend.java index 74c5346..21a8e18 100644 --- a/lib/src/test/java/lang/ktav/Backend.java +++ b/lib/src/test/java/lang/ktav/Backend.java @@ -40,6 +40,13 @@ interface Backend { String editValueSegments(String src, java.util.List segments, Value replacement); + /** Lossless source insertion by textual path (0.9). */ + String insertValue(String src, String path, Value value); + + /** Lossless source insertion by decoded segments (0.9). */ + String insertValueSegments(String src, java.util.List segments, + Value value); + static Backend nativeBackend() { return new Backend() { @Override public String name() { @@ -91,6 +98,16 @@ static Backend nativeBackend() { java.util.List segments, Value replacement) { return Ktav.editValueSegments(src, segments, replacement); } + + @Override public String insertValue(String src, String path, + Value value) { + return Ktav.insertValue(src, path, value); + } + + @Override public String insertValueSegments(String src, + java.util.List segments, Value value) { + return Ktav.insertValueSegments(src, segments, value); + } }; } @@ -147,6 +164,17 @@ static Backend pureBackend() { return lang.ktav.pure.PureKtav.editValueSegments(src, segments, replacement); } + + @Override public String insertValue(String src, String path, + Value value) { + return lang.ktav.pure.PureKtav.insertValue(src, path, value); + } + + @Override public String insertValueSegments(String src, + java.util.List segments, Value value) { + return lang.ktav.pure.PureKtav.insertValueSegments(src, + segments, value); + } }; } } diff --git a/lib/src/test/java/lang/ktav/EditValueTest.java b/lib/src/test/java/lang/ktav/EditValueTest.java index bc8244e..a99c88a 100644 --- a/lib/src/test/java/lang/ktav/EditValueTest.java +++ b/lib/src/test/java/lang/ktav/EditValueTest.java @@ -14,7 +14,10 @@ /** * Verbatim port of the reference layout regressions * ({@code tests/suite/api/text/edit_value/layout.rs}, 22 named tests, - * every tabular subcase, exact source/expected bytes). Every case runs + * every tabular subcase, exact source/expected bytes). Cases 23–26 + * (0.9 prep; 26 covers insertion through the native facade too) are supplementary Rust 1f7c717 parity checks: verbatim + * data lines with significant leading spaces survive reindentation + * byte-exact. Every case runs * BOTH API forms (textual path + decoded segments) on BOTH backends; * the engine's own semantic verification covers the reference's * {@code parse(result) == wanted} assertion. @@ -330,6 +333,85 @@ private static void unsafeCommentLossStillFailsClosed(Backend b) { } } + // ── 23 ── 0.9 prep, Rust 1f7c717 parity ───────────────────────────── + + private static final String LEADING = " four\n six"; + + /** String replacement in a nested block object: markers take the + * pair indent, verbatim data lines keep their leading spaces. */ + private static void stringReplaceKeepsVerbatimLeadingSpaces(Backend b) { + String name = "string_replace_keeps_verbatim_leading_spaces"; + check(b, "parent: {\n keep: old\n}\n", + List.of("parent", "keep"), s(LEADING), + "parent: {\n keep: ((\n four\n six\n ))\n}\n", name); + check(b, "parent: {\r\n keep: old\r\n}\r\n", + List.of("parent", "keep"), s(LEADING), + "parent: {\r\n keep: ((\r\n four\r\n six\r\n ))\r\n}\r\n", + name); + } + + /** Inline→block promotion with a leading-space multiline string: + * structural markers reindent, data lines stay byte-exact. */ + private static void promotionKeepsVerbatimLeadingSpaces(Backend b) { + String name = "promotion_keeps_verbatim_leading_spaces"; + check(b, + "## top\na: [{x: old, untouched: [1, 2]}, {keep: yes}]\nz: keep\n", + List.of("a", "0", "x"), s(LEADING), + "## top\na: [\n {\n x: ((\n four\n six\n ))\n" + + " untouched: [1, 2]\n }\n {keep: yes}\n]" + + "\nz: keep\n", + name); + check(b, + "## top\r\na: [{x: old, untouched: [1, 2]}, {keep: yes}]\r\nz: keep\r\n", + List.of("a", "0", "x"), s(LEADING), + "## top\r\na: [\r\n {\r\n x: ((\r\n four\r\n six\r\n ))\r\n" + + " untouched: [1, 2]\r\n }\r\n {keep: yes}\r\n]" + + "\r\nz: keep\r\n", + name); + } + + /** Replacing a block object with an object holding the string: + * container braces re-emitted, pairs one level under the target, + * verbatim data preserved. */ + private static void blockObjectReplaceKeepsVerbatimLeadingSpaces(Backend b) { + String name = "block_object_replace_keeps_verbatim_leading_spaces"; + Value replacement = obj("value", s(LEADING)); + check(b, "parent: {\n child: {\n keep: 1\n }\n}\n", + List.of("parent", "child"), replacement, + "parent: {\n child: {\n value: ((\n four\n six\n ))\n }\n}\n", + name); + check(b, "parent: {\r\n child: {\r\n keep: 1\r\n }\r\n}\r\n", + List.of("parent", "child"), replacement, + "parent: {\r\n child: {\r\n value: ((\r\n four\r\n six\r\n ))\r\n }\r\n}\r\n", + name); + } + + /** Insertion into a nested object with the leading-space string: + * native facade AND pure, both API forms, LF and CRLF. */ + private static void insertKeepsVerbatimLeadingSpaces(Backend b) { + String name = "insert_keeps_verbatim_leading_spaces"; + Value expected = obj("parent", obj("keep", new Value.Int("1"), + "added", s(LEADING))); + String lfOut = "parent: {\n keep: 1\n added: ((\n four\n six\n ))\n}\n"; + assertEquals(lfOut, + b.insertValue("parent: {\n keep: 1\n}\n", "parent.added", + s(LEADING)), name + " [textual]"); + assertEquals(lfOut, + b.insertValueSegments("parent: {\n keep: 1\n}\n", + List.of("parent", "added"), s(LEADING)), + name + " [segments]"); + assertEquals(expected, b.loads(lfOut), name + " [reparse]"); + String crlfOut = "parent: {\r\n keep: 1\r\n added: ((\r\n four\r\n six\r\n ))\r\n}\r\n"; + assertEquals(crlfOut, + b.insertValue("parent: {\r\n keep: 1\r\n}\r\n", + "parent.added", s(LEADING)), name + " [textual]"); + assertEquals(crlfOut, + b.insertValueSegments("parent: {\r\n keep: 1\r\n}\r\n", + List.of("parent", "added"), s(LEADING)), + name + " [segments]"); + assertEquals(expected, b.loads(crlfOut), name + " [reparse]"); + } + // ── runners ───────────────────────────────────────────────────────── private static final String[] NAMES = { @@ -355,6 +437,10 @@ private static void unsafeCommentLossStillFailsClosed(Backend b) { "reopened_inline_parent_promotes_only_its_physical_definition", "impossible_block_encoding_keeps_valid_inline_form", "unsafe_comment_loss_still_fails_closed", + "string_replace_keeps_verbatim_leading_spaces", + "promotion_keeps_verbatim_leading_spaces", + "block_object_replace_keeps_verbatim_leading_spaces", + "insert_keeps_verbatim_leading_spaces", }; private static void runCase(Backend b, String name) { @@ -403,6 +489,14 @@ private static void runCase(Backend b, String name) { impossibleBlockEncodingKeepsValidInlineForm(b); case "unsafe_comment_loss_still_fails_closed" -> unsafeCommentLossStillFailsClosed(b); + case "string_replace_keeps_verbatim_leading_spaces" -> + stringReplaceKeepsVerbatimLeadingSpaces(b); + case "promotion_keeps_verbatim_leading_spaces" -> + promotionKeepsVerbatimLeadingSpaces(b); + case "block_object_replace_keeps_verbatim_leading_spaces" -> + blockObjectReplaceKeepsVerbatimLeadingSpaces(b); + case "insert_keeps_verbatim_leading_spaces" -> + insertKeepsVerbatimLeadingSpaces(b); default -> throw new AssertionError("unknown case " + name); } } diff --git a/lib/src/test/java/lang/ktav/PureApiTest.java b/lib/src/test/java/lang/ktav/PureApiTest.java index d24029c..6323057 100644 --- a/lib/src/test/java/lang/ktav/PureApiTest.java +++ b/lib/src/test/java/lang/ktav/PureApiTest.java @@ -26,8 +26,8 @@ final class PureApiTest { @Test void versionMatchesImplementedSpec() { // The SPEC version the pure backend implements (0.9 source - // diagnostics + lossless source edit) — deliberately NOT the - // package version, which stays 0.8.1 until release. + // diagnostics + lossless source edit) — now aligned with the + // 0.9.0 candidate package version. assertEquals("0.9.0", lang.ktav.pure.PureKtav.version()); } diff --git a/lib/src/test/java/lang/ktav/PureInsertValueTest.java b/lib/src/test/java/lang/ktav/PureInsertValueTest.java index 6de3fb5..6ffd0f3 100644 --- a/lib/src/test/java/lang/ktav/PureInsertValueTest.java +++ b/lib/src/test/java/lang/ktav/PureInsertValueTest.java @@ -317,6 +317,27 @@ private static void exactAndTree(String output, String expectedBytes, Value expe "base: 0\n\"a,b\": 1\n", o("base", i("0"), "a,b", i("1"))); } + /** Rust 1f7c717: verbatim data lines keep significant leading spaces + * while only the ((/)) structural markers take the child indent. */ + @Test void nestedInsertVerbatimDataLeadingSpacesLfAndCrlf() { + String value = " four\n six"; + Value expected = o("parent", o("keep", i("1"), "added", s(value))); + String lf = "parent: {\n keep: 1\n added: ((\n four\n six\n ))\n}\n"; + String lfSource = "parent: {\n keep: 1\n}\n"; + byte[] lfBytes = lfSource.getBytes(StandardCharsets.UTF_8); + exactAndTree(lang.ktav.pure.PureKtav.insertValue(lfSource, "parent.added", s(value)), lf, expected); + exactAndTree(lang.ktav.pure.PureKtav.insertValueSegments(lfSource, List.of("parent", "added"), s(value)), lf, expected); + exactAndTree(lang.ktav.pure.PureKtav.insertValue(lfBytes, "parent.added", s(value)), lf, expected); + exactAndTree(lang.ktav.pure.PureKtav.insertValueSegments(lfBytes, List.of("parent", "added"), s(value)), lf, expected); + String crlf = "parent: {\r\n keep: 1\r\n added: ((\r\n four\r\n six\r\n ))\r\n}\r\n"; + String crlfSource = "parent: {\r\n keep: 1\r\n}\r\n"; + byte[] crlfBytes = crlfSource.getBytes(StandardCharsets.UTF_8); + exactAndTree(lang.ktav.pure.PureKtav.insertValue(crlfSource, "parent.added", s(value)), crlf, expected); + exactAndTree(lang.ktav.pure.PureKtav.insertValueSegments(crlfSource, List.of("parent", "added"), s(value)), crlf, expected); + exactAndTree(lang.ktav.pure.PureKtav.insertValue(crlfBytes, "parent.added", s(value)), crlf, expected); + exactAndTree(lang.ktav.pure.PureKtav.insertValueSegments(crlfBytes, List.of("parent", "added"), s(value)), crlf, expected); + } + @Test void blockInsertionReindentsVerbatimCloserWithoutChangingData() { String source = "parent: {\r\n keep: 1\r\n}\r\n"; Value value = o("value", s("first\n)\nlast")); diff --git a/root-docs/CHANGELOG/source-edit09/body-1.md b/root-docs/CHANGELOG/source-edit09/body-1.md index e06edf2..e1ab711 100644 --- a/root-docs/CHANGELOG/source-edit09/body-1.md +++ b/root-docs/CHANGELOG/source-edit09/body-1.md @@ -1,33 +1,33 @@ >>>>> lang=en -## Unreleased — 0.9 preparation +## Unreleased — 0.9.0 preparation - Add native and standalone pure editing by textual path or literal segments: source splicing, preserved container forms, minimal readability transitions, comment protection, byte-identical no-op and semantic verification. - Apply 0.9 source diagnostics and the pinned 412-case conformance corpus, including 72 diagnostic fixtures with raw UTF-8 byte locations and EOF opener spans. -- Native uses the immutable preparing-0.9 core and C ABI 2; pure remains independent of native binaries. Package versions are unchanged; this functionality is not published in 0.8.1. +- Native uses the immutable 0.9.0-candidate core pinned to its exact git revision, with C ABI 2; pure remains independent of native binaries. Package versions move to 0.9.0 in this candidate; nothing is published yet. ### Documentation -- Expand README examples for dotted and literal-key paths, mixed arrays, String/Integer identity, multiline unfolding, byte-identical no-op and BOM/CRLF/EOF preservation. Clarify 0.9 byte diagnostics, safe refusal, ABI 2 and standalone pure usage; these additions are not part of published 0.8.1. +- Expand README examples for dotted and literal-key paths, mixed arrays, String/Integer identity, multiline unfolding, byte-identical no-op and BOM/CRLF/EOF preservation. Clarify 0.9 byte diagnostics, safe refusal, ABI 2 and standalone pure usage; these additions are part of the 0.9.0 candidate and are not published yet. >>>>> lang=ru -## Ещё не выпущено — подготовка 0.9 +## Ещё не выпущено — подготовка 0.9.0 - Добавлено редактирование по текстовому пути или буквальным сегментам в native- и самостоятельном pure-backend: source splice, сохранение форм контейнеров, минимальные переходы читаемости, защита комментариев, byte-identical no-op и семантическая проверка. - Применена диагностика исходника 0.9 и закреплён corpus из 412 фикстур, включая 72 диагностические фикстуры с позициями сырых байтов UTF-8 и EOF spans от opener. -- Native использует immutable ядро подготовки 0.9 и C ABI 2; pure не требует native-бинарников. Версии пакетов не менялись; функционал не опубликован в 0.8.1. +- Native использует immutable ядро кандидата 0.9.0, закреплённое за точной git-ревизией, и C ABI 2; pure не требует native-бинарников. Версии пакетов в этом кандидате переходят к 0.9.0; публикация ещё не выполнена. ### Документация -- Дополнены примеры README: dotted-пути и буквальные ключи, смешанные массивы, различие String/Integer, раскрытие многострочной замены, побайтовый no-op и сохранение BOM/CRLF/EOF. Уточнены байтовая диагностика 0.9, безопасные отказы, ABI 2 и самостоятельный pure-бэкенд; дополнения не относятся к опубликованному 0.8.1. +- Дополнены примеры README: dotted-пути и буквальные ключи, смешанные массивы, различие String/Integer, раскрытие многострочной замены, побайтовый no-op и сохранение BOM/CRLF/EOF. Уточнены байтовая диагностика 0.9, безопасные отказы, ABI 2 и самостоятельный pure-бэкенд; дополнения входят в кандидат 0.9.0 и ещё не опубликованы. >>>>> lang=zh -## 尚未发布 — 0.9 准备版本 +## 尚未发布 — 0.9.0 准备 - 新增原生及独立纯实现的路径编辑,支持点分文本或字面路径段:源文本拼接、保留容器形式、最小可读性展开、注释保护、逐字节 no-op 及语义验证。 - 应用 0.9 源诊断及固定的 412 个一致性 fixture,包括 72 个诊断 fixture,检查原始 UTF-8 字节位置及从起始标记到 EOF 的区间。 -- 原生后端使用不可变的 0.9 准备核心及 C ABI 2;纯实现不需要原生二进制。包版本不变,这些功能尚未包含在已发布的 0.8.1 中。 +- 原生后端使用固定到确切 git 修订版的不可变 0.9.0 候选核心及 C ABI 2;纯实现不需要原生二进制。包版本在此候选版本中更新为 0.9.0;尚未发布。 ### 文档 -- 扩展 README 示例:点分路径与字面键、混合数组、String/Integer 区别、多行展开、逐字节 no-op 及 BOM/CRLF/EOF 保留。明确 0.9 字节诊断、安全拒绝、ABI 2 和独立纯实现用法;这些新增功能不属于已发布的 0.8.1。 +- 扩展 README 示例:点分路径与字面键、混合数组、String/Integer 区别、多行展开、逐字节 no-op 及 BOM/CRLF/EOF 保留。明确 0.9 字节诊断、安全拒绝、ABI 2 和独立纯实现用法;这些新增功能属于 0.9.0 候选版本,尚未发布。 diff --git a/root-docs/CHANGELOG/unreleased/body-1.md b/root-docs/CHANGELOG/unreleased/body-1.md index 9b87cdb..4c2f04a 100644 --- a/root-docs/CHANGELOG/unreleased/body-1.md +++ b/root-docs/CHANGELOG/unreleased/body-1.md @@ -1,15 +1,15 @@ >>>>> lang=en -## Unreleased +## Unreleased — 0.9.0 preparation -- Add pure-backend `insertValue` / `insertValueSegments`, `removeValue` / `removeValueSegments`, and `renameKey` / `renameKeySegments`, matching the native source-edit APIs. Insert requires an existing Object parent; remove retains empty ancestors; rename preserves value and order. Successful splices verify the intended tree, and unsafe source shapes fail with `EditUnsupported`. Insert/rename collisions report `EditAlreadyExists`. These APIs prepare 0.9; package versions are unchanged. +- Add pure-backend `insertValue` / `insertValueSegments`, `removeValue` / `removeValueSegments`, and `renameKey` / `renameKeySegments`, matching the native source-edit APIs. Insert requires an existing Object parent; remove retains empty ancestors; rename preserves value and order. Successful splices verify the intended tree, and unsafe source shapes fail with `EditUnsupported`. Insert/rename collisions report `EditAlreadyExists`. These APIs are part of the 0.9.0 candidate; package versions move to 0.9.0 and nothing is published yet. >>>>> lang=ru -## Unreleased +## Unreleased — 0.9.0 preparation -- Добавлены чистые `insertValue` / `insertValueSegments`, `removeValue` / `removeValueSegments` и `renameKey` / `renameKeySegments`, соответствующие нативному API. Вставка требует существующего Object-родителя, удаление сохраняет пустых предков, переименование сохраняет значение и порядок. Успешный сплайс проверяет ожидаемое дерево; небезопасная форма исходника даёт `EditUnsupported`. Коллизии вставки/переименования — `EditAlreadyExists`. Это подготовка 0.9; версии пакетов не изменены. +- Добавлены чистые `insertValue` / `insertValueSegments`, `removeValue` / `removeValueSegments` и `renameKey` / `renameKeySegments`, соответствующие нативному API. Вставка требует существующего Object-родителя, удаление сохраняет пустых предков, переименование сохраняет значение и порядок. Успешный сплайс проверяет ожидаемое дерево; небезопасная форма исходника даёт `EditUnsupported`. Коллизии вставки/переименования — `EditAlreadyExists`. Это часть кандидата 0.9.0; версии пакетов переходят к 0.9.0, публикация ещё не выполнена. >>>>> lang=zh -## Unreleased +## Unreleased — 0.9.0 preparation -- 新增纯后端 `insertValue` / `insertValueSegments`、`removeValue` / `removeValueSegments` 和 `renameKey` / `renameKeySegments`,对应原生源文本编辑 API。插入要求已存在的 Object 父节点,删除保留空祖先,重命名保留值和顺序。成功拼接验证预期树,无法安全处理的源形式返回 `EditUnsupported`;插入或重命名冲突返回 `EditAlreadyExists`。这些 API 为 0.9 做准备,包版本不变。 +- 新增纯后端 `insertValue` / `insertValueSegments`、`removeValue` / `removeValueSegments` 和 `renameKey` / `renameKeySegments`,对应原生源文本编辑 API。插入要求已存在的 Object 父节点,删除保留空祖先,重命名保留值和顺序。成功拼接验证预期树,无法安全处理的源形式返回 `EditUnsupported`;插入或重命名冲突返回 `EditAlreadyExists`。这些 API 属于 0.9.0 候选版本;包版本更新为 0.9.0,尚未发布。 diff --git a/root-docs/README/editing-cookbook/body-1.md b/root-docs/README/editing-cookbook/body-1.md index a7a8b20..404ab8e 100644 --- a/root-docs/README/editing-cookbook/body-1.md +++ b/root-docs/README/editing-cookbook/body-1.md @@ -1,7 +1,7 @@ >>>>> lang=en ### Source-edit cookbook -These examples describe the unreleased 0.9 API, not the published 0.8.1 package. They replace existing values only: keys are not renamed, missing paths are not created, and entries are not removed. Each snippet is independent; Rust `?` assumes an enclosing `Result`-returning function. Go examples panic only for these fixed, known-valid inputs; applications should handle the returned error. +These examples describe the 0.9.0-candidate API, which is not part of a published package yet. They replace existing values only: keys are not renamed, missing paths are not created, and entries are not removed. Each snippet is independent; Rust `?` assumes an enclosing `Result`-returning function. Go examples panic only for these fixed, known-valid inputs; applications should handle the returned error. The binding examples use the standalone pure backend, without a native binary. Native entry points accept the same paths and values: `ktav.EditValue` (Go), `Ktav.editValue` (Java), `KtavApi.EditValue(..., KtavBackend.Native)` (C#), `Ktav::editValue` (PHP), the package's native/FFI exports (JS), and `ktav.edit_value` (Python). C-ABI backends require ABI 2; PyO3/N-API/WASM require the matching preparing-0.9 core. Bun/Deno FFI calls return promises: use `await`; pure/Node/WASM examples shown here are synchronous. @@ -30,7 +30,7 @@ targets.storagehost.user: mcp-agent >>>>> lang=ru ### Практические примеры правки исходника -Примеры относятся к ещё не выпущенному API 0.9, а не к опубликованному пакету 0.8.1. Они заменяют только существующие значения: не переименовывают ключи, не создают отсутствующие пути и не удаляют записи. Фрагменты независимы; Rust `?` предполагает внешнюю функцию с результатом `Result`. В Go panic используется только для фиксированных корректных данных примера; приложение должно обработать возвращённую ошибку. +Примеры относятся к API кандидата 0.9.0, который пока не входит в опубликованные пакеты. Они заменяют только существующие значения: не переименовывают ключи, не создают отсутствующие пути и не удаляют записи. Фрагменты независимы; Rust `?` предполагает внешнюю функцию с результатом `Result`. В Go panic используется только для фиксированных корректных данных примера; приложение должно обработать возвращённую ошибку. Примеры привязок используют самостоятельный pure-бэкенд без native-бинарника. Нативные точки входа принимают те же пути и значения: `ktav.EditValue` (Go), `Ktav.editValue` (Java), `KtavApi.EditValue(..., KtavBackend.Native)` (C#), `Ktav::editValue` (PHP), native/FFI-экспорты пакета (JS), `ktav.edit_value` (Python). C ABI требует версию 2; PyO3/N-API/WASM — совместимое ядро подготовки 0.9. FFI-вызовы Bun/Deno возвращают promise и требуют `await`; показанные pure/Node/WASM-варианты синхронны. @@ -59,7 +59,7 @@ targets.storagehost.user: mcp-agent >>>>> lang=zh ### 源文本编辑示例 -以下示例适用于尚未发布的 0.9 API,而非已发布的 0.8.1 包。只能替换已有值:不会重命名键、创建缺失路径或删除条目。各代码片段相互独立;Rust 的 `?` 假定外层函数返回 `Result`。Go 示例仅针对固定且有效的输入使用 panic;应用程序应处理返回的错误。 +以下示例适用于 0.9.0 候选 API,尚未包含在已发布的包中。只能替换已有值:不会重命名键、创建缺失路径或删除条目。各代码片段相互独立;Rust 的 `?` 假定外层函数返回 `Result`。Go 示例仅针对固定且有效的输入使用 panic;应用程序应处理返回的错误。 绑定示例使用无需原生二进制的独立纯实现。原生入口接收相同的路径和值:Go 的 `ktav.EditValue`、Java 的 `Ktav.editValue`、C# 的 `KtavApi.EditValue(..., KtavBackend.Native)`、PHP 的 `Ktav::editValue`、JS 包的 native/FFI 导出及 Python 的 `ktav.edit_value`。C ABI 后端要求 ABI 2;PyO3/N-API/WASM 要求兼容的 0.9 准备核心。Bun/Deno FFI 返回 promise,需要 `await`;此处 pure/Node/WASM 示例为同步调用。 diff --git a/root-docs/README/pure-backend/body-1.md b/root-docs/README/pure-backend/body-1.md index 2357b63..e0a46a5 100644 --- a/root-docs/README/pure-backend/body-1.md +++ b/root-docs/README/pure-backend/body-1.md @@ -22,7 +22,7 @@ The combined artifact's build declares JNA 5.15.0 as `api` and jackson-core 2.18 For pure-only Gradle use, disable transitive dependencies: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` For Maven, exclude both `net.java.dev.jna:jna` and `com.fasterxml.jackson.core:jackson-core`; alternatively, use the library JAR directly. Pure-only runtime use requires JDK 17 and no third-party runtime libraries. Pure success and error paths use no JNA, Jackson, JUnit, native code, WASM, subprocesses, network access, or fallback. Native backend use requires its dependencies; retain normal dependency resolution for it. @@ -51,7 +51,7 @@ For Maven, exclude both `net.java.dev.jna:jna` and `com.fasterxml.jackson.core:j Для использования только чистого бэкенда в Gradle отключите транзитивные зависимости: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` В Maven исключите `net.java.dev.jna:jna` и `com.fasterxml.jackson.core:jackson-core`; альтернативно используйте JAR библиотеки напрямую. Для выполнения только чистого бэкенда нужен JDK 17, сторонние runtime-библиотеки не нужны. Успешные и ошибочные пути чистого бэкенда не используют JNA, Jackson, JUnit, нативный код, WASM, процессы, сеть или fallback. Нативному бэкенду нужны его зависимости; для него сохраняйте обычное разрешение зависимостей. @@ -80,7 +80,7 @@ implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } Gradle 纯后端用法可关闭传递依赖: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` Maven 请同时排除 `net.java.dev.jna:jna` 和 `com.fasterxml.jackson.core:jackson-core`;也可直接使用本库 JAR。纯后端运行需要 JDK 17,不需要第三方运行时库。纯后端的成功和错误路径均不使用 JNA、Jackson、JUnit、原生代码、WASM、子进程、网络或回退。原生后端用法需要其依赖;请为其保留常规依赖解析。 diff --git a/root-docs/README/quick-start/body-1.md b/root-docs/README/quick-start/body-1.md index 9d28542..3ab60f4 100644 --- a/root-docs/README/quick-start/body-1.md +++ b/root-docs/README/quick-start/body-1.md @@ -9,7 +9,7 @@ repositories { } dependencies { - implementation("io.github.ktav-lang:ktav:0.8.1") + implementation("io.github.ktav-lang:ktav:0.9.0") } ``` @@ -18,7 +18,7 @@ For normal use, the combined artifact resolves its native dependencies: JNA 5.15 For pure-only Gradle use, disable transitive dependencies and call `PureKtav`: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` Pure runtime requires only JDK 17+. Its parser, writer, formatter, and `ErrorEnvelope` holder use no Jackson, JNA, JUnit, native code, WASM, subprocess, network, or fallback. Maven pure-only consumers must exclude both `net.java.dev.jna:jna` and `com.fasterxml.jackson.core:jackson-core`. Build, test, and documentation tooling is separate from runtime. @@ -34,7 +34,7 @@ repositories { } dependencies { - implementation("io.github.ktav-lang:ktav:0.8.1") + implementation("io.github.ktav-lang:ktav:0.9.0") } ``` @@ -43,7 +43,7 @@ dependencies { Для использования только чистого backend в Gradle отключите транзитивные зависимости и вызывайте `PureKtav`: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` Для runtime чистого backend требуется только JDK 17+. Его парсер, writer, formatter и контейнер `ErrorEnvelope` не используют Jackson, JNA, JUnit, native-код, WASM, подпроцессы, сеть или fallback. Для чистого backend в Maven исключите `net.java.dev.jna:jna` и `com.fasterxml.jackson.core:jackson-core`. Инструменты сборки, тестирования и документации отделены от runtime. @@ -59,7 +59,7 @@ repositories { } dependencies { - implementation("io.github.ktav-lang:ktav:0.8.1") + implementation("io.github.ktav-lang:ktav:0.9.0") } ``` @@ -68,7 +68,7 @@ dependencies { 若在 Gradle 中仅使用纯后端,请禁用传递依赖并调用 `PureKtav`: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` 纯后端运行时仅需 JDK 17+。其解析器、写入器、格式化器和 `ErrorEnvelope` 持有对象不使用 Jackson、JNA、JUnit、原生代码、WASM、子进程、网络或回退机制。Maven 纯后端用户需排除 `net.java.dev.jna:jna` 和 `com.fasterxml.jackson.core:jackson-core`。构建、测试和文档工具与运行时相互独立。 diff --git a/root-docs/README/runtime-support/body-1.md b/root-docs/README/runtime-support/body-1.md index fa3aecd..2f8035b 100644 --- a/root-docs/README/runtime-support/body-1.md +++ b/root-docs/README/runtime-support/body-1.md @@ -8,7 +8,7 @@ (musl) support is planned. -The prepared 0.8.1 Windows native distribution uses GNU/LLVM targets +The prepared 0.9.0-candidate Windows native distribution uses GNU/LLVM targets `x86_64-pc-windows-gnullvm` and `aarch64-pc-windows-gnullvm`. The existing `windows-amd64` and `windows-arm64` asset names remain compatibility identifiers, not MSVC compiler claims. These DLLs require @@ -29,7 +29,7 @@ the prepared candidate, not a repair of previously published binaries. Rust). Поддержка Alpine (musl) — запланирована. -Подготовленная Windows native distribution 0.8.1 использует GNU/LLVM targets +Подготовленная Windows native distribution кандидата 0.9.0 использует GNU/LLVM targets `x86_64-pc-windows-gnullvm` и `aarch64-pc-windows-gnullvm`. Прежние имена assets `windows-amd64` и `windows-arm64` сохраняются как идентификаторы совместимости, а не как указание на компилятор MSVC. @@ -51,7 +51,7 @@ the prepared candidate, not a repair of previously published binaries. (musl)支持已规划。 -准备中的 0.8.1 Windows 原生发行包使用 GNU/LLVM 目标 +准备中的 0.9.0 候选 Windows 原生发行包使用 GNU/LLVM 目标 `x86_64-pc-windows-gnullvm` 和 `aarch64-pc-windows-gnullvm`。 现有的 `windows-amd64`、`windows-arm64` 文件名保留为兼容性标识, 并不表示使用 MSVC 编译。这些 DLL 在运行时不需要 Rust/LLVM 构建工具 diff --git a/root-docs/README/source-edit-status/body-1.md b/root-docs/README/source-edit-status/body-1.md index 00dd212..5db5cdf 100644 --- a/root-docs/README/source-edit-status/body-1.md +++ b/root-docs/README/source-edit-status/body-1.md @@ -1,9 +1,9 @@ >>>>> lang=en -> **Unreleased (0.9 preparation):** These editing APIs and updated diagnostics are not included in published 0.8.1 packages. Native backends require the pinned 0.9 core (C ABI 2 for C-FFI); pure backends remain standalone. +> **Unreleased (0.9 preparation):** These editing APIs and updated diagnostics are part of the 0.9.0 candidate and are not published in any released package yet. Native backends require the pinned 0.9.0-candidate core (C ABI 2 for C-FFI); pure backends remain standalone. >>>>> lang=ru -> **Ещё не выпущено (подготовка 0.9):** Эти API редактирования и обновлённая диагностика не входят в опубликованные пакеты 0.8.1. Native-backend требует закреплённое ядро 0.9 (C ABI 2 для C-FFI); pure-backend остаётся самостоятельным. +> **Ещё не выпущено (подготовка 0.9):** Эти API редактирования и обновлённая диагностика входят в кандидат 0.9.0 и пока не опубликованы ни в одном выпущенном пакете. Native-backend требует закреплённое ядро кандидата 0.9.0 (C ABI 2 для C-FFI); pure-backend остаётся самостоятельным. >>>>> lang=zh -> **尚未发布(0.9 准备版本):** 这些编辑 API 和更新后的诊断不包含在已发布的 0.8.1 包中。原生后端需要固定的 0.9 核心(C-FFI 使用 C ABI 2);纯实现仍完全独立。 +> **尚未发布(0.9 准备版本):** 这些编辑 API 和更新后的诊断属于 0.9.0 候选版本,尚未包含在任何已发布包中。原生后端需要固定的 0.9.0 候选核心(C-FFI 使用 C ABI 2);纯实现仍完全独立。 diff --git a/scripts/cabi_gnullvm_notices.py b/scripts/cabi_gnullvm_notices.py index 167b8d5..e0eba85 100644 --- a/scripts/cabi_gnullvm_notices.py +++ b/scripts/cabi_gnullvm_notices.py @@ -13,6 +13,8 @@ CATALOG = 'ci/licenses/cabi-gnullvm-runtime.json' CATALOG_SHA = '793c61f930c31a27f987c169eec4a07cc8c140dd16e91653fec3d029f803a816' SDK_SHA = 'fd5462b7f5d93b2ff981fcd3f9c7e427e47f3203c64ea91c27bcc444eebd74cd' +HISTORICAL_SOURCE = 'b252ccfaed66505952ad63a99663e8b6ff530d62' +CANDIDATE_CORE = 'git+https://github.com/ktav-lang/rust?rev=c1d569f60b7f64fe94b5f022082a52c0bcac194e#c1d569f60b7f64fe94b5f022082a52c0bcac194e' REVISIONS = {'mingw-w64/mingw-w64': '0d6dfbc348dfad714761c0a7151615767f96bcb5', 'llvm/llvm-project': '7a941dfb2877a0b8cf30323fefa85ad019e0b0f5'} DATA_ONLY = {'mingw-w64-crt/crt/cinitexe.c', 'mingw-w64-crt/misc/mingw_matherr.c', 'mingw-w64-crt/misc/dllmain.c'} MAX_FILE = 4 * 1024 * 1024 @@ -162,6 +164,29 @@ def sdk_inputs(items, target): return sorted(selected, key=lambda item: item['path']) +def source_binding(provenance, evidence, expected_source_sha): + # The expected source SHA is passed INDEPENDENTLY by the caller + # (workflow input), never read from the provenance record itself. + # Historical 0.8.1 proof keeps its exact byte binding; the 0.9.0 + # candidate additionally requires the declared core git source to + # match the lock-derived core-provenance.json (verified Cargo.lock + # identity) and the expected candidate core string. + source_ref = provenance.get('source_ref') + if not isinstance(source_ref, str) or not re.fullmatch(r'[0-9a-f]{40}', source_ref): + return False + if provenance['source_ref'] != expected_source_sha: + return False + if provenance['source_ref'] == HISTORICAL_SOURCE: + return provenance.get('core_git_source') is None + try: + core_lock = json.loads(read(evidence / 'core-provenance.json', MAX_FILE)) + except (ValueError, json.JSONDecodeError): + return False + return (provenance.get('core_git_source') == CANDIDATE_CORE + and core_lock.get('source') == CANDIDATE_CORE + and core_lock.get('version') == '0.9.0') + + def verify_inputs(items, mapping, document, target): if target not in document['targets']: raise ValueError('unreviewed C ABI target') @@ -170,7 +195,7 @@ def verify_inputs(items, mapping, document, target): raise ValueError('C ABI SDK bytes or retained objects differ from reviewed profile') -def verify(evidence, binary, target): +def verify(evidence, binary, target, expected_source_sha): spec = importlib.util.spec_from_file_location('cabi_notice_scanner', Path(__file__).with_name('check_embedded_notices.py')) scanner = importlib.util.module_from_spec(spec) spec.loader.exec_module(scanner) @@ -197,8 +222,10 @@ def verify(evidence, binary, target): inputs = json.loads(read(evidence / 'link-input-fingerprints.json', MAX_FILE)) verify_inputs(inputs, mapping, document, target) provenance = json.loads(read(evidence / 'source-provenance.json', MAX_FILE)) - if provenance['sdk_archive_sha256'] != SDK_SHA or provenance['source_ref'] != 'b252ccfaed66505952ad63a99663e8b6ff530d62': + if provenance['sdk_archive_sha256'] != SDK_SHA: raise ValueError('C ABI source/SDK identity differs') + if not source_binding(provenance, evidence, expected_source_sha): + raise ValueError('C ABI source/core-lock identity differs from the independently expected source') report = {'target': target, 'binary_sha256': identity['binary_sha256'], 'notice_sha256': hashlib.sha256(notice).hexdigest(), 'catalog_sha256': CATALOG_SHA, 'sdk_inputs': len(expected['sdk_inputs']), 'retained_runtime_objects': len(expected['retained_objects']), 'source_records': len(document['source_files']), 'scope': 'Actual C ABI DLL resource and target-specific SDK input/source-grant binding; not NAPI compatibility, other targets or historical published artifact clearance.'} (evidence / 'native-runtime-verification.json').write_text(json.dumps(report, sort_keys=True, indent=2) + '\n', encoding='utf-8') print(json.dumps(report, sort_keys=True)) @@ -207,7 +234,7 @@ def verify(evidence, binary, target): if __name__ == '__main__': if len(sys.argv) == 4 and sys.argv[1] == 'prepare': prepare(Path(sys.argv[2]), sys.argv[3]) - elif len(sys.argv) == 5 and sys.argv[1] == 'verify': - verify(Path(sys.argv[2]), Path(sys.argv[3]), sys.argv[4]) + elif len(sys.argv) == 6 and sys.argv[1] == 'verify': + verify(Path(sys.argv[2]), Path(sys.argv[3]), sys.argv[4], sys.argv[5]) else: - raise SystemExit('usage: cabi_gnullvm_notices.py prepare EVIDENCE TARGET | verify EVIDENCE BINARY TARGET') + raise SystemExit('usage: cabi_gnullvm_notices.py prepare EVIDENCE TARGET | verify EVIDENCE BINARY TARGET EXPECTED_SOURCE_SHA') diff --git a/scripts/check_publish_metadata.py b/scripts/check_publish_metadata.py index 96e46ee..5f7756c 100644 --- a/scripts/check_publish_metadata.py +++ b/scripts/check_publish_metadata.py @@ -4,7 +4,7 @@ Default mode verifies, without publishing, signing, or any secrets: - lib/build/publications/maven/pom-default.xml - lib/build/publications/maven/module.json - - lib/build/libs/ktav-0.8.1.jar (exact name) + - lib/build/libs/ktav-0.9.0.jar (exact name) All checks are structural (stdlib XML/JSON/zipfile parsing), fail-closed, and print "FAIL: " per defect. Exit 0 only if everything passes. @@ -26,10 +26,10 @@ GROUP = "io.github.ktav-lang" ARTIFACT = "ktav" -VERSION = "0.8.1" +VERSION = "0.9.0" POM = "lib/build/publications/maven/pom-default.xml" MODULE = "lib/build/publications/maven/module.json" -JAR = "lib/build/libs/ktav-0.8.1.jar" +JAR = "lib/build/libs/ktav-0.9.0.jar" # (group, artifact, version, allowed_scopes) — scope None means omitted-or-compile. EXPECTED_POM_DEPS = { diff --git a/scripts/metadata-fixtures/module-good.json b/scripts/metadata-fixtures/module-good.json index 69244a3..985d3b1 100644 --- a/scripts/metadata-fixtures/module-good.json +++ b/scripts/metadata-fixtures/module-good.json @@ -3,7 +3,7 @@ "component": { "group": "io.github.ktav-lang", "module": "ktav", - "version": "0.8.1" + "version": "0.9.0" }, "variants": [ { diff --git a/scripts/metadata-fixtures/pom-good.xml b/scripts/metadata-fixtures/pom-good.xml index c72d352..b914f05 100644 --- a/scripts/metadata-fixtures/pom-good.xml +++ b/scripts/metadata-fixtures/pom-good.xml @@ -7,7 +7,7 @@ io.github.ktav-lang ktav - 0.8.1 + 0.9.0 net.java.dev.jna From d6d078a01da794a091b23d0eba06d01b3bb1f954 Mon Sep 17 00:00:00 2001 From: Marat K Date: Thu, 3 Dec 2026 10:19:14 +0100 Subject: [PATCH 2/6] Fix Java candidate provenance and local installation checks Preserve signing for remote publication, use the reviewed notice hook on candidate sources, and include the CI-generated documentation. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci.yml | 3 +- .github/workflows/licenses.yml | 4 +- .../workflows/windows-gnu-cabi-candidate.yml | 19 +++++-- CHANGELOG.md | 10 ++-- README.md | 12 ++--- ci/allowed-licenses.json | 2 +- ci/check_native_distribution.rb | 11 +++- ci/license-init.gradle | 35 +++++++++++++ ci/test_native_distribution_contract.py | 34 +++++++++++++ docs/ru/CHANGELOG.ru.md | 10 ++-- docs/ru/README.ru.md | 12 ++--- docs/zh/CHANGELOG.zh.md | 10 ++-- docs/zh/README.zh.md | 12 ++--- lib/build.gradle.kts | 8 ++- scripts/stage_java_gnu_release.py | 50 ++++++++++++++++--- 15 files changed, 181 insertions(+), 51 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 625bc1a..76c648c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -198,7 +198,8 @@ jobs: - name: Install the candidate package into an isolated maven repo run: > ./gradlew :lib:publishToMavenLocal - -Dmaven.repo.local="$RUNNER_TEMP/maven-local" --no-daemon --stacktrace + -Dmaven.repo.local="$RUNNER_TEMP/maven-local" + -Pktav.candidateInstall=true --no-daemon --stacktrace - name: Installed 0.9.0 artifact is exactly the built jar run: | set -euo pipefail diff --git a/.github/workflows/licenses.yml b/.github/workflows/licenses.yml index 48b3d13..772bb05 100644 --- a/.github/workflows/licenses.yml +++ b/.github/workflows/licenses.yml @@ -132,7 +132,9 @@ jobs: curl -fsSL https://raw.githubusercontent.com/gradle/foojay-toolchains/f4575ddf844fcfd4ad9e758d2040cfd50b59f173/LICENSE > "$RUNNER_TEMP/foojay-LICENSE" printf '%s %s\n' c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 "$RUNNER_TEMP/foojay-LICENSE" | sha256sum --check - name: Check all Gradle configurations and buildscript dependencies - run: ./gradlew --no-daemon --no-parallel -I ci/license-init.gradle checkLicense + run: > + ./gradlew --no-daemon --no-parallel -I ci/license-init.gradle + :lib:generatePomFileForMavenPublication checkLicense - name: Build JARs and verify license files shell: bash run: | diff --git a/.github/workflows/windows-gnu-cabi-candidate.yml b/.github/workflows/windows-gnu-cabi-candidate.yml index 4a9af54..735fdd1 100644 --- a/.github/workflows/windows-gnu-cabi-candidate.yml +++ b/.github/workflows/windows-gnu-cabi-candidate.yml @@ -89,9 +89,20 @@ jobs: raise SystemExit('existing Java build hook requires review') shutil.copyfile(path, destination) hook = b'include!(concat!(env!("OUT_DIR"), "/native_notices.rs"));' - if hook in original: - raise SystemExit('unexpected original notice overlay') - source.write_bytes(original + bytes([10, 10]) + hook + bytes([10])) + if historical: + if hook in original: + raise SystemExit('unexpected original notice overlay') + source.write_bytes(original + bytes([10, 10]) + hook + bytes([10])) + else: + # The 0.9.0 candidate source already carries its native + # notice resource hook: never re-apply the legacy overlay. + # Bind the EXACT source identity instead — the hook must + # occur exactly once and the whole file must hash to the + # reviewed candidate bytes recorded below. + if original.count(hook) != 1: + raise SystemExit('candidate native notice resource hook is missing or duplicated') + if hashlib.sha256(original).hexdigest() != 'eb69a5d46243e2527fdbf32de4b7cd6fb3ab1638bfc6174e4d06f72115f3c6e3': + raise SystemExit('candidate C ABI source identity differs') protected = ['Cargo.toml', 'crates', 'lib', 'tests', 'root-docs', 'pom.xml'] changed = set(subprocess.check_output(['git', 'diff', '--name-only', '--', *protected], text=True).splitlines()) changed.update(subprocess.check_output(['git', 'ls-files', '--others', '--exclude-standard', '--', *protected], text=True).splitlines()) @@ -503,7 +514,7 @@ jobs: shell: bash run: | set -euo pipefail - python -I scripts/stage_java_gnu_release.py "$RUNNER_TEMP/java-gnu-delivered" "$RUNNER_TEMP/java-gnu-release" '${{ matrix.target }}' + python -I scripts/stage_java_gnu_release.py "$RUNNER_TEMP/java-gnu-delivered" "$RUNNER_TEMP/java-gnu-release" '${{ matrix.target }}' --expected-source "$SOURCE_REF" - uses: actions/upload-artifact@v4 with: name: native-distribution-${{ matrix.target }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 2eae786..e2b9693 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,19 +11,19 @@ This changelog tracks **binding releases**, not changes to the Ktav format itself — for the latter see [`ktav-lang/spec`](https://github.com/ktav-lang/spec/blob/main/CHANGELOG.md). -## Unreleased — 0.9 preparation +## Unreleased — 0.9.0 preparation - Add native and standalone pure editing by textual path or literal segments: source splicing, preserved container forms, minimal readability transitions, comment protection, byte-identical no-op and semantic verification. - Apply 0.9 source diagnostics and the pinned 412-case conformance corpus, including 72 diagnostic fixtures with raw UTF-8 byte locations and EOF opener spans. -- Native uses the immutable preparing-0.9 core and C ABI 2; pure remains independent of native binaries. Package versions are unchanged; this functionality is not published in 0.8.1. +- Native uses the immutable 0.9.0-candidate core pinned to its exact git revision, with C ABI 2; pure remains independent of native binaries. Package versions move to 0.9.0 in this candidate; nothing is published yet. ### Documentation -- Expand README examples for dotted and literal-key paths, mixed arrays, String/Integer identity, multiline unfolding, byte-identical no-op and BOM/CRLF/EOF preservation. Clarify 0.9 byte diagnostics, safe refusal, ABI 2 and standalone pure usage; these additions are not part of published 0.8.1. +- Expand README examples for dotted and literal-key paths, mixed arrays, String/Integer identity, multiline unfolding, byte-identical no-op and BOM/CRLF/EOF preservation. Clarify 0.9 byte diagnostics, safe refusal, ABI 2 and standalone pure usage; these additions are part of the 0.9.0 candidate and are not published yet. -## Unreleased +## Unreleased — 0.9.0 preparation -- Add pure-backend `insertValue` / `insertValueSegments`, `removeValue` / `removeValueSegments`, and `renameKey` / `renameKeySegments`, matching the native source-edit APIs. Insert requires an existing Object parent; remove retains empty ancestors; rename preserves value and order. Successful splices verify the intended tree, and unsafe source shapes fail with `EditUnsupported`. Insert/rename collisions report `EditAlreadyExists`. These APIs prepare 0.9; package versions are unchanged. +- Add pure-backend `insertValue` / `insertValueSegments`, `removeValue` / `removeValueSegments`, and `renameKey` / `renameKeySegments`, matching the native source-edit APIs. Insert requires an existing Object parent; remove retains empty ancestors; rename preserves value and order. Successful splices verify the intended tree, and unsafe source shapes fail with `EditUnsupported`. Insert/rename collisions report `EditAlreadyExists`. These APIs are part of the 0.9.0 candidate; package versions move to 0.9.0 and nothing is published yet. ## 0.8.1 — 2026-10-22 diff --git a/README.md b/README.md index 3cc3e66..ad0ac1c 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ repositories { } dependencies { - implementation("io.github.ktav-lang:ktav:0.8.1") + implementation("io.github.ktav-lang:ktav:0.9.0") } ``` @@ -38,7 +38,7 @@ For normal use, the combined artifact resolves its native dependencies: JNA 5.15 For pure-only Gradle use, disable transitive dependencies and call `PureKtav`: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` Pure runtime requires only JDK 17+. Its parser, writer, formatter, and `ErrorEnvelope` holder use no Jackson, JNA, JUnit, native code, WASM, subprocess, network, or fallback. Maven pure-only consumers must exclude both `net.java.dev.jna:jna` and `com.fasterxml.jackson.core:jackson-core`. Build, test, and documentation tooling is separate from runtime. @@ -173,7 +173,7 @@ equals `Ktav.emitCanonical(Ktav.loads(src))`. The stronger condition is deliberate: blank lines are no more part of the `Value` model than comments are, so the canonical writer drops them and `format` does not. -> **Unreleased (0.9 preparation):** These editing APIs and updated diagnostics are not included in published 0.8.1 packages. Native backends require the pinned 0.9 core (C ABI 2 for C-FFI); pure backends remain standalone. +> **Unreleased (0.9 preparation):** These editing APIs and updated diagnostics are part of the 0.9.0 candidate and are not published in any released package yet. Native backends require the pinned 0.9.0-candidate core (C ABI 2 for C-FFI); pure backends remain standalone. ### Editing source text @@ -231,7 +231,7 @@ over edit validation. Pure mode has no native dependency or fallback. ### Source-edit cookbook -These examples describe the unreleased 0.9 API, not the published 0.8.1 package. They replace existing values only: keys are not renamed, missing paths are not created, and entries are not removed. Each snippet is independent; Rust `?` assumes an enclosing `Result`-returning function. Go examples panic only for these fixed, known-valid inputs; applications should handle the returned error. +These examples describe the 0.9.0-candidate API, which is not part of a published package yet. They replace existing values only: keys are not renamed, missing paths are not created, and entries are not removed. Each snippet is independent; Rust `?` assumes an enclosing `Result`-returning function. Go examples panic only for these fixed, known-valid inputs; applications should handle the returned error. The binding examples use the standalone pure backend, without a native binary. Native entry points accept the same paths and values: `ktav.EditValue` (Go), `Ktav.editValue` (Java), `KtavApi.EditValue(..., KtavBackend.Native)` (C#), `Ktav::editValue` (PHP), the package's native/FFI exports (JS), and `ktav.edit_value` (Python). C-ABI backends require ABI 2; PyO3/N-API/WASM require the matching preparing-0.9 core. Bun/Deno FFI calls return promises: use `await`; pure/Node/WASM examples shown here are synchronous. @@ -490,7 +490,7 @@ The combined artifact's build declares JNA 5.15.0 as `api` and jackson-core 2.18 For pure-only Gradle use, disable transitive dependencies: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` For Maven, exclude both `net.java.dev.jna:jna` and `com.fasterxml.jackson.core:jackson-core`; alternatively, use the library JAR directly. Pure-only runtime use requires JDK 17 and no third-party runtime libraries. Pure success and error paths use no JNA, Jackson, JUnit, native code, WASM, subprocesses, network access, or fallback. Native backend use requires its dependencies; retain normal dependency resolution for it. @@ -532,7 +532,7 @@ reference writer's documented layout (4-space indent, insertion order, (musl) support is planned. -The prepared 0.8.1 Windows native distribution uses GNU/LLVM targets +The prepared 0.9.0-candidate Windows native distribution uses GNU/LLVM targets `x86_64-pc-windows-gnullvm` and `aarch64-pc-windows-gnullvm`. The existing `windows-amd64` and `windows-arm64` asset names remain compatibility identifiers, not MSVC compiler claims. These DLLs require diff --git a/ci/allowed-licenses.json b/ci/allowed-licenses.json index 038115a..7770c97 100644 --- a/ci/allowed-licenses.json +++ b/ci/allowed-licenses.json @@ -12,7 +12,7 @@ { "moduleLicense": "ISC" }, { "moduleName": "org[.]junit([.].*)?:.*", "moduleLicense": "Eclipse Public License - v 2[.]0" }, { "moduleName": "org[.]junit([.].*)?:.*", "moduleLicense": "Eclipse Public License v2[.]0" }, - { "moduleName": "io[.]github[.]ktav-lang:lib", "moduleVersion": "0[.]8[.]1", "moduleLicense": "" }, + { "moduleName": "io[.]github[.]ktav-lang:lib", "moduleVersion": "0[.]9[.]0", "moduleLicense": "" }, { "moduleName": "org[.]gradle[.]toolchains:foojay-resolver", "moduleVersion": "0[.]9[.]0", "moduleLicense": "" } ] } diff --git a/ci/check_native_distribution.rb b/ci/check_native_distribution.rb index a98c02d..aa64a06 100644 --- a/ci/check_native_distribution.rb +++ b/ci/check_native_distribution.rb @@ -39,9 +39,16 @@ %w[ktav_cabi-windows-amd64.dll ktav_cabi-windows-arm64.dll .NOTICE.json .NOTICE.manifest.json check_embedded_notices.py source_ref target].each do |role| abort "missing GNU delivery role #{role}" unless stager.include?(role) end -caller = YAML.load_file('.github/workflows/native-distribution-check.yml').fetch('jobs').fetch('native-distribution') +caller_file = YAML.load_file('.github/workflows/native-distribution-check.yml') +caller = caller_file.fetch('jobs').fetch('native-distribution') abort 'wrong native CI caller' unless caller.fetch('uses') == path -abort 'native CI source is not pinned' unless caller.fetch('with').fetch('source-ref').match?(/\A[0-9a-f]{40}\z/) +# The candidate source is the EXACT PR head commit (never the synthetic +# merge commit), bound by a checkout + rev-parse guard job. +abort 'native CI source is not the exact PR head' unless caller.fetch('with').fetch('source-ref') == '${{ github.event.pull_request.head.sha }}' +binder = caller_file.fetch('jobs').fetch('bind-source') +abort 'missing PR head binding job' unless !binder.key?('needs') && binder.fetch('steps').any? { |step| step['run'].to_s.include?('git rev-parse HEAD') } +abort 'PR head binding guard compares the wrong reference' unless caller_file.to_s.include?('${{ github.event.pull_request.head.sha }}') && binder.fetch('steps').any? { |step| step['run'].to_s.include?('github.event.pull_request.head.sha') } +abort 'PR head binding job does not gate the distribution' unless caller.fetch('needs').to_s == 'bind-source' release = YAML.load_file('.github/workflows/release.yml').fetch('jobs') producer = release.fetch('build-native') abort 'production native build differs from CI' unless producer.fetch('uses') == path diff --git a/ci/license-init.gradle b/ci/license-init.gradle index f79fe6a..32c5c96 100644 --- a/ci/license-init.gradle +++ b/ci/license-init.gradle @@ -57,6 +57,15 @@ gradle.projectsEvaluated { } } } + // The plugin reports the build's OWN project component with an + // empty license list, because no POM exists during the report run. + // The gap is covered WITHOUT rewriting the scanner's input report: + // 1) an exact allowed-licenses rule scoped to + // io.github.ktav-lang:lib at 0.9.0 with an empty module license + // (nothing else matches it), + // 2) a verification that the real LICENSE-MIT / LICENSE-APACHE + // files are present and the generated publication POM declares + // exactly the MIT and Apache-2.0 licenses of this project. root.tasks.named("checkLicense") { dependsOn(guard) doLast { @@ -65,6 +74,32 @@ gradle.projectsEvaluated { if (!names.contains("org.gradle.toolchains:foojay-resolver") || !names.contains("com.google.code.gson:gson")) { throw new GradleException("Foojay resolver and its transitive Gson dependency must be in the license report") } + // Own component: exact moduleName form as in the guard above + // (fully qualified "group:name"), exact candidate version. + def own = data.dependencies.findAll { + it.moduleName == "io.github.ktav-lang:lib" && it.moduleVersion == "0.9.0" + } + if (own.size() != 1) throw new GradleException("Expected exactly one own component io.github.ktav-lang:lib:0.9.0 in the license report, found " + own.size()) + if (own[0].moduleLicense != null && own[0].moduleLicense != "") { + throw new GradleException("The empty-metadata rule must stay scoped to the own 0.9.0 component; it must not mask a real license of any other module: " + own[0].moduleLicense) + } + // Real own LICENSE files at the repository root. + def mit = root.file("LICENSE-MIT") + def apache = root.file("LICENSE-APACHE") + if (!mit.isFile() || !apache.isFile()) throw new GradleException("Own LICENSE-MIT / LICENSE-APACHE files are missing") + if (!mit.text.contains("Permission is hereby granted, free of charge")) throw new GradleException("LICENSE-MIT does not contain the MIT permission grant") + if (!apache.text.contains("Apache License") || !apache.text.contains("Version 2.0, January 2004")) throw new GradleException("LICENSE-APACHE is not the Apache License 2.0 text") + // The generated publication POM must declare exactly these + // two licenses for the own component. + def pom = root.file("lib/build/publications/maven/pom-default.xml") + if (!pom.isFile()) throw new GradleException("Generated publication POM is missing; generate it before checkLicense") + def licenses = [] + new groovy.util.XmlSlurper().parse(pom).depthFirst().findAll { it.name() == "license" }.each { license -> + licenses << license.children().find { it.name() == "name" }?.text() + } + licenses = licenses.findAll { it != null && it != "" } + def expected = ["MIT License", "Apache License 2.0"] as Set + if (licenses as Set != expected) throw new GradleException("Publication POM licenses differ from the real own licenses: " + licenses) } } } diff --git a/ci/test_native_distribution_contract.py b/ci/test_native_distribution_contract.py index fc362b4..645bbff 100644 --- a/ci/test_native_distribution_contract.py +++ b/ci/test_native_distribution_contract.py @@ -43,6 +43,40 @@ def test_missing_genuine_gnu_target_is_rejected(self): def test_missing_source_forwarding_is_rejected(self): self.reject(NATIVE, ' source-ref: ${{ inputs.source-ref }}\n', ' source-ref: fixed-unreviewed-source\n', 'GNU source is not forwarded') + def test_merge_commit_source_is_rejected(self): + self.reject('.github/workflows/native-distribution-check.yml', + "source-ref: ${{ github.event.pull_request.head.sha }}", + "source-ref: ${{ github.sha }}", + 'native CI source is not the exact PR head') + + def test_literal_pinned_sha_caller_is_rejected(self): + self.reject('.github/workflows/native-distribution-check.yml', + "source-ref: ${{ github.event.pull_request.head.sha }}", + "source-ref: b252ccfaed66505952ad63a99663e8b6ff530d62", + 'native CI source is not the exact PR head') + + def test_missing_head_binding_job_is_rejected(self): + self.reject('.github/workflows/native-distribution-check.yml', + ' bind-source: +', + ' bind-source-unused: +', + 'missing PR head binding job') + + def test_head_binding_without_rev_parse_is_rejected(self): + self.reject('.github/workflows/native-distribution-check.yml', + 'git rev-parse HEAD', + 'git status --short', + 'missing PR head binding job') + + def test_binding_job_not_gating_distribution_is_rejected(self): + self.reject('.github/workflows/native-distribution-check.yml', + ' needs: bind-source +', + ' needs: [] +', + 'PR head binding job does not gate the distribution') + def test_missing_consumer_success_gate_is_rejected(self): self.reject(GNU, ' needs: [cabi-gnullvm, java-consumers]\n', ' needs: [cabi-gnullvm]\n', 'missing complete GNU consumer gate') diff --git a/docs/ru/CHANGELOG.ru.md b/docs/ru/CHANGELOG.ru.md index 185229f..ac20f95 100644 --- a/docs/ru/CHANGELOG.ru.md +++ b/docs/ru/CHANGELOG.ru.md @@ -11,19 +11,19 @@ формата Ktav — для последнего см. [`ktav-lang/spec`](https://github.com/ktav-lang/spec/blob/main/CHANGELOG.md). -## Ещё не выпущено — подготовка 0.9 +## Ещё не выпущено — подготовка 0.9.0 - Добавлено редактирование по текстовому пути или буквальным сегментам в native- и самостоятельном pure-backend: source splice, сохранение форм контейнеров, минимальные переходы читаемости, защита комментариев, byte-identical no-op и семантическая проверка. - Применена диагностика исходника 0.9 и закреплён corpus из 412 фикстур, включая 72 диагностические фикстуры с позициями сырых байтов UTF-8 и EOF spans от opener. -- Native использует immutable ядро подготовки 0.9 и C ABI 2; pure не требует native-бинарников. Версии пакетов не менялись; функционал не опубликован в 0.8.1. +- Native использует immutable ядро кандидата 0.9.0, закреплённое за точной git-ревизией, и C ABI 2; pure не требует native-бинарников. Версии пакетов в этом кандидате переходят к 0.9.0; публикация ещё не выполнена. ### Документация -- Дополнены примеры README: dotted-пути и буквальные ключи, смешанные массивы, различие String/Integer, раскрытие многострочной замены, побайтовый no-op и сохранение BOM/CRLF/EOF. Уточнены байтовая диагностика 0.9, безопасные отказы, ABI 2 и самостоятельный pure-бэкенд; дополнения не относятся к опубликованному 0.8.1. +- Дополнены примеры README: dotted-пути и буквальные ключи, смешанные массивы, различие String/Integer, раскрытие многострочной замены, побайтовый no-op и сохранение BOM/CRLF/EOF. Уточнены байтовая диагностика 0.9, безопасные отказы, ABI 2 и самостоятельный pure-бэкенд; дополнения входят в кандидат 0.9.0 и ещё не опубликованы. -## Unreleased +## Unreleased — 0.9.0 preparation -- Добавлены чистые `insertValue` / `insertValueSegments`, `removeValue` / `removeValueSegments` и `renameKey` / `renameKeySegments`, соответствующие нативному API. Вставка требует существующего Object-родителя, удаление сохраняет пустых предков, переименование сохраняет значение и порядок. Успешный сплайс проверяет ожидаемое дерево; небезопасная форма исходника даёт `EditUnsupported`. Коллизии вставки/переименования — `EditAlreadyExists`. Это подготовка 0.9; версии пакетов не изменены. +- Добавлены чистые `insertValue` / `insertValueSegments`, `removeValue` / `removeValueSegments` и `renameKey` / `renameKeySegments`, соответствующие нативному API. Вставка требует существующего Object-родителя, удаление сохраняет пустых предков, переименование сохраняет значение и порядок. Успешный сплайс проверяет ожидаемое дерево; небезопасная форма исходника даёт `EditUnsupported`. Коллизии вставки/переименования — `EditAlreadyExists`. Это часть кандидата 0.9.0; версии пакетов переходят к 0.9.0, публикация ещё не выполнена. ## 0.8.1 — 2026-10-22 diff --git a/docs/ru/README.ru.md b/docs/ru/README.ru.md index 178db7a..01dc9b0 100644 --- a/docs/ru/README.ru.md +++ b/docs/ru/README.ru.md @@ -30,7 +30,7 @@ repositories { } dependencies { - implementation("io.github.ktav-lang:ktav:0.8.1") + implementation("io.github.ktav-lang:ktav:0.9.0") } ``` @@ -39,7 +39,7 @@ dependencies { Для использования только чистого backend в Gradle отключите транзитивные зависимости и вызывайте `PureKtav`: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` Для runtime чистого backend требуется только JDK 17+. Его парсер, writer, formatter и контейнер `ErrorEnvelope` не используют Jackson, JNA, JUnit, native-код, WASM, подпроцессы, сеть или fallback. Для чистого backend в Maven исключите `net.java.dev.jna:jna` и `com.fasterxml.jackson.core:jackson-core`. Инструменты сборки, тестирования и документации отделены от runtime. @@ -176,7 +176,7 @@ System.out.print(Ktav.format("## the server\nserver: {host: a, port: 80}\n")); пустые строки входят в модель `Value` не больше, чем комментарии, поэтому канонический writer их отбрасывает, а `format` — нет. -> **Ещё не выпущено (подготовка 0.9):** Эти API редактирования и обновлённая диагностика не входят в опубликованные пакеты 0.8.1. Native-backend требует закреплённое ядро 0.9 (C ABI 2 для C-FFI); pure-backend остаётся самостоятельным. +> **Ещё не выпущено (подготовка 0.9):** Эти API редактирования и обновлённая диагностика входят в кандидат 0.9.0 и пока не опубликованы ни в одном выпущенном пакете. Native-backend требует закреплённое ядро кандидата 0.9.0 (C ABI 2 для C-FFI); pure-backend остаётся самостоятельным. ### Правка исходного текста @@ -235,7 +235,7 @@ Object либо индекс Array с нуля в зависимости от р ### Практические примеры правки исходника -Примеры относятся к ещё не выпущенному API 0.9, а не к опубликованному пакету 0.8.1. Они заменяют только существующие значения: не переименовывают ключи, не создают отсутствующие пути и не удаляют записи. Фрагменты независимы; Rust `?` предполагает внешнюю функцию с результатом `Result`. В Go panic используется только для фиксированных корректных данных примера; приложение должно обработать возвращённую ошибку. +Примеры относятся к API кандидата 0.9.0, который пока не входит в опубликованные пакеты. Они заменяют только существующие значения: не переименовывают ключи, не создают отсутствующие пути и не удаляют записи. Фрагменты независимы; Rust `?` предполагает внешнюю функцию с результатом `Result`. В Go panic используется только для фиксированных корректных данных примера; приложение должно обработать возвращённую ошибку. Примеры привязок используют самостоятельный pure-бэкенд без native-бинарника. Нативные точки входа принимают те же пути и значения: `ktav.EditValue` (Go), `Ktav.editValue` (Java), `KtavApi.EditValue(..., KtavBackend.Native)` (C#), `Ktav::editValue` (PHP), native/FFI-экспорты пакета (JS), `ktav.edit_value` (Python). C ABI требует версию 2; PyO3/N-API/WASM — совместимое ядро подготовки 0.9. FFI-вызовы Bun/Deno возвращают promise и требуют `await`; показанные pure/Node/WASM-варианты синхронны. @@ -495,7 +495,7 @@ macOS, `$XDG_CACHE_HOME` или `~/.cache` на Linux. Для использования только чистого бэкенда в Gradle отключите транзитивные зависимости: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` В Maven исключите `net.java.dev.jna:jna` и `com.fasterxml.jackson.core:jackson-core`; альтернативно используйте JAR библиотеки напрямую. Для выполнения только чистого бэкенда нужен JDK 17, сторонние runtime-библиотеки не нужны. Успешные и ошибочные пути чистого бэкенда не используют JNA, Jackson, JUnit, нативный код, WASM, процессы, сеть или fallback. Нативному бэкенду нужны его зависимости; для него сохраняйте обычное разрешение зависимостей. @@ -536,7 +536,7 @@ implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } Rust). Поддержка Alpine (musl) — запланирована. -Подготовленная Windows native distribution 0.8.1 использует GNU/LLVM targets +Подготовленная Windows native distribution кандидата 0.9.0 использует GNU/LLVM targets `x86_64-pc-windows-gnullvm` и `aarch64-pc-windows-gnullvm`. Прежние имена assets `windows-amd64` и `windows-arm64` сохраняются как идентификаторы совместимости, а не как указание на компилятор MSVC. diff --git a/docs/zh/CHANGELOG.zh.md b/docs/zh/CHANGELOG.zh.md index 9d7e4d4..faf3723 100644 --- a/docs/zh/CHANGELOG.zh.md +++ b/docs/zh/CHANGELOG.zh.md @@ -10,19 +10,19 @@ MINOR 递增视为破坏性变更。 本 changelog 跟踪 **绑定发布**,不覆盖 Ktav 格式自身的变更 —— 后者见 [`ktav-lang/spec`](https://github.com/ktav-lang/spec/blob/main/CHANGELOG.md)。 -## 尚未发布 — 0.9 准备版本 +## 尚未发布 — 0.9.0 准备 - 新增原生及独立纯实现的路径编辑,支持点分文本或字面路径段:源文本拼接、保留容器形式、最小可读性展开、注释保护、逐字节 no-op 及语义验证。 - 应用 0.9 源诊断及固定的 412 个一致性 fixture,包括 72 个诊断 fixture,检查原始 UTF-8 字节位置及从起始标记到 EOF 的区间。 -- 原生后端使用不可变的 0.9 准备核心及 C ABI 2;纯实现不需要原生二进制。包版本不变,这些功能尚未包含在已发布的 0.8.1 中。 +- 原生后端使用固定到确切 git 修订版的不可变 0.9.0 候选核心及 C ABI 2;纯实现不需要原生二进制。包版本在此候选版本中更新为 0.9.0;尚未发布。 ### 文档 -- 扩展 README 示例:点分路径与字面键、混合数组、String/Integer 区别、多行展开、逐字节 no-op 及 BOM/CRLF/EOF 保留。明确 0.9 字节诊断、安全拒绝、ABI 2 和独立纯实现用法;这些新增功能不属于已发布的 0.8.1。 +- 扩展 README 示例:点分路径与字面键、混合数组、String/Integer 区别、多行展开、逐字节 no-op 及 BOM/CRLF/EOF 保留。明确 0.9 字节诊断、安全拒绝、ABI 2 和独立纯实现用法;这些新增功能属于 0.9.0 候选版本,尚未发布。 -## Unreleased +## Unreleased — 0.9.0 preparation -- 新增纯后端 `insertValue` / `insertValueSegments`、`removeValue` / `removeValueSegments` 和 `renameKey` / `renameKeySegments`,对应原生源文本编辑 API。插入要求已存在的 Object 父节点,删除保留空祖先,重命名保留值和顺序。成功拼接验证预期树,无法安全处理的源形式返回 `EditUnsupported`;插入或重命名冲突返回 `EditAlreadyExists`。这些 API 为 0.9 做准备,包版本不变。 +- 新增纯后端 `insertValue` / `insertValueSegments`、`removeValue` / `removeValueSegments` 和 `renameKey` / `renameKeySegments`,对应原生源文本编辑 API。插入要求已存在的 Object 父节点,删除保留空祖先,重命名保留值和顺序。成功拼接验证预期树,无法安全处理的源形式返回 `EditUnsupported`;插入或重命名冲突返回 `EditAlreadyExists`。这些 API 属于 0.9.0 候选版本;包版本更新为 0.9.0,尚未发布。 ## 0.8.1 — 2026-10-22 diff --git a/docs/zh/README.zh.md b/docs/zh/README.zh.md index c69f700..8c0601c 100644 --- a/docs/zh/README.zh.md +++ b/docs/zh/README.zh.md @@ -28,7 +28,7 @@ repositories { } dependencies { - implementation("io.github.ktav-lang:ktav:0.8.1") + implementation("io.github.ktav-lang:ktav:0.9.0") } ``` @@ -37,7 +37,7 @@ dependencies { 若在 Gradle 中仅使用纯后端,请禁用传递依赖并调用 `PureKtav`: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` 纯后端运行时仅需 JDK 17+。其解析器、写入器、格式化器和 `ErrorEnvelope` 持有对象不使用 Jackson、JNA、JUnit、原生代码、WASM、子进程、网络或回退机制。Maven 纯后端用户需排除 `net.java.dev.jna:jna` 和 `com.fasterxml.jackson.core:jackson-core`。构建、测试和文档工具与运行时相互独立。 @@ -168,7 +168,7 @@ System.out.print(Ktav.format("## the server\nserver: {host: a, port: 80}\n")); 与注释一样都不属于 `Value` 模型,所以规范 writer 会丢弃它们,而 `format` 不会。 -> **尚未发布(0.9 准备版本):** 这些编辑 API 和更新后的诊断不包含在已发布的 0.8.1 包中。原生后端需要固定的 0.9 核心(C-FFI 使用 C ABI 2);纯实现仍完全独立。 +> **尚未发布(0.9 准备版本):** 这些编辑 API 和更新后的诊断属于 0.9.0 候选版本,尚未包含在任何已发布包中。原生后端需要固定的 0.9.0 候选核心(C-FFI 使用 C ABI 2);纯实现仍完全独立。 ### 编辑源文本 @@ -216,7 +216,7 @@ inline。与当前值相等的替换是字节完全一致的 no-op,即使标 ### 源文本编辑示例 -以下示例适用于尚未发布的 0.9 API,而非已发布的 0.8.1 包。只能替换已有值:不会重命名键、创建缺失路径或删除条目。各代码片段相互独立;Rust 的 `?` 假定外层函数返回 `Result`。Go 示例仅针对固定且有效的输入使用 panic;应用程序应处理返回的错误。 +以下示例适用于 0.9.0 候选 API,尚未包含在已发布的包中。只能替换已有值:不会重命名键、创建缺失路径或删除条目。各代码片段相互独立;Rust 的 `?` 假定外层函数返回 `Result`。Go 示例仅针对固定且有效的输入使用 panic;应用程序应处理返回的错误。 绑定示例使用无需原生二进制的独立纯实现。原生入口接收相同的路径和值:Go 的 `ktav.EditValue`、Java 的 `Ktav.editValue`、C# 的 `KtavApi.EditValue(..., KtavBackend.Native)`、PHP 的 `Ktav::editValue`、JS 包的 native/FFI 导出及 Python 的 `ktav.edit_value`。C ABI 后端要求 ABI 2;PyO3/N-API/WASM 要求兼容的 0.9 准备核心。Bun/Deno FFI 返回 promise,需要 `await`;此处 pure/Node/WASM 示例为同步调用。 @@ -470,7 +470,7 @@ writer 的两种拒绝被分开命名 —— 当 writer 能指出是哪个节点 Gradle 纯后端用法可关闭传递依赖: ```kotlin -implementation("io.github.ktav-lang:ktav:0.8.1") { isTransitive = false } +implementation("io.github.ktav-lang:ktav:0.9.0") { isTransitive = false } ``` Maven 请同时排除 `net.java.dev.jna:jna` 和 `com.fasterxml.jackson.core:jackson-core`;也可直接使用本库 JAR。纯后端运行需要 JDK 17,不需要第三方运行时库。纯后端的成功和错误路径均不使用 JNA、Jackson、JUnit、原生代码、WASM、子进程、网络或回退。原生后端用法需要其依赖;请为其保留常规依赖解析。 @@ -502,7 +502,7 @@ Maven 请同时排除 `net.java.dev.jna:jna` 和 `com.fasterxml.jackson.core:jac (musl)支持已规划。 -准备中的 0.8.1 Windows 原生发行包使用 GNU/LLVM 目标 +准备中的 0.9.0 候选 Windows 原生发行包使用 GNU/LLVM 目标 `x86_64-pc-windows-gnullvm` 和 `aarch64-pc-windows-gnullvm`。 现有的 `windows-amd64`、`windows-arm64` 文件名保留为兼容性标识, 并不表示使用 MSVC 编译。这些 DLL 在运行时不需要 Rust/LLVM 构建工具 diff --git a/lib/build.gradle.kts b/lib/build.gradle.kts index 718481d..94f0a46 100644 --- a/lib/build.gradle.kts +++ b/lib/build.gradle.kts @@ -97,7 +97,13 @@ mavenPublishing { ), ) publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL, automaticRelease = true) - signAllPublications() + if (providers.gradleProperty("ktav.candidateInstall").orNull == "true") { + require(gradle.startParameter.taskNames == listOf(":lib:publishToMavenLocal")) { + "ktav.candidateInstall requires only :lib:publishToMavenLocal" + } + } else { + signAllPublications() + } coordinates("io.github.ktav-lang", "ktav", project.version.toString()) pom { name.set("ktav") diff --git a/scripts/stage_java_gnu_release.py b/scripts/stage_java_gnu_release.py index 60c59c5..c447571 100644 --- a/scripts/stage_java_gnu_release.py +++ b/scripts/stage_java_gnu_release.py @@ -8,10 +8,33 @@ import sys SOURCE = 'b252ccfaed66505952ad63a99663e8b6ff530d62' +CANDIDATE_CORE = 'git+https://github.com/ktav-lang/rust?rev=c1d569f60b7f64fe94b5f022082a52c0bcac194e#c1d569f60b7f64fe94b5f022082a52c0bcac194e' TARGETS = {'x86_64-pc-windows-gnullvm': 'ktav_cabi-windows-amd64.dll', 'aarch64-pc-windows-gnullvm': 'ktav_cabi-windows-arm64.dll'} -def stage(evidence, output, target): +def candidate_core_identity(evidence, expected_source_sha): + # Analogous blocker guard: the 0.9.0 candidate is staged only with + # the INDEPENDENTLY expected exact source SHA and the lock-verified + # candidate core identity (no historical bytes, no invented values). + source = json.loads((evidence / 'source-provenance.json').read_bytes()) + if source.get('source_ref') != expected_source_sha: + raise ValueError('candidate staged from an unexpected source') + if source.get('core_git_source') != CANDIDATE_CORE: + raise ValueError('candidate core git provenance differs') + try: + core_lock = json.loads((evidence / 'core-provenance.json').read_bytes()) + except (ValueError, json.JSONDecodeError): + raise ValueError('candidate core lock provenance missing or unreadable') + if core_lock.get('source') != CANDIDATE_CORE or core_lock.get('version') != '0.9.0': + raise ValueError('candidate core lock identity differs') + import tomllib + lock = tomllib.loads((evidence / 'Cargo.lock').read_text()) + cores = [item for item in lock.get('package', []) if item['name'] == 'ktav'] + if len(cores) != 1 or cores[0].get('version') != '0.9.0' or cores[0].get('source') != 'git+https://github.com/ktav-lang/rust?rev=c1d569f60b7f64fe94b5f022082a52c0bcac194e#c1d569f60b7f64fe94b5f022082a52c0bcac194e': + raise ValueError('candidate Cargo.lock core identity differs') + + +def stage(evidence, output, target, expected_source_sha=None): if target not in TARGETS or output.exists(): raise ValueError('reviewed target and new release directory required') binary = evidence / 'ktav_cabi.dll' @@ -21,10 +44,20 @@ def stage(evidence, output, target): runtime = json.loads((evidence / 'native-runtime-verification.json').read_bytes()) source = json.loads((evidence / 'source-provenance.json').read_bytes()) bundle = json.loads((evidence / 'NOTICE.json').read_bytes()) - if source['source_ref'] != SOURCE or source['target'] != target or runtime['target'] != target or runtime['binary_sha256'] != report['binary_sha256']: + candidate = expected_source_sha is not None and expected_source_sha != SOURCE + if candidate: + if expected_source_sha != source['source_ref']: + raise ValueError('candidate staged from an unexpected source') + candidate_core_identity(evidence, expected_source_sha) + else: + if source['source_ref'] != SOURCE: + raise ValueError('source-bound GNU producer identity differs') + if hashlib.sha256((evidence / 'Cargo.lock').read_bytes()).hexdigest() != 'a7066ecc92727ae12c3905cbf1a2b73266da609773356f725e931682381b7a8b': + raise ValueError('reviewed SDK or original Java lock differs') + if source['target'] != target or runtime['target'] != target or runtime['binary_sha256'] != report['binary_sha256']: raise ValueError('source-bound GNU producer identity differs') - if source['sdk_archive_sha256'] != 'fd5462b7f5d93b2ff981fcd3f9c7e427e47f3203c64ea91c27bcc444eebd74cd' or hashlib.sha256((evidence / 'Cargo.lock').read_bytes()).hexdigest() != 'a7066ecc92727ae12c3905cbf1a2b73266da609773356f725e931682381b7a8b': - raise ValueError('reviewed SDK or original Java lock differs') + if source['sdk_archive_sha256'] != 'fd5462b7f5d93b2ff981fcd3f9c7e427e47f3203c64ea91c27bcc444eebd74cd': + raise ValueError('reviewed SDK differs') compiler = bundle['rust_compiler_builtins'] runtimes = bundle['non_cargo_runtimes'] if compiler['profile_sha256'] != '39cbf18420d5e0c0a35fb2d5e5fbed4db755488ea0ca11414944ead9fbabab92' or len(compiler['materials']) != 14 or compiler['compiler_builtins_license'] != 'MIT AND Apache-2.0 WITH LLVM-exception': @@ -42,7 +75,7 @@ def stage(evidence, output, target): asset = output / TARGETS[target] shutil.copyfile(binary, asset) shutil.copyfile(evidence / 'NOTICE.json', output / (asset.name + '.NOTICE.json')) - manifest = {**report, 'binary': asset.name, 'source_ref': SOURCE, 'tooling_ref': source['tooling_ref'], 'target': target, 'sdk_archive_sha256': source['sdk_archive_sha256'], 'coverage': 'GNU native distribution role; original metadata hook only. Complete runtime and compiler grant texts remain embedded and in the adjacent NOTICE.json. No historical asset repair.'} + manifest = {**report, 'binary': asset.name, 'source_ref': source['source_ref'], 'tooling_ref': source['tooling_ref'], 'target': target, 'sdk_archive_sha256': source['sdk_archive_sha256'], 'coverage': 'GNU native distribution role; original metadata hook only. Complete runtime and compiler grant texts remain embedded and in the adjacent NOTICE.json. No historical asset repair.'} (output / (asset.name + '.NOTICE.manifest.json')).write_text(json.dumps(manifest, sort_keys=True, indent=2) + '\n', encoding='utf-8') if asset.read_bytes() != binary.read_bytes(): raise ValueError('staged release DLL differs') @@ -50,6 +83,7 @@ def stage(evidence, output, target): if __name__ == '__main__': - if len(sys.argv) != 4: - raise SystemExit('usage: stage_java_gnu_release.py EVIDENCE NEW_OUTPUT TARGET') - stage(Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3]) + if len(sys.argv) not in (4, 6) or (len(sys.argv) == 6 and sys.argv[4] != '--expected-source'): + raise SystemExit('usage: stage_java_gnu_release.py EVIDENCE NEW_OUTPUT TARGET [--expected-source SHA]') + expected = sys.argv[5] if len(sys.argv) == 6 else None + stage(Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3], expected) From 0ac474be5de9e1858c73df406f7f8d28a3346971 Mon Sep 17 00:00:00 2001 From: Marat K Date: Thu, 3 Dec 2026 10:42:14 +0100 Subject: [PATCH 3/6] Fix installed Java consumer and native source guards Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci.yml | 3 +- .../workflows/windows-gnu-cabi-candidate.yml | 10 ++++-- ci/host-consumer/build.gradle.kts | 33 +++++++++---------- ci/test_native_distribution_contract.py | 12 +++---- settings.gradle.kts | 19 +++++++++++ 5 files changed, 48 insertions(+), 29 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 76c648c..0863496 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -234,7 +234,8 @@ jobs: run: > ./gradlew -p ci/host-consumer verifyResolved run -Dmaven.repo.local="$RUNNER_TEMP/maven-local" - -PinstalledRepo="$RUNNER_TEMP/maven-local" --no-daemon --stacktrace + -PinstalledJarChecksum="$(sha256sum < "$RUNNER_TEMP/maven-local/io/github/ktav-lang/ktav/0.9.0/ktav-0.9.0.jar" | cut -d' ' -f1)" + --no-daemon --stacktrace lint-rust: name: rust clippy + fmt diff --git a/.github/workflows/windows-gnu-cabi-candidate.yml b/.github/workflows/windows-gnu-cabi-candidate.yml index 735fdd1..90bca73 100644 --- a/.github/workflows/windows-gnu-cabi-candidate.yml +++ b/.github/workflows/windows-gnu-cabi-candidate.yml @@ -106,8 +106,14 @@ jobs: protected = ['Cargo.toml', 'crates', 'lib', 'tests', 'root-docs', 'pom.xml'] changed = set(subprocess.check_output(['git', 'diff', '--name-only', '--', *protected], text=True).splitlines()) changed.update(subprocess.check_output(['git', 'ls-files', '--others', '--exclude-standard', '--', *protected], text=True).splitlines()) - if changed != set(overlay): - raise SystemExit('Java candidate changed protected source beyond notice metadata') + # Historical proof: the legacy overlay MUST touch exactly the + # overlay files. Candidate: the hook is already committed, so + # NOTHING inside the protected trees may change. + expected_changed = set(overlay) if historical else set() + if changed != expected_changed: + raise SystemExit( + 'Java candidate changed protected source beyond notice metadata; ' + 'expected=' + sorted(expected_changed).__repr__() + ' actual=' + sorted(changed).__repr__()) if historical: lock = Path('ci/java-windows-gnu.lock').read_bytes() if hashlib.sha256(lock).hexdigest() != 'a7066ecc92727ae12c3905cbf1a2b73266da609773356f725e931682381b7a8b': diff --git a/ci/host-consumer/build.gradle.kts b/ci/host-consumer/build.gradle.kts index 7b0ea67..3daf43f 100644 --- a/ci/host-consumer/build.gradle.kts +++ b/ci/host-consumer/build.gradle.kts @@ -1,3 +1,6 @@ +import java.nio.file.Files +import java.security.MessageDigest + // Host consumer for the installed candidate: resolves the REAL // io.github.ktav-lang:ktav package from the ISOLATED install repo that // the CI job published with publishToMavenLocal (never the repo's own @@ -22,27 +25,21 @@ application { } // Prove the resolved ktav artifact IS the freshly installed 0.9.0 -// candidate jar from the isolated repo: exact version and file located -// inside the repo directory passed via -PinstalledRepo. +// candidate jar: exact version, and byte identity (SHA-256) with the +// jar the install step published, passed independently via +// -PinstalledJarChecksum. No assumption about any repo/cache path. tasks.register("verifyResolved") { doLast { - val installedRepo = providers.gradleProperty("installedRepo").orNull - ?: throw GradleException("pass -PinstalledRepo=") - val repoRoot = java.nio.file.Path.of(installedRepo).toAbsolutePath().normalize() - configurations.named("runtimeClasspath").get() - .resolvedConfiguration.resolvedArtifacts.forEach { artifact -> + val expectedChecksum = providers.gradleProperty("installedJarChecksum").orNull + ?: throw GradleException("pass -PinstalledJarChecksum=") + val candidate = configurations.named("runtimeClasspath").get() + .resolvedConfiguration.resolvedArtifacts.single { artifact -> val id = artifact.moduleVersion.id - println("resolved: " + id + " -> " + artifact.file) - if (id.group == "io.github.ktav-lang" && id.name == "ktav") { - if (id.version != "0.9.0") { - throw GradleException("installed ktav version is not 0.9.0: " + id.version) - } - val file = artifact.file.toPath().toAbsolutePath().normalize() - if (!file.startsWith(repoRoot)) { - throw GradleException( - "resolved ktav artifact is outside the isolated install repo: " + file) - } - } + id.group == "io.github.ktav-lang" && id.name == "ktav" } + require(candidate.moduleVersion.id.version == "0.9.0") + val bytes = Files.readAllBytes(candidate.file.toPath()) + val checksum = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + require(checksum == expectedChecksum) { "Resolved JAR differs from the installed candidate" } } } diff --git a/ci/test_native_distribution_contract.py b/ci/test_native_distribution_contract.py index 645bbff..1518ee0 100644 --- a/ci/test_native_distribution_contract.py +++ b/ci/test_native_distribution_contract.py @@ -57,10 +57,8 @@ def test_literal_pinned_sha_caller_is_rejected(self): def test_missing_head_binding_job_is_rejected(self): self.reject('.github/workflows/native-distribution-check.yml', - ' bind-source: -', - ' bind-source-unused: -', + ' bind-source: ' + chr(10), + ' bind-source-unused: ' + chr(10), 'missing PR head binding job') def test_head_binding_without_rev_parse_is_rejected(self): @@ -71,10 +69,8 @@ def test_head_binding_without_rev_parse_is_rejected(self): def test_binding_job_not_gating_distribution_is_rejected(self): self.reject('.github/workflows/native-distribution-check.yml', - ' needs: bind-source -', - ' needs: [] -', + ' needs: bind-source' + chr(10), + ' needs: []' + chr(10), 'PR head binding job does not gate the distribution') def test_missing_consumer_success_gate_is_rejected(self): diff --git a/settings.gradle.kts b/settings.gradle.kts index 15e70e7..1e61997 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,3 +1,22 @@ +pluginManagement { + repositories { + gradlePluginPortal() + // The foojay-resolver-convention plugin resolves its transitive + // org.gradle.toolchains:foojay-resolver:0.9.0 -> gson dependency + // through the plugin classpath, and plugins.gradle.org does not + // host com.google.code.gson:gson. Serve exactly this artifact + // from official Maven Central; versions are never changed here. + exclusiveContent { + filter { + includeModule("com.google.code.gson", "gson") + } + repository { + mavenCentral() + } + } + } +} + plugins { id("org.gradle.toolchains.foojay-resolver-convention") version "0.9.0" } From 22327adcc02de0b75d2f98c2439f9e56a564f1c4 Mon Sep 17 00:00:00 2001 From: Marat K Date: Thu, 3 Dec 2026 10:43:31 +0100 Subject: [PATCH 4/6] Use the Gradle repository factory and exact YAML anchor Co-Authored-By: Claude Fable 5.2 --- ci/test_native_distribution_contract.py | 4 ++-- settings.gradle.kts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ci/test_native_distribution_contract.py b/ci/test_native_distribution_contract.py index 1518ee0..2eb434e 100644 --- a/ci/test_native_distribution_contract.py +++ b/ci/test_native_distribution_contract.py @@ -57,8 +57,8 @@ def test_literal_pinned_sha_caller_is_rejected(self): def test_missing_head_binding_job_is_rejected(self): self.reject('.github/workflows/native-distribution-check.yml', - ' bind-source: ' + chr(10), - ' bind-source-unused: ' + chr(10), + ' bind-source:\n', + ' bind-source-unused:\n', 'missing PR head binding job') def test_head_binding_without_rev_parse_is_rejected(self): diff --git a/settings.gradle.kts b/settings.gradle.kts index 1e61997..875e6a7 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -10,7 +10,7 @@ pluginManagement { filter { includeModule("com.google.code.gson", "gson") } - repository { + forRepository { mavenCentral() } } From 09b95fe0e340414bde587876dce23ba9cba564db Mon Sep 17 00:00:00 2001 From: Marat K Date: Thu, 3 Dec 2026 11:01:50 +0100 Subject: [PATCH 5/6] Require one verified lock for both Java Windows targets Keep the historical lock separate and fail if the candidate lock is missing. Preserve the settings checksum and reject missing PR source binding. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci.yml | 79 +++++++++++++--- .github/workflows/licenses.yml | 2 +- .../workflows/windows-gnu-cabi-candidate.yml | 92 +++++++++++++++++-- ci/check_native_distribution.rb | 3 +- ci/test_cabi_gnullvm_notices.py | 14 ++- scripts/cabi_gnullvm_notices.py | 9 +- scripts/stage_java_gnu_release.py | 2 + 7 files changed, 174 insertions(+), 27 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0863496..c49ef01 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -196,10 +196,29 @@ jobs: java-version: "17" - uses: gradle/actions/setup-gradle@v4 - name: Install the candidate package into an isolated maven repo - run: > - ./gradlew :lib:publishToMavenLocal - -Dmaven.repo.local="$RUNNER_TEMP/maven-local" - -Pktav.candidateInstall=true --no-daemon --stacktrace + run: | + set -euo pipefail + # ONLY download errors (Maven Central HTTP 429) are retried + # with growing backoff; any other failure (tests, signing, + # assertions) fails immediately. The rate limit is respected: + # versions and signing policy are untouched. + attempt=1 + while true; do + if ./gradlew :lib:publishToMavenLocal \ + -Dmaven.repo.local="$RUNNER_TEMP/maven-local" \ + -Pktav.candidateInstall=true --no-daemon --stacktrace \ + 2>&1 | tee "$RUNNER_TEMP/install-attempt.log"; then + exit 0 + fi + grep -Eq "Received status code 429|Too Many Requests" "$RUNNER_TEMP/install-attempt.log" \ + || { echo 'non-download Gradle failure is not retried' >&2; exit 1; } + if [ "$attempt" -ge 4 ]; then + echo 'download still rate limited after retries' >&2 + exit 1 + fi + sleep $((attempt * 20)) + attempt=$((attempt + 1)) + done - name: Installed 0.9.0 artifact is exactly the built jar run: | set -euo pipefail @@ -231,11 +250,28 @@ jobs: test "$(sha256sum < "$jar" | cut -d' ' -f1)" = "$(sha256sum < lib/build/libs/ktav-0.9.0.jar | cut -d' ' -f1)" echo "installed jar is byte-identical to the built candidate jar" - name: Host consumer resolves and runs the installed package via the project wrapper - run: > - ./gradlew -p ci/host-consumer verifyResolved run - -Dmaven.repo.local="$RUNNER_TEMP/maven-local" - -PinstalledJarChecksum="$(sha256sum < "$RUNNER_TEMP/maven-local/io/github/ktav-lang/ktav/0.9.0/ktav-0.9.0.jar" | cut -d' ' -f1)" - --no-daemon --stacktrace + run: | + set -euo pipefail + checksum="$(sha256sum < "$RUNNER_TEMP/maven-local/io/github/ktav-lang/ktav/0.9.0/ktav-0.9.0.jar" | cut -d' ' -f1)" + # Same download-only 429 backoff as the install step above; + # consumer assertion failures are never retried. + attempt=1 + while true; do + if ./gradlew -p ci/host-consumer verifyResolved run \ + -Dmaven.repo.local="$RUNNER_TEMP/maven-local" \ + -PinstalledJarChecksum="$checksum" --no-daemon --stacktrace \ + 2>&1 | tee "$RUNNER_TEMP/consumer-attempt.log"; then + exit 0 + fi + grep -Eq "Received status code 429|Too Many Requests" "$RUNNER_TEMP/consumer-attempt.log" \ + || { echo 'non-download Gradle failure is not retried' >&2; exit 1; } + if [ "$attempt" -ge 4 ]; then + echo 'download still rate limited after retries' >&2 + exit 1 + fi + sleep $((attempt * 20)) + attempt=$((attempt + 1)) + done lint-rust: name: rust clippy + fmt @@ -427,12 +463,31 @@ jobs: rustc --version cargo --version java -version - for round in 1 2 3 4 5; do + bench_gradle() { + local side="$1" attempt=1 log + # ONLY download errors (HTTP 429) are retried; benchmark + # assertion failures fail immediately. + log="$(mktemp)" + while true; do + if JAVA_TOOL_OPTIONS='-Dktav.bench.repeats=1' KTAV_LIB_PATH="$GITHUB_WORKSPACE/$side/target/release/libktav_cabi.so" \ + ./"$side"/gradlew -p "$side" :lib:sourceEditBenchmark --no-daemon --stacktrace \ + 2>&1 | tee "$log"; then + return 0 + fi + grep -Eq "Received status code 429|Too Many Requests" "$log" || return 1 + if [ "$attempt" -ge 4 ]; then + echo 'download still rate limited after retries' >&2 + return 1 + fi + sleep $((attempt * 20)) + attempt=$((attempt + 1)) + done + } + for round in 1 2 3 4 5; do if (( round % 2 == 1 )); then first=baseline; second=candidate; else first=candidate; second=baseline; fi for side in "$first" "$second"; do echo "===== round=${round} side=${side} =====" - JAVA_TOOL_OPTIONS='-Dktav.bench.repeats=1' KTAV_LIB_PATH="$GITHUB_WORKSPACE/$side/target/release/libktav_cabi.so" \ - ./"$side"/gradlew -p "$side" :lib:sourceEditBenchmark --no-daemon --stacktrace + bench_gradle "$side" done done } 2>&1 | tee source-edit-benchmark.log diff --git a/.github/workflows/licenses.yml b/.github/workflows/licenses.yml index 772bb05..85f3e0c 100644 --- a/.github/workflows/licenses.yml +++ b/.github/workflows/licenses.yml @@ -126,7 +126,7 @@ jobs: - name: Verify settings plugin and reviewed source license run: | set -euo pipefail - printf '%s %s\n' 25feb033cedd1d724cdbe0dce5e8148f4734518e1db325b1b3c8b95ade92ef90 settings.gradle.kts | sha256sum --check + printf '%s %s\n' 2df4888531d1a0b8de77d556582d2e6933d160356b84b992b02e75ab8d718480 settings.gradle.kts | sha256sum --check curl -fsSL https://plugins.gradle.org/m2/org/gradle/toolchains/foojay-resolver-convention/org.gradle.toolchains.foojay-resolver-convention.gradle.plugin/0.9.0/org.gradle.toolchains.foojay-resolver-convention.gradle.plugin-0.9.0.pom > "$RUNNER_TEMP/foojay-marker.pom" printf '%s %s\n' db7cf11bee6884efb28904139f62c00f8b45853e60c0f41715cf69576b6bfdf0 "$RUNNER_TEMP/foojay-marker.pom" | sha256sum --check curl -fsSL https://raw.githubusercontent.com/gradle/foojay-toolchains/f4575ddf844fcfd4ad9e758d2040cfd50b59f173/LICENSE > "$RUNNER_TEMP/foojay-LICENSE" diff --git a/.github/workflows/windows-gnu-cabi-candidate.yml b/.github/workflows/windows-gnu-cabi-candidate.yml index 90bca73..bffead7 100644 --- a/.github/workflows/windows-gnu-cabi-candidate.yml +++ b/.github/workflows/windows-gnu-cabi-candidate.yml @@ -16,7 +16,56 @@ env: SOURCE_REF: ${{ inputs.source-ref || 'b252ccfaed66505952ad63a99663e8b6ff530d62' }} jobs: + lock-bootstrap: + name: bootstrap single candidate Cargo.lock + if: inputs.source-ref != '' && inputs.source-ref != 'b252ccfaed66505952ad63a99663e8b6ff530d62' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.source-ref }} + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + - name: Generate and verify the single candidate lock + run: | + set -euo pipefail + grep -F 'rev = "c1d569f60b7f64fe94b5f022082a52c0bcac194e"' Cargo.toml \ + || { echo 'workspace does not pin the reviewed core revision' >&2; exit 1; } + test "$(git rev-parse HEAD)" = "$SOURCE_REF" + cargo generate-lockfile + python3 - <<'PY' + import hashlib + import json + import pathlib + import tomllib + core = [item for item in tomllib.loads(pathlib.Path('Cargo.lock').read_text())['package'] if item['name'] == 'ktav'] + expected = { + 'version': '0.9.0', + 'source': 'git+https://github.com/ktav-lang/rust?rev=c1d569f60b7f64fe94b5f022082a52c0bcac194e#c1d569f60b7f64fe94b5f022082a52c0bcac194e', + } + if len(core) != 1: + raise SystemExit('expected exactly one ktav core') + for field, value in expected.items(): + if core[0].get(field) != value: + raise SystemExit(f'ktav {field} mismatch: {core[0].get(field)!r}') + lock_sha256 = hashlib.sha256(pathlib.Path('Cargo.lock').read_bytes()).hexdigest() + pathlib.Path('core-provenance.json').write_text(json.dumps( + {'source': expected['source'], 'version': expected['version'], 'lock_sha256': lock_sha256}, + sort_keys=True) + '\n', encoding='utf-8') + print('single candidate lock verified; lock ' + lock_sha256) + PY + - uses: actions/upload-artifact@v4 + with: + name: candidate-cargo-lock + path: | + Cargo.lock + core-provenance.json + if-no-files-found: error + retention-days: 7 + cabi-gnullvm: + needs: lock-bootstrap + if: ${{ !cancelled() && (needs.lock-bootstrap.result == 'success' || needs.lock-bootstrap.result == 'skipped') }} name: Java GNU C ABI / ${{ matrix.target }} runs-on: windows-latest timeout-minutes: 45 @@ -141,9 +190,16 @@ jobs: import sys for pattern in ['test_embedded_notices.py', 'test_rust_compiler_notices.py', 'test_cabi_gnullvm_notices.py']: subprocess.run([sys.executable, '-I', '-m', 'unittest', 'discover', '-s', 'ci', '-p', pattern, '-v'], check=True) + - name: Fetch the single bootstrapped candidate lock (PR runs) + if: env.SOURCE_REF != 'b252ccfaed66505952ad63a99663e8b6ff530d62' + uses: actions/download-artifact@v4 + with: + name: candidate-cargo-lock + path: ${{ runner.temp }}/candidate-lock - name: Prepare locked Java Cargo compiler and runtime grants shell: python run: | + import hashlib import json import os import shutil @@ -151,16 +207,29 @@ jobs: import sys import tomllib from pathlib import Path - core = [item for item in tomllib.loads(Path('Cargo.lock').read_text())['package'] if item['name'] == 'ktav'] - if len(core) != 1: - raise SystemExit('expected exactly one ktav core') + # The lock bytes must EXIST and be verified before the first + # read: historical binds the reviewed lock bytes in the bind + # step; the candidate GENERATES the lock from the pinned git + # core here. Both CPU matrix targets build against the SAME + # generated lock, whose sha256 is recorded in the evidence + # provenance (no invented hashes). if os.environ['SOURCE_REF'] == 'b252ccfaed66505952ad63a99663e8b6ff530d62': + if not Path('Cargo.lock').is_file(): + raise SystemExit('historical reviewed lock missing before verification') + core = [item for item in tomllib.loads(Path('Cargo.lock').read_text())['package'] if item['name'] == 'ktav'] + if len(core) != 1: + raise SystemExit('expected exactly one ktav core') if core[0]['version'] != '0.8.1' or core[0]['checksum'] != '7140dfe2fa6c320e74768cd6a637828c2d26f81746254f4fcd805f3993bd3fd5': raise SystemExit('original registry core identity differs') else: if 'rev = "c1d569f60b7f64fe94b5f022082a52c0bcac194e"' not in Path('Cargo.toml').read_text(): raise SystemExit('workspace does not pin the reviewed core revision') - subprocess.run(['cargo', 'generate-lockfile'], check=True) + lock_dir = Path(os.environ['RUNNER_TEMP']) / 'candidate-lock' + provenance_record = json.loads((lock_dir / 'core-provenance.json').read_bytes()) + lock = (lock_dir / 'Cargo.lock').read_bytes() + if provenance_record['lock_sha256'] != hashlib.sha256(lock).hexdigest(): + raise SystemExit('bootstrapped Cargo.lock differs from its recorded provenance') + Path('Cargo.lock').write_bytes(lock) core = [item for item in tomllib.loads(Path('Cargo.lock').read_text())['package'] if item['name'] == 'ktav'] if len(core) != 1: raise SystemExit('expected exactly one ktav core') @@ -168,12 +237,19 @@ jobs: for field, value in expected.items(): if core[0].get(field) != value: raise SystemExit(f'candidate core git provenance differs: {field}={core[0].get(field)!r}') - evidence = Path(os.environ['RUNNER_TEMP']) / 'cabi-gnullvm-evidence' - evidence.mkdir(parents=True, exist_ok=True) - (evidence / 'core-provenance.json').write_text(json.dumps({'source': expected['source'], 'version': expected['version']}, sort_keys=True) + '\n', encoding='utf-8') - print('candidate ktav 0.9.0 core resolved from the exact pinned git revision') + candidate_lock_sha256 = hashlib.sha256(Path('Cargo.lock').read_bytes()).hexdigest() evidence = Path(os.environ['RUNNER_TEMP']) / 'cabi-gnullvm-evidence' subprocess.run([sys.executable, 'scripts/prepare_cabi_notices.py', str(evidence)], check=True) + if os.environ['SOURCE_REF'] != 'b252ccfaed66505952ad63a99663e8b6ff530d62': + # prepare_cabi_notices copies the verified root Cargo.lock + # into the evidence; bind it and the provenance record here, + # after prepare, so nothing rewrites them. + if Path('Cargo.lock').read_bytes() != (evidence / 'Cargo.lock').read_bytes(): + raise SystemExit('prepared evidence lock differs from the verified candidate lock') + provenance_record = provenance_record or {'source': expected['source'], 'version': expected['version'], 'lock_sha256': candidate_lock_sha256} + if provenance_record['lock_sha256'] != candidate_lock_sha256: + raise SystemExit('candidate provenance lock sha differs from the verified lock') + (evidence / 'core-provenance.json').write_text(json.dumps(provenance_record, sort_keys=True) + '\n', encoding='utf-8') for name in ['LICENSE-MIT', 'LICENSE-APACHE']: shutil.copyfile(name, evidence / name) profile = json.loads(Path('ci/rust-compiler-notices.json').read_bytes()) diff --git a/ci/check_native_distribution.rb b/ci/check_native_distribution.rb index aa64a06..a634669 100644 --- a/ci/check_native_distribution.rb +++ b/ci/check_native_distribution.rb @@ -45,7 +45,8 @@ # The candidate source is the EXACT PR head commit (never the synthetic # merge commit), bound by a checkout + rev-parse guard job. abort 'native CI source is not the exact PR head' unless caller.fetch('with').fetch('source-ref') == '${{ github.event.pull_request.head.sha }}' -binder = caller_file.fetch('jobs').fetch('bind-source') +binder = caller_file.fetch('jobs').fetch('bind-source', nil) +abort 'missing PR head binding job' unless binder.is_a?(Hash) abort 'missing PR head binding job' unless !binder.key?('needs') && binder.fetch('steps').any? { |step| step['run'].to_s.include?('git rev-parse HEAD') } abort 'PR head binding guard compares the wrong reference' unless caller_file.to_s.include?('${{ github.event.pull_request.head.sha }}') && binder.fetch('steps').any? { |step| step['run'].to_s.include?('github.event.pull_request.head.sha') } abort 'PR head binding job does not gate the distribution' unless caller.fetch('needs').to_s == 'bind-source' diff --git a/ci/test_cabi_gnullvm_notices.py b/ci/test_cabi_gnullvm_notices.py index b44d0ea..3cf9546 100644 --- a/ci/test_cabi_gnullvm_notices.py +++ b/ci/test_cabi_gnullvm_notices.py @@ -63,9 +63,15 @@ def provenance(self, evidence, **fields): (evidence / 'source-provenance.json').write_text( __import__('json').dumps(record), encoding='utf-8') - def candidate_core_lock(self, evidence, source=MODULE.CANDIDATE_CORE, version='0.9.0'): + def candidate_core_lock(self, evidence, source=MODULE.CANDIDATE_CORE, version='0.9.0', + lock_sha256=None): + import hashlib + lock_bytes = b'cargo lock fixture bytes\n' + recorded = lock_sha256 or hashlib.sha256(lock_bytes).hexdigest() + evidence.joinpath('Cargo.lock').write_bytes(lock_bytes) evidence.joinpath('core-provenance.json').write_text( - __import__('json').dumps({'source': source, 'version': version}, sort_keys=True), + __import__('json').dumps({'source': source, 'version': version, + 'lock_sha256': recorded}, sort_keys=True), encoding='utf-8') def test_historical_binding_accepts_only_exact_legacy_source(self): @@ -111,6 +117,10 @@ def test_candidate_rejects_unverified_or_drifting_lock_identity(self): __import__('json').loads((evidence / 'source-provenance.json').read_text()), evidence, declared)) self.candidate_core_lock(evidence, version='0.8.1') + self.assertFalse(MODULE.source_binding( + __import__('json').loads((evidence / 'source-provenance.json').read_text()), + evidence, declared)) + self.candidate_core_lock(evidence, lock_sha256='0' * 64) self.assertFalse(MODULE.source_binding( __import__('json').loads((evidence / 'source-provenance.json').read_text()), evidence, declared)) diff --git a/scripts/cabi_gnullvm_notices.py b/scripts/cabi_gnullvm_notices.py index e0eba85..2a1dc93 100644 --- a/scripts/cabi_gnullvm_notices.py +++ b/scripts/cabi_gnullvm_notices.py @@ -182,9 +182,12 @@ def source_binding(provenance, evidence, expected_source_sha): core_lock = json.loads(read(evidence / 'core-provenance.json', MAX_FILE)) except (ValueError, json.JSONDecodeError): return False - return (provenance.get('core_git_source') == CANDIDATE_CORE - and core_lock.get('source') == CANDIDATE_CORE - and core_lock.get('version') == '0.9.0') + if core_lock.get('source') != CANDIDATE_CORE or core_lock.get('version') != '0.9.0': + return False + recorded_lock = core_lock.get('lock_sha256') + if not isinstance(recorded_lock, str): + return False + return recorded_lock == hashlib.sha256(read(evidence / 'Cargo.lock', MAX_FILE)).hexdigest() def verify_inputs(items, mapping, document, target): diff --git a/scripts/stage_java_gnu_release.py b/scripts/stage_java_gnu_release.py index c447571..0da310a 100644 --- a/scripts/stage_java_gnu_release.py +++ b/scripts/stage_java_gnu_release.py @@ -27,6 +27,8 @@ def candidate_core_identity(evidence, expected_source_sha): raise ValueError('candidate core lock provenance missing or unreadable') if core_lock.get('source') != CANDIDATE_CORE or core_lock.get('version') != '0.9.0': raise ValueError('candidate core lock identity differs') + if core_lock.get('lock_sha256') != hashlib.sha256((evidence / 'Cargo.lock').read_bytes()).hexdigest(): + raise ValueError('candidate staged against a different Cargo.lock') import tomllib lock = tomllib.loads((evidence / 'Cargo.lock').read_text()) cores = [item for item in lock.get('package', []) if item['name'] == 'ktav'] From 5591a8cc089a870d839d98d208655b01cdbce552 Mon Sep 17 00:00:00 2001 From: Marat K Date: Thu, 3 Dec 2026 11:24:54 +0100 Subject: [PATCH 6/6] Verify ABI 2 exports and stage native Java consumer input Keep the benchmark baseline unchanged. Limit the settings repository filter to Gson without excluding the license inventory repositories. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci.yml | 7 ++++++- .github/workflows/licenses.yml | 2 +- .../workflows/windows-gnu-cabi-candidate.yml | 17 ++++++++++++++--- ci/host-consumer/build.gradle.kts | 15 +++++++++++++++ settings.gradle.kts | 10 +++++----- 5 files changed, 41 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c49ef01..b14a24c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -190,11 +190,15 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 - uses: actions/setup-java@v4 with: distribution: temurin java-version: "17" - uses: gradle/actions/setup-gradle@v4 + - name: Stage this PR's native artifact for the consumer + run: cargo build --release -p ktav-cabi - name: Install the candidate package into an isolated maven repo run: | set -euo pipefail @@ -259,7 +263,8 @@ jobs: while true; do if ./gradlew -p ci/host-consumer verifyResolved run \ -Dmaven.repo.local="$RUNNER_TEMP/maven-local" \ - -PinstalledJarChecksum="$checksum" --no-daemon --stacktrace \ + -PinstalledJarChecksum="$checksum" \ + -PktavNativeLib="$GITHUB_WORKSPACE/target/release/libktav_cabi.so" --no-daemon --stacktrace \ 2>&1 | tee "$RUNNER_TEMP/consumer-attempt.log"; then exit 0 fi diff --git a/.github/workflows/licenses.yml b/.github/workflows/licenses.yml index 85f3e0c..45cbd95 100644 --- a/.github/workflows/licenses.yml +++ b/.github/workflows/licenses.yml @@ -126,7 +126,7 @@ jobs: - name: Verify settings plugin and reviewed source license run: | set -euo pipefail - printf '%s %s\n' 2df4888531d1a0b8de77d556582d2e6933d160356b84b992b02e75ab8d718480 settings.gradle.kts | sha256sum --check + printf '%s %s\n' 4a2014dc8c905824163ebc3fd396d24b9fbdf33bf30d050e79f8643a3432ae20 settings.gradle.kts | sha256sum --check curl -fsSL https://plugins.gradle.org/m2/org/gradle/toolchains/foojay-resolver-convention/org.gradle.toolchains.foojay-resolver-convention.gradle.plugin/0.9.0/org.gradle.toolchains.foojay-resolver-convention.gradle.plugin-0.9.0.pom > "$RUNNER_TEMP/foojay-marker.pom" printf '%s %s\n' db7cf11bee6884efb28904139f62c00f8b45853e60c0f41715cf69576b6bfdf0 "$RUNNER_TEMP/foojay-marker.pom" | sha256sum --check curl -fsSL https://raw.githubusercontent.com/gradle/foojay-toolchains/f4575ddf844fcfd4ad9e758d2040cfd50b59f173/LICENSE > "$RUNNER_TEMP/foojay-LICENSE" diff --git a/.github/workflows/windows-gnu-cabi-candidate.yml b/.github/workflows/windows-gnu-cabi-candidate.yml index bffead7..b9f0709 100644 --- a/.github/workflows/windows-gnu-cabi-candidate.yml +++ b/.github/workflows/windows-gnu-cabi-candidate.yml @@ -351,9 +351,20 @@ jobs: if not imports or not all(os_import(name) for name in imports): raise SystemExit('C ABI candidate imports a non-OS runtime DLL: ' + repr(imports)) exports = re.findall(rb'^\s*Name: (ktav_[^\r\n]+)\s*$', pe, re.M) - expected_exports = {b'ktav_loads', b'ktav_loads_strict', b'ktav_dumps', b'ktav_dumps_force_strings', b'ktav_emit_canonical', b'ktav_format', b'ktav_canonical_from_source', b'ktav_free', b'ktav_version', b'ktav_abi_version'} - if len(exports) != 10 or set(exports) != expected_exports: - raise SystemExit('original callable C ABI export set differs') + # Exact equality per branch: the historical 0.8.1 proof keeps + # the ten ABI-1 exports; the 0.9.0 candidate MUST export all + # eighteen ABI-2 symbols (the original ten plus the eight + # source-edit symbols). Negative control: a candidate DLL with + # exactly the legacy ABI-1 set is rejected too. + expected_exports_abi1 = {b'ktav_loads', b'ktav_loads_strict', b'ktav_dumps', b'ktav_dumps_force_strings', b'ktav_emit_canonical', b'ktav_format', b'ktav_canonical_from_source', b'ktav_free', b'ktav_version', b'ktav_abi_version'} + expected_exports_abi2 = expected_exports_abi1 | {b'ktav_edit_value', b'ktav_edit_value_segments', b'ktav_insert_value', b'ktav_insert_value_segments', b'ktav_remove_value', b'ktav_remove_value_segments', b'ktav_rename_key', b'ktav_rename_key_segments'} + actual_exports = set(exports) + if os.environ['SOURCE_REF'] == 'b252ccfaed66505952ad63a99663e8b6ff530d62': + if len(exports) != 10 or actual_exports != expected_exports_abi1: + raise SystemExit('original callable C ABI export set differs; expected=' + sorted(expected_exports_abi1).__repr__() + ' actual=' + sorted(actual_exports).__repr__()) + else: + if len(exports) != 18 or actual_exports != expected_exports_abi2: + raise SystemExit('candidate callable C ABI export set differs from ABI 2; expected=' + sorted(expected_exports_abi2).__repr__() + ' actual=' + sorted(actual_exports).__repr__()) if len(re.findall(rb'^\s*Name: KTAV_THIRD_PARTY_NOTICES\s*$', pe, re.M)) != 1: raise SystemExit('C ABI notice static export missing') link_map = evidence / 'native-link.map' diff --git a/ci/host-consumer/build.gradle.kts b/ci/host-consumer/build.gradle.kts index 3daf43f..13987f3 100644 --- a/ci/host-consumer/build.gradle.kts +++ b/ci/host-consumer/build.gradle.kts @@ -24,6 +24,21 @@ application { mainClass.set("consumer.Smoke") } +// Strict binding to the explicitly staged native artifact of the same +// PR: every JavaExec (run) gets KTAV_LIB_PATH pointed at that exact +// file, so the candidate NEVER falls back to downloading a release +// native that does not exist yet. No property, no run. +val stagedNative = providers.gradleProperty("ktavNativeLib").orNull + ?: throw GradleException("pass -PktavNativeLib=") +val stagedNativeFile = file(stagedNative) +if (!stagedNativeFile.isFile) { + throw GradleException("staged native artifact is missing: " + stagedNativeFile) +} + +tasks.withType().configureEach { + environment("KTAV_LIB_PATH", stagedNativeFile.absolutePath) +} + // Prove the resolved ktav artifact IS the freshly installed 0.9.0 // candidate jar: exact version, and byte identity (SHA-256) with the // jar the install step published, passed independently via diff --git a/settings.gradle.kts b/settings.gradle.kts index 875e6a7..a2ee6dc 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -6,13 +6,13 @@ pluginManagement { // through the plugin classpath, and plugins.gradle.org does not // host com.google.code.gson:gson. Serve exactly this artifact // from official Maven Central; versions are never changed here. - exclusiveContent { - filter { + // A plain content-filtered repository (NOT exclusiveContent): + // the license init script must stay able to add buildscript + // repositories for the plugin inventory. + mavenCentral { + content { includeModule("com.google.code.gson", "gson") } - forRepository { - mavenCentral() - } } } }