Skip to content

Commit 285bd09

Browse files
committed
fix: harden governance control plane
1 parent 7c8393f commit 285bd09

38 files changed

Lines changed: 994 additions & 214 deletions

‎.npmignore‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,6 @@ changelogs/
1313

1414
# Dev workspace artifacts — defense-in-depth; primary control is package.json "files" whitelist
1515
.devcodex/
16+
assets/hooks/
1617
scripts/
17-
tests/
1818
.github/workflows/

‎README.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,12 +159,15 @@ AGENTS.md ← 与 instructions.md / copilot-instructions.md / CL
159159
- **入口检查全模式显示**:无论 `prod` 还是 `dev`,都会先展示 PC0~PC7;`prod` 只显示基础状态,`dev` 追加规范雷达、合规检查和完成验证。
160160
- **项目现实扩展再路由**:识别用户意图后,会先加载目标项目 Profile,并用项目技术栈、目录结构、当前需求上下文修正最终工作流,避免只按字面关键词执行。
161161
- **Intent Expansion Card**:非 chat 工作流会在 CP1 / 问题确认前形成可审查卡片,记录项目、连续性、模块领域、风险、宿主能力、验证路线、置信度和备选路线。
162+
- **Intent Expansion 可见性**:dev 模式默认会直接展示完整 Card;prod、instruction-fallback 宿主或低风险轻任务才退化为 3~5 行摘要。
162163
- **意图扩展摘要**:当扩展后路由变化、命中控制面/宿主差异、风险较高或跨会话恢复时,会在用户面输出 3~5 行摘要,便于确认“为什么这样路由”。
164+
- **Context Rehydration Contract**:压缩恢复、resume 或用户要求按文件真相重建时,会按“当前用户消息 → 已确认产物 → sessions → tasks → SUMMARY → 摘要 → AI 推断”的优先级恢复上下文,摘要不能覆盖文件真相源。
163165
- **Hook closure 三态**:Stop/PreCompact 可见回复验证区分 `verified-present`、`verified-missing`、`unverified`;无法解析最终 assistant 内容时只提示无法验证,并给出 payload capture 指引,不再断言“未输出”。
164166
- **长流程执行契约**:Auto、控制面、多批次、预计修改 ≥10 文件或发布前置任务会触发 ExecutionContract;测试路线不明显时触发 TestRoute;正式发版前触发 ReleaseVerification;控制面消费链联动时建立 Concept Sync Map;宿主契约变化时触发 `host-contract-verification`。
167+
- **执行期 CP3 回退**:若执行过程中实际修改范围扩展到 CP3 门槛(≥5 文件、高风险、控制面联动),必须暂停执行并先补做 CP3,再继续改动。
165168
- **边界先确认**:若已判断为新需求切换,且当前工作区还有未提交变更,会先提醒是否应先提交当前变更。
166169
- **报告推荐项**:当报告中存在多个可执行建议或后续路径时,会明确给出推荐结论和推荐理由;没有建议时也会写明“推荐:无后续动作”。
167-
- **确认交互适配**:ConfirmationRequest 是确认语义的统一抽象;Claude Code SDK / VS Code 扩展可用按钮,Hook 宿主可用阻断原因,Cursor / JetBrains 等 fallback 宿主使用文本确认。
170+
- **确认交互适配**:ConfirmationRequest 是确认语义的统一抽象,不要求 runtime 逐字输出同名对象;Claude Code SDK / VS Code 扩展可用按钮,Hook 宿主可用阻断原因,Cursor / JetBrains 等 fallback 宿主使用文本确认。
168171
- **高联动默认联查**:当任务涉及控制面规则、模板、接口契约/验证产物、工作区真相源/部署副本或发布口径变更时,会默认联查相关文件;若同时命中多真相源同步或模板-示例-校验链,会升级为交叉验证或 `CRS`。
169172
- **官方资料优先**:涉及平台能力、框架 API、版本兼容性或工具语义判断时,优先读取官方文档,再降级到其他资料。
170173
- **提交标题收短**:用户要求提交时,DevCodex 会优先生成一句简洁的 commit subject,而不是把整段会话摘要塞进标题。
@@ -277,7 +280,7 @@ devcodex/
277280
├── skills/ # Skill 详细检查标准(43 个,按 01-common §按需读取表 路由读取)
278281
├── prompts/ # Prompt 模板(26 个)
279282
├── hooks/ # Workspace Hooks 配置与分发到 `.github/hooks/_runtime/` 的运行时
280-
├── codex/ # Codex Hook 配置源,分发到 `.codex/hooks.json`
283+
├── codex/ # Codex adapter 源模板(分发到 `.codex/hooks.json`,不是工作区部署副本 `.codex/`)
281284
├── data/ # 运行时数据模板(分发到目标项目的空骨架)
282285
│ ├── README.md
283286
│ └── templates/ # 空模板:violations / pending-fixes / pending-issues / process-improvements / gap-registry

‎assets/hooks/README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# assets/hooks
2+
3+
> Hooks 运行时相关的源码/模板占位目录,用于维护者区分“源仓说明资产”和真正分发到宿主工作区的运行时副本。
4+
5+
## 源仓维护说明
6+
7+
- 当前正式分发的 Hook runtime 位于 `hooks/_runtime/`,并由 CLI 同步到目标项目的 `.github/hooks/_runtime/`、`.claude/hooks/_runtime/` 或 `.codex/hooks/_runtime/`
8+
- `assets/hooks/` 仅保留源仓侧的说明占位,便于后续如需补充截图、示意图或额外模板时有明确归属
9+
- 本目录默认不会打包发布;发布包以 `package.json` 的 `files` 白名单和 `scripts/test-pack-clean.js` 为准

‎codex/README.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# codex
2+
3+
> Codex adapter 源模板目录,用于维护工作区根 `AGENTS.md` / `.agents/skills/` / `.codex/hooks.json` 这一条分发链的源码侧资产。
4+
5+
## 边界说明
6+
7+
- 这里保存的是源模板与说明,不是工作区部署副本
8+
- CLI 会把 `codex/hooks.json` 分发到目标项目的 `.codex/hooks.json`
9+
- 真正运行时的 Hook 副本位于目标工作区 `.codex/hooks/_runtime/`
10+
- 若需要核对目标项目当前实际状态,请使用 `devcodex doctor` 或直接检查工作区根 `.codex/`

‎hooks/_runtime/lifecycle.cjs‎

