# Agent Gate Loop 重构计划

> **实施状态：🔄 schema 就绪，运行时接入中 (2026-06-10)**
> 
> | 阶段 | schema | 运行时接入 | 核心产物 |
> |------|--------|-----------|---------|
> | Phase 0 | ✅ | ✅ | 目录结构、5 schema、迁移开关、覆盖分析 |
> | Phase 1 | ✅ | ❌ | GateRunner + 8 P0 policies + Ledger Trace + Authorization |
> | Phase 2 | ✅ | ❌ | ToolPipeline + WritePipeline + UntrustedContent |
> | Phase 3 | ✅ | ❌ | LoopKernel + CompletionPromise + StopHook + VerifyPlan |
> | Phase 4 | ✅ | ❌ | PromptSectionRegistry + CompactCapsule + DelegationPolicy |
> | Phase 5 | ✅ | ❌ | ArchitectureFitness + GovernanceAudit + RegressionCorpus |
> 
> **当前状态**：37 个新模块就绪（`tsc --noEmit` 零错误）。V2 路径已接入：`kingdee-harness-tool-events.ts`（pre-tool gate + WritePipeline）、`goal-loop.ts`（VerifyExecutor + GateRunner）、`release-check.ts`（ArchitectureFitness + GovernanceAudit hard gate）。
> 激活：`KCODE_GATE_RUNNER_V2=1`。
> 
> **已知 P2 缺口**：kd_* 工具的 ToolResultContract 尚未统一收敛到 ToolPipeline 合同路径。详见计划自查"问题 4"。

执行任务拆解见：[Agent Gate Loop 完整重构任务书](AGENT_GATE_LOOP_REFACTOR_TASKS.md)。

## 背景

本计划针对 KCode Harness 中“门禁、工具拦截、阶段推进、修复循环、上下文注入”逐渐分散的问题。近期暴露出的典型问题包括：

- `execute` 阶段写生产代码被当前阶段文档门禁反向阻断，形成循环依赖。
- loop 循环曾从用户目标文本抽取 shell 命令并执行，过度信任自然语言。
- 工具门禁散落在 action policy、tool gateway、PowerShell wrapper、具体 `kd_*` 工具和阶段门禁中。
- 系统提示词承载了过多“请勿跑偏”的约束，但部分约束必须由宿主程序执行，不能靠 LLM 自觉遵守。

本计划的目标是把门禁做成统一的运行时机制：loop 在关键检查点触发门禁，规则仍由独立 policy 模块维护，避免把所有规则堆进主流程或提示词。

本次重构按“完整成熟化”执行，不以最小改动、低风险兼容或短期不出 bug 为主要目标。允许重写当前分散的门禁、loop、工具拦截和上下文链路，目标是形成长期稳定、可审计、可扩展的 agent control plane。

优先级调整：

- 架构完整性高于局部兼容。
- 统一运行时门禁高于保留旧函数形态。
- 可观测、可测试、可审计高于短期实现速度。
- 规则单一来源高于提示词和代码双写。
- 真实坏例回归高于手工经验判断。

仍然必须保留的底线：

- 不引入第二套 PI agent runtime。
- 不让 LLM 自己判断能否绕过门禁。
- 不让用户普通确认解除 hard-deny。
- 不把子 agent 输出直接写成主 facts/evidence。
- 不把提示词当安全边界。

## 已识别但尚未完成的重构项

以下项目来自前期审查和本轮讨论，必须纳入整体路线图，不能只修 GateRunner：

| 重构项 | 当前状态 | 风险 | 纳入阶段 |
| --- | --- | --- | --- |
| GateRunner 统一门禁执行器 | 未实现 | 门禁散落在主流程、工具和具体扩展里，新增入口容易漏拦 | Phase 1-4 |
| 工具注册覆盖审计 | 未实现 | 新增写类工具或 shell 包装后可能绕过 gateway | Phase 0、Phase 5 |
| 风险 taxonomy 集中化 | 未完成 | hard deny、soft deny、evidence required、warning 语义分散，用户授权边界不清 | Phase 1、Phase 2 |
| PI system context 化 | 未完成 | 仍主要依赖 workflow prompt 注入，长期容易变成长提示词堆叠 | Phase 4 之后 |
| post-compact 安全约束保留 | 未完成 | 压缩/恢复后可能丢 open question、hard deny、source anchor、gate 状态 | Phase 4 |
| 子 agent post-delegation gate | 未完成 | 子 agent 输出可能被主流程误当 facts/evidence/验证结果 | Phase 4 |
| Harness audit 产品化 | 未实现 | 只能靠人工 review 和零散 smoke，缺少固定评分和入口覆盖表 | Phase 5 |
| Evidence 来源分级 | 未完成 | 本地命令、用户提供、外部系统、人工说明混在一起，ship 风险不清 | Phase 3、Phase 5 |
| Gate next-action 结构化 | 未完成 | 门禁失败时只给自然语言建议，agent 可能猜下一步 | Phase 1、Phase 3 |
| Quick/normal 语义收敛 | 未完成 | quick 低风险体验和 normal 强门禁之间可能互相误伤 | Phase 1、Phase 3 |
| Prompt policy 与 runtime policy 去重 | 未完成 | 同一规则同时写在提示词和代码里，容易漂移 | Phase 2、Phase 4 |
| Tool result contract 强校验 | 未完成 | 非 `kd_*` 工具结果结构不完整，后续上下文可能误用 | Phase 2、Phase 5 |
| Goal loop 修复循环事件化 | 部分完成 | 已限制 npm scripts，但 loop 的每轮 gate/repair 事件仍不够统一 | Phase 3 |
| 用户授权模型 | 未完成 | 缺少结构化授权对象，容易把“可以”误当所有阻断的豁免 | Phase 1、Phase 3 |
| 文档不可信内容统一包装 | 部分完成 | `kd_doc_read` 已包装，其他外部输入来源仍需统一 | Phase 2、Phase 4 |

这些项目的优先顺序不是按“架构漂亮程度”，而是按风险面排序：先处理可执行副作用入口，再处理上下文和审计成熟度。

## 最佳实践基线

本计划参考以下公开资料，并转换为适合 KCode 的工程约束：

