From 8003423a1ff54e518d67be58dfc70380e94c8b92 Mon Sep 17 00:00:00 2001
From: appergb <192432815+appergb@users.noreply.github.com>
Date: Fri, 27 Nov 2026 21:00:19 +0800
Subject: [PATCH 1/8] test(styles): assert injected credentials stay out of
comparison reports
---
openless-all/app/scripts/intent-style-comparison.test.mjs | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/openless-all/app/scripts/intent-style-comparison.test.mjs b/openless-all/app/scripts/intent-style-comparison.test.mjs
index 3c7ad3e0a..ce6a5379a 100644
--- a/openless-all/app/scripts/intent-style-comparison.test.mjs
+++ b/openless-all/app/scripts/intent-style-comparison.test.mjs
@@ -15,7 +15,9 @@ const rendered = renderComparison(report);
assert.ok(rendered.includes('<old> | before
second'));
assert.ok(rendered.includes('Source: 源文
after'));
assert.ok(rendered.includes('12 ms'));
-assert.ok(!rendered.includes('must-never-render'));
+assert.ok(!rendered.includes(report.credentials['ark.api_key']));
+assert.ok(!rendered.includes('credentials'));
+assert.ok(!rendered.includes('ark.api_key'));
report.cases[0].old = { errorCode: 'Provider' };
assert.ok(renderComparison(report).includes('Request failed: Provider'));
assert.throws(() => renderComparison({ schemaVersion: 2, cases: [] }));
From c5518fce6f2b825f2693f21754db348aa8479cfa Mon Sep 17 00:00:00 2001
From: appergb <192432815+appergb@users.noreply.github.com>
Date: Fri, 27 Nov 2026 21:11:46 +0800
Subject: [PATCH 2/8] ci(styles): add trusted opt-in intent comparison status
run
---
.github/workflows/ci.yml | 49 ++++-
docs/intent-style-evaluation.md | 33 +++
.../app/scripts/intent-style-comparison-ci.py | 194 ++++++++++++++++++
.../test_intent_style_comparison_ci.py | 164 +++++++++++++++
4 files changed, 436 insertions(+), 4 deletions(-)
create mode 100644 openless-all/app/scripts/intent-style-comparison-ci.py
create mode 100644 openless-all/app/scripts/test_intent_style_comparison_ci.py
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 589afff5b..586268132 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -22,7 +22,7 @@ on:
live_acceptance:
description: Paid official-provider acceptance only (skips ordinary platform checks)
type: choice
- options: ['off', style, style-diagnostic, search]
+ options: ['off', style, style-diagnostic, search, intent-style-comparison]
default: 'off'
platform:
description: Platforms to check (macos runs only macOS gates)
@@ -1284,9 +1284,15 @@ jobs:
live-acceptance:
name: Optional official-provider live acceptance
- if: github.event_name == 'workflow_dispatch' && inputs.live_acceptance != 'off'
+ if: >-
+ github.event_name == 'workflow_dispatch' &&
+ inputs.live_acceptance != 'off' &&
+ github.repository == 'Open-Less/openless' &&
+ contains(fromJSON('["refs/heads/main","refs/heads/beta"]'), github.ref)
runs-on: ubuntu-latest
timeout-minutes: 20
+ env:
+ CARGO_TARGET_DIR: ${{ runner.temp }}/openless-live-target
permissions:
contents: read
defaults:
@@ -1294,10 +1300,20 @@ jobs:
working-directory: openless-all/app
steps:
- uses: actions/checkout@v4
+ with:
+ persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
- name: Build acceptance without credentials
- run: cargo test --locked -p openless-core --lib --no-run
+ id: live-build
+ run: |
+ set -euo pipefail
+ umask 077
+ build_manifest=$(mktemp "$RUNNER_TEMP/openless-live-build.XXXXXX")
+ trap 'rm -f "$build_manifest"' EXIT
+ cargo test --locked -p openless-core --lib -j 1 --no-run --message-format=json > "$build_manifest"
+ python3 scripts/intent-style-comparison-ci.py select-binary "$build_manifest" >> "$GITHUB_OUTPUT"
- name: Run explicitly selected bounded acceptance
+ if: inputs.live_acceptance != 'intent-style-comparison'
env:
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
LIVE_ACCEPTANCE: ${{ inputs.live_acceptance }}
@@ -1311,10 +1327,35 @@ jobs:
esac
cargo test --locked -p openless-core --lib "$target" -- --list --ignored | grep -q "$target: test"
cargo test --locked -p openless-core --lib "$target" -- --ignored --nocapture --test-threads=1 | tee live-acceptance.log
+ - name: Compare intent 1.3.0 and 1.4.0 with existing official credentials
+ if: inputs.live_acceptance == 'intent-style-comparison'
+ env:
+ DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
+ INTENT_TEST_BINARY: ${{ steps.live-build.outputs.binary }}
+ run: |
+ set -euo pipefail
+ umask 077
+ private_dir=$(mktemp -d "$RUNNER_TEMP/openless-intent.XXXXXX")
+ chmod 700 "$private_dir"
+ trap 'rm -rf "$private_dir"' EXIT
+ python3 scripts/intent-style-comparison-ci.py run \
+ "$INTENT_TEST_BINARY" "$private_dir" "$RUNNER_TEMP/openless-intent-evidence"
- name: Preserve public output evidence
- if: always()
+ if: always() && inputs.live_acceptance != 'intent-style-comparison'
uses: actions/upload-artifact@v4
with:
name: official-provider-live-acceptance
path: openless-all/app/live-acceptance.log
if-no-files-found: ignore
+ - name: Preserve only safe intent execution status
+ if: always() && inputs.live_acceptance == 'intent-style-comparison'
+ uses: actions/upload-artifact@v4
+ with:
+ name: intent-style-comparison-status
+ path: ${{ runner.temp }}/openless-intent-evidence/status.json
+ if-no-files-found: ignore
+ retention-days: 7
+ - name: Clean dedicated live acceptance artifacts
+ if: always()
+ run: |
+ rm -rf "$RUNNER_TEMP/openless-live-target" "$RUNNER_TEMP/openless-intent-evidence"
diff --git a/docs/intent-style-evaluation.md b/docs/intent-style-evaluation.md
index ae3c36a0c..7af2f24f0 100644
--- a/docs/intent-style-evaluation.md
+++ b/docs/intent-style-evaluation.md
@@ -66,6 +66,39 @@ OAuth 渠道或不希望复制凭据时,在风格设置建立两个临时自
逐条检查信息是否遗漏、撤销是否生效、是否重复归组、层级与编号是否合理、专名数字是否保留、是否新增要求或代答。给每条记录通过 / 不通过和具体偏差;失败后可以修改提示词,但不能覆盖已有对照证据。最终效果由用户判断。渠道是否返回缓存读取和推理用量,仍须通过应用的用量账本另行检查;该并排记录不代替缓存或计费测量。
+## 使用既有 Actions secret 的手动状态对照
+
+仓库已有的 `Optional official-provider live acceptance` 增加了非默认选项
+`intent-style-comparison`。仅限 `Open-Less/openless` 仓库的 `main` / `beta`
+分支手动运行;fork、PR、tag 和其他分支不进入带 secret 的 job。默认仍为 `off`,
+普通 CI 不会调用模型。协调者先将本改动接入经审查的集成版本,核对分支 SHA 后可执行一次:
+
+```sh
+gh workflow run ci.yml --repo Open-Less/openless --ref beta \
+ -f live_acceptance=intent-style-comparison
+```
+
+这是未自动执行的真实付费调用命令;沿用调用前授权,不能重复运行消耗预算。
+它只使用现存 `DEEPSEEK_API_KEY` secret,不读取或搬运本机配置;渠道固定为官方 DeepSeek,
+模型与现有官方验收一致为 `deepseek-flash`,思考关闭,使用默认参数。
+两版在同一配置下按原 16 条夹具顺序比较旧运行版 **1.3.0** 与 **1.4.0**:
+12 条听写、2 条翻译、2 条选区;32 主请求加最多 4 个翻译兜底,总上限 36。
+这不是用户本机渠道身份/模型的证明,也不是旧应用二进制的完整复刻。
+
+先在无 secret 的 step 编译,再直接执行唯一已编译的 Core 测试二进制及精确 ignored
+测试。secret 只给执行 step;runner 专用目录 0700、配置文件 0600,
+不把密钥放进命令行。子进程不继承 secret 环境变量,stdout/stderr 丢弃,
+配置及原始结果由 Python finally 和 shell trap 清理。缺失凭据、渠道报错、超时、
+缺报告、零测试或不完整结果均使 step 失败,不自动重试。
+
+上传工件 `intent-style-comparison-status` 只含 `status.json`:可信夹具及期望、
+版本、请求模型、思考开关、源 SHA(格式有效时)、每侧 pending/completed/request_failed
+和有界端到端耗时。provider text、sourceText、原始错误、配置和 Cargo/HTTP 日志全部不上传。
+模型响应属于不可信数据,字段筛选本身无法保证任意响应内容不含凭据,因此这一模式
+保守地只留下安全执行状态。**completed 只表示请求返回,不表示语义通过;工件不能替代
+旧新正文的人审。** 如需实际语义对照,须由协调者另行确认能够安全查看响应的受控路径,
+或在 Dev 应用中按真实输入流程验收,不把状态工件称为 #26 通过证据。
+
## 版本与迁移设计
运行版此前已是 1.3.0,所以本次递增为 1.4.0,而非回退至 1.1.0。主 JSON 的两个作者槽和共享 Markdown 内容一致,运行时仅追加一次全局口述撤回规则。稳定正文不包含热词占位符,组装器在正文之后追加可变热词和上下文,不向存储回写动态数据。
diff --git a/openless-all/app/scripts/intent-style-comparison-ci.py b/openless-all/app/scripts/intent-style-comparison-ci.py
new file mode 100644
index 000000000..4eda8e790
--- /dev/null
+++ b/openless-all/app/scripts/intent-style-comparison-ci.py
@@ -0,0 +1,194 @@
+"""Opt-in CI runner. Never publish untrusted provider text, errors, or config."""
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+
+TARGET = "intent_style_tests::intent_live_configured_channel_comparison"
+MODEL = "deepseek-flash"
+ENDPOINT = "https://api.deepseek.com/v1"
+FIXTURE = Path(__file__).resolve().parent.parent / (
+ "crates/openless-core/tests/fixtures/intent-reconstruction-evaluation.json"
+)
+
+
+def select_binary(manifest):
+ binaries = set()
+ for line in Path(manifest).read_text().splitlines():
+ row = json.loads(line)
+ if (
+ row.get("reason") == "compiler-artifact"
+ and row.get("target", {}).get("name") == "openless_core"
+ and row.get("profile", {}).get("test") is True
+ and row.get("executable")
+ ):
+ binaries.add(row["executable"])
+ if len(binaries) != 1:
+ raise ValueError("expected one compiled Core test binary")
+ binary = next(iter(binaries))
+ if "\n" in binary or "\r" in binary or not Path(binary).is_file():
+ raise ValueError("invalid compiled test binary")
+ print("binary=" + binary)
+
+
+def safe_report(evaluation):
+ # Every string comes from a trusted repository fixture or a constant here.
+ # Arbitrary response text cannot be guaranteed secret-free, so omit it.
+ return {
+ "schemaVersion": 1,
+ "baselineVersion": "1.3.0",
+ "candidateVersion": "1.4.0",
+ "requestedModel": MODEL,
+ "thinkingEnabled": False,
+ "primaryRequestLimit": 32,
+ "totalRequestLimit": 36,
+ "executionStatus": "not_started",
+ "semanticReview": "pending; provider text intentionally not published",
+ "cases": [
+ {
+ **{
+ key: case[key]
+ for key in (
+ "id", "operation", "input", "mustPreserve", "mustRemove", "structure"
+ )
+ },
+ **{
+ key: case[key]
+ for key in ("instruction", "targetLanguage")
+ if key in case
+ },
+ "old": {"status": "pending"},
+ "new": {"status": "pending"},
+ }
+ for case in evaluation["cases"]
+ ],
+ }
+
+
+def apply_status(report, raw):
+ if (
+ raw.get("schemaVersion") != 1
+ or raw.get("baselineVersion") != "1.3.0"
+ or raw.get("candidateVersion") != "1.4.0"
+ or raw.get("requestedModel") != MODEL
+ or raw.get("thinkingEnabled") is not False
+ or not isinstance(raw.get("cases"), list)
+ or [case.get("id") for case in raw["cases"]]
+ != [case["id"] for case in report["cases"]]
+ ):
+ raise ValueError("unexpected comparison report")
+ for target, case in zip(report["cases"], raw["cases"]):
+ for side in ("old", "new"):
+ value = case.get(side)
+ if value is None:
+ continue
+ if not isinstance(value, dict):
+ raise ValueError("unexpected result")
+ if "errorCode" in value:
+ target[side] = {"status": "request_failed"}
+ elif isinstance(value.get("text"), str):
+ target[side] = {"status": "completed"}
+ elapsed = value.get("elapsedMs")
+ if type(elapsed) is int and 0 <= elapsed <= 900_000:
+ target[side]["elapsedMs"] = elapsed
+ else:
+ raise ValueError("unexpected result")
+
+
+def run(binary, private_directory, evidence_directory):
+ report = safe_report(json.loads(FIXTURE.read_text()))
+ source_sha = os.environ.get("GITHUB_SHA", "")
+ if re.fullmatch("[0-9a-f]{40}", source_sha):
+ report["sourceSha"] = source_sha
+ operations = [case["operation"] for case in report["cases"]]
+ if (
+ len(operations) != 16
+ or operations.count("dictation") != 12
+ or operations.count("translation") != 2
+ or operations.count("selection") != 2
+ ):
+ raise ValueError("expected the original bounded 16 fixtures")
+ evidence_directory = Path(evidence_directory)
+ evidence_directory.mkdir(mode=0o700, parents=True, exist_ok=False)
+ output = evidence_directory / "status.json"
+ private_directory = Path(private_directory)
+ config = private_directory / "channel.json"
+ raw_output = private_directory / "results.json"
+ result = 1
+ try:
+ key = os.environ.pop("DEEPSEEK_API_KEY", "")
+ if not key or key != key.strip() or any(char.isspace() for char in key):
+ report["executionStatus"] = "credentials_missing_or_invalid"
+ return result
+ # This matches the existing official-provider suite, not local user settings.
+ settings = {
+ "channelId": "deepseek",
+ "providerType": "deepseek",
+ "model": MODEL,
+ "thinkingEnabled": False,
+ "baseline": "1.3.0",
+ "credentials": {
+ "ark.endpoint": ENDPOINT,
+ "ark.api_key": key,
+ },
+ }
+ with open(config, "x", opener=lambda path, flags: os.open(path, flags, 0o600)) as stream:
+ json.dump(settings, stream)
+ # No workflow credentials or logging environment are inherited by the test.
+ environment = {
+ name: os.environ[name]
+ for name in ("PATH", "HOME", "TMPDIR", "LANG")
+ if name in os.environ
+ }
+ environment.update({
+ "OPENLESS_INTENT_COMPARISON_APPROVED": "yes",
+ "OPENLESS_INTENT_COMPARISON_CONFIG": str(config),
+ "OPENLESS_INTENT_COMPARISON_OUTPUT": str(raw_output),
+ })
+ completed = subprocess.run(
+ [binary, TARGET, "--ignored", "--exact", "--test-threads=1"],
+ env=environment,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ timeout=900,
+ check=False,
+ )
+ if not raw_output.is_file() or raw_output.stat().st_size > 2_000_000:
+ report["executionStatus"] = "missing_or_invalid_report"
+ return result
+ apply_status(report, json.loads(raw_output.read_text()))
+ all_completed = all(
+ case[side]["status"] == "completed"
+ for case in report["cases"]
+ for side in ("old", "new")
+ )
+ result = 0 if completed.returncode == 0 and all_completed else 1
+ report["executionStatus"] = "completed" if result == 0 else "test_failed"
+ return result
+ except subprocess.TimeoutExpired:
+ report["executionStatus"] = "timed_out"
+ return 1
+ except Exception:
+ # No repr/traceback: even parser and filesystem errors can contain secrets.
+ report["executionStatus"] = "execution_or_report_failed"
+ return 1
+ finally:
+ config.unlink(missing_ok=True)
+ raw_output.unlink(missing_ok=True)
+ output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
+
+
+if __name__ == "__main__":
+ try:
+ if len(sys.argv) == 3 and sys.argv[1] == "select-binary":
+ select_binary(sys.argv[2])
+ elif len(sys.argv) == 5 and sys.argv[1] == "run":
+ sys.exit(run(*sys.argv[2:]))
+ else:
+ sys.exit(2)
+ except Exception:
+ # Inputs in this wrapper are never printed, including exception messages.
+ print("Intent comparison wrapper failed; no private diagnostic was published.")
+ sys.exit(1)
diff --git a/openless-all/app/scripts/test_intent_style_comparison_ci.py b/openless-all/app/scripts/test_intent_style_comparison_ci.py
new file mode 100644
index 000000000..c799c3a8f
--- /dev/null
+++ b/openless-all/app/scripts/test_intent_style_comparison_ci.py
@@ -0,0 +1,164 @@
+"""Offline tests only: the process boundary is mocked; no credentials or network."""
+import importlib.util
+import contextlib
+import io
+import json
+import os
+from pathlib import Path
+import re
+import stat
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+SCRIPT = Path(__file__).with_name("intent-style-comparison-ci.py")
+SPEC = importlib.util.spec_from_file_location("intent_comparison_ci", SCRIPT)
+ci = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(ci)
+SENTINEL = "synthetic-ci-fixture-secret"
+
+
+class IntentComparisonCiTests(unittest.TestCase):
+ def setUp(self):
+ self.scratch = tempfile.TemporaryDirectory(prefix="openless-intent-ci-test-")
+ self.addCleanup(self.scratch.cleanup)
+ self.private = Path(self.scratch.name) / "private"
+ self.private.mkdir(mode=0o700)
+ self.evidence = Path(self.scratch.name) / "evidence"
+ self.evaluation = json.loads(ci.FIXTURE.read_text())
+
+ def raw(self):
+ return {
+ **ci.safe_report(self.evaluation),
+ "credentials": {"key": SENTINEL},
+ "cases": [
+ {
+ "id": case["id"],
+ "input": SENTINEL,
+ "old": {"text": SENTINEL, "elapsedMs": 12},
+ "new": {"text": "https://private.invalid/" + SENTINEL, "elapsedMs": 15},
+ }
+ for case in self.evaluation["cases"]
+ ],
+ }
+
+ def execute(self, raw=None, returncode=0, exception=None, key=SENTINEL):
+ def fake_process(argv, **kwargs):
+ self.assertEqual(argv, [
+ "/unused/test-binary", ci.TARGET, "--ignored", "--exact", "--test-threads=1"
+ ])
+ self.assertEqual(kwargs["stdout"], subprocess.DEVNULL)
+ self.assertEqual(kwargs["stderr"], subprocess.DEVNULL)
+ self.assertNotIn("DEEPSEEK_API_KEY", kwargs["env"])
+ self.assertNotIn("GITHUB_TOKEN", kwargs["env"])
+ config = self.private / "channel.json"
+ self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600)
+ settings = json.loads(config.read_text())
+ self.assertEqual(settings["credentials"]["ark.api_key"], SENTINEL)
+ self.assertEqual(settings["baseline"], "1.3.0")
+ self.assertEqual(settings["model"], ci.MODEL)
+ self.assertIs(settings["thinkingEnabled"], False)
+ if exception:
+ raise exception
+ if raw is not None:
+ (self.private / "results.json").write_text(json.dumps(raw))
+ return subprocess.CompletedProcess(argv, returncode)
+
+ with patch.dict(os.environ, {
+ "DEEPSEEK_API_KEY": key, "GITHUB_TOKEN": SENTINEL, "GITHUB_SHA": "a" * 40
+ }):
+ with patch.object(ci.subprocess, "run", side_effect=fake_process) as process:
+ code = ci.run("/unused/test-binary", self.private, self.evidence)
+ published = (self.evidence / "status.json").read_text()
+ self.assertNotIn(SENTINEL, published)
+ self.assertNotIn("private.invalid", published)
+ self.assertEqual(list(self.private.iterdir()), [])
+ return code, json.loads(published), process.call_count
+
+ def test_success_uploads_only_canonical_fixtures_and_status(self):
+ code, report, calls = self.execute(self.raw())
+ self.assertEqual((code, calls), (0, 1))
+ self.assertEqual(report["executionStatus"], "completed")
+ self.assertEqual(report["cases"][0]["old"], {"status": "completed", "elapsedMs": 12})
+ self.assertEqual(report["cases"][0]["input"], self.evaluation["cases"][0]["input"])
+ self.assertNotIn("credentials", report)
+ self.assertNotIn("text", report["cases"][0]["new"])
+ self.assertEqual(report["sourceSha"], "a" * 40)
+
+ def test_provider_failure_drops_error_and_retains_pending(self):
+ raw = self.raw()
+ raw["cases"][0]["new"] = {"errorCode": SENTINEL}
+ for case in raw["cases"][1:]:
+ case["old"] = case["new"] = None
+ code, report, _ = self.execute(raw, returncode=101)
+ self.assertEqual(code, 1)
+ self.assertEqual(report["cases"][0]["new"], {"status": "request_failed"})
+ self.assertEqual(report["cases"][1]["old"], {"status": "pending"})
+
+ def test_missing_or_invalid_credentials_fail_before_process(self):
+ code, report, calls = self.execute(key="")
+ self.assertEqual((code, calls), (1, 0))
+ self.assertEqual(report["executionStatus"], "credentials_missing_or_invalid")
+
+ def test_timeout_is_safe_and_cleans_config(self):
+ code, report, _ = self.execute(exception=subprocess.TimeoutExpired(SENTINEL, 900))
+ self.assertEqual(code, 1)
+ self.assertEqual(report["executionStatus"], "timed_out")
+
+ def test_invalid_report_never_publishes_raw_diagnostic(self):
+ raw = self.raw()
+ raw["cases"][0]["id"] = SENTINEL
+ code, report, _ = self.execute(raw)
+ self.assertEqual(code, 1)
+ self.assertEqual(report["executionStatus"], "execution_or_report_failed")
+
+ def test_zero_tests_is_failure(self):
+ code, report, _ = self.execute()
+ self.assertEqual(code, 1)
+ self.assertEqual(report["executionStatus"], "missing_or_invalid_report")
+
+ def test_selects_one_precompiled_binary_and_rejects_ambiguity(self):
+ binary = self.private / "test-binary"
+ binary.touch()
+ manifest = self.private / "build.jsonl"
+ artifact = {
+ "reason": "compiler-artifact", "target": {"name": "openless_core"},
+ "profile": {"test": True}, "executable": str(binary)
+ }
+ manifest.write_text(json.dumps(artifact) + "\n")
+ with contextlib.redirect_stdout(io.StringIO()) as output:
+ ci.select_binary(manifest)
+ self.assertEqual(output.getvalue(), "binary=" + str(binary) + "\n")
+ artifact["executable"] = str(self.private / "another-binary")
+ with manifest.open("a") as stream:
+ stream.write(json.dumps(artifact) + "\n")
+ with self.assertRaises(ValueError):
+ ci.select_binary(manifest)
+
+ def test_workflow_uses_only_trusted_manual_path_and_safe_artifact(self):
+ workflow = SCRIPT.parents[3] / ".github/workflows/ci.yml"
+ text = workflow.read_text()
+ live = text.split("\n live-acceptance:\n", 1)[1]
+ self.assertIn("default: 'off'", text)
+ self.assertIn('["refs/heads/main","refs/heads/beta"]', live)
+ self.assertIn("github.repository == 'Open-Less/openless'", live)
+ self.assertIn("github.event_name == 'workflow_dispatch'", live)
+ self.assertIn("persist-credentials: false", live)
+ self.assertIn("chmod 700", live)
+ self.assertIn("trap 'rm -rf", live)
+ self.assertIn("inputs.live_acceptance != 'intent-style-comparison'", live)
+ self.assertIn("openless-intent-evidence/status.json", live)
+ self.assertIn("CARGO_TARGET_DIR: ${{ runner.temp }}/openless-live-target", live)
+ self.assertIn('rm -rf "$RUNNER_TEMP/openless-live-target"', live)
+ suite = SCRIPT.parent.parent / "crates/openless-core/src/deepseek_suite.rs"
+ for name, value in (("MODEL", ci.MODEL), ("ENDPOINT", ci.ENDPOINT)):
+ found = re.search(rf'pub const {name}: &str = "([^"]+)";', suite.read_text())
+ self.assertEqual(found.group(1), value)
+ self.assertEqual(
+ sum(c["operation"] == "translation" for c in self.evaluation["cases"]), 2
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
From 51ad48ac784134747bbd0694e039d348d3647b8c Mon Sep 17 00:00:00 2001
From: appergb <192432815+appergb@users.noreply.github.com>
Date: Fri, 27 Nov 2026 21:25:55 +0800
Subject: [PATCH 3/8] ci(styles): encrypt reviewable intent comparison evidence
---
.github/workflows/ci.yml | 19 +-
docs/intent-style-evaluation.md | 118 +++++++---
.../app/scripts/intent-style-comparison-ci.py | 207 +++++++++++++++++-
.../test_intent_style_comparison_ci.py | 152 ++++++++++++-
4 files changed, 449 insertions(+), 47 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 586268132..63acd8b31 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -24,6 +24,11 @@ on:
type: choice
options: ['off', style, style-diagnostic, search, intent-style-comparison]
default: 'off'
+ intent_recipient_certificate:
+ description: Public PEM recipient certificate for encrypted intent evidence (never a private key)
+ type: string
+ required: false
+ default: ''
platform:
description: Platforms to check (macos runs only macOS gates)
type: choice
@@ -1302,6 +1307,11 @@ jobs:
- uses: actions/checkout@v4
with:
persist-credentials: false
+ - name: Validate intent evidence recipient before any paid request
+ if: inputs.live_acceptance == 'intent-style-comparison'
+ env:
+ INTENT_RECIPIENT_CERTIFICATE: ${{ inputs.intent_recipient_certificate }}
+ run: python3 scripts/intent-style-comparison-ci.py preflight
- uses: dtolnay/rust-toolchain@stable
- name: Build acceptance without credentials
id: live-build
@@ -1332,6 +1342,7 @@ jobs:
env:
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
INTENT_TEST_BINARY: ${{ steps.live-build.outputs.binary }}
+ INTENT_RECIPIENT_CERTIFICATE: ${{ inputs.intent_recipient_certificate }}
run: |
set -euo pipefail
umask 077
@@ -1347,12 +1358,14 @@ jobs:
name: official-provider-live-acceptance
path: openless-all/app/live-acceptance.log
if-no-files-found: ignore
- - name: Preserve only safe intent execution status
+ - name: Preserve encrypted intent review and safe execution status
if: always() && inputs.live_acceptance == 'intent-style-comparison'
uses: actions/upload-artifact@v4
with:
- name: intent-style-comparison-status
- path: ${{ runner.temp }}/openless-intent-evidence/status.json
+ name: intent-style-comparison-evidence
+ path: |
+ ${{ runner.temp }}/openless-intent-evidence/status.json
+ ${{ runner.temp }}/openless-intent-evidence/comparison.cms
if-no-files-found: ignore
retention-days: 7
- name: Clean dedicated live acceptance artifacts
diff --git a/docs/intent-style-evaluation.md b/docs/intent-style-evaluation.md
index 7af2f24f0..2faf69c0e 100644
--- a/docs/intent-style-evaluation.md
+++ b/docs/intent-style-evaluation.md
@@ -66,38 +66,92 @@ OAuth 渠道或不希望复制凭据时,在风格设置建立两个临时自
逐条检查信息是否遗漏、撤销是否生效、是否重复归组、层级与编号是否合理、专名数字是否保留、是否新增要求或代答。给每条记录通过 / 不通过和具体偏差;失败后可以修改提示词,但不能覆盖已有对照证据。最终效果由用户判断。渠道是否返回缓存读取和推理用量,仍须通过应用的用量账本另行检查;该并排记录不代替缓存或计费测量。
-## 使用既有 Actions secret 的手动状态对照
-
-仓库已有的 `Optional official-provider live acceptance` 增加了非默认选项
-`intent-style-comparison`。仅限 `Open-Less/openless` 仓库的 `main` / `beta`
-分支手动运行;fork、PR、tag 和其他分支不进入带 secret 的 job。默认仍为 `off`,
-普通 CI 不会调用模型。协调者先将本改动接入经审查的集成版本,核对分支 SHA 后可执行一次:
-
-```sh
-gh workflow run ci.yml --repo Open-Less/openless --ref beta \
- -f live_acceptance=intent-style-comparison
-```
-
-这是未自动执行的真实付费调用命令;沿用调用前授权,不能重复运行消耗预算。
-它只使用现存 `DEEPSEEK_API_KEY` secret,不读取或搬运本机配置;渠道固定为官方 DeepSeek,
-模型与现有官方验收一致为 `deepseek-flash`,思考关闭,使用默认参数。
-两版在同一配置下按原 16 条夹具顺序比较旧运行版 **1.3.0** 与 **1.4.0**:
-12 条听写、2 条翻译、2 条选区;32 主请求加最多 4 个翻译兜底,总上限 36。
-这不是用户本机渠道身份/模型的证明,也不是旧应用二进制的完整复刻。
-
-先在无 secret 的 step 编译,再直接执行唯一已编译的 Core 测试二进制及精确 ignored
-测试。secret 只给执行 step;runner 专用目录 0700、配置文件 0600,
-不把密钥放进命令行。子进程不继承 secret 环境变量,stdout/stderr 丢弃,
-配置及原始结果由 Python finally 和 shell trap 清理。缺失凭据、渠道报错、超时、
-缺报告、零测试或不完整结果均使 step 失败,不自动重试。
-
-上传工件 `intent-style-comparison-status` 只含 `status.json`:可信夹具及期望、
-版本、请求模型、思考开关、源 SHA(格式有效时)、每侧 pending/completed/request_failed
-和有界端到端耗时。provider text、sourceText、原始错误、配置和 Cargo/HTTP 日志全部不上传。
-模型响应属于不可信数据,字段筛选本身无法保证任意响应内容不含凭据,因此这一模式
-保守地只留下安全执行状态。**completed 只表示请求返回,不表示语义通过;工件不能替代
-旧新正文的人审。** 如需实际语义对照,须由协调者另行确认能够安全查看响应的受控路径,
-或在 Dev 应用中按真实输入流程验收,不把状态工件称为 #26 通过证据。
+## 使用既有 Actions secret 的加密语义对照
+
+现有 `Optional official-provider live acceptance` 的非默认选项
+`intent-style-comparison` 只接受 `Open-Less/openless` 仓库的 `main` / `beta`
+分支手动运行。fork、PR、tag 和其他分支不进入带 secret 的 job;默认仍为 `off`。
+不能运行只留下状态的旧入口:调用前必须有已在协调者本机验证的一次性公有收件人证书,
+云端只接收该证书,私钥留在协调者本机。新增机制不增加模型请求或 App 构建。
+
+以下是供协调者执行的步骤,本改动的开发/离线测试没有执行真实请求或生成正式收件人。
+协调者先将本改动接入经审查的集成版本,锁定可信分支 SHA;使用已经安装且支持
+CMS AuthEnvelopedData、AES-256-GCM 和 RSA-OAEP 的 OpenSSL,不在本任务安装组件。
+本机若只有不支持该格式的工具,应停止并采用受控 Dev 真机路径。
+
+1. 在仓库之外创建私有目录、一次性 RSA 3072 收件人;下面的私钥不加口令,仅靠 0700
+ 目录与 0600 权限保管,以便本地解密 helper 无交互运行。它永远不提交、不上传:
+
+ ```sh
+ umask 077
+ review_dir=$(mktemp -d "${TMPDIR:-/tmp}/openless-intent-review.XXXXXX")
+ chmod 700 "$review_dir"
+ openssl req -x509 -newkey rsa:3072 -sha256 -nodes -days 2 \
+ -subj /CN=OpenLess-intent-review \
+ -keyout "$review_dir/recipient.key" -out "$review_dir/recipient.crt"
+ chmod 600 "$review_dir/recipient.key" "$review_dir/recipient.crt"
+ python3 scripts/intent-style-comparison-ci.py check-recipient \
+ "$review_dir/recipient.crt" "$review_dir/recipient.key"
+ ```
+
+ 在 `openless-all/app/` 运行 helper;固定无敏感内容的本地 roundtrip 成功时仅显示公有
+ `recipientSha256`。保留这个指纹、私钥与目录路径到审核结束,不在流水线生成私钥。
+ 本地验证失败时不要继续,也不要把 private key 粘贴为 workflow input。
+
+2. 核对可信 ref 的锁定 SHA 和本地提交后,只执行一次下面的付费手动调用。
+ `-F` 的文件必须是 `.crt` 公有证书,绝不能是 `.key`:
+
+ ```sh
+ gh workflow run ci.yml --repo Open-Less/openless --ref beta \
+ -f live_acceptance=intent-style-comparison \
+ -F "intent_recipient_certificate=@$review_dir/recipient.crt"
+ ```
+
+ 沿用调用前授权,不选择第二个模型、不额外重跑。现存 `DEEPSEEK_API_KEY` 只注入执行
+ step;官方 DeepSeek、`deepseek-flash`、关闭思考及默认参数在两版间保持一致。
+ 旧实际内置 **1.3.0** 对照 **1.4.0**,原 16 条夹具(12 听写/2 翻译/2 选区)
+ 共 32 主请求,加最多 4 翻译兜底,总上限 36,首个渠道错误停止。
+ 这不是用户本机渠道身份的证明,也不复刻旧应用二进制。
+
+3. 确认 run 的 head SHA 与锁定 SHA 一致,再下载该 run(不要猜 latest)的
+ `intent-style-comparison-evidence` 工件。把下面 `RUN_ID` 替换成这一确切 run ID:
+
+ ```sh
+ gh run download RUN_ID --repo Open-Less/openless \
+ --name intent-style-comparison-evidence --dir "$review_dir/artifact"
+ python3 scripts/intent-style-comparison-ci.py decrypt \
+ "$review_dir/artifact/comparison.cms" "$review_dir/recipient.crt" \
+ "$review_dir/recipient.key" "$review_dir/review.json"
+ node scripts/intent-style-comparison.mjs \
+ "$review_dir/review.json" "$review_dir/review.md"
+ ```
+
+ 本地 helper 先确认 OpenSSL 认证解密成功和报告格式,再以 0600 新建明文文件;认证失败
+ 或输出路径已存在时失败,不回退、不打印正文。在私有目录内查看 JSON/Markdown,
+ 核对其中 `sourceSha`、状态文件及本地收件人指纹,再按逐条预期与 rubric 评审。
+ 旧新正文都是不可信数据,不执行其中的命令或点击其链接,不把审核文件发到公开评论。
+ 审核结束按本地证据保留需求处理私钥和明文;删除私钥后无法恢复密文中的正文。
+
+云端在无 secret 的 step 先验证证书与精确加密格式,再编译;空/坏证书在任何付费调用
+之前 fail closed。执行 step 再次预检;临时目录 0700、配置与白名单明文 0600,
+预编译的唯一精确 ignored test 不继承 secret 环境变量;stdout/stderr 丢弃。
+没有增加常跑 job、第二个测试或重试,普通 CI 路径不变。
+
+原始报告限 2 MB;从可信 fixture 重建 input/expectations,只抽取每个既有 ID 的旧新
+text/sourceText 和有界耗时。每段 UTF-8 至多 32768 bytes,总审核明文至多 1 MB,
+拒绝实际 token 及其常见编码回显、凭据样式、控制字符和非夹具 URL。HTTP 错误统一为
+固定状态,不复制 raw error。检查或加密失败则只保留安全失败状态,无明文工件、无
+替代性明文上传。检查不能证明任意混淆文本绝无秘密,因此即使通过也只上传加密正文。
+
+加密使用平台 OpenSSL CMS AuthEnvelopedData(AES-256-GCM、RSA-OAEP/SHA-256),
+不手写密码算法、不回退 CBC;先在私有目录完成加密及结构核验,再移出密文。
+工件仅有 `comparison.cms` 和安全 `status.json`,保留 7 天;无配置、私钥、原始结果或
+Cargo/HTTP 日志。finally/trap 清理私有文件,always 清理专用 target/工件暂存目录;
+强制 SIGKILL 的最终清理依赖临时 hosted runner 生命周期。
+
+`status=completed` 或成功解密均不表示语义通过。缺密文时不要再次消耗预算,先核对
+安全失败状态及已发请求;部分渠道失败仍可能留下经过同样检查和加密的部分对照。
+密文完整性不是发送者签名,必须从锁定 SHA 的可信 GitHub run 取得并核对来源。
## 版本与迁移设计
diff --git a/openless-all/app/scripts/intent-style-comparison-ci.py b/openless-all/app/scripts/intent-style-comparison-ci.py
index 4eda8e790..0b5176fc3 100644
--- a/openless-all/app/scripts/intent-style-comparison-ci.py
+++ b/openless-all/app/scripts/intent-style-comparison-ci.py
@@ -1,14 +1,22 @@
-"""Opt-in CI runner. Never publish untrusted provider text, errors, or config."""
+"""Opt-in CI runner. Review text leaves the runner only in authenticated CMS."""
+import base64
+import copy
+import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
+import tempfile
+from urllib.parse import quote
TARGET = "intent_style_tests::intent_live_configured_channel_comparison"
MODEL = "deepseek-flash"
ENDPOINT = "https://api.deepseek.com/v1"
+MAX_REPORT = 2_000_000
+MAX_REVIEW = 1_000_000
+MAX_TEXT = 32_768
FIXTURE = Path(__file__).resolve().parent.parent / (
"crates/openless-core/tests/fixtures/intent-reconstruction-evaluation.json"
)
@@ -45,7 +53,7 @@ def safe_report(evaluation):
"primaryRequestLimit": 32,
"totalRequestLimit": 36,
"executionStatus": "not_started",
- "semanticReview": "pending; provider text intentionally not published",
+ "semanticReview": "pending human review; outputs are untrusted text",
"cases": [
{
**{
@@ -97,6 +105,161 @@ def apply_status(report, raw):
raise ValueError("unexpected result")
+def openssl(arguments, data=None):
+ result = subprocess.run(
+ ["openssl", *arguments], input=data, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, timeout=30, check=False,
+ env={name: os.environ[name] for name in ("PATH", "HOME", "TMPDIR", "LANG")
+ if name in os.environ},
+ )
+ if result.returncode != 0:
+ raise ValueError("cryptographic operation failed")
+ return result.stdout
+
+
+def private_write(path, data):
+ with open(path, "xb", opener=lambda name, flags: os.open(name, flags, 0o600)) as stream:
+ stream.write(data)
+
+
+def cms_encrypt(plaintext, ciphertext, certificate):
+ openssl([
+ "cms", "-encrypt", "-binary", "-aes-256-gcm",
+ "-in", str(plaintext), "-outform", "DER", "-out", str(ciphertext),
+ "-recip", str(certificate), "-keyopt", "rsa_padding_mode:oaep",
+ "-keyopt", "rsa_oaep_md:sha256", "-keyopt", "rsa_mgf1_md:sha256",
+ ])
+ validate_ciphertext(ciphertext)
+
+
+def validate_ciphertext(ciphertext):
+ # Both sides reject unauthenticated CBC, even for an otherwise valid CMS file.
+ if not 128 <= ciphertext.stat().st_size <= MAX_REPORT:
+ raise ValueError("unexpected ciphertext size")
+ structure = openssl(["cms", "-cmsout", "-inform", "DER", "-in", str(ciphertext), "-print"])
+ for field in (
+ rb"^ contentType: id-smime-ct-authEnvelopedData \(",
+ rb"^\s+algorithm: aes-256-gcm \(",
+ rb"^\s+algorithm: rsaesOaep \(",
+ ):
+ if not re.search(field, structure, re.M):
+ raise ValueError("authenticated CMS required")
+
+
+def validate_recipient(certificate, directory):
+ if (
+ not isinstance(certificate, str) or len(certificate) > 8192
+ or not re.fullmatch(
+ r"\s*-----BEGIN CERTIFICATE-----\r?\n[A-Za-z0-9+/=\r\n]+"
+ r"-----END CERTIFICATE-----\s*", certificate
+ )
+ ):
+ raise ValueError("one public PEM certificate required")
+ path = directory / "recipient.pem"
+ private_write(path, certificate.encode("ascii"))
+ der = openssl(["x509", "-in", str(path), "-outform", "DER"])
+ openssl(["x509", "-in", str(path), "-checkend", "3600", "-noout"])
+ public = openssl(["x509", "-in", str(path), "-pubkey", "-noout"])
+ details = openssl(["rsa", "-pubin", "-text", "-noout"], public)
+ bits = re.search(rb"Public-Key: \((\d+) bit\)", details)
+ if not bits or not 3072 <= int(bits[1]) <= 8192:
+ raise ValueError("RSA 3072..8192 recipient required")
+ # Prove that this installed OpenSSL supports the exact authenticated format
+ # before the caller reads provider credentials or starts a paid request.
+ probe = directory / "probe.json"
+ encrypted = directory / "probe.cms"
+ private_write(probe, b'{"preflight":"non-sensitive fixture"}')
+ cms_encrypt(probe, encrypted, path)
+ probe.unlink()
+ encrypted.unlink()
+ return path, hashlib.sha256(der).hexdigest()
+
+
+def review_text(text, key, allowed_urls):
+ if not isinstance(text, str) or len(text.encode("utf-8")) > MAX_TEXT:
+ raise ValueError("invalid review text")
+ if any(ord(char) < 32 and char not in "\r\n\t" for char in text):
+ raise ValueError("unexpected control character")
+ variants = {
+ key, quote(key, safe=""), key.encode().hex(),
+ base64.b64encode(key.encode()).decode(),
+ base64.urlsafe_b64encode(key.encode()).decode(),
+ json.dumps(key)[1:-1],
+ }
+ if any(value in text for value in variants):
+ raise ValueError("credential echo rejected")
+ if re.search(
+ r"-----BEGIN (?:[A-Z ]*PRIVATE KEY|CERTIFICATE)-----"
+ r"|authorization\s*:\s*bearer|(?:api[_ -]?key|token)\s*[:=]"
+ r"|\bsk-[A-Za-z0-9_-]{16,}", text, re.I
+ ):
+ raise ValueError("credential-like content rejected")
+ if set(re.findall(r'https?://[^\s<>"`(),。;)]+', text)) - allowed_urls:
+ raise ValueError("unexpected URL")
+ return text
+
+
+def review_payload(report, raw, key):
+ payload = copy.deepcopy(report)
+ for target, canonical, case in zip(payload["cases"], report["cases"], raw["cases"]):
+ allowed_urls = set(re.findall(r'https?://[^\s<>"`(),。;)]+', canonical["input"]))
+ for side in ("old", "new"):
+ value = case.get(side)
+ if value is None:
+ target[side] = None
+ elif "errorCode" in value:
+ target[side] = {"errorCode": "request_failed"}
+ else:
+ selected = {"text": review_text(value["text"], key, allowed_urls)}
+ source = value.get("sourceText")
+ if source is not None:
+ selected["sourceText"] = review_text(source, key, allowed_urls)
+ elapsed = canonical[side].get("elapsedMs")
+ if elapsed is not None:
+ selected["elapsedMs"] = elapsed
+ target[side] = selected
+ encoded = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode()
+ if len(encoded) > MAX_REVIEW:
+ raise ValueError("oversize review")
+ return encoded
+
+
+def decrypt_review(ciphertext, certificate, private_key, output):
+ """Local explicit command only. Never writes unauthenticated plaintext."""
+ ciphertext = Path(ciphertext)
+ validate_ciphertext(ciphertext)
+ plaintext = openssl([
+ "cms", "-decrypt", "-binary", "-inform", "DER", "-in", str(ciphertext),
+ "-recip", certificate, "-inkey", private_key,
+ ])
+ if len(plaintext) > MAX_REVIEW:
+ raise ValueError("oversize review")
+ payload = json.loads(plaintext)
+ canonical = safe_report(json.loads(FIXTURE.read_text()))
+ apply_status(canonical, payload)
+ # Keep the plaintext out of stdout; the original renderer reads this private file.
+ private_write(Path(output), plaintext)
+
+
+def check_recipient(certificate, private_key):
+ """Coordinator-only local receipt check, with fixed non-sensitive bytes."""
+ with tempfile.TemporaryDirectory(prefix="openless-local-recipient-") as scratch:
+ directory = Path(scratch)
+ recipient, fingerprint = validate_recipient(Path(certificate).read_text(), directory)
+ plaintext = directory / "local-check.txt"
+ ciphertext = directory / "local-check.cms"
+ expected = b"OpenLess one-time recipient possession check"
+ private_write(plaintext, expected)
+ cms_encrypt(plaintext, ciphertext, recipient)
+ actual = openssl([
+ "cms", "-decrypt", "-binary", "-inform", "DER", "-in", str(ciphertext),
+ "-recip", str(recipient), "-inkey", private_key,
+ ])
+ if actual != expected:
+ raise ValueError("recipient possession check failed")
+ return fingerprint
+
+
def run(binary, private_directory, evidence_directory):
report = safe_report(json.loads(FIXTURE.read_text()))
source_sha = os.environ.get("GITHUB_SHA", "")
@@ -117,7 +280,16 @@ def run(binary, private_directory, evidence_directory):
config = private_directory / "channel.json"
raw_output = private_directory / "results.json"
result = 1
+ ciphertext = evidence_directory / "comparison.cms"
try:
+ try:
+ recipient, fingerprint = validate_recipient(
+ os.environ.get("INTENT_RECIPIENT_CERTIFICATE", ""), private_directory
+ )
+ report["recipientSha256"] = fingerprint
+ except Exception:
+ report["executionStatus"] = "recipient_invalid_or_crypto_unavailable"
+ return 1
key = os.environ.pop("DEEPSEEK_API_KEY", "")
if not key or key != key.strip() or any(char.isspace() for char in key):
report["executionStatus"] = "credentials_missing_or_invalid"
@@ -155,10 +327,11 @@ def run(binary, private_directory, evidence_directory):
timeout=900,
check=False,
)
- if not raw_output.is_file() or raw_output.stat().st_size > 2_000_000:
+ if not raw_output.is_file() or raw_output.stat().st_size > MAX_REPORT:
report["executionStatus"] = "missing_or_invalid_report"
return result
- apply_status(report, json.loads(raw_output.read_text()))
+ raw = json.loads(raw_output.read_text())
+ apply_status(report, raw)
all_completed = all(
case[side]["status"] == "completed"
for case in report["cases"]
@@ -166,6 +339,16 @@ def run(binary, private_directory, evidence_directory):
)
result = 0 if completed.returncode == 0 and all_completed else 1
report["executionStatus"] = "completed" if result == 0 else "test_failed"
+ try:
+ plaintext = private_directory / "review.json"
+ private_write(plaintext, review_payload(report, raw, key))
+ encrypted = private_directory / "comparison.cms"
+ cms_encrypt(plaintext, encrypted, recipient)
+ encrypted.replace(ciphertext)
+ report["encryptedReview"] = "available"
+ except Exception:
+ report["executionStatus"] = "review_rejected_or_encryption_failed"
+ return 1
return result
except subprocess.TimeoutExpired:
report["executionStatus"] = "timed_out"
@@ -175,8 +358,11 @@ def run(binary, private_directory, evidence_directory):
report["executionStatus"] = "execution_or_report_failed"
return 1
finally:
- config.unlink(missing_ok=True)
- raw_output.unlink(missing_ok=True)
+ for name in (
+ "channel.json", "results.json", "review.json", "comparison.cms",
+ "recipient.pem", "probe.json", "probe.cms",
+ ):
+ (private_directory / name).unlink(missing_ok=True)
output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
@@ -184,6 +370,15 @@ def run(binary, private_directory, evidence_directory):
try:
if len(sys.argv) == 3 and sys.argv[1] == "select-binary":
select_binary(sys.argv[2])
+ elif len(sys.argv) == 2 and sys.argv[1] == "preflight":
+ with tempfile.TemporaryDirectory(prefix="openless-intent-recipient-") as scratch:
+ validate_recipient(
+ os.environ.get("INTENT_RECIPIENT_CERTIFICATE", ""), Path(scratch)
+ )
+ elif len(sys.argv) == 6 and sys.argv[1] == "decrypt":
+ decrypt_review(*sys.argv[2:])
+ elif len(sys.argv) == 4 and sys.argv[1] == "check-recipient":
+ print("recipientSha256=" + check_recipient(*sys.argv[2:]))
elif len(sys.argv) == 5 and sys.argv[1] == "run":
sys.exit(run(*sys.argv[2:]))
else:
diff --git a/openless-all/app/scripts/test_intent_style_comparison_ci.py b/openless-all/app/scripts/test_intent_style_comparison_ci.py
index c799c3a8f..91dd34a8d 100644
--- a/openless-all/app/scripts/test_intent_style_comparison_ci.py
+++ b/openless-all/app/scripts/test_intent_style_comparison_ci.py
@@ -17,9 +17,25 @@
ci = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(ci)
SENTINEL = "synthetic-ci-fixture-secret"
+REAL_RUN = subprocess.run
class IntentComparisonCiTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.recipient_scratch = tempfile.TemporaryDirectory(prefix="openless-dummy-recipient-")
+ cls.addClassCleanup(cls.recipient_scratch.cleanup)
+ cls.cert = Path(cls.recipient_scratch.name) / "dummy.crt"
+ cls.key = Path(cls.recipient_scratch.name) / "dummy.key"
+ result = REAL_RUN([
+ "openssl", "req", "-x509", "-newkey", "rsa:3072", "-sha256", "-nodes",
+ "-keyout", str(cls.key), "-out", str(cls.cert), "-days", "2",
+ "-subj", "/CN=OpenLess-offline-dummy",
+ ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
+ if result.returncode != 0:
+ raise RuntimeError("existing OpenSSL required for offline dummy roundtrip")
+ cls.certificate = cls.cert.read_text()
+
def setUp(self):
self.scratch = tempfile.TemporaryDirectory(prefix="openless-intent-ci-test-")
self.addCleanup(self.scratch.cleanup)
@@ -36,15 +52,19 @@ def raw(self):
{
"id": case["id"],
"input": SENTINEL,
- "old": {"text": SENTINEL, "elapsedMs": 12},
- "new": {"text": "https://private.invalid/" + SENTINEL, "elapsedMs": 15},
+ "old": {"text": "合成旧版正文。", "elapsedMs": 12},
+ "new": {"text": "合成新版正文。", "sourceText": "合成源文。", "elapsedMs": 15},
}
for case in self.evaluation["cases"]
],
}
- def execute(self, raw=None, returncode=0, exception=None, key=SENTINEL):
+ def execute(self, raw=None, returncode=0, exception=None, key=SENTINEL, certificate=None):
+ model_calls = []
def fake_process(argv, **kwargs):
+ if argv[0] != "/unused/test-binary":
+ return REAL_RUN(argv, **kwargs)
+ model_calls.append(argv)
self.assertEqual(argv, [
"/unused/test-binary", ci.TARGET, "--ignored", "--exact", "--test-threads=1"
])
@@ -52,6 +72,7 @@ def fake_process(argv, **kwargs):
self.assertEqual(kwargs["stderr"], subprocess.DEVNULL)
self.assertNotIn("DEEPSEEK_API_KEY", kwargs["env"])
self.assertNotIn("GITHUB_TOKEN", kwargs["env"])
+ self.assertNotIn("INTENT_RECIPIENT_CERTIFICATE", kwargs["env"])
config = self.private / "channel.json"
self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600)
settings = json.loads(config.read_text())
@@ -66,15 +87,28 @@ def fake_process(argv, **kwargs):
return subprocess.CompletedProcess(argv, returncode)
with patch.dict(os.environ, {
- "DEEPSEEK_API_KEY": key, "GITHUB_TOKEN": SENTINEL, "GITHUB_SHA": "a" * 40
+ "DEEPSEEK_API_KEY": key, "GITHUB_TOKEN": SENTINEL, "GITHUB_SHA": "a" * 40,
+ "INTENT_RECIPIENT_CERTIFICATE": (
+ self.certificate if certificate is None else certificate
+ ),
}):
- with patch.object(ci.subprocess, "run", side_effect=fake_process) as process:
+ with patch.object(ci.subprocess, "run", side_effect=fake_process):
code = ci.run("/unused/test-binary", self.private, self.evidence)
published = (self.evidence / "status.json").read_text()
self.assertNotIn(SENTINEL, published)
self.assertNotIn("private.invalid", published)
+ self.assertNotIn("合成旧版正文", published)
+ self.assertNotIn("合成新版正文", published)
self.assertEqual(list(self.private.iterdir()), [])
- return code, json.loads(published), process.call_count
+ if code == 0:
+ self.assertTrue((self.evidence / "comparison.cms").is_file())
+ else:
+ self.assertFalse((self.evidence / "review.json").exists())
+ self.assertEqual(
+ {path.name for path in self.evidence.iterdir()} - {"status.json", "comparison.cms"},
+ set(),
+ )
+ return code, json.loads(published), len(model_calls)
def test_success_uploads_only_canonical_fixtures_and_status(self):
code, report, calls = self.execute(self.raw())
@@ -85,6 +119,109 @@ def test_success_uploads_only_canonical_fixtures_and_status(self):
self.assertNotIn("credentials", report)
self.assertNotIn("text", report["cases"][0]["new"])
self.assertEqual(report["sourceSha"], "a" * 40)
+ self.assertEqual(report["encryptedReview"], "available")
+ output = Path(self.scratch.name) / "reviewed.json"
+ ci.decrypt_review(
+ self.evidence / "comparison.cms", str(self.cert), str(self.key), str(output)
+ )
+ review = json.loads(output.read_text())
+ self.assertEqual(review["cases"][0]["old"]["text"], "合成旧版正文。")
+ self.assertEqual(review["cases"][0]["new"]["sourceText"], "合成源文。")
+ self.assertNotIn(SENTINEL, output.read_text())
+ self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600)
+
+ def test_missing_recipient_fails_before_any_model_process(self):
+ code, report, calls = self.execute(certificate="")
+ self.assertEqual((code, calls), (1, 0))
+ self.assertEqual(report["executionStatus"], "recipient_invalid_or_crypto_unavailable")
+ self.assertFalse((self.evidence / "comparison.cms").exists())
+
+ def test_private_key_or_bad_certificate_is_rejected_before_model(self):
+ code, report, calls = self.execute(certificate=self.key.read_text())
+ self.assertEqual((code, calls), (1, 0))
+ self.assertEqual(report["executionStatus"], "recipient_invalid_or_crypto_unavailable")
+
+ def test_malformed_public_certificate_is_rejected_before_model(self):
+ code, _, calls = self.execute(
+ certificate="-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"
+ )
+ self.assertEqual((code, calls), (1, 0))
+
+ def test_sensitive_echo_is_rejected_and_no_plaintext_is_published(self):
+ raw = self.raw()
+ raw["cases"][0]["new"]["text"] = SENTINEL
+ code, report, calls = self.execute(raw)
+ self.assertEqual((code, calls), (1, 1))
+ self.assertEqual(report["executionStatus"], "review_rejected_or_encryption_failed")
+ self.assertFalse((self.evidence / "comparison.cms").exists())
+
+ def test_encoded_echo_and_abnormal_output_are_rejected(self):
+ for index, text in enumerate((
+ ci.base64.b64encode(SENTINEL.encode()).decode(),
+ "Authorization: Bearer hidden", "https://private.invalid/path",
+ "\x00", "x" * (ci.MAX_TEXT + 1),
+ )):
+ self.evidence = Path(self.scratch.name) / f"rejected-{index}"
+ raw = self.raw()
+ raw["cases"][0]["new"]["sourceText"] = text
+ code, report, _ = self.execute(raw)
+ self.assertEqual(code, 1)
+ self.assertEqual(report["executionStatus"], "review_rejected_or_encryption_failed")
+ self.assertFalse((self.evidence / "comparison.cms").exists())
+
+ def test_tampered_ciphertext_never_writes_decrypted_output(self):
+ self.execute(self.raw())
+ ciphertext = self.evidence / "comparison.cms"
+ data = bytearray(ciphertext.read_bytes())
+ data[-1] ^= 1
+ ciphertext.write_bytes(data)
+ output = Path(self.scratch.name) / "must-not-exist.json"
+ with self.assertRaises(ValueError):
+ ci.decrypt_review(ciphertext, str(self.cert), str(self.key), str(output))
+ self.assertFalse(output.exists())
+
+ def test_cms_uses_fresh_randomness(self):
+ plain = self.private / "dummy.json"
+ plain.write_bytes(b'{"dummy":true}')
+ first = self.private / "first.cms"
+ second = self.private / "second.cms"
+ ci.cms_encrypt(plain, first, self.cert)
+ ci.cms_encrypt(plain, second, self.cert)
+ self.assertNotEqual(first.read_bytes(), second.read_bytes())
+
+ def test_local_decrypt_rejects_unauthenticated_cms_before_private_key_use(self):
+ plain = self.private / "dummy.txt"
+ plain.write_bytes(b"non-sensitive fixture")
+ cipher = self.private / "cbc.cms"
+ ci.openssl([
+ "cms", "-encrypt", "-binary", "-aes-256-cbc", "-in", str(plain),
+ "-outform", "DER", "-out", str(cipher), str(self.cert)
+ ])
+ output = self.private / "must-not-exist.json"
+ with patch.object(ci, "openssl", wraps=ci.openssl) as operations:
+ with self.assertRaises(ValueError):
+ ci.decrypt_review(cipher, str(self.cert), str(self.key), str(output))
+ self.assertFalse(any("-decrypt" in call.args[0] for call in operations.call_args_list))
+ self.assertFalse(output.exists())
+
+ def test_encrypt_failure_cleans_plaintext_and_publishes_no_ciphertext(self):
+ real_encrypt = ci.cms_encrypt
+ calls = []
+ def fail_second(plain, cipher, certificate):
+ calls.append(plain)
+ if len(calls) == 1:
+ return real_encrypt(plain, cipher, certificate)
+ cipher.write_bytes(b"partial cipher")
+ raise ValueError(SENTINEL)
+ with patch.object(ci, "cms_encrypt", side_effect=fail_second):
+ code, report, _ = self.execute(self.raw())
+ self.assertEqual(code, 1)
+ self.assertEqual(report["executionStatus"], "review_rejected_or_encryption_failed")
+ self.assertFalse((self.evidence / "comparison.cms").exists())
+
+ def test_coordinator_can_check_dummy_recipient_without_paid_requests(self):
+ fingerprint = ci.check_recipient(str(self.cert), str(self.key))
+ self.assertRegex(fingerprint, "^[0-9a-f]{64}$")
def test_provider_failure_drops_error_and_retains_pending(self):
raw = self.raw()
@@ -149,6 +286,9 @@ def test_workflow_uses_only_trusted_manual_path_and_safe_artifact(self):
self.assertIn("trap 'rm -rf", live)
self.assertIn("inputs.live_acceptance != 'intent-style-comparison'", live)
self.assertIn("openless-intent-evidence/status.json", live)
+ self.assertIn("openless-intent-evidence/comparison.cms", live)
+ self.assertNotIn("openless-intent-evidence/*.json", live)
+ self.assertLess(live.index("preflight"), live.index("Build acceptance without credentials"))
self.assertIn("CARGO_TARGET_DIR: ${{ runner.temp }}/openless-live-target", live)
self.assertIn('rm -rf "$RUNNER_TEMP/openless-live-target"', live)
suite = SCRIPT.parent.parent / "crates/openless-core/src/deepseek_suite.rs"
From ad4af2be8fae8b17e2b3dd0cab1eb6071424b2c0 Mon Sep 17 00:00:00 2001
From: appergb <192432815+appergb@users.noreply.github.com>
Date: Fri, 27 Nov 2026 22:06:03 +0800
Subject: [PATCH 4/8] fix(ci): bind intent send budget and authorized dispatch
evidence
---
.github/workflows/ci.yml | 37 +++
docs/intent-style-evaluation.md | 92 +++----
.../openless-core/src/cloud_providers.rs | 2 +
.../openless-core/src/intent_style_tests.rs | 252 ++++++++++++++++--
.../app/crates/openless-core/src/polish.rs | 86 +++++-
.../app/scripts/intent-style-comparison-ci.py | 111 +++++++-
.../test_intent_style_comparison_ci.py | 119 ++++++++-
7 files changed, 602 insertions(+), 97 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 63acd8b31..e89b245c3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -29,6 +29,16 @@ on:
type: string
required: false
default: ''
+ intent_expected_source_sha:
+ description: Reviewed 40-character source/workflow SHA for intent comparison only
+ type: string
+ required: false
+ default: ''
+ intent_recipient_sha256:
+ description: Locally confirmed recipient certificate DER SHA256 for this single intent dispatch
+ type: string
+ required: false
+ default: ''
platform:
description: Platforms to check (macos runs only macOS gates)
type: choice
@@ -1311,6 +1321,10 @@ jobs:
if: inputs.live_acceptance == 'intent-style-comparison'
env:
INTENT_RECIPIENT_CERTIFICATE: ${{ inputs.intent_recipient_certificate }}
+ INTENT_RECIPIENT_SHA256: ${{ inputs.intent_recipient_sha256 }}
+ INTENT_EXPECTED_SOURCE_SHA: ${{ inputs.intent_expected_source_sha }}
+ INTENT_WORKFLOW_SHA: ${{ github.workflow_sha }}
+ INTENT_TRIGGERING_ACTOR: ${{ github.triggering_actor }}
run: python3 scripts/intent-style-comparison-ci.py preflight
- uses: dtolnay/rust-toolchain@stable
- name: Build acceptance without credentials
@@ -1322,6 +1336,25 @@ jobs:
trap 'rm -f "$build_manifest"' EXIT
cargo test --locked -p openless-core --lib -j 1 --no-run --message-format=json > "$build_manifest"
python3 scripts/intent-style-comparison-ci.py select-binary "$build_manifest" >> "$GITHUB_OUTPUT"
+ - name: Verify intent mock transport gates without provider credentials
+ if: inputs.live_acceptance == 'intent-style-comparison'
+ env:
+ INTENT_TEST_BINARY: ${{ steps.live-build.outputs.binary }}
+ run: |
+ set -euo pipefail
+ PYTHONDONTWRITEBYTECODE=1 python3 scripts/test_intent_style_comparison_ci.py
+ for name in \
+ intent_comparison_http_loop_32_and_36 \
+ intent_comparison_http_loop_stops_on_first_error \
+ intent_comparison_transport_budget_and_redirects \
+ intent_comparison_transport_connect_request_and_timeout_stop \
+ intent_comparison_legacy_limits_remain_independent; do
+ target="intent_style_tests::$name"
+ "$INTENT_TEST_BINARY" "$target" --exact --list | grep -Fx "$target: test" > /dev/null
+ done
+ "$INTENT_TEST_BINARY" intent_style_tests::intent_comparison_ --test-threads=1
+ target=intent_style_tests::intent_live_configured_channel_comparison
+ "$INTENT_TEST_BINARY" "$target" --ignored --exact --list | grep -Fx "$target: test" > /dev/null
- name: Run explicitly selected bounded acceptance
if: inputs.live_acceptance != 'intent-style-comparison'
env:
@@ -1343,6 +1376,10 @@ jobs:
DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
INTENT_TEST_BINARY: ${{ steps.live-build.outputs.binary }}
INTENT_RECIPIENT_CERTIFICATE: ${{ inputs.intent_recipient_certificate }}
+ INTENT_RECIPIENT_SHA256: ${{ inputs.intent_recipient_sha256 }}
+ INTENT_EXPECTED_SOURCE_SHA: ${{ inputs.intent_expected_source_sha }}
+ INTENT_WORKFLOW_SHA: ${{ github.workflow_sha }}
+ INTENT_TRIGGERING_ACTOR: ${{ github.triggering_actor }}
run: |
set -euo pipefail
umask 077
diff --git a/docs/intent-style-evaluation.md b/docs/intent-style-evaluation.md
index 2faf69c0e..8c8d0c0be 100644
--- a/docs/intent-style-evaluation.md
+++ b/docs/intent-style-evaluation.md
@@ -18,45 +18,19 @@ node scripts/intent-style-comparison.mjs /tmp/intent-comparison.json /tmp/intent
结果对象使用 `{"text":"最终正文","sourceText":"翻译前源文或 null","elapsedMs":123}`。失败时使用 `{"errorCode":"Provider"}`。离线渲染器不发请求、不读取凭据。
-## 获准后使用现有后处理渠道对照
-
-先获得真实调用许可,说明请求数:16 条 × 旧新版各一次 = 32 个主要请求;两个翻译样例若两版都缺少标记,现有纯翻译兜底最多再发 4 次,合计最多 36 次。无自动重试、无多渠道或多模型扫描,遇到首个渠道错误即停止并保留部分记录。
-
-提供的是被 `#[ignore]` 排除的测试 `intent_style_tests::intent_live_configured_channel_comparison`。它复用 `SharedCloudTextPolisher`、生产请求组装、协议、翻译解析与兜底路径,不自行创建另一个模型客户端。仅测试构造的内存凭据被使用,不修改应用设置、渠道、风格选择或请求参数。
-
-从用户已经配置的后处理渠道复制渠道 ID、协议类型、模型、思考开关、endpoint、API Key 和渠道级选项到仓库之外的私有 JSON 文件。不要把密钥写到命令行、日志、报告或 Git。以下仅描述字段形状,所有字段值均应来自同一现有渠道:
-
-```json
-{
- "channelId": "existing-channel-id",
- "providerType": "openai-compatible",
- "model": "existing-model-id",
- "thinkingEnabled": false,
- "baseline": "1.0.0",
- "credentials": {
- "ark.endpoint": "https://your-configured-endpoint.example/v1",
- "ark.api_key": "your-existing-key",
- "ark.request_format": "chat_completions"
- }
-}
-```
-
-`thinkingEnabled` 必须与现有配置一致,示例中的 `false` 不代表要求修改用户设置。`providerType` 和 `ark.request_format` 也应照抄,兼容渠道支持 `chat_completions`、`responses`、`messages`,也支持已有 Gemini API 渠道。需要时同时复制 `ark.temperature`、`ark.extra_headers`、`ark.messages_thinking`、`ark.max_tokens`、`ark.thinking_budget`、`ark.service_tier`;凭据值均为字符串,与 Core 存储一致。OAuth / ChatGPT Plan 渠道使用下方应用操作步骤,不由该测试隐式选取登录身份。
-
-旧基线默认由配置显式指定为反馈中的 `1.0.0`;也可填 `1.3.0` 对比当前 beta 实际运行版本。两者均使用不可变的发布快照。新版本为 `1.4.0`。为保持可比,两版使用同一当前组装器及全局口述修正规则;这不是复刻旧应用二进制。每条按旧版、新版顺序串行执行,未注入热词、应用或历史。选区专用指令放在独立的 `selection_instruction` 段,原文始终作为数据处理。
+## 本任务的真实对照范围
-获得许可、填好私有配置后执行(以下命令会真实调用渠道):
-
-```sh
-chmod 600 /private/path/intent-channel.json
-OPENLESS_INTENT_COMPARISON_APPROVED=yes \
-OPENLESS_INTENT_COMPARISON_CONFIG=/private/path/intent-channel.json \
-OPENLESS_INTENT_COMPARISON_OUTPUT=/tmp/intent-live-results.json \
-cargo test -p openless-core -j 1 intent_style_tests::intent_live_configured_channel_comparison -- --ignored --exact --test-threads=1
-node scripts/intent-style-comparison.mjs /tmp/intent-live-results.json /tmp/intent-live-results.md
-```
+唯一真实入口为默认 ignored 的 `intent_style_tests::intent_live_configured_channel_comparison`,
+只允许下方已授权官方 DeepSeek 配置、1.3.0 与 1.4.0,不接受另一个模型或本机渠道导出。
+生产组装、选区封套、翻译解析与兜底保持共用;测试独立作用域在共同实际发送边界计数,
+拒绝第 37 次 send,首个错误停止,无生产重试。隔离客户端禁重定向、协议重试与连接池
+复用;正常产品和旧 style/diagnostic/search 的路径不变。
-批准标志只是防误触门槛,不能代替调用前的用户许可。输出包含渠道 ID、请求模型、思考开关、基线版本、候选版本、原始输入、期望要点、源文、最终正文和耗时;不保存配置中的凭据。耗时为整个处理路径耗时,可能包括翻译兜底,并非单次首 token 延迟。该工具不将调用成功视作语义通过,也不声称服务端返回的实际模型与请求名称一致。
+本项目禁止本机 Cargo/编译。不要手工复制用户密钥或直接运行 ignored 测试;仅由协调者
+在 B1–B3 重审及目标云端 mock 门禁通过后,使用下方锁定来源与收件人的唯一手动模式。
+32 主请求加最多 4 翻译兜底是上限;安全证据另给实际 attemptedSends/fallbackSends。
+只有正常结束并写出 final 计数才可确证;超时、信号中止或不完整报告均记 unknown,
+不能用 32/36 常量当实际请求数,也不能无证据重跑。
## 在应用内手工对照
@@ -71,6 +45,9 @@ OAuth 渠道或不希望复制凭据时,在风格设置建立两个临时自
现有 `Optional official-provider live acceptance` 的非默认选项
`intent-style-comparison` 只接受 `Open-Less/openless` 仓库的 `main` / `beta`
分支手动运行。fork、PR、tag 和其他分支不进入带 secret 的 job;默认仍为 `off`。
+新模式还要求原 actor 为 `appergb`(稳定 ID `192432815`)、triggering actor
+同为 `appergb`、run attempt 严格为 1。身份来自 GitHub 上下文,不能通过 input 覆盖。
+官方 repo/ref 外的 skipped job 不等于验收通过;合法 ref 内的错误身份/SHA/指纹会显式失败。
不能运行只留下状态的旧入口:调用前必须有已在协调者本机验证的一次性公有收件人证书,
云端只接收该证书,私钥留在协调者本机。新增机制不增加模型请求或 App 构建。
@@ -90,20 +67,27 @@ CMS AuthEnvelopedData、AES-256-GCM 和 RSA-OAEP 的 OpenSSL,不在本任务
-subj /CN=OpenLess-intent-review \
-keyout "$review_dir/recipient.key" -out "$review_dir/recipient.crt"
chmod 600 "$review_dir/recipient.key" "$review_dir/recipient.crt"
- python3 scripts/intent-style-comparison-ci.py check-recipient \
- "$review_dir/recipient.crt" "$review_dir/recipient.key"
+ recipient_sha256=$(python3 scripts/intent-style-comparison-ci.py check-recipient \
+ "$review_dir/recipient.crt" "$review_dir/recipient.key")
+ recipient_sha256=${recipient_sha256#recipientSha256=}
```
在 `openless-all/app/` 运行 helper;固定无敏感内容的本地 roundtrip 成功时仅显示公有
`recipientSha256`。保留这个指纹、私钥与目录路径到审核结束,不在流水线生成私钥。
本地验证失败时不要继续,也不要把 private key 粘贴为 workflow input。
-2. 核对可信 ref 的锁定 SHA 和本地提交后,只执行一次下面的付费手动调用。
+2. 在已完成重审和云端 mock 的完整集成 checkout 记录审查 SHA;不能把未验的 worker
+ 候选当作可调用版本。下面 `git rev-parse HEAD` 必须是这一确切审查值。
+ 核对可信 ref 后,只执行一次下面的付费手动调用。
`-F` 的文件必须是 `.crt` 公有证书,绝不能是 `.key`:
```sh
+ expected_source_sha=$(git rev-parse HEAD)
+ test "$(gh api repos/Open-Less/openless/git/ref/heads/beta --jq .object.sha)" = "$expected_source_sha"
gh workflow run ci.yml --repo Open-Less/openless --ref beta \
-f live_acceptance=intent-style-comparison \
+ -f "intent_expected_source_sha=$expected_source_sha" \
+ -f "intent_recipient_sha256=$recipient_sha256" \
-F "intent_recipient_certificate=@$review_dir/recipient.crt"
```
@@ -112,28 +96,44 @@ CMS AuthEnvelopedData、AES-256-GCM 和 RSA-OAEP 的 OpenSSL,不在本任务
旧实际内置 **1.3.0** 对照 **1.4.0**,原 16 条夹具(12 听写/2 翻译/2 选区)
共 32 主请求,加最多 4 翻译兜底,总上限 36,首个渠道错误停止。
这不是用户本机渠道身份的证明,也不复刻旧应用二进制。
+ 无 secret 预检严格要求 event SHA、workflow SHA、checkout HEAD 与该 40 位小写 SHA
+ 全相等,并绑定官方 `.github/workflows/ci.yml@refs/heads/main|beta`。
+ 因而分支在核对与 dispatch 之间移动会在任何付费前失败,不能事后才发现。
+ 云端重新计算证书 DER 指纹,与已预确认的 `intent_recipient_sha256` 相等才允许继续。
+ 不使用 re-run;attempt 2 必定失败。代码不阻止授权者故意新建第二个 run,
+ “只 dispatch 一次”仍是本次授权边界,不能借新 run 重置预算。
3. 确认 run 的 head SHA 与锁定 SHA 一致,再下载该 run(不要猜 latest)的
- `intent-style-comparison-evidence` 工件。把下面 `RUN_ID` 替换成这一确切 run ID:
+ `intent-style-comparison-evidence` 工件。将此次确切 ID 填入 `run_id` 并保留来源记录,
+ 不选 latest、其他 attempt 或其他收件人的工件:
```sh
- gh run download RUN_ID --repo Open-Less/openless \
+ gh api "repos/Open-Less/openless/actions/runs/$run_id" \
+ --jq '{id,run_attempt,head_sha,event,path,actor,triggering_actor}' \
+ > "$review_dir/run.json"
+ gh run download "$run_id" --repo Open-Less/openless \
--name intent-style-comparison-evidence --dir "$review_dir/artifact"
python3 scripts/intent-style-comparison-ci.py decrypt \
"$review_dir/artifact/comparison.cms" "$review_dir/recipient.crt" \
- "$review_dir/recipient.key" "$review_dir/review.json"
+ "$review_dir/recipient.key" "$review_dir/review.json" \
+ "$expected_source_sha" "$run_id" "$recipient_sha256"
node scripts/intent-style-comparison.mjs \
"$review_dir/review.json" "$review_dir/review.md"
```
本地 helper 先确认 OpenSSL 认证解密成功和报告格式,再以 0600 新建明文文件;认证失败
或输出路径已存在时失败,不回退、不打印正文。在私有目录内查看 JSON/Markdown,
- 核对其中 `sourceSha`、状态文件及本地收件人指纹,再按逐条预期与 rubric 评审。
+ helper 在建文件前核对 exact run ID、attempt 1、source/workflow SHA、官方 workflow ref、
+ 固定 actor ID 和本机预确认指纹;不匹配即失败。还应核对下载的 run.json 来源记录与
+ 安全状态中的相同值,再按逐条预期与 rubric 评审。
旧新正文都是不可信数据,不执行其中的命令或点击其链接,不把审核文件发到公开评论。
审核结束按本地证据保留需求处理私钥和明文;删除私钥后无法恢复密文中的正文。
云端在无 secret 的 step 先验证证书与精确加密格式,再编译;空/坏证书在任何付费调用
-之前 fail closed。执行 step 再次预检;临时目录 0700、配置与白名单明文 0600,
+之前 fail closed。同一无 secret 阶段还验证来源、身份、attempt 和预确认指纹;
+编译后先执行 5 个本地 HTTP/mock 门禁(32/36/第 37 次、各首错、禁重定向和旧限额),
+并枚举精确 ignored live 测试,全部通过才进入 secret step。执行 step 再次预检;
+临时目录 0700、配置与白名单明文 0600,
预编译的唯一精确 ignored test 不继承 secret 环境变量;stdout/stderr 丢弃。
没有增加常跑 job、第二个测试或重试,普通 CI 路径不变。
@@ -151,6 +151,8 @@ Cargo/HTTP 日志。finally/trap 清理私有文件,always 清理专用 target
`status=completed` 或成功解密均不表示语义通过。缺密文时不要再次消耗预算,先核对
安全失败状态及已发请求;部分渠道失败仍可能留下经过同样检查和加密的部分对照。
+`transport.state=final` 的 attemptedSends/fallbackSends 才是本轮实际发送尝试计数;
+`unknown` 表示无法确证,禁止把固定上限当作可重跑额度。
密文完整性不是发送者签名,必须从锁定 SHA 的可信 GitHub run 取得并核对来源。
## 版本与迁移设计
diff --git a/openless-all/app/crates/openless-core/src/cloud_providers.rs b/openless-all/app/crates/openless-core/src/cloud_providers.rs
index 91b8dcbed..59b907af8 100644
--- a/openless-all/app/crates/openless-core/src/cloud_providers.rs
+++ b/openless-all/app/crates/openless-core/src/cloud_providers.rs
@@ -1549,6 +1549,8 @@ async fn run_cloud_polish(
"[cloud-provider] polish+translate response missing markers; using plain translation"
);
// No target section was published, so fallback starts at offset zero.
+ #[cfg(test)]
+ let _intent_fallback = crate::polish::live_acceptance::intent_fallback();
let stream = PolishStreamPublisher::new(
Arc::clone(&partials),
Arc::clone(&cancellation),
diff --git a/openless-all/app/crates/openless-core/src/intent_style_tests.rs b/openless-all/app/crates/openless-core/src/intent_style_tests.rs
index 23ac062be..91e4cc122 100644
--- a/openless-all/app/crates/openless-core/src/intent_style_tests.rs
+++ b/openless-all/app/crates/openless-core/src/intent_style_tests.rs
@@ -245,28 +245,26 @@ fn intent_stable_prefix_survives_hotwords_context_translation_and_custom_slots()
);
}
-/// No endpoint or key is selected implicitly; copy settings from the user's existing
-/// channel into a private config. Normal test runs never enter this function.
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+struct ComparisonConfig {
+ channel_id: String,
+ provider_type: String,
+ model: String,
+ thinking_enabled: bool,
+ baseline: String,
+ credentials: std::collections::BTreeMap,
+}
+
+/// Normal test runs never enter the approved official-channel comparison.
#[tokio::test]
#[ignore = "real configured-channel requests; approval and private config required"]
async fn intent_live_configured_channel_comparison() {
- use crate::credentials::{CredentialKey, CredentialNamespace, CredentialStore};
- use crate::ports::TextPolisher;
- #[derive(Deserialize)]
- #[serde(rename_all = "camelCase", deny_unknown_fields)]
- struct Config {
- channel_id: String,
- provider_type: String,
- model: String,
- thinking_enabled: bool,
- baseline: String,
- credentials: std::collections::BTreeMap,
- }
assert_eq!(
std::env::var("OPENLESS_INTENT_COMPARISON_APPROVED").as_deref(),
Ok("yes")
);
- let config: Config = serde_json::from_slice(
+ let config: ComparisonConfig = serde_json::from_slice(
&std::fs::read(
std::env::var("OPENLESS_INTENT_COMPARISON_CONFIG").expect("private config path"),
)
@@ -294,11 +292,25 @@ async fn intent_live_configured_channel_comparison() {
.is_some_and(|endpoint| !endpoint.trim().is_empty()),
"copy the existing channel endpoint explicitly; no implicit provider default"
);
- let old = match config.baseline.as_str() {
- "1.0.0" => original_intent_pack(),
- "1.3.0" => released_intent_v1_3_pack(),
- _ => panic!("baseline must be 1.0.0 or 1.3.0"),
- };
+ assert_eq!(config.provider_type, "deepseek");
+ assert_eq!(config.model, crate::deepseek_suite::MODEL);
+ assert!(!config.thinking_enabled);
+ assert_eq!(config.baseline, "1.3.0");
+ assert_eq!(
+ config.credentials.get(crate::credentials::LLM_ENDPOINT_ACCOUNT).map(String::as_str),
+ Some(crate::deepseek_suite::ENDPOINT),
+ );
+ let report = crate::polish::live_acceptance::intent_scope(
+ run_intent_comparison(&config, &output_path),
+ ).await;
+ assert_eq!(report["executionStatus"], "completed", "comparison stopped; safe report retained");
+}
+
+// The same loop is exercised against a local HTTP fixture by the non-live tests.
+async fn run_intent_comparison(config: &ComparisonConfig, output_path: &str) -> Value {
+ use crate::credentials::{CredentialKey, CredentialNamespace, CredentialStore};
+ use crate::ports::TextPolisher;
+ let old = released_intent_v1_3_pack();
let new = builtin_intent_pack();
let evaluation = evaluation();
let store = std::sync::Arc::new(crate::InMemoryCredentialStore::default());
@@ -327,6 +339,8 @@ async fn intent_live_configured_channel_comparison() {
"schemaVersion": 1, "channelId": config.channel_id, "providerType": config.provider_type,
"requestedModel": config.model, "thinkingEnabled": config.thinking_enabled,
"baselineVersion": old.version, "candidateVersion": new.version,
+ "executionStatus": "running",
+ "transport": {"state": "running"},
"provenance": evaluation.provenance, "semanticReview": "pending human review",
"cases": evaluation.cases.iter().map(|case| json!({
"id": case.id, "input": case.input, "operation": case.operation,
@@ -344,7 +358,7 @@ async fn intent_live_configured_channel_comparison() {
file.write_all(&serde_json::to_vec_pretty(&report).unwrap())
.unwrap();
drop(file);
- for (index, case) in evaluation.cases.iter().enumerate() {
+ 'cases: for (index, case) in evaluation.cases.iter().enumerate() {
for (side, pack) in [("old", &old), ("new", &new)] {
let mut context = case_context(pack, case);
context.llm = crate::ProviderInvocation::for_provider(&config.provider_type);
@@ -367,12 +381,198 @@ async fn intent_live_configured_channel_comparison() {
}),
Err(error) => json!({"errorCode": format!("{:?}", error.code)}),
};
- std::fs::write(&output_path, serde_json::to_vec_pretty(&report).unwrap()).unwrap();
- assert!(
- result.is_ok(),
- "{} {side}: channel failed; partial report retained",
- case.id
+ let mut counts = crate::polish::live_acceptance::intent_counts();
+ counts["state"] = json!("running");
+ report["transport"] = counts;
+ std::fs::write(output_path, serde_json::to_vec_pretty(&report).unwrap()).unwrap();
+ if result.is_err() {
+ report["executionStatus"] = json!("failed");
+ break 'cases;
+ }
+ }
+ }
+ if report["executionStatus"] == "running" {
+ report["executionStatus"] = json!("completed");
+ }
+ let mut counts = crate::polish::live_acceptance::intent_counts();
+ counts["state"] = json!("final");
+ report["transport"] = counts;
+ std::fs::write(output_path, serde_json::to_vec_pretty(&report).unwrap()).unwrap();
+ report
+}
+
+// These are local HTTP fixtures, never provider calls. They use the exact loop,
+// production assembly, translation fallback and common send boundary above.
+async fn comparison_mock(fallback: bool, failure: Option<(usize, bool)>) -> (Value, usize) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let endpoint = format!("http://{}/v1", listener.local_addr().unwrap());
+ let (stop, mut stopping) = tokio::sync::oneshot::channel::<()>();
+ let server = tokio::spawn(async move {
+ let mut seen = 0;
+ loop {
+ let accepted = tokio::select! {
+ _ = &mut stopping => break,
+ accepted = listener.accept() => accepted.unwrap(),
+ };
+ let mut socket = accepted.0;
+ let mut request = Vec::new();
+ let mut buffer = [0_u8; 4096];
+ loop {
+ let count = socket.read(&mut buffer).await.unwrap();
+ if count == 0 { break; }
+ request.extend_from_slice(&buffer[..count]);
+ if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
+ let headers = String::from_utf8_lossy(&request[..end]);
+ let length = headers.lines().find_map(|line| {
+ line.to_ascii_lowercase().strip_prefix("content-length:")
+ .and_then(|value| value.trim().parse::().ok())
+ }).unwrap();
+ if request.len() >= end + 4 + length { break; }
+ }
+ }
+ seen += 1;
+ if failure == Some((seen, true)) {
+ // A request/read error that the production retry arm would retry.
+ drop(socket);
+ continue;
+ }
+ let content = if fallback {
+ "fixture output"
+ } else {
+ "[[OPENLESS_POLISHED_SOURCE]]\n源文。\n[[OPENLESS_TRANSLATION]]\nTranslation."
+ };
+ let event = json!({"choices":[{"delta":{"content":content}}]});
+ let body = format!("data: {event}\n\ndata: [DONE]\n\n");
+ let status = if failure == Some((seen, false)) { 500 } else { 200 };
+ let response = format!(
+ "HTTP/1.1 {status} fixture\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len(),
);
+ socket.write_all(response.as_bytes()).await.unwrap();
}
+ seen
+ });
+ struct Scratch(std::path::PathBuf);
+ impl Drop for Scratch {
+ fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); }
+ }
+ let scratch = Scratch(std::env::temp_dir().join(format!("intent-mock-{}", uuid::Uuid::new_v4())));
+ std::fs::create_dir(&scratch.0).unwrap();
+ let output = scratch.0.join("results.json");
+ let config = ComparisonConfig {
+ channel_id: "fixture".into(), provider_type: "deepseek".into(),
+ model: crate::deepseek_suite::MODEL.into(), thinking_enabled: false, baseline: "1.3.0".into(),
+ credentials: [
+ ("ark.api_key".into(), "fixture-key".into()),
+ ("ark.endpoint".into(), endpoint),
+ ].into_iter().collect(),
+ };
+ let report = crate::polish::live_acceptance::intent_scope(
+ run_intent_comparison(&config, output.to_str().unwrap()),
+ ).await;
+ stop.send(()).unwrap();
+ (report, server.await.unwrap())
+}
+
+#[tokio::test]
+async fn intent_comparison_http_loop_32_and_36() {
+ for (fallback, expected) in [(false, 32), (true, 36)] {
+ let (report, seen) = comparison_mock(fallback, None).await;
+ assert_eq!(report["executionStatus"], "completed");
+ assert_eq!(seen, expected);
+ assert_eq!(report["transport"]["attemptedSends"], expected);
+ assert_eq!(report["transport"]["fallbackSends"], if fallback { 4 } else { 0 });
+ assert_eq!(report["transport"]["state"], "final");
+ }
+}
+
+#[tokio::test]
+async fn intent_comparison_http_loop_stops_on_first_error() {
+ for (fallback, failure, expected_fallbacks) in [
+ (false, (1, true), 0), (false, (1, false), 0),
+ (true, (24, false), 1), (true, (24, true), 1),
+ ] {
+ let (report, seen) = comparison_mock(fallback, Some(failure)).await;
+ assert_eq!(report["executionStatus"], "failed");
+ assert_eq!(seen, failure.0);
+ assert_eq!(report["transport"]["attemptedSends"], failure.0);
+ assert_eq!(report["transport"]["fallbackSends"], expected_fallbacks);
+ }
+}
+
+#[tokio::test]
+async fn intent_comparison_transport_budget_and_redirects() {
+ use crate::polish::{live_acceptance as probe, send_with_transient_retry as send};
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ probe::intent_scope(async {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ for _ in 0..36 {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut buffer = [0_u8; 4096];
+ socket.read(&mut buffer).await.unwrap();
+ socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await.unwrap();
+ }
+ assert!(tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept()).await.is_err());
+ });
+ let client = probe::intent_client(&url, 1);
+ for _ in 0..36 { send(client.post(&url)).await.unwrap(); }
+ assert!(send(client.post(&url)).await.is_err());
+ assert_eq!(probe::intent_counts()["attemptedSends"], 36);
+ server.await.unwrap();
+ }).await;
+ probe::intent_scope(async {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let redirect = format!("{url}/must-not-follow");
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut buffer = [0_u8; 4096];
+ socket.read(&mut buffer).await.unwrap();
+ socket.write_all(format!("HTTP/1.1 307 Temporary Redirect\r\nLocation: {redirect}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").as_bytes()).await.unwrap();
+ assert!(tokio::time::timeout(std::time::Duration::from_millis(50), listener.accept()).await.is_err());
+ });
+ let client = probe::intent_client(&url, 1);
+ assert_eq!(send(client.post(&url)).await.unwrap().status(), 307);
+ assert!(send(client.post(&url)).await.is_err());
+ assert_eq!(probe::intent_counts()["attemptedSends"], 1);
+ server.await.unwrap();
+ }).await;
+}
+
+#[tokio::test]
+async fn intent_comparison_transport_connect_request_and_timeout_stop() {
+ use crate::polish::{live_acceptance as probe, send_with_transient_retry as send};
+ // A closed port (connect) and invalid URI (request building) cannot retry.
+ for invalid_uri in [false, true] {
+ probe::intent_scope(async {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ drop(listener);
+ let client = probe::intent_client(&url, 1);
+ assert!(send(client.post(if invalid_uri { "http://[" } else { &url })).await.is_err());
+ assert!(send(client.post(&url)).await.is_err());
+ assert_eq!(probe::intent_counts()["attemptedSends"], 1);
+ }).await;
}
+ probe::intent_scope(async {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let client = probe::intent_client(&url, 1);
+ assert!(tokio::time::timeout(
+ std::time::Duration::from_millis(20), send(client.post(&url)),
+ ).await.is_err());
+ assert!(send(client.post(&url)).await.is_err());
+ assert_eq!(probe::intent_counts()["attemptedSends"], 1);
+ }).await;
+}
+
+#[test]
+fn intent_comparison_legacy_limits_remain_independent() {
+ let probe = crate::polish::live_acceptance::legacy_limit;
+ assert_eq!(probe(false), 10);
+ assert_eq!(probe(true), 1);
+ assert!(!crate::polish::live_acceptance::intent_active());
}
diff --git a/openless-all/app/crates/openless-core/src/polish.rs b/openless-all/app/crates/openless-core/src/polish.rs
index 62502b9cc..52fd14334 100644
--- a/openless-all/app/crates/openless-core/src/polish.rs
+++ b/openless-all/app/crates/openless-core/src/polish.rs
@@ -594,12 +594,22 @@ impl OpenAICompatibleLLMProvider {
let no_proxy =
crate::net::should_bypass_proxy(&config.base_url, crate::net::use_system_proxy());
let polish_base_url = config.base_url.clone();
- let polish_client =
+ let cached_client = ||
crate::net::cached_client((POLISH_CLIENT_HARD_CAP_SECS, no_proxy), || {
http_client_builder(&polish_base_url, POLISH_CLIENT_HARD_CAP_SECS)
.build()
.unwrap_or_else(|_| reqwest::Client::new())
});
+ // The comparison must never reuse a production client's pool, redirects,
+ // or protocol retry policy. Other tests and production keep the cache.
+ #[cfg(test)]
+ let polish_client = if live_acceptance::intent_active() {
+ live_acceptance::intent_client(&polish_base_url, POLISH_CLIENT_HARD_CAP_SECS)
+ } else {
+ cached_client()
+ };
+ #[cfg(not(test))]
+ let polish_client = cached_client();
Self {
config,
qa_web_search: false,
@@ -1921,6 +1931,13 @@ fn should_retry_transient(is_connect: bool, is_request: bool, is_timeout: bool)
pub(crate) async fn send_with_transient_retry(
request: reqwest::RequestBuilder,
) -> Result {
+ #[cfg(test)]
+ if live_acceptance::intent_active() {
+ let mut send = live_acceptance::intent_before_send()?;
+ let response = request.send().await.map_err(llm_error_from_reqwest);
+ send.succeeded = response.as_ref().is_ok_and(|response| response.status().is_success());
+ return response;
+ }
#[cfg(test)]
if live_acceptance::active() {
let attempt = live_acceptance::before_send()?;
@@ -5746,15 +5763,78 @@ mod tests {
// and observes the public response model without retaining raw SSE or reasoning.
#[cfg(test)]
pub(crate) mod live_acceptance {
- use std::sync::{atomic::{AtomicBool, AtomicUsize, Ordering}, Mutex};
+ use std::sync::{atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, Mutex};
+ tokio::task_local! {
+ static INTENT: Arc>;
+ }
+ #[derive(Default)]
+ struct IntentState {
+ sends: usize,
+ fallbacks: usize,
+ in_fallback: bool,
+ stopped: bool,
+ }
+ pub async fn intent_scope(future: F) -> F::Output {
+ INTENT.scope(Arc::new(Mutex::new(IntentState::default())), future).await
+ }
+ pub fn intent_active() -> bool { INTENT.try_with(|_| ()).is_ok() }
+ pub fn intent_client(base_url: &str, timeout_secs: u64) -> reqwest::Client {
+ super::http_client_builder(base_url, timeout_secs)
+ .no_proxy()
+ .redirect(reqwest::redirect::Policy::none())
+ .retry(reqwest::retry::never())
+ .http1_only()
+ .pool_max_idle_per_host(0)
+ .build()
+ .expect("isolated intent transport")
+ }
+ pub struct IntentSend {
+ state: Arc>,
+ pub succeeded: bool,
+ }
+ impl Drop for IntentSend {
+ fn drop(&mut self) {
+ if !self.succeeded { self.state.lock().unwrap().stopped = true; }
+ }
+ }
+ pub fn intent_before_send() -> Result {
+ let state = INTENT.with(Arc::clone);
+ {
+ let mut current = state.lock().unwrap();
+ if current.stopped || current.sends >= 36 {
+ return Err(super::LLMError::Network("intent comparison stopped or budget exhausted".into()));
+ }
+ current.sends += 1;
+ if current.in_fallback { current.fallbacks += 1; }
+ }
+ Ok(IntentSend { state, succeeded: false })
+ }
+ pub struct IntentFallback(Option>>);
+ impl Drop for IntentFallback {
+ fn drop(&mut self) {
+ if let Some(state) = &self.0 { state.lock().unwrap().in_fallback = false; }
+ }
+ }
+ pub fn intent_fallback() -> IntentFallback {
+ let state = INTENT.try_with(Arc::clone).ok();
+ if let Some(state) = &state { state.lock().unwrap().in_fallback = true; }
+ IntentFallback(state)
+ }
+ pub fn intent_counts() -> serde_json::Value {
+ INTENT.with(|state| {
+ let current = state.lock().unwrap();
+ serde_json::json!({"attemptedSends": current.sends, "fallbackSends": current.fallbacks})
+ })
+ }
static ACTIVE: AtomicBool = AtomicBool::new(false);
static SENDS: AtomicUsize = AtomicUsize::new(0);
static RESPONSE_MODEL: Mutex