diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index 57f7f3f3a9..8977935e3d 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -182,7 +182,19 @@ jobs: - name: Verify native Keychain across processes run: cargo run --locked --manifest-path src-tauri/Cargo.toml --example credential_probe - name: Build unsigned macOS app and DMG - run: pnpm desktop:build + run: | + mkdir -p .artifacts + set -o pipefail + pnpm tauri build --ci --verbose -- --locked 2>&1 | tee .artifacts/macos-build.log + - name: Upload failed macOS build diagnostics + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: desktop-macos-${{ matrix.runner }}-build-diagnostics + path: | + desktop/.artifacts/macos-build.log + desktop/src-tauri/target/release/bundle/dmg/bundle_dmg.sh + if-no-files-found: warn - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: desktop-macos-${{ matrix.runner }}-internal-unsigned diff --git a/desktop/README.md b/desktop/README.md index 30c82e1a89..296547a9c1 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -96,9 +96,21 @@ Search uses FTS in the selected Scope and returns at most 10 matches. This is no A successful save that returns no memory record is reported as an operation success without inventing a reference. A timeout or interrupted dispatched write is **unknown**, not a safe invitation to retry: inspect the original Server/Scope before deciding whether to submit again. Identical text alone cannot identify that operation. Desktop does not automatically replay writes or keep an offline queue. Switching context hides old results while retaining minimal original-operation metadata for this session. See [validation guide](VALIDATION.md) for tested behavior and qualification gaps. +## Native discovery results + +Connection checks call the public `get_server_info` operation through the existing native transport. `CheckReport.discovery` reports `supported`, `missing`, `denied`, `unavailable`, `invalid`, or `incompatible`, the observed Server metadata, safe errors, and per-operation `qualified`/`unsupported`/`unverified` results with reasons. Compatible discovery minor versions accept additional optional fields in the response and its nested version/feature objects. + +Qualification still requires an explicitly selected native record matching the bundled contract. A discovery 404 permits that record's independently qualified legacy operations; 401, 403, 503, malformed responses and incompatible products/required majors do not select a legacy fallback. Missing feature groups, unsupported feature versions and absent operation IDs restrict the affected operations. Exact Artifact reads require their own qualification; the `memory.explicit` group does not establish that support. Discovery metadata never grants authorization or attests a remote binary. + +Connection checks and anonymous identity revalidation still perform readiness probes. The observed `server_id` is recorded with the check; deployment-aware context fencing and explicit readiness separation are not established by this discovery result. + +Connections displays discovery separately from the compatibility verdict, with guidance for denied or temporarily unavailable discovery and the reason for an incompatible product or major version. A failed discovery check keeps business operations unavailable; it does not remove the selected qualification record. After correcting the connection or service, explicitly check the connection again to reassess operation availability. Only a discovery 404 permits the qualified legacy policy described above. + +Save, search, exact revision reads, Scope lookup and Scope selection each require their own entry in `supportedOperations`; the aggregate compatibility verdict does not enable other operations. An unavailable action explains missing features, unsupported feature versions, missing operation support or missing independent qualification. Independently supported actions remain usable, and Overview shows availability for each Memory feature. Native request-time authorization and compatibility checks remain authoritative. + ## Contracts and resources -`pnpm --dir desktop generate` derives TypeScript schemas, the reviewed ten-operation manifest, and the Rust wire models from `openapi/powercontext.yaml`; `generate:check` detects drift, including a normalized contract SHA-256. The OpenAPI Generator CLI version is pinned in `desktop/openapitools.json`, and the limited Rust customization lives in `desktop/scripts/openapi-generator/rust/`. Generated `src-tauri/src/transport/wire.rs` must not be edited by hand: after changing the contract or generator template, run `pnpm --dir desktop generate`, then run `pnpm --dir desktop generate:check` in CI. Typed Rust adapters consume that generated manifest and generated wire schemas. No public route is independently handwritten in the application. The manifest is not an IPC permission grant. +`pnpm --dir desktop generate` derives TypeScript schemas, the reviewed eleven-operation manifest, and the Rust wire models from `openapi/powercontext.yaml`; `generate:check` detects drift, including a normalized contract SHA-256. The OpenAPI Generator CLI version is pinned in `desktop/openapitools.json`, and the limited Rust customization lives in `desktop/scripts/openapi-generator/rust/`. Generated `src-tauri/src/transport/wire.rs` must not be edited by hand: after changing the contract or generator template, run `pnpm --dir desktop generate`, then run `pnpm --dir desktop generate:check` in CI. Typed Rust adapters consume that generated manifest and generated wire schemas. No public route is independently handwritten in the application. The manifest is not an IPC permission grant. `cargo run --locked --manifest-path desktop/src-tauri/Cargo.toml --example export_ipc` derives the TypeScript IPC request/receipt/error types from Rust. `ipc:check` verifies them. IPC exposes typed connection, Scope, memory and diagnostic operations to the main window only; no generic fetch, shell, file, database or secret-read command is granted. @@ -150,7 +162,7 @@ Installed boundary checks exercise an 8192-byte Unicode note, reject over-budget After upgrading from an earlier preview, open Connections and select your saved connection. Profiles matching the bundled API contract appear under “Available for this Desktop build”; compare their tested Server builds with your deployment before selecting one, saving, checking and explicitly using the connection again. New connections start with no compatibility selection. -Historical profiles appear as disabled records. A saved incompatible or unavailable selection remains visible with an explanation until explicitly replaced; it is never silently upgraded. For the qualified current Server sources, explicitly choose `sqlite-atomic-dd62723d-v1` and check the connection before selecting a Scope; that record's contract digest matches this build's bundled contract, while `sqlite-atomic-98275dbb-v1`, `sqlite-atomic-1da99747-v1`, `sqlite-atomic-8f10c560-v1`, `sqlite-atomic-d9a78567-v1`, `sqlite-atomic-caf2a35a-v1`, `sqlite-atomic-683e2db0-v1` and `sqlite-atomic-cab054db-v1` qualify their corresponding Server source deployments and do not match it. The recorded Server source and wheel identities must match the deployment you intend to use. The independently qualified `ci-fixtures` build is for disposable acceptance tests. Historical qualification evidence and remaining requirements are documented in the [validation guide](VALIDATION.md). +Historical profiles appear as disabled records. A saved incompatible or unavailable selection remains visible with an explanation until explicitly replaced; it is never silently upgraded. For qualified current Server sources, explicitly choose `sqlite-atomic-dd62723d-v1` or `sqlite-atomic-4ffdf4e9-v1` according to the recorded Server sources and wheel, then check the connection before selecting a Scope. Both records match this bundled contract and retain their independently verified operation sets. Historical profiles, including `sqlite-atomic-c535d816-v1`, retain their original Server sources, contracts and operation sets and do not match this bundled contract. The recorded Server source and wheel identities must match the deployment you intend to use. The independently qualified `ci-fixtures` build is for disposable acceptance tests. Historical qualification evidence and remaining requirements are documented in the [validation guide](VALIDATION.md). ## Build on macOS diff --git a/desktop/README.zh.md b/desktop/README.zh.md index e916063635..026cc31f72 100644 --- a/desktop/README.zh.md +++ b/desktop/README.zh.md @@ -74,9 +74,21 @@ pnpm --dir desktop desktop:dev 连接配置存放在应用数据目录,JSON 不包含秘密。重启后需要重新验证连接和选择范围;仅会话凭据不保留。移除连接仅移除此桌面的配置和自有凭据,不停止 Server 或删除业务数据。 +## 原生发现结果 + +连接检查通过现有原生传输调用公开的 `get_server_info`。`CheckReport.discovery` 返回 `supported`、`missing`、`denied`、`unavailable`、`invalid` 或 `incompatible`,并包含观察到的 Server 元数据、安全错误,以及逐项操作的 `qualified`/`unsupported`/`unverified` 状态和原因。兼容的发现协议 minor 版本可增加响应及其嵌套版本、功能对象的可选字段。 + +操作资格仍要求明确选择与当前契约匹配的原生验证记录。仅发现接口的 404 允许沿用该记录已独立验证的旧版操作;401、403、503、无效响应、不兼容产品或必要 major 版本不会触发旧版回退。缺失功能组、不支持的功能版本和缺失 operation ID 分别限制受影响的操作。Artifact 精确读取需要独立资格,不能从 `memory.explicit` 推断。发现元数据不授予权限,也不证明远端二进制身份。 + +当前连接检查和匿名身份复核仍会调用 readiness。检查结果记录观察到的 `server_id`;这不代表已经实现部署身份隔离或显式 readiness 分离。 + +连接页分别展示发现状态和兼容性结论,说明访问被拒绝、暂时不可用时的恢复方法,以及产品或 major 版本不兼容的原因。发现检查失败时业务操作保持不可用,但不会删除已选择的资格记录。修正连接或服务后,须明确重新检查连接,重新判定操作可用性。仅发现接口的 404 适用上述已验证旧版策略。 + +保存、搜索、精确版本读取、范围查找和范围选择分别要求 `supportedOperations` 包含各自的操作,总体兼容性结论不会启用其他操作。不可用的操作会说明功能缺失、功能版本不兼容、未声明操作支持或缺少独立验证记录的原因。其他独立支持的操作仍可使用,总览也逐项展示记忆功能的可用性。原生层在请求时执行的授权和兼容性检查仍是最终依据。 + 工程边界: -- OpenAPI 自动派生的 TypeScript schema 和十项 operation 映射,包含契约摘要及漂移检查。 +- OpenAPI 自动派生的 TypeScript schema 和十一项 operation 映射,包含契约摘要及漂移检查。 - `desktop/openapitools.json` 固定 OpenAPI Generator CLI 版本,Rust 模板位于 `desktop/scripts/openapi-generator/rust/`。修改 OpenAPI 合同或模板后,在仓库根目录执行 `pnpm --dir desktop generate`,不要手动编辑生成的 `src-tauri/src/transport/wire.rs`;CI 通过 `pnpm --dir desktop generate:check` 检查生成结果是否漂移。 - Rust 自动派生的 IPC 类型与安全错误;凭据只写请求必须显式选择持久化或仅会话,成功回执只含存储模式,不含秘密或凭据标识。 - Windows Credential Manager 原生适配器;保存失败直接报错,只有显式选择才采用仅会话内存。秘密类型不支持序列化,不实现 Debug。 @@ -133,7 +145,7 @@ Windows GitHub Actions 会构建未签名安装包,安装到临时中文路径 从早期预览版升级后,请打开「连接」并选中已保存的连接。与当前 API 契约匹配的配置显示在「此 Desktop 构建可用」中;先核对已测试的 Server 构建与实际部署,再明确选择、保存、检查并使用该连接。新连接默认不选择兼容配置。 -历史配置显示为不可选择的记录。已保存的不匹配或不可用配置仍会显示并说明原因,须明确替换,不会静默升级。对于已资格化的当前 Server 源码,明确选择 `sqlite-atomic-dd62723d-v1` 并在选取范围前检查连接;该记录的契约摘要与本构建的打包契约匹配,而 `sqlite-atomic-98275dbb-v1`、`sqlite-atomic-1da99747-v1`、`sqlite-atomic-8f10c560-v1`、`sqlite-atomic-d9a78567-v1`、`sqlite-atomic-caf2a35a-v1`、`sqlite-atomic-683e2db0-v1` 与 `sqlite-atomic-cab054db-v1` 只资格化各自对应 Server 源码的部署,并不匹配打包契约。已记录的 Server 源码和 wheel 身份必须与实际部署一致。独立验证的 `ci-fixtures` 构建仅用于临时验收测试。历史资格证据和剩余要求见[验证说明](VALIDATION.md)。 +历史配置显示为不可选择的记录。已保存的不匹配或不可用配置仍会显示并说明原因,须明确替换,不会静默升级。对于已资格化的当前 Server 源码,请按记录的 Server 源码和 wheel 明确选择 `sqlite-atomic-dd62723d-v1` 或 `sqlite-atomic-4ffdf4e9-v1`,检查连接后再选择范围。两项记录均匹配本构建的契约,并保留各自独立验证的操作集合。包括 `sqlite-atomic-c535d816-v1` 在内的历史配置保留原有 Server 源码、契约和操作集合,不匹配本构建的打包契约。已记录的 Server 源码和 wheel 身份必须与实际部署一致。独立验证的 `ci-fixtures` 构建仅用于临时验收测试。历史资格证据和剩余要求见[验证说明](VALIDATION.md)。 ## 在 macOS 上构建 diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 6d22245ac1..5f98d5c2ba 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -20,9 +20,17 @@ cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml [Desktop CI](../.github/workflows/desktop.yml) also builds a Server wheel, runs real Server and CLI tests, checks Windows credentials and process containment, builds the installer, and exercises installation, the installed UI and uninstallation. Consult the PR checks for the exact commit being reviewed. Reports, logs and screenshots are generated under ignored `.artifacts/` and uploaded as Actions artifacts; do not copy them into the repository. +## Native discovery acceptance + +The native `get_server_info` adapter and full real-Server harness were exercised on Windows x64 on 2026-10-23 with Rust 1.95.0 and Python 3.11.15. The Server sources, project configuration and lock matched baseline commit `c535d816`; the wheel was built at Desktop commit `f2b442fc41f724e206a50f2415a03476abdcdf76` with an unrelated dirty documentation tree. The wheel `powercontext-1.4.1.dev138+gf2b442fc4.d20261023-py3-none-any.whl` had SHA-256 `677812c860dd6f12866afa3b6b3e2e0529a6d37b427187c0ce4f3cd732349551`; the normalized contract digest was `5878999ce9e239d6642e4da858074b281ed465629432c578b3584eec47cbce6c`. All four isolated SQLite Server configurations passed: anonymous loopback, static Bearer, HTTPS with an explicit CA and reverse-proxy base path, and an enforced authentication Provider. Checks covered discovery, Scope selection, Memory save/search/exact revision reads, Principal changes, same-Principal revocation, uncertain writes without replay, pagination and independent Server survival. The Server environment included the declared `jieba==0.42.1` dependency. Results are recorded under ignored `.artifacts/real-server.json`. + +The native suite passed all 61 tests, including synthetic HTTP regressions for missing/denied/unavailable/invalid/incompatible discovery, optional-field additions, operation membership, duplicate deployment-identity fields, qualification isolation, cancellation, credentials and uncertain writes. A synthetic HTTP regression verifies that a qualified connection blocks Scope requests after discovery returns 503 and allows them again after an explicit successful recheck. The bundled-product qualification test also exercised explicit Scope browsing through the normal manager. All 116 frontend tests passed, including distinct bilingual discovery diagnostics, replacement of a temporary-failure diagnostic after a successful recheck, and per-operation Memory/Scope gating with restriction reasons while independently supported operations remain available, including exact-read gating for records returned by a save. Clippy with `--all-targets -- -D warnings`, Rust formatting, generated contract drift, IPC export drift, frontend lint/type checks/build and seven focused Python contract/fixture tests passed. Generation was executed from a Windows checkout whose path contains a space. Repository hooks passed except default Windows `ty check`, which reported POSIX-only attributes in unchanged Python modules; `ty check --python-platform linux` passed. Synthetic HTTP and UI fixtures establish local status/recovery handling, not installed-host or release acceptance. + +The historical Server c535d816 protocol qualification below records the specific source, wheel and operation identities independently of the CI-only fixture. It does not establish installed UI or release acceptance. The focused `server_probe discovery-only` mode calls discovery without readiness or Memory requests and accepts the full probe's fixture format. Historical product records remain unchanged; the locally generated qualification file is a CI-only fixture. This historical discovery qualification retains its original contract digest; the current-contract records retain their ten independently qualified operations and do not add discovery qualification. Deployment-aware read/write fencing, explicit readiness separation, local setup approval handoff and installed Windows/macOS qualification remain separate acceptance requirements. + ## Compatibility scope -[compatibility.json](src-tauri/src/connections/compatibility.json) preserves the recorded Server sources, normalized OpenAPI contract digests and qualification-wheel digests for the historical profiles below. The current contract has source-specific qualifications `sqlite-atomic-dd62723d-v1` and `sqlite-atomic-4ffdf4e9-v1` below. Ordinary builds require explicitly selecting the record whose tested Server source and wheel match the deployment, then checking the connection before business operations become available. The `dd62723d` record covers the migration-framework sources; the `4ffdf4e9` record covers the earlier release-preparation sources. The `sqlite-atomic-98275dbb-v1`, `sqlite-atomic-1da99747-v1`, `sqlite-atomic-8f10c560-v1`, `sqlite-atomic-d9a78567-v1`, `sqlite-atomic-caf2a35a-v1`, `sqlite-atomic-683e2db0-v1` and `sqlite-atomic-cab054db-v1` records qualify their corresponding Server source deployments and do not match this bundled contract. Historical records are disabled in the selector, and saved unavailable selections remain visible until explicitly replaced. CI builds have their own artifact identities and do not change product qualification. +[compatibility.json](src-tauri/src/connections/compatibility.json) preserves the recorded Server sources, normalized OpenAPI contract digests and qualification-wheel digests for the historical profiles below. The current contract has source-specific qualifications `sqlite-atomic-dd62723d-v1` and `sqlite-atomic-4ffdf4e9-v1` below. Ordinary builds require explicitly selecting the record whose tested Server source and wheel match the deployment, then checking the connection before business operations become available. The `dd62723d` record covers the migration-framework sources; the `4ffdf4e9` record covers the earlier release-preparation sources. The `sqlite-atomic-c535d816-v1`, `sqlite-atomic-98275dbb-v1`, `sqlite-atomic-1da99747-v1`, `sqlite-atomic-8f10c560-v1`, `sqlite-atomic-d9a78567-v1`, `sqlite-atomic-caf2a35a-v1`, `sqlite-atomic-683e2db0-v1` and `sqlite-atomic-cab054db-v1` records qualify their corresponding Server source deployments and do not match this bundled contract. Historical records are disabled in the selector, and saved unavailable selections remain visible until explicitly replaced. CI builds have their own artifact identities and do not change product qualification. The real Server harness covers SQLite with anonymous loopback, static Bearer, HTTPS with explicit CA/base path, and injected-provider/enforced access. It exercises save/search/exact reads, identity changes, binding revocation, ambiguous writes without replay and Scope pagination. Installed UI checks cover repeated launches preserving the existing editor, late committed-save responses preserving a new Scope draft, explicit connection/Scope selection, clipboard copies, connection isolation, draft cancellation, byte limits and independent Server survival after Desktop exit. @@ -232,6 +240,35 @@ Repository hooks passed except the existing Windows Python type errors in unchan see ignored `.artifacts/desktop-shell/current-contract-prek.log`. 仓库全量钩子仍有未修改代码的既存 Windows Python 类型错误,其余钩子通过。 +#### Server c535d816 protocol qualification + +`sqlite-atomic-c535d816-v1` records Server sources at +`c535d816cee43fe1d80871489361a34c70306e61`, normalized OpenAPI digest +`5878999ce9e239d6642e4da858074b281ed465629432c578b3584eec47cbce6c`, and wheel +`powercontext-1.4.1.dev138+gf2b442fc4.d20261023-py3-none-any.whl`, SHA-256 +`677812c860dd6f12866afa3b6b3e2e0529a6d37b427187c0ce4f3cd732349551`. +The wheel was built at Desktop commit `f2b442fc41f724e206a50f2415a03476abdcdf76`. +All 540 packaged runtime files match the recorded Server sources after CRLF normalization; +the OpenAPI contract, project configuration and lock also match. The sorted wheel runtime +source-manifest digest is `de9a0d13784677fcf1b3dd0cc1c54fc719d462e4a6dbafc5524071125ad96504` +(one `wheel/path sha256` entry per line, with a final newline; hashes use the packaged bytes). + +The eleven recorded operations include discovery and the existing health, Principal, Scope and +Atomic Memory operations. The full real-Server harness passed in all four SQLite modes described +above. A second run used the normal `ConnectionManager::new` and explicitly selected this bundled +product record, without injected qualification. Its temporary native probe reused the existing +`server_probe.rs` assertions, changing only manager construction and the selected qualification ID. +All four modes passed again, including save/search/exact reads, Principal changes and revocation, +pagination, uncertain writes without replay and independent Server survival. The product +connection, transport, credential and error implementations were unchanged. Evidence is recorded +under ignored `.artifacts/real-server-product-protocol.json` and +`.artifacts/product-protocol-source-verification.json`. + +Qualification used Windows 10 x64 (10.0.19045), Python 3.11.15 and Rust 1.95.0. This establishes +Server protocol compatibility for these sources and this wheel. It does not establish Windows 11 +or macOS installed-package, credential-store, UI or release qualification. Historical catalog +records retain their exact identities and evidence. + #### Server d9a78567 protocol qualification The corresponding historical preview contract is qualified by `sqlite-atomic-d9a78567-v1`. The record identifies Server diff --git a/desktop/scripts/generate.mjs b/desktop/scripts/generate.mjs index 9e055311af..2a23ff8c8e 100644 --- a/desktop/scripts/generate.mjs +++ b/desktop/scripts/generate.mjs @@ -14,11 +14,19 @@ * limitations under the License. */ -import { readFile, writeFile, mkdir, mkdtemp, rm } from "node:fs/promises"; +import { + access, + readFile, + writeFile, + mkdir, + mkdtemp, + rm, +} from "node:fs/promises"; import { createHash } from "node:crypto"; import { spawn } from "node:child_process"; +import { createRequire } from "node:module"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import YAML from "yaml"; import openapiTS, { astToString } from "openapi-typescript"; @@ -28,6 +36,7 @@ const contractUrl = new URL("../openapi/powercontext.yaml", root); const raw = await readFile(contractUrl, "utf8"); const contract = YAML.parse(raw); const wanted = [ + "get_server_info", "get_liveness", "get_readiness", "get_capabilities", @@ -40,16 +49,24 @@ const wanted = [ "get_artifact_revision", ]; const operations = {}; +const operationFeatures = {}; for (const [path, item] of Object.entries(contract.paths)) { for (const [method, op] of Object.entries(item)) { if (wanted.includes(op?.operationId)) { if (operations[op.operationId]) throw new Error("Duplicate operation"); operations[op.operationId] = { method: method.toUpperCase(), path }; + operationFeatures[op.operationId] = + op["x-powercontext-feature-contracts"] ?? []; } } } if (Object.keys(operations).length !== wanted.length) throw new Error("Missing public operation"); +const discovery = { + apiMajor: Number(contract.info.version.split(".")[0]), + features: contract["x-powercontext-feature-contracts"], + operationFeatures, +}; const digest = createHash("sha256") .update(raw.replaceAll("\r\n", "\n")) .digest("hex"); @@ -82,14 +99,7 @@ function snakeCase(name) { } function run(command, args, cwd) { return new Promise((resolve, reject) => { - const useWindowsCmd = process.platform === "win32" && command === "pnpm"; - const executable = useWindowsCmd - ? (process.env.ComSpec ?? "cmd.exe") - : command; - const executableArgs = useWindowsCmd - ? ["/d", "/s", "/c", command, ...args] - : args; - const child = spawn(executable, executableArgs, { + const child = spawn(command, args, { cwd, stdio: ["ignore", "pipe", "pipe"], }); @@ -115,16 +125,42 @@ async function generateRustModels() { ); const output = join(temporary, "generated"); const modelNames = [...schemaNames].sort(); - const pnpm = "pnpm"; + const generatorCli = createRequire(import.meta.url).resolve( + "@openapitools/openapi-generator-cli/main.js", + ); try { + const generatorConfig = JSON.parse( + await readFile(new URL("openapitools.json", root), "utf8"), + ); + const jar = join( + dirname(generatorCli), + "versions", + `${generatorConfig["generator-cli"].version}.jar`, + ); + try { + await access(jar); + } catch { + await run( + process.execPath, + [generatorCli, "version"], + fileURLToPath(root), + ); + } + // Discovery minor versions may add optional fields, including in nested contracts. + const input = structuredClone(contract); + for (const name of ["ServerInfo", "ContractVersion", "FeatureContract"]) { + input.components.schemas[name]["x-rust-allow-unknown-fields"] = true; + } + const inputPath = join(temporary, "openapi.yaml"); + await writeFile(inputPath, YAML.stringify(input)); await run( - pnpm, + "java", [ - "exec", - "openapi-generator-cli", + "-jar", + jar, "generate", "-i", - fileURLToPath(contractUrl), + inputPath, "-g", "rust", "-t", @@ -219,7 +255,8 @@ const outputs = { JSON.stringify(operations, null, 2) + " as const;\n", "src-tauri/src/transport/operations.json": - JSON.stringify({ contractSha256: digest, operations }, null, 2) + "\n", + JSON.stringify({ contractSha256: digest, operations, discovery }, null, 2) + + "\n", }; for (const [name, text] of Object.entries(outputs)) { const target = new URL(name, root); diff --git a/desktop/scripts/openapi-generator/rust/model.mustache b/desktop/scripts/openapi-generator/rust/model.mustache index 980f6c4939..27a99706ae 100644 --- a/desktop/scripts/openapi-generator/rust/model.mustache +++ b/desktop/scripts/openapi-generator/rust/model.mustache @@ -141,7 +141,8 @@ impl Default for {{classname}} { {{^discriminator}} {{#vendorExtensions.x-rust-has-byte-array}}#[serde_as] {{/vendorExtensions.x-rust-has-byte-array}}{{#oneOf.isEmpty}}#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, TS)] -#[serde(deny_unknown_fields)] +{{^vendorExtensions.x-rust-allow-unknown-fields}}#[serde(deny_unknown_fields)] +{{/vendorExtensions.x-rust-allow-unknown-fields}} pub struct {{{classname}}} { {{#vars}} {{#description}} diff --git a/desktop/src-tauri/examples/export_ipc.rs b/desktop/src-tauri/examples/export_ipc.rs index 66623da867..3bf7ef15a5 100644 --- a/desktop/src-tauri/examples/export_ipc.rs +++ b/desktop/src-tauri/examples/export_ipc.rs @@ -16,6 +16,10 @@ use powercontext_desktop::{ connections::{ + discovery::{ + CompatibilityReason, CompatibilityStatus, DiscoveryResult, DiscoveryStatus, + OperationCompatibility, + }, profiles::{Authentication, CredentialState, ProfileInput, ProfileView}, session::{ ActiveView, CheckReport, CompatibilityProfile, DesktopState, Fact, MemoryContext, @@ -59,6 +63,11 @@ fn main() { ProfileInput::decl(&config), CredentialState::decl(&config), Fact::::decl(&config), + DiscoveryStatus::decl(&config), + CompatibilityReason::decl(&config), + CompatibilityStatus::decl(&config), + OperationCompatibility::decl(&config), + DiscoveryResult::decl(&config), CheckReport::decl(&config), CompatibilityProfile::decl(&config), ActiveView::decl(&config), diff --git a/desktop/src-tauri/examples/server_probe.rs b/desktop/src-tauri/examples/server_probe.rs index d807b12bce..31fb37bb5d 100644 --- a/desktop/src-tauri/examples/server_probe.rs +++ b/desktop/src-tauri/examples/server_probe.rs @@ -22,7 +22,7 @@ use powercontext_desktop::{ }, credentials::{NativeVault, Secret}, error::SafeError, - transport::{Endpoint, ServerApi, wire::ArtifactReference}, + transport::{DiscoveryDocument, Endpoint, ServerApi, wire::ArtifactReference}, }; use serde::Deserialize; #[derive(Deserialize)] @@ -74,6 +74,17 @@ async fn main() { fixture.token.take(), ) .unwrap(); + assert!(matches!( + api.server_info().await.unwrap(), + DiscoveryDocument::Server(_) + )); + if args + .get(2) + .is_some_and(|argument| argument == "discovery-only") + { + println!("{{\"result\":\"passed\",\"operation\":\"get_server_info\"}}"); + return; + } api.live().await.unwrap(); api.readiness().await.unwrap(); if has_token { diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index db01c42325..aaf7d8133b 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -246,5 +246,25 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-dd62723d-protocol-qualification" + }, + { + "id": "sqlite-atomic-c535d816-v1", + "serverCommit": "c535d816cee43fe1d80871489361a34c70306e61", + "contractSha256": "5878999ce9e239d6642e4da858074b281ed465629432c578b3584eec47cbce6c", + "artifactSha256": "677812c860dd6f12866afa3b6b3e2e0529a6d37b427187c0ce4f3cd732349551", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#server-c535d816-protocol-qualification" } ] diff --git a/desktop/src-tauri/src/connections/discovery.rs b/desktop/src-tauri/src/connections/discovery.rs new file mode 100644 index 0000000000..f307ec4033 --- /dev/null +++ b/desktop/src-tauri/src/connections/discovery.rs @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//! Operation availability requires discovery compatibility and explicit qualification evidence. +//! A failed discovery observation gates operations until a successful recheck; health is not proof. +use super::session::CompatibilityProfile; +use crate::{ + error::SafeError, + transport::{ + ApiFailure, DiscoveryDocument, + wire::{ContractVersion, ServerInfo}, + }, +}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use ts_rs::TS; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, TS)] +#[serde(rename_all = "snake_case")] +pub enum DiscoveryStatus { + Supported, + Missing, + Denied, + Unavailable, + Invalid, + Incompatible, +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, TS)] +#[serde(rename_all = "snake_case")] +pub enum CompatibilityReason { + ProductMismatch, + SchemaVersion, + ApiVersion, + DiscoveryMissing, + DiscoveryDenied, + DiscoveryUnavailable, + InvalidDiscovery, + QualificationRequired, + QualifiedProfile, + FeatureMissing, + FeatureVersion, + OperationMissing, +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, TS)] +#[serde(rename_all = "snake_case")] +pub enum CompatibilityStatus { + Qualified, + Unsupported, + Unverified, +} + +#[derive(Clone, Serialize, TS)] +#[serde(rename_all = "camelCase")] +pub struct OperationCompatibility { + pub status: CompatibilityStatus, + pub reason: CompatibilityReason, + pub qualification_id: Option, +} + +#[derive(Clone, Serialize, TS)] +#[serde(rename_all = "camelCase")] +pub struct DiscoveryResult { + pub status: DiscoveryStatus, + pub server: Option, + pub error: Option, + pub reason: Option, + pub operations: BTreeMap, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Requirements { + api_major: i64, + features: BTreeMap, + operation_features: BTreeMap>, +} + +impl DiscoveryResult { + /// Evidence is selected and checked by the native manager; discovery never creates qualification. + pub fn assess( + response: Result, + qualification: Option<&CompatibilityProfile>, + ) -> Self { + let manifest: serde_json::Value = + serde_json::from_str(include_str!("../transport/operations.json")) + .expect("generated operation manifest"); + let requirements: Requirements = serde_json::from_value(manifest["discovery"].clone()) + .expect("generated discovery requirements"); + let (status, server, error, reason) = match response { + Ok(DiscoveryDocument::UnsupportedProduct) => ( + DiscoveryStatus::Incompatible, + None, + None, + Some(CompatibilityReason::ProductMismatch), + ), + Ok(DiscoveryDocument::Server(server)) => { + let reason = if server.schema_version.major != 1 { + Some(CompatibilityReason::SchemaVersion) + } else if server.api_contract_version.major != requirements.api_major { + Some(CompatibilityReason::ApiVersion) + } else { + None + }; + ( + if reason.is_some() { + DiscoveryStatus::Incompatible + } else { + DiscoveryStatus::Supported + }, + Some(server), + None, + reason, + ) + } + Err(error) => { + let (status, reason) = match error.code { + SafeError::NotFound => ( + DiscoveryStatus::Missing, + CompatibilityReason::DiscoveryMissing, + ), + SafeError::Unauthorized | SafeError::Forbidden => ( + DiscoveryStatus::Denied, + CompatibilityReason::DiscoveryDenied, + ), + SafeError::Network + | SafeError::Tls + | SafeError::Redirect + | SafeError::Busy + | SafeError::Timeout + | SafeError::Server + | SafeError::RuntimeNotReady + | SafeError::AuthenticationUnavailable => ( + DiscoveryStatus::Unavailable, + CompatibilityReason::DiscoveryUnavailable, + ), + _ => ( + DiscoveryStatus::Invalid, + CompatibilityReason::InvalidDiscovery, + ), + }; + (status, None, Some(error), Some(reason)) + } + }; + let operations = requirements + .operation_features + .iter() + .map(|(operation, features)| { + let known = qualification.filter(|q| q.operations.contains(operation)); + let restriction = if status == DiscoveryStatus::Supported { + let server = server.as_ref().expect("supported discovery"); + features.iter().find_map(|feature| { + let minimum = &requirements.features[feature]; + match server.feature_contracts.get(feature) { + None => Some(CompatibilityReason::FeatureMissing), + Some(actual) + if actual.version.major != minimum.major + || actual.version.minor < minimum.minor => + { + Some(CompatibilityReason::FeatureVersion) + } + Some(actual) if !actual.operations.contains(operation) => { + Some(CompatibilityReason::OperationMissing) + } + _ => None, + } + }) + } else { + reason + }; + let (status, reason) = + if status == DiscoveryStatus::Missing && operation == "get_server_info" { + ( + CompatibilityStatus::Unsupported, + CompatibilityReason::DiscoveryMissing, + ) + } else if status == DiscoveryStatus::Missing && known.is_some() { + ( + CompatibilityStatus::Qualified, + CompatibilityReason::QualifiedProfile, + ) + } else if let Some(restriction) = restriction { + ( + if matches!( + status, + DiscoveryStatus::Supported | DiscoveryStatus::Incompatible + ) { + CompatibilityStatus::Unsupported + } else { + CompatibilityStatus::Unverified + }, + restriction, + ) + } else if known.is_some() { + ( + CompatibilityStatus::Qualified, + CompatibilityReason::QualifiedProfile, + ) + } else { + ( + CompatibilityStatus::Unverified, + CompatibilityReason::QualificationRequired, + ) + }; + ( + operation.clone(), + OperationCompatibility { + status, + reason, + qualification_id: known.map(|q| q.id.clone()), + }, + ) + }) + .collect(); + Self { + status, + server, + error, + reason, + operations, + } + } + pub fn supported_operations(&self) -> Vec { + self.operations + .iter() + .filter(|(_, result)| result.status == CompatibilityStatus::Qualified) + .map(|(operation, _)| operation.clone()) + .collect() + } +} diff --git a/desktop/src-tauri/src/connections/mod.rs b/desktop/src-tauri/src/connections/mod.rs index 35b2fc01f5..9181fa1b63 100644 --- a/desktop/src-tauri/src/connections/mod.rs +++ b/desktop/src-tauri/src/connections/mod.rs @@ -14,5 +14,6 @@ * limitations under the License. */ +pub mod discovery; pub mod profiles; pub mod session; diff --git a/desktop/src-tauri/src/connections/session.rs b/desktop/src-tauri/src/connections/session.rs index ca97ba304b..67224edbba 100644 --- a/desktop/src-tauri/src/connections/session.rs +++ b/desktop/src-tauri/src/connections/session.rs @@ -15,6 +15,7 @@ */ //! Native-owned connection and Scope context. Viewing a profile never activates it. +use super::discovery::DiscoveryResult; use super::profiles::{ProfileInput, ProfileRepository, ProfileView}; use crate::{ error::SafeError, @@ -61,6 +62,9 @@ pub struct CheckReport { pub compatibility_verified: bool, pub anonymous_access: bool, pub supported_operations: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub discovery: Option, } #[derive(Clone, Deserialize, Serialize, TS)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -311,6 +315,8 @@ impl ConnectionManager { ) }; let report = Self::cancellable(&mut cancelled, async { + // Discovery is separate from the bounded observation batch (four transport slots). + let discovery = api.server_info().await; let (live, ready, identity, capabilities) = tokio::join!( api.live(), api.readiness(), @@ -338,6 +344,8 @@ impl ConnectionManager { .as_ref() .is_err_and(|e| e.code == SafeError::InvalidResponse) }); + let discovery = DiscoveryResult::assess(discovery, compatible); + let supported_operations = discovery.supported_operations(); Ok(CheckReport { anonymous_access, connection_id: id.into(), @@ -350,8 +358,9 @@ impl ConnectionManager { readiness: ready.into(), identity: identity.into(), capabilities: capabilities.into(), - compatibility_verified: compatible.is_some(), - supported_operations: compatible.map(|c| c.operations.clone()).unwrap_or_default(), + compatibility_verified: !supported_operations.is_empty(), + supported_operations, + discovery: Some(discovery), }) }) .await?; diff --git a/desktop/src-tauri/src/transport/api.rs b/desktop/src-tauri/src/transport/api.rs index c48e684176..8cf2b37861 100644 --- a/desktop/src-tauri/src/transport/api.rs +++ b/desktop/src-tauri/src/transport/api.rs @@ -21,7 +21,7 @@ use reqwest::{ Method, header::{AUTHORIZATION, HeaderValue}, }; -use serde::{Serialize, de::DeserializeOwned}; +use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned}; use ts_rs::TS; #[derive(Clone, Debug, Serialize, TS)] @@ -76,6 +76,51 @@ pub struct ServerApi { endpoint: Endpoint, credential: Option, } + +/// A foreign product is a recognizable incompatibility, rather than malformed JSON. +pub enum DiscoveryDocument { + Server(ServerInfo), + UnsupportedProduct, +} +impl<'de> Deserialize<'de> for DiscoveryDocument { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Document { + Server(ServerInfo), + OtherProduct { product: String }, + } + let server = match Document::deserialize(deserializer)? { + Document::Server(server) => server, + Document::OtherProduct { product } if product != "powercontext" => { + return Ok(Self::UnsupportedProduct); + } + _ => return Err(serde::de::Error::custom("invalid discovery document")), + }; + if server.server_id.is_empty() + || server.server_id.chars().count() > 128 + || server.package_version.is_empty() + || server.schema_version.major < 1 + || server.schema_version.minor < 0 + || server.api_contract_version.major < 1 + || server.api_contract_version.minor < 0 + || server.feature_contracts.values().any(|feature| { + feature.version.major < 1 + || feature.version.minor < 0 + || feature.operations.is_empty() + || feature + .operations + .iter() + .collect::>() + .len() + != feature.operations.len() + }) + { + return Err(serde::de::Error::custom("invalid discovery document")); + } + Ok(Self::Server(server)) + } +} impl ServerApi { pub fn new( endpoint: Endpoint, @@ -241,6 +286,10 @@ impl ServerApi { } Ok(result) } + pub async fn server_info(&self) -> Result { + self.execute("get_server_info", None, &[], None, false) + .await + } pub async fn readiness(&self) -> Result { self.execute("get_readiness", None, &[], None, true).await } diff --git a/desktop/src-tauri/src/transport/mod.rs b/desktop/src-tauri/src/transport/mod.rs index aeee5896d7..d11551e82a 100644 --- a/desktop/src-tauri/src/transport/mod.rs +++ b/desktop/src-tauri/src/transport/mod.rs @@ -17,8 +17,8 @@ mod api; pub mod wire; pub use api::{ - ApiFailure, AtomicMemoryDetail, MemorySaveResponse, MemorySearchHit, MemorySearchResponse, - ServerApi, validate_text, + ApiFailure, AtomicMemoryDetail, DiscoveryDocument, MemorySaveResponse, MemorySearchHit, + MemorySearchResponse, ServerApi, validate_text, }; // Only native adapters use this transport; it is not an IPC fetch primitive. diff --git a/desktop/src-tauri/src/transport/operations.json b/desktop/src-tauri/src/transport/operations.json index 9170a68dba..b041e70422 100644 --- a/desktop/src-tauri/src/transport/operations.json +++ b/desktop/src-tauri/src/transport/operations.json @@ -9,6 +9,10 @@ "method": "GET", "path": "/health/ready" }, + "get_server_info": { + "method": "GET", + "path": "/v1/server-info" + }, "get_capabilities": { "method": "GET", "path": "/v1/capabilities" @@ -41,5 +45,47 @@ "method": "GET", "path": "/v1/access/me" } + }, + "discovery": { + "apiMajor": 1, + "features": { + "access.principal": { + "major": 1, + "minor": 0 + }, + "scope.selection": { + "major": 1, + "minor": 0 + }, + "memory.explicit": { + "major": 1, + "minor": 0 + } + }, + "operationFeatures": { + "get_liveness": [], + "get_readiness": [], + "get_server_info": [], + "get_capabilities": [], + "list_scopes": [ + "scope.selection" + ], + "get_scope": [ + "scope.selection" + ], + "get_default_scope": [ + "scope.selection" + ], + "remember_memory": [ + "memory.explicit" + ], + "search_memory": [ + "memory.explicit" + ], + "get_artifact_revision": [], + "get_access_principal": [ + "access.principal" + ] + } } } diff --git a/desktop/src-tauri/src/transport/wire.rs b/desktop/src-tauri/src/transport/wire.rs index 73828fceaa..70912c8814 100644 --- a/desktop/src-tauri/src/transport/wire.rs +++ b/desktop/src-tauri/src/transport/wire.rs @@ -730,6 +730,23 @@ impl Capabilities { } } +/// ContractVersion : A major/minor compatibility version. A major increment may remove or incompatibly change the governed contract. A minor increment only adds backward-compatible behavior or fields. +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, TS)] +pub struct ContractVersion { + #[serde(rename = "major")] + pub major: i64, + #[serde(rename = "minor")] + pub minor: i64, +} + +impl ContractVersion { + /// A major/minor compatibility version. A major increment may remove or incompatibly change the governed contract. A minor increment only adds backward-compatible behavior or fields. + #[allow(clippy::too_many_arguments)] + pub fn new(major: i64, minor: i64) -> ContractVersion { + ContractVersion { major, minor } + } +} + #[derive( Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, TS, Default, )] @@ -980,6 +997,26 @@ pub enum Configuration { Unknown, } +/// FeatureContract : Compatibility version for exactly the listed OpenAPI operation IDs. Adding operations or compatible semantics increments minor; removing, renaming or incompatibly changing a listed operation increments major. +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, TS)] +pub struct FeatureContract { + #[serde(rename = "version")] + pub version: ContractVersion, + #[serde(rename = "operations")] + pub operations: Vec, +} + +impl FeatureContract { + /// Compatibility version for exactly the listed OpenAPI operation IDs. Adding operations or compatible semantics increments minor; removing, renaming or incompatibly changing a listed operation increments major. + #[allow(clippy::too_many_arguments)] + pub fn new(version: ContractVersion, operations: Vec) -> FeatureContract { + FeatureContract { + version, + operations, + } + } +} + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, TS)] #[serde(deny_unknown_fields)] pub struct HealthResponse { @@ -1379,6 +1416,57 @@ impl SearchMemoryResponse { } } +/// ServerInfo : Stable deployment identity and protocol compatibility metadata. Compatible clients must ignore unknown optional fields added by a future schema minor version. This contract intentionally excludes runtime capabilities, health, limits, inventory and authorization-principal identity. +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, TS)] +pub struct ServerInfo { + /// Compatibility version for this response shape and field semantics. + #[serde(rename = "schema_version")] + pub schema_version: ContractVersion, + #[serde(rename = "product")] + pub product: Product, + /// Opaque identity of the durable Server deployment. It is unrelated to Access deployment_id and remains stable across restarts, upgrades, backup restore and replicas sharing the same primary database. + #[serde(rename = "server_id")] + pub server_id: String, + #[serde(rename = "package_version")] + pub package_version: String, + /// Major/minor projection of the OpenAPI info.version served by this package. + #[serde(rename = "api_contract_version")] + pub api_contract_version: ContractVersion, + /// Stable feature groups keyed by contract name. + #[serde(rename = "feature_contracts")] + pub feature_contracts: std::collections::HashMap, +} + +impl ServerInfo { + /// Stable deployment identity and protocol compatibility metadata. Compatible clients must ignore unknown optional fields added by a future schema minor version. This contract intentionally excludes runtime capabilities, health, limits, inventory and authorization-principal identity. + #[allow(clippy::too_many_arguments)] + pub fn new( + schema_version: ContractVersion, + product: Product, + server_id: String, + package_version: String, + api_contract_version: ContractVersion, + feature_contracts: std::collections::HashMap, + ) -> ServerInfo { + ServerInfo { + schema_version, + product, + server_id, + package_version, + api_contract_version, + feature_contracts, + } + } +} +#[derive( + Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, TS, Default, +)] +pub enum Product { + #[serde(rename = "powercontext")] + #[default] + Powercontext, +} + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, TS)] #[serde(deny_unknown_fields)] pub struct SourceTypeReference { @@ -1462,6 +1550,7 @@ pub fn declarations(config: &ts_rs::Config) -> Vec { ::decl(config), ::decl(config), ::decl(config), + ::decl(config), ::decl(config), ::decl(config), ::decl(config), @@ -1469,6 +1558,7 @@ pub fn declarations(config: &ts_rs::Config) -> Vec { ::decl(config), ::decl(config), ::decl(config), + ::decl(config), ::decl(config), ::decl(config), ::decl(config), @@ -1476,6 +1566,7 @@ pub fn declarations(config: &ts_rs::Config) -> Vec { ::decl(config), ::decl(config), ::decl(config), + ::decl(config), ::decl(config), ::decl(config), ::decl(config), @@ -1489,6 +1580,7 @@ pub fn declarations(config: &ts_rs::Config) -> Vec { ::decl(config), ::decl(config), ::decl(config), + ::decl(config), ::decl(config), ::decl(config), ::decl(config), diff --git a/desktop/src-tauri/tests/api.rs b/desktop/src-tauri/tests/api.rs index e2071ccbd8..d5a8d5c139 100644 --- a/desktop/src-tauri/tests/api.rs +++ b/desktop/src-tauri/tests/api.rs @@ -93,6 +93,21 @@ async fn exact_scope_uses_one_encoded_path_segment() { .starts_with("GET /proxy/%E4%B8%AD%E6%96%87/v1/scopes/scope%2F%E4%B8%AD%E6%96%87%3Fx ") ); } + +#[tokio::test] +async fn discovery_rejects_duplicate_deployment_identity_fields() { + let (api, request) = fixture(200, r#"{"schema_version":{"major":1,"minor":0},"product":"powercontext","server_id":"old","server_id":"new","package_version":"1.4.0","api_contract_version":{"major":1,"minor":4},"feature_contracts":{}}"#).await; + assert_eq!( + api.server_info().await.err().unwrap().code, + SafeError::InvalidResponse + ); + assert!( + request + .await + .unwrap() + .starts_with("GET /proxy/%E4%B8%AD%E6%96%87/v1/server-info ") + ); +} #[tokio::test] async fn readiness_failure_is_a_fact_and_write_failure_keeps_dispatch_uncertainty() { let (api, request) = fixture( diff --git a/desktop/src-tauri/tests/discovery.rs b/desktop/src-tauri/tests/discovery.rs new file mode 100644 index 0000000000..611839cf10 --- /dev/null +++ b/desktop/src-tauri/tests/discovery.rs @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2026 OceanBase. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +mod common; +use powercontext_desktop::{ + connections::{ + discovery::{CompatibilityReason, CompatibilityStatus, DiscoveryResult, DiscoveryStatus}, + profiles::ProfileRepository, + session::ConnectionManager, + }, + credentials::NativeVault, + error::SafeError, +}; +use serde_json::{Value, json}; +use std::sync::{ + Arc, + atomic::{AtomicU16, Ordering}, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener, +}; + +fn document() -> Value { + json!({"schema_version":{"major":1,"minor":0},"product":"powercontext","server_id":"synthetic-server", + "package_version":"display-only-version","api_contract_version":{"major":1,"minor":4},"feature_contracts":{ + "access.principal":{"version":{"major":1,"minor":0},"operations":["get_access_principal"]}, + "scope.selection":{"version":{"major":1,"minor":0},"operations":["list_scopes","get_scope","get_default_scope"]}, + "memory.explicit":{"version":{"major":1,"minor":0},"operations":["remember_memory","search_memory"]} + }}) +} +struct Fixture { + manager: ConnectionManager, + id: String, + status: Arc, + server: tokio::task::JoinHandle<()>, + _directory: tempfile::TempDir, +} +impl Drop for Fixture { + fn drop(&mut self) { + self.server.abort(); + } +} +async fn fixture(status: u16, document: Value, qualified: bool) -> Fixture { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}/prefix", listener.local_addr().unwrap()); + let status = Arc::new(AtomicU16::new(status)); + let response_status = status.clone(); + let server = tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let document = document.clone(); + let status = response_status.load(Ordering::Relaxed); + tokio::spawn(async move { + let mut bytes = Vec::new(); + loop { + let mut chunk = [0; 4096]; + let count = socket.read(&mut chunk).await.unwrap(); + if count == 0 { + return; + } + bytes.extend_from_slice(&chunk[..count]); + if bytes.windows(4).any(|v| v == b"\r\n\r\n") { + break; + } + } + let request = String::from_utf8(bytes).unwrap(); + let path = request.split_whitespace().nth(1).unwrap(); + if status == 0 && path == "/prefix/v1/server-info" { + return; + } + let (status, body) = match path { + "/prefix/v1/server-info" => (status, document), + "/prefix/health/ready" => ( + 200, + json!({"status":"ready","checks":{"access_mode":"disabled"}}), + ), + "/prefix/v1/access/me" => (503, json!({"error":{"code":"runtime_not_ready"}})), + "/prefix/v1/capabilities" => (403, json!({})), + path if path.starts_with("/prefix/v1/scopes?") => { + (200, json!({"items":[],"next_cursor":null})) + } + _ => (200, json!({"status":"ok"})), + }; + let body = body.to_string(); + let response = format!( + "HTTP/1.1 {status} Result\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = socket.write_all(response.as_bytes()).await; + }); + } + }); + let directory = tempfile::tempdir().unwrap(); + let repository = ProfileRepository::open( + directory.path().join("profiles.json"), + Arc::new(NativeVault), + ) + .unwrap(); + let manager = if qualified { + common::connection_manager(repository) + } else { + ConnectionManager::new(repository) + }; + let state = manager.save_profile(serde_json::from_value(json!({"id":null,"revision":null,"name":"Synthetic", + "endpoint":endpoint,"authentication":"unauthenticated_loopback","caPem":null,"compatibility":common::PROFILE_ID, + "keepCredential":false,"credential":null})).unwrap()).unwrap(); + Fixture { + manager, + id: state.profiles[0].id.clone(), + status, + server, + _directory: directory, + } +} +async fn check(status: u16, document: Value, qualified: bool) -> DiscoveryResult { + let fixture = fixture(status, document, qualified).await; + let result = fixture.manager.check(&fixture.id, false).await.unwrap(); + assert!( + result.active.is_none(), + "passive discovery must not activate a connection" + ); + result + .reports + .into_iter() + .next() + .unwrap() + .discovery + .unwrap() +} + +#[tokio::test] +async fn qualified_connection_recovers_from_discovery_503_after_explicit_recheck() { + let fixture = fixture(200, document(), true).await; + let state = fixture.manager.check(&fixture.id, true).await.unwrap(); + assert!(state.active.unwrap().report.compatibility_verified); + + fixture.status.store(503, Ordering::Relaxed); + let state = fixture.manager.check(&fixture.id, true).await.unwrap(); + let report = &state.active.as_ref().unwrap().report; + assert_eq!( + report.discovery.as_ref().unwrap().status, + DiscoveryStatus::Unavailable + ); + assert!(!report.compatibility_verified); + assert_eq!( + fixture + .manager + .scopes(state.generation, "", None) + .await + .err() + .unwrap() + .code, + SafeError::CompatibilityUnverified + ); + + fixture.status.store(200, Ordering::Relaxed); + let state = fixture.manager.check(&fixture.id, true).await.unwrap(); + let active = state.active.as_ref().unwrap(); + assert_eq!(active.connection_id, fixture.id); + assert!(active.report.compatibility_verified); + assert_eq!( + active.report.discovery.as_ref().unwrap().status, + DiscoveryStatus::Supported + ); + assert!( + fixture + .manager + .scopes(state.generation, "", None) + .await + .is_ok() + ); +} + +#[tokio::test] +async fn compatible_minor_additions_and_base_paths_preserve_independent_qualification() { + let mut value = document(); + value["schema_version"]["minor"] = json!(50); + value["schema_version"]["future"] = json!(true); + value["api_contract_version"]["future"] = json!(true); + value["new_optional_field"] = json!({"opaque":true}); + value["feature_contracts"]["memory.explicit"]["version"]["minor"] = json!(50); + value["feature_contracts"]["memory.explicit"]["future"] = json!(true); + let result = check(200, value, true).await; + assert_eq!(result.status, DiscoveryStatus::Supported); + assert_eq!(result.server.unwrap().server_id, "synthetic-server"); + assert_eq!( + result.operations["remember_memory"].status, + CompatibilityStatus::Qualified + ); + assert_eq!( + result.operations["get_artifact_revision"].status, + CompatibilityStatus::Qualified + ); +} + +#[tokio::test] +async fn handshake_success_does_not_create_qualification() { + let result = check(200, document(), false).await; + assert_eq!(result.status, DiscoveryStatus::Supported); + assert_eq!( + result.operations["remember_memory"].status, + CompatibilityStatus::Unverified + ); + assert_eq!( + result.operations["remember_memory"].reason, + CompatibilityReason::QualificationRequired + ); +} + +#[tokio::test] +async fn only_a_missing_handshake_allows_explicit_qualified_legacy_operations() { + let result = check(404, json!({}), true).await; + assert_eq!(result.status, DiscoveryStatus::Missing); + assert_eq!( + result.operations["remember_memory"].status, + CompatibilityStatus::Qualified + ); + let result = check(404, json!({}), false).await; + assert_eq!( + result.operations["remember_memory"].status, + CompatibilityStatus::Unverified + ); + for (code, status) in [ + (0, DiscoveryStatus::Unavailable), + (401, DiscoveryStatus::Denied), + (403, DiscoveryStatus::Denied), + (503, DiscoveryStatus::Unavailable), + ] { + let result = check(code, json!({"error":{"code":"runtime_not_ready"}}), true).await; + assert_eq!(result.status, status); + assert!(result.error.is_some()); + assert!(result.supported_operations().is_empty()); + } +} + +#[tokio::test] +async fn incompatible_products_and_required_major_versions_remain_distinct_from_invalid_documents() +{ + for (field, reason) in [ + ("product", CompatibilityReason::ProductMismatch), + ("schema_version", CompatibilityReason::SchemaVersion), + ("api_contract_version", CompatibilityReason::ApiVersion), + ] { + let mut value = document(); + if field == "product" { + value[field] = json!("another-product"); + } else { + value[field]["major"] = json!(9); + } + let result = check(200, value, true).await; + assert_eq!(result.status, DiscoveryStatus::Incompatible); + assert_eq!(result.reason, Some(reason)); + assert!(result.supported_operations().is_empty()); + } + for value in [ + json!({"status":"ok"}), + { + let mut value = document(); + value["server_id"] = json!(""); + value + }, + { + let mut value = document(); + value["schema_version"]["minor"] = json!(-1); + value + }, + ] { + let result = check(200, value, true).await; + assert_eq!(result.status, DiscoveryStatus::Invalid); + assert!(result.supported_operations().is_empty()); + } +} + +#[tokio::test] +async fn optional_feature_and_operation_restrictions_do_not_disable_unrelated_scopes() { + for (change, reason) in [ + ("missing", CompatibilityReason::FeatureMissing), + ("version", CompatibilityReason::FeatureVersion), + ("operation", CompatibilityReason::OperationMissing), + ] { + let mut value = document(); + match change { + "missing" => { + value["feature_contracts"] + .as_object_mut() + .unwrap() + .remove("memory.explicit"); + } + "version" => { + value["feature_contracts"]["memory.explicit"]["version"]["major"] = json!(2) + } + _ => { + value["feature_contracts"]["memory.explicit"]["operations"] = + json!(["search_memory"]) + } + } + let result = check(200, value, true).await; + assert_eq!(result.status, DiscoveryStatus::Supported); + assert_eq!( + result.operations["remember_memory"].status, + CompatibilityStatus::Unsupported + ); + assert_eq!(result.operations["remember_memory"].reason, reason); + assert_eq!( + result.operations["list_scopes"].status, + CompatibilityStatus::Qualified + ); + } +} diff --git a/desktop/src-tauri/tests/memory.rs b/desktop/src-tauri/tests/memory.rs index 84c1d78140..bcd61eab01 100644 --- a/desktop/src-tauri/tests/memory.rs +++ b/desktop/src-tauri/tests/memory.rs @@ -107,6 +107,7 @@ async fn setup_response(response: serde_json::Value) -> Fixture { .unwrap() .to_owned(); let (status, value) = match path.as_str() { + "/v1/server-info" => (404, serde_json::json!({})), "/v1/access/me" => ( 503, serde_json::json!({"error":{"code":"runtime_not_ready"}}), diff --git a/desktop/src-tauri/tests/session.rs b/desktop/src-tauri/tests/session.rs index b7f5a5babc..2419e47145 100644 --- a/desktop/src-tauri/tests/session.rs +++ b/desktop/src-tauri/tests/session.rs @@ -73,7 +73,9 @@ async fn fixture() -> Fixture { } let text = String::from_utf8(request).unwrap(); let path = text.split_whitespace().nth(1).unwrap(); - let (status, body) = if path.contains("/access/me") { + let (status, body) = if path.contains("/server-info") { + (404, r#"{}"#) + } else if path.contains("/access/me") { if changed.load(Ordering::Relaxed) { (401, r#"{}"#) } else { diff --git a/desktop/ui/src/app/Connections.tsx b/desktop/ui/src/app/Connections.tsx index b4f571ab8a..bf0da51867 100644 --- a/desktop/ui/src/app/Connections.tsx +++ b/desktop/ui/src/app/Connections.tsx @@ -24,7 +24,11 @@ import type { } from "../generated/ipc"; import { contractSha256 } from "../generated/operations"; import { desktopApi } from "../shared/ipc"; -import { connectionMessages, connectionError } from "./connection-messages"; +import { + connectionMessages, + connectionError, + discoveryMessage, +} from "./connection-messages"; import { messages, type Language } from "./messages"; import { PageFeedback, ErrorFeedback } from "./PageFeedback"; import { useConfirmation } from "./useConfirmation"; @@ -489,6 +493,14 @@ export function Connections({ {report?.compatibilityVerified ? t.verified : t.unverified} + {report?.discovery && ( +
+
{t.discovery}
+
+ {discoveryMessage(report.discovery, language)} +
+
+ )}
{t.capabilities}
diff --git a/desktop/ui/src/app/MemoryWorkspace.tsx b/desktop/ui/src/app/MemoryWorkspace.tsx index 48f6fbb65c..1921a60e64 100644 --- a/desktop/ui/src/app/MemoryWorkspace.tsx +++ b/desktop/ui/src/app/MemoryWorkspace.tsx @@ -24,7 +24,8 @@ import type { WriteOutcome, } from "../generated/ipc"; import { desktopApi } from "../shared/ipc"; -import { connectionError } from "./connection-messages"; +import { connectionError, operationRestriction } from "./connection-messages"; +import { operationSupported } from "./context"; import { memoryMessages } from "./memory-messages"; import { messages, type Language } from "./messages"; import { PageFeedback, ErrorFeedback } from "./PageFeedback"; @@ -78,7 +79,13 @@ export function NoteForm({ const contentInvalidation = useRef(invalidateSaved); contentInvalidation.current = invalidateSaved; const enabled = - !contextPending && !!active?.scope && active.report.compatibilityVerified; + !contextPending && + !!active?.scope && + operationSupported(active.report, "remember_memory"); + const savedReadEnabled = + !contextPending && + !!active?.scope && + operationSupported(active.report, "get_artifact_revision"); const bytes = textBytes(text); useEffect(() => { setText(""); @@ -195,6 +202,8 @@ export function NoteForm({ ) : contextPending ? ( messages[language].contextUpdating + ) : active?.scope ? ( + operationRestriction(active.report, "remember_memory", language) ) : ( t.noScope )} @@ -235,7 +244,9 @@ export function NoteForm({ outcome.record.status === "succeeded" ? returnedCount ? t.savedReturned(returnedCount) + - (saved.length > 0 ? ` ${t.savedOpen}` : "") + (saved.length > 0 && savedReadEnabled + ? ` ${t.savedOpen}` + : "") : t.noEntry : outcome.record.status === "unknown" ? t.unknown @@ -270,6 +281,7 @@ export function NoteForm({
)} @@ -309,6 +332,10 @@ export function MemoryWorkspace(props: Props) { current.current = active?.generation; const enabled = !contextPending && !!active?.scope && active.report.compatibilityVerified; + const searchEnabled = + enabled && operationSupported(active?.report, "search_memory"); + const readEnabled = + enabled && operationSupported(active?.report, "get_artifact_revision"); function clearRead() { failedReference.current = undefined; sequence.current++; @@ -338,7 +365,7 @@ export function MemoryWorkspace(props: Props) { }; }, [active?.generation]); async function read(reference?: ArtifactReference, fromSave = false) { - if (!enabled || !active?.scope) return; + if (!(reference ? readEnabled : searchEnabled) || !active?.scope) return; const generation = active.generation; const ticket = ++sequence.current; failedReference.current = reference; @@ -477,7 +504,7 @@ export function MemoryWorkspace(props: Props) { { setQuery(e.target.value); @@ -488,7 +515,7 @@ export function MemoryWorkspace(props: Props) {

{t.searchSummary}

- {!enabled && ( -

{contextPending ? common.contextUpdating : t.noScope}

+ {!searchEnabled && ( +

+ {contextPending + ? common.contextUpdating + : active?.scope + ? operationRestriction(active.report, "search_memory", language) + : t.noScope} +

)} {busy && ( void read(failedReference.current)} @@ -580,7 +616,7 @@ export function MemoryWorkspace(props: Props) { {t.hitVector} )} ); const active = state?.active; + const listSupported = operationSupported(active?.report, "list_scopes"); + const selectionSupported = operationSupported(active?.report, "get_scope"); const [query, setQuery] = useState(""); const [items, setItems] = useState(null); const [cursor, setCursor] = useState(null); @@ -74,7 +80,7 @@ export function Scopes({ setBusy(false); }, [active?.generation]); async function load(next: string | null) { - if (!active) return; + if (!active || !listSupported) return; setOperation("list"); const generation = active.generation; const ticket = ++sequence.current; @@ -112,7 +118,7 @@ export function Scopes({ } } async function select(id: string) { - if (!active) return; + if (!active || !selectionSupported) return; const ticket = lifetime.current; const generation = active.generation; if ( @@ -160,20 +166,36 @@ export function Scopes({ {active.scope.scope_id}

)} - {!active.report.compatibilityVerified && ( + {!listSupported && ( + > +

+ {operationRestriction(active.report, "list_scopes", language)} +

+
+ )} + {!selectionSupported && ( + +

+ {operationRestriction(active.report, "get_scope", language)} +

+
)} {error != null && ( void load(null)}> {common.restartScopeSearch} @@ -192,23 +214,16 @@ export function Scopes({ } /> )} - {!busy && - error == null && - items === null && - active.report.compatibilityVerified && ( - -

{common.scopeIdleHint}

-
- )} -
+ {!busy && error == null && items === null && listSupported && ( + +

{common.scopeIdleHint}

+
+ )} +
-
@@ -237,7 +255,7 @@ export function Scopes({ {items.map((scope) => (
  • )} diff --git a/desktop/ui/src/app/connection-messages.ts b/desktop/ui/src/app/connection-messages.ts index 6c3d0e6e20..ca7a662185 100644 --- a/desktop/ui/src/app/connection-messages.ts +++ b/desktop/ui/src/app/connection-messages.ts @@ -14,6 +14,10 @@ * limitations under the License. */ +import type { CheckReport, DiscoveryResult } from "../generated/ipc"; +import type { operations } from "../generated/operations"; +import { operationSupported } from "./context"; + export const connectionMessages = { zh: { add: "添加连接", @@ -56,6 +60,29 @@ export const connectionMessages = { "此 Desktop 未包含该兼容配置的验证记录。请选择可用配置,保存后重新检查连接。", compatibilityHint: "配置表示已测试的 Server 构建,不证明远端二进制身份。请先核对部署版本。", + discovery: "Server 发现", + discovery_supported: "发现协议受支持;操作仍需要已验证的兼容配置。", + discovery_missing: + "Server 未提供发现接口;仅可使用明确选择的旧版兼容配置已验证的操作。", + discovery_denied: + "Server 拒绝访问发现接口。请核对凭据与访问权限,然后重新检查连接。", + discovery_unavailable: + "Server 发现暂时不可用。请检查服务和网络,然后重新检查连接;兼容性确认前业务操作不可用。", + discovery_invalid: + "Server 发现响应无效。请核对 Server 构建,然后重新检查连接。", + discovery_incompatible: "Server 发现协议与此 Desktop 构建不兼容。", + discovery_product_mismatch: "该地址返回的不是 PowerContext Server。", + discovery_schema_version: "发现响应的 major 版本不受支持。", + discovery_api_version: "Server API 的 major 版本不受支持。", + operation_feature_missing: + "Server 未声明此操作所需的功能,请核对受支持的 Server 构建。", + operation_feature_version: + "此操作所需的功能版本不受支持,请核对 Server 构建。", + operation_missing: "Server 未声明支持此操作,其他已验证操作仍可使用。", + operation_qualification_required: + "所选兼容配置没有此操作的独立验证记录,请核对该操作支持的 Server 构建和兼容配置。", + operation_unverified: + "此连接的该项操作尚未验证,请核对 Server 支持情况和兼容配置。", save: "保存配置", check: "检查连接", activate: "使用此连接", @@ -87,6 +114,8 @@ export const connectionMessages = { disconnect: "断开桌面连接", scope: "选择精确范围", scopeQuery: "按范围标题查找", + scopeListUnavailable: "范围查找不可用", + scopeSelectUnavailable: "范围选择不可用", find: "查找范围", more: "下一页", empty: "本页没有可访问的范围。", @@ -172,6 +201,34 @@ export const connectionMessages = { "This Desktop does not include a qualification record for this profile. Select an available profile, save, and check the connection again.", compatibilityHint: "A profile identifies a tested Server build, not the identity of the remote binary. Check your deployment version.", + discovery: "Server discovery", + discovery_supported: + "The discovery contract is supported; operations still require a verified compatibility profile.", + discovery_missing: + "The Server has no discovery endpoint; only operations verified by an explicitly selected legacy profile can be used.", + discovery_denied: + "Server discovery access was denied. Check credentials and access permissions, then check this connection again.", + discovery_unavailable: + "Server discovery is temporarily unavailable. Check the service and network, then check this connection again; business operations remain unavailable until compatibility is verified.", + discovery_invalid: + "The Server discovery response is invalid. Verify the Server build, then check this connection again.", + discovery_incompatible: + "Server discovery is incompatible with this Desktop build.", + discovery_product_mismatch: + "This address did not return a PowerContext Server.", + discovery_schema_version: + "The discovery response major version is unsupported.", + discovery_api_version: "The Server API major version is unsupported.", + operation_feature_missing: + "The Server does not declare the feature required for this operation. Check the supported Server build.", + operation_feature_version: + "The feature version required for this operation is unsupported. Check the Server build.", + operation_missing: + "The Server does not declare support for this operation. Other verified operations remain available.", + operation_qualification_required: + "The selected profile has no independent qualification for this operation. Check the Server build and profile verified for this operation.", + operation_unverified: + "This operation is unverified for this connection. Check Server support and the compatibility profile.", save: "Save configuration", check: "Check connection", activate: "Use this connection", @@ -205,6 +262,8 @@ export const connectionMessages = { disconnect: "Disconnect Desktop", scope: "Select an exact scope", scopeQuery: "Find scopes by title", + scopeListUnavailable: "Scope search is unavailable", + scopeSelectUnavailable: "Scope selection is unavailable", find: "Find scopes", more: "Next page", empty: "No accessible scopes on this page.", @@ -263,6 +322,51 @@ export function connectionError(error: unknown, language: "zh" | "en"): string { : text.error; } +export function discoveryMessage( + result: DiscoveryResult, + language: "zh" | "en", +): string { + const text = connectionMessages[language]; + const reason = result.reason; + const detail = + reason === "product_mismatch" || + reason === "schema_version" || + reason === "api_version" + ? text[`discovery_${reason}`] + : null; + return [ + text[`discovery_${result.status}`], + detail, + result.error && connectionError(result.error, language), + ] + .filter(Boolean) + .join(" "); +} + +export function operationRestriction( + report: CheckReport | undefined, + operation: keyof typeof operations, + language: "zh" | "en", +): string | null { + if (operationSupported(report, operation)) return null; + const text = connectionMessages[language]; + const reason = report?.discovery?.operations[operation]?.reason; + switch (reason) { + case "feature_missing": + return text.operation_feature_missing; + case "feature_version": + return text.operation_feature_version; + case "operation_missing": + return text.operation_missing; + case "qualification_required": + return text.operation_qualification_required; + default: + return report?.discovery && report.discovery.status !== "supported" + ? discoveryMessage(report.discovery, language) + : text.operation_unverified; + } +} + export function connectionErrorCode(error: unknown): string | null { const code = typeof error === "string" diff --git a/desktop/ui/src/app/context.ts b/desktop/ui/src/app/context.ts index 5b1241afea..b0d8a5642b 100644 --- a/desktop/ui/src/app/context.ts +++ b/desktop/ui/src/app/context.ts @@ -14,7 +14,18 @@ * limitations under the License. */ -import type { DesktopState } from "../generated/ipc"; +import type { CheckReport, DesktopState } from "../generated/ipc"; +import type { operations } from "../generated/operations"; + +export function operationSupported( + report: CheckReport | undefined, + operation: keyof typeof operations, +): boolean { + return ( + !!report?.compatibilityVerified && + report.supportedOperations.includes(operation) + ); +} // Presentation only: operation authorization remains at the native boundary. export function activeCheckReport(state: DesktopState | null) { diff --git a/desktop/ui/src/generated/ipc.ts b/desktop/ui/src/generated/ipc.ts index 7474c29357..6cb3161ac3 100644 --- a/desktop/ui/src/generated/ipc.ts +++ b/desktop/ui/src/generated/ipc.ts @@ -29,7 +29,12 @@ export type ProfileView = { id: string, revision: number, name: string, endpoint export type ProfileInput = { id: string | null, revision: number | null, name: string, endpoint: string, authentication: Authentication, caPem: string | null, compatibility: string | null, keepCredential: boolean, credential: CredentialWriteRequest | null, }; export type CredentialState = "not_required" | "stored" | "session_only" | "missing"; export type Fact = { value: T | null, error: ApiFailure | null, }; -export type CheckReport = { connectionId: string, revision: number, checkedAt: number, liveness: Fact, readiness: Fact, identity: Fact, capabilities: Fact, compatibilityVerified: boolean, anonymousAccess: boolean, supportedOperations: Array, }; +export type DiscoveryStatus = "supported" | "missing" | "denied" | "unavailable" | "invalid" | "incompatible"; +export type CompatibilityReason = "product_mismatch" | "schema_version" | "api_version" | "discovery_missing" | "discovery_denied" | "discovery_unavailable" | "invalid_discovery" | "qualification_required" | "qualified_profile" | "feature_missing" | "feature_version" | "operation_missing"; +export type CompatibilityStatus = "qualified" | "unsupported" | "unverified"; +export type OperationCompatibility = { status: CompatibilityStatus, reason: CompatibilityReason, qualificationId: string | null, }; +export type DiscoveryResult = { status: DiscoveryStatus, server: ServerInfo | null, error: ApiFailure | null, reason: CompatibilityReason | null, operations: { [key in string]: OperationCompatibility }, }; +export type CheckReport = { connectionId: string, revision: number, checkedAt: number, liveness: Fact, readiness: Fact, identity: Fact, capabilities: Fact, compatibilityVerified: boolean, anonymousAccess: boolean, supportedOperations: Array, discovery?: DiscoveryResult, }; export type CompatibilityProfile = { id: string, serverCommit: string, contractSha256: string, artifactSha256: string, operations: Array, evidence: string, }; export type ActiveView = { connectionId: string, generation: number, report: CheckReport, scope: ScopeDescriptor | null, }; export type MemoryContext = { connectionId: string, endpoint: string, principal: AccessPrincipal | null, generation: number, scopeId: string, }; @@ -113,6 +118,7 @@ external_skill_registry?: boolean, */ handoff_generation: boolean, search_modes: Array, context_versions: Array, }; export type Configuration = "configured" | "unconfigured" | "unknown"; +export type ContractVersion = { major: number, minor: number, }; export type DreamOperation = "refine_experience" | "derive_skill" | "revise_skill" | "revise_profile" | "revise_memory" | "revise_topic_memory" | "refresh_handoff" | "revise_prompt" | "revise_tags"; export type Effect = "review_then_publish" | "review_then_publish_configuration" | "review_then_replace_tags"; export type ExtractionBackground = { @@ -164,6 +170,7 @@ export type ExtractionStatus = { * Whether a local extraction model or custom pipeline is assembled. Configured does not verify credentials or connectivity. Unknown means execution is external and its configuration is not observed. */ configuration: Configuration, background: ExtractionBackground, observation: ExtractionObservation, }; +export type FeatureContract = { version: ContractVersion, operations: Array, }; export type HealthResponse = { status: string, }; export type Location = "local" | "external" | "none"; export type MatchedBy = "text" | "vector"; @@ -171,6 +178,7 @@ export type MemoryMutationResponse = { changed: boolean, records: Array, next_cursor?: string | export type ScopeQueryField = "scope_id" | "title" | "summary" | "external_reference_value" | "binding_external_id"; export type SearchMemoryRequest = { tag_filter?: TagFilter, scope_id: string, query: string, limit?: number, mode?: MemorySearchMode, }; export type SearchMemoryResponse = { mode: AtomicMemorySearchMode, hits: Array, }; +export type ServerInfo = { +/** + * Compatibility version for this response shape and field semantics. + */ +schema_version: ContractVersion, product: Product, +/** + * Opaque identity of the durable Server deployment. It is unrelated to Access deployment_id and remains stable across restarts, upgrades, backup restore and replicas sharing the same primary database. + */ +server_id: string, package_version: string, +/** + * Major/minor projection of the OpenAPI info.version served by this package. + */ +api_contract_version: ContractVersion, +/** + * Stable feature groups keyed by contract name. + */ +feature_contracts: { [key in string]: FeatureContract }, }; export type ShareUnit = "artifact" | "memory_entry"; export type SourceTypeReference = { /** diff --git a/desktop/ui/src/generated/operations.ts b/desktop/ui/src/generated/operations.ts index 9909a8b309..06889f38b5 100644 --- a/desktop/ui/src/generated/operations.ts +++ b/desktop/ui/src/generated/operations.ts @@ -25,6 +25,10 @@ export const operations = { "method": "GET", "path": "/health/ready" }, + "get_server_info": { + "method": "GET", + "path": "/v1/server-info" + }, "get_capabilities": { "method": "GET", "path": "/v1/capabilities" diff --git a/desktop/ui/tests/connection-transition.test.tsx b/desktop/ui/tests/connection-transition.test.tsx index d3f9e43cbb..87287c6e7f 100644 --- a/desktop/ui/tests/connection-transition.test.tsx +++ b/desktop/ui/tests/connection-transition.test.tsx @@ -55,7 +55,13 @@ const report = { capabilities: fact, compatibilityVerified: true, anonymousAccess: true, - supportedOperations: [], + supportedOperations: [ + "remember_memory", + "search_memory", + "get_artifact_revision", + "list_scopes", + "get_scope", + ], }; const scope = { scope_id: "scope-a", diff --git a/desktop/ui/tests/connections.test.tsx b/desktop/ui/tests/connections.test.tsx index 72eb3b0c40..63713b76f6 100644 --- a/desktop/ui/tests/connections.test.tsx +++ b/desktop/ui/tests/connections.test.tsx @@ -28,7 +28,11 @@ import { answerConfirmation } from "./confirmation"; import { App } from "../src/app/App"; import { Connections } from "../src/app/Connections"; import { desktopApi } from "../src/shared/ipc"; -import type { DesktopState, ProfileView } from "../src/generated/ipc"; +import type { + DesktopState, + DiscoveryResult, + ProfileView, +} from "../src/generated/ipc"; import { contractSha256 } from "../src/generated/operations"; import qualifications from "../../src-tauri/src/connections/compatibility.json"; vi.mock("../src/shared/ipc", () => ({ @@ -91,6 +95,29 @@ function qualifiedState(p = profile): DesktopState { compatibilityProfiles: [historicalCompatibility, currentCompatibility], }; } +function discoveryState(discovery: DiscoveryResult): DesktopState { + const next = qualifiedState({ + ...profile, + compatibility: currentCompatibility.id, + }); + next.reports = [ + { + connectionId: profile.id, + revision: 1, + checkedAt: 1, + liveness: { value: null, error: null }, + readiness: { value: null, error: null }, + identity: { value: null, error: null }, + capabilities: { value: null, error: null }, + compatibilityVerified: discovery.status === "supported", + supportedOperations: + discovery.status === "supported" ? ["list_scopes"] : [], + anonymousAccess: false, + discovery, + }, + ]; + return next; +} beforeEach(() => { vi.clearAllMocks(); }); @@ -98,6 +125,120 @@ afterEach(() => { cleanup(); vi.restoreAllMocks(); }); +const discoveryCases: Array<{ + language: "en" | "zh"; + status: DiscoveryResult["status"]; + reason: DiscoveryResult["reason"]; + expected: string; +}> = [ + { + language: "en", + status: "supported", + reason: null, + expected: "The discovery contract is supported", + }, + { + language: "en", + status: "missing", + reason: "discovery_missing", + expected: "The Server has no discovery endpoint", + }, + { + language: "en", + status: "denied", + reason: "discovery_denied", + expected: "Server discovery access was denied", + }, + { + language: "en", + status: "unavailable", + reason: "discovery_unavailable", + expected: "Server discovery is temporarily unavailable", + }, + { + language: "en", + status: "invalid", + reason: "invalid_discovery", + expected: "The Server discovery response is invalid", + }, + { + language: "en", + status: "incompatible", + reason: "api_version", + expected: "The Server API major version is unsupported", + }, + { + language: "zh", + status: "unavailable", + reason: "discovery_unavailable", + expected: "Server 发现暂时不可用。请检查服务和网络,然后重新检查连接", + }, + { + language: "zh", + status: "denied", + reason: "discovery_denied", + expected: "Server 拒绝访问发现接口。请核对凭据与访问权限", + }, +]; +test.each(discoveryCases)( + "discovery $status has a distinct diagnostic in $language", + ({ language, status, reason, expected }) => { + render( + , + ); + expect(screen.getByText(expected, { exact: false })).toBeTruthy(); + }, +); +test("a successful recheck replaces the temporary discovery failure diagnostic", async () => { + const user = userEvent.setup(); + const unavailable = discoveryState({ + status: "unavailable", + reason: "discovery_unavailable", + error: { code: "timeout", requestId: null, dispatched: true }, + server: null, + operations: {}, + }); + const recovered = discoveryState({ + status: "supported", + reason: null, + error: null, + server: null, + operations: {}, + }); + const onState = vi.fn(); + const props = { + language: "en" as const, + onState, + onDirty: vi.fn(), + initialProfileId: profile.id, + }; + vi.mocked(desktopApi.check).mockResolvedValue(recovered); + const view = render(); + expect( + screen.getByText(/Server discovery is temporarily unavailable/).textContent, + ).toContain("The request timed out."); + await user.click(screen.getByRole("button", { name: "Check connection" })); + expect(desktopApi.check).toHaveBeenCalledWith(profile.id, false); + expect(onState).toHaveBeenCalledWith(recovered); + view.rerender(); + expect( + screen.queryByText(/Server discovery is temporarily unavailable/), + ).toBeNull(); + expect(screen.getByText(/The discovery contract is supported/)).toBeTruthy(); + expect(screen.getByText("Verified")).toBeTruthy(); +}); test("new connections offer only current-contract profiles and keep no selection by default", async () => { const user = userEvent.setup(); render( diff --git a/desktop/ui/tests/feedback.test.tsx b/desktop/ui/tests/feedback.test.tsx index 2d665eddff..e8c628aa6d 100644 --- a/desktop/ui/tests/feedback.test.tsx +++ b/desktop/ui/tests/feedback.test.tsx @@ -73,7 +73,13 @@ const report: CheckReport = { capabilities: fact, compatibilityVerified: true, anonymousAccess: true, - supportedOperations: [], + supportedOperations: [ + "remember_memory", + "search_memory", + "get_artifact_revision", + "list_scopes", + "get_scope", + ], }; const scope = { scope_id: "exact-scope-a", diff --git a/desktop/ui/tests/memory.test.tsx b/desktop/ui/tests/memory.test.tsx index 2a145d9da3..55a404a882 100644 --- a/desktop/ui/tests/memory.test.tsx +++ b/desktop/ui/tests/memory.test.tsx @@ -22,6 +22,7 @@ import { fireEvent, act, waitFor, + within, } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { @@ -35,6 +36,7 @@ import { Overview } from "../src/app/Overview"; import { desktopApi } from "../src/shared/ipc"; import type { ArtifactReference, + CompatibilityReason, DesktopState, MemorySearchResponse, WriteOutcome, @@ -84,7 +86,13 @@ const state: DesktopState = { capabilities: fact, compatibilityVerified: true, anonymousAccess: true, - supportedOperations: [], + supportedOperations: [ + "remember_memory", + "search_memory", + "get_artifact_revision", + "list_scopes", + "get_scope", + ], }, }, compatibilityProfiles: [], @@ -96,6 +104,241 @@ const artifact: ArtifactReference = { artifact_id: "atomic-a", revision: 7, }; +function restrictedState( + operation: string, + reason: CompatibilityReason, +): DesktopState { + const active = state.active!; + return { + ...state, + active: { + ...active, + report: { + ...active.report, + supportedOperations: active.report.supportedOperations.filter( + (item) => item !== operation, + ), + discovery: { + status: "supported", + server: null, + error: null, + reason: null, + operations: { + [operation]: { + status: + reason === "qualification_required" + ? "unverified" + : "unsupported", + reason, + qualificationId: null, + }, + }, + }, + }, + }, + }; +} +test.each(["en", "zh"] as const)( + "unsupported saving preserves independently supported search and exact reads (%s)", + async (language) => { + const user = userEvent.setup(); + const restricted = restrictedState("remember_memory", "operation_missing"); + vi.mocked(desktopApi.search).mockResolvedValue({ + hits: [ + { artifact, text: "supported search", score: 1, matched_by: ["text"] }, + ], + }); + vi.mocked(desktopApi.atomicEntry).mockResolvedValue({ + artifact, + kind: "note", + text: "exact content", + source_refs: [], + }); + render( + , + ); + const input = screen.getByLabelText( + language === "en" ? "Memory text" : "记忆内容", + ) as HTMLTextAreaElement; + expect(input.disabled).toBe(true); + const save = screen.getByRole("button", { + name: language === "en" ? "Save" : "保存", + }) as HTMLButtonElement; + expect(save.disabled).toBe(true); + expect( + screen.getByText( + language === "en" + ? /Server does not declare support for this operation/ + : /Server 未声明支持此操作/, + ), + ).toBeTruthy(); + await user.click(save); + expect(desktopApi.remember).not.toHaveBeenCalled(); + await user.type( + screen.getByLabelText( + language === "en" ? "Keyword search" : "关键词搜索", + ), + "supported", + ); + await user.click( + screen.getByRole("button", { + name: language === "en" ? "Search" : "搜索", + }), + ); + await user.click( + screen.getByRole("button", { + name: language === "en" ? "Read exact version" : "阅读精确版本", + }), + ); + expect(desktopApi.search).toHaveBeenCalledWith(1, "supported"); + expect(desktopApi.atomicEntry).toHaveBeenCalledWith(1, artifact); + expect(screen.getByText("exact content")).toBeTruthy(); + }, +); +test("unqualified exact reads leave search results and saving usable", async () => { + const user = userEvent.setup(); + vi.mocked(desktopApi.search).mockResolvedValue({ + hits: [{ artifact, text: "searchable", score: 1, matched_by: ["text"] }], + }); + render( + , + ); + expect( + (screen.getByLabelText("Memory text") as HTMLTextAreaElement).disabled, + ).toBe(false); + await user.type(screen.getByLabelText("Keyword search"), "query"); + await user.click(screen.getByRole("button", { name: "Search" })); + expect(screen.getAllByText("searchable").length).toBeGreaterThan(0); + const read = screen.getByRole("button", { + name: "Read exact version", + }) as HTMLButtonElement; + expect(read.disabled).toBe(true); + expect( + screen.getByText( + /selected profile has no independent qualification for this operation/, + ), + ).toBeTruthy(); + await user.click(read); + expect(desktopApi.atomicEntry).not.toHaveBeenCalled(); +}); +test("an unavailable search does not disable saving", async () => { + const user = userEvent.setup(); + const restricted = restrictedState("search_memory", "feature_missing"); + vi.mocked(desktopApi.state).mockResolvedValue(restricted); + vi.mocked(desktopApi.remember).mockResolvedValue(outcome("succeeded")); + render( + , + ); + expect( + (screen.getByLabelText("Keyword search") as HTMLInputElement).disabled, + ).toBe(true); + expect( + screen.getByText( + /Server does not declare the feature required for this operation/, + ), + ).toBeTruthy(); + await user.type(screen.getByLabelText("Memory text"), "supported save"); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(desktopApi.remember).toHaveBeenCalledWith(1, "supported save"); + expect(desktopApi.search).not.toHaveBeenCalled(); +}); +test("an aggregate compatibility verdict cannot enable an unlisted save operation", () => { + const active = state.active!; + render( + , + ); + expect( + (screen.getByLabelText("Memory text") as HTMLTextAreaElement).disabled, + ).toBe(true); + expect( + screen.getByText(/This operation is unverified for this connection/), + ).toBeTruthy(); +}); + +test("saved records cannot open an unqualified exact read while saving remains available", async () => { + const user = userEvent.setup(); + const restricted = restrictedState( + "get_artifact_revision", + "qualification_required", + ); + const saved = makeSaved(1); + vi.mocked(desktopApi.remember).mockResolvedValue(saved.outcome); + vi.mocked(desktopApi.state).mockResolvedValue(restricted); + render( + , + ); + await user.type(screen.getByLabelText("Memory text"), "supported save"); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(desktopApi.remember).toHaveBeenCalledWith(1, "supported save"); + const open = screen.getByRole("button", { + name: "Open saved record", + }) as HTMLButtonElement; + expect(open.disabled).toBe(true); + expect( + screen.getAllByText( + /selected profile has no independent qualification for this operation/, + ).length, + ).toBeGreaterThan(0); + await user.click(open); + expect(desktopApi.atomicEntry).not.toHaveBeenCalled(); +}); +test("Overview shows availability and restriction for each feature", () => { + render( + , + ); + const save = within(screen.getByRole("group", { name: "Save memories" })); + expect(save.getByText("Unavailable")).toBeTruthy(); + expect( + save.getByText(/Server does not declare support for this operation/), + ).toBeTruthy(); + expect( + within(screen.getByRole("group", { name: "Full-text search" })).getByText( + "Available", + ), + ).toBeTruthy(); + expect( + within(screen.getByRole("group", { name: "Exact details" })).getByText( + "Available", + ), + ).toBeTruthy(); +}); function outcome(status: "succeeded" | "unknown" | "failed"): WriteOutcome { return { record: { diff --git a/desktop/ui/tests/observation.test.tsx b/desktop/ui/tests/observation.test.tsx index 034340c958..62af1fff03 100644 --- a/desktop/ui/tests/observation.test.tsx +++ b/desktop/ui/tests/observation.test.tsx @@ -166,7 +166,7 @@ test("entering Observation respects the existing Memory draft confirmation", asy capabilities: fact, compatibilityVerified: true, anonymousAccess: true, - supportedOperations: [], + supportedOperations: ["remember_memory"], }, }, }); diff --git a/desktop/ui/tests/scope-navigation.test.tsx b/desktop/ui/tests/scope-navigation.test.tsx index 3afc65a2de..c4b171b51d 100644 --- a/desktop/ui/tests/scope-navigation.test.tsx +++ b/desktop/ui/tests/scope-navigation.test.tsx @@ -69,7 +69,13 @@ const report = { capabilities: fact, compatibilityVerified: true, anonymousAccess: true, - supportedOperations: [], + supportedOperations: [ + "remember_memory", + "search_memory", + "get_artifact_revision", + "list_scopes", + "get_scope", + ], }; const scopeA = { scope_id: "scope-a", diff --git a/desktop/ui/tests/scopes.test.tsx b/desktop/ui/tests/scopes.test.tsx index a92b3cbb93..c950735941 100644 --- a/desktop/ui/tests/scopes.test.tsx +++ b/desktop/ui/tests/scopes.test.tsx @@ -56,10 +56,122 @@ const state: DesktopState = { capabilities: emptyFact, compatibilityVerified: true, anonymousAccess: true, - supportedOperations: ["list_scopes"], + supportedOperations: ["list_scopes", "get_scope"], }, }, }; +test("unsupported Scope selection leaves lookup and pagination available", async () => { + const user = userEvent.setup(); + const active = state.active!; + const partial: DesktopState = { + ...state, + active: { + ...active, + report: { + ...active.report, + supportedOperations: ["list_scopes"], + discovery: { + status: "supported", + reason: null, + error: null, + server: null, + operations: { + get_scope: { + status: "unsupported", + reason: "operation_missing", + qualificationId: null, + }, + }, + }, + }, + }, + }; + vi.mocked(desktopApi.scopes).mockResolvedValue({ + items: [ + { + scope_id: "scope-a", + title: "Listed scope", + summary: "", + context_references: [], + external_references: [], + version: 1, + }, + ], + next_cursor: "opaque-next", + }); + render( + true} + />, + ); + expect(screen.getByText(/Server 未声明支持此操作/)).toBeTruthy(); + await user.click(screen.getByRole("button", { name: "查找范围" })); + const choice = screen.getByRole("button", { + name: "Listed scope", + }) as HTMLButtonElement; + expect(choice.disabled).toBe(true); + await user.click(choice); + expect(desktopApi.selectScope).not.toHaveBeenCalled(); + const more = screen.getByRole("button", { + name: "下一页", + }) as HTMLButtonElement; + expect(more.disabled).toBe(false); + await user.click(more); + expect(desktopApi.scopes).toHaveBeenLastCalledWith(1, "", "opaque-next"); +}); +test("missing Scope lookup is disabled without claiming selection is unsupported", async () => { + const user = userEvent.setup(); + const active = state.active!; + const partial: DesktopState = { + ...state, + active: { + ...active, + report: { + ...active.report, + supportedOperations: ["get_scope"], + discovery: { + status: "supported", + reason: null, + error: null, + server: null, + operations: { + list_scopes: { + status: "unsupported", + reason: "operation_missing", + qualificationId: null, + }, + }, + }, + }, + }, + }; + render( + true} + />, + ); + expect( + (screen.getByLabelText("Find scopes by title") as HTMLInputElement) + .disabled, + ).toBe(true); + const find = screen.getByRole("button", { + name: "Find scopes", + }) as HTMLButtonElement; + expect(find.disabled).toBe(true); + expect(screen.getByText("Scope search is unavailable")).toBeTruthy(); + expect( + screen.getByText(/Server does not declare support for this operation/), + ).toBeTruthy(); + expect(screen.queryByText("Scope selection is unavailable")).toBeNull(); + await user.click(find); + expect(desktopApi.scopes).not.toHaveBeenCalled(); +}); test("editing a query cancels the native read and hides a late response", async () => { const user = userEvent.setup(); let finish!: (page: ScopePage) => void; diff --git a/docs/en/docs/operate/database-migrations.md b/docs/en/docs/operate/database-migrations.md index 8a85ea15dd..3e65a35739 100644 --- a/docs/en/docs/operate/database-migrations.md +++ b/docs/en/docs/operate/database-migrations.md @@ -16,8 +16,8 @@ The design follows [RFC #1771](https://github.com/oceanbase/powercontext/pull/17 The full Server framework registers two installed-release sources for the PowerContext 1.4.1 target (stored compatibility IDs shown below): -- **1.3.0:** `s1300 → s1400 → s1401 → s1402`. -- **1.4.0:** `r1400 → s1400 → s1401 → s1402` through a separate frozen source bridge. +- **1.3.0:** `s1300 → s1400 → s1401 → s1402 → v1_4_1_004`. +- **1.4.0:** `r1400 → s1400 → s1401 → s1402 → v1_4_1_004` through a separate frozen source bridge. Application release numbers and schema revisions are distinct. The 1.4.0 release is not the `s1400` checkpoint: its existing Candidate schema is current, but its Topic attempt storage still needs the registered bridge. @@ -49,6 +49,8 @@ Revision `s1402` registers portable restore receipts and preserves microsecond p Profile, Topic publication, and tag timestamps on MySQL-compatible backends. These schema changes run through explicit maintenance for existing managed storage. Runtime startup does not add the receipt table or alter timestamp columns. +Revision `v1_4_1_004` registers `pc_access_owner_recovery` for durable Artifact and Candidate ownership intents. Both installed-release source paths and vector profiles include this table. Existing managed databases require explicit maintenance; fresh databases create the registered empty table. Pending intents retain their original deployment, principal and idempotency identity across Server restarts. Earlier revision resources and checksums remain unchanged. Unregistered database layouts are rejected rather than adopted from a table name alone. This registration does not establish installed-release or external-Provider upgrade acceptance. + An interrupted [portable restore](portable-archive.md) keeps normal startup and workers blocked until its projections are complete. Retry `powercontext archive restore --yes` with the same validated bundle. Only this explicit recovery path can open an incomplete projection set, after validating the registered layout and the configured vector diff --git a/docs/zh/docs/operate/database-migrations.md b/docs/zh/docs/operate/database-migrations.md index 667ace4c98..721787250c 100644 --- a/docs/zh/docs/operate/database-migrations.md +++ b/docs/zh/docs/operate/database-migrations.md @@ -14,8 +14,8 @@ description: 了解数据库迁移命令、备份策略、服务启停及当前 完整 Server 框架登记了两个真实安装包来源: -- **1.3.0:**`s1300 → s1400 → s1401 → s1402`。 -- **1.4.0:**通过独立冻结的来源桥接,执行 `r1400 → s1400 → s1401 → s1402`。 +- **1.3.0:**`s1300 → s1400 → s1401 → s1402 → v1_4_1_004`。 +- **1.4.0:**通过独立冻结的来源桥接,执行 `r1400 → s1400 → s1401 → s1402 → v1_4_1_004`。 应用发布版本与 schema revision 分别编号。1.4.0 发行包不等于 `s1400` 检查点:其 Candidate 结构已经是当前格式, 但 Topic 尝试状态仍需登记的桥接。两条路径保留既有引用和历史,到达相同的受管目标结构;原有资源摘要分别保留, @@ -42,6 +42,8 @@ payload 身份及待处理 intent。兼容的当前任务原样保留,不套 `s1402` 登记可移植归档的恢复回执,并为 MySQL 兼容后端中可移植的 Artifact、Profile、Topic 发布及标签时间戳 保留微秒精度。已有受管库通过显式维护执行这些结构变更;运行时启动不补建回执表,也不修改时间戳列。 +修订 `v1_4_1_004` 将 `pc_access_owner_recovery` 纳入管理,用于持久保存 Artifact 和 Candidate 的所有权写入意图。两条已登记发布源路径及向量配置均包含此表。已有受管数据库需要显式维护,新数据库创建已登记的空表。待恢复意图在 Server 重启后保留原有 deployment、Principal 与幂等身份;历史修订资源及校验和保持不变。未登记布局不会仅凭表名被自动接纳。此登记不代表已通过安装发布版或外部 Provider 的升级验收。 + [可移植归档恢复](portable-archive.md) 中断后,普通启动和 worker 会继续拒绝未完成的检索投影。 请使用同一个通过校验的归档,重新执行 `powercontext archive restore --yes`。 仅此显式恢复路径可在验证已登记结构和配置的向量 profile 后打开投影尚未完整的数据库,且不启动 worker。 diff --git a/release/upgrade-support.json b/release/upgrade-support.json index c0afba9bf2..a34cf9674f 100644 --- a/release/upgrade-support.json +++ b/release/upgrade-support.json @@ -3,8 +3,8 @@ "target_version": "1.4.1", "mode": "upgrade-required", "schema_review": { - "persistence_sha256": "9b67d639cf57b3ae7cf37dcd1845f50561af36bb19edd9a7b979408f31e9a6de", - "rationale": "The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB full-server-code and full-server-vector-code are temporarily manual-only due to native DDL waits with the available engine. Main and publication require the other ten; no manual result is needed for publication. The two deferred configurations remain unverified and are excluded from generated supported upgrade declarations. Reports retain their identities and explicitly record incomplete full-matrix acceptance. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged." + "persistence_sha256": "99d448c2b9f3a3ef23a5e348a747d9e277c4cca13ad3bee475b26d10faabac98", + "rationale": "The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB full-server-code and full-server-vector-code are temporarily manual-only due to native DDL waits with the available engine. Main and publication require the other ten; no manual result is needed for publication. The two deferred configurations remain unverified and are excluded from generated supported upgrade declarations. Reports retain their identities and explicitly record incomplete full-matrix acceptance. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the same automatic matrix, manual-only configurations and publication restrictions." }, "cases": [], "automatic_sources": { diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json b/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json index 5664018968..65c518659d 100644 --- a/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json +++ b/src/powercontext/builtin/persistence/migrations/server_resources/manifest.json @@ -20,6 +20,10 @@ "s1402": [ "schemas/sqlite-s1402.json", "schemas/mysql-s1402.json" + ], + "v1_4_1_004": [ + "schemas/sqlite-v1_4_1_004.json", + "schemas/mysql-v1_4_1_004.json" ] }, "sqlite_baselines": { @@ -37,6 +41,9 @@ ], "s1402": [ "795b6fd01188c15d16625c59506aadc42134dc8293ffdd4a1588a04f8f66e877" + ], + "v1_4_1_004": [ + "84d736b5e722a56ebe8a32318732543d43548a63a43709dbf0c571e7e4af83b5" ] }, "affected_objects": [ @@ -130,7 +137,8 @@ "pc_retained_dream_candidate_heads", "pc_retained_dream_candidate_versions", "pc_memory_artifact_archive", - "pc_portable_restore_receipts" + "pc_portable_restore_receipts", + "pc_access_owner_recovery" ], "readiness_scope": "server", "retained_objects": [ @@ -183,6 +191,10 @@ "s1402": [ "server_upgrade", "portable_storage" + ], + "v1_4_1_004": [ + "server_upgrade", + "portable_storage" ] }, "retained_fingerprints": { @@ -197,7 +209,8 @@ "schemas/mysql-s1300.json", "schemas/mysql-s1400.json", "schemas/mysql-s1401.json", - "schemas/mysql-s1402.json" + "schemas/mysql-s1402.json", + "schemas/mysql-v1_4_1_004.json" ], "mysql_history": "mysql", "mysql_schema_extensions": { diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/mysql/versions/v1_4_1_004.py b/src/powercontext/builtin/persistence/migrations/server_resources/mysql/versions/v1_4_1_004.py new file mode 100644 index 0000000000..493a5d8e14 --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/mysql/versions/v1_4_1_004.py @@ -0,0 +1,24 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Register durable external-owner intents through the shared DDL executor.""" + +from alembic import context + +revision = "v1_4_1_004" +down_revision = "s1402" + + +def upgrade() -> None: + context.config.attributes["execute_revision"](revision) diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/schemas/mysql-v1_4_1_004.json b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/mysql-v1_4_1_004.json new file mode 100644 index 0000000000..58815f0db5 --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/mysql-v1_4_1_004.json @@ -0,0 +1,112 @@ +{ + "format": "powercontext.mysql-state-layouts.v1", + "revisions": { + "v1_4_1_004": { + "statements": [ + "CREATE TABLE pc_access_owner_recovery (\n\toperation_id VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\tdeployment_id VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\tscope_id VARCHAR(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\tcompleted TINYINT(1) NOT NULL, \n\tpayload TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, \n\tPRIMARY KEY (operation_id), \n\tCONSTRAINT uq_pc_access_owner_recovery_pending UNIQUE (deployment_id, completed, operation_id)\n)" + ], + "changes": [ + { + "pc_access_owner_recovery": { + "columns": { + "operation_id": { + "type": [ + "varchar", + [ + "64" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "deployment_id": { + "type": [ + "varchar", + [ + "128" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "scope_id": { + "type": [ + "varchar", + [ + "256" + ] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + }, + "completed": { + "type": [ + "tinyint", + [ + "1" + ] + ], + "nullable": false, + "default": null, + "charset": null, + "collation": null, + "extra": [] + }, + "payload": { + "type": [ + "text", + [] + ], + "nullable": false, + "default": null, + "charset": "utf8mb4", + "collation": "utf8mb4_bin", + "extra": [] + } + }, + "primary_key": [ + [ + "operation_id", + null, + "asc" + ] + ], + "foreign_keys": [], + "checks": {}, + "indexes": { + "uq_pc_access_owner_recovery_pending": { + "columns": [ + [ + "deployment_id", + null, + "asc" + ], + [ + "completed", + null, + "asc" + ], + [ + "operation_id", + null, + "asc" + ] + ], + "unique": true + } + } + } + } + ] + } + } +} diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/schemas/sqlite-v1_4_1_004.json b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/sqlite-v1_4_1_004.json new file mode 100644 index 0000000000..3f8c2c8d86 --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/schemas/sqlite-v1_4_1_004.json @@ -0,0 +1,3 @@ +{ + "create": "CREATE TABLE pc_access_owner_recovery (\n\toperation_id VARCHAR(64) NOT NULL, \n\tdeployment_id VARCHAR(128) NOT NULL, \n\tscope_id VARCHAR(256) NOT NULL, \n\tcompleted BOOLEAN NOT NULL, \n\tpayload TEXT NOT NULL, \n\tPRIMARY KEY (operation_id), \n\tCONSTRAINT uq_pc_access_owner_recovery_pending UNIQUE (deployment_id, completed, operation_id)\n)" +} diff --git a/src/powercontext/builtin/persistence/migrations/server_resources/versions/v1_4_1_004_owner_recovery.py b/src/powercontext/builtin/persistence/migrations/server_resources/versions/v1_4_1_004_owner_recovery.py new file mode 100644 index 0000000000..94bb8decbd --- /dev/null +++ b/src/powercontext/builtin/persistence/migrations/server_resources/versions/v1_4_1_004_owner_recovery.py @@ -0,0 +1,28 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Register durable external-owner intents without rewriting historical layouts.""" + +import json +from pathlib import Path + +from alembic import op + +revision = "v1_4_1_004" +down_revision = "s1402" + + +def upgrade(): + resource = Path(__file__).parents[1] / "schemas/sqlite-v1_4_1_004.json" + op.get_bind().exec_driver_sql(json.loads(resource.read_text(encoding="utf-8"))["create"]) diff --git a/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json b/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json index 5c06c6a39b..0e52e9ff79 100644 --- a/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json +++ b/src/powercontext/builtin/persistence/migrations/server_sources/1.4.0/manifest.json @@ -19,6 +19,10 @@ "release1400_operations.py", "schemas/mysql-r1400.json", "source-provenance.json" + ], + "v1_4_1_004": [ + "schemas/sqlite-v1_4_1_004.json", + "schemas/mysql-v1_4_1_004.json" ] }, "sqlite_baselines": { @@ -36,6 +40,9 @@ ], "r1400": [ "374ad3217e4dc286c3942708da52cc8262e30581e2b836bedd0c4e693f1b75bc" + ], + "v1_4_1_004": [ + "84d736b5e722a56ebe8a32318732543d43548a63a43709dbf0c571e7e4af83b5" ] }, "affected_objects": [ @@ -129,7 +136,8 @@ "pc_retained_dream_candidate_heads", "pc_retained_dream_candidate_versions", "pc_memory_artifact_archive", - "pc_portable_restore_receipts" + "pc_portable_restore_receipts", + "pc_access_owner_recovery" ], "readiness_scope": "server", "retained_objects": [ @@ -187,6 +195,10 @@ "s1402": [ "server_upgrade", "portable_storage" + ], + "v1_4_1_004": [ + "server_upgrade", + "portable_storage" ] }, "retained_fingerprints": { @@ -201,7 +213,8 @@ "schemas/mysql-r1400.json", "schemas/mysql-s1400.json", "schemas/mysql-s1401.json", - "schemas/mysql-s1402.json" + "schemas/mysql-s1402.json", + "schemas/mysql-v1_4_1_004.json" ], "mysql_history": "mysql", "mysql_schema_extensions": { diff --git a/src/powercontext/builtin/persistence/migrations/vector_profile.py b/src/powercontext/builtin/persistence/migrations/vector_profile.py index 3b00999970..f2a4d2814d 100644 --- a/src/powercontext/builtin/persistence/migrations/vector_profile.py +++ b/src/powercontext/builtin/persistence/migrations/vector_profile.py @@ -80,6 +80,11 @@ def sqlite_layouts(self, directory: Path) -> dict[str, list[list[Any]]]: layouts["s1402"] = layouts["s1401"] + [ ["table", "pc_portable_restore_receipts", "pc_portable_restore_receipts", receipt] ] + if "v1_4_1_004" in manifest["revision_resources"]: + owner = json.loads((directory / "schemas/sqlite-v1_4_1_004.json").read_text(encoding="utf-8"))["create"] + layouts["v1_4_1_004"] = layouts["s1402"] + [ + ["table", "pc_access_owner_recovery", "pc_access_owner_recovery", owner] + ] for entries in layouts.values(): entries.sort(key=lambda row: (row[0], row[1])) return layouts diff --git a/tests/builtin/persistence/test_full_server_migrations.py b/tests/builtin/persistence/test_full_server_migrations.py index 5c4b975d60..8a764c7b55 100644 --- a/tests/builtin/persistence/test_full_server_migrations.py +++ b/tests/builtin/persistence/test_full_server_migrations.py @@ -73,8 +73,8 @@ def dump(path): def test_complete_upgrade_preserves_history_backup_and_repeated_apply(source): before = dump(source.database) plan = source.plan() - assert plan.source_revision == "s1300" and plan.target_revision == "s1402" - assert plan.revisions == ("s1400", "s1401", "s1402") + assert plan.source_revision == "s1300" and plan.target_revision == "v1_4_1_004" + assert plan.revisions == ("s1400", "s1401", "s1402", "v1_4_1_004") assert dump(source.database) == before result = apply(source) assert result.readiness_scope == "server" and result.backup_state == "completed" diff --git a/tests/builtin/persistence/test_mysql_migration_runner.py b/tests/builtin/persistence/test_mysql_migration_runner.py index 9113bf677b..61cb536104 100644 --- a/tests/builtin/persistence/test_mysql_migration_runner.py +++ b/tests/builtin/persistence/test_mysql_migration_runner.py @@ -561,7 +561,7 @@ def test_oceanbase_server_upgrade_with_separate_code_cache_preserves_history( ) assert runner.plan(backup_policy="manual").source_revision == "s1300" result = _apply(runner, policy="manual") - assert result.readiness_scope == "server" and result.revision == "s1402" + assert result.readiness_scope == "server" and result.revision == "v1_4_1_004" assert runner.verify().state == "ready" prepare_server_storage(settings) assert not _apply(runner, policy="manual").changed @@ -692,7 +692,7 @@ def inspect_history(connection, identity, guard): ).scalar_one(), ) - assert backend.connections().run(inspect_history) == ("s1402", "dedicated", b'{"history":"unchanged"}') + assert backend.connections().run(inspect_history) == ("v1_4_1_004", "dedicated", b'{"history":"unchanged"}') (main_path,) = backend.evidence_directory.glob("*/maintenance.json") evidence = json.loads(main_path.read_text()) @@ -702,7 +702,7 @@ def inspect_history(connection, identity, guard): for inspect in (runner.plan, runner.verify, runner.apply): with pytest.raises(MigrationError, match="checksum_conflict"): inspect() - assert backend.connections().run(inspect_history) == ("s1402", "dedicated", b'{"history":"unchanged"}') + assert backend.connections().run(inspect_history) == ("v1_4_1_004", "dedicated", b'{"history":"unchanged"}') assert { path: path.read_bytes() for path in backend.evidence_directory.rglob("maintenance.json") } == original_evidence @@ -769,7 +769,7 @@ def inspect_history(connection, identity, guard): ).scalar_one(), ) - assert backend.connections().run(inspect_history) == ("s1402", b'{"history":"unchanged"}') + assert backend.connections().run(inspect_history) == ("v1_4_1_004", b'{"history":"unchanged"}') def test_mysql_registered_projection_repair_preserves_authority_and_revision(backend: _BackendTarget) -> None: @@ -837,7 +837,7 @@ def inspect_content(connection, identity, guard): ).scalar_one(), ) - assert backend.connections().run(inspect_content) == ("s1402", content, "Preserve immutable nebula evidence.") + assert backend.connections().run(inspect_content) == ("v1_4_1_004", content, "Preserve immutable nebula evidence.") @pytest.mark.parametrize("origin", ("empty", "released")) @@ -992,7 +992,7 @@ def test_mysql_full_server_interruption_preserves_history_and_original_maintenan _load_full_server_baseline(backend) runner = _full_server_runner(backend) original = runner.plan(backup_policy="manual") - assert original.source_revision == "s1300" and original.target_revision == "s1402" + assert original.source_revision == "s1300" and original.target_revision == "v1_4_1_004" _interrupt_after_ddl(runner, interruption) journals = list(backend.evidence_directory.rglob("maintenance.json")) assert len(journals) == 1 @@ -1014,7 +1014,7 @@ def test_mysql_full_server_interruption_preserves_history_and_original_maintenan result = _apply(resumed, policy="manual") - assert result.readiness_scope == "server" and result.revision == "s1402" + assert result.readiness_scope == "server" and result.revision == "v1_4_1_004" assert result.backup_state == "user_confirmed" assert result.backup_ref == interrupted["manual_ref"] assert resumed.verify().state == "ready" @@ -1094,7 +1094,7 @@ def client_active(connection: Connection | None, _identity: BackendIdentity, _gu # interruption. An arbitrary remote failure cannot be acknowledged blindly. resumed = _full_server_runner(backend, acknowledge_previous_run=token) result = _apply(resumed, policy="manual") - assert result.state == "ready" and result.readiness_scope == "server" and result.revision == "s1402" + assert result.state == "ready" and result.readiness_scope == "server" and result.revision == "v1_4_1_004" assert result.backup_state == "user_confirmed" and result.backup_ref == interrupted["manual_ref"] assert resumed.verify().state == "ready" completed = json.loads(journals[0].read_text(encoding="utf-8")) diff --git a/tests/builtin/persistence/test_owner_recovery_migration.py b/tests/builtin/persistence/test_owner_recovery_migration.py new file mode 100644 index 0000000000..e91b321acb --- /dev/null +++ b/tests/builtin/persistence/test_owner_recovery_migration.py @@ -0,0 +1,116 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Append owner recovery storage without changing historical migration evidence.""" + +import json +import shutil +import sqlite3 +from contextlib import closing + +import pytest + +from powercontext.builtin.artifacts.memory import EmbeddingProfile +from powercontext.builtin.persistence.migrations.bundle import MigrationBundle +from powercontext.builtin.persistence.migrations.deployment import server_bundle +from powercontext.builtin.persistence.migrations.models import MigrationError +from powercontext.builtin.persistence.migrations.mysql_schema import MySQLSchema +from powercontext.builtin.persistence.migrations.sqlite import SQLiteMigrationRunner +from tests.builtin.persistence.test_mysql_migration_schema import _inventory, _ReflectedDatabase +from tests.builtin.persistence.test_portable_storage_migration import apply, configuration + + +@pytest.mark.parametrize("vectors", [False, True]) +def test_registered_owner_recovery_upgrade_preserves_history_and_revision_checksums(tmp_path, vectors): + embedding = EmbeddingProfile(profile_id="owner-vectors", model="fixture", dimension=3) if vectors else None + current = server_bundle(embedding_profile=embedding) + directory = tmp_path / "previous" + shutil.copytree(current.directory, directory, ignore=shutil.ignore_patterns("__pycache__")) + manifest_path = directory / "manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + resources = manifest["revision_resources"].pop("v1_4_1_004") + for resource in (*resources, "versions/v1_4_1_004_owner_recovery.py", "mysql/versions/v1_4_1_004.py"): + (directory / resource).unlink() + del manifest["sqlite_fingerprints"]["v1_4_1_004"] + del manifest["domain_readiness"]["v1_4_1_004"] + manifest["mysql_state_layouts"].remove("schemas/mysql-v1_4_1_004.json") + manifest["affected_objects"].remove("pc_access_owner_recovery") + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + previous = MigrationBundle(directory, embedding_profile=embedding) + database = tmp_path / "managed.db" + old = SQLiteMigrationRunner(database, previous, configuration=configuration(embedding)) + assert apply(old).revision == "s1402" + with closing(sqlite3.connect(database)) as connection, connection: + connection.execute( + "INSERT INTO pc_scopes (scope_id,title,summary,scope_id_search,title_search,summary_search,version) " + "VALUES ('original','title','summary','original','title','summary',1)" + ) + original_evidence = json.loads(old.evidence_path.read_text(encoding="utf-8")) + upgraded = SQLiteMigrationRunner(database, current, configuration=configuration(embedding)) + plan = upgraded.plan() + assert plan.source_revision == "s1402" and plan.revisions == ("v1_4_1_004",) + assert apply(upgraded).revision == "v1_4_1_004" + assert upgraded.verify().state == "ready" + assert not apply(upgraded).changed + evidence = json.loads(upgraded.evidence_path.read_text(encoding="utf-8")) + for revision, checksum in original_evidence["release_checksums"].items(): + assert evidence["release_checksums"][revision] == checksum + with closing(sqlite3.connect(database)) as connection: + assert connection.execute("SELECT scope_id,title,version FROM pc_scopes").fetchall() == [ + ("original", "title", 1) + ] + assert connection.execute("SELECT COUNT(*) FROM pc_access_owner_recovery").fetchone() == (0,) + fresh = SQLiteMigrationRunner(tmp_path / "fresh.db", current, configuration=configuration(embedding)) + apply(fresh) + assert upgraded.plan().schema_fingerprint == fresh.plan().schema_fingerprint + + +@pytest.mark.parametrize("damage", [None, "payload-collation", "pending-index"]) +def test_owner_recovery_mysql_registration_matches_native_character_and_key_definitions(damage): + # Simulated SHOW output checks normalization, not execution on a native backend. + definition = """CREATE TABLE `pc_access_owner_recovery` ( + `operation_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, + `deployment_id` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, + `scope_id` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, + `completed` tinyint(1) NOT NULL, + `payload` text CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, + PRIMARY KEY (`operation_id`), + UNIQUE KEY `uq_pc_access_owner_recovery_pending` (`deployment_id`,`completed`,`operation_id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci""" + bundle = server_bundle() + inventory = {"tables": {}, "views": [], "triggers": []} + for revision in bundle.revisions[:-1]: + path = bundle.directory / f"schemas/mysql-{revision}.json" + fragment = json.loads(path.read_text(encoding="utf-8")) + for change in fragment["revisions"][revision]["changes"]: + for name, table in change.items(): + if table is None: + del inventory["tables"][name] + else: + inventory["tables"][name] = table + table = _inventory(_ReflectedDatabase({"pc_access_owner_recovery": definition}))["tables"][ + "pc_access_owner_recovery" + ] + inventory["tables"]["pc_access_owner_recovery"] = table + if damage == "payload-collation": + table["columns"]["payload"]["collation"] = "utf8mb4_general_ci" + elif damage == "pending-index": + table["indexes"] = {} + schema = MySQLSchema(bundle) + if damage is None: + schema.verify(inventory, "v1_4_1_004") + assert schema.identify(inventory) == "v1_4_1_004" + else: + with pytest.raises(MigrationError, match="incompatible_schema"): + schema.verify(inventory, "v1_4_1_004") diff --git a/tests/builtin/persistence/test_portable_storage_migration.py b/tests/builtin/persistence/test_portable_storage_migration.py index 39b299ab3d..16724dd2b2 100644 --- a/tests/builtin/persistence/test_portable_storage_migration.py +++ b/tests/builtin/persistence/test_portable_storage_migration.py @@ -35,6 +35,13 @@ def previous_bundle(directory, embedding): shutil.copytree(current.directory, directory, ignore=shutil.ignore_patterns("__pycache__")) manifest_path = directory / "manifest.json" manifest = json.loads(manifest_path.read_text()) + owner_resources = manifest["revision_resources"].pop("v1_4_1_004") + for resource in (*owner_resources, "versions/v1_4_1_004_owner_recovery.py", "mysql/versions/v1_4_1_004.py"): + (directory / resource).unlink() + del manifest["sqlite_fingerprints"]["v1_4_1_004"] + del manifest["domain_readiness"]["v1_4_1_004"] + manifest["mysql_state_layouts"].remove("schemas/mysql-v1_4_1_004.json") + manifest["affected_objects"].remove("pc_access_owner_recovery") removed = manifest["revision_resources"].pop("s1402") for resource in (*removed, "versions/s1402_portable_storage.py", "mysql/versions/s1402.py", "portable_storage.py"): (directory / resource).unlink() @@ -86,8 +93,8 @@ def test_registered_s1401_upgrade_preserves_completed_evidence_and_matches_fresh upgraded = SQLiteMigrationRunner(database, bundle, configuration=config) plan = upgraded.plan() assert plan.source_revision == "s1401" - assert plan.revisions == ("s1402",) - assert apply(upgraded).revision == "s1402" + assert plan.revisions == ("s1402", "v1_4_1_004") + assert apply(upgraded).revision == "v1_4_1_004" assert upgraded.verify().state == "ready" assert not apply(upgraded).changed fresh = SQLiteMigrationRunner(tmp_path / "fresh.db", bundle, configuration=config) diff --git a/tests/builtin/persistence/test_release140_server_migrations.py b/tests/builtin/persistence/test_release140_server_migrations.py index 699e054f8f..fcaeef4336 100644 --- a/tests/builtin/persistence/test_release140_server_migrations.py +++ b/tests/builtin/persistence/test_release140_server_migrations.py @@ -134,7 +134,7 @@ def test_registered_sources_choose_distinct_lineages(tmp_path, release, expected _settings, _embedding, runner = _source(tmp_path, release=release) plan = runner.plan() assert plan.source_revision == expected - assert plan.revisions == ("s1400", "s1401", "s1402") + assert plan.revisions == ("s1400", "s1401", "s1402", "v1_4_1_004") @pytest.mark.parametrize(("vectors", "code"), [(False, False), (True, False), (False, True), (True, True)]) diff --git a/tests/native/test_oceanbase_engine_recovery.py b/tests/native/test_oceanbase_engine_recovery.py index 480febf54c..7f144e8f6b 100644 --- a/tests/native/test_oceanbase_engine_recovery.py +++ b/tests/native/test_oceanbase_engine_recovery.py @@ -175,7 +175,7 @@ def ping(connection, _identity, _guard): _apply(_full_server_runner(backend), policy="manual") resumed = _full_server_runner(backend, acknowledge_previous_run=token) result = _apply(resumed, policy="manual") - assert result.state == "ready" and result.revision == "s1402" and result.readiness_scope == "server" + assert result.state == "ready" and result.revision == "v1_4_1_004" and result.readiness_scope == "server" assert result.backup_state == "user_confirmed" and result.backup_ref == interrupted["manual_ref"] assert resumed.verify().state == "ready" completed = json.loads(journal.read_text()) diff --git a/tests/native/test_personal_service_lifecycle.py b/tests/native/test_personal_service_lifecycle.py index 87bae12cf0..6d17946926 100644 --- a/tests/native/test_personal_service_lifecycle.py +++ b/tests/native/test_personal_service_lifecycle.py @@ -401,7 +401,7 @@ def test_native_public_migration_switches_an_installed_130_service( if failure in {"startup", "switch"}: assert applied.exit_code == 1, applied.output assert result["error"] == "service_start_failed" - assert result["database_state"] == "ready" and result["revision"] == "s1402" + assert result["database_state"] == "ready" and result["revision"] == "v1_4_1_004" assert adapter.manager_state() in {ManagerState.INACTIVE, ManagerState.FAILED} phase = "switching" if failure == "switch" else "start_failed" assert json.loads(controller.maintenance_path.read_text())["phase"] == phase diff --git a/tests/test_managed_atomic_maintenance.py b/tests/test_managed_atomic_maintenance.py index d7e87d6270..68f5f77e5c 100644 --- a/tests/test_managed_atomic_maintenance.py +++ b/tests/test_managed_atomic_maintenance.py @@ -76,7 +76,7 @@ def test_atomic_alias_upgrades_complete_historical_server_with_shared_plan_and_b assert inspected.exit_code == 0, inspected.output plan = json.loads(inspected.output) assert plan["source_revision"] == "s1300" - assert plan["target_revision"] == "s1402" + assert plan["target_revision"] == "v1_4_1_004" assert plan["readiness_scope"] == "server" assert historical.read_bytes() == original @@ -103,7 +103,7 @@ def test_atomic_alias_upgrades_complete_historical_server_with_shared_plan_and_b with closing(sqlite3.connect(result["backup_ref"])) as connection: assert tuple(connection.iterdump()) == original_dump with closing(sqlite3.connect(historical)) as connection: - assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("s1402",)] + assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_4_1_004",)] assert connection.execute("SELECT content FROM pc_artifacts").fetchall() == [(b'{"history":"unchanged"}',)] verified = CliRunner().invoke(cli, [*arguments, "--action", "verify"]) assert verified.exit_code == 0, verified.output diff --git a/tests/test_managed_processing_maintenance.py b/tests/test_managed_processing_maintenance.py index c1857ad893..d1d06578f0 100644 --- a/tests/test_managed_processing_maintenance.py +++ b/tests/test_managed_processing_maintenance.py @@ -75,7 +75,7 @@ def test_registered_mode_switch_backs_up_preserves_revision_and_fences_old_worke assert result.backup_state == "completed" assert result.backup_ref and Path(result.backup_ref).is_file() with closing(sqlite3.connect(path)) as connection: - assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("s1402",)] + assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_4_1_004",)] assert ( json.loads(connection.execute("SELECT config_manifest FROM pc_artifact_processing_schema").fetchone()[0])[ "mode" diff --git a/tests/test_migration_revision_names.py b/tests/test_migration_revision_names.py index 562f82f9ab..3db38c5731 100644 --- a/tests/test_migration_revision_names.py +++ b/tests/test_migration_revision_names.py @@ -54,9 +54,14 @@ def invoke(action, *options): assert status["source_migration"] == plan["source_migration"] == expected_source assert plan["plan_id"] == reviewed.plan_id assert runner.database.read_bytes() == original - assert [item["name"] for item in plan["pending_migrations"]] == ["v1_4_1_001", "v1_4_1_002", "v1_4_1_003"] + assert [item["name"] for item in plan["pending_migrations"]] == [ + "v1_4_1_001", + "v1_4_1_002", + "v1_4_1_003", + "v1_4_1_004", + ] assert [item["revision"] for item in plan["pending_migrations"]] == list(reviewed.revisions) - target = {"revision": "s1402", "name": "v1_4_1_003", "software_version": "1.4.1", "sequence": 3} + target = {"revision": "v1_4_1_004", "name": "v1_4_1_004", "software_version": "1.4.1", "sequence": 4} assert plan["target_migration"] == target applied = invoke( @@ -71,11 +76,11 @@ def invoke(action, *options): ) assert applied["migration"] == target and applied["server_ready"] with closing(sqlite3.connect(runner.database)) as connection: - assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("s1402",)] + assert connection.execute("SELECT version_num FROM pc_schema_revision").fetchall() == [("v1_4_1_004",)] evidence = runner.evidence_path.read_bytes() recorded = json.loads(evidence) assert recorded["source_revision"] == expected_source["revision"] - assert set(recorded["release_checksums"]) == {expected_source["revision"], "s1400", "s1401", "s1402"} + assert set(recorded["release_checksums"]) == {expected_source["revision"], "s1400", "s1401", "s1402", "v1_4_1_004"} assert runner.verify().state == "ready" assert invoke("verify")["migration"] == target repeated = invoke("apply") diff --git a/tests/test_registered_source_maintenance_cli.py b/tests/test_registered_source_maintenance_cli.py index e4d6b2c13e..7cdbb5ce2c 100644 --- a/tests/test_registered_source_maintenance_cli.py +++ b/tests/test_registered_source_maintenance_cli.py @@ -63,7 +63,7 @@ def test_release140_compatibility_commands_preserve_source_and_share_full_upgrad planned = CliRunner().invoke(cli, [*arguments, "plan", "--backup", "skip"]) assert planned.exit_code == 0, planned.output plan = json.loads(planned.output) - assert plan["source_revision"] == "r1400" and plan["target_revision"] == "s1402" + assert plan["source_revision"] == "r1400" and plan["target_revision"] == "v1_4_1_004" assert plan["readiness_scope"] == "server" full = CliRunner().invoke(cli, ["server", "db-migrate", "plan", "--backup", "skip"]) assert full.exit_code == 0, full.output