From 7c45cc61b2918e86121936d53533fb555bb0c98c Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:47:50 +0800 Subject: [PATCH 1/8] Define verifier hook co-design contract Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/architecture/rfcs/README.md | 2 + .../rfcs/verifier-hook-co-design-v0.md | 57 +++++++ .../rfcs/verifier-hook-co-design-v0.zh-CN.md | 57 +++++++ .../turn_driver/verifier_hook_contract.ts | 142 ++++++++++++++++++ .../verifier_hook_contract.test.ts | 73 +++++++++ 5 files changed, 331 insertions(+) create mode 100644 docs/architecture/rfcs/verifier-hook-co-design-v0.md create mode 100644 docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md create mode 100644 loopx/control_plane/turn_driver/verifier_hook_contract.ts create mode 100644 tests/control_plane_ts/verifier_hook_contract.test.ts diff --git a/docs/architecture/rfcs/README.md b/docs/architecture/rfcs/README.md index ba2f0db398..43c0bda41f 100644 --- a/docs/architecture/rfcs/README.md +++ b/docs/architecture/rfcs/README.md @@ -201,6 +201,8 @@ Paired diffs do not certify translation accuracy. Existing Core/request/session owners retain authority, identity and recovery. C1–C9 connect concrete refactors, real host adoption and complete-cost qualification without changing defaults or launching experiments. +- [Verifier Hook Co-Design v0](verifier-hook-co-design-v0.md) + ([中文版](verifier-hook-co-design-v0.zh-CN.md)) - [Recoverable History Working Sets and Context Policy Extensions v0](history-working-set-context-policy-v0.md) ([中文版](history-working-set-context-policy-v0.zh-CN.md)) - **Delivery on `main`:** Proposal only; tracking [#8450](https://github.com/loopx-project/loopx/issues/8450). diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.md new file mode 100644 index 0000000000..b9ed444f70 --- /dev/null +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.md @@ -0,0 +1,57 @@ +# RFC: Verifier Hook Co-Design (v0) + +- **RFC status:** Proposed +- **Delivery maturity:** TypeScript contract. Host adapters and outcome qualification are pending. +- **Related contracts:** [Controller and executor](controller-executor-unified-contract-v0.md), [History working sets](history-working-set-context-policy-v0.md), [Target, Yardstick and Stride](target-yardstick-stride-decisions-v0.md), [Capability portfolio](goal-scoped-capability-portfolio-v0.md) +- **Language mirror:** [中文版](verifier-hook-co-design-v0.zh-CN.md) + +## 1. Authority and solver view + +Use public host hooks and session branching at four boundaries to improve independently accepted outcomes and reduce full cost. C1 remains the authority for Goal, Todo, acceptance, evidence and settlement. The solver receives a projection of the objective, cumulative acceptance and constraints, verifier profile, best verified incumbent and falsification references. The controller keeps the complete decision and uses existing admission and settlement. A successful model response, a hook event and accepted work are distinct facts. + +The Goal verifier profile identifies a version-bound external Oracle and may refer to the existing work-yardstick profile. The cheap yardstick steers exploration. The independent Oracle validates the exact candidate under current acceptance. Missing observations remain unknown. Run the verifier outside the solver's writable checkout with independent process and file permissions. Use existing controls for external actions. Attribute candidate and evaluator changes separately at settlement. Diff audit can withhold acceptance after a discrepancy. Filesystem isolation and external authorization enforce the boundary before effects. + +Use official extension interfaces with unmodified host kernels and supported authentication for each host. Credentials stay with the client they were issued for. Adapters report observed behavior for their version and surface. Feature off leaves current execution, C1 transport and settlement unchanged. + +## 2. Capability negotiation and boundaries + +No verifier hook route participates when the feature is off. When enabled, L0 uses bounded launch and stop with the same independent Oracle and settlement semantics. L1 adds observed session lineage and bounded context delivery at supported boundaries. L2 additionally requires milestone observation, isolated child work and verified return. The highest supported tier applies. Opt-in for the optional pre-tool extension requires explicit policy and an observed matching hook. It is off in ordinary solve at every tier. Capabilities and tiers grant no authority. + +| Boundary | Behavior | Fallback | +| --- | --- | --- | +| Start or resume | At a real resume or phase change, deliver the bounded solver view or exact evidence references. Quiet turns skip recurring administrative context. | Deliver the view at bounded launch. Measure actual cache use separately from prefix equality. | +| Milestone probe | Enqueue a configured, budgeted observation outside the synchronous tool path. Feed back evidenced plateau, regression or proxy rank reversal at the next supported boundary. | Read at the next bounded turn. An unavailable probe stays unknown. | +| Compaction or subscope | Capture open constraints and falsification references before the boundary, then restore their verified projection. Verify a child branch before returning a compact result. | Keep original inputs and defer the return to the next supported boundary. | +| Stop or completion claim | Submit the exact candidate to the independent Oracle. Return a reproducible counterexample after a bounded failure. The controller owns pending or expensive evaluation. | Normal settlement withholds acceptance when the host cannot continue in place. | + +Transitions report `completion_claim` to the Oracle, `yardstick_plateau_or_regression` to Stride, and `proxy_order_reversed` to the yardstick owner for verification or replacement. `protected_boundary_touch` retains isolation refusal or audit evidence, stops the affected attempt and re-enters under original authority. Observations cannot directly change the Todo, activate a capability, publish or spend. Regular work avoids a per-tool synchronous verifier. + +| Host | Start / resume | Milestone | Compaction / subscope | Stop | +| --- | --- | --- | --- | --- | +| Official Codex | `SessionStart`, supported `UserPromptSubmit` context, native lineage and Turn-bound MCP probes | Selected `PostToolUse` or tool-completion observation with bounded asynchronous work | `PreCompact` / `PostCompact` observe compaction. Restore through supported start context or a bound read. Use `SubagentStart` / `SubagentStop` for lifecycle and App Server `thread/fork` for a separate branch | `Stop` blocking feedback where supported. Otherwise use controller settlement | +| DSH Cordis | Plugin observes the session and first bound turn | `session/event` with `step/end` | Observe supported session events and qualify concrete branch, restore and verified return before declaring L2 | `turn/end` through `session/event`, then controller acceptance | +| Claude Code | `SessionStart` and supported `UserPromptSubmit` | Selected `PostToolUse` | Supported `PreCompact` / `PostCompact` and `SubagentStart` / `SubagentStop`. Verify post-compact output on the installed version or restore on next start | `Stop` feedback where supported | +| Google Antigravity | `SessionStart` or next bounded `PreInvocation` | Selected `PostToolUse` or meaningful `PostInvocation` | Keep raw and recover at the next supported start | `Stop`, with independent controller acceptance | +| Generic CLI or Pi compatibility | Controller-supplied bounded start | Read at the turn boundary | Keep raw, qualify richer behavior by adapter | Outer Stop-Hook or bounded exit | + +Official Codex and DSH are complementary reference adapters. Use official Codex for same-host strong-model comparison and consequential candidate or verifier design. Use DSH for approved high-throughput candidate screening and plugin trials. Preserve shared artifact identity and report cross-host outcomes separately from same-host comparisons. Pi remains an optional capability-based route. Optional pre-tool entries include Codex, Claude and Antigravity `PreToolUse`, and DSH `agent/pre-step` at its own granularity. A hook registration alone provides no filesystem fence. [Codex Hooks](https://learn.chatgpt.com/docs/hooks), [Codex App Server](https://learn.chatgpt.com/docs/app-server), [Claude Code Hooks](https://code.claude.com/docs/en/hooks), [Antigravity Hooks](https://antigravity.google/docs/hooks), [DSH adapter](../../../packages/dsh-loopx-plugin/src/driver.ts). + +## 3. VerifiedClose + +1. Branch from a known session and parent epoch using a public host or controller operation. Isolate the candidate workspace. Conversation branching grants no new write lease, verifier authority, credentials or cache guarantee. +2. Capture the exact candidate for the independent Oracle. Its immutable receipt binds Goal, Todo, parent epoch, child scope, `candidate_sha` and `verifier_version`. It identifies available fast and slow readings, verdict, falsified hypotheses and original observations or transcript. Matching failure carries a reproducible counterexample. Missing readings stay unknown. +3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. Append its compact evidence-linked result at a supported parent boundary. Preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return a matching counterexample when available. + +Classify overlap from the next work's evidence dependencies. High overlap means the next probe still needs intermediate candidate state, unresolved counterexamples or the raw comparison history. Low overlap means the next scope can act from the verified result and its bounded evidence references. Treat an unbound next step or an incomplete dependency read as unknown. Apply the existing reset break-even against the saved context bytes, cold prefill and any expected recovery reads. + +The history policy owns the transitions, including `EpochReset` as the only explicit prefix rebase after its break-even and exact-source checks. Branch return alone does not start a new epoch. Use compact events as boundary observations. Restore through a model-visible hook or a bound read after invalidation. Codex compact events alone do not deliver arbitrary model context or replace the sampling compiler. Spine motivates protecting parent context through structured child work. Its in-core compiler and reported results do not qualify the hook route. Measure cache hits, full cost and outcome quality independently. [Spine](https://arxiv.org/abs/2610.37224), [History working sets](history-working-set-context-policy-v0.md). + +## 4. Verifier-gated domain plugins + +The solver may stage content-addressed yardsticks, diagnostics or verification recipes. An independent trial tests held-out failures, benign cases, overhead and, for a new yardstick, rank fidelity against the Oracle. Bind the trial receipt to the exact artifact, verifier and configured scope. Trial success supports adoption through existing Goal configuration and capability portfolio ownership. It cannot activate the artifact, grant permissions or replace the Oracle. Observe post-adoption utility and use existing degrade or retire routes when cost or fidelity regresses. Keep prior revisions and negative results readable. DSH is one delivery adapter. [Capability portfolio](goal-scoped-capability-portfolio-v0.md). + +## 5. Acceptance + +- Contract checks cover feature off, L0/L1/L2 negotiation, explicit pre-tool opt-in, exact accepted return and refusal of foreign receipts. Run bilingual and diff-based premerge validation. +- Qualify the deployed host path on one original Goal/Todo, with an ordinary turn, missing or failed verification, compact or branch readback and exact settlement replay. Confirm the actual Hook outputs on that version and surface. Contract tests establish neither native adoption nor cache retention. +- Compare with the same host's Stop-Hook baseline at matched model, task, access and budget. Record accepted outcomes, invalid completions, elapsed time, cached and uncached tokens, verifier calls, retries, storage and human intervention. Include high and low overlap. Keep cross-host results outside causal attribution for the same-host treatment. diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md new file mode 100644 index 0000000000..b5d7fcb0e4 --- /dev/null +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md @@ -0,0 +1,57 @@ +# RFC:面向独立验证的 Hook 协同契约(v0) + +- **RFC 状态:** Proposed +- **交付成熟度:** TypeScript 契约。宿主适配与成果验收待验证。 +- **关联契约:** [控制器与执行器](controller-executor-unified-contract-v0.zh-CN.md)、[历史工作集](history-working-set-context-policy-v0.zh-CN.md)、[Target、Yardstick 与 Stride](target-yardstick-stride-decisions-v0.zh-CN.md)、[能力组合](goal-scoped-capability-portfolio-v0.zh-CN.md) +- **语言镜像:** [English](verifier-hook-co-design-v0.md) + +## 1. 权限与求解视图 + +通过公开宿主 Hook 和会话分支,在四个边界提高可独立验收的成果并降低完整成本。C1 继续持有 Goal、Todo、验收、证据和结算。求解器消费目标、累积验收及硬约束、Verifier Profile、已验历史最优和证伪引用的投影。控制器保留完整决策并走既有准入与结算。模型成功响应、Hook 触发和成果通过验收是独立事实。 + +Goal Verifier Profile 绑定外部权威验证器(Oracle)的版本,可引用现有快尺配置。快尺为探索提供方向,独立 Oracle 按当前验收核验确切候选。缺证保持未知。验证器在求解器可写工作区之外运行,由独立进程和文件权限保护。外部行动沿现有控制。结算时区分候选和验证器改动。Diff 审计发现偏离后可暂缓验收。文件系统隔离和外部授权在副作用之前实施保护。 + +采用官方扩展和未修改的宿主内核,各宿主走各自支持的身份认证,凭据限于原客户端。适配器按版本与入口报告观察到的行为。关闭功能时保持现有执行、C1 传输和结算行为。 + +## 2. 能力协商与边界 + +功能关闭时没有验证 Hook 参与。启用后,L0 以有界启动和停止保留独立 Oracle 与结算语义。L1 额外要求观察到会话血统及有界上下文交付。L2 再要求可观测里程碑、隔离子工作和经验证的回传。按已支持的最高档执行。可选前置扩展须显式选择且存在已观察匹配的 Hook。每一档常规求解都默认关闭此扩展。能力和档位本身不授予权限。 + +| 边界 | 行为 | 回退 | +| --- | --- | --- | +| 启动或恢复 | 实际恢复或阶段变化时交付有界求解视图或精确引用。安静轮次省去重复记账上下文。 | 在有界启动交付同一视图。实际缓存命中与前缀字节一致性分别测量。 | +| 里程碑采样 | 将已配置且有预算的观测排至同步工具路径之外。在下一可用反馈边界带回有证据的平台期、回退或排序反转。 | 下一有界回合读回,无法观测保持未知。 | +| 压缩或子作用域 | 边界前固化未决约束及证伪引用,之后恢复核验过的投影。子工作经过验证后才回传精简结果。 | 保留原始输入,在下一支持的边界回传。 | +| 停止或成果声明 | 将确切候选交独立 Oracle。有界失败回传可复现反例,昂贵或未结束的验证归控制器推进。 | 宿主无法原位继续时,通过普通结算保留未验状态。 | + +`completion_claim` 提交 Oracle。 `yardstick_plateau_or_regression` 交给 Stride。 `proxy_order_reversed` 由快尺 owner 核查或换尺。 `protected_boundary_touch` 保留隔离拒绝或审计证据,停止受影响尝试并按原权限重新进入。观测不能直接选换 Todo、激活能力、发布或记账。常规工作避免逐工具同步验证。 + +| 宿主 | 启动或恢复 | 里程碑 | 压缩或子作用域 | 停止 | +| --- | --- | --- | --- | --- | +| 官方 Codex | `SessionStart`、受支持的 `UserPromptSubmit` 上下文、原生血统与 Turn 绑定 MCP 探针 | 选定 `PostToolUse` 或工具完成事件入队后尽快返回 | `PreCompact` / `PostCompact` 观察压缩边界,经受支持的 SessionStart 上下文或绑定读取恢复、`SubagentStart` / `SubagentStop` 生命周期、App Server `thread/fork` 分支 | 支持时由 `Stop` 反馈阻断,否则控制器结算 | +| DSH Cordis | 插件观察会话及首个绑定回合 | `session/event` 的 `step/end` | 观察受支持的会话事件,具体分支、恢复和验证回传通过核验才能声明 L2 | `session/event` 的 `turn/end` 进入控制器验收 | +| Claude Code | `SessionStart` 与受支持的 `UserPromptSubmit` | 选定 `PostToolUse` | 受支持的 `PreCompact` / `PostCompact` 与 `SubagentStart` / `SubagentStop`,在已安装版本验证压缩后输出,否则下次启动恢复 | 受支持的 `Stop` 反馈 | +| Google Antigravity | `SessionStart` 或下一有界 `PreInvocation` | 选定 `PostToolUse` 或有实质进展的 `PostInvocation` | 保留原内容并在下一可用启动时恢复 | `Stop`,控制器独立验收 | +| 通用 CLI 或 Pi 兼容层 | 控制器供有界启动 | 在回合边界读回 | 保留原内容,按适配器核验增强行为 | 外层 Stop-Hook 或有界退出 | + +官方 Codex 和 DSH 是互补的参考适配器。官方 Codex 负责同宿主强模型对照、关键候选和验证器设计。DSH 承接获准的高吞吐筛选和插件试验。两边复用统一产物身份,跨宿主成果单独报告。Pi 可按能力接入。可选前置接口包括 Codex、Claude 和 Antigravity 的 `PreToolUse`,以及粒度不同的 DSH `agent/pre-step`。注册 Hook 本身无法保证文件系统隔离。 [Codex Hooks](https://learn.chatgpt.com/docs/hooks)、[Codex App Server](https://learn.chatgpt.com/docs/app-server)、[Claude Code Hooks](https://code.claude.com/docs/en/hooks)、[Antigravity Hooks](https://antigravity.google/docs/hooks)、[DSH 适配器](../../../packages/dsh-loopx-plugin/src/driver.ts)。 + +## 3. VerifiedClose + +1. 以公开宿主或控制器操作,从已识别会话及父纪元派生分支,隔离候选工作区。复制会话不授予写租约、验证权限或凭据,也不证明缓存命中。 +2. 捕获确切候选交给独立 Oracle。其不可变回执绑定 Goal、Todo、父纪元、子作用域、`candidate_sha` 和 `verifier_version`,记录可用快慢尺读数、裁决及证伪条目,包含原始观测或轨迹引用。身份匹配的失败回执提供可复现反例,缺失读数保持未知。 +3. 通过受信任原验证器解析回执。只有身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。在受支持的父会话边界追加精简证据,原件可独立重读。缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有身份匹配的反例则回传。 + +按下一步工作的证据依赖判断重叠。下一探针仍需中间候选状态、未决反例或原始比较历史时为高重叠。下一作用域凭已核验结果及有界证据引用即可推进时为低重叠。下一步未绑定或依赖未读全时保持未知。结合节省的上下文字节、冷前缀重建和预期恢复读取,沿既有策略判断重置能否回本。 + +现有历史策略持有状态跃迁。仅允许该策略按收支平衡及精确源检查显式执行 `EpochReset` 重建前缀。子分支回传不自动开启新纪元。用压缩事件标记边界。失效后沿模型可见的 Hook 或绑定读取恢复。Codex 压缩事件本身无法注入任意模型上下文或替换采样编译器。Spine 说明结构化子工作可以保护父上下文,但其内核编译及论文结果不构成 Hook 路线验收。缓存命中、完整成本及成果质量须独立测量。 [Spine](https://arxiv.org/abs/2610.37224)、[历史工作集](history-working-set-context-policy-v0.zh-CN.md)。 + +## 4. 经 Verifier 准入的领域插件 + +求解器可暂存按内容寻址的快尺、诊断探针和验证配方。独立 trial 测试留出的失败样例、正常样例、开销及新快尺对 Oracle 的排序保真。试验回执绑定确切产物、验证器和配置作用域。试验通过后,沿现有 Goal 配置和能力组合决定是否采用。通过试验不自动激活产物、不增加权限、不替换 Oracle。采用后观测效用,在成本或保真退化时使用现有降级或退役入口。保留历史版本及负结果。DSH 是其中一种交付适配器。 [能力组合](goal-scoped-capability-portfolio-v0.zh-CN.md)。 + +## 5. 验收 + +- 契约检查覆盖功能关闭、L0/L1/L2 协商、显式前置扩展、确切已验回传及拒绝其他作用域的回执。运行双语和基于 diff 的 premerge 检查。 +- 宿主路径在同一原 Goal/Todo 上通过普通回合、验证失败或缺证、压缩或分支读回及确切结算重放。对实际版本及入口验证 Hook 输出。契约测试无法证明原生采用或缓存保持。 +- 匹配模型、任务、访问权限和预算,对照同宿主 Stop-Hook。记录验收成果、错误完成、耗时、缓存和未缓存 token、验证调用、重试、存储及人工介入。覆盖高低重叠工作。跨宿主结果不计入同宿主效果归因。 diff --git a/loopx/control_plane/turn_driver/verifier_hook_contract.ts b/loopx/control_plane/turn_driver/verifier_hook_contract.ts new file mode 100644 index 0000000000..650140d33c --- /dev/null +++ b/loopx/control_plane/turn_driver/verifier_hook_contract.ts @@ -0,0 +1,142 @@ +// Host-neutral contract for the proposed verifier Hook adapter. The C1, +// working-set and capability-portfolio owners still admit every effect. +import type { WorkYardstickProfile } from "../work_items/yardstick_decision.ts"; + +export type HarnessVerifierCapabilities = Readonly<{ + session_lineage?: boolean; + boundary_context?: boolean; + milestone_observation?: boolean; + isolated_subscope?: boolean; + verified_return?: boolean; + pre_tool_use?: boolean; +}>; + +export type VerifierHookPolicy = Readonly<{ + enabled: boolean; + pre_tool_use?: boolean; +}>; + +export function negotiateVerifierHooks( + policy: VerifierHookPolicy, + capabilities: HarnessVerifierCapabilities = {}, +): { tier: "L0" | "L1" | "L2"; pre_tool_use: boolean } | null { + if (policy.enabled !== true) return null; + + const lineage = capabilities.session_lineage === true && capabilities.boundary_context === true; + const scoped = capabilities.milestone_observation === true + && capabilities.isolated_subscope === true && capabilities.verified_return === true; + return { + tier: lineage ? (scoped ? "L2" : "L1") : "L0", + pre_tool_use: policy.pre_tool_use === true && capabilities.pre_tool_use === true, + }; +} + +export type GoalVerifierProfile = Readonly<{ + oracle_ref: string; + verifier_version: string; + yardstick?: WorkYardstickProfile; +}>; + +export type VerifierSolverView = Readonly<{ + objective: string; + acceptance_refs: readonly string[]; + verifier: GoalVerifierProfile; + incumbent_ref?: string; + falsification_refs: readonly string[]; +}>; + +export type VerifierTransition = + | { kind: "completion_claim"; candidate_sha: string } + | { kind: "yardstick_plateau_or_regression"; evidence_ref: string } + | { kind: "proxy_order_reversed"; evidence_ref: string } + | { kind: "protected_boundary_touch"; isolation_receipt_ref: string }; + +export type VerifierHookEvent = Readonly<{ + goal_id: string; + todo_id: string; + session_ref: string; + epoch_ref: string; + turn_ref?: string; +}> & ( + | { boundary: "start" } + | { boundary: "milestone_probe"; observation_ref: string } + | { boundary: "compaction_or_subscope"; source_ref: string } + | { boundary: "stop"; transition: Extract } +); + +export type VerifiedScopeIdentity = Readonly<{ + goal_id: string; + todo_id: string; + parent_epoch_ref: string; + child_scope_ref: string; + candidate_sha: string; + verifier_version: string; +}>; + +export type VerifierScopeReceipt = Readonly<{ + identity: VerifiedScopeIdentity; + oracle_evidence_ref: string; + yardstick_evidence_ref?: string; + source_ref: string; + falsification_refs: readonly string[]; +}> & ( + | { verdict: "passed"; summary_ref: string } + | { verdict: "failed"; counterexample_ref: string } + | { verdict: "unknown" } +); + +export type VerifiedCloseRequest = Readonly<{ + identity: VerifiedScopeIdentity; + receipt_ref: string; + overlap: "high" | "low" | "unknown"; + open_obligations: boolean; +}>; + +export type VerifiedCloseRecommendation = + | { action: "KeepRaw"; counterexample_ref?: string } + | { action: "FoldToReceipt"; receipt_ref: string; source_ref: string; summary_ref: string }; + +// The caller binds the reader to the independent verifier's authenticated, +// immutable receipt store. A hook report or model transcript is never that store. +export function recommendVerifiedClose( + request: VerifiedCloseRequest, + readVerifierReceipt: (ref: string) => VerifierScopeReceipt | undefined, +): VerifiedCloseRecommendation { + const receipt = readVerifierReceipt(request.receipt_ref); + const expected = request.identity; + const observed = receipt?.identity; + if (!receipt || !observed + || observed.goal_id !== expected.goal_id || observed.todo_id !== expected.todo_id + || observed.parent_epoch_ref !== expected.parent_epoch_ref + || observed.child_scope_ref !== expected.child_scope_ref + || observed.candidate_sha !== expected.candidate_sha + || observed.verifier_version !== expected.verifier_version) { + return { action: "KeepRaw" }; + } + if (receipt.verdict === "failed") { + return { action: "KeepRaw", counterexample_ref: receipt.counterexample_ref }; + } + if (receipt.verdict !== "passed" || request.open_obligations !== false || request.overlap !== "low") { + return { action: "KeepRaw" }; + } + return { + action: "FoldToReceipt", + receipt_ref: request.receipt_ref, + source_ref: receipt.source_ref, + summary_ref: receipt.summary_ref, + }; +} + +export type DomainPluginCandidate = Readonly<{ + artifact_digest: string; + capability_ref: string; + kind: "yardstick" | "diagnostic_probe" | "verification_recipe"; +}>; + +// These observations index the existing portfolio and verifier owners. The +// solver can propose staging only. Activated versions are read from configuration. +export type DomainPluginTrial = + | { stage: "staging"; candidate: DomainPluginCandidate } + | { stage: "trial"; candidate: DomainPluginCandidate; trial_receipt_ref: string } + | { stage: "adopted"; candidate: DomainPluginCandidate; adoption_receipt_ref: string } + | { stage: "retired"; candidate: DomainPluginCandidate; retirement_receipt_ref: string }; diff --git a/tests/control_plane_ts/verifier_hook_contract.test.ts b/tests/control_plane_ts/verifier_hook_contract.test.ts new file mode 100644 index 0000000000..9c4a7e6075 --- /dev/null +++ b/tests/control_plane_ts/verifier_hook_contract.test.ts @@ -0,0 +1,73 @@ +import { strict as assert } from "node:assert"; +import test from "node:test"; + +import { + negotiateVerifierHooks, recommendVerifiedClose, type VerifiedCloseRequest, +} from "../../loopx/control_plane/turn_driver/verifier_hook_contract.ts"; + +const l1 = { session_lineage: true, boundary_context: true }; +const l2 = { ...l1, milestone_observation: true, isolated_subscope: true, verified_return: true }; + +test("enabled negotiation uses observed capabilities and never infers pre-tool opt-in", () => { + const policy = { enabled: true }; + assert.equal(negotiateVerifierHooks({ enabled: false, pre_tool_use: true }, l2), null); + assert.deepEqual(negotiateVerifierHooks(policy), { tier: "L0", pre_tool_use: false }); + assert.deepEqual(negotiateVerifierHooks(policy, { ...l2, session_lineage: false }), + { tier: "L0", pre_tool_use: false }); + assert.deepEqual(negotiateVerifierHooks(policy, l1), { tier: "L1", pre_tool_use: false }); + assert.deepEqual(negotiateVerifierHooks(policy, { ...l2, verified_return: false }), + { tier: "L1", pre_tool_use: false }); + assert.deepEqual(negotiateVerifierHooks(policy, { ...l2, pre_tool_use: true }), + { tier: "L2", pre_tool_use: false }); + assert.deepEqual(negotiateVerifierHooks({ ...policy, pre_tool_use: true }, l2), + { tier: "L2", pre_tool_use: false }); + assert.deepEqual(negotiateVerifierHooks({ ...policy, pre_tool_use: true }, { ...l2, pre_tool_use: true }), + { tier: "L2", pre_tool_use: true }); +}); + +const identity = { + goal_id: "goal", todo_id: "todo", parent_epoch_ref: "epoch:9", child_scope_ref: "scope:3", + candidate_sha: "candidate:26", verifier_version: "verifier:4", +}; +const request: VerifiedCloseRequest = { + identity, receipt_ref: "receipt:21", overlap: "low", open_obligations: false, +}; +const source = { + identity, oracle_evidence_ref: "oracle:result", yardstick_evidence_ref: "probe:result", + source_ref: "capture:raw-child", falsification_refs: ["finding:invalid-shortcut"], +}; + +test("verified return resolves the named oracle receipt and stages the exact source reference", () => { + const result = recommendVerifiedClose(request, ref => { + assert.equal(ref, "receipt:21"); + return { ...source, verdict: "passed", summary_ref: "capture:child-receipt" }; + }); + assert.deepEqual(result, { + action: "FoldToReceipt", receipt_ref: "receipt:21", + source_ref: "capture:raw-child", summary_ref: "capture:child-receipt", + }); +}); + +test("open, overlapping, unknown and mismatched work stays raw", () => { + const passed = { ...source, verdict: "passed", summary_ref: "capture:child-receipt" } as const; + for (const variant of [ + { ...request, overlap: "high" as const }, + { ...request, overlap: "unknown" as const }, + { ...request, open_obligations: true }, + ]) { + assert.deepEqual(recommendVerifiedClose(variant, () => passed), { action: "KeepRaw" }); + } + const missingObligations = { ...request, open_obligations: undefined } as unknown as VerifiedCloseRequest; + assert.deepEqual(recommendVerifiedClose(missingObligations, () => passed), { action: "KeepRaw" }); + for (const key of Object.keys(identity) as (keyof typeof identity)[]) { + const mismatch = { ...identity, [key]: "different" }; + assert.deepEqual(recommendVerifiedClose(request, () => ({ ...passed, identity: mismatch })), + { action: "KeepRaw" }); + } + assert.deepEqual(recommendVerifiedClose(request, () => undefined), { action: "KeepRaw" }); + assert.deepEqual(recommendVerifiedClose(request, () => ({ ...source, verdict: "unknown" })), + { action: "KeepRaw" }); + assert.deepEqual(recommendVerifiedClose(request, () => ({ + ...source, verdict: "failed", counterexample_ref: "oracle:counterexample", + })), { action: "KeepRaw", counterexample_ref: "oracle:counterexample" }); +}); From 2bc53310f659e7222dfe73293bc350735d841df3 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:24:33 +0800 Subject: [PATCH 2/8] Require readable verifier evidence and bind solver constraints Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../rfcs/verifier-hook-co-design-v0.md | 4 +- .../rfcs/verifier-hook-co-design-v0.zh-CN.md | 4 +- loopx/control_plane/quota/turn_envelope.ts | 4 + .../turn_driver/verifier_hook_contract.ts | 31 ++++++-- .../verifier_hook_contract.test.ts | 75 ++++++++++++++++--- 5 files changed, 95 insertions(+), 23 deletions(-) diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.md index b9ed444f70..7d137d729e 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.md @@ -7,7 +7,7 @@ ## 1. Authority and solver view -Use public host hooks and session branching at four boundaries to improve independently accepted outcomes and reduce full cost. C1 remains the authority for Goal, Todo, acceptance, evidence and settlement. The solver receives a projection of the objective, cumulative acceptance and constraints, verifier profile, best verified incumbent and falsification references. The controller keeps the complete decision and uses existing admission and settlement. A successful model response, a hook event and accepted work are distinct facts. +Use public host hooks and session branching at four boundaries to improve independently accepted outcomes and reduce full cost. C1 remains the authority for Goal, Todo, acceptance, evidence and settlement. The solver receives a projection of the objective, cumulative acceptance and constraints, verifier profile, best verified incumbent and falsification references. Startup and recovery read the same write scope and stop conditions through the original C1 capture digest and `/goal_boundary` pointer. The controller keeps the complete decision and uses existing admission and settlement. A successful model response, a hook event and accepted work are distinct facts. The Goal verifier profile identifies a version-bound external Oracle and may refer to the existing work-yardstick profile. The cheap yardstick steers exploration. The independent Oracle validates the exact candidate under current acceptance. Missing observations remain unknown. Run the verifier outside the solver's writable checkout with independent process and file permissions. Use existing controls for external actions. Attribute candidate and evaluator changes separately at settlement. Diff audit can withhold acceptance after a discrepancy. Filesystem isolation and external authorization enforce the boundary before effects. @@ -40,7 +40,7 @@ Official Codex and DSH are complementary reference adapters. Use official Codex 1. Branch from a known session and parent epoch using a public host or controller operation. Isolate the candidate workspace. Conversation branching grants no new write lease, verifier authority, credentials or cache guarantee. 2. Capture the exact candidate for the independent Oracle. Its immutable receipt binds Goal, Todo, parent epoch, child scope, `candidate_sha` and `verifier_version`. It identifies available fast and slow readings, verdict, falsified hypotheses and original observations or transcript. Matching failure carries a reproducible counterexample. Missing readings stay unknown. -3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. Append its compact evidence-linked result at a supported parent boundary. Preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return a matching counterexample when available. +3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. The authoritative reader must resolve the Oracle evidence, original source and compact result. An empty, mismatched or unreadable reference keeps `KeepRaw`. Append its compact evidence-linked result at a supported parent boundary. Preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return a matching counterexample when available. Classify overlap from the next work's evidence dependencies. High overlap means the next probe still needs intermediate candidate state, unresolved counterexamples or the raw comparison history. Low overlap means the next scope can act from the verified result and its bounded evidence references. Treat an unbound next step or an incomplete dependency read as unknown. Apply the existing reset break-even against the saved context bytes, cold prefill and any expected recovery reads. diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md index b5d7fcb0e4..2f42981cf0 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md @@ -7,7 +7,7 @@ ## 1. 权限与求解视图 -通过公开宿主 Hook 和会话分支,在四个边界提高可独立验收的成果并降低完整成本。C1 继续持有 Goal、Todo、验收、证据和结算。求解器消费目标、累积验收及硬约束、Verifier Profile、已验历史最优和证伪引用的投影。控制器保留完整决策并走既有准入与结算。模型成功响应、Hook 触发和成果通过验收是独立事实。 +通过公开宿主 Hook 和会话分支,在四个边界提高可独立验收的成果并降低完整成本。C1 继续持有 Goal、Todo、验收、证据和结算。求解器消费目标、累积验收及硬约束、Verifier Profile、已验历史最优和证伪引用的投影。启动和恢复视图通过原 C1 捕获散列和 `/goal_boundary` 指针读回同一套写入范围与停止条件。控制器保留完整决策并走既有准入与结算。模型成功响应、Hook 触发和成果通过验收是独立事实。 Goal Verifier Profile 绑定外部权威验证器(Oracle)的版本,可引用现有快尺配置。快尺为探索提供方向,独立 Oracle 按当前验收核验确切候选。缺证保持未知。验证器在求解器可写工作区之外运行,由独立进程和文件权限保护。外部行动沿现有控制。结算时区分候选和验证器改动。Diff 审计发现偏离后可暂缓验收。文件系统隔离和外部授权在副作用之前实施保护。 @@ -40,7 +40,7 @@ Goal Verifier Profile 绑定外部权威验证器(Oracle)的版本,可引 1. 以公开宿主或控制器操作,从已识别会话及父纪元派生分支,隔离候选工作区。复制会话不授予写租约、验证权限或凭据,也不证明缓存命中。 2. 捕获确切候选交给独立 Oracle。其不可变回执绑定 Goal、Todo、父纪元、子作用域、`candidate_sha` 和 `verifier_version`,记录可用快慢尺读数、裁决及证伪条目,包含原始观测或轨迹引用。身份匹配的失败回执提供可复现反例,缺失读数保持未知。 -3. 通过受信任原验证器解析回执。只有身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。在受支持的父会话边界追加精简证据,原件可独立重读。缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有身份匹配的反例则回传。 +3. 通过受信任原验证器解析回执。只有身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。权威读取方须能读回 Oracle 证据、原始来源和摘要。任一引用为空、错绑或无法读取时维持 `KeepRaw`。在受支持的父会话边界追加精简证据,原件可独立重读。缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有身份匹配的反例则回传。 按下一步工作的证据依赖判断重叠。下一探针仍需中间候选状态、未决反例或原始比较历史时为高重叠。下一作用域凭已核验结果及有界证据引用即可推进时为低重叠。下一步未绑定或依赖未读全时保持未知。结合节省的上下文字节、冷前缀重建和预期恢复读取,沿既有策略判断重置能否回本。 diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 9e31ec2309..b4bb6d782e 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -73,6 +73,10 @@ export const ACTION_SIGNATURE_COVERAGE = ACTION_SIGNATURE_COVERAGE_V0; // Single owner for the should-run artifact path a child brief points at, so the // legacy field token stays inside this module's retirement budget. export const QUOTA_GOAL_BOUNDARY_ARTIFACT = "quota_should_run.goal_boundary"; +export type QuotaGoalBoundaryReference = Readonly<{ + capture_sha256: string; + pointer: "/goal_boundary"; +}>; export const SCHEDULER_QUOTA_IDENTITY_KEYS = ["goal_id", "agent_identity.agent_id", "effective_action", "heartbeat_recommendation.recommended_mode", "interaction_contract.mode"]; const PLANNING_HORIZON_DETAIL_REFS_REF = "$.detail_ref"; diff --git a/loopx/control_plane/turn_driver/verifier_hook_contract.ts b/loopx/control_plane/turn_driver/verifier_hook_contract.ts index 650140d33c..855993f445 100644 --- a/loopx/control_plane/turn_driver/verifier_hook_contract.ts +++ b/loopx/control_plane/turn_driver/verifier_hook_contract.ts @@ -1,5 +1,6 @@ // Host-neutral contract for the proposed verifier Hook adapter. The C1, // working-set and capability-portfolio owners still admit every effect. +import type { QuotaGoalBoundaryReference } from "../quota/turn_envelope.ts"; import type { WorkYardstickProfile } from "../work_items/yardstick_decision.ts"; export type HarnessVerifierCapabilities = Readonly<{ @@ -40,6 +41,7 @@ export type GoalVerifierProfile = Readonly<{ export type VerifierSolverView = Readonly<{ objective: string; acceptance_refs: readonly string[]; + goal_boundary_ref: QuotaGoalBoundaryReference; verifier: GoalVerifierProfile; incumbent_ref?: string; falsification_refs: readonly string[]; @@ -58,7 +60,7 @@ export type VerifierHookEvent = Readonly<{ epoch_ref: string; turn_ref?: string; }> & ( - | { boundary: "start" } + | { boundary: "start"; view: VerifierSolverView } | { boundary: "milestone_probe"; observation_ref: string } | { boundary: "compaction_or_subscope"; source_ref: string } | { boundary: "stop"; transition: Extract } @@ -96,13 +98,22 @@ export type VerifiedCloseRecommendation = | { action: "KeepRaw"; counterexample_ref?: string } | { action: "FoldToReceipt"; receipt_ref: string; source_ref: string; summary_ref: string }; -// The caller binds the reader to the independent verifier's authenticated, -// immutable receipt store. A hook report or model transcript is never that store. +export type VerifiedCloseReader = Readonly<{ + readReceipt: (ref: string) => VerifierScopeReceipt | undefined; + canReadEvidence: (ref: string) => boolean; +}>; + +function hasReference(ref: string): boolean { + return typeof ref === "string" && ref.trim().length > 0; +} + +// The adapter binds both reads to their authoritative stores and current scope. +// It reports absent, inaccessible or mismatched evidence as unreadable. export function recommendVerifiedClose( request: VerifiedCloseRequest, - readVerifierReceipt: (ref: string) => VerifierScopeReceipt | undefined, + reader: VerifiedCloseReader, ): VerifiedCloseRecommendation { - const receipt = readVerifierReceipt(request.receipt_ref); + const receipt = hasReference(request.receipt_ref) ? reader.readReceipt(request.receipt_ref) : undefined; const expected = request.identity; const observed = receipt?.identity; if (!receipt || !observed @@ -114,9 +125,15 @@ export function recommendVerifiedClose( return { action: "KeepRaw" }; } if (receipt.verdict === "failed") { - return { action: "KeepRaw", counterexample_ref: receipt.counterexample_ref }; + if (hasReference(receipt.counterexample_ref) && reader.canReadEvidence(receipt.counterexample_ref) === true) { + return { action: "KeepRaw", counterexample_ref: receipt.counterexample_ref }; + } + return { action: "KeepRaw" }; } - if (receipt.verdict !== "passed" || request.open_obligations !== false || request.overlap !== "low") { + if (receipt.verdict !== "passed" || request.open_obligations !== false || request.overlap !== "low" + || ![receipt.oracle_evidence_ref, receipt.source_ref, receipt.summary_ref].every( + ref => hasReference(ref) && reader.canReadEvidence(ref) === true + )) { return { action: "KeepRaw" }; } return { diff --git a/tests/control_plane_ts/verifier_hook_contract.test.ts b/tests/control_plane_ts/verifier_hook_contract.test.ts index 9c4a7e6075..2eb0f97066 100644 --- a/tests/control_plane_ts/verifier_hook_contract.test.ts +++ b/tests/control_plane_ts/verifier_hook_contract.test.ts @@ -1,9 +1,12 @@ import { strict as assert } from "node:assert"; import test from "node:test"; +import {createHash} from "node:crypto"; import { - negotiateVerifierHooks, recommendVerifiedClose, type VerifiedCloseRequest, + negotiateVerifierHooks, recommendVerifiedClose, type VerifiedCloseReader, + type VerifiedCloseRequest, type VerifierHookEvent, type VerifierScopeReceipt, } from "../../loopx/control_plane/turn_driver/verifier_hook_contract.ts"; +import {capturedContextSelection} from "../../loopx/control_plane/quota/context_selection.ts"; const l1 = { session_lineage: true, boundary_context: true }; const l2 = { ...l1, milestone_observation: true, isolated_subscope: true, verified_return: true }; @@ -37,11 +40,20 @@ const source = { source_ref: "capture:raw-child", falsification_refs: ["finding:invalid-shortcut"], }; +const passed = { ...source, verdict: "passed", summary_ref: "capture:child-receipt" } as const; +const readable = new Set([source.oracle_evidence_ref, source.source_ref, passed.summary_ref, "oracle:counterexample"]); +function authority(receipt?: VerifierScopeReceipt): VerifiedCloseReader { + return { + readReceipt(ref) { + assert.equal(ref, request.receipt_ref); + return receipt; + }, + canReadEvidence: ref => readable.has(ref), + }; +} + test("verified return resolves the named oracle receipt and stages the exact source reference", () => { - const result = recommendVerifiedClose(request, ref => { - assert.equal(ref, "receipt:21"); - return { ...source, verdict: "passed", summary_ref: "capture:child-receipt" }; - }); + const result = recommendVerifiedClose(request, authority(passed)); assert.deepEqual(result, { action: "FoldToReceipt", receipt_ref: "receipt:21", source_ref: "capture:raw-child", summary_ref: "capture:child-receipt", @@ -49,25 +61,64 @@ test("verified return resolves the named oracle receipt and stages the exact sou }); test("open, overlapping, unknown and mismatched work stays raw", () => { - const passed = { ...source, verdict: "passed", summary_ref: "capture:child-receipt" } as const; for (const variant of [ { ...request, overlap: "high" as const }, { ...request, overlap: "unknown" as const }, { ...request, open_obligations: true }, ]) { - assert.deepEqual(recommendVerifiedClose(variant, () => passed), { action: "KeepRaw" }); + assert.deepEqual(recommendVerifiedClose(variant, authority(passed)), { action: "KeepRaw" }); } const missingObligations = { ...request, open_obligations: undefined } as unknown as VerifiedCloseRequest; - assert.deepEqual(recommendVerifiedClose(missingObligations, () => passed), { action: "KeepRaw" }); + assert.deepEqual(recommendVerifiedClose(missingObligations, authority(passed)), { action: "KeepRaw" }); for (const key of Object.keys(identity) as (keyof typeof identity)[]) { const mismatch = { ...identity, [key]: "different" }; - assert.deepEqual(recommendVerifiedClose(request, () => ({ ...passed, identity: mismatch })), + assert.deepEqual(recommendVerifiedClose(request, authority({ ...passed, identity: mismatch })), { action: "KeepRaw" }); } - assert.deepEqual(recommendVerifiedClose(request, () => undefined), { action: "KeepRaw" }); - assert.deepEqual(recommendVerifiedClose(request, () => ({ ...source, verdict: "unknown" })), + assert.deepEqual(recommendVerifiedClose(request, authority()), { action: "KeepRaw" }); + assert.deepEqual(recommendVerifiedClose(request, authority({ ...source, verdict: "unknown" })), { action: "KeepRaw" }); - assert.deepEqual(recommendVerifiedClose(request, () => ({ + assert.deepEqual(recommendVerifiedClose(request, authority({ ...source, verdict: "failed", counterexample_ref: "oracle:counterexample", })), { action: "KeepRaw", counterexample_ref: "oracle:counterexample" }); }); + +test("the verifier, raw source and compact result must each remain readable", () => { + for (const field of ["oracle_evidence_ref", "source_ref", "summary_ref"] as const) { + for (const ref of ["", " ", "capture:unavailable"]) { + const result = recommendVerifiedClose(request, authority({ ...passed, [field]: ref })); + assert.deepEqual(result, { action: "KeepRaw" }, field); + } + } + assert.deepEqual(recommendVerifiedClose({ ...request, receipt_ref: "" }, authority(passed)), + { action: "KeepRaw" }); + assert.deepEqual(recommendVerifiedClose(request, authority({ + ...source, verdict: "failed", counterexample_ref: "capture:unavailable", + })), { action: "KeepRaw" }); +}); + +test("startup and recovery use the same captured C1 Goal boundary", () => { + const context = { goal_boundary: { + rule: "stay_in_scope_or_stop", write_scope: ["candidate"], stop_condition: "Stop before publishing.", + } }; + const captureSha256 = createHash("sha256").update(JSON.stringify(context)).digest("hex"); + const boundary = { capture_sha256: captureSha256, pointer: "/goal_boundary" } as const; + const start: Extract = { + boundary: "start", goal_id: "goal", todo_id: "todo", session_ref: "session", + epoch_ref: "before-compact", + view: { + objective: "Verify the selected delivery.", acceptance_refs: ["acceptance:1"], + goal_boundary_ref: boundary, verifier: { oracle_ref: "oracle:1", verifier_version: "v1" }, + falsification_refs: [], + }, + }; + const recovery: typeof start = { ...start, epoch_ref: "after-compact" }; + for (const event of [start, recovery]) { + const ref = event.view.goal_boundary_ref; + assert.equal(ref.capture_sha256, captureSha256); + const read = capturedContextSelection({context, select: [ref.pointer]}); + assert.deepEqual(read.selections, [{pointer: "/goal_boundary", path: ["goal_boundary"]}]); + } + assert.throws(() => capturedContextSelection({context: {}, select: [boundary.pointer]}), + /pointer does not exist/); +}); From 1bf996ef9ad1b4b614b2a5b4201acdc5b8e90fe9 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:01:56 +0800 Subject: [PATCH 3/8] Require role- and scope-bound verifier evidence Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/architecture/rfcs/STATUS.md | 3 +- docs/architecture/rfcs/STATUS.zh-CN.md | 3 +- .../rfcs/verifier-hook-co-design-v0.md | 7 ++- .../rfcs/verifier-hook-co-design-v0.zh-CN.md | 7 ++- .../turn_driver/verifier_hook_contract.ts | 52 +++++++++++++----- .../verifier_hook_contract.test.ts | 55 +++++++++++++++++-- 6 files changed, 100 insertions(+), 27 deletions(-) diff --git a/docs/architecture/rfcs/STATUS.md b/docs/architecture/rfcs/STATUS.md index 86b76ad7bc..7035830ba3 100644 --- a/docs/architecture/rfcs/STATUS.md +++ b/docs/architecture/rfcs/STATUS.md @@ -18,7 +18,7 @@ appendix may keep dated history, but no dated log heading may precede it. [中文版](STATUS.zh-CN.md) is the semantic mirror of this file. -## Accepted (54) +## Accepted (55) | RFC | Header status | Supersedes / closes | Ledger | | --- | --- | --- | --- | @@ -76,6 +76,7 @@ appendix may keep dated history, but no dated log heading may precede it. | [RFC: Single-Owner Local Daemon (v0)](single-owner-local-daemon-v0.md) | Accepted | none | — | | [RFC: Joint Target, Yardstick and Stride Decisions (v0)](target-yardstick-stride-decisions-v0.md) | Accepted | none | — | | [RFC: TypeScript Control-Plane Migration Direction v0](typescript-control-plane-migration-v0.md) | Accepted | none | [27 entries](ledger/typescript-control-plane-migration-v0/) | +| [RFC: Verifier Hook Co-Design (v0)](verifier-hook-co-design-v0.md) | Accepted | none | — | ## Superseded (1) diff --git a/docs/architecture/rfcs/STATUS.zh-CN.md b/docs/architecture/rfcs/STATUS.zh-CN.md index f519f7e11c..1fc785ff0c 100644 --- a/docs/architecture/rfcs/STATUS.zh-CN.md +++ b/docs/architecture/rfcs/STATUS.zh-CN.md @@ -15,7 +15,7 @@ [English](STATUS.md) 与本文互为语义镜像。 -## 已接受 (54) +## 已接受 (55) | RFC | 头部状态 | 替代 / 关闭 | Ledger | | --- | --- | --- | --- | @@ -73,6 +73,7 @@ | [RFC: Single-Owner Local Daemon (v0)](single-owner-local-daemon-v0.md) | 已接受 | none | — | | [RFC:Target、Yardstick 与 Stride 联合决策(v0)](target-yardstick-stride-decisions-v0.zh-CN.md) | 已接受 | none | — | | [RFC:LoopX 控制面 TypeScript 渐进迁移方向 v0](typescript-control-plane-migration-v0.zh-CN.md) | 已接受 | 无 | [27 条](ledger/typescript-control-plane-migration-v0/) | +| [RFC:面向独立验证的 Hook 协同契约(v0)](verifier-hook-co-design-v0.zh-CN.md) | 已接受 | 无 | — | ## 已被替代 (1) diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.md index 7d137d729e..a7fe1bb5c1 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.md @@ -1,9 +1,10 @@ # RFC: Verifier Hook Co-Design (v0) -- **RFC status:** Proposed +- **RFC status:** Accepted (upon merge) +- **Supersedes / closes:** none - **Delivery maturity:** TypeScript contract. Host adapters and outcome qualification are pending. - **Related contracts:** [Controller and executor](controller-executor-unified-contract-v0.md), [History working sets](history-working-set-context-policy-v0.md), [Target, Yardstick and Stride](target-yardstick-stride-decisions-v0.md), [Capability portfolio](goal-scoped-capability-portfolio-v0.md) -- **Language mirror:** [中文版](verifier-hook-co-design-v0.zh-CN.md) +- **Language mirror:** [中文版 — semantic mirror](verifier-hook-co-design-v0.zh-CN.md) ## 1. Authority and solver view @@ -40,7 +41,7 @@ Official Codex and DSH are complementary reference adapters. Use official Codex 1. Branch from a known session and parent epoch using a public host or controller operation. Isolate the candidate workspace. Conversation branching grants no new write lease, verifier authority, credentials or cache guarantee. 2. Capture the exact candidate for the independent Oracle. Its immutable receipt binds Goal, Todo, parent epoch, child scope, `candidate_sha` and `verifier_version`. It identifies available fast and slow readings, verdict, falsified hypotheses and original observations or transcript. Matching failure carries a reproducible counterexample. Missing readings stay unknown. -3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. The authoritative reader must resolve the Oracle evidence, original source and compact result. An empty, mismatched or unreadable reference keeps `KeepRaw`. Append its compact evidence-linked result at a supported parent boundary. Preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return a matching counterexample when available. +3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with nonblank scope identifiers, no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. The authoritative reader resolves the Oracle evidence, original source and compact result with their recorded roles and scope. Each binding must match the requested reference, its role and the exact receipt identity. An empty, mismatched or unreadable reference keeps `KeepRaw`. Append its compact evidence-linked result at a supported parent boundary. Preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return an available counterexample whose role and scope match. Classify overlap from the next work's evidence dependencies. High overlap means the next probe still needs intermediate candidate state, unresolved counterexamples or the raw comparison history. Low overlap means the next scope can act from the verified result and its bounded evidence references. Treat an unbound next step or an incomplete dependency read as unknown. Apply the existing reset break-even against the saved context bytes, cold prefill and any expected recovery reads. diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md index 2f42981cf0..f52697a314 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md @@ -1,9 +1,10 @@ # RFC:面向独立验证的 Hook 协同契约(v0) -- **RFC 状态:** Proposed +- **RFC 状态:** Accepted (upon merge) +- **替代 / 关闭:** 无 - **交付成熟度:** TypeScript 契约。宿主适配与成果验收待验证。 - **关联契约:** [控制器与执行器](controller-executor-unified-contract-v0.zh-CN.md)、[历史工作集](history-working-set-context-policy-v0.zh-CN.md)、[Target、Yardstick 与 Stride](target-yardstick-stride-decisions-v0.zh-CN.md)、[能力组合](goal-scoped-capability-portfolio-v0.zh-CN.md) -- **语言镜像:** [English](verifier-hook-co-design-v0.md) +- **语言镜像:** [English(语义镜像)](verifier-hook-co-design-v0.md) ## 1. 权限与求解视图 @@ -40,7 +41,7 @@ Goal Verifier Profile 绑定外部权威验证器(Oracle)的版本,可引 1. 以公开宿主或控制器操作,从已识别会话及父纪元派生分支,隔离候选工作区。复制会话不授予写租约、验证权限或凭据,也不证明缓存命中。 2. 捕获确切候选交给独立 Oracle。其不可变回执绑定 Goal、Todo、父纪元、子作用域、`candidate_sha` 和 `verifier_version`,记录可用快慢尺读数、裁决及证伪条目,包含原始观测或轨迹引用。身份匹配的失败回执提供可复现反例,缺失读数保持未知。 -3. 通过受信任原验证器解析回执。只有身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。权威读取方须能读回 Oracle 证据、原始来源和摘要。任一引用为空、错绑或无法读取时维持 `KeepRaw`。在受支持的父会话边界追加精简证据,原件可独立重读。缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有身份匹配的反例则回传。 +3. 通过受信任原验证器解析回执。作用域标识都非空、回执身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。权威读取方为 Oracle 证据、原始来源和摘要返回各自登记的角色与作用域。每项都须匹配所请求的引用、对应的角色和确切回执身份。任一引用为空、错绑或无法读取时维持 `KeepRaw`。在受支持的父会话边界追加精简证据,原件可独立重读。缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有角色和作用域都匹配的反例则回传。 按下一步工作的证据依赖判断重叠。下一探针仍需中间候选状态、未决反例或原始比较历史时为高重叠。下一作用域凭已核验结果及有界证据引用即可推进时为低重叠。下一步未绑定或依赖未读全时保持未知。结合节省的上下文字节、冷前缀重建和预期恢复读取,沿既有策略判断重置能否回本。 diff --git a/loopx/control_plane/turn_driver/verifier_hook_contract.ts b/loopx/control_plane/turn_driver/verifier_hook_contract.ts index 855993f445..280c074cb1 100644 --- a/loopx/control_plane/turn_driver/verifier_hook_contract.ts +++ b/loopx/control_plane/turn_driver/verifier_hook_contract.ts @@ -98,42 +98,64 @@ export type VerifiedCloseRecommendation = | { action: "KeepRaw"; counterexample_ref?: string } | { action: "FoldToReceipt"; receipt_ref: string; source_ref: string; summary_ref: string }; +export type VerifiedScopeEvidence = Readonly<{ + ref: string; + role: "oracle_evidence" | "source" | "summary" | "counterexample"; + identity: VerifiedScopeIdentity; +}>; + export type VerifiedCloseReader = Readonly<{ readReceipt: (ref: string) => VerifierScopeReceipt | undefined; - canReadEvidence: (ref: string) => boolean; + readEvidence: (ref: string) => VerifiedScopeEvidence | undefined; }>; +const scopeIdentityFields = [ + "goal_id", "todo_id", "parent_epoch_ref", "child_scope_ref", "candidate_sha", "verifier_version", +] as const; + function hasReference(ref: string): boolean { return typeof ref === "string" && ref.trim().length > 0; } -// The adapter binds both reads to their authoritative stores and current scope. -// It reports absent, inaccessible or mismatched evidence as unreadable. +function matchesScope(expected: VerifiedScopeIdentity, observed?: VerifiedScopeIdentity): boolean { + return observed != null && scopeIdentityFields.every(field => observed[field] === expected[field]); +} + +function matchesEvidence( + reader: VerifiedCloseReader, + identity: VerifiedScopeIdentity, + ref: string, + role: VerifiedScopeEvidence["role"], +): boolean { + const evidence = hasReference(ref) ? reader.readEvidence(ref) : undefined; + return evidence != null && evidence.ref === ref && evidence.role === role && matchesScope(identity, evidence.identity); +} + +// The adapter resolves receipts and evidence from their independent stores. +// Evidence describes its recorded role and scope and is absent when unreadable. export function recommendVerifiedClose( request: VerifiedCloseRequest, reader: VerifiedCloseReader, ): VerifiedCloseRecommendation { - const receipt = hasReference(request.receipt_ref) ? reader.readReceipt(request.receipt_ref) : undefined; const expected = request.identity; - const observed = receipt?.identity; - if (!receipt || !observed - || observed.goal_id !== expected.goal_id || observed.todo_id !== expected.todo_id - || observed.parent_epoch_ref !== expected.parent_epoch_ref - || observed.child_scope_ref !== expected.child_scope_ref - || observed.candidate_sha !== expected.candidate_sha - || observed.verifier_version !== expected.verifier_version) { + if (!expected || !scopeIdentityFields.every(field => hasReference(expected[field])) + || !hasReference(request.receipt_ref)) { + return { action: "KeepRaw" }; + } + const receipt = reader.readReceipt(request.receipt_ref); + if (!receipt || !matchesScope(expected, receipt.identity)) { return { action: "KeepRaw" }; } if (receipt.verdict === "failed") { - if (hasReference(receipt.counterexample_ref) && reader.canReadEvidence(receipt.counterexample_ref) === true) { + if (matchesEvidence(reader, expected, receipt.counterexample_ref, "counterexample")) { return { action: "KeepRaw", counterexample_ref: receipt.counterexample_ref }; } return { action: "KeepRaw" }; } if (receipt.verdict !== "passed" || request.open_obligations !== false || request.overlap !== "low" - || ![receipt.oracle_evidence_ref, receipt.source_ref, receipt.summary_ref].every( - ref => hasReference(ref) && reader.canReadEvidence(ref) === true - )) { + || !matchesEvidence(reader, expected, receipt.oracle_evidence_ref, "oracle_evidence") + || !matchesEvidence(reader, expected, receipt.source_ref, "source") + || !matchesEvidence(reader, expected, receipt.summary_ref, "summary")) { return { action: "KeepRaw" }; } return { diff --git a/tests/control_plane_ts/verifier_hook_contract.test.ts b/tests/control_plane_ts/verifier_hook_contract.test.ts index 2eb0f97066..c76274e08d 100644 --- a/tests/control_plane_ts/verifier_hook_contract.test.ts +++ b/tests/control_plane_ts/verifier_hook_contract.test.ts @@ -4,7 +4,7 @@ import {createHash} from "node:crypto"; import { negotiateVerifierHooks, recommendVerifiedClose, type VerifiedCloseReader, - type VerifiedCloseRequest, type VerifierHookEvent, type VerifierScopeReceipt, + type VerifiedCloseRequest, type VerifiedScopeEvidence, type VerifierHookEvent, type VerifierScopeReceipt, } from "../../loopx/control_plane/turn_driver/verifier_hook_contract.ts"; import {capturedContextSelection} from "../../loopx/control_plane/quota/context_selection.ts"; @@ -41,14 +41,22 @@ const source = { }; const passed = { ...source, verdict: "passed", summary_ref: "capture:child-receipt" } as const; -const readable = new Set([source.oracle_evidence_ref, source.source_ref, passed.summary_ref, "oracle:counterexample"]); -function authority(receipt?: VerifierScopeReceipt): VerifiedCloseReader { +const evidence = new Map([ + [source.oracle_evidence_ref, { ref: source.oracle_evidence_ref, role: "oracle_evidence", identity }], + [source.source_ref, { ref: source.source_ref, role: "source", identity }], + [passed.summary_ref, { ref: passed.summary_ref, role: "summary", identity }], + ["oracle:counterexample", { ref: "oracle:counterexample", role: "counterexample", identity }], +]); +function authority( + receipt?: VerifierScopeReceipt, + readEvidence: VerifiedCloseReader["readEvidence"] = ref => evidence.get(ref), +): VerifiedCloseReader { return { readReceipt(ref) { assert.equal(ref, request.receipt_ref); return receipt; }, - canReadEvidence: ref => readable.has(ref), + readEvidence, }; } @@ -97,6 +105,45 @@ test("the verifier, raw source and compact result must each remain readable", () })), { action: "KeepRaw" }); }); +test("readable evidence must match the recorded role, reference and exact work scope", () => { + for (const receipt of [ + { ...passed, source_ref: passed.summary_ref, summary_ref: passed.source_ref }, + { ...passed, oracle_evidence_ref: passed.summary_ref }, + { ...passed, source_ref: passed.oracle_evidence_ref }, + ]) { + assert.deepEqual(recommendVerifiedClose(request, authority(receipt)), { action: "KeepRaw" }); + } + for (const ref of [passed.oracle_evidence_ref, passed.source_ref, passed.summary_ref]) { + for (const field of Object.keys(identity) as (keyof typeof identity)[]) { + const scopedReader = (key: string) => { + const record = evidence.get(key); + return record && key === ref + ? { ...record, identity: { ...identity, [field]: "another-scope" } } + : record; + }; + assert.deepEqual(recommendVerifiedClose(request, authority(passed, scopedReader)), { action: "KeepRaw" }); + } + } + assert.deepEqual(recommendVerifiedClose(request, authority(passed, ref => { + const record = evidence.get(ref); + return record && ref === passed.source_ref ? { ...record, ref: "another-source" } : record; + })), { action: "KeepRaw" }); + assert.deepEqual(recommendVerifiedClose(request, authority({ + ...source, verdict: "failed", counterexample_ref: passed.summary_ref, + })), { action: "KeepRaw" }); +}); + +test("matching blank identity fields do not authorize a receipt read", () => { + const reader = { + readReceipt: () => assert.fail("invalid identity reached receipt authority"), + readEvidence: () => assert.fail("invalid identity reached evidence authority"), + }; + for (const field of Object.keys(identity) as (keyof typeof identity)[]) { + const invalid = { ...identity, [field]: " " }; + assert.deepEqual(recommendVerifiedClose({ ...request, identity: invalid }, reader), { action: "KeepRaw" }); + } +}); + test("startup and recovery use the same captured C1 Goal boundary", () => { const context = { goal_boundary: { rule: "stay_in_scope_or_stop", write_scope: ["candidate"], stop_condition: "Stop before publishing.", From 185f0999defd83f5b8375206d4fd8993dd0256e7 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:36:19 +0800 Subject: [PATCH 4/8] Bind verified close to immutable candidate digests Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../rfcs/verifier-hook-co-design-v0.md | 2 +- .../rfcs/verifier-hook-co-design-v0.zh-CN.md | 2 +- .../turn_driver/verifier_hook_contract.ts | 3 ++ .../verifier_hook_contract.test.ts | 29 +++++++++++++++++-- 4 files changed, 32 insertions(+), 4 deletions(-) diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.md index a7fe1bb5c1..3f3d46bf81 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.md @@ -40,7 +40,7 @@ Official Codex and DSH are complementary reference adapters. Use official Codex ## 3. VerifiedClose 1. Branch from a known session and parent epoch using a public host or controller operation. Isolate the candidate workspace. Conversation branching grants no new write lease, verifier authority, credentials or cache guarantee. -2. Capture the exact candidate for the independent Oracle. Its immutable receipt binds Goal, Todo, parent epoch, child scope, `candidate_sha` and `verifier_version`. It identifies available fast and slow readings, verdict, falsified hypotheses and original observations or transcript. Matching failure carries a reproducible counterexample. Missing readings stay unknown. +2. Capture the exact candidate for the independent Oracle. Its immutable receipt binds Goal, Todo, parent epoch, child scope, `candidate_sha` and `verifier_version`. Use the canonical `sha256:<64 lowercase hexadecimal digits>` digest of the candidate submitted to the Oracle. The recommendation checks the digest before reading any receipt. Branch names, tags and other identifier formats keep the raw scope. The receipt identifies available fast and slow readings, verdict, falsified hypotheses and original observations or transcript. Matching failure carries a reproducible counterexample. Missing readings stay unknown. 3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with nonblank scope identifiers, no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. The authoritative reader resolves the Oracle evidence, original source and compact result with their recorded roles and scope. Each binding must match the requested reference, its role and the exact receipt identity. An empty, mismatched or unreadable reference keeps `KeepRaw`. Append its compact evidence-linked result at a supported parent boundary. Preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return an available counterexample whose role and scope match. Classify overlap from the next work's evidence dependencies. High overlap means the next probe still needs intermediate candidate state, unresolved counterexamples or the raw comparison history. Low overlap means the next scope can act from the verified result and its bounded evidence references. Treat an unbound next step or an incomplete dependency read as unknown. Apply the existing reset break-even against the saved context bytes, cold prefill and any expected recovery reads. diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md index f52697a314..11b7262146 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md @@ -40,7 +40,7 @@ Goal Verifier Profile 绑定外部权威验证器(Oracle)的版本,可引 ## 3. VerifiedClose 1. 以公开宿主或控制器操作,从已识别会话及父纪元派生分支,隔离候选工作区。复制会话不授予写租约、验证权限或凭据,也不证明缓存命中。 -2. 捕获确切候选交给独立 Oracle。其不可变回执绑定 Goal、Todo、父纪元、子作用域、`candidate_sha` 和 `verifier_version`,记录可用快慢尺读数、裁决及证伪条目,包含原始观测或轨迹引用。身份匹配的失败回执提供可复现反例,缺失读数保持未知。 +2. 捕获确切候选交给独立 Oracle。其不可变回执绑定 Goal、Todo、父纪元、子作用域、`candidate_sha` 和 `verifier_version`。`candidate_sha` 使用提交给 Oracle 的候选内容摘要,格式为 `sha256:<64 位小写十六进制字符>`。读取回执前先检查摘要格式。分支、标签和其他格式都保留原始作用域。回执记录可用快慢尺读数、裁决及证伪条目,包含原始观测或轨迹引用。身份匹配的失败回执提供可复现反例,缺失读数保持未知。 3. 通过受信任原验证器解析回执。作用域标识都非空、回执身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。权威读取方为 Oracle 证据、原始来源和摘要返回各自登记的角色与作用域。每项都须匹配所请求的引用、对应的角色和确切回执身份。任一引用为空、错绑或无法读取时维持 `KeepRaw`。在受支持的父会话边界追加精简证据,原件可独立重读。缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有角色和作用域都匹配的反例则回传。 按下一步工作的证据依赖判断重叠。下一探针仍需中间候选状态、未决反例或原始比较历史时为高重叠。下一作用域凭已核验结果及有界证据引用即可推进时为低重叠。下一步未绑定或依赖未读全时保持未知。结合节省的上下文字节、冷前缀重建和预期恢复读取,沿既有策略判断重置能否回本。 diff --git a/loopx/control_plane/turn_driver/verifier_hook_contract.ts b/loopx/control_plane/turn_driver/verifier_hook_contract.ts index 280c074cb1..b78cfb89ba 100644 --- a/loopx/control_plane/turn_driver/verifier_hook_contract.ts +++ b/loopx/control_plane/turn_driver/verifier_hook_contract.ts @@ -1,5 +1,6 @@ // Host-neutral contract for the proposed verifier Hook adapter. The C1, // working-set and capability-portfolio owners still admit every effect. +import { ENVELOPED_SHA256_PATTERN } from "../content_digest.ts"; import type { QuotaGoalBoundaryReference } from "../quota/turn_envelope.ts"; import type { WorkYardstickProfile } from "../work_items/yardstick_decision.ts"; @@ -71,6 +72,7 @@ export type VerifiedScopeIdentity = Readonly<{ todo_id: string; parent_epoch_ref: string; child_scope_ref: string; + /** Canonical SHA-256 digest of the candidate submitted to the verifier. */ candidate_sha: string; verifier_version: string; }>; @@ -139,6 +141,7 @@ export function recommendVerifiedClose( ): VerifiedCloseRecommendation { const expected = request.identity; if (!expected || !scopeIdentityFields.every(field => hasReference(expected[field])) + || !ENVELOPED_SHA256_PATTERN.test(expected.candidate_sha) || !hasReference(request.receipt_ref)) { return { action: "KeepRaw" }; } diff --git a/tests/control_plane_ts/verifier_hook_contract.test.ts b/tests/control_plane_ts/verifier_hook_contract.test.ts index c76274e08d..bcf1336915 100644 --- a/tests/control_plane_ts/verifier_hook_contract.test.ts +++ b/tests/control_plane_ts/verifier_hook_contract.test.ts @@ -30,7 +30,7 @@ test("enabled negotiation uses observed capabilities and never infers pre-tool o const identity = { goal_id: "goal", todo_id: "todo", parent_epoch_ref: "epoch:9", child_scope_ref: "scope:3", - candidate_sha: "candidate:26", verifier_version: "verifier:4", + candidate_sha: "sha256:" + "a".repeat(64), verifier_version: "verifier:4", }; const request: VerifiedCloseRequest = { identity, receipt_ref: "receipt:21", overlap: "low", open_obligations: false, @@ -68,6 +68,30 @@ test("verified return resolves the named oracle receipt and stages the exact sou }); }); +test("matching candidate identifiers must still identify immutable content", () => { + for (const candidate_sha of [ + "main", "candidate:26", "a".repeat(64), + "sha256:" + "a".repeat(63), "sha256:" + "g".repeat(64), "sha256:" + "A".repeat(64), + ]) { + const invalid = { ...identity, candidate_sha }; + const reads: string[] = []; + const reader = { + readReceipt(ref: string): VerifierScopeReceipt { + reads.push(ref); + return { ...passed, identity: invalid }; + }, + readEvidence(ref: string): VerifiedScopeEvidence | undefined { + reads.push(ref); + const record = evidence.get(ref); + return record && { ...record, identity: invalid }; + }, + }; + assert.deepEqual(recommendVerifiedClose({ ...request, identity: invalid }, reader), + { action: "KeepRaw" }, candidate_sha); + assert.deepEqual(reads, [], candidate_sha); + } +}); + test("open, overlapping, unknown and mismatched work stays raw", () => { for (const variant of [ { ...request, overlap: "high" as const }, @@ -79,7 +103,8 @@ test("open, overlapping, unknown and mismatched work stays raw", () => { const missingObligations = { ...request, open_obligations: undefined } as unknown as VerifiedCloseRequest; assert.deepEqual(recommendVerifiedClose(missingObligations, authority(passed)), { action: "KeepRaw" }); for (const key of Object.keys(identity) as (keyof typeof identity)[]) { - const mismatch = { ...identity, [key]: "different" }; + const different = key === "candidate_sha" ? "sha256:" + "b".repeat(64) : "different"; + const mismatch = { ...identity, [key]: different }; assert.deepEqual(recommendVerifiedClose(request, authority({ ...passed, identity: mismatch })), { action: "KeepRaw" }); } From ed4e62cdbd2f3590d895e24aa33ff46ce51fa967 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:09:49 +0800 Subject: [PATCH 5/8] Register the canonical digest consumers in the architecture test Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- tests/control_plane_ts/content_digest_single_owner.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/control_plane_ts/content_digest_single_owner.test.ts b/tests/control_plane_ts/content_digest_single_owner.test.ts index a5880485ae..3ad1ff363b 100644 --- a/tests/control_plane_ts/content_digest_single_owner.test.ts +++ b/tests/control_plane_ts/content_digest_single_owner.test.ts @@ -180,6 +180,7 @@ const CANONICAL_CONSUMERS = [ "control_plane/todos/read_transport.ts", "control_plane/turn_driver/capability_context.ts", "control_plane/turn_driver/chat_turn_acceptance.ts", + "control_plane/turn_driver/verifier_hook_contract.ts", "control_plane/work_items/operation_agent_handoff.ts", "control_plane/work_items/goal_context_source.ts", "control_plane/work_items/interaction_contract.ts", From 93b57fbdc41ef0af2284e1be56f0e5e5781849dd Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:40:00 +0800 Subject: [PATCH 6/8] Keep verifier authority reads bounded to the contract fixture Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/architecture/rfcs/README.md | 4 + .../rfcs/verifier-hook-co-design-v0.md | 8 +- .../rfcs/verifier-hook-co-design-v0.zh-CN.md | 8 +- .../turn_driver/verifier_hook_contract.ts | 92 +------------------ .../content_digest_single_owner.test.ts | 1 - .../fixtures/verifier_hook_contract.ts | 88 ++++++++++++++++++ .../verifier_hook_contract.test.ts | 46 +++++++++- 7 files changed, 148 insertions(+), 99 deletions(-) create mode 100644 tests/control_plane_ts/fixtures/verifier_hook_contract.ts diff --git a/docs/architecture/rfcs/README.md b/docs/architecture/rfcs/README.md index 43c0bda41f..abd928013b 100644 --- a/docs/architecture/rfcs/README.md +++ b/docs/architecture/rfcs/README.md @@ -203,6 +203,10 @@ Paired diffs do not certify translation accuracy. qualification without changing defaults or launching experiments. - [Verifier Hook Co-Design v0](verifier-hook-co-design-v0.md) ([中文版](verifier-hook-co-design-v0.zh-CN.md)) + - **Delivery on `main`:** Bilingual RFC, TypeScript interface and executable contract fixture. + - **Current boundary:** The first live acceptance slice connects one verified child + return to the existing history working-set reader. It covers original receipt + readback, missing evidence, native recovery and exact C1 settlement replay. - [Recoverable History Working Sets and Context Policy Extensions v0](history-working-set-context-policy-v0.md) ([中文版](history-working-set-context-policy-v0.zh-CN.md)) - **Delivery on `main`:** Proposal only; tracking [#8450](https://github.com/loopx-project/loopx/issues/8450). diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.md index 3f3d46bf81..d601c0c5cf 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.md @@ -2,7 +2,7 @@ - **RFC status:** Accepted (upon merge) - **Supersedes / closes:** none -- **Delivery maturity:** TypeScript contract. Host adapters and outcome qualification are pending. +- **Delivery maturity:** TypeScript interface and executable contract fixture. History working-set integration and host qualification are pending. - **Related contracts:** [Controller and executor](controller-executor-unified-contract-v0.md), [History working sets](history-working-set-context-policy-v0.md), [Target, Yardstick and Stride](target-yardstick-stride-decisions-v0.md), [Capability portfolio](goal-scoped-capability-portfolio-v0.md) - **Language mirror:** [中文版 — semantic mirror](verifier-hook-co-design-v0.zh-CN.md) @@ -41,7 +41,7 @@ Official Codex and DSH are complementary reference adapters. Use official Codex 1. Branch from a known session and parent epoch using a public host or controller operation. Isolate the candidate workspace. Conversation branching grants no new write lease, verifier authority, credentials or cache guarantee. 2. Capture the exact candidate for the independent Oracle. Its immutable receipt binds Goal, Todo, parent epoch, child scope, `candidate_sha` and `verifier_version`. Use the canonical `sha256:<64 lowercase hexadecimal digits>` digest of the candidate submitted to the Oracle. The recommendation checks the digest before reading any receipt. Branch names, tags and other identifier formats keep the raw scope. The receipt identifies available fast and slow readings, verdict, falsified hypotheses and original observations or transcript. Matching failure carries a reproducible counterexample. Missing readings stay unknown. -3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with nonblank scope identifiers, no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. The authoritative reader resolves the Oracle evidence, original source and compact result with their recorded roles and scope. Each binding must match the requested reference, its role and the exact receipt identity. An empty, mismatched or unreadable reference keeps `KeepRaw`. Append its compact evidence-linked result at a supported parent boundary. Preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return an available counterexample whose role and scope match. +3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with nonblank scope identifiers, no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. The authoritative reader resolves the Oracle evidence, original source and compact result with their recorded roles and scope. Each binding must match the requested reference, its role and the exact receipt identity. An empty, mismatched or unreadable reference keeps `KeepRaw`. At the reader boundary, a filesystem lookup that reports a missing record becomes an unavailable read. Unexpected reader errors remain visible. Append the compact evidence-linked result at a supported parent boundary and preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return an available counterexample whose role and scope match. Classify overlap from the next work's evidence dependencies. High overlap means the next probe still needs intermediate candidate state, unresolved counterexamples or the raw comparison history. Low overlap means the next scope can act from the verified result and its bounded evidence references. Treat an unbound next step or an incomplete dependency read as unknown. Apply the existing reset break-even against the saved context bytes, cold prefill and any expected recovery reads. @@ -53,6 +53,6 @@ The solver may stage content-addressed yardsticks, diagnostics or verification r ## 5. Acceptance -- Contract checks cover feature off, L0/L1/L2 negotiation, explicit pre-tool opt-in, exact accepted return and refusal of foreign receipts. Run bilingual and diff-based premerge validation. -- Qualify the deployed host path on one original Goal/Todo, with an ordinary turn, missing or failed verification, compact or branch readback and exact settlement replay. Confirm the actual Hook outputs on that version and surface. Contract tests establish neither native adoption nor cache retention. +- The executable contract fixture covers feature off, L0/L1/L2 negotiation, explicit pre-tool opt-in, exact accepted return, refusal of foreign receipts and a real missing-file read. Run bilingual and diff-based premerge validation. +- For the first live slice, connect one verified child return to the existing history working-set reader. Cover an ordinary turn, missing or failed verification, compact or branch readback of the original receipt and exact C1 settlement replay on the same Goal/Todo. Confirm the actual Hook outputs on the installed host version and surface. - Compare with the same host's Stop-Hook baseline at matched model, task, access and budget. Record accepted outcomes, invalid completions, elapsed time, cached and uncached tokens, verifier calls, retries, storage and human intervention. Include high and low overlap. Keep cross-host results outside causal attribution for the same-host treatment. diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md index 11b7262146..1a51d56909 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md @@ -2,7 +2,7 @@ - **RFC 状态:** Accepted (upon merge) - **替代 / 关闭:** 无 -- **交付成熟度:** TypeScript 契约。宿主适配与成果验收待验证。 +- **交付成熟度:** TypeScript 接口及可执行契约验证样例。历史工作集接入和宿主资格待验证。 - **关联契约:** [控制器与执行器](controller-executor-unified-contract-v0.zh-CN.md)、[历史工作集](history-working-set-context-policy-v0.zh-CN.md)、[Target、Yardstick 与 Stride](target-yardstick-stride-decisions-v0.zh-CN.md)、[能力组合](goal-scoped-capability-portfolio-v0.zh-CN.md) - **语言镜像:** [English(语义镜像)](verifier-hook-co-design-v0.md) @@ -41,7 +41,7 @@ Goal Verifier Profile 绑定外部权威验证器(Oracle)的版本,可引 1. 以公开宿主或控制器操作,从已识别会话及父纪元派生分支,隔离候选工作区。复制会话不授予写租约、验证权限或凭据,也不证明缓存命中。 2. 捕获确切候选交给独立 Oracle。其不可变回执绑定 Goal、Todo、父纪元、子作用域、`candidate_sha` 和 `verifier_version`。`candidate_sha` 使用提交给 Oracle 的候选内容摘要,格式为 `sha256:<64 位小写十六进制字符>`。读取回执前先检查摘要格式。分支、标签和其他格式都保留原始作用域。回执记录可用快慢尺读数、裁决及证伪条目,包含原始观测或轨迹引用。身份匹配的失败回执提供可复现反例,缺失读数保持未知。 -3. 通过受信任原验证器解析回执。作用域标识都非空、回执身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。权威读取方为 Oracle 证据、原始来源和摘要返回各自登记的角色与作用域。每项都须匹配所请求的引用、对应的角色和确切回执身份。任一引用为空、错绑或无法读取时维持 `KeepRaw`。在受支持的父会话边界追加精简证据,原件可独立重读。缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有角色和作用域都匹配的反例则回传。 +3. 通过受信任原验证器解析回执。作用域标识都非空、回执身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。权威读取方为 Oracle 证据、原始来源和摘要返回各自登记的角色与作用域。每项都须匹配所请求的引用、对应的角色和确切回执身份。任一引用为空、错绑或无法读取时维持 `KeepRaw`。文件系统报告缺失记录时,读取边界将其视为不可用。意外读取错误保持可见。在受支持的父会话边界追加精简证据,并保留可独立重读的原件。回执缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有角色和作用域都匹配的反例则回传。 按下一步工作的证据依赖判断重叠。下一探针仍需中间候选状态、未决反例或原始比较历史时为高重叠。下一作用域凭已核验结果及有界证据引用即可推进时为低重叠。下一步未绑定或依赖未读全时保持未知。结合节省的上下文字节、冷前缀重建和预期恢复读取,沿既有策略判断重置能否回本。 @@ -53,6 +53,6 @@ Goal Verifier Profile 绑定外部权威验证器(Oracle)的版本,可引 ## 5. 验收 -- 契约检查覆盖功能关闭、L0/L1/L2 协商、显式前置扩展、确切已验回传及拒绝其他作用域的回执。运行双语和基于 diff 的 premerge 检查。 -- 宿主路径在同一原 Goal/Todo 上通过普通回合、验证失败或缺证、压缩或分支读回及确切结算重放。对实际版本及入口验证 Hook 输出。契约测试无法证明原生采用或缓存保持。 +- 可执行契约验证覆盖功能关闭、L0/L1/L2 协商、显式前置扩展、确切已验回传、拒绝其他作用域的回执及真实文件缺失。运行双语和基于 diff 的 premerge 检查。 +- 首个正式接入切片使用既有历史工作集读取方处理一次已验证的子工作回传。在同一 Goal/Todo 上覆盖普通回合、验证失败或缺证、压缩或分支后的原回执读回及确切 C1 结算重放。在实际安装的宿主版本和入口验证 Hook 输出。 - 匹配模型、任务、访问权限和预算,对照同宿主 Stop-Hook。记录验收成果、错误完成、耗时、缓存和未缓存 token、验证调用、重试、存储及人工介入。覆盖高低重叠工作。跨宿主结果不计入同宿主效果归因。 diff --git a/loopx/control_plane/turn_driver/verifier_hook_contract.ts b/loopx/control_plane/turn_driver/verifier_hook_contract.ts index b78cfb89ba..8e6b44bec9 100644 --- a/loopx/control_plane/turn_driver/verifier_hook_contract.ts +++ b/loopx/control_plane/turn_driver/verifier_hook_contract.ts @@ -1,6 +1,5 @@ // Host-neutral contract for the proposed verifier Hook adapter. The C1, // working-set and capability-portfolio owners still admit every effect. -import { ENVELOPED_SHA256_PATTERN } from "../content_digest.ts"; import type { QuotaGoalBoundaryReference } from "../quota/turn_envelope.ts"; import type { WorkYardstickProfile } from "../work_items/yardstick_decision.ts"; @@ -18,20 +17,10 @@ export type VerifierHookPolicy = Readonly<{ pre_tool_use?: boolean; }>; -export function negotiateVerifierHooks( - policy: VerifierHookPolicy, - capabilities: HarnessVerifierCapabilities = {}, -): { tier: "L0" | "L1" | "L2"; pre_tool_use: boolean } | null { - if (policy.enabled !== true) return null; - - const lineage = capabilities.session_lineage === true && capabilities.boundary_context === true; - const scoped = capabilities.milestone_observation === true - && capabilities.isolated_subscope === true && capabilities.verified_return === true; - return { - tier: lineage ? (scoped ? "L2" : "L1") : "L0", - pre_tool_use: policy.pre_tool_use === true && capabilities.pre_tool_use === true, - }; -} +export type VerifierHookNegotiation = Readonly<{ + tier: "L0" | "L1" | "L2"; + pre_tool_use: boolean; +}>; export type GoalVerifierProfile = Readonly<{ oracle_ref: string; @@ -106,79 +95,8 @@ export type VerifiedScopeEvidence = Readonly<{ identity: VerifiedScopeIdentity; }>; +// Readers return undefined for unavailable authority records. export type VerifiedCloseReader = Readonly<{ readReceipt: (ref: string) => VerifierScopeReceipt | undefined; readEvidence: (ref: string) => VerifiedScopeEvidence | undefined; }>; - -const scopeIdentityFields = [ - "goal_id", "todo_id", "parent_epoch_ref", "child_scope_ref", "candidate_sha", "verifier_version", -] as const; - -function hasReference(ref: string): boolean { - return typeof ref === "string" && ref.trim().length > 0; -} - -function matchesScope(expected: VerifiedScopeIdentity, observed?: VerifiedScopeIdentity): boolean { - return observed != null && scopeIdentityFields.every(field => observed[field] === expected[field]); -} - -function matchesEvidence( - reader: VerifiedCloseReader, - identity: VerifiedScopeIdentity, - ref: string, - role: VerifiedScopeEvidence["role"], -): boolean { - const evidence = hasReference(ref) ? reader.readEvidence(ref) : undefined; - return evidence != null && evidence.ref === ref && evidence.role === role && matchesScope(identity, evidence.identity); -} - -// The adapter resolves receipts and evidence from their independent stores. -// Evidence describes its recorded role and scope and is absent when unreadable. -export function recommendVerifiedClose( - request: VerifiedCloseRequest, - reader: VerifiedCloseReader, -): VerifiedCloseRecommendation { - const expected = request.identity; - if (!expected || !scopeIdentityFields.every(field => hasReference(expected[field])) - || !ENVELOPED_SHA256_PATTERN.test(expected.candidate_sha) - || !hasReference(request.receipt_ref)) { - return { action: "KeepRaw" }; - } - const receipt = reader.readReceipt(request.receipt_ref); - if (!receipt || !matchesScope(expected, receipt.identity)) { - return { action: "KeepRaw" }; - } - if (receipt.verdict === "failed") { - if (matchesEvidence(reader, expected, receipt.counterexample_ref, "counterexample")) { - return { action: "KeepRaw", counterexample_ref: receipt.counterexample_ref }; - } - return { action: "KeepRaw" }; - } - if (receipt.verdict !== "passed" || request.open_obligations !== false || request.overlap !== "low" - || !matchesEvidence(reader, expected, receipt.oracle_evidence_ref, "oracle_evidence") - || !matchesEvidence(reader, expected, receipt.source_ref, "source") - || !matchesEvidence(reader, expected, receipt.summary_ref, "summary")) { - return { action: "KeepRaw" }; - } - return { - action: "FoldToReceipt", - receipt_ref: request.receipt_ref, - source_ref: receipt.source_ref, - summary_ref: receipt.summary_ref, - }; -} - -export type DomainPluginCandidate = Readonly<{ - artifact_digest: string; - capability_ref: string; - kind: "yardstick" | "diagnostic_probe" | "verification_recipe"; -}>; - -// These observations index the existing portfolio and verifier owners. The -// solver can propose staging only. Activated versions are read from configuration. -export type DomainPluginTrial = - | { stage: "staging"; candidate: DomainPluginCandidate } - | { stage: "trial"; candidate: DomainPluginCandidate; trial_receipt_ref: string } - | { stage: "adopted"; candidate: DomainPluginCandidate; adoption_receipt_ref: string } - | { stage: "retired"; candidate: DomainPluginCandidate; retirement_receipt_ref: string }; diff --git a/tests/control_plane_ts/content_digest_single_owner.test.ts b/tests/control_plane_ts/content_digest_single_owner.test.ts index 3ad1ff363b..a5880485ae 100644 --- a/tests/control_plane_ts/content_digest_single_owner.test.ts +++ b/tests/control_plane_ts/content_digest_single_owner.test.ts @@ -180,7 +180,6 @@ const CANONICAL_CONSUMERS = [ "control_plane/todos/read_transport.ts", "control_plane/turn_driver/capability_context.ts", "control_plane/turn_driver/chat_turn_acceptance.ts", - "control_plane/turn_driver/verifier_hook_contract.ts", "control_plane/work_items/operation_agent_handoff.ts", "control_plane/work_items/goal_context_source.ts", "control_plane/work_items/interaction_contract.ts", diff --git a/tests/control_plane_ts/fixtures/verifier_hook_contract.ts b/tests/control_plane_ts/fixtures/verifier_hook_contract.ts new file mode 100644 index 0000000000..03470de430 --- /dev/null +++ b/tests/control_plane_ts/fixtures/verifier_hook_contract.ts @@ -0,0 +1,88 @@ +// Executable examples for the Verifier Hook contract before history-owner integration. +import { ENVELOPED_SHA256_PATTERN } from "../../../loopx/control_plane/content_digest.ts"; +import type { + HarnessVerifierCapabilities, VerifiedCloseReader, VerifiedCloseRecommendation, VerifiedCloseRequest, + VerifiedScopeEvidence, VerifiedScopeIdentity, VerifierHookNegotiation, VerifierHookPolicy, +} from "../../../loopx/control_plane/turn_driver/verifier_hook_contract.ts"; + +export function negotiateVerifierHooks( + policy: VerifierHookPolicy, + capabilities: HarnessVerifierCapabilities = {}, +): VerifierHookNegotiation | null { + if (policy.enabled !== true) return null; + + const lineage = capabilities.session_lineage === true && capabilities.boundary_context === true; + const scoped = capabilities.milestone_observation === true + && capabilities.isolated_subscope === true && capabilities.verified_return === true; + return { + tier: lineage ? (scoped ? "L2" : "L1") : "L0", + pre_tool_use: policy.pre_tool_use === true && capabilities.pre_tool_use === true, + }; +} + +const scopeIdentityFields = [ + "goal_id", "todo_id", "parent_epoch_ref", "child_scope_ref", "candidate_sha", "verifier_version", +] as const; + +function hasReference(ref: string): boolean { + return typeof ref === "string" && ref.trim().length > 0; +} + +function matchesScope(expected: VerifiedScopeIdentity, observed?: VerifiedScopeIdentity): boolean { + return observed != null && scopeIdentityFields.every(field => observed[field] === expected[field]); +} + +function readAvailable(read: () => T | undefined): T | undefined { + try { + return read(); + } catch (error) { + if (error instanceof Error && "code" in error && error.code === "ENOENT") return undefined; + throw error; + } +} + +function matchesEvidence( + reader: VerifiedCloseReader, + identity: VerifiedScopeIdentity, + ref: string, + role: VerifiedScopeEvidence["role"], +): boolean { + const evidence = hasReference(ref) ? readAvailable(() => reader.readEvidence(ref)) : undefined; + return evidence != null && evidence.ref === ref && evidence.role === role && matchesScope(identity, evidence.identity); +} + +// The adapter resolves receipts and evidence from their independent stores. +// Evidence describes its recorded role and scope and is absent when unreadable. +export function recommendVerifiedClose( + request: VerifiedCloseRequest, + reader: VerifiedCloseReader, +): VerifiedCloseRecommendation { + const expected = request.identity; + if (!expected || !scopeIdentityFields.every(field => hasReference(expected[field])) + || !ENVELOPED_SHA256_PATTERN.test(expected.candidate_sha) + || !hasReference(request.receipt_ref)) { + return { action: "KeepRaw" }; + } + const receipt = readAvailable(() => reader.readReceipt(request.receipt_ref)); + if (!receipt || !matchesScope(expected, receipt.identity)) { + return { action: "KeepRaw" }; + } + if (receipt.verdict === "failed") { + if (matchesEvidence(reader, expected, receipt.counterexample_ref, "counterexample")) { + return { action: "KeepRaw", counterexample_ref: receipt.counterexample_ref }; + } + return { action: "KeepRaw" }; + } + if (receipt.verdict !== "passed" || request.open_obligations !== false || request.overlap !== "low" + || !matchesEvidence(reader, expected, receipt.oracle_evidence_ref, "oracle_evidence") + || !matchesEvidence(reader, expected, receipt.source_ref, "source") + || !matchesEvidence(reader, expected, receipt.summary_ref, "summary")) { + return { action: "KeepRaw" }; + } + return { + action: "FoldToReceipt", + receipt_ref: request.receipt_ref, + source_ref: receipt.source_ref, + summary_ref: receipt.summary_ref, + }; +} diff --git a/tests/control_plane_ts/verifier_hook_contract.test.ts b/tests/control_plane_ts/verifier_hook_contract.test.ts index bcf1336915..de1fe167db 100644 --- a/tests/control_plane_ts/verifier_hook_contract.test.ts +++ b/tests/control_plane_ts/verifier_hook_contract.test.ts @@ -1,11 +1,14 @@ import { strict as assert } from "node:assert"; import test from "node:test"; import {createHash} from "node:crypto"; +import {mkdtempSync, readFileSync, rmSync} from "node:fs"; +import {tmpdir} from "node:os"; +import {join} from "node:path"; -import { - negotiateVerifierHooks, recommendVerifiedClose, type VerifiedCloseReader, - type VerifiedCloseRequest, type VerifiedScopeEvidence, type VerifierHookEvent, type VerifierScopeReceipt, +import type { + VerifiedCloseReader, VerifiedCloseRequest, VerifiedScopeEvidence, VerifierHookEvent, VerifierScopeReceipt, } from "../../loopx/control_plane/turn_driver/verifier_hook_contract.ts"; +import {negotiateVerifierHooks, recommendVerifiedClose} from "./fixtures/verifier_hook_contract.ts"; import {capturedContextSelection} from "../../loopx/control_plane/quota/context_selection.ts"; const l1 = { session_lineage: true, boundary_context: true }; @@ -158,6 +161,43 @@ test("readable evidence must match the recorded role, reference and exact work s })), { action: "KeepRaw" }); }); +test("files missing from the receipt or evidence reader preserve the raw child scope", async (t) => { + const directory = mkdtempSync(join(tmpdir(), "loopx-verifier-hook-")); + t.after(() => rmSync(directory, { recursive: true, force: true })); + const readMissingFile = (): never => { + readFileSync(join(directory, "unavailable.json"), "utf8"); + return assert.fail("the verifier fixture unexpectedly found an unavailable file"); + }; + + await t.test("a missing receipt short-circuits all evidence reads", () => { + assert.deepEqual(recommendVerifiedClose(request, { + readReceipt: readMissingFile, + readEvidence: () => assert.fail("evidence read after receipt disappeared"), + }), { action: "KeepRaw" }); + }); + await t.test("a missing required evidence file or counterexample retains the raw scope", () => { + for (const ref of [passed.oracle_evidence_ref, passed.source_ref, passed.summary_ref]) { + assert.deepEqual(recommendVerifiedClose(request, authority(passed, key => + key === ref ? readMissingFile() : evidence.get(key), + )), { action: "KeepRaw" }, ref); + } + const failed = { ...source, verdict: "failed", counterexample_ref: "oracle:counterexample" } as const; + assert.deepEqual(recommendVerifiedClose(request, authority(failed, readMissingFile)), { action: "KeepRaw" }); + }); +}); + +test("unexpected authority reader errors remain observable", () => { + const failure = new TypeError("invalid authority record"); + const fail = (): never => { throw failure; }; + const readers = [ + { readReceipt: fail, readEvidence: () => assert.fail("evidence read after unexpected failure") }, + authority(passed, fail), + ]; + for (const reader of readers) { + assert.throws(() => recommendVerifiedClose(request, reader), error => error === failure); + } +}); + test("matching blank identity fields do not authorize a receipt read", () => { const reader = { readReceipt: () => assert.fail("invalid identity reached receipt authority"), From 1a4253e8d8a63446330f5482ef96751c5cd97dc8 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:16:15 +0800 Subject: [PATCH 7/8] fix(verifier_hook): treat EACCES, EPERM, EISDIR, and ENOTDIR as unavailable -> KeepRaw Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../rfcs/verifier-hook-co-design-v0.md | 4 +- .../rfcs/verifier-hook-co-design-v0.zh-CN.md | 4 +- .../fixtures/verifier_hook_contract.ts | 11 +- .../verifier_hook_contract.test.ts | 120 +++++++++++++++--- 4 files changed, 119 insertions(+), 20 deletions(-) diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.md index d601c0c5cf..3e081015b8 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.md @@ -41,7 +41,7 @@ Official Codex and DSH are complementary reference adapters. Use official Codex 1. Branch from a known session and parent epoch using a public host or controller operation. Isolate the candidate workspace. Conversation branching grants no new write lease, verifier authority, credentials or cache guarantee. 2. Capture the exact candidate for the independent Oracle. Its immutable receipt binds Goal, Todo, parent epoch, child scope, `candidate_sha` and `verifier_version`. Use the canonical `sha256:<64 lowercase hexadecimal digits>` digest of the candidate submitted to the Oracle. The recommendation checks the digest before reading any receipt. Branch names, tags and other identifier formats keep the raw scope. The receipt identifies available fast and slow readings, verdict, falsified hypotheses and original observations or transcript. Matching failure carries a reproducible counterexample. Missing readings stay unknown. -3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with nonblank scope identifiers, no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. The authoritative reader resolves the Oracle evidence, original source and compact result with their recorded roles and scope. Each binding must match the requested reference, its role and the exact receipt identity. An empty, mismatched or unreadable reference keeps `KeepRaw`. At the reader boundary, a filesystem lookup that reports a missing record becomes an unavailable read. Unexpected reader errors remain visible. Append the compact evidence-linked result at a supported parent boundary and preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return an available counterexample whose role and scope match. +3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with nonblank scope identifiers, no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. The authoritative reader resolves the Oracle evidence, original source and compact result with their recorded roles and scope. Each binding must match the requested reference, its role and the exact receipt identity. An empty, mismatched or unreadable reference keeps `KeepRaw`. At the reader boundary, a filesystem lookup that reports a missing, permission-denied or wrong-kind record becomes an unavailable read. Parse and unexpected reader errors remain visible. Append the compact evidence-linked result at a supported parent boundary and preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return an available counterexample whose role and scope match. Classify overlap from the next work's evidence dependencies. High overlap means the next probe still needs intermediate candidate state, unresolved counterexamples or the raw comparison history. Low overlap means the next scope can act from the verified result and its bounded evidence references. Treat an unbound next step or an incomplete dependency read as unknown. Apply the existing reset break-even against the saved context bytes, cold prefill and any expected recovery reads. @@ -53,6 +53,6 @@ The solver may stage content-addressed yardsticks, diagnostics or verification r ## 5. Acceptance -- The executable contract fixture covers feature off, L0/L1/L2 negotiation, explicit pre-tool opt-in, exact accepted return, refusal of foreign receipts and a real missing-file read. Run bilingual and diff-based premerge validation. +- The executable contract fixture covers feature off, L0/L1/L2 negotiation, explicit pre-tool opt-in, exact accepted return, refusal of foreign receipts and real missing, permission-denied and wrong-kind file reads. Run bilingual and diff-based premerge validation. - For the first live slice, connect one verified child return to the existing history working-set reader. Cover an ordinary turn, missing or failed verification, compact or branch readback of the original receipt and exact C1 settlement replay on the same Goal/Todo. Confirm the actual Hook outputs on the installed host version and surface. - Compare with the same host's Stop-Hook baseline at matched model, task, access and budget. Record accepted outcomes, invalid completions, elapsed time, cached and uncached tokens, verifier calls, retries, storage and human intervention. Include high and low overlap. Keep cross-host results outside causal attribution for the same-host treatment. diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md index 1a51d56909..da349540c4 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md @@ -41,7 +41,7 @@ Goal Verifier Profile 绑定外部权威验证器(Oracle)的版本,可引 1. 以公开宿主或控制器操作,从已识别会话及父纪元派生分支,隔离候选工作区。复制会话不授予写租约、验证权限或凭据,也不证明缓存命中。 2. 捕获确切候选交给独立 Oracle。其不可变回执绑定 Goal、Todo、父纪元、子作用域、`candidate_sha` 和 `verifier_version`。`candidate_sha` 使用提交给 Oracle 的候选内容摘要,格式为 `sha256:<64 位小写十六进制字符>`。读取回执前先检查摘要格式。分支、标签和其他格式都保留原始作用域。回执记录可用快慢尺读数、裁决及证伪条目,包含原始观测或轨迹引用。身份匹配的失败回执提供可复现反例,缺失读数保持未知。 -3. 通过受信任原验证器解析回执。作用域标识都非空、回执身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。权威读取方为 Oracle 证据、原始来源和摘要返回各自登记的角色与作用域。每项都须匹配所请求的引用、对应的角色和确切回执身份。任一引用为空、错绑或无法读取时维持 `KeepRaw`。文件系统报告缺失记录时,读取边界将其视为不可用。意外读取错误保持可见。在受支持的父会话边界追加精简证据,并保留可独立重读的原件。回执缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有角色和作用域都匹配的反例则回传。 +3. 通过受信任原验证器解析回执。作用域标识都非空、回执身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。权威读取方为 Oracle 证据、原始来源和摘要返回各自登记的角色与作用域。每项都须匹配所请求的引用、对应的角色和确切回执身份。任一引用为空、错绑或无法读取时维持 `KeepRaw`。文件系统报告记录缺失、拒绝访问或路径类型不符时,读取边界将其视为不可用。解析错误及意外读取故障保持可见。在受支持的父会话边界追加精简证据,并保留可独立重读的原件。回执缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有角色和作用域都匹配的反例则回传。 按下一步工作的证据依赖判断重叠。下一探针仍需中间候选状态、未决反例或原始比较历史时为高重叠。下一作用域凭已核验结果及有界证据引用即可推进时为低重叠。下一步未绑定或依赖未读全时保持未知。结合节省的上下文字节、冷前缀重建和预期恢复读取,沿既有策略判断重置能否回本。 @@ -53,6 +53,6 @@ Goal Verifier Profile 绑定外部权威验证器(Oracle)的版本,可引 ## 5. 验收 -- 可执行契约验证覆盖功能关闭、L0/L1/L2 协商、显式前置扩展、确切已验回传、拒绝其他作用域的回执及真实文件缺失。运行双语和基于 diff 的 premerge 检查。 +- 可执行契约验证覆盖功能关闭、L0/L1/L2 协商、显式前置扩展、确切已验回传、拒绝其他作用域的回执以及真实的文件缺失、权限拒绝和错型路径读取。运行双语和基于 diff 的 premerge 检查。 - 首个正式接入切片使用既有历史工作集读取方处理一次已验证的子工作回传。在同一 Goal/Todo 上覆盖普通回合、验证失败或缺证、压缩或分支后的原回执读回及确切 C1 结算重放。在实际安装的宿主版本和入口验证 Hook 输出。 - 匹配模型、任务、访问权限和预算,对照同宿主 Stop-Hook。记录验收成果、错误完成、耗时、缓存和未缓存 token、验证调用、重试、存储及人工介入。覆盖高低重叠工作。跨宿主结果不计入同宿主效果归因。 diff --git a/tests/control_plane_ts/fixtures/verifier_hook_contract.ts b/tests/control_plane_ts/fixtures/verifier_hook_contract.ts index 03470de430..084e388ad5 100644 --- a/tests/control_plane_ts/fixtures/verifier_hook_contract.ts +++ b/tests/control_plane_ts/fixtures/verifier_hook_contract.ts @@ -32,11 +32,20 @@ function matchesScope(expected: VerifiedScopeIdentity, observed?: VerifiedScopeI return observed != null && scopeIdentityFields.every(field => observed[field] === expected[field]); } +const unavailableFsCodes = new Set(["ENOENT", "EACCES", "EPERM", "EISDIR", "ENOTDIR"]); + function readAvailable(read: () => T | undefined): T | undefined { try { return read(); } catch (error) { - if (error instanceof Error && "code" in error && error.code === "ENOENT") return undefined; + if ( + error instanceof Error + && "code" in error + && typeof error.code === "string" + && unavailableFsCodes.has(error.code) + ) { + return undefined; + } throw error; } } diff --git a/tests/control_plane_ts/verifier_hook_contract.test.ts b/tests/control_plane_ts/verifier_hook_contract.test.ts index de1fe167db..16df5306a5 100644 --- a/tests/control_plane_ts/verifier_hook_contract.test.ts +++ b/tests/control_plane_ts/verifier_hook_contract.test.ts @@ -1,7 +1,7 @@ import { strict as assert } from "node:assert"; import test from "node:test"; import {createHash} from "node:crypto"; -import {mkdtempSync, readFileSync, rmSync} from "node:fs"; +import {chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs"; import {tmpdir} from "node:os"; import {join} from "node:path"; @@ -161,12 +161,45 @@ test("readable evidence must match the recorded role, reference and exact work s })), { action: "KeepRaw" }); }); -test("files missing from the receipt or evidence reader preserve the raw child scope", async (t) => { +test("files missing, unreadable or wrong-kind at receipt or evidence readers preserve raw scope", async (t) => { const directory = mkdtempSync(join(tmpdir(), "loopx-verifier-hook-")); - t.after(() => rmSync(directory, { recursive: true, force: true })); - const readMissingFile = (): never => { - readFileSync(join(directory, "unavailable.json"), "utf8"); - return assert.fail("the verifier fixture unexpectedly found an unavailable file"); + const protectedPaths: string[] = []; + t.after(() => { + for (const target of protectedPaths) { + try { + chmodSync(target, 0o600); + } catch { + // Best-effort restore before directory cleanup. + } + } + rmSync(directory, { recursive: true, force: true }); + }); + const readJsonFile = (filePath: string): T => JSON.parse(readFileSync(filePath, "utf8")) as T; + const readMissingFile = (): never => readJsonFile(join(directory, "unavailable.json")); + const subDir = join(directory, "record-dir"); + mkdirSync(subDir); + const regularFile = join(directory, "regular-file.txt"); + writeFileSync(regularFile, "not-a-directory", "utf8"); + const wrongKindParentPath = join(regularFile, "entry.json"); + const lockedReceiptFile = join(directory, "locked-receipt.json"); + const lockedEvidenceFile = join(directory, "locked-evidence.json"); + writeFileSync(lockedReceiptFile, JSON.stringify(passed), "utf8"); + writeFileSync(lockedEvidenceFile, JSON.stringify(evidence.get(passed.source_ref)), "utf8"); + + const runReadBackCounterfactual = (label: string, path: string): void => { + assert.deepEqual(recommendVerifiedClose(request, { + readReceipt: () => readJsonFile(path), + readEvidence: () => assert.fail(`evidence read after receipt became unavailable (${label})`), + }), { action: "KeepRaw" }, `receipt ${label}`); + for (const ref of [passed.oracle_evidence_ref, passed.source_ref, passed.summary_ref]) { + assert.deepEqual(recommendVerifiedClose(request, authority(passed, key => + key === ref ? readJsonFile(path) : evidence.get(key), + )), { action: "KeepRaw" }, `evidence ${ref} (${label})`); + } + const failed = { ...source, verdict: "failed", counterexample_ref: "oracle:counterexample" } as const; + assert.deepEqual(recommendVerifiedClose(request, authority(failed, key => + key === "oracle:counterexample" ? readJsonFile(path) : evidence.get(key), + )), { action: "KeepRaw" }, `counterexample ${label}`); }; await t.test("a missing receipt short-circuits all evidence reads", () => { @@ -184,17 +217,74 @@ test("files missing from the receipt or evidence reader preserve the raw child s const failed = { ...source, verdict: "failed", counterexample_ref: "oracle:counterexample" } as const; assert.deepEqual(recommendVerifiedClose(request, authority(failed, readMissingFile)), { action: "KeepRaw" }); }); + await t.test("wrong-kind directory and non-directory paths (EISDIR / ENOTDIR) keep raw scope", () => { + runReadBackCounterfactual("EISDIR", subDir); + runReadBackCounterfactual("ENOTDIR", wrongKindParentPath); + }); + await t.test("permission-denied receipt and evidence files (EACCES) keep raw scope while readable files fold", () => { + const readableOracle = join(directory, "ok-oracle.json"); + const readableSource = join(directory, "ok-source.json"); + const readableSummary = join(directory, "ok-summary.json"); + writeFileSync(readableOracle, JSON.stringify(evidence.get(passed.oracle_evidence_ref)), "utf8"); + writeFileSync(readableSource, JSON.stringify(evidence.get(passed.source_ref)), "utf8"); + writeFileSync(readableSummary, JSON.stringify(evidence.get(passed.summary_ref)), "utf8"); + const fileBackedMap = new Map([ + [passed.oracle_evidence_ref, readableOracle], + [passed.source_ref, readableSource], + [passed.summary_ref, readableSummary], + ]); + assert.deepEqual(recommendVerifiedClose(request, { + readReceipt: () => readJsonFile(lockedReceiptFile), + readEvidence: ref => { + const target = fileBackedMap.get(ref); + return target ? readJsonFile(target) : undefined; + }, + }), { + action: "FoldToReceipt", + receipt_ref: "receipt:21", + source_ref: passed.source_ref, + summary_ref: passed.summary_ref, + }); + + if (typeof process.getuid === "function" && process.getuid() === 0) { + t.skip("root bypasses POSIX chmod 0o000 EACCES restrictions"); + return; + } + chmodSync(lockedReceiptFile, 0o000); + chmodSync(lockedEvidenceFile, 0o000); + protectedPaths.push(lockedReceiptFile, lockedEvidenceFile); + assert.throws( + () => readFileSync(lockedReceiptFile, "utf8"), + error => error instanceof Error && "code" in error && error.code === "EACCES", + ); + runReadBackCounterfactual("EACCES-receipt", lockedReceiptFile); + runReadBackCounterfactual("EACCES-evidence", lockedEvidenceFile); + }); }); -test("unexpected authority reader errors remain observable", () => { - const failure = new TypeError("invalid authority record"); - const fail = (): never => { throw failure; }; - const readers = [ - { readReceipt: fail, readEvidence: () => assert.fail("evidence read after unexpected failure") }, - authority(passed, fail), - ]; - for (const reader of readers) { - assert.throws(() => recommendVerifiedClose(request, reader), error => error === failure); +test("unexpected authority reader and parse errors remain observable", () => { + const directory = mkdtempSync(join(tmpdir(), "loopx-verifier-parse-")); + try { + const corruptFile = join(directory, "corrupt.json"); + writeFileSync(corruptFile, "{invalid-json", "utf8"); + const readCorrupt = (): never => JSON.parse(readFileSync(corruptFile, "utf8")) as never; + for (const reader of [ + { readReceipt: readCorrupt, readEvidence: () => assert.fail("evidence read after parse failure") }, + authority(passed, readCorrupt), + ]) { + assert.throws(() => recommendVerifiedClose(request, reader), error => error instanceof SyntaxError); + } + + const failure = new TypeError("invalid authority record"); + const fail = (): never => { throw failure; }; + for (const reader of [ + { readReceipt: fail, readEvidence: () => assert.fail("evidence read after unexpected failure") }, + authority(passed, fail), + ]) { + assert.throws(() => recommendVerifiedClose(request, reader), error => error === failure); + } + } finally { + rmSync(directory, { recursive: true, force: true }); } }); From cfa7c3589bd93f0034db834c1b659260f93c2751 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:31:56 +0800 Subject: [PATCH 8/8] fix(verifier_hook): bind authoritative acceptance_digest in VerifiedScopeIdentity Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../rfcs/verifier-hook-co-design-v0.md | 2 +- .../rfcs/verifier-hook-co-design-v0.zh-CN.md | 2 +- .../turn_driver/verifier_hook_contract.ts | 2 + .../fixtures/verifier_hook_contract.ts | 6 +- .../verifier_hook_contract.test.ts | 128 ++++++++++++++---- 5 files changed, 113 insertions(+), 27 deletions(-) diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.md index 3e081015b8..bc970c231d 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.md @@ -40,7 +40,7 @@ Official Codex and DSH are complementary reference adapters. Use official Codex ## 3. VerifiedClose 1. Branch from a known session and parent epoch using a public host or controller operation. Isolate the candidate workspace. Conversation branching grants no new write lease, verifier authority, credentials or cache guarantee. -2. Capture the exact candidate for the independent Oracle. Its immutable receipt binds Goal, Todo, parent epoch, child scope, `candidate_sha` and `verifier_version`. Use the canonical `sha256:<64 lowercase hexadecimal digits>` digest of the candidate submitted to the Oracle. The recommendation checks the digest before reading any receipt. Branch names, tags and other identifier formats keep the raw scope. The receipt identifies available fast and slow readings, verdict, falsified hypotheses and original observations or transcript. Matching failure carries a reproducible counterexample. Missing readings stay unknown. +2. Capture the exact candidate for the independent Oracle. Its immutable receipt binds Goal, Todo, parent epoch, child scope, `candidate_sha`, C1 `acceptance_digest` and `verifier_version`. Use canonical `sha256:<64 lowercase hexadecimal digits>` for the candidate submitted to the Oracle and the canonical 64 lowercase hexadecimal `acceptance_digest` from the current Goal acceptance context (`outcome_context.acceptance_digest`). The recommendation checks both digest formats before reading any receipt. Branch names, tags and other identifier formats keep the raw scope. The receipt identifies available fast and slow readings, verdict, falsified hypotheses and original observations or transcript. Matching failure carries a reproducible counterexample. Missing readings stay unknown. 3. Resolve the receipt through the trusted verifier owner. Only an exact, passed receipt with nonblank scope identifiers, no open obligations and evidenced low overlap permits a `FoldToReceipt` recommendation. The authoritative reader resolves the Oracle evidence, original source and compact result with their recorded roles and scope. Each binding must match the requested reference, its role and the exact receipt identity. An empty, mismatched or unreadable reference keeps `KeepRaw`. At the reader boundary, a filesystem lookup that reports a missing, permission-denied or wrong-kind record becomes an unavailable read. Parse and unexpected reader errors remain visible. Append the compact evidence-linked result at a supported parent boundary and preserve original evidence for independent readback. A missing, mismatched or failed receipt keeps `KeepRaw`, as does high or unknown overlap. Return an available counterexample whose role and scope match. Classify overlap from the next work's evidence dependencies. High overlap means the next probe still needs intermediate candidate state, unresolved counterexamples or the raw comparison history. Low overlap means the next scope can act from the verified result and its bounded evidence references. Treat an unbound next step or an incomplete dependency read as unknown. Apply the existing reset break-even against the saved context bytes, cold prefill and any expected recovery reads. diff --git a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md index da349540c4..c88ec5a1f3 100644 --- a/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md @@ -40,7 +40,7 @@ Goal Verifier Profile 绑定外部权威验证器(Oracle)的版本,可引 ## 3. VerifiedClose 1. 以公开宿主或控制器操作,从已识别会话及父纪元派生分支,隔离候选工作区。复制会话不授予写租约、验证权限或凭据,也不证明缓存命中。 -2. 捕获确切候选交给独立 Oracle。其不可变回执绑定 Goal、Todo、父纪元、子作用域、`candidate_sha` 和 `verifier_version`。`candidate_sha` 使用提交给 Oracle 的候选内容摘要,格式为 `sha256:<64 位小写十六进制字符>`。读取回执前先检查摘要格式。分支、标签和其他格式都保留原始作用域。回执记录可用快慢尺读数、裁决及证伪条目,包含原始观测或轨迹引用。身份匹配的失败回执提供可复现反例,缺失读数保持未知。 +2. 捕获确切候选交给独立 Oracle。其不可变回执绑定 Goal、Todo、父纪元、子作用域、`candidate_sha`、C1 权威 `acceptance_digest` 和 `verifier_version`。`candidate_sha` 使用提交给 Oracle 的候选内容摘要(`sha256:<64 位小写十六进制字符>`),`acceptance_digest` 复用当前 Goal 验收上下文的规范 64 位小写十六进制摘要(`outcome_context.acceptance_digest`)。读取回执前先检查两项摘要格式,分支、标签及其他标识格式均保留原始作用域。回执记录可用快慢尺读数、裁决及证伪条目,包含原始观测或轨迹引用。身份匹配的失败回执提供可复现反例,缺失读数保持未知。 3. 通过受信任原验证器解析回执。作用域标识都非空、回执身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。权威读取方为 Oracle 证据、原始来源和摘要返回各自登记的角色与作用域。每项都须匹配所请求的引用、对应的角色和确切回执身份。任一引用为空、错绑或无法读取时维持 `KeepRaw`。文件系统报告记录缺失、拒绝访问或路径类型不符时,读取边界将其视为不可用。解析错误及意外读取故障保持可见。在受支持的父会话边界追加精简证据,并保留可独立重读的原件。回执缺失、不匹配、失败或重叠高或未知时保持 `KeepRaw`。有角色和作用域都匹配的反例则回传。 按下一步工作的证据依赖判断重叠。下一探针仍需中间候选状态、未决反例或原始比较历史时为高重叠。下一作用域凭已核验结果及有界证据引用即可推进时为低重叠。下一步未绑定或依赖未读全时保持未知。结合节省的上下文字节、冷前缀重建和预期恢复读取,沿既有策略判断重置能否回本。 diff --git a/loopx/control_plane/turn_driver/verifier_hook_contract.ts b/loopx/control_plane/turn_driver/verifier_hook_contract.ts index 8e6b44bec9..3e57045d5d 100644 --- a/loopx/control_plane/turn_driver/verifier_hook_contract.ts +++ b/loopx/control_plane/turn_driver/verifier_hook_contract.ts @@ -63,6 +63,8 @@ export type VerifiedScopeIdentity = Readonly<{ child_scope_ref: string; /** Canonical SHA-256 digest of the candidate submitted to the verifier. */ candidate_sha: string; + /** Canonical SHA-256 digest of the Goal acceptance contract (outcome_context.acceptance_digest). */ + acceptance_digest: string; verifier_version: string; }>; diff --git a/tests/control_plane_ts/fixtures/verifier_hook_contract.ts b/tests/control_plane_ts/fixtures/verifier_hook_contract.ts index 084e388ad5..7baf5ab603 100644 --- a/tests/control_plane_ts/fixtures/verifier_hook_contract.ts +++ b/tests/control_plane_ts/fixtures/verifier_hook_contract.ts @@ -1,5 +1,5 @@ // Executable examples for the Verifier Hook contract before history-owner integration. -import { ENVELOPED_SHA256_PATTERN } from "../../../loopx/control_plane/content_digest.ts"; +import { BARE_SHA256_PATTERN, ENVELOPED_SHA256_PATTERN } from "../../../loopx/control_plane/content_digest.ts"; import type { HarnessVerifierCapabilities, VerifiedCloseReader, VerifiedCloseRecommendation, VerifiedCloseRequest, VerifiedScopeEvidence, VerifiedScopeIdentity, VerifierHookNegotiation, VerifierHookPolicy, @@ -21,7 +21,8 @@ export function negotiateVerifierHooks( } const scopeIdentityFields = [ - "goal_id", "todo_id", "parent_epoch_ref", "child_scope_ref", "candidate_sha", "verifier_version", + "goal_id", "todo_id", "parent_epoch_ref", "child_scope_ref", + "candidate_sha", "acceptance_digest", "verifier_version", ] as const; function hasReference(ref: string): boolean { @@ -69,6 +70,7 @@ export function recommendVerifiedClose( const expected = request.identity; if (!expected || !scopeIdentityFields.every(field => hasReference(expected[field])) || !ENVELOPED_SHA256_PATTERN.test(expected.candidate_sha) + || !BARE_SHA256_PATTERN.test(expected.acceptance_digest) || !hasReference(request.receipt_ref)) { return { action: "KeepRaw" }; } diff --git a/tests/control_plane_ts/verifier_hook_contract.test.ts b/tests/control_plane_ts/verifier_hook_contract.test.ts index 16df5306a5..aab441b7a7 100644 --- a/tests/control_plane_ts/verifier_hook_contract.test.ts +++ b/tests/control_plane_ts/verifier_hook_contract.test.ts @@ -9,6 +9,7 @@ import type { VerifiedCloseReader, VerifiedCloseRequest, VerifiedScopeEvidence, VerifierHookEvent, VerifierScopeReceipt, } from "../../loopx/control_plane/turn_driver/verifier_hook_contract.ts"; import {negotiateVerifierHooks, recommendVerifiedClose} from "./fixtures/verifier_hook_contract.ts"; +import {canonicalAuthoritySha256} from "../../loopx/control_plane/coordination/authority_store_codec.ts"; import {capturedContextSelection} from "../../loopx/control_plane/quota/context_selection.ts"; const l1 = { session_lineage: true, boundary_context: true }; @@ -31,9 +32,11 @@ test("enabled negotiation uses observed capabilities and never infers pre-tool o { tier: "L2", pre_tool_use: true }); }); +const acceptanceR1 = canonicalAuthoritySha256({ criteria: [{ id: "R1", required: true }] }); +const acceptanceR2 = canonicalAuthoritySha256({ criteria: [{ id: "R1", required: true }, { id: "R2", required: true }] }); const identity = { goal_id: "goal", todo_id: "todo", parent_epoch_ref: "epoch:9", child_scope_ref: "scope:3", - candidate_sha: "sha256:" + "a".repeat(64), verifier_version: "verifier:4", + candidate_sha: "sha256:" + "a".repeat(64), acceptance_digest: acceptanceR1, verifier_version: "verifier:4", }; const request: VerifiedCloseRequest = { identity, receipt_ref: "receipt:21", overlap: "low", open_obligations: false, @@ -71,27 +74,32 @@ test("verified return resolves the named oracle receipt and stages the exact sou }); }); -test("matching candidate identifiers must still identify immutable content", () => { - for (const candidate_sha of [ - "main", "candidate:26", "a".repeat(64), - "sha256:" + "a".repeat(63), "sha256:" + "g".repeat(64), "sha256:" + "A".repeat(64), - ]) { - const invalid = { ...identity, candidate_sha }; - const reads: string[] = []; - const reader = { - readReceipt(ref: string): VerifierScopeReceipt { - reads.push(ref); - return { ...passed, identity: invalid }; - }, - readEvidence(ref: string): VerifiedScopeEvidence | undefined { - reads.push(ref); - const record = evidence.get(ref); - return record && { ...record, identity: invalid }; - }, - }; - assert.deepEqual(recommendVerifiedClose({ ...request, identity: invalid }, reader), - { action: "KeepRaw" }, candidate_sha); - assert.deepEqual(reads, [], candidate_sha); +test("matching candidate and acceptance identifiers must still identify immutable content", () => { + const cases: readonly ["candidate_sha" | "acceptance_digest", readonly string[]][] = [ + ["candidate_sha", ["main", "candidate:26", "a".repeat(64), + "sha256:" + "a".repeat(63), "sha256:" + "g".repeat(64), "sha256:" + "A".repeat(64)]], + ["acceptance_digest", ["main", "R1", "sha256:" + "a".repeat(64), + "a".repeat(63), "g".repeat(64), "A".repeat(64)]], + ]; + for (const [field, malformed] of cases) { + for (const digest of malformed) { + const invalid = { ...identity, [field]: digest }; + const reads: string[] = []; + const reader = { + readReceipt(ref: string): VerifierScopeReceipt { + reads.push(ref); + return { ...passed, identity: invalid }; + }, + readEvidence(ref: string): VerifiedScopeEvidence | undefined { + reads.push(ref); + const record = evidence.get(ref); + return record && { ...record, identity: invalid }; + }, + }; + assert.deepEqual(recommendVerifiedClose({ ...request, identity: invalid }, reader), + { action: "KeepRaw" }, `${field}:${digest}`); + assert.deepEqual(reads, [], `${field}:${digest}`); + } } }); @@ -106,7 +114,11 @@ test("open, overlapping, unknown and mismatched work stays raw", () => { const missingObligations = { ...request, open_obligations: undefined } as unknown as VerifiedCloseRequest; assert.deepEqual(recommendVerifiedClose(missingObligations, authority(passed)), { action: "KeepRaw" }); for (const key of Object.keys(identity) as (keyof typeof identity)[]) { - const different = key === "candidate_sha" ? "sha256:" + "b".repeat(64) : "different"; + const different = key === "candidate_sha" + ? "sha256:" + "b".repeat(64) + : key === "acceptance_digest" + ? "b".repeat(64) + : "different"; const mismatch = { ...identity, [key]: different }; assert.deepEqual(recommendVerifiedClose(request, authority({ ...passed, identity: mismatch })), { action: "KeepRaw" }); @@ -324,3 +336,73 @@ test("startup and recovery use the same captured C1 Goal boundary", () => { assert.throws(() => capturedContextSelection({context: {}, select: [boundary.pointer]}), /pointer does not exist/); }); + +test("acceptance revision drift R1 -> R2 forces KeepRaw against identical file-backed receipt while R1 folds", () => { + const directory = mkdtempSync(join(tmpdir(), "loopx-verifier-acceptance-")); + const protectedPaths: string[] = []; + try { + const receiptPath = join(directory, "receipt.json"); + const oraclePath = join(directory, "oracle.json"); + const sourcePath = join(directory, "source.json"); + const summaryPath = join(directory, "summary.json"); + writeFileSync(receiptPath, JSON.stringify(passed), "utf8"); + writeFileSync(oraclePath, JSON.stringify(evidence.get(passed.oracle_evidence_ref)), "utf8"); + writeFileSync(sourcePath, JSON.stringify(evidence.get(passed.source_ref)), "utf8"); + writeFileSync(summaryPath, JSON.stringify(evidence.get(passed.summary_ref)), "utf8"); + const filePaths = new Map([ + [passed.oracle_evidence_ref, oraclePath], + [passed.source_ref, sourcePath], + [passed.summary_ref, summaryPath], + ]); + const fileReader: VerifiedCloseReader = { + readReceipt: ref => (ref === request.receipt_ref ? JSON.parse(readFileSync(receiptPath, "utf8")) : undefined), + readEvidence: ref => { + const target = filePaths.get(ref); + return target ? JSON.parse(readFileSync(target, "utf8")) : undefined; + }, + }; + + assert.deepEqual(recommendVerifiedClose(request, fileReader), { + action: "FoldToReceipt", + receipt_ref: request.receipt_ref, + source_ref: passed.source_ref, + summary_ref: passed.summary_ref, + }); + + // Only Goal acceptance changes (R1 -> R2); candidate, other 5 fields and verifier_version remain identical. + assert.notEqual(acceptanceR1, acceptanceR2); + assert.deepEqual( + recommendVerifiedClose({ ...request, identity: { ...identity, acceptance_digest: acceptanceR2 } }, fileReader), + { action: "KeepRaw" }, + ); + + // Control 1: verifier_version mismatch still returns KeepRaw. + assert.deepEqual( + recommendVerifiedClose({ ...request, identity: { ...identity, verifier_version: "verifier:5" } }, fileReader), + { action: "KeepRaw" }, + ); + + // Control 2: EACCES unreadable receipt still returns KeepRaw rather than folding. + if (typeof process.getuid !== "function" || process.getuid() !== 0) { + chmodSync(receiptPath, 0o000); + protectedPaths.push(receiptPath); + const unavailableFsReader: VerifiedCloseReader = { + readReceipt: () => { + try { + return JSON.parse(readFileSync(receiptPath, "utf8")); + } catch (error) { + if (error instanceof Error && "code" in error && error.code === "EACCES") return undefined; + throw error; + } + }, + readEvidence: fileReader.readEvidence, + }; + assert.deepEqual(recommendVerifiedClose(request, unavailableFsReader), { action: "KeepRaw" }); + } + } finally { + for (const target of protectedPaths) { + try { chmodSync(target, 0o600); } catch {} + } + rmSync(directory, { recursive: true, force: true }); + } +});