- OpenAI Prompt Engineering：提示词要清晰、结构化、提供上下文、约束输出格式，并通过评估持续迭代。参考：https://developers.openai.com/api/docs/guides/prompt-engineering
- OpenAI Agents SDK Guardrails：区分 input、output、tool guardrails；工具 guardrail 应在每次工具调用前后执行，不能只依赖 agent 入口和最终输出。参考：https://openai.github.io/openai-agents-python/guardrails/
- OpenAI Agents SDK Tracing：agent 运行需要 trace/span 级别的可观测性，并注意敏感数据处理。参考：https://openai.github.io/openai-agents-python/tracing/
- Anthropic Prompt Engineering：复杂任务应给出清晰角色、目标、上下文、示例、思考空间和不确定性处理方式。参考：https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview
- Anthropic Building Effective Agents：优先使用简单、可组合的 workflow；增加复杂 agent loop 前要确保可调试、可观测、可回退。参考：https://www.anthropic.com/engineering/building-effective-agents
- ReAct：将 reasoning trace 与 actions 交替，让模型通过外部动作获取信息、更新计划并提高可解释性。参考：https://arxiv.org/abs/2210.03629
- Loop Engineering 最新范式：从一次性 prompt 冷启动转向长流式自主循环，核心是持久状态、可审计反馈、生成器-评估器、完成承诺和停止钩子。参考：https://www.neican.ai/insights/loop-engineering--20260608194006630-2/
- Agent Harness 工程：Agent 产品不是把规则链硬编码成“智能”，而是为模型提供 Tools、Knowledge、Observation、Action Interfaces、Permissions。参考：https://github.com/shareAI-lab/learn-claude-code
- OWASP Top 10 for LLM Applications：重点防 prompt injection、sensitive information disclosure、excessive agency、unbounded consumption 等 agent 风险。参考：https://genai.owasp.org/llm-top-10/
- NIST AI Risk Management Framework：风险治理应覆盖 Govern、Map、Measure、Manage，并形成持续评估闭环。参考：https://www.nist.gov/itl/ai-risk-management-framework

转化到 KCode 后的原则：

- Prompt 是行为说明，不是安全边界。
- Gate 是可执行策略，不是文档建议。
- Loop 是编排器，不直接内嵌业务规则。
- Tool call 是主要风险面，必须每次 pre/post 检查。
- Evidence、facts、ledger 是唯一可信状态源；自然语言只作为输入事件。
- 所有真实坏例必须沉淀成 smoke 或 transcript eval。
- 长流式 loop 替代单轮 prompt 冷启动。
- Completion Promise 和 Stop Hook 是 loop 的一等对象。
- Generator-Evaluator 必须隔离上下文，评估器不能被生成器自述污染。
- Token、时间、工具调用和修复轮次预算必须是运行时治理对象。
- Harness 不是智能本身；Harness 负责感知、行动、权限、记忆和反馈。

## Loop Engineering 范式吸收

AI 内参的 Loop Engineering 文章把新范式概括为：开发者不再主要发送一次性 prompt，而是构建长时间运行、自我校验、可审计、可停止的自主反馈系统。这一判断应成为 KCode 重构的主方向。

### 从冷启动到长流式

旧模式：

```text
用户写 prompt
  -> 模型生成代码
  -> 人工检查
  -> 下一次重新 prompt
```

新模式：

```text
Completion Promise
  -> StateKernel
  -> LoopKernel
  -> Tool / Write / Verify / Delegate
  -> Observation
  -> Evaluator
  -> GateRunner
  -> Repair / Stop / Ship
```

KCode 要从“每轮 prompt 注入大量约束”改为“长流式 LoopKernel 持续维护目标、状态、证据、评估和停止条件”。

### Completion Promise

Completion Promise 是 agent 承诺完成的可验证目标，不是聊天中的泛泛意图。

```ts
interface CompletionPromise {
  id: string;
  objective: string;
  acceptance: AcceptanceCriterion[];
  allowedScope: string[];
  disallowedScope: string[];
  requiredEvidence: string[];
  doneWhen: StopCondition[];
  abortWhen: StopCondition[];
}
```

要求：

- 每个 run 必须有 Completion Promise。
- PLAN、VERIFY、SHIP 都引用同一个 Completion Promise。
- `/kd goal` 不是直接执行命令，而是补充或验证 Completion Promise。
- Completion Promise 不满足时，agent 不得自称完成。

### Stop Hook

Stop Hook 是防止无限循环、影子自动化和自我确认的运行时钩子。

KCode Stop Hook 类型：

- `done`：验收标准满足，证据齐全，门禁通过。
- `blocked`：缺用户事实、缺环境、缺权限、缺外部系统证据。
- `budget-exhausted`：token、时间、工具调用、修复轮次超过预算。
- `stuck`：重复同一失败、重复同一工具、重复同一问题。
- `unsafe`：hard-deny、外部路径、凭证、越权、破坏性命令。
- `scope-drift`：修改范围偏离 Completion Promise 或 PLAN。

Stop Hook 必须写入 ledger，并成为 control frame 的最高优先级输入。

### Generator-Evaluator

完整重构后，KCode 不应让同一个上下文中的生成器自评“我写得对”。应建立隔离的 evaluator 机制。

```text
Generator Loop
  -> 生成实现 / 修复
  -> 写入 evidence
  -> 提交候选状态

Evaluator Loop
  -> 读取候选 diff、PLAN、Completion Promise、evidence
  -> 独立运行 check、static analysis、domain checks
  -> 输出 EvaluationFinding

GateRunner
  -> 根据 EvaluationFinding 决定 continue / repair / stop / ship
```

规则：

- Evaluator 默认只读，不能写生产代码。
- Evaluator 不能信任 Generator 的自述，只信 diff、命令输出、evidence 和 source refs。
- Evaluator 输出不能直接推进阶段，必须进入 GateRunner。
- 高风险任务必须有 evaluator finding 才能 ship。

### Loop Budget

长流式 loop 必须内置成本治理，否则会变成无限自我消耗。

```ts
interface LoopBudget {
  maxTurns: number;
  maxToolCalls: number;
  maxVerifyAttempts: number;
  maxWallClockMs: number;
  maxContextChars: number;
  maxDelegations: number;
}
```

预算不是为了保守，而是为了让长循环工业化：

- 超预算必须触发 Stop Hook。
- Stop Hook 必须给出继续所需的结构化条件。
- 用户授权继续时生成新的 budget segment，而不是无限延长当前循环。

### 影子自动化治理

Loop 失控会导致代码库膨胀和不可预测行为。KCode 对应治理：

- 每轮 action 必须绑定 Completion Promise。
- 每个文件修改必须绑定 allowedScope 和 PLAN path。
- 每次新增文件必须有 gate finding 说明。
- 每次重复失败必须进入 stuck detector。
- 每次跨 run 行为必须经过 active run check。
- 所有后台或子 agent 行为必须有 parent run traceId。

### Agent Harness 公式

采用 learn-claude-code 的 Harness 公式：

```text
Harness = Tools + Knowledge + Observation + Action Interfaces + Permissions
```

映射到 KCode：

| Harness 要素 | KCode 目标模块 |
| --- | --- |
| Tools | ToolPipeline、PowerShell wrapper、kd_* tools、MCP adapters |
| Knowledge | kd knowledge、SDK signature、metadata、project context、skills |
| Observation | Ledger、ToolResultContract、EvidenceStore、git diff、build logs |
| Action Interfaces | ActionPlan、VerifyPlan、WritePipeline、DelegationPlan |
| Permissions | GateRunner、PolicyRegistry、AuthorizationModel、workspace sandbox |

这个公式也定义了边界：KCode 不训练模型，不伪造 intelligence；KCode 构建的是让模型稳定工作的载具。

### learn-claude-code 20 课映射

| learn-claude-code 机制 | KCode 重构落点 |
| --- | --- |
| s01 agent loop | LoopKernel |
| s02 tool use | ToolPipeline |
| s03 permission | GateRunner + AuthorizationModel |
| s04 hooks | Stop Hook + pre/post checkpoints |
| s05 todo write | CompletionPromise + TaskGraph |
| s06 subagent | DelegationPlan + post-delegation gate |
| s07 skill loading | Skill/Knowledge on-demand loading |
| s08 context compact | CompactCapsule + post-compact gate |
| s09 memory | StateKernel + durable context entries |
| s10 system prompt | PromptSectionRegistry |
| s11 error recovery | StuckDetector + RepairLoop |
| s12 task system | TaskGraph + CompletionPromise |
| s13 background tasks | Background evaluator with parent traceId |
| s14 cron scheduler | Scheduled audit/evaluator, not unsupervised write |
| s15 agent teams | Generator/Evaluator/Reviewer roles |
| s16 team protocols | Async mailbox + typed handoff contracts |
| s17 autonomous agents | Long-running LoopBudget + Stop Hook |
| s18 worktree isolation | Future parallel worktree sandbox |
| s19 MCP plugin | MCP adapter through ToolPipeline |
| s20 comprehensive | Full control plane release gate |

## 四大工程统一架构

本次完整重构不是单点优化，而是把 Prompt Engineering、Harness Engineering、ReAct Loop Engineering、Agent Governance 四条工程线统一到一个控制平面。

### 1. Prompt Engineering

目标：提示词只表达任务协议、状态摘要和输出约束，不再承载安全规则的最终解释权。

成熟形态：

- Prompt 由结构化 context packet 渲染，不直接读取分散状态。
- Prompt sections 有固定 schema、优先级和预算，不靠手写长文本拼接。
- 每个 section 明确来源：run state、facts、evidence、gate decision、tool result、ledger、project context。
- Prompt 中的规则只引用 runtime policy 摘要，不复制 policy 实现。
- Prompt 支持 few-shot，但示例必须来自可测试模板，不允许临时散落在业务逻辑里。
- Prompt 明确不确定性协议：缺事实就问、缺证据就阻断、缺工具就报告真实阻塞。
- Prompt 输出必须能映射为 action intent、tool plan、verify plan 或 user response，不接受无结构化落点的自由发挥。

需要重构的模块：

- `src/harness/prompt.ts`
- `src/harness/prompt-policy.ts`
- `src/harness/context-compiler.ts`
- `src/harness/context-packet.ts`
- `src/harness/control-frame.ts`

目标产物：

- `PromptSectionRegistry`
- `PromptContract`
- `PromptBudgetPlan`
- `PromptRenderTrace`
- `PromptPolicySummary`，从 runtime policy 自动生成。

### 2. Harness Engineering

目标：Harness 是唯一状态机和控制平面，所有事实、证据、门禁、工具观测、修复循环都进入同一状态内核。

成熟形态：

- State Kernel 是唯一可信状态源。
- GateRunner 是唯一门禁执行器。
- Ledger 是唯一审计轨迹。
- Evidence Store 是唯一证据索引。
- Tool Result Contract 是唯一工具观测格式。
- Control Frame 是唯一下一动作来源。
- Context Compiler 只消费 State Kernel，不做业务推断。
- 旧模块只能作为 adapter，不再拥有规则判断权。

需要重构的模块：

- `src/harness/state.ts`
- `src/harness/gates.ts`
- `src/harness/tool-gateway.ts`
- `src/harness/action-policy.ts`
- `src/harness/write-transaction.ts`
- `src/harness/evidence.ts`
- `src/harness/ledger.ts`
- `src/harness/observation.ts`
- `extensions/kingdee-tools.ts`
- `extensions/kingdee-powershell-tool.ts`

目标产物：

- `StateKernel`
- `GateRunner`
- `PolicyRegistry`
- `EvidenceStore`
- `ToolPipeline`
- `WritePipeline`
- `HarnessTrace`
- `ArchitectureFitnessTests`

### 3. ReAct Loop Engineering

目标：KCode 的 agent loop 不再是“LLM 自己想下一步”，而是结构化的 Reason -> Gate -> Act -> Observe -> Update -> Evaluate。

成熟形态：

```text
User/Input/Event
  -> Intent Router
  -> Reason State
  -> GateRunner
  -> Action Plan
  -> Tool/Verify/Ask/Write/Delegate
  -> Observation
  -> State Update
  -> Evaluation
  -> Next Control Frame
```

关键原则：

- Reasoning 可以存在，但不能直接产生副作用。
- Action 必须来自通过 gate 的结构化 action plan。
- Observation 必须写入 ledger 和 tool result contract。
- State Update 只能由 reducer 处理，不能由 prompt 自由改写。
- Loop 必须有预算、停止条件、重复检测和 stuck detector。
- Repair loop、goal loop、demand loop、phase loop 统一到同一 Loop Kernel。
- LLM 的“我已经验证/我已经完成”不能更新状态，只有真实 observation/evidence 可以。

需要重构的模块：

- `src/harness/demand-loop.ts`
- `src/harness/goal-loop.ts`
- `src/harness/repair.ts`
- `src/harness/action-router.ts`
- `src/harness/next-action.ts`
- `src/harness/control-frame.ts`
- `src/harness/delegation.ts`

目标产物：

- `LoopKernel`
- `ActionPlan`
- `VerifyPlan`
- `AskPlan`
- `DelegationPlan`
- `LoopReducer`
- `StuckDetector`
- `LoopBudget`
- `LoopReplay`

### 4. Agent Governance

目标：把 agent 风险治理工程化，覆盖设计、运行、观测、评估和发布。

成熟形态：

- 风险 taxonomy 是代码结构，不是文档段落。
- hard-deny、soft-deny、evidence-required、warning 有一致语义。
- 用户授权是结构化对象，不是自然语言“可以”。
- 每个高风险 action 都有 gate traceId。
- 每个 release 都跑 architecture fitness tests。
- 每个真实坏例都进入 regression corpus。
- 每个未完成重构项都有状态、责任模块和验收标准。

需要重构的模块：

- `src/harness/risk-policy.ts`
- `src/harness/consistency.ts`
- `src/harness/context-validation.ts`
- `src/harness/transcript-eval.ts`
- `scripts/smoke-harness.ts`
- `scripts/smoke-harness-evals.ts`
- `scripts/release-check.ts`

目标产物：

- `RiskTaxonomy`
- `AuthorizationModel`
- `GovernanceAudit`
- `ArchitectureFitnessTest`
- `RegressionCorpus`
- `ReleaseGate`

## 成熟后目标目录

完整重构后建议形成以下模块边界：

```text
src/harness/kernel/
  state-kernel.ts
  reducers.ts
  events.ts
  snapshots.ts

src/harness/gates/
  gate-runner.ts
  policy-registry.ts
  findings.ts
  taxonomy.ts
  policies/
    workspace-path-policy.ts
    source-write-policy.ts
    phase-policy.ts
    tdd-policy.ts
    verify-command-policy.ts
    delegation-policy.ts
    context-policy.ts

src/harness/loop/
  loop-kernel.ts
  action-plan.ts
  verify-plan.ts
  repair-loop.ts
  demand-loop.ts
  stuck-detector.ts
  replay.ts

src/harness/context/
  context-compiler.ts
  prompt-section-registry.ts
  prompt-contract.ts
  handoff-capsule.ts
  compact-capsule.ts

src/harness/tools/
  tool-pipeline.ts
  tool-contract.ts
  write-pipeline.ts
  postconditions.ts

src/harness/evidence/
  evidence-store.ts
  evidence-source.ts
  evidence-validation.ts

src/harness/audit/
  governance-audit.ts
  architecture-fitness.ts
  transcript-regression.ts
```

旧的 `src/harness/*.ts` 文件可以在迁移期保留 adapter，但最终应收敛到上述边界，避免再次形成大平铺模块。

## 目标架构

### 一句话目标

建立 `GateRunner + LoopKernel + StateKernel + PromptSectionRegistry` 作为 KCode Harness 的统一 agent control plane，让主流程、goal loop、tool gateway、阶段推进、上下文压缩和子 agent 委派都通过同一套可审计机制执行。

### 分层

```text
PI Runtime
  -> KCode Extension Adapter
  -> LoopKernel
  -> GateRunner
       -> Gate Checkpoints
       -> Policy Registry
       -> Decision / Finding / Trace
  -> StateKernel / EvidenceStore / Ledger
  -> Context Compiler / PromptSectionRegistry
  -> Prompt Renderer
```

### GateRunner 职责

`GateRunner` 只负责三件事：

- 在固定检查点收集上下文。
- 调用注册的 policy。
- 输出结构化 decision，并写入 ledger/trace。

`GateRunner` 不负责：

- 生成 prompt。
- 推断业务事实。
- 直接读写阶段文档。
- 执行工具或命令。
- 替代现有 policy 的业务规则。

### 检查点

第一阶段建议定义以下检查点：

```ts
type GateCheckpoint =
  | "pre-input"
  | "pre-plan"
  | "pre-phase-transition"
  | "pre-tool"
  | "post-tool"
  | "pre-write"
  | "post-write"
  | "pre-verify-command"
  | "post-verify-result"
  | "pre-delegation"
  | "post-delegation"
  | "pre-context-compile"
  | "post-context-compile";
```

检查点含义：

- `pre-input`：处理用户输入前，检查是否存在 open question、resumeSnapshot、consistency error。
- `pre-plan`：生成或替换 PLAN 前，检查需求边界、产品画像、模式强度。
- `pre-phase-transition`：阶段推进前，调用现有 `canEnterPhase` / `inspectGate`。
- `pre-tool`：工具执行前，检查路径、工具角色、子 agent 权限、document reader、安全输入。
- `post-tool`：工具执行后，检查输出是否包含敏感信息、是否需要包装为 untrusted content、是否应记录 evidence/tool result。
- `pre-write`：写入前，检查工作区、阶段、PLAN 批准文件、source anchor、TDD red。
- `post-write`：写入后，检查文件存在、后置条件、模板占位符、write transaction 状态。
- `pre-verify-command`：验证命令执行前，检查命令来源、脚本白名单、shell 禁用策略。
- `post-verify-result`：验证结果记录前，检查 exit code、stdout/stderr、绿灯证据有效性。
- `pre-delegation`：委派前，检查角色、工具边界、handoff capsule、并行/串行限制。
- `post-delegation`：委派后，阻止子 agent 输出直接成为主 evidence 或 facts。
- `pre-context-compile`：编译 prompt 前，检查 run state 一致性。
- `post-context-compile`：发送 prompt 前，检查 hard deny、open question、gate、budget report 是否保留。

## 目标接口草案

```ts
export interface GateContext {
  cwd: string;
  checkpoint: GateCheckpoint;
  run?: ActiveRun;
  toolName?: string;
  path?: string;
  command?: string;
  delegationRole?: DelegationRole;
  phaseTarget?: HarnessPhase;
  payload?: unknown;
}

export type GateSeverity = "hard-deny" | "soft-deny" | "evidence-required" | "warning";

export interface GateFinding {
  id: string;
  severity: GateSeverity;
  policy: string;
  message: string;
  nextAction?: string;
  evidencePath?: string;
  sourceRefs?: string[];
}

export interface GateDecision {
  allowed: boolean;
  checkpoint: GateCheckpoint;
  findings: GateFinding[];
  traceId: string;
}
```

规则：

- 任何 `hard-deny` 使 `allowed=false`。
- `soft-deny` 默认阻断，但可通过明确的结构化用户授权或计划修订解除。
- `evidence-required` 不一定阻断当前工具，但阻断阶段推进或交付。
- `warning` 只记录，不阻断。
- `allow` 不是 finding severity；允许是 `GateDecision.allowed=true` 且没有阻断 finding 的结果。
- 每个 finding 必须有 `policy`、`message` 和建议的 `nextAction`。

### EvidenceRecord 草案

`sourceTrust` 必须显式定义，不能只在后续章节中零散引用。

```ts
export type EvidenceSourceTrust =
  | "local-command"
  | "project-metadata"
  | "project-source"
  | "user-provided"
  | "external-system"
  | "manual-note";

export interface EvidenceRecord {
  id: string;
  path: string;
  kind: "sdk-signature" | "metadata" | "tdd-red" | "tdd-green" | "verify" | "evaluation" | "manual";
  sourceTrust: EvidenceSourceTrust;
  producerTraceId: string;
  command?: string;
  exitCode?: number;
  sourceRefs: string[];
  createdAt: string;
}
```

规则：

- `local-command`、`project-metadata`、`project-source` 可以作为本地强证据。
- `user-provided`、`external-system` 可以作为交付证据，但 ship 必须显示残余风险和来源。
- `manual-note` 只能解释阻塞或风险，不能单独作为绿灯。
- TDD green / verify pass 若来自非本地强证据，不能自动等同于本地验证通过。

## Policy Registry

将现有规则迁移到 policy registry。迁移可以按入口批次切换，但目标不是长期双轨；旧规则源必须被删除或 adapter 化，不能继续作为并行权威。

### 第一批迁移

| Policy | 现有来源 | 目标 checkpoint | 优先级 |
| --- | --- | --- | --- |
| WorkspacePathPolicy | `src/platform/path.ts`、`tool-gateway.ts`、各工具 path 检查 | `pre-tool`、`pre-write` | P0 |
| SourceWritePolicy | `src/harness/action-policy.ts` | `pre-write` | P0 |
| PhaseGatePolicy | `src/harness/gates.ts` | `pre-phase-transition`、`pre-write` | P0 |
| TddPolicy | `src/harness/tdd-policy.ts` | `pre-write`、`post-verify-result` | P0 |
| PlanPathPolicy | `src/harness/path-policy.ts` | `pre-write` | P0 |
| ToolGatewayPolicy | `src/harness/tool-gateway.ts` | `pre-tool` | P0 |
| PowerShellMutationPolicy | `extensions/kingdee-powershell-tool.ts` | `pre-tool` | P0 |
| VerifyCommandPolicy | `src/harness/goal-loop.ts` | `pre-verify-command` | P0 |
| DelegationPolicy | `src/harness/delegation.ts` | `pre-delegation`、`post-delegation` | P1 |
| ContextValidationPolicy | `src/harness/context-validation.ts` | `post-context-compile` | P1 |

### 完整迁移范围

本次按完整重构处理，除 PI Runtime 本体之外，KCode Harness 内部与门禁、loop、上下文、证据、委派相关的逻辑都纳入迁移范围：

- prompt 文案生成要改为消费 GateRunner 和 Context Kernel 的结构化输出，不能再复制规则。
- Required Facts Contract 保留业务判断，但其结果必须成为 GateRunner finding。
- evidence 文件格式允许升级，新增来源分级、验证主体、可信等级和关联 gate decision。
- session/compaction 不重写 PI 机制，但 KCode 的 handoff/post-compact 必留内容要结构化生成。
- 旧函数可以短期作为适配层存在，但不得继续成为规则源。

唯一明确不迁移的是 PI CLI/Runtime 本体。KCode 仍是 PI 之上的 Harness control plane，不 fork PI agent loop。

## 完整重构实施计划

### 并行工作流

本次大破大立按 4 条主线并行推进，而不是线性等一个模块全部完成后再做下一个：

| 工作流 | 目标 | 核心产物 | 必须先完成 |
| --- | --- | --- | --- |
| Prompt Engineering | 结构化 prompt 生成，不再把规则写死在提示词里 | PromptSectionRegistry、PromptContract、PromptRenderTrace | StateKernel snapshot schema |
| Harness Engineering | 统一状态、门禁、证据、工具观测 | StateKernel、GateRunner、EvidenceStore、ToolPipeline | Gate taxonomy |
| ReAct Loop Engineering | Reason/Gate/Act/Observe/Update/Evaluate 统一循环 | LoopKernel、ActionPlan、LoopReducer、StuckDetector | GateRunner decision schema |
| Governance Engineering | 审计、回归、架构 fitness tests | GovernanceAudit、RegressionCorpus、ReleaseGate | traceId 和 ledger schema |

并行推进原则：

- schema 先行：先定 `GateDecision`、`ActionPlan`、`KernelSnapshot`、`EvidenceRecord`、`ToolResultContract`。
- adapter 可临时存在，但旧规则源不得继续扩张。
- 每条工作流都必须提供自己的 smoke/eval。
- 每次真实坏例必须归入某条工作流并形成回归。

### Phase 0：建立架构断言和破坏性迁移开关

目标：承认本次是完整重构，先建立防止架构继续分叉的硬约束。

任务：

- 列出所有工具执行入口、写入入口、阶段推进入口、验证命令入口、子 agent 入口。
- 为每个入口标注当前调用了哪些 policy。
- 增加审计脚本或 smoke：发现疑似写类工具但未接入 gate 时失败。
- 生成“历史未完成重构项”到 phase 的映射，防止只重构 GateRunner 壳而漏掉 context、audit、授权和 evidence 来源。
- 文档更新：在 `HARNESS_WORKFLOW.md` 链接本计划。
- 增加 `ARCHITECTURE BREAK` 章节或代码注释，明确旧路径即将废弃。
- 建立迁移开关，例如 `KCODE_GATE_RUNNER_V2=1`，用于在本地完整切换到新控制平面。
- 列出允许删除或改签名的旧函数，避免为了兼容保留双轨规则。
- 定义 5 个核心 schema：`KernelSnapshot`、`GateDecision`、`ActionPlan`、`EvidenceRecord`、`ToolResultContract`。
- 建立大破大立迁移看板：每个旧模块标记 `adapter`、`rewrite`、`delete`、`keep-runtime`。

验收：

- 能输出一张入口到 policy 的覆盖表。
- 新增写类工具时，如果未注册 gate，测试失败。
- 新旧入口冲突时，以 GateRunner V2 为准。
- 明确哪些旧函数会被删除、哪些只作为 adapter 保留。
- 5 个核心 schema 有类型定义和最小单测。

风险：

- 一开始就破坏兼容，短期 bug 变多。

缓解：

- 接受短期 bug，但每个 bug 必须进入 regression matrix。

### Phase 1：重建 GateRunner Control Plane

目标：不是“引入壳”，而是建立新的门禁控制平面，旧 policy 全部通过 registry 运行。

任务：

- 新增 `src/harness/gate-runner.ts`。
- 定义 `GateCheckpoint`、`GateContext`、`GateFinding`、`GateDecision`。
- 支持 policy 注册、顺序执行、finding 合并。
- 支持 `recordGateDecision(cwd, run, decision)` 写入 ledger。
- 定义集中风险 taxonomy：`hard-deny`、`soft-deny`、`evidence-required`、`warning`。
- 定义结构化 `nextAction`，避免门禁失败后只给自然语言建议。
- 设计用户授权对象，但只允许解除 `soft-deny`，不能解除 `hard-deny`。
- 一次性注册第一批 P0 policy：WorkspacePath、ToolGateway、PowerShellMutation、SourceWrite、PhaseGate、PlanPath、TDD、VerifyCommand。
- GateDecision 成为 control frame、tool result contract、write transaction、repair loop 的共同输入。
- 删除或降级旧模块中的重复 severity/next-action 判断。

验收：

- 现有 `npm run smoke:harness` 不变。
- GateRunner 单测覆盖 hard-deny、warning、多个 finding 合并。
- ledger 能看到 gate decision。
- finding 中的 `nextAction` 可被 control frame 直接消费。
- 所有 P0 写入和命令执行路径都能追溯到一个 GateDecision traceId。
- Prompt renderer 不再直接决定 hard/soft/evidence/warning。

风险：

- GateRunner 变成新上帝对象。

缓解：

- GateRunner 只编排 policy，不内嵌规则；超过 200 行时拆分 registry、decision、trace。

### Phase 2：重写工具执行边界

目标：所有工具调用都进入同一个 pre/post tool pipeline，消除扩展层各自实现门禁。

任务：

- `evaluateToolGateway` 改为 GateRunner adapter，旧工具网关不再作为规则源。
- `sourceWriteBlockReason` 改为 GateRunner adapter，旧 action policy 不再作为规则源。
- PowerShell wrapper 在执行前调用 `runGate("pre-tool")`。
- `kd_doc_read`、`kd_anchor_read`、`kd_find_file`、`kd_sdk_signature` 等 path 检查改为统一 policy。
- 保留工具内部最后一道 path check，作为 defense-in-depth。
- 统一外部输入包装策略：文档、网页、外部文件、用户粘贴的大段内容都标记为 untrusted content，禁止其中指令覆盖系统规则。
- 建立 tool result contract 强校验：工具成功必须明确 status、kind、sourceRefs/evidencePath、nextAction。
- 去重 prompt policy 和 runtime policy：提示词只引用门禁结果，不复制完整阻断规则。
- 所有 tool call 形成 `tool.requested -> gate.decision -> tool.executed|tool.blocked -> post-tool.gate -> tool.result.recorded` 事件链。
- 内置 read/write/edit/bash、KCode kd_*、PowerShell wrapper、subagent tool 都进入同一观察模型。
- ToolPipeline 负责所有工具输入输出，不允许扩展层绕过 pipeline 自己记录 context/evidence。
- WritePipeline 负责 source anchor、write transaction、postcondition，旧 write transaction 逻辑 adapter 化。
- 对 PI Runtime 无法暴露 pre/post hook 的内置工具，不能假设已被保护；必须二选一：
  - 通过 KCode wrapper 禁用原工具并暴露受控工具。
  - 或在可用 extension hook 中强制拦截，无法拦截时该工具在 KCode 模式下不可用。

验收：

- 外部路径读写仍被拦截。
- PowerShell mutation 绕过仍被拦截。
- 已进入 execute 且证据满足时，生产源码写入不被当前 `EXECUTION.md` 缺失阻断。
- 现有 path/tool smoke 全过。
- `kd_doc_read` 之外的外部内容入口也有 untrusted 包装或明确阻断。
- 工具成功但缺少 result contract 时产生 warning 或 eval failure。
- 任意工具调用都可在 ledger 中按 traceId 重放。
- write/edit/read/bash/kd_* 的结果都能转成统一 ToolResultContract。

风险：

- 工具链路短期大面积失败。

缓解：

- 允许失败，但失败必须结构化；禁止静默 fallback 到旧规则。

### Phase 3：重写阶段推进、验证和修复循环

目标：所有 loop 都是可审计状态机，不再从自然语言或提示词中隐式推断可执行动作。

任务：

- `advanceRun` / `advanceRunIfReady` 在阶段推进前调用 `runGate("pre-phase-transition")`。
- `executeGoal` 在执行 npm script 前调用 `runGate("pre-verify-command")`。
- `recordVerifyResult` 在记录前调用 `runGate("post-verify-result")`。
- goal loop 不接收任意 shell；只接收 `GateDecision.allowed=true` 的命令计划。
- 修复循环达到上限时，finding 写入 run question 的 reason。
- Evidence 增加来源分级：`local-command`、`project-metadata`、`user-provided`、`external-system`、`manual-note`。
- quick/normal 规则由 policy 明确表达，禁止 quick 误触 normal-only evidence gate，也禁止 high-risk 需求停留在 quick。
- goal loop 每轮尝试写入 gate/repair 事件，方便 replay 和审计。
- 合并 demand loop、goal loop、phase loop 的公共状态机接口：`LoopStep -> GateDecision -> Action -> Observation -> StateUpdate`。
- 取消 loop 内部直接调用 shell、直接推进阶段、直接记录验证结果的分散路径。
- 所有 verify command 先变成 `VerifyPlan`，再由 GateRunner 判定是否可执行。
- evidence 写入必须绑定 producing action、command、exitCode、sourceTrust 和 gate traceId。
- LoopKernel 引入统一 reducer：所有状态变更只能通过事件和 reducer 完成。
- ActionRouter 输出 ActionPlan，不直接触发工具。
- ControlFrame 消费 ActionPlan 和 GateDecision，不再重复推断 next action。

验收：

- `npm run missing`、`node -e`、`npx xxx` 不会被 goal loop 执行。
- `npm run check` 仅当 package script 存在时允许。
- 验证绿灯缺 `Exit: 0` 仍阻断 verify/ship。
- 自动修复上限行为不变。
- user-provided/external-system evidence 在 ship 中显示残余风险，不等同 local-command。
- high-risk 信号仍强制 normal。
- 所有阶段推进都能解释为一个通过的 GateDecision。
- 修复循环可以从 ledger replay 出每次失败、修复、再验证和阻断原因。
- demand/goal/repair/phase 四类 loop 都能输出同一格式 LoopTrace。

风险：

- 现有命令体验变化明显。

缓解：

- 接受体验变化；文档明确新模型：自然语言提出目标，运行时只执行结构化 VerifyPlan。

### Phase 4：重写上下文内核、压缩恢复和委派边界

目标：防止压缩、恢复和子 agent 委派绕过主状态机。

任务：

- `compileWorkflowContext` 后调用 `runGate("post-context-compile")`。
- 检查 hard deny、open question、resumeSnapshot、gate、writeTransactions、sourceAnchors 是否保留。
- `kd_subagent` 委派前调用 `runGate("pre-delegation")`。
- 子 agent 输出返回后调用 `runGate("post-delegation")`，禁止直接写 facts/evidence。
- 增加 transcript eval：子 agent 说“验证通过”但主 run 没有真实 evidence 时不能推进。
- 把 hard deny、open question、resumeSnapshot、gate、writeTransactions、sourceAnchors 固定为 post-compact 必留内容。
- 明确 PI system context 适配点；如果 PI 当前不提供足够 API，则用 PromptContract 渲染到现有 workflow prompt，但规则源仍必须是 PromptSectionRegistry 和 GateRunner，不允许回到手写长提示词。
- 将 prompt policy 改为渲染 runtime policy 摘要，避免提示词和代码规则长期漂移。
- Context Compiler 改为消费结构化 Kernel Snapshot，不直接读取分散状态。
- Workflow prompt 只渲染 control frame、gate findings、working set、required facts、evidence summary，不再承载规则源。
- Handoff Capsule 和 post-compact capsule 使用同一生成器。
- 子 agent 输入只能来自 capsule，不允许扩展层临时拼上下文。
- 子 agent 输出只能进入 observation/context entry，不能直接进入 facts/evidence/gate pass。
- PromptSectionRegistry 接管 prompt section 排序、预算、来源标注和不可裁剪段。
- Context Compiler 输出 PromptContract，Prompt Renderer 只负责格式化。
- Required Facts Contract 的评估结果进入 GateFinding，不再只作为 prompt 文本。

验收：

- blocking question 场景下 prompt 不会丢恢复断点。
- 子 agent 只读 review 输出不会变成主验证结果。
- context budget 裁剪时，硬风控段落仍保留。
- compact/handoff 后仍能恢复唯一下一动作。
- 系统上下文和 workflow prompt 的职责边界写入文档。
- prompt 中不存在与 runtime policy 冲突的重复规则。
- 子 agent 全链路有 pre/post delegation GateDecision。
- 每个 prompt section 都有来源、预算、裁剪状态和 traceId。

风险：

- context gate 过严可能阻断正常 prompt。

缓解：

- 本次完整重构允许阻断正常 prompt；优先保证状态机正确，再调优误拦。

### Phase 5：重建审计、评估和发布门禁

目标：让门禁体系可持续维护。

任务：

- 新增 harness audit 脚本，输出固定评分：
  - Tool Coverage
  - Write Safety
  - Phase Safety
  - Verify Safety
  - Context Persistence
  - Delegation Safety
  - Eval Coverage
- 每个评分项列 Top Findings 和 Top Actions。
- `release:check` 纳入 harness audit。完整重构分支允许 audit 红灯暴露问题，但合并和发布前必须通过。
- 审计历史未完成重构项：每项必须显示 `not-started`、`in-progress`、`covered-by-test` 或 `done`。
- 审计 evidence 来源分级覆盖率和 tool result contract 覆盖率。
- harness audit 从 Phase 5 开始就是发布 hard gate；完整重构完成前允许失败但不能忽略，必须进入重构 backlog。
- transcript eval 覆盖真实坏例：循环依赖、shell 抽取执行、外部路径读取、子 agent 误证据、compact 丢约束。
- 建立 architecture fitness tests，扫描禁止模式：
  - policy 规则写在 prompt renderer。
  - tool 直接绕过 GateRunner。
  - loop 直接 spawn shell。
  - evidence 无 sourceTrust。
  - delegation 输出直接写 facts/evidence。
- 建立 prompt regression：同一 KernelSnapshot 渲染出的 prompt 必须稳定、预算可解释、不可裁剪段保留。
- 建立 loop regression：同一事件序列 replay 后得到同一 KernelSnapshot 和 GateDecision。
- 建立 harness maturity score，低于阈值禁止发布。

验收：

- 能复盘本轮门禁缺陷并给出分数。
- 新增风险点能进入 eval backlog。
- 文档、测试和代码入口覆盖一致。
- 未完成重构项不会在 release 说明里被误报为完成。
- 架构 fitness tests 进入 release hard gate。
- prompt、loop、gate、evidence、delegation 五类 regression 进入 release hard gate。

风险：

- 审计脚本变成噪音。

缓解：

- audit 只报告确定性事实，不做 LLM 评分；完整重构验收时必须成为 hard gate。

## 迁移策略

采用 control-plane replacement 方式，不以渐进兼容为优先目标。

- 旧函数只允许作为 adapter，不能继续拥有规则判断。
- 能删除旧规则就删除，不能删除时必须标注 deprecated 和迁移目标。
- 每迁移一个入口，必须补一个回归用例。
- 每个 policy 必须可单测，不依赖 LLM。
- 每个 finding 必须能被最终用户理解。
- 提示词只引用 GateRunner 输出，不复制规则文本。
- 允许一次性改多个模块，但必须保持 trace、ledger、eval 可定位失败。

禁止事项：

- 禁止把所有 policy 直接塞进 `gate-runner.ts`。
- 禁止为了统一接口删除现有 evidence/facts/ledger。
- 禁止让 GateRunner 读取任意文档自由文本后自行推断事实。
- 禁止把用户确认作为 hard-deny 的通用豁免。
- 禁止引入第二套 PI agent loop。

## 回归矩阵

### P0 必须覆盖

- 工作区外 read/write 被拦截。
- Windows PowerShell 变更命令和嵌套解释器被拦截。
- 非 execute 阶段写 source-like 文件被拦截。
- execute 阶段已满足 gate 和 TDD red 时允许写 PLAN 批准文件。
- PLAN 未批准文件被拦截。
- open blocking question 时写代码被拦截。
- goal loop 不执行任意 shell。
- package script 白名单验证可执行。
- 文档读取内容被标记为 untrusted。
- 子 agent 不可写主 evidence/facts。

### P1 应覆盖

- prompt compact 后 hard deny 保留。
- resumeSnapshot 保留并优先处理。
- tool failure 后禁止猜路径。
- SDK 签名 path 工作区外明确报错。
- verify 绿灯缺退出码时阻断。
- KSQL/SQL normal 模式强制证据。
- 多 run 切换后不会污染 active run。

## 本计划自查

### 问题 1：计划跨度偏大

风险：GateRunner、policy registry、context gate、audit 同时做，会造成大面积回归。

修正：本次接受大面积回归风险，但必须有明确 phase、trace 和 regression matrix。不是降低范围，而是提高可观测性。

### 问题 2：可能过度抽象

风险：为了统一门禁而引入复杂框架，反而让调试变难。

修正：GateRunner 只做 checkpoint、policy 调用和 decision 汇总；业务规则迁移到独立 policy 模块，禁止塞进 runner。

### 问题 3：可能重复阻断

风险：迁移期旧 tool gateway 和新 GateRunner 同时报错，用户看到重复提示。

修正：旧规则源必须下线或 adapter 化；重复阻断视为迁移 bug。

### 问题 4：可能影响现有 quick 体验

风险：门禁统一后 quick 模式也被 normal 规则误伤。

修正：GateContext 必须带 run mode；quick/normal 改成显式 policy 分支。短期误伤可接受，但必须由 eval 暴露。

### 问题 5：可能把用户授权做成万能钥匙

风险：soft deny 需要授权，但 hard deny 不能被普通确认绕过。

修正：severity 语义固定；只有 soft-deny 可由结构化授权或计划修订解除，hard-deny 必须改状态、改路径或补证据。

### 问题 6：可能忽略无工具路径

风险：部分风险发生在 prompt/context/phase，不走工具调用。

修正：检查点覆盖 `pre-input`、`pre-phase-transition`、`post-context-compile`，不是只做 tool guardrail。

### 问题 7：可能把子 agent 输出误当证据

风险：review/verify 子 agent 语言上说“通过”，主流程误推进。

修正：`post-delegation` 明确子 agent 输出只作为 context/tool result，不写 facts/evidence；真实 evidence 仍由主 run 写入。

### 问题 8：可能忽略可观测性

风险：门禁变统一后，如果没有 trace，排查更难。

修正：GateDecision 必须有 traceId，并写入 ledger；后续 audit 基于 ledger 而不是重新猜测。

### 问题 9：完整重构可能失控

风险：不在乎短期 bug 容易演变成无边界重写。

修正：本次“不在乎风险”只表示不为兼容牺牲架构，不表示不设验收。所有改动仍受 checkpoint、policy registry、ledger trace、eval matrix 和 release audit 约束。

### 问题 10：把 `allow` 当作 finding severity 会污染语义

风险：finding 本质是问题、要求或提示；`allow` 放在 severity 中会导致 policy 返回“允许 finding”，实现时容易出现 allowed 和 finding 互相打架。

修正：`allow` 从 `GateSeverity` 移除。允许只由 `GateDecision.allowed=true` 表达。

### 问题 11：PI 内置工具 hook 能力可能不足

风险：计划要求所有 tool call 都经过 ToolPipeline，但 PI Runtime 可能没有暴露所有内置工具的 pre/post hook。若文档不说明，会导致实现时以为“已经保护”，实际仍有绕过路径。

修正：无法拦截的内置工具必须在 KCode 模式下禁用或被 wrapper 替代；不能以提示词要求代替 runtime 拦截。

### 问题 12：Completion Promise、PLAN、facts 可能互相争权

风险：Completion Promise 描述目标，PLAN 描述实现路径，facts 描述业务事实。如果三者都能独立解除门禁，会再次形成多事实源。

修正：权威关系固定为：`facts/evidence` 证明事实，`CompletionPromise` 定义完成目标，`PLAN` 定义允许修改范围和执行步骤。三者缺一不可，但不能互相替代。

### 问题 13：Generator-Evaluator 可能退化成同一个 agent 自问自答

风险：如果 evaluator 复用 generator 的上下文和自述，评估器只是形式隔离，仍会继承生成器的盲点。

修正：Evaluator 输入只允许 diff、Completion Promise、PLAN、facts/evidence、真实命令输出和 source refs；禁止读取 generator 的自由文本“我认为已经完成”作为证据。

### 问题 14：sourceTrust 未定义会导致 evidence 分级落不了地

风险：文档多处要求 `sourceTrust`，但若不定义枚举和 gate 语义，实现时会变成字符串备注。

修正：新增 `EvidenceSourceTrust` 和 `EvidenceRecord` 草案，并明确哪些来源可以作为强证据、哪些只能作为残余风险证据。

### 问题 15：learn-claude-code 的“模型决定工具”与 KCode 门禁可能被误读为冲突

风险：Harness 工程强调模型决定何时调用工具，但 KCode 又要求 GateRunner 拦截工具。实现者可能误以为要让模型完全自由调用。

修正：模型可以提出 tool/action intent；Harness 必须执行权限、范围、证据和预算检查。即“model proposes, harness disposes”。

### 问题 16：few-shot 示例可能重新变成提示词手工业

风险：文档允许 prompt few-shot，但如果示例散落在 prompt 文案里，会回到手工 prompt 堆叠。

修正：few-shot 只能来自 ExampleRegistry，必须有适用条件、版本、测试和 token 预算；不能在业务流程中临时拼接。

### 问题 17：background evaluator / cron 容易变成无人监管自动化

风险：借鉴 background tasks 和 cron scheduler 后，系统可能出现无人监督的长期写入或验证循环。

修正：后台任务默认只读；任何写入、阶段推进、ship 或外部系统操作必须回到主 run，并经过 GateRunner 和 Stop Hook。

### 问题 18：大目录重组可能先破坏测试定位

风险：一次性改成 `kernel/ gates/ loop/ context/ tools/ evidence/ audit/` 目录后，旧测试大量失效，短期无法判断是架构问题还是路径问题。

修正：先建立新目录和 adapter，再按入口迁移；但旧规则源必须同步废弃，不能只搬文件不改控制权。

## 推荐落地顺序

本次按完整重构推进：

1. Phase 0：架构断言、入口覆盖清单、迁移开关、旧规则源废弃清单。
2. Phase 1：GateRunner control plane、风险 taxonomy、结构化 nextAction、用户授权模型。
3. Phase 2：工具执行边界全量接入 pre/post tool gate，写入边界全量接入 pre/post write gate。
4. Phase 3：阶段推进、验证命令、goal/repair/demand loop 统一为可审计 loop。
5. Phase 4：上下文内核、handoff/post-compact、子 agent 委派全量接入 gate。
6. Phase 5：harness audit、architecture fitness tests、evidence 来源分级和 release hard gate。

不暂缓 context/delegation/audit/system context/evidence 分级；它们都在本次完整重构范围内。唯一不做的是重写 PI Runtime 本体。

## 验收定义

一次重构完成不能只看代码合并，必须满足：

- 本文 P0 回归矩阵全部有测试或 smoke。
- `npm run check` 通过。
- `npm run smoke:harness` 通过。
- `npm run smoke:harness-evals` 通过。
- `npm run smoke:kcode-command` 通过。
- 至少一个真实坏例被转成确定性回归。
- 文档说明新增 checkpoint、policy 和迁移状态。
- 没有新增用户命令作为绕过手段。

## 最终成熟度验收

完整重构完成后，KCode agent 必须达到以下成熟度：

### Prompt 成熟度

- Prompt 由 registry 渲染，section 顺序、预算、来源和裁剪状态可追踪。
- Prompt 不再复制 runtime policy 规则，只引用 policy summary 和 gate findings。
- 同一 KernelSnapshot 渲染结果稳定，可被 snapshot test 覆盖。
- 外部输入全部标记为 untrusted，不能成为系统指令。
- Prompt 中每个“下一步”都能映射到 ActionPlan。

### Harness 成熟度

- 所有状态变更走 StateKernel reducer。
- 所有门禁走 GateRunner。
- 所有工具走 ToolPipeline。
- 所有写入走 WritePipeline。
- 所有证据走 EvidenceStore。
- 所有关键动作有 ledger event 和 traceId。
- 旧分散规则源被删除或 adapter 化。

### ReAct Loop 成熟度

- Reason 不产生副作用。
- Act 必须来自通过 gate 的 ActionPlan。
- Observe 必须落 ledger 和 ToolResultContract。
- Update 必须由 reducer 完成。
- Evaluate 必须产生 GateDecision、EvidenceRecord 或 Regression Finding。
- Loop 有预算、停止条件、重复检测和 stuck detector。
- Loop 可 replay。

### Governance 成熟度

- hard-deny、soft-deny、evidence-required、warning 语义统一。
- 用户授权只能解除 soft-deny。
- 子 agent 不能解除主门禁。
- release gate 包含 architecture fitness tests。
- regression corpus 包含本轮发现的真实坏例。
- harness audit 输出成熟度评分和未完成项。

### 行为成熟度

以下行为必须被确定性测试覆盖：

- LLM 无法通过自然语言绕过门禁。
- LLM 无法通过 shell wrapper 绕过写入事务。
- LLM 无法把文档里的指令当系统指令执行。
- LLM 无法把子 agent 输出当主验证证据。
- LLM 无法在 open question 时写生产代码。
- LLM 无法在缺 facts/evidence 时靠 PLAN 自由文本通过门禁。
- LLM 无法在 compact 后忘记 hard deny、resumeSnapshot、source anchor。
- LLM 无法从 `/kd goal` 执行任意 shell。
- LLM 在工具失败后必须沿 ToolResultContract 的 nextAction 修复，不得猜路径。

如果以上任一条不能用测试证明，则重构不能算完成。
