diff --git a/docs/architecture/rfcs/README.md b/docs/architecture/rfcs/README.md index ba2f0db398..abd928013b 100644 --- a/docs/architecture/rfcs/README.md +++ b/docs/architecture/rfcs/README.md @@ -201,6 +201,12 @@ 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)) + - **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/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 new file mode 100644 index 0000000000..bc970c231d --- /dev/null +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.md @@ -0,0 +1,58 @@ +# RFC: Verifier Hook Co-Design (v0) + +- **RFC status:** Accepted (upon merge) +- **Supersedes / closes:** none +- **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) + +## 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. 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. + +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`, 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. + +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 + +- 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 new file mode 100644 index 0000000000..c88ec5a1f3 --- /dev/null +++ b/docs/architecture/rfcs/verifier-hook-co-design-v0.zh-CN.md @@ -0,0 +1,58 @@ +# RFC:面向独立验证的 Hook 协同契约(v0) + +- **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) + +## 1. 权限与求解视图 + +通过公开宿主 Hook 和会话分支,在四个边界提高可独立验收的成果并降低完整成本。C1 继续持有 Goal、Todo、验收、证据和结算。求解器消费目标、累积验收及硬约束、Verifier Profile、已验历史最优和证伪引用的投影。启动和恢复视图通过原 C1 捕获散列和 `/goal_boundary` 指针读回同一套写入范围与停止条件。控制器保留完整决策并走既有准入与结算。模型成功响应、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`、C1 权威 `acceptance_digest` 和 `verifier_version`。`candidate_sha` 使用提交给 Oracle 的候选内容摘要(`sha256:<64 位小写十六进制字符>`),`acceptance_digest` 复用当前 Goal 验收上下文的规范 64 位小写十六进制摘要(`outcome_context.acceptance_digest`)。读取回执前先检查两项摘要格式,分支、标签及其他标识格式均保留原始作用域。回执记录可用快慢尺读数、裁决及证伪条目,包含原始观测或轨迹引用。身份匹配的失败回执提供可复现反例,缺失读数保持未知。 +3. 通过受信任原验证器解析回执。作用域标识都非空、回执身份一致且通过验证、无未决义务并有证据支持低重叠时,才能提议 `FoldToReceipt`。权威读取方为 Oracle 证据、原始来源和摘要返回各自登记的角色与作用域。每项都须匹配所请求的引用、对应的角色和确切回执身份。任一引用为空、错绑或无法读取时维持 `KeepRaw`。文件系统报告记录缺失、拒绝访问或路径类型不符时,读取边界将其视为不可用。解析错误及意外读取故障保持可见。在受支持的父会话边界追加精简证据,并保留可独立重读的原件。回执缺失、不匹配、失败或重叠高或未知时保持 `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 上覆盖普通回合、验证失败或缺证、压缩或分支后的原回执读回及确切 C1 结算重放。在实际安装的宿主版本和入口验证 Hook 输出。 +- 匹配模型、任务、访问权限和预算,对照同宿主 Stop-Hook。记录验收成果、错误完成、耗时、缓存和未缓存 token、验证调用、重试、存储及人工介入。覆盖高低重叠工作。跨宿主结果不计入同宿主效果归因。 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 new file mode 100644 index 0000000000..3e57045d5d --- /dev/null +++ b/loopx/control_plane/turn_driver/verifier_hook_contract.ts @@ -0,0 +1,104 @@ +// 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<{ + 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 type VerifierHookNegotiation = Readonly<{ + tier: "L0" | "L1" | "L2"; + pre_tool_use: boolean; +}>; + +export type GoalVerifierProfile = Readonly<{ + oracle_ref: string; + verifier_version: string; + yardstick?: WorkYardstickProfile; +}>; + +export type VerifierSolverView = Readonly<{ + objective: string; + acceptance_refs: readonly string[]; + goal_boundary_ref: QuotaGoalBoundaryReference; + 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"; view: VerifierSolverView } + | { 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; + /** 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; +}>; + +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 }; + +export type VerifiedScopeEvidence = Readonly<{ + ref: string; + role: "oracle_evidence" | "source" | "summary" | "counterexample"; + identity: VerifiedScopeIdentity; +}>; + +// Readers return undefined for unavailable authority records. +export type VerifiedCloseReader = Readonly<{ + readReceipt: (ref: string) => VerifierScopeReceipt | undefined; + readEvidence: (ref: string) => VerifiedScopeEvidence | undefined; +}>; 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..7baf5ab603 --- /dev/null +++ b/tests/control_plane_ts/fixtures/verifier_hook_contract.ts @@ -0,0 +1,99 @@ +// Executable examples for the Verifier Hook contract before history-owner integration. +import { BARE_SHA256_PATTERN, 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", "acceptance_digest", "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]); +} + +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 + && typeof error.code === "string" + && unavailableFsCodes.has(error.code) + ) { + 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) + || !BARE_SHA256_PATTERN.test(expected.acceptance_digest) + || !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 new file mode 100644 index 0000000000..aab441b7a7 --- /dev/null +++ b/tests/control_plane_ts/verifier_hook_contract.test.ts @@ -0,0 +1,408 @@ +import { strict as assert } from "node:assert"; +import test from "node:test"; +import {createHash} from "node:crypto"; +import {chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs"; +import {tmpdir} from "node:os"; +import {join} from "node:path"; + +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 }; +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 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), acceptance_digest: acceptanceR1, 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"], +}; + +const passed = { ...source, verdict: "passed", summary_ref: "capture:child-receipt" } as const; +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; + }, + readEvidence, + }; +} + +test("verified return resolves the named oracle receipt and stages the exact source reference", () => { + 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", + }); +}); + +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}`); + } + } +}); + +test("open, overlapping, unknown and mismatched work stays raw", () => { + for (const variant of [ + { ...request, overlap: "high" as const }, + { ...request, overlap: "unknown" as const }, + { ...request, open_obligations: true }, + ]) { + assert.deepEqual(recommendVerifiedClose(variant, authority(passed)), { action: "KeepRaw" }); + } + 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) + : key === "acceptance_digest" + ? "b".repeat(64) + : "different"; + const mismatch = { ...identity, [key]: different }; + assert.deepEqual(recommendVerifiedClose(request, authority({ ...passed, identity: mismatch })), + { action: "KeepRaw" }); + } + assert.deepEqual(recommendVerifiedClose(request, authority()), { action: "KeepRaw" }); + assert.deepEqual(recommendVerifiedClose(request, authority({ ...source, verdict: "unknown" })), + { action: "KeepRaw" }); + 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("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("files missing, unreadable or wrong-kind at receipt or evidence readers preserve raw scope", async (t) => { + const directory = mkdtempSync(join(tmpdir(), "loopx-verifier-hook-")); + 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", () => { + 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" }); + }); + 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 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 }); + } +}); + +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.", + } }; + 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/); +}); + +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 }); + } +});