diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index cb39853f81..5c2d0271f8 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -2755,3 +2755,93 @@ installed-platform acceptance remain separate requirements. 连接模式均通过。原生协议模块和业务断言保持不变;本机验收将 Server 启动就绪等待设为 60 秒, 不代表默认启动预算通过,也不构成启动性能承诺。该记录不替代安装后 GUI、原生凭据持久化、 Windows/macOS、数据库升级、签名或正式发行验收。 + +## Task stop reason contract protocol qualification + +`sqlite-task-stop-reason-0b434770-v1` qualifies all twelve Desktop protocol operations against +Server source `0b43477001e3453a79b310b40fc3e3e7e648c2a6`. Its OpenAPI contract adds the optional +Task Outcome stop reason; the Desktop operation set and runtime behavior are unchanged. + +- Normalized OpenAPI SHA-256: `34cc6572321296c6d67d2a8ca1dffd93d8ebb187a54af8f6dcdb5cd489a0926c`. +- Wheel: `powercontext-1.5.1.dev129+g0b4347700-py3-none-any.whl`. +- Wheel SHA-256: `f572a91a6796d645c6545eaaa8278a2c4b1598b83fa8392df754e187277ab490`. +- Native debug probe SHA-256: `584859ac181e7abe9d6fc84e69c9d8993446837788c630280c0780744fd4f023`. + +All 738 packaged runtime files match the recorded Git source byte for byte, with no missing or +extra runtime files. The wheel was built from the clean Server commit before Desktop generation +and qualification changes. The native probe was built from that commit with the regenerated +Desktop contract and new bundled profile present as working-tree changes, using the product +Cargo lock and Rust 1.95.0, without `ci-fixtures`. + +On 2026-11-10, macOS 26.5.1 ARM64 and Python 3.13.15 passed all four modes in the unchanged +`desktop/tests/real_server.py`: anonymous loopback, static Bearer, HTTPS with explicit CA/base +path, and enforced Provider access. Each case reports `bundled product records` qualification +through the ordinary product ConnectionManager. Checks cover discovery, Scope selection, +statistics, Memory save/search/exact revision reads, committed writes with lost responses +without replay, and independent Server survival after client exit. Provider mode also checks +Principal changes, same-identity revocation, scoped authorization, and 51 same-title Scopes. +Statistics usage is controlled fixture input, not an external model-provider execution claim. + +The source verification, exact wheel, native build log, probe identity and real-Server report +are retained under ignored `desktop/.artifacts/issue-2544/`. Historical qualification records +retain their exact source, contract, artifact identities and operation sets. This run qualifies +the observed local SQLite protocol, not installed WebView behavior, native credential persistence, +other operating systems, external databases, production deployment, or release acceptance. +The Desktop probe exercises its existing operations; the new stop reason's recording and +readback are covered by the separate Work/HTTP SQLite tests, not by a Desktop UI flow. + +Reproduce against the recorded Server source and artifact: + +```sh +pnpm --dir desktop generate +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +# The harness requires exactly this wheel under desktop/.artifacts/server-wheel/. +uv run --no-sync python desktop/tests/real_server.py \ + --product-qualification sqlite-task-stop-reason-0b434770-v1 +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml \ + --test session bundled_product_qualification_covers_every_desktop_operation +``` + +## Task stop reason merged contract protocol qualification + +`sqlite-task-stop-reason-4cb70619-v1` qualifies all thirteen bundled Desktop protocol operations +against Server source `4cb7061913f5484c3b848551c1d570e59bab846f`, including connection identity. + +- Normalized OpenAPI SHA-256: `e1ff2e3ad1d6a09a9288c4c66e111a54c4979026e29806ff70543988b8e29220`. +- Wheel: `powercontext-1.5.2.dev5+g4cb706191-py3-none-any.whl`. +- Wheel SHA-256: `e4c0d3f7549fe28abfd09669c3dc53ded66d79a4711b1e89da93611717b64a76`. +- Native debug probe SHA-256: `6685c55fac1cacf45292757767283851f242b2cdfbfe6f4a16d73795ad150844`. + +All 750 packaged runtime files match the clean recorded Git source byte for byte, with no missing, +extra or changed runtime files. The wheel uses its actual VCS development version. The native probe +was built with the product Cargo lock and Rust 1.95.0, without `ci-fixtures`. Its working tree contained +the added bundled profile; no runtime implementation or harness assertion was substituted. + +On 2026-11-10, macOS 26.5.1 ARM64 and Python 3.13.15 passed all four modes of the unchanged +`desktop/tests/real_server.py`: anonymous loopback, static Bearer, HTTPS with explicit CA/base path, +and enforced Provider access. The ordinary product ConnectionManager selected the bundled profile. +Checks cover discovery and connection identity, exact Scope selection, statistics, Memory save/search/ +exact revision reads, committed writes with lost responses without replay, independent Server survival, +Principal changes, same-identity revocation, scoped authorization and 51 same-title Scopes. +Statistics usage is controlled fixture input, not an external model-provider execution claim. + +The exact wheel, source verification, native build log, probe identity and real-Server report are retained +under ignored `desktop/.artifacts/issue-2544-merged/`. Historical profiles retain their original identities, +operation sets and evidence. The complete contract gate passes 67 tests; the focused stop-reason Work/HTTP +suite passes 23 tests. Desktop generation, TypeScript checking and native bundled-operation coverage pass. +This record qualifies local SQLite protocol behavior, not installed WebView behavior, native credential +persistence, other operating systems, external databases, production deployment or release acceptance. +Stop-reason recording and readback use the Work/HTTP tests; Desktop has no outcome UI flow. + +Reproduce using the recorded wheel and the client containing this bundled profile: + +```sh +pnpm --dir desktop generate:check +cargo build --locked --manifest-path desktop/src-tauri/Cargo.toml --example server_probe +uv run --no-sync python desktop/tests/real_server.py \ + --product-qualification sqlite-task-stop-reason-4cb70619-v1 \ + --wheel desktop/.artifacts/issue-2544-merged/server-wheel/powercontext-1.5.2.dev5+g4cb706191-py3-none-any.whl +cargo test --locked --manifest-path desktop/src-tauri/Cargo.toml \ + --test session bundled_product_qualification_covers_every_desktop_operation +make contract-test +``` diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index c0b77a7664..87eb6baa42 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1268,5 +1268,48 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-bcc0d93a-v151-protocol-qualification" + }, + { + "id": "sqlite-task-stop-reason-0b434770-v1", + "serverCommit": "0b43477001e3453a79b310b40fc3e3e7e648c2a6", + "contractSha256": "34cc6572321296c6d67d2a8ca1dffd93d8ebb187a54af8f6dcdb5cd489a0926c", + "artifactSha256": "f572a91a6796d645c6545eaaa8278a2c4b1598b83fa8392df754e187277ab490", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#task-stop-reason-contract-protocol-qualification" + }, + { + "id": "sqlite-task-stop-reason-4cb70619-v1", + "serverCommit": "4cb7061913f5484c3b848551c1d570e59bab846f", + "contractSha256": "e1ff2e3ad1d6a09a9288c4c66e111a54c4979026e29806ff70543988b8e29220", + "artifactSha256": "e4c0d3f7549fe28abfd09669c3dc53ded66d79a4711b1e89da93611717b64a76", + "operations": [ + "get_access_principal", + "get_artifact_revision", + "get_capabilities", + "get_connection_identity", + "get_default_scope", + "get_liveness", + "get_readiness", + "get_scope", + "get_server_info", + "get_stats", + "list_scopes", + "remember_memory", + "search_memory" + ], + "evidence": "desktop/VALIDATION.md#task-stop-reason-merged-contract-protocol-qualification" } ] diff --git a/desktop/src-tauri/src/transport/operations.json b/desktop/src-tauri/src/transport/operations.json index 915c139259..690afa0e09 100644 --- a/desktop/src-tauri/src/transport/operations.json +++ b/desktop/src-tauri/src/transport/operations.json @@ -1,5 +1,5 @@ { - "contractSha256": "93b733bda25ab4db0e883f63a2571334c7c1dfb3af68a18b330384fd344c2d4c", + "contractSha256": "e1ff2e3ad1d6a09a9288c4c66e111a54c4979026e29806ff70543988b8e29220", "operations": { "get_liveness": { "method": "GET", diff --git a/desktop/ui/src/generated/api.d.ts b/desktop/ui/src/generated/api.d.ts index 888efc0493..3b00cb3ac3 100644 --- a/desktop/ui/src/generated/api.d.ts +++ b/desktop/ui/src/generated/api.d.ts @@ -3937,6 +3937,17 @@ export interface components { basis: components["schemas"]["WorkClaimBasis"]; evidence: components["schemas"]["HandoffCitation"][]; }; + /** @enum {string} */ + TaskStopReasonKind: "safety" | "authorization" | "capability" | "missing_evidence" | "scope"; + /** @description A caller-recorded judgement about why continuing would have been wrong. It grants no permission, approval, or retry budget and is not success or failure evidence. */ + TaskStopReason: { + kind: components["schemas"]["TaskStopReasonKind"]; + /** @description The circumstance under which continuing would have been wrong; must be trimmed. */ + condition: string; + basis: components["schemas"]["WorkClaimBasis"]; + /** @description Use [] with declared. verified requires exact previously returned same-scope citations. */ + evidence: components["schemas"]["HandoffCitation"][]; + }; TaskOutcome: { /** @enum {string} */ schema: "powercontext.task-outcome.v1"; @@ -3946,6 +3957,8 @@ export interface components { status: components["schemas"]["TaskOutcomeStatus"]; summary: string; handoff_receipt_ref?: components["schemas"]["SourceReference"]; + /** @description Optional deliberate-stop reason, accepted only with blocked or cancelled status. */ + stop_reason?: components["schemas"]["TaskStopReason"]; observations: components["schemas"]["WorkClaim"][]; checks: components["schemas"]["TaskCheck"][]; produced_artifacts: components["schemas"]["ArtifactReference"][]; diff --git a/desktop/ui/src/generated/operations.ts b/desktop/ui/src/generated/operations.ts index dc02c35b11..74138e76fd 100644 --- a/desktop/ui/src/generated/operations.ts +++ b/desktop/ui/src/generated/operations.ts @@ -15,7 +15,7 @@ */ // Generated from openapi/powercontext.yaml. Do not edit. -export const contractSha256 = "93b733bda25ab4db0e883f63a2571334c7c1dfb3af68a18b330384fd344c2d4c"; +export const contractSha256 = "e1ff2e3ad1d6a09a9288c4c66e111a54c4979026e29806ff70543988b8e29220"; export const operations = { "get_liveness": { "method": "GET", diff --git a/docs/en/docs/develop/interfaces.md b/docs/en/docs/develop/interfaces.md index fc3ea13a78..6ad163f744 100644 --- a/docs/en/docs/develop/interfaces.md +++ b/docs/en/docs/develop/interfaces.md @@ -65,6 +65,19 @@ unlinked Outcome in the same scope does not cover it. The operation stores a `ta Experience incubation can inspect, but does not generate or approve an Experience by itself. Integrations call it only at a real completion or interruption boundary, not solely because a prompt, Stop event, or Session ended. +For `blocked` or `cancelled`, an optional `stop_reason` records why continuing would have been wrong. Its `kind` is +`safety`, `authorization`, `capability`, `missing_evidence`, or `scope`; `condition` is nonblank, trimmed text. +Like claims, its `basis` is `declared` with empty `evidence`, or `verified` with exact same-scope citations +(at most 31). Other outcome statuses reject a reason. Omitting it preserves the existing stored representation +and content digest, including for older `blocked` outcomes; historical records gain no inferred reason. +Read the structured reason from the outcome Source's `content` through `get_source`. The continuity projection +counts it as an outcome with its original status and does not expose the reason or classify it as success or +failure. The reason itself is excluded from recurrence failure evidence and `avoided` derivation; existing +observation and check rules still apply. It records a judgement without establishing that stopping was correct, +granting permission, approval, or a retry budget, or ensuring that another agent will honour it. +OpenClaw's `powercontext_task_outcome` and Pi's `pc_task_outcome` expose the same optional field and forward it +to the Server, which owns status and evidence validation. + Claims and checks are either `declared` with no evidence or `verified` with exact same-scope citations. A readable citation proves identity and availability, not freshness. Current instructions, live workspace state, capabilities, and authorization still take precedence over all Work and Handoff records. diff --git a/docs/zh/docs/develop/interfaces.md b/docs/zh/docs/develop/interfaces.md index f299c65a2a..ded179ce5a 100644 --- a/docs/zh/docs/develop/interfaces.md +++ b/docs/zh/docs/develop/interfaces.md @@ -60,6 +60,17 @@ create_work_contract Outcome 不会覆盖它。该 operation 保存现有 Experience 孵化可读取的 `task-outcome` Source,但不会自行生成或批准 Experience。Integration 只应在真实完成或中断边界调用它,不能仅因 Prompt、Stop 或 Session 结束而调用。 +`blocked` 或 `cancelled` 可以用可选的 `stop_reason` 记录继续执行会有问题的原因。`kind` 只能是 `safety`、 +`authorization`、`capability`、`missing_evidence` 或 `scope`;`condition` 必须是非空且首尾无空白的文字。 +与 Claim 一样,`basis` 为 `declared` 时 `evidence` 必须为空,为 `verified` 时必须有同 scope 的精确 citation, +最多 31 条。其他 outcome 状态不接受原因。省略此字段会保留现有存储表示和内容摘要哈希,也适用于旧的 `blocked` +outcome;历史记录不会被推断或补写原因。通过 `get_source` 读取 outcome Source 的 `content` 即可取得结构化原因。 +Continuity 投影按原状态将其计为一条 outcome,不展示原因,也不将其分类为成功或失败。原因本身不进入 recurrence +失败证据或 `avoided` 推导;已有 observation 和 check 规则继续适用。它只记录判断,不能证明停止是正确的, +不能授予权限、批准或重试预算,也不保证后续 Agent 会遵循该原因。 +OpenClaw 的 `powercontext_task_outcome` 和 Pi 的 `pc_task_outcome` 均暴露同一可选字段并透传至 Server, +状态和证据规则由 Server 统一校验。 + Claim 和 check 要么是没有 evidence 的 `declared`,要么是拥有同 scope 精确 citation 的 `verified`。Citation 可读只证明 身份和可用性,不证明事实仍然新鲜。当前指令、实时 workspace、能力和授权始终优先于 Work 与 Handoff 记录。 diff --git a/e2e/bub/README.md b/e2e/bub/README.md index 0ca322ddb1..1466f745bc 100644 --- a/e2e/bub/README.md +++ b/e2e/bub/README.md @@ -573,7 +573,11 @@ installs Bub with the local PowerContext plugin when enabled, then `bub install` environment. Both steps pin Bub to the harness version so installing ACP cannot upgrade the host. The ACP step also names the pre-release ACP SDK that `bub-acp-server` pins, because uv resolves a pre-release only when a direct requirement asks for it. Harbor starts the server with `bub acp` in that environment and runs its native ACP client. The -Terminal-Bench task keeps its original image, setup, verifier, and isolation boundary. The harness ignores dataset CPU +client runner uses a separate virtual environment constrained to `agent-client-protocol==0.10.0`: Harbor 0.16 depends +on `text_block` and `set_session_model` APIs. This client constraint does not replace the server's SDK pin. +The harness checks the runner's startup and a deterministic ACP exchange locally; full Bub workload acceptance +still requires the container harness and its configured model provider. +The Terminal-Bench task keeps its original image, setup, verifier, and isolation boundary. The harness ignores dataset CPU and memory limits because it evaluates Memory behavior rather than benchmark resource compliance. This also keeps the fixed harness usable in nested container runtimes that cannot create additional cgroups. diff --git a/e2e/bub/pyproject.toml b/e2e/bub/pyproject.toml index 7a428d101f..7b03b71019 100644 --- a/e2e/bub/pyproject.toml +++ b/e2e/bub/pyproject.toml @@ -32,7 +32,7 @@ dependencies = [ powercontext-e2e = "powercontext_e2e.__main__:main" [dependency-groups] -dev = ["pytest>=9,<10"] +dev = ["agent-client-protocol==0.10.0", "pytest>=9,<10"] [build-system] requires = ["hatchling"] diff --git a/e2e/bub/tests/test_harbor_agent.py b/e2e/bub/tests/test_harbor_agent.py index 6c47b0e45b..8bbd5753a9 100644 --- a/e2e/bub/tests/test_harbor_agent.py +++ b/e2e/bub/tests/test_harbor_agent.py @@ -13,6 +13,7 @@ # limitations under the License. import importlib +import json import os import shlex import shutil @@ -21,9 +22,12 @@ from importlib.metadata import version from pathlib import Path +from harbor.agents.installed import acp as harbor_acp + from powercontext_e2e.harbor_agent import ( ACP_SDK_REQUIREMENT, BUB_ACP_SERVER_VERSION, + HARBOR_ACP_SDK_REQUIREMENT, REMOTE_BIN_DIR, REMOTE_SOURCE_OVERRIDE, _install_acp_server_command, @@ -72,6 +76,70 @@ def test_acp_server_install_names_the_pre_release_sdk_and_keeps_the_harness_bub( } +def test_harbor_acp_runner_completes_a_prompt_with_the_pinned_client_sdk(tmp_path: Path) -> None: + assert f"agent-client-protocol=={version('agent-client-protocol')}" == HARBOR_ACP_SDK_REQUIREMENT + # Copy as Harbor does in the task container, away from its sibling acp.py module. + runner = tmp_path / "acp_runner.py" + shutil.copy2(Path(harbor_acp.__file__).with_name("acp_runner.py"), runner) + server = tmp_path / "agent.py" + server.write_text( + """import json +import sys +from pathlib import Path + +for line in sys.stdin: + request = json.loads(line) + if "id" not in request: + continue + method = request["method"] + if method == "initialize": + result = {"protocolVersion": request["params"]["protocolVersion"], "agentCapabilities": {}, "authMethods": []} + elif method == "session/new": + result = {"sessionId": "fixture-session"} + elif method == "session/prompt": + Path(__file__).with_name("prompt.json").write_text(json.dumps(request["params"])) + result = {"stopReason": "end_turn"} + else: + raise RuntimeError(method) + print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}), flush=True) +""", + encoding="utf-8", + ) + launcher = tmp_path / "launch.sh" + launcher.write_text(f"#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(server))}\n", encoding="utf-8") + launcher.chmod(0o755) + logs = tmp_path / "logs" + env = {key: value for key, value in os.environ.items() if not key.startswith("HARBOR_ACP_")} + env["HARBOR_ACP_AUTH_POLICY"] = "disabled" + + result = subprocess.run( # noqa: S603 - actual Harbor runner against a local deterministic ACP fixture + [ + sys.executable, + str(runner), + "--instruction", + "Report fixture readiness", + "--logs-dir", + str(logs), + "--launcher", + str(launcher), + ], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + timeout=30, + check=False, + ) + + assert result.returncode == 0, result.stderr + summary = json.loads((logs / "acp-summary.json").read_text()) + assert "error" not in summary + assert summary["session"]["sessionId"] == "fixture-session" + assert summary["prompt_response"]["stopReason"] == "end_turn" + prompt = json.loads((tmp_path / "prompt.json").read_text()) + assert prompt["prompt"] == [{"type": "text", "text": "Report fixture readiness"}] + + def test_codex_plugin_accepts_the_server_url_the_harness_writes(monkeypatch, tmp_path: Path) -> None: # The plugin validates its .mcp.json strictly, so load the rewritten copy with the plugin's own settings. for name in ("settings.py", "powercontext_client_config.py", ".mcp.json"): diff --git a/e2e/bub/uv.lock b/e2e/bub/uv.lock index 1369a84900..52b44d0bd5 100644 --- a/e2e/bub/uv.lock +++ b/e2e/bub/uv.lock @@ -10,6 +10,18 @@ resolution-markers = [ "python_full_version < '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] +[[package]] +name = "agent-client-protocol" +version = "0.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/21/5c/d60196c536c8f66bb6a238c8a6d0d6fa84a2e3436008c139cb4a79003a25/agent_client_protocol-0.10.0.tar.gz", hash = "sha256:f8a6041e27423131e42e4d0cdd850d5b094b1092f79cc29501ab2bd57b92ee88", size = 81502, upload-time = "2026-05-07T19:11:56.784Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/cc/139895c0c5cd2acefc365085da0735d93df0cf8427ff4ee351961090e1af/agent_client_protocol-0.10.0-py3-none-any.whl", hash = "sha256:97a1a69c5d094e2625b09c4dbc2d5cf19637c4943630ceed52ab0578ecd5e14c", size = 65400, upload-time = "2026-05-07T19:11:55.614Z" }, +] + [[package]] name = "aiohappyeyeballs" version = "2.7.1" @@ -1886,6 +1898,7 @@ dependencies = [ [package.dev-dependencies] dev = [ + { name = "agent-client-protocol" }, { name = "pytest" }, ] @@ -1902,7 +1915,10 @@ requires-dist = [ ] [package.metadata.requires-dev] -dev = [{ name = "pytest", specifier = ">=9,<10" }] +dev = [ + { name = "agent-client-protocol", specifier = "==0.10.0" }, + { name = "pytest", specifier = ">=9,<10" }, +] [[package]] name = "prompt-toolkit" diff --git a/integrations/dsh/plugins/powercontext/tests/runtime/setup.test.mjs b/integrations/dsh/plugins/powercontext/tests/runtime/setup.test.mjs index 36df39ea1b..6b45d2fb1b 100644 --- a/integrations/dsh/plugins/powercontext/tests/runtime/setup.test.mjs +++ b/integrations/dsh/plugins/powercontext/tests/runtime/setup.test.mjs @@ -104,6 +104,7 @@ test('setup validates native include trees observed by a real DSH startup', { ti const result = JSON.parse(await fixture.cli(['setup', 'dsh', '--source', source, '--server-url', runtime.baseUrl, '--json'])) assert.equal(result.hosts.dsh.setup, 'complete') + assert.equal(result.hosts.dsh.checks.plugin_memory_protocol.status, 'ok') assert.equal(JSON.parse(readFileSync(fixture.clients, 'utf8')).hosts.dsh.server_url, runtime.baseUrl) assert.equal(JSON.parse(readFileSync(credentials, 'utf8')).authorization, 'Bearer new-token') for (const [index, path] of includePaths.entries()) assert.deepEqual(readFileSync(path), includeBefore[index]) diff --git a/integrations/openclaw/plugins/memory-powercontext/src/work.test.ts b/integrations/openclaw/plugins/memory-powercontext/src/work.test.ts index ccdd7fbee3..b049df5f7c 100644 --- a/integrations/openclaw/plugins/memory-powercontext/src/work.test.ts +++ b/integrations/openclaw/plugins/memory-powercontext/src/work.test.ts @@ -154,6 +154,57 @@ describe("PowerContext work tools", () => { }); }); + it.each([ + ["safety", "blocked", "declared"], + ["authorization", "blocked", "verified"], + ["capability", "cancelled", "verified"], + ["missing_evidence", "blocked", "verified"], + ["scope", "cancelled", "declared"], + ])("exposes and forwards a %s stop reason unchanged", async (kind, status, basis) => { + const { deps, requests } = fixture(); + const tool = createTaskOutcomeTool(context, deps)!; + const reason = { + kind, + condition: "继续执行需要先确认前提条件。", + basis, + evidence: basis === "declared" ? [] : [ + { kind: "source", source_ref: { name: "content", source_id: "evidence-1" } }, + { kind: "artifact", artifact_ref: { family: "handoff", artifact_id: "h-1", revision: 2 } }, + ], + }; + const outcome = { + schema: "powercontext.task-outcome.v1", + trust: "untrusted_observation", + objective: "Attempt an action.", + status, + summary: "The caller deliberately stopped.", + observations: [{ text: "The caller reported stopping.", basis: "declared", evidence: [] }], + checks: [], + produced_artifacts: [], + remaining_work: [], + }; + const params = { source_id: "outcome-1", outcome: { ...outcome, stop_reason: reason } }; + + expect(tool.parameters.properties.outcome.properties.stop_reason).toBeDefined(); + expect(Value.Check(tool.parameters, params)).toBe(true); + expect(Value.Check(tool.parameters, { outcome })).toBe(true); + expect(Value.Check(tool.parameters, { outcome: { ...outcome, stop_reason: null } })).toBe(true); + for (const invalid of [ + { ...reason, kind: "refused" }, + { ...reason, condition: " " }, + { ...reason, evidence: Array(32).fill({ kind: "source", source_ref: { name: "content", source_id: "evidence-1" } }) }, + ]) { + expect(Value.Check(tool.parameters, { outcome: { ...outcome, stop_reason: invalid } })).toBe(false); + } + + await tool.execute("call-stop", params); + + expect(requests.find(({ path }) => path === "/v1/work/outcomes/record")).toEqual({ + path: "/v1/work/outcomes/record", + body: { scope_id: "scope-1", ...params }, + }); + }); + it("treats nullable handoff inputs as omitted optional fields", async () => { const { deps, requests } = fixture(); const revision = { family: "handoff", artifact_id: "h-1", revision: 1 }; diff --git a/integrations/openclaw/plugins/memory-powercontext/src/work.ts b/integrations/openclaw/plugins/memory-powercontext/src/work.ts index a124d76236..50818088d3 100644 --- a/integrations/openclaw/plugins/memory-powercontext/src/work.ts +++ b/integrations/openclaw/plugins/memory-powercontext/src/work.ts @@ -99,6 +99,18 @@ const taskCheck = Type.Object({ basis: Type.Union([Type.Literal("declared"), Type.Literal("verified")]), evidence: Type.Array(handoffCitation, { maxItems: 32 }), }, { additionalProperties: false }); +const taskStopReason = Type.Object({ + kind: Type.Union([ + Type.Literal("safety"), + Type.Literal("authorization"), + Type.Literal("capability"), + Type.Literal("missing_evidence"), + Type.Literal("scope"), + ]), + condition: Type.String({ minLength: 1, maxLength: 8192, pattern: ".*\\S.*", description: "The circumstance under which continuing would have been wrong; must be trimmed." }), + basis: Type.Union([Type.Literal("declared"), Type.Literal("verified")]), + evidence: Type.Array(handoffCitation, { maxItems: 31, description: "Use [] with declared. verified requires exact previously returned same-scope citations." }), +}, { additionalProperties: false }); const taskOutcome = Type.Object({ schema: Type.Literal("powercontext.task-outcome.v1"), trust: Type.Literal("untrusted_observation"), @@ -113,6 +125,7 @@ const taskOutcome = Type.Object({ ]), summary: workText, handoff_receipt_ref: Type.Optional(Type.Union([sourceReference, Type.Null()])), + stop_reason: Type.Optional(Type.Union([taskStopReason, Type.Null()], { description: "Optional deliberate-stop reason, accepted only with blocked or cancelled status. Records a judgement without granting permission, approval, or retry budget." })), observations: Type.Array(workClaim, { minItems: 1, maxItems: 64 }), checks: Type.Array(taskCheck, { maxItems: 64 }), produced_artifacts: Type.Array(artifactReference, { maxItems: 32 }), @@ -448,7 +461,7 @@ export function createTaskOutcomeTool(ctx: OpenClawPluginToolContext, deps: Tool name: POWERCONTEXT_TASK_OUTCOME_TOOL, label: "Record Task Outcome", description: - "Record the exact outcome, checks, produced artifacts, and remaining work at a completion or interruption boundary. Provide schema powercontext.task-outcome.v1, trust untrusted_observation, objective, status, summary, at least one observation, and all result arrays.", + "Record the exact outcome, checks, produced artifacts, and remaining work at a completion or interruption boundary. Provide schema powercontext.task-outcome.v1, trust untrusted_observation, objective, status, summary, at least one observation, and all result arrays. For blocked or cancelled, optionally record stop_reason with kind, condition, basis, and evidence; declared requires [], verified requires exact same-scope citations. A reason grants no authority.", parameters: Type.Object({ outcome: taskOutcome, source_id: Type.Optional(Type.String({ minLength: 1, maxLength: 256 })), diff --git a/integrations/pi/plugins/powercontext/src/tools.ts b/integrations/pi/plugins/powercontext/src/tools.ts index 500a251838..16ec300e2a 100644 --- a/integrations/pi/plugins/powercontext/src/tools.ts +++ b/integrations/pi/plugins/powercontext/src/tools.ts @@ -190,6 +190,19 @@ const TASK_CHECK = Type.Object({ basis: Type.Union([Type.Literal('declared'), Type.Literal('verified')]), evidence: Type.Array(HANDOFF_CITATION, { maxItems: 32 }), }) +const TASK_STOP_REASON = Type.Object({ + kind: Type.Union([ + Type.Literal('safety'), Type.Literal('authorization'), Type.Literal('capability'), + Type.Literal('missing_evidence'), Type.Literal('scope'), + ]), + condition: Type.String({ minLength: 1, maxLength: 8192, pattern: '.*\\S.*', + description: 'The circumstance under which continuing would have been wrong; must be trimmed.', + }), + basis: Type.Union([Type.Literal('declared'), Type.Literal('verified')]), + evidence: Type.Array(HANDOFF_CITATION, { maxItems: 31, + description: 'Use [] with declared. verified requires exact previously returned same-scope citations.', + }), +}, { additionalProperties: false }) const TASK_OUTCOME = Type.Object({ schema: Type.Literal('powercontext.task-outcome.v1'), trust: Type.Literal('untrusted_observation'), @@ -200,6 +213,9 @@ const TASK_OUTCOME = Type.Object({ ]), summary: NON_EMPTY_STRING, handoff_receipt_ref: Type.Optional(Type.Union([SOURCE_REFERENCE, Type.Null()])), + stop_reason: Type.Optional(Type.Union([TASK_STOP_REASON, Type.Null()], { + description: 'Optional deliberate-stop reason, accepted only with blocked or cancelled status. Records a judgement without granting permission, approval, or retry budget.', + })), observations: Type.Array(WORK_CLAIM, { minItems: 1, maxItems: 64 }), checks: Type.Array(TASK_CHECK, { maxItems: 64 }), produced_artifacts: Type.Array(ARTIFACT_REFERENCE, { maxItems: 32 }), @@ -643,7 +659,7 @@ export function registerTools(pi: ExtensionAPI, runtime: PluginRuntime): void { registerOperationTool(pi, runtime, { name: 'pc_task_outcome', label: 'PowerContext Task Outcome', - description: 'Record a structured outcome at an actual completion or interruption boundary.', + description: 'Record a structured outcome at an actual completion or interruption boundary. For blocked or cancelled, optionally record stop_reason with kind, condition, basis, and evidence; declared requires [], verified requires exact same-scope citations. A reason grants no authority.', parameters: Type.Object({ source_id: ID_STRING, outcome: TASK_OUTCOME, diff --git a/integrations/pi/plugins/powercontext/tests/tools.spec.ts b/integrations/pi/plugins/powercontext/tests/tools.spec.ts index 2f7594b507..056d52ef67 100644 --- a/integrations/pi/plugins/powercontext/tests/tools.spec.ts +++ b/integrations/pi/plugins/powercontext/tests/tools.spec.ts @@ -661,6 +661,58 @@ describe('Pi native tool surface', () => { ]) }) + it.each([ + ['safety', 'blocked', 'declared'], + ['authorization', 'blocked', 'verified'], + ['capability', 'cancelled', 'verified'], + ['missing_evidence', 'blocked', 'verified'], + ['scope', 'cancelled', 'declared'], + ])('exposes and forwards a %s stop reason through Pi argument validation', async (kind, status, basis) => { + const registered: Array> = [] + const fetch = vi.fn(async (_url: string, _init?: RequestInit) => new Response(JSON.stringify({ ok: true }))) + registerTools({ registerTool: (tool: Record) => registered.push(tool) } as never, createRuntime(fetch)) + const tool = registeredTool>(registered, 'pc_task_outcome') + const schema = JSON.parse(JSON.stringify(tool.parameters)) + expect(schema.properties.outcome.properties.stop_reason).toBeDefined() + const reason = { + kind, condition: '继续执行需要先确认前提条件。', basis, + evidence: basis === 'declared' ? [] : [ + { kind: 'source', source_ref: { name: 'content', source_id: 'evidence-1' } }, + { kind: 'artifact', artifact_ref: { family: 'handoff', artifact_id: 'h-1', revision: 2 } }, + ], + } + const outcome = { + schema: 'powercontext.task-outcome.v1', trust: 'untrusted_observation', objective: 'Attempt an action.', + status, summary: 'The caller deliberately stopped.', + observations: [{ text: 'The caller reported stopping.', basis: 'declared', evidence: [] }], + checks: [], produced_artifacts: [], remaining_work: [], + } + const params = { source_id: 'outcome-1', outcome: { ...outcome, stop_reason: reason } } + expect(Value.Check(schema, params)).toBe(true) + expect(Value.Check(schema, { source_id: 'outcome-1', outcome })).toBe(true) + expect(Value.Check(schema, { source_id: 'outcome-1', outcome: { ...outcome, stop_reason: null } })).toBe(true) + for (const invalid of [ + { ...reason, kind: 'refused' }, + { ...reason, condition: ' ' }, + { ...reason, evidence: Array(32).fill({ kind: 'source', source_ref: { name: 'content', source_id: 'evidence-1' } }) }, + ]) { + expect(Value.Check(schema, { source_id: 'outcome-1', outcome: { ...outcome, stop_reason: invalid } })).toBe(false) + } + const validated = validatePiArguments(tool as unknown as Tool, { + type: 'toolCall', id: 'call-stop', name: 'pc_task_outcome', arguments: params, + }) + expect(validated).toEqual(params) + const context = { cwd: '/workspace/repo', hasUI: true, ui: { confirm: vi.fn(async () => true) } } + + const result = await tool.execute('call-stop', validated, new AbortController().signal, () => undefined, context) + + expect(result.details.ok).toBe(true) + expect(context.ui.confirm).toHaveBeenCalled() + expect(fetch.mock.calls.map(([url, init]) => [url, JSON.parse(String(init?.body))])).toEqual([ + ['http://127.0.0.1:8000/v1/work/outcomes/record', { ...params, scope_id: 'project:demo' }], + ]) + }) + it('accepts and forwards advisory rollover reasons for Handoff preparation', async () => { const registered: Array> = [] const fetch = vi.fn(async (_url: string, _init?: RequestInit) => new Response(JSON.stringify({ ok: true }))) diff --git a/openapi/powercontext.yaml b/openapi/powercontext.yaml index 6729737386..f452fd87c8 100644 --- a/openapi/powercontext.yaml +++ b/openapi/powercontext.yaml @@ -9081,6 +9081,33 @@ components: maxItems: 32 items: $ref: "#/components/schemas/HandoffCitation" + TaskStopReasonKind: + type: string + enum: [safety, authorization, capability, missing_evidence, scope] + TaskStopReason: + description: >- + A caller-recorded judgement about why continuing would have been wrong. + It grants no permission, approval, or retry budget and is not success or failure evidence. + type: object + additionalProperties: false + required: [kind, condition, basis, evidence] + properties: + kind: + $ref: "#/components/schemas/TaskStopReasonKind" + condition: + type: string + minLength: 1 + maxLength: 8192 + pattern: '.*\S.*' + description: The circumstance under which continuing would have been wrong; must be trimmed. + basis: + $ref: "#/components/schemas/WorkClaimBasis" + evidence: + type: array + maxItems: 31 + description: Use [] with declared. verified requires exact previously returned same-scope citations. + items: + $ref: "#/components/schemas/HandoffCitation" TaskOutcome: type: object additionalProperties: false @@ -9107,6 +9134,10 @@ components: handoff_receipt_ref: $ref: "#/components/schemas/SourceReference" nullable: true + stop_reason: + $ref: "#/components/schemas/TaskStopReason" + nullable: true + description: Optional deliberate-stop reason, accepted only with blocked or cancelled status. observations: type: array minItems: 1 diff --git a/src/powercontext/builtin/runtime/application.py b/src/powercontext/builtin/runtime/application.py index c952627f3b..29c4f32b8c 100644 --- a/src/powercontext/builtin/runtime/application.py +++ b/src/powercontext/builtin/runtime/application.py @@ -4936,6 +4936,8 @@ def _contract_evidence(contract: WorkContract) -> tuple[HandoffCitation, ...]: def _outcome_evidence(outcome: TaskOutcome) -> tuple[HandoffCitation, ...]: citations = [*_claims_evidence(outcome.observations)] + if outcome.stop_reason is not None: + citations.extend(outcome.stop_reason.evidence) citations.extend(citation for check in outcome.checks for citation in check.evidence) citations.extend(HandoffArtifactCitation(artifact_ref=reference) for reference in outcome.produced_artifacts) return _unique_citations(citations) diff --git a/src/powercontext/builtin/work/__init__.py b/src/powercontext/builtin/work/__init__.py index 7dc1722d87..f7240a2c22 100644 --- a/src/powercontext/builtin/work/__init__.py +++ b/src/powercontext/builtin/work/__init__.py @@ -31,6 +31,7 @@ RecordTaskOutcome, TaskCheck, TaskOutcome, + TaskStopReason, WorkClaim, WorkContinuity, WorkContinuityCoverage, @@ -59,6 +60,7 @@ "RecordTaskOutcome", "TaskCheck", "TaskOutcome", + "TaskStopReason", "WorkClaim", "WorkContinuity", "WorkContinuityCoverage", diff --git a/src/powercontext/builtin/work/models.py b/src/powercontext/builtin/work/models.py index fbb7222390..45b28b7ebd 100644 --- a/src/powercontext/builtin/work/models.py +++ b/src/powercontext/builtin/work/models.py @@ -19,7 +19,7 @@ from hashlib import sha256 from typing import Annotated, Literal, TypeAlias -from pydantic import BaseModel, ConfigDict, Field, StrictInt, field_validator, model_validator +from pydantic import BaseModel, ConfigDict, Field, StrictInt, field_validator, model_serializer, model_validator from powercontext.artifacts import ArtifactRef from powercontext.builtin.artifacts.experience import TASK_OUTCOME_SOURCE_KIND @@ -162,6 +162,28 @@ def require_evidence_for_verified_checks(self) -> TaskCheck: return self +class TaskStopReason(_WorkValue): + """A recorded judgement about continuing an attempt; it grants no authority.""" + + kind: Literal["safety", "authorization", "capability", "missing_evidence", "scope"] + condition: Annotated[str, Field(max_length=MAX_WORK_TEXT_LENGTH)] + basis: WorkClaimBasis = "declared" + evidence: Annotated[tuple[HandoffCitation, ...], Field(max_length=MAX_WORK_CLAIM_EVIDENCE)] = () + + @field_validator("condition") + @classmethod + def require_condition(cls, value: str) -> str: + return _require_text("stop condition", value) + + @model_validator(mode="after") + def require_evidence_for_verified_reasons(self) -> TaskStopReason: + if self.basis == "verified" and not self.evidence: + raise ValueError("verified Task stop reasons require exact evidence") # noqa: TRY003 + if self.basis == "declared" and self.evidence: + raise ValueError("declared Task stop reasons cannot present evidence as verified") # noqa: TRY003 + return self + + class TaskOutcome(_WorkValue): """What one completed or interrupted work attempt actually produced.""" @@ -178,6 +200,7 @@ class TaskOutcome(_WorkValue): checks: Annotated[tuple[TaskCheck, ...], Field(max_length=MAX_WORK_ITEMS)] = () produced_artifacts: Annotated[tuple[ArtifactRef, ...], Field(max_length=MAX_WORK_EVIDENCE)] = () remaining_work: Annotated[tuple[str, ...], Field(max_length=MAX_WORK_ITEMS)] = () + stop_reason: TaskStopReason | None = None @field_validator("objective", "summary") @classmethod @@ -189,6 +212,22 @@ def require_text(cls, value: str, info) -> str: def require_remaining_work(cls, values: tuple[str, ...]) -> tuple[str, ...]: return _require_text_items("remaining_work", values) + @model_validator(mode="after") + def require_interrupted_status_for_stop_reason(self) -> TaskOutcome: + if self.stop_reason is not None and self.status not in ("blocked", "cancelled"): + raise ValueError( # noqa: TRY003 + f"Task stop_reason requires blocked or cancelled status; got {self.status}" + ) + return self + + @model_serializer(mode="wrap") + def serialize_stop_reason(self, handler): + result = handler(self) + # Preserve historical Source bytes and content digests when no reason was recorded. + if self.stop_reason is None: + result.pop("stop_reason", None) + return result + class CurrentWorkHandoff(_WorkValue): """Caller-inspected current state used to prepare a temporary Handoff.""" @@ -485,6 +524,7 @@ def _require_text_items(field: str, values: tuple[str, ...]) -> tuple[str, ...]: "RecordTaskOutcome", "TaskCheck", "TaskOutcome", + "TaskStopReason", "WorkClaim", "WorkContinuity", "WorkContinuityCoverage", diff --git a/src/powercontext/http/__init__.py b/src/powercontext/http/__init__.py index c504b6bb22..d3a2191077 100644 --- a/src/powercontext/http/__init__.py +++ b/src/powercontext/http/__init__.py @@ -483,6 +483,8 @@ TaskCheckStatus, TaskOutcome, TaskOutcomeStatus, + TaskStopReason, + TaskStopReasonKind, Timezone, TokenEstimatorProfile, TopicMemoryArtifact, @@ -980,6 +982,8 @@ "TaskCheckStatus", "TaskOutcome", "TaskOutcomeStatus", + "TaskStopReason", + "TaskStopReasonKind", "Timezone", "TokenEstimatorProfile", "TopicMemoryArtifact", diff --git a/src/powercontext/http/_generated/models.py b/src/powercontext/http/_generated/models.py index 8eafeaf718..3d4218f543 100644 --- a/src/powercontext/http/_generated/models.py +++ b/src/powercontext/http/_generated/models.py @@ -1154,6 +1154,14 @@ class TaskCheckStatus(StrEnum): UNKNOWN = "unknown" +class TaskStopReasonKind(StrEnum): + SAFETY = "safety" + AUTHORIZATION = "authorization" + CAPABILITY = "capability" + MISSING_EVIDENCE = "missing_evidence" + SCOPE = "scope" + + class Schema3(StrEnum): POWERCONTEXT_TASK_OUTCOME_V1 = "powercontext.task-outcome.v1" @@ -6175,6 +6183,30 @@ class TaskCheck(BaseModel): evidence: Annotated[list[HandoffCitation], Field(max_length=32)] +class TaskStopReason(BaseModel): + model_config = ConfigDict( + extra="forbid", + ) + kind: TaskStopReasonKind + condition: Annotated[ + StrictStr, + Field( + description="The circumstance under which continuing would have been wrong; must be trimmed.", + max_length=8192, + min_length=1, + pattern=".*\\S.*", + ), + ] + basis: WorkClaimBasis + evidence: Annotated[ + list[HandoffCitation], + Field( + description="Use [] with declared. verified requires exact previously returned same-scope citations.", + max_length=31, + ), + ] + + class TaskOutcome(BaseModel): model_config = ConfigDict( extra="forbid", @@ -6185,6 +6217,10 @@ class TaskOutcome(BaseModel): status: TaskOutcomeStatus summary: Annotated[StrictStr, Field(max_length=8192, min_length=1, pattern=".*\\S.*")] handoff_receipt_ref: SourceReference | None = None + stop_reason: Annotated[ + TaskStopReason | None, + Field(description="Optional deliberate-stop reason, accepted only with blocked or cancelled status."), + ] = None observations: Annotated[list[WorkClaim], Field(max_length=64, min_length=1)] checks: Annotated[list[TaskCheck], Field(max_length=64)] produced_artifacts: Annotated[list[ArtifactReference], Field(max_length=32)] diff --git a/src/powercontext/http/_generated/schema.py b/src/powercontext/http/_generated/schema.py index 933b17e3a1..6a18e344f2 100644 --- a/src/powercontext/http/_generated/schema.py +++ b/src/powercontext/http/_generated/schema.py @@ -9513,6 +9513,57 @@ "type": "object", "required": ["name", "status", "basis", "evidence"], }, + "TaskStopReasonKind": { + "type": "string", + "enum": ["safety", "authorization", "capability", "missing_evidence", "scope"], + }, + "TaskStopReason": { + "properties": { + "kind": {"$ref": "#/components/schemas/TaskStopReasonKind"}, + "condition": { + "type": "string", + "maxLength": 8192, + "minLength": 1, + "pattern": ".*\\S.*", + "description": "The " + "circumstance " + "under " + "which " + "continuing " + "would " + "have " + "been " + "wrong; " + "must " + "be " + "trimmed.", + }, + "basis": {"$ref": "#/components/schemas/WorkClaimBasis"}, + "evidence": { + "items": {"$ref": "#/components/schemas/HandoffCitation"}, + "type": "array", + "maxItems": 31, + "description": "Use [] " + "with " + "declared. " + "verified " + "requires " + "exact " + "previously " + "returned " + "same-scope " + "citations.", + }, + }, + "additionalProperties": False, + "type": "object", + "required": ["kind", "condition", "basis", "evidence"], + "description": "A caller-recorded judgement about " + "why continuing would have been " + "wrong. It grants no permission, " + "approval, or retry budget and is " + "not success or failure evidence.", + }, "TaskOutcome": { "properties": { "schema": {"type": "string", "enum": ["powercontext.task-outcome.v1"]}, @@ -9521,6 +9572,20 @@ "status": {"$ref": "#/components/schemas/TaskOutcomeStatus"}, "summary": {"type": "string", "maxLength": 8192, "minLength": 1, "pattern": ".*\\S.*"}, "handoff_receipt_ref": {"$ref": "#/components/schemas/SourceReference", "nullable": True}, + "stop_reason": { + "$ref": "#/components/schemas/TaskStopReason", + "description": "Optional " + "deliberate-stop " + "reason, " + "accepted " + "only " + "with " + "blocked " + "or " + "cancelled " + "status.", + "nullable": True, + }, "observations": { "items": {"$ref": "#/components/schemas/WorkClaim"}, "type": "array", diff --git a/src/powercontext/server/mapping.py b/src/powercontext/server/mapping.py index 4a3bbbf9f3..c531e6d7f3 100644 --- a/src/powercontext/server/mapping.py +++ b/src/powercontext/server/mapping.py @@ -173,6 +173,7 @@ from powercontext.builtin.work import RecordTaskOutcome as RuntimeRecordTaskOutcome from powercontext.builtin.work import TaskCheck as RuntimeTaskCheck from powercontext.builtin.work import TaskOutcome as RuntimeTaskOutcome +from powercontext.builtin.work import TaskStopReason as RuntimeTaskStopReason from powercontext.builtin.work import WorkClaim as RuntimeWorkClaim from powercontext.builtin.work import WorkContract as RuntimeWorkContract from powercontext.builtin.work import WorkSourceReceipt as RuntimeWorkSourceReceipt @@ -453,6 +454,18 @@ def record_task_outcome_request(value: RecordTaskOutcomeRequest) -> RuntimeRecor checks=tuple(_runtime_task_check(check) for check in value.outcome.checks), produced_artifacts=tuple(runtime_artifact_reference(ref) for ref in value.outcome.produced_artifacts), remaining_work=tuple(item.root for item in value.outcome.remaining_work), + stop_reason=( + None + if value.outcome.stop_reason is None + else RuntimeTaskStopReason( + kind=value.outcome.stop_reason.kind.value, + condition=value.outcome.stop_reason.condition, + basis=value.outcome.stop_reason.basis.value, + evidence=tuple( + runtime_handoff_citation(citation) for citation in value.outcome.stop_reason.evidence + ), + ) + ), ), ) except ValidationError as error: diff --git a/tests/builtin/runtime/test_task_stop_reason.py b/tests/builtin/runtime/test_task_stop_reason.py new file mode 100644 index 0000000000..05516861ab --- /dev/null +++ b/tests/builtin/runtime/test_task_stop_reason.py @@ -0,0 +1,163 @@ +# 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. + +from __future__ import annotations + +import asyncio +import json +from hashlib import sha256 +from pathlib import Path +from typing import get_args + +import pytest + +from powercontext.builtin.artifacts.handoff import HandoffEvidenceUnavailableError, HandoffSourceCitation +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.runtime import BuiltinConfig, CaptureSource, open_builtin_runtime +from powercontext.builtin.scope import ScopeDraft +from powercontext.builtin.work import RecordTaskOutcome, TaskOutcome, TaskStopReason, WorkClaim +from powercontext.builtin.work.models import TaskOutcomeStatus, WorkClaimBasis +from powercontext.sources import SourceRef + + +@pytest.mark.parametrize("status", ["blocked", "cancelled"]) +@pytest.mark.parametrize("basis", ["declared", "verified"]) +def test_stop_reason_survives_sqlite_reopen_and_continuity( + tmp_path: Path, status: TaskOutcomeStatus, basis: WorkClaimBasis +) -> None: + config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'work.db'}")) + + async def scenario() -> None: + async with open_builtin_runtime(config) as runtime: + assert runtime.scopes is not None + scope = await runtime.scopes.create( + ScopeDraft(summary="Work outcome test", title="Stop reason", idempotency_key="stop-reason") + ) + sources = runtime.sources.for_scope(scope.scope_id) + evidence = await sources.capture( + CaptureSource(metadata={}, source_id="evidence-1", content="Required condition is absent.") + ) + reason = TaskStopReason( + kind="safety" if status == "blocked" else "scope", + condition="继续执行超出已确认的安全范围。", + basis=basis, + evidence=() if basis == "declared" else (HandoffSourceCitation(source_ref=evidence.source_ref),), + ) + outcome = TaskOutcome( + objective="Attempt an action.", + status=status, + summary="The caller deliberately stopped.", + observations=(WorkClaim(text="The caller reported stopping."),), + stop_reason=reason, + ) + receipt = await runtime.work.for_scope(scope.scope_id).record_outcome( + RecordTaskOutcome(source_id="outcome-1", outcome=outcome) + ) + + async with open_builtin_runtime(config) as runtime: + stored = await runtime.records.for_scope(scope.scope_id).get_source("content", "outcome-1") + assert isinstance(stored.content, str) + assert TaskOutcome.model_validate_json(stored.content) == outcome + assert json.loads(stored.content)["stop_reason"] == reason.model_dump(mode="json") + continuity = await runtime.work.for_scope(scope.scope_id).continuity() + assert continuity.invalid_record_count == 0 + assert continuity.coverage.outcome_records == 1 + assert continuity.events[0].status == status + assert continuity.events[0].source_ref == receipt.source_ref + assert continuity.coverage.transfer_state == "not_applicable" + assert continuity.coverage.outcome_state == "not_expected" + + asyncio.run(scenario()) + + +def test_legacy_outcomes_preserve_source_bytes_and_digests_for_every_status() -> None: + async def scenario() -> None: + async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime: + assert runtime.scopes is not None + scope = await runtime.scopes.create( + ScopeDraft(summary="Work outcome test", title="Legacy outcomes", idempotency_key="legacy-outcomes") + ) + work = runtime.work.for_scope(scope.scope_id) + for status in get_args(TaskOutcomeStatus): + legacy = { + "schema": "powercontext.task-outcome.v1", + "trust": "untrusted_observation", + "objective": "Attempt an action.", + "status": status, + "summary": "The caller reported a result.", + "handoff_receipt_ref": None, + "observations": [{"text": "The caller reported a result.", "basis": "declared", "evidence": []}], + "checks": [], + "produced_artifacts": [], + "remaining_work": [], + } + compact = json.dumps(legacy, separators=(",", ":")) + outcome = TaskOutcome.model_validate_json(compact) + assert outcome.stop_reason is None + assert outcome.model_dump_json(by_alias=True, exclude_none=False) == compact + # Explicit null and nesting must also preserve the old representation. + assert ( + TaskOutcome.model_validate_json(json.dumps({**legacy, "stop_reason": None})).model_dump( + mode="json", by_alias=True + ) + == legacy + ) + request = RecordTaskOutcome(source_id=f"outcome-{status}", outcome=outcome) + assert request.model_dump(mode="json", by_alias=True)["outcome"] == legacy + receipt = await work.record_outcome(request) + assert receipt.content_digest == f"sha256:{sha256(compact.encode()).hexdigest()}" + stored = await runtime.records.for_scope(scope.scope_id).get_source("content", f"outcome-{status}") + assert stored.content == json.dumps(legacy, indent=2) + continuity = await work.continuity() + assert continuity.invalid_record_count == 0 + assert [event.status for event in continuity.events] == list(get_args(TaskOutcomeStatus)) + + asyncio.run(scenario()) + + +def test_stop_reason_rejects_unavailable_evidence_before_recording() -> None: + async def scenario() -> None: + async with open_builtin_runtime(BuiltinConfig(database=SQLiteConfig())) as runtime: + assert runtime.scopes is not None + other = await runtime.scopes.create( + ScopeDraft(summary="Work outcome test", title="Other scope", idempotency_key="other") + ) + await runtime.sources.for_scope(other.scope_id).capture( + CaptureSource(metadata={}, source_id="other-evidence", content="Other scope.") + ) + scope = await runtime.scopes.create( + ScopeDraft(summary="Work outcome test", title="Stop reason", idempotency_key="stop-reason") + ) + work = runtime.work.for_scope(scope.scope_id) + for source_id in ("missing", "other-evidence"): + outcome = TaskOutcome( + objective="Attempt an action.", + status="blocked", + summary="The caller stopped.", + observations=(WorkClaim(text="The caller reported stopping."),), + stop_reason=TaskStopReason( + kind="authorization", + condition="Authorization was not confirmed.", + basis="verified", + evidence=( + HandoffSourceCitation(source_ref=SourceRef(source_type="content", source_id=source_id)), + ), + ), + ) + with pytest.raises(HandoffEvidenceUnavailableError): + await work.record_outcome(RecordTaskOutcome(source_id="outcome-1", outcome=outcome)) + continuity = await work.continuity() + assert continuity.total_event_count == 0 + + asyncio.run(scenario()) diff --git a/tests/builtin/test_task_stop_reason.py b/tests/builtin/test_task_stop_reason.py new file mode 100644 index 0000000000..a7a9213a94 --- /dev/null +++ b/tests/builtin/test_task_stop_reason.py @@ -0,0 +1,91 @@ +# 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. + +"""Deliberate-stop provenance and status constraints.""" + +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +from powercontext.builtin.artifacts.experience.recurrence import failure_refs +from powercontext.builtin.artifacts.handoff import HandoffSourceCitation +from powercontext.builtin.work import TaskOutcome, TaskStopReason, WorkClaim +from powercontext.builtin.work.models import TaskOutcomeStatus +from powercontext.sources import SourceRef + +CITATION = HandoffSourceCitation(source_ref=SourceRef(source_type="content", source_id="evidence-1")) + + +@pytest.mark.parametrize("status", ["succeeded", "partial", "failed", "unknown"]) +def test_stop_reason_rejects_completed_or_indeterminate_status(status: TaskOutcomeStatus) -> None: + with pytest.raises(ValidationError, match=f"requires blocked or cancelled status; got {status}"): + TaskOutcome( + objective="Attempt an action.", + status=status, + summary="The attempt stopped.", + observations=(WorkClaim(text="The caller reported stopping."),), + stop_reason=TaskStopReason(kind="safety", condition="Completion could not be guaranteed."), + ) + + +def test_stop_reason_requires_evidence_exactly_when_verified() -> None: + with pytest.raises(ValidationError, match="verified Task stop reasons require exact evidence"): + TaskStopReason(kind="safety", condition="Completion could not be guaranteed.", basis="verified") + with pytest.raises(ValidationError, match="declared Task stop reasons cannot present evidence as verified"): + TaskStopReason(kind="safety", condition="Completion could not be guaranteed.", evidence=(CITATION,)) + + +@pytest.mark.parametrize("condition", ["", " ", "\n", " leading", "trailing ", "x" * 8193]) +def test_stop_reason_requires_bounded_trimmed_condition(condition: str) -> None: + with pytest.raises(ValidationError): + TaskStopReason(kind="safety", condition=condition) + + +def test_stop_reason_rejects_unknown_kinds_and_inexact_evidence() -> None: + with pytest.raises(ValidationError, match="kind"): + TaskStopReason.model_validate({"kind": "refused", "condition": "Cannot continue."}) + with pytest.raises(ValidationError): + TaskStopReason.model_validate_json( + '{"kind":"safety","condition":"Cannot continue.","basis":"verified",' + '"evidence":[{"kind":"artifact","artifact_ref":{"family":"handoff","artifact_id":"h"}}]}' + ) + + +def test_stop_reason_keeps_claim_evidence_bound() -> None: + reason = TaskStopReason( + kind="missing_evidence", condition="A prerequisite is unproven.", basis="verified", evidence=(CITATION,) * 31 + ) + assert len(reason.evidence) == 31 + with pytest.raises(ValidationError, match="at most 31 items"): + TaskStopReason( + kind="missing_evidence", + condition="A prerequisite is unproven.", + basis="verified", + evidence=(CITATION,) * 32, + ) + + +@pytest.mark.parametrize("status", ["blocked", "cancelled"]) +def test_verified_stop_reason_is_not_recurrence_failure_evidence(status: TaskOutcomeStatus) -> None: + outcome = TaskOutcome( + objective="Attempt an action.", + status=status, + summary="The attempt stopped.", + observations=(WorkClaim(text="The caller reported stopping."),), + stop_reason=TaskStopReason( + kind="safety", condition="Completion could not be guaranteed.", basis="verified", evidence=(CITATION,) + ), + ) + assert failure_refs(outcome, SourceRef(source_type="content", source_id="outcome-1")) == () diff --git a/tests/e2e/test_runtime_server.py b/tests/e2e/test_runtime_server.py index 124889956c..cf45872dff 100644 --- a/tests/e2e/test_runtime_server.py +++ b/tests/e2e/test_runtime_server.py @@ -683,6 +683,119 @@ async def scenario() -> None: asyncio.run(scenario()) +def test_sdk_records_and_reads_structured_stop_reasons(tmp_path: Path) -> None: + app = create_server_app(settings=_server_settings(tmp_path / "stop-reasons.db")) + + async def scenario() -> None: + async with ( + app.router.lifespan_context(app), + httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as transport, + ): + client = PowerContextClient("http://testserver", http_client=transport, trust_transport_security=True) + scope = await client.create_scope( + CreateScopeRequest( + title="Stop reasons", summary="Structured stop reasons", idempotency_key="stop-reasons" + ) + ) + captured = await client.capture_content_source( + CaptureContentSourceRequest( + scope_id=scope.scope_id, + source_id="evidence-1", + content="Required condition is absent.", + metadata={}, + ) + ) + for kind, status, basis in ( + ("safety", "blocked", "declared"), + ("scope", "cancelled", "declared"), + ("authorization", "blocked", "verified"), + ("capability", "cancelled", "verified"), + ("missing_evidence", "blocked", "verified"), + ): + reason = { + "kind": kind, + "condition": "继续执行需要先确认前提条件。", + "basis": basis, + "evidence": [] + if basis == "declared" + else [{"kind": "source", "source_ref": captured.source.model_dump(mode="json")}], + } + request = RecordTaskOutcomeRequest.model_validate({ + "scope_id": scope.scope_id, + "source_id": f"outcome-{kind}", + "outcome": { + "schema": "powercontext.task-outcome.v1", + "trust": "untrusted_observation", + "objective": "Attempt an action.", + "status": status, + "summary": "The caller deliberately stopped.", + "stop_reason": reason, + "observations": [ + {"text": "The caller reported stopping.", "basis": "declared", "evidence": []} + ], + "checks": [], + "produced_artifacts": [], + "remaining_work": [], + }, + }) + receipt = await client.record_task_outcome(request) + stored = await client.get_source(scope.scope_id, receipt.source.name, receipt.source.source_id) + content = json.loads(stored.content) + assert content["status"] == status + assert content["stop_reason"] == { + **reason, + "evidence": [] + if basis == "declared" + else [ + { + "kind": "source", + "source_ref": {"source_type": captured.source.name, "source_id": captured.source.source_id}, + } + ], + } + + asyncio.run(scenario()) + + +def test_http_rejects_invalid_stop_reason_combinations_before_writing(tmp_path: Path) -> None: + app = create_server_app(settings=_server_settings(tmp_path / "invalid-stop-reasons.db")) + with TestClient(app) as transport: + scope = transport.get("/v1/scopes/default") + scope.raise_for_status() + scope_id = scope.json()["scope_id"] + declared = {"kind": "safety", "condition": "Cannot guarantee completion.", "basis": "declared", "evidence": []} + citation = {"kind": "source", "source_ref": {"name": "content", "source_id": "evidence-1"}} + for index, (status, reason) in enumerate([ + *((status, declared) for status in ("succeeded", "partial", "failed", "unknown")), + ("blocked", {**declared, "basis": "verified"}), + ("cancelled", {**declared, "evidence": [citation]}), + ]): + response = transport.post( + "/v1/work/outcomes/record", + json={ + "scope_id": scope_id, + "source_id": f"invalid-{index}", + "outcome": { + "schema": "powercontext.task-outcome.v1", + "trust": "untrusted_observation", + "objective": "Attempt an action.", + "status": status, + "summary": "The caller stopped.", + "stop_reason": reason, + "observations": [ + {"text": "The caller reported stopping.", "basis": "declared", "evidence": []} + ], + "checks": [], + "produced_artifacts": [], + "remaining_work": [], + }, + }, + ) + assert response.status_code == 422 + readback = transport.get(f"/v1/scopes/{scope_id}/sources/content/invalid-{index}") + assert readback.status_code == 404 + + def test_sdk_closes_the_delegation_handoff_and_outcome_loop(tmp_path: Path) -> None: app = create_server_app(settings=_server_settings(tmp_path / "work-continuity.db", handoff_report=True)) diff --git a/tests/test_dsh_transport.py b/tests/test_dsh_transport.py index a9dcde5acd..05ebf07d83 100644 --- a/tests/test_dsh_transport.py +++ b/tests/test_dsh_transport.py @@ -1079,4 +1079,5 @@ def test_explicit_web_doctor_does_not_read_desktop_environment_profile( assert result.exit_code == 0, result.output host = json.loads(result.stdout)["hosts"]["dsh"] assert host["ok"] is True + assert host["checks"]["plugin_memory_protocol"]["status"] == "ok" assert host["checks"]["plugin_memory_protocol"]["checks"]["memory_protocol"] == "atomic-artifact-v1"