From 0b43477001e3453a79b310b40fc3e3e7e648c2a6 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Tue, 10 Nov 2026 18:31:07 +0800 Subject: [PATCH 1/5] feat(work): record structured task stop reasons --- docs/en/docs/develop/interfaces.md | 13 ++ docs/zh/docs/develop/interfaces.md | 11 ++ .../memory-powercontext/src/work.test.ts | 51 ++++++ .../plugins/memory-powercontext/src/work.ts | 15 +- .../pi/plugins/powercontext/src/tools.ts | 18 +- .../plugins/powercontext/tests/tools.spec.ts | 52 ++++++ openapi/powercontext.yaml | 31 ++++ .../builtin/runtime/application.py | 2 + src/powercontext/builtin/work/__init__.py | 2 + src/powercontext/builtin/work/models.py | 42 ++++- src/powercontext/http/__init__.py | 4 + src/powercontext/http/_generated/models.py | 36 ++++ src/powercontext/http/_generated/schema.py | 65 +++++++ src/powercontext/server/mapping.py | 13 ++ .../builtin/runtime/test_task_stop_reason.py | 163 ++++++++++++++++++ tests/builtin/test_task_stop_reason.py | 91 ++++++++++ tests/e2e/test_runtime_server.py | 113 ++++++++++++ 17 files changed, 719 insertions(+), 3 deletions(-) create mode 100644 tests/builtin/runtime/test_task_stop_reason.py create mode 100644 tests/builtin/test_task_stop_reason.py 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/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 4087190b18..7acd8c8935 100644 --- a/openapi/powercontext.yaml +++ b/openapi/powercontext.yaml @@ -9051,6 +9051,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 @@ -9077,6 +9104,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 d31b295cf3..2438e0c2da 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 2720cf8acc..2391e01c90 100644 --- a/src/powercontext/http/__init__.py +++ b/src/powercontext/http/__init__.py @@ -478,6 +478,8 @@ TaskCheckStatus, TaskOutcome, TaskOutcomeStatus, + TaskStopReason, + TaskStopReasonKind, Timezone, TokenEstimatorProfile, TopicMemoryArtifact, @@ -970,6 +972,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 1908b8b04a..8ccd9a495e 100644 --- a/src/powercontext/http/_generated/models.py +++ b/src/powercontext/http/_generated/models.py @@ -1184,6 +1184,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" @@ -6114,6 +6122,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", @@ -6124,6 +6156,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 c9affc309e..e47926e2e7 100644 --- a/src/powercontext/http/_generated/schema.py +++ b/src/powercontext/http/_generated/schema.py @@ -9472,6 +9472,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"]}, @@ -9480,6 +9531,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 fdb15890b3..75c31b909e 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 @@ -452,6 +453,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)) From ded2e6a6573e8164281493de472f7c4a3f054c69 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Tue, 10 Nov 2026 21:09:24 +0800 Subject: [PATCH 2/5] fix(desktop): qualify task stop reason contract --- desktop/VALIDATION.md | 46 +++++++++++++++++++ .../src/connections/compatibility.json | 21 +++++++++ .../src-tauri/src/transport/operations.json | 2 +- desktop/ui/src/generated/api.d.ts | 13 ++++++ desktop/ui/src/generated/operations.ts | 2 +- 5 files changed, 82 insertions(+), 2 deletions(-) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index cc06bcdc72..5f6dd41e42 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -2043,3 +2043,49 @@ All 736 packaged runtime files match the recorded Git source bytes. Evidence is under ignored `desktop/.artifacts/real-server.json` and `desktop/.artifacts/server-wheel/`. This record covers local SQLite protocol behavior. It does not establish installed UI, native credential persistence, Windows execution, external production acceptance or release readiness. + +## 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 +``` diff --git a/desktop/src-tauri/src/connections/compatibility.json b/desktop/src-tauri/src/connections/compatibility.json index 8c548d5cec..15e3129d6f 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1002,5 +1002,26 @@ "search_memory" ], "evidence": "desktop/VALIDATION.md#server-4568b499-statistics-product-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" } ] diff --git a/desktop/src-tauri/src/transport/operations.json b/desktop/src-tauri/src/transport/operations.json index c53302eed6..69e9cd64c4 100644 --- a/desktop/src-tauri/src/transport/operations.json +++ b/desktop/src-tauri/src/transport/operations.json @@ -1,5 +1,5 @@ { - "contractSha256": "de74d806343998bae877effb732b1606b3eb27ee9c31fbc39509ee3937fa2a4a", + "contractSha256": "34cc6572321296c6d67d2a8ca1dffd93d8ebb187a54af8f6dcdb5cd489a0926c", "operations": { "get_liveness": { "method": "GET", diff --git a/desktop/ui/src/generated/api.d.ts b/desktop/ui/src/generated/api.d.ts index 9024161177..d693e41d9a 100644 --- a/desktop/ui/src/generated/api.d.ts +++ b/desktop/ui/src/generated/api.d.ts @@ -3916,6 +3916,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"; @@ -3925,6 +3936,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 8b6ab76551..3042916e4b 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 = "de74d806343998bae877effb732b1606b3eb27ee9c31fbc39509ee3937fa2a4a"; +export const contractSha256 = "34cc6572321296c6d67d2a8ca1dffd93d8ebb187a54af8f6dcdb5cd489a0926c"; export const operations = { "get_liveness": { "method": "GET", From c786e47606d65484ea06b8eb343e248539b0d229 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Tue, 10 Nov 2026 21:33:08 +0800 Subject: [PATCH 3/5] fix(desktop): qualify merged stop reason contract --- desktop/VALIDATION.md | 44 +++++++++++++++++++ .../src/connections/compatibility.json | 22 ++++++++++ 2 files changed, 66 insertions(+) diff --git a/desktop/VALIDATION.md b/desktop/VALIDATION.md index 1bcaecc3dd..5dbd4fc7eb 100644 --- a/desktop/VALIDATION.md +++ b/desktop/VALIDATION.md @@ -2722,3 +2722,47 @@ uv run --no-sync python desktop/tests/real_server.py \ 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 c26da0b379..87eb6baa42 100644 --- a/desktop/src-tauri/src/connections/compatibility.json +++ b/desktop/src-tauri/src/connections/compatibility.json @@ -1289,5 +1289,27 @@ "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" } ] From baec263932b0419da8d115b16966abd4101a1359 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Wed, 11 Nov 2026 10:02:34 +0800 Subject: [PATCH 4/5] fix(ci): restore OpenDAL and ACP harness checks --- e2e/bub/README.md | 6 +- e2e/bub/pyproject.toml | 2 +- e2e/bub/src/powercontext_e2e/harbor_agent.py | 7 +- e2e/bub/tests/test_harbor_agent.py | 68 +++++++++++++++++++ e2e/bub/tests/test_harbor_job_config.py | 5 ++ e2e/bub/uv.lock | 18 ++++- .../powercontext_connector_opendal/source.py | 12 ++-- 7 files changed, 108 insertions(+), 10 deletions(-) diff --git a/e2e/bub/README.md b/e2e/bub/README.md index 0ca322ddb1..bf4ef0f417 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 with `agent-client-protocol==0.12.1`: Harbor 0.16 depends on +helpers such as `text_block` that SDK 1.0 no longer exports. This client pin 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..890205165b 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.12.1", "pytest>=9,<10"] [build-system] requires = ["hatchling"] diff --git a/e2e/bub/src/powercontext_e2e/harbor_agent.py b/e2e/bub/src/powercontext_e2e/harbor_agent.py index b347f13721..ccaa6d2da2 100644 --- a/e2e/bub/src/powercontext_e2e/harbor_agent.py +++ b/e2e/bub/src/powercontext_e2e/harbor_agent.py @@ -45,6 +45,8 @@ # install must repeat the pin or it cannot resolve the server at all. A server release that pins another SDK version # conflicts with this requirement and fails to install. ACP_SDK_REQUIREMENT = "agent-client-protocol==1.0.0rc2" +# Harbor 0.16's runner uses helpers removed in SDK 1.0; its venv is separate from Bub's server. +ACP_RUNNER_SDK_REQUIREMENT = "agent-client-protocol==0.12.1" STEP_FAILURE_MARKER = "/logs/agent/powercontext-step-failed" # Harbor uploads each step's tests to this directory before running the step's verifier and leaves them there. STEP_TESTS_DIR = "/tests" @@ -103,7 +105,10 @@ async def run(self, instruction: str, environment: BaseEnvironment, context: Age async def install(self, environment: BaseEnvironment) -> None: await self.exec_as_root( environment, - command=self._build_dependencies_command("uvx"), + command=( + self._build_dependencies_command("uvx") + + f"\n{self._RUNNER_VENV_PATH}/bin/pip install {shlex.quote(ACP_RUNNER_SDK_REQUIREMENT)}" + ), env={"DEBIAN_FRONTEND": "noninteractive", "PIP_INDEX_URL": pip_index_url()}, ) await self.exec_as_root(environment, command=_install_bub_command(powercontext=self._powercontext)) diff --git a/e2e/bub/tests/test_harbor_agent.py b/e2e/bub/tests/test_harbor_agent.py index 6c47b0e45b..a41cfbc68b 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,7 +22,10 @@ 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_RUNNER_SDK_REQUIREMENT, ACP_SDK_REQUIREMENT, BUB_ACP_SERVER_VERSION, REMOTE_BIN_DIR, @@ -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')}" == ACP_RUNNER_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/tests/test_harbor_job_config.py b/e2e/bub/tests/test_harbor_job_config.py index 2c621dbff3..f34ab97238 100644 --- a/e2e/bub/tests/test_harbor_job_config.py +++ b/e2e/bub/tests/test_harbor_job_config.py @@ -26,6 +26,7 @@ import threading import time import urllib.request +from importlib.metadata import version from pathlib import Path from types import SimpleNamespace from typing import NamedTuple @@ -462,6 +463,10 @@ def test_bub_runtime_install_does_not_use_the_task_images_pip_index( env for command, env in zip(environment.commands, environment.envs, strict=True) if "pip install" in command ] assert install_env["PIP_INDEX_URL"] == expected + assert any( + f"/bin/pip install agent-client-protocol=={version('agent-client-protocol')}" in command + for command in environment.commands + ) def _opencode_agent(tmp_path: Path, *, powercontext: bool) -> PowerContextOpenCodeAgent: diff --git a/e2e/bub/uv.lock b/e2e/bub/uv.lock index 1369a84900..ae60fd9eb6 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.12.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9d/95/2c28ca34e545ce0282e88272aa3a8abdf8f3f926a0492f567ea11acd071b/agent_client_protocol-0.12.1.tar.gz", hash = "sha256:9963ccb590ed96d7dc542c9c023e90676fc76b1c6562e21a9ee112f4fbcb0095", size = 130605, upload-time = "2026-08-16T14:08:22.545Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/21/61/0a2186c8ca53cf464767d4c4fb7fd9e23f48ce4547c2fa0d1c83a4d52410/agent_client_protocol-0.12.1-py3-none-any.whl", hash = "sha256:aaf3cc301ed87d9e2c4ccb91adfe1cd58784355f6ce7e513f50e7ca2391862ef", size = 85929, upload-time = "2026-08-16T14:08:21.307Z" }, +] + [[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.12.1" }, + { name = "pytest", specifier = ">=9,<10" }, +] [[package]] name = "prompt-toolkit" diff --git a/integrations/opendal/src/powercontext_connector_opendal/source.py b/integrations/opendal/src/powercontext_connector_opendal/source.py index 920719eccc..a71885c5be 100644 --- a/integrations/opendal/src/powercontext_connector_opendal/source.py +++ b/integrations/opendal/src/powercontext_connector_opendal/source.py @@ -157,12 +157,12 @@ def project(self, source: TextFileSnapshotSource, /) -> BaseModel: metadata["provider_version"] = source.provider_version if source.modified_at is not None: metadata["modified_at"] = source.modified_at.isoformat() - return _TEXT_EVIDENCE_MODEL( - source_type=TEXT_FILE_SNAPSHOT_SOURCE_NAME, - source_id=source.name, - content=source.content, - metadata=metadata, - ) + return _TEXT_EVIDENCE_MODEL.model_validate({ + "source_type": TEXT_FILE_SNAPSHOT_SOURCE_NAME, + "source_id": source.name, + "content": source.content, + "metadata": metadata, + }) def _snapshot_id(namespace: str, path: str, content_digest: str) -> str: From e2717e9de8074b063fa70c6021919ac6b6d89992 Mon Sep 17 00:00:00 2001 From: beatenevo <1578940127@qq.com> Date: Wed, 11 Nov 2026 17:21:13 +0800 Subject: [PATCH 5/5] test(dsh): declare Memory protocol in setup fixtures --- .../plugins/powercontext/tests/runtime/setup.test.mjs | 4 ++++ tests/test_dsh_transport.py | 10 +++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/integrations/dsh/plugins/powercontext/tests/runtime/setup.test.mjs b/integrations/dsh/plugins/powercontext/tests/runtime/setup.test.mjs index 9e1e3c58f5..606d52f622 100644 --- a/integrations/dsh/plugins/powercontext/tests/runtime/setup.test.mjs +++ b/integrations/dsh/plugins/powercontext/tests/runtime/setup.test.mjs @@ -34,9 +34,12 @@ test('setup validates native include trees observed by a real DSH startup', { ti const source = join(home, 'recording-powercontext') mkdirSync(join(source, 'lib'), { recursive: true }) cpSync(join(fixture.root, 'integrations/dsh/plugins/powercontext/skills'), join(source, 'skills'), { recursive: true }) + const pluginMetadata = JSON.parse(readFileSync( + join(fixture.root, 'integrations/dsh/plugins/powercontext/package.json'), 'utf8')) writeFileSync(join(source, 'package.json'), JSON.stringify({ name: 'powercontext-dsh', version: '1.0.0', type: 'module', main: './lib/index.js', dsh: { bundle: { patch: './cordis.patch.yml' } }, + powercontext: { memoryProtocol: pluginMetadata.powercontext.memoryProtocol }, })) const recording = join(home, 'received.jsonl') writeFileSync(join(source, 'lib/index.js'), @@ -103,6 +106,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/tests/test_dsh_transport.py b/tests/test_dsh_transport.py index e25c42474d..b38805d86b 100644 --- a/tests/test_dsh_transport.py +++ b/tests/test_dsh_transport.py @@ -1058,6 +1058,12 @@ def test_explicit_web_doctor_does_not_read_desktop_environment_profile(dsh_profi import powercontext.cli.dsh as dsh from powercontext.cli.system import doctor_app + source = Path(__file__).resolve().parents[1] / "integrations/dsh/plugins/powercontext" + installed = dsh_profile / "node_modules/powercontext-dsh" + installed.mkdir(parents=True) + for name in ("package.json", "cordis.patch.yml"): + shutil.copyfile(source / name, installed / name) + (dsh_profile / "package.json").write_text(json.dumps({"dsh": {"profile": {"bundles": ["powercontext-dsh"]}}})) desktop = dsh_profile.parent / "desktop" desktop.mkdir() (desktop / "package.json").write_bytes((dsh_profile / "package.json").read_bytes()) @@ -1070,4 +1076,6 @@ def test_explicit_web_doctor_does_not_read_desktop_environment_profile(dsh_profi monkeypatch.setattr(dsh, "_run_dsh", lambda *_args, **_kwargs: "id: powercontext-dsh\n") result = CliRunner().invoke(create_cli([doctor_app]), ["doctor", "dsh", "--profile", "web", "--json"]) assert result.exit_code == 0, result.output - assert json.loads(result.stdout)["hosts"]["dsh"]["ok"] is True + checks = json.loads(result.stdout)["hosts"]["dsh"] + assert checks["ok"] is True + assert checks["checks"]["plugin_memory_protocol"]["status"] == "ok"