Lines changed: 133 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ const STICKY_PROJECT_TTL_MS = 30 * 60 * 1000
2929
const CP1_FILE = '01-需求概述.md'
3030
const CP2_FILE = '02-技术方案.md'
3131
const CP3_FILE = '04-实施计划.md'
32+
const CP3_RUNTIME_FILE_THRESHOLD = 5
3233
const EXECUTION_MODE = { CONFIRM: 'confirm', AUTO: 'auto' }
3334
const ENFORCEMENT_MODE = (() => {
3435
const mode = String(process.env.DEVCODEX_HOOK_ENFORCEMENT || 'safety-only').trim().toLowerCase()
@@ -398,6 +399,8 @@ function toolBlockOutput(eventName, reason, detail) {
398399
function blockOutput(platform, eventName, reason, detail) {
399400
const event = normalizeHookEvent(eventName)
400401
const message = detail || reason
402+
// ConfirmationRequest is a host-agnostic semantic contract; runtime outputs
403+
// only need to match each host's actual hook schema, not emit a literal object.
401404
if (platform === 'codex') {
402405
if (['pretooluse', 'permissionrequest'].includes(event)) {
403406
return toolBlockOutput(eventName, reason, detail)
@@ -979,6 +982,7 @@ function buildDefaultState(mode) {
979982
precheckStatus: 'unverified', precheck: false, compliance: false, artifactPaths: false
980983
},
981984
stickyProject: { project: CONTEXT_PROJECT || '', source: CONTEXT_PROJECT ? 'context' : '', sessionKey: '', updatedAt: '', updatedAtMs: 0 },
985+
cp3Runtime: {},
982986
mutated: false, reportTouched: false, memoryTouched: false,
983987
dangerousApprovals: {},
984988
lastEvent: '', lastReason: ''
@@ -1007,6 +1011,7 @@ function loadState(modeHint) {
10071011
bootstrap: { ...current.bootstrap, ...(saved.bootstrap || {}) },
10081012
visible: { ...current.visible, ...(saved.visible || {}) },
10091013
stickyProject: { ...current.stickyProject, ...(saved.stickyProject || {}), ...(metaState?.stickyProject || {}) },
1014+
cp3Runtime: { ...current.cp3Runtime, ...(saved.cp3Runtime || {}) },
10101015
dangerousApprovals: { ...current.dangerousApprovals, ...(saved.dangerousApprovals || {}) }
10111016
}
10121017
}
@@ -1037,6 +1042,7 @@ function resetState(mode, previousState) {
10371042
state.activeProjectSource = previousState?.activeProjectSource || (CONTEXT_PROJECT ? 'context' : '')
10381043
state.lastMultiProjectWarningKey = previousState?.lastMultiProjectWarningKey || ''
10391044
state.stickyProject = { ...state.stickyProject, ...(previousState?.stickyProject || {}) }
1045+
state.cp3Runtime = { ...(previousState?.cp3Runtime || {}) }
10401046
state.dangerousApprovals = { ...(previousState?.dangerousApprovals || {}) }
10411047
saveState(state)
10421048
return state
@@ -1275,12 +1281,44 @@ function findIncompleteTask(state) {
12751281
if (fs.existsSync(path.join(d.fullPath, '.archived'))) return false
12761282
if (!hasTaskArtifact(d, 'CP1')) return false
12771283
const cp = readCpConfirmations(d.fullPath)
1278-
if (cp.CP3) return false
1284+
if (cp.CP3) {
1285+
clearTaskCp3RuntimeRecord(state, d)
1286+
return false
1287+
}
12791288
if (!hasTaskArtifact(d, 'CP3')) return true
12801289
return !cp.CP3
12811290
}) || null
12821291
}
12831292

1293+
function getTaskRuntimeKey(task) {
1294+
return `${task.kind}:${path.normalize(task.fullPath).toLowerCase()}`
1295+
}
1296+
1297+
function getTaskCp3RuntimeRecord(state, task) {
1298+
if (!isPlainObject(state.cp3Runtime)) state.cp3Runtime = {}
1299+
const key = getTaskRuntimeKey(task)
1300+
if (!isPlainObject(state.cp3Runtime[key])) {
1301+
state.cp3Runtime[key] = {
1302+
kind: task.kind,
1303+
name: task.name,
1304+
reqPath: task.fullPath,
1305+
trackedFiles: [],
1306+
triggered: false,
1307+
triggerType: '',
1308+
triggerReason: '',
1309+
triggerCount: 0,
1310+
triggeredAt: '',
1311+
updatedAt: ''
1312+
}
1313+
}
1314+
return state.cp3Runtime[key]
1315+
}
1316+
1317+
function clearTaskCp3RuntimeRecord(state, task) {
1318+
if (!isPlainObject(state.cp3Runtime)) return
1319+
delete state.cp3Runtime[getTaskRuntimeKey(task)]
1320+
}
1321+
12841322
// Extract file paths from a PreToolUse payload (Claude Code + Copilot field names)
12851323
function extractToolPaths(payload) {
12861324
if (!payload) return []
@@ -1319,6 +1357,72 @@ function extractToolPaths(payload) {
13191357
return out.map(p => { try { return path.normalize(p) } catch { return p } }).filter(Boolean)
13201358
}
13211359

1360+
function extractSourceMutationTargets(payload, state) {
1361+
return [...new Set(extractToolPaths(payload))]
1362+
.map(resolveRelativeToContext)
1363+
.filter(target => SOURCE_EXT_RE.test(target) && !isDevCodexManagedPath(target, state))
1364+
}
1365+
1366+
function isHighRiskCp3RuntimeTarget(target) {
1367+
const rel = toWorkspaceRelativePath(target)
1368+
return [
1369+
/(^|\/)package\.json$/i,
1370+
/(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$/i,
1371+
/(^|\/)\.env(?:\.[^\/]+)?$/i,
1372+
/(^|\/)(Dockerfile|docker-compose(?:\.[^\/]+)?\.ya?ml)$/i,
1373+
/(^|\/)\.github\/workflows\/.+\.ya?ml$/i,
1374+
/(^|\/)(?:prisma\/schema\.prisma|schema\.prisma)$/i,
1375+
/(^|\/)(?:migrations?|db\/migrations?)\//i
1376+
].some(re => re.test(rel))
1377+
}
1378+
1379+
function assessBugCp3RuntimeEscalation(task, payload, state) {
1380+
const targets = extractSourceMutationTargets(payload, state)
1381+
if (!targets.length) return null
1382+
1383+
const record = getTaskCp3RuntimeRecord(state, task)
1384+
const tracked = new Set(Array.isArray(record.trackedFiles) ? record.trackedFiles : [])
1385+
const nextTargets = targets.map(toWorkspaceRelativePath).filter(Boolean)
1386+
for (const rel of nextTargets) tracked.add(rel)
1387+
1388+
record.trackedFiles = [...tracked].sort()
1389+
record.updatedAt = new Date().toISOString()
1390+
1391+
const highRiskTarget = targets.find(isHighRiskCp3RuntimeTarget)
1392+
if (highRiskTarget) {
1393+
const rel = toWorkspaceRelativePath(highRiskTarget)
1394+
record.triggered = true
1395+
record.triggerType = 'high-risk'
1396+
record.triggerReason = `执行中新增高风险文件 ${rel}`
1397+
record.triggerCount = tracked.size
1398+
record.triggeredAt = record.updatedAt
1399+
return {
1400+
type: 'high-risk',
1401+
reason: record.triggerReason,
1402+
count: tracked.size,
1403+
threshold: CP3_RUNTIME_FILE_THRESHOLD,
1404+
trackedFiles: record.trackedFiles
1405+
}
1406+
}
1407+
1408+
if (tracked.size >= CP3_RUNTIME_FILE_THRESHOLD) {
1409+
record.triggered = true
1410+
record.triggerType = 'file-threshold'
1411+
record.triggerReason = `执行中已触达 ${tracked.size} 个源码/配置文件(阈值 ${CP3_RUNTIME_FILE_THRESHOLD})`
1412+
record.triggerCount = tracked.size
1413+
record.triggeredAt = record.updatedAt
1414+
return {
1415+
type: 'file-threshold',
1416+
reason: record.triggerReason,
1417+
count: tracked.size,
1418+
threshold: CP3_RUNTIME_FILE_THRESHOLD,
1419+
trackedFiles: record.trackedFiles
1420+
}
1421+
}
1422+
1423+
return null
1424+
}
1425+
13221426
// Map a file path to its owning task scope (.devcodex/requirements/<X>/... or .devcodex/bugs/<X>/...).
13231427
// returns null when the path is not under any supported task directory.
13241428
function getTaskScopeFromPath(p, state) {
@@ -1390,7 +1494,10 @@ function findIncompleteTaskForPaths(payload, state) {
13901494
if (fs.existsSync(path.join(task.fullPath, '.archived'))) continue
13911495
if (!hasTaskArtifact(task, 'CP1')) continue
13921496
const cp = readCpConfirmations(task.fullPath)
1393-
if (cp.CP3) continue
1497+
if (cp.CP3) {
1498+
clearTaskCp3RuntimeRecord(state, task)
1499+
continue
1500+
}
13941501
if (!hasTaskArtifact(task, 'CP3')) return task
13951502
if (!cp.CP3) return task
13961503
}
@@ -1406,6 +1513,20 @@ function checkCpGate(payload, state) {
14061513
if (!hasTaskArtifact(task, 'CP2') || !confirmed.CP2) {
14071514
return { phase: 'CP2', reqName: task.name, reqPath: task.fullPath, kind: task.kind }
14081515
}
1516+
if (task.kind === 'bugs' && !confirmed.CP3) {
1517+
const runtimeTrigger = assessBugCp3RuntimeEscalation(task, payload, state)
1518+
if (!runtimeTrigger) return null
1519+
return {
1520+
phase: 'CP3',
1521+
reqName: task.name,
1522+
reqPath: task.fullPath,
1523+
kind: task.kind,
1524+
code: runtimeTrigger.type === 'high-risk'
1525+
? 'cp-gate-CP3-runtime-risk'
1526+
: 'cp-gate-CP3-runtime-threshold',
1527+
runtimeTrigger
1528+
}
1529+
}
14091530
return { phase: 'CP3', reqName: task.name, reqPath: task.fullPath, kind: task.kind }
14101531
}
14111532

@@ -1505,23 +1626,28 @@ function buildCpDenyOutput(state, platform, eventName, gate, toolName) {
15051626
CP2: 'CP2 (技术方案) 未完成 — 请先输出对应的 CP2 方案产物(如 02-技术方案.md 或 CP2 报告产物),并在 .memory/sessions.md 记录用户确认(✅)后再编码。',
15061627
CP3: `CP3 (实施计划) 未完成 — 请先输出 ${CP3_FILE} 并在 .memory/sessions.md 记录用户确认(✅)后再编码。`
15071628
}
1508-
const msg = msgs[gate.phase]
1629+
const runtimeDetail = gate.runtimeTrigger
1630+
? `${gate.runtimeTrigger.reason},请先回到 CP3 更新实施计划并获得确认后再继续。`
1631+
: ''
1632+
const msg = runtimeDetail || msgs[gate.phase]
15091633
return buildInterceptionOutput(
1510-
state, platform, eventName, INTERCEPTION_ACTION.REQUIRE_COMPLETION, `cp-gate-${gate.phase}`,
1634+
state, platform, eventName, INTERCEPTION_ACTION.REQUIRE_COMPLETION, gate.code || `cp-gate-${gate.phase}`,
15111635
`CP gate: ${gate.phase} not confirmed for "${gate.reqName}" — ${toolName} denied`,
15121636
msg,
15131637
`Complete and confirm ${gate.phase}, then retry the source mutation.`
15141638
)
15151639
}
15161640

15171641
function buildCpWarningOutput(state, platform, eventName, gate, toolName) {
1518-
const detail = gate.phase === 'CP2'
1642+
const detail = gate.runtimeTrigger
1643+
? `${gate.runtimeTrigger.reason},请先回到 CP3 更新实施计划并获得确认。 Tool allowed in safety-only mode.`
1644+
: gate.phase === 'CP2'
15191645
? 'CP2 (技术方案) 未完成;请尽快补齐方案产物与用户确认记录。'
15201646
: `CP3 (实施计划) 未完成;请尽快补齐 ${CP3_FILE} 与用户确认记录。`
15211647
return buildInterceptionOutput(
1522-
state, platform, eventName, INTERCEPTION_ACTION.REQUIRE_COMPLETION, `cp-gate-${gate.phase}`,
1648+
state, platform, eventName, INTERCEPTION_ACTION.REQUIRE_COMPLETION, gate.code || `cp-gate-${gate.phase}`,
15231649
`CP gate warning: ${gate.phase} not confirmed for "${gate.reqName}" before ${toolName}`,
1524-
`${detail} Tool allowed in safety-only mode.`,
1650+
gate.runtimeTrigger ? detail : `${detail} Tool allowed in safety-only mode.`,
15251651
`Complete and confirm ${gate.phase}, then retry the source mutation.`
15261652
)
15271653
}

0 commit comments

Comments
 (0)