From bfd9e43e6a9eb5e1506b89bb3a6159c3d7730415 Mon Sep 17 00:00:00 2001 From: ssw Date: Tue, 28 Jul 2026 20:38:13 +0800 Subject: [PATCH] =?UTF-8?q?fix(gates):=20T9=20=E2=80=94=20AppContext=20?= =?UTF-8?q?=E5=AD=97=E6=AE=B5=E6=98=A0=E5=B0=84=E4=BF=AE=E6=AD=A3,=20K=20g?= =?UTF-8?q?ate=20=E5=AD=90=E5=91=BD=E4=BB=A4=E6=8E=A5=E5=85=A5,=20designRe?= =?UTF-8?q?sources=20=E8=90=BD=E5=9C=B0=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. buildContextSummary 字段名映射修复 (实 AppContext schema): - full.currentSystemId → summary.systemId (不是 full.systemId) - full.currentUser → summary.user (不是 full.user) - tokenStatus union: 'valid' | 'expired' | 'unknown' (不是 'ok') - resourceCounts 从 releasedForms/unreleasedForms/modifiedAfterPublishForms/workflowList/menus/existingTables 派生 2. wire dacli gate k 子命令 (CLI 最小接入, 走 checkKCheckpoint) 3. _checkpoint_k.ts 实际使用 designResources: phase=summary 校验 summaryResources ⊇ designResources (design→delivery 一致性) 4. 加 4 新单测: 真实 AppContext literal / currentUser undefined / designed but not delivered / 全交付 --- src/commands/_gates/_checkpoint_k.ts | 48 +++++++++++--- src/commands/app/_context_summary.ts | 50 ++++++++++---- src/commands/gate/index.ts | 79 +++++++++++++++++++++++ src/program.ts | 2 + tests/unit/app_context_summary.test.ts | 75 ++++++++++++++++++--- tests/unit/checkpoint_k_semantics.test.ts | 60 +++++++++++++++-- 6 files changed, 279 insertions(+), 35 deletions(-) create mode 100644 src/commands/gate/index.ts diff --git a/src/commands/_gates/_checkpoint_k.ts b/src/commands/_gates/_checkpoint_k.ts index 986a533..d20dc73 100644 --- a/src/commands/_gates/_checkpoint_k.ts +++ b/src/commands/_gates/_checkpoint_k.ts @@ -6,20 +6,30 @@ * 设计: * - 设计阶段 (phase='design'): 不实施检查, 返回 not-applicable (退出 0). * 理由: 设计阶段还没创建资源, summaryResources 为空是预期的. - * - 总结阶段 (phase='summary'): 回查 summaryResources 实际是否仍存在, 缺则非零退出. - * 理由: 总结文档引用的资源可能已被中途删/改, 引用失效的 doc 价值低. + * - 总结阶段 (phase='summary'): + * 1. **设计资源落地校验**: summaryResources ⊇ designResources (设计阶段说要做的事, 总结阶段必须看到交付) + * - 任一 designResource 不在 summaryResources → missing (reason='designed but not delivered') + * 2. **存活校验**: 每个 summaryResource 走 liveLookup, 缺则 missing (reason='no longer exists') + * 任一失败 → failure (退出 1) + 列出 missing. * * 设计原则: * - 纯函数 (除 liveLookup 外零 I/O): caller 注入 lookup, 模块不依赖 webapi loader / dict / menu * - liveLookup 默认 null → 视为缺失 (缺省情况, 总结阶段无 lookup 不通过) - * - 失败信息: 列出 missing 资源 (供 caller 写日志/stdout) + * - 失败信息: 列出 missing 资源 + reason (供 caller 写日志/stdout) */ +export interface KResource { + kind: string + id: string + /** 缺失原因 (由 checkKCheckpoint 填充): 'designed but not delivered' | 'no longer exists' */ + reason?: string +} + export interface KInput { phase: 'design' | 'summary' appCode: string - /** 设计阶段声明的资源 (设计阶段此字段在 doc 里, summary 阶段可对照) */ + /** 设计阶段声明的资源 (总结阶段应 ⊇ 此集合) */ designResources: Array<{ kind: string; id: string }> - /** 总结阶段声明的资源 (必须回查存在) */ + /** 总结阶段声明的资源 (必须回查存在 + 必须 ⊇ designResources) */ summaryResources: Array<{ kind: string; id: string }> /** 注入: 实际查询函数, 返回 id 表示存在, null 表示缺失 */ liveLookup?: (res: { kind: string; id: string }) => Promise @@ -28,25 +38,43 @@ export interface KInput { export interface KResult { status: 'not-applicable' | 'ok' | 'failure' exitCode: 0 | 1 - missing?: Array<{ kind: string; id: string }> + missing?: KResource[] reason?: string } /** * K 关卡主函数 * - phase=design: 永远 not-applicable (退出 0) - * - phase=summary: 逐个回查 summaryResources, 全部存在 → ok; 任一缺失 → failure (退出 1) + 列出 missing + * - phase=summary: + * a. 校验 summaryResources ⊇ designResources + * b. 逐个回查 summaryResources (liveLookup) + * 任一失败 → failure (退出 1) + 列出 missing (含 reason) */ export async function checkKCheckpoint(input: KInput): Promise { if (input.phase === 'design') { return { status: 'not-applicable', exitCode: 0 } } + const missing: KResource[] = [] + + // a. 设计资源落地校验: summaryResources 必须 ⊇ designResources + for (const dr of input.designResources) { + const delivered = input.summaryResources.some( + (sr) => sr.kind === dr.kind && sr.id === dr.id, + ) + if (!delivered) { + missing.push({ kind: dr.kind, id: dr.id, reason: 'designed but not delivered' }) + } + } + + // b. 存活校验: 每个 summaryResource 走 liveLookup const lookup = input.liveLookup ?? (async () => null) - const missing: KResult['missing'] = [] for (const r of input.summaryResources) { const got = await lookup(r) - if (!got) missing.push(r) + if (!got) { + missing.push({ kind: r.kind, id: r.id, reason: 'no longer exists' }) + } } + if (missing.length > 0) { return { status: 'failure', @@ -56,4 +84,4 @@ export async function checkKCheckpoint(input: KInput): Promise { } } return { status: 'ok', exitCode: 0 } -} +} \ No newline at end of file diff --git a/src/commands/app/_context_summary.ts b/src/commands/app/_context_summary.ts index b2fcd47..44b5213 100644 --- a/src/commands/app/_context_summary.ts +++ b/src/commands/app/_context_summary.ts @@ -4,36 +4,64 @@ * `dacli app context --summary` 摘要 (webapi hardening, v0.23+) * * 设计: - * - AI 工作流通常只需要: appCode / dbLinkId / tokenStatus / user / resourceCounts / warnings - * - 完整 context 含 menuList / permissionTree / existingEnCodes (可能数百条), 占用 AI context window + * - AI 工作流通常只需要: appCode / systemId / dbLinkId / tokenStatus / user / resourceCounts / warnings + * - 完整 context 含 existingEnCodes (数百条) / menus (数十条) / topLevelMenus / workflowList, + * 占用 AI context window * - 摘要模式剔除重字段, warnings 限长 ≤5 * + * 字段映射 (与 src/core/types.ts AppContext 对齐): + * - full.currentSystemId → summary.systemId (不是 full.systemId — AppContext 无此字段) + * - full.currentUser → summary.user (不是 full.user — AppContext 无此字段) + * - full.tokenStatus: 'valid' | 'expired' | 'unknown' (AppContext 的 union, 不是 'ok') + * - resourceCounts 从 releasedForms/unreleasedForms/modifiedAfterPublishForms/workflowList/menus/existingTables 派生 + * * 注意: 这是一个**纯函数** (零 I/O, 零副作用), 方便 vitest 单测 + 任何 caller 复用. */ export interface ContextSummary { appCode: string systemId: string dbLinkId: string - tokenStatus: 'ok' | 'expired' | 'unknown' + tokenStatus: 'valid' | 'expired' | 'unknown' user: { id: string; account: string; realName?: string } - resourceCounts?: { forms: number; flows: number; menus: number; dicts: number } + resourceCounts?: { forms: number; flows: number; menus: number; tables: number; dicts: number } warnings: Array<{ kind: string; message: string }> } -/** 摘要 — 剔除 menuList/permissionTree, warnings 限长 ≤5 */ +/** 摘要 — 剔除重字段, warnings 限长 ≤5 */ export function buildContextSummary(full: any): ContextSummary { const warnings = Array.isArray(full?.warnings) ? full.warnings.slice(0, 5) : [] + // resourceCounts 派生: 仅当 full 含相关字段 (real AppContext) 时填充, 否则 undefined + // (测试传 fake 对象时, 没这些字段就不填, 避免误报 0) + const hasResourceFields = + Array.isArray(full?.unreleasedForms) || + Array.isArray(full?.releasedForms) || + Array.isArray(full?.modifiedAfterPublishForms) || + Array.isArray(full?.workflowList) || + Array.isArray(full?.menus) || + Array.isArray(full?.existingTables) + const resourceCounts = hasResourceFields + ? { + forms: + (full?.unreleasedForms?.length ?? 0) + + (full?.releasedForms?.length ?? 0) + + (full?.modifiedAfterPublishForms?.length ?? 0), + flows: full?.workflowList?.length ?? 0, + menus: full?.menus?.length ?? 0, + tables: full?.existingTables?.length ?? 0, + dicts: 0, // AppContext 不收集 dicts (B-12 已知 limitation, 后续可扩展) + } + : undefined return { appCode: full?.appCode ?? '', - systemId: full?.systemId ?? '', + systemId: full?.currentSystemId ?? '', dbLinkId: full?.dbLinkId ?? '', tokenStatus: (full?.tokenStatus ?? 'unknown') as ContextSummary['tokenStatus'], user: { - id: full?.user?.id ?? '', - account: full?.user?.account ?? '', - realName: full?.user?.realName, + id: full?.currentUser?.id ?? '', + account: full?.currentUser?.account ?? '', + realName: full?.currentUser?.realName, }, - resourceCounts: full?.resourceCounts, + resourceCounts, warnings, } -} +} \ No newline at end of file diff --git a/src/commands/gate/index.ts b/src/commands/gate/index.ts new file mode 100644 index 0000000..f525ca6 --- /dev/null +++ b/src/commands/gate/index.ts @@ -0,0 +1,79 @@ +/** + * commands/gate/index.ts — `dacli gate k` (v0.23+ K 关卡 CLI 接入) + * + * T9 spec review 要求: _checkpoint_k.ts 创建了, 但 program.ts 没 wire. + * 最小 wiring: 让 caller 可通过 CLI 调用 K gate 验证资源落地. + * + * 用法: + * dacli gate k --phase=design (设计阶段占位, 返 not-applicable) + * dacli gate k --phase=summary --summary-resources=form:F1,flow:W1,menu:M1 + * + * 设计原则: + * - 纯 CLI 包装, 不引入新依赖 (liveLookup 默认 null → summary 阶段默认全失败, + * caller 必须自己注入 lookup 才能跑通) + * - 退出码语义: not-applicable=0 / ok=0 / failure=1, 跟模块语义一致 + * - 命令 tree 简单: 当前只暴露 K 关卡 (其他关卡如 G 走 _gate_webapi 顶级命令) + */ +import { Command } from 'commander' +import { checkKCheckpoint } from '../_gates/_checkpoint_k.ts' +import { log } from '../../core/log.ts' + +interface KGateOpts { + phase: 'design' | 'summary' + summaryResources?: string + app?: string +} + +/** + * 解析 "form:F1,flow:W1,menu:M1" → [{kind:'form',id:'F1'}, ...] + * 失败 (格式错) 抛 DacliError-like 错 (string, 由 commander catch). + */ +function parseResources(raw: string | undefined): Array<{ kind: string; id: string }> { + if (!raw) return [] + return raw + .split(',') + .map((s) => s.trim()) + .filter(Boolean) + .map((s) => { + const idx = s.indexOf(':') + if (idx <= 0 || idx === s.length - 1) { + throw new Error(`--summary-resources 格式错: "${s}" (期望 kind:id, e.g. form:F1)`) + } + return { kind: s.slice(0, idx), id: s.slice(idx + 1) } + }) +} + +export function buildGateCommand(): Command { + const k = new Command('k') + .description('K 关卡 (设计/总结 phase 感知, 资源落地 + 存活校验)') + .option('--phase ', 'design | summary', 'design') + .option('--summary-resources ', 'comma-separated kind:id list (e.g. form:F1,flow:W1)') + .option('--app ', '覆盖 token 中的 appCode') + .action(async (opts: KGateOpts) => { + setupOutputIfPresent() + try { + const resources = parseResources(opts.summaryResources) + const r = await checkKCheckpoint({ + phase: opts.phase, + appCode: opts.app ?? '', + designResources: [], // CLI 暂不接 designResources (留 caller 注入) + summaryResources: resources, + // liveLookup 留空 → summary 阶段默认全失败 (caller 必须注入) + }) + console.log(JSON.stringify(r)) + process.exit(r.exitCode) + } catch (e) { + log.error((e as Error).message) + process.exit(1) + } + }) + + return new Command('gate') + .description('CI 关卡 (K 关卡 phase 感知; G 关卡走顶级 _gate_webapi 命令)') + .addCommand(k) +} + +// 复用其他命令的输出过滤 (可空 — CLI 简单优先) +function setupOutputIfPresent() { + // 简单 stdout-only 输出, 不接 setupOutputFilter (CLI 简单优先) +} \ No newline at end of file diff --git a/src/program.ts b/src/program.ts index afdbdb1..183bf23 100644 --- a/src/program.ts +++ b/src/program.ts @@ -35,6 +35,7 @@ import { buildSelfCheckCommand } from './commands/_selfcheck.ts' import { buildDriftCheckCommand } from './commands/_drift_check.ts' import { buildCoverageCommand } from './commands/_coverage.ts' import { buildKbCommand } from './commands/kb/index.ts' +import { buildGateCommand } from './commands/gate/index.ts' // v0.23+ (webapi hardening, Task 9): K 关卡 CLI 接入 export const VERSION = '0.1.0' @@ -74,6 +75,7 @@ export function buildProgram(): Command { program.addCommand(buildDriftCheckCommand()) program.addCommand(buildCoverageCommand()) program.addCommand(buildKbCommand()) + program.addCommand(buildGateCommand()) // v0.23+ (webapi hardening, Task 9): K 关卡 CLI return program } diff --git a/tests/unit/app_context_summary.test.ts b/tests/unit/app_context_summary.test.ts index 7592786..e5dd35e 100644 --- a/tests/unit/app_context_summary.test.ts +++ b/tests/unit/app_context_summary.test.ts @@ -9,20 +9,22 @@ * - 返回 ContextSummary: 剔除重字段, warnings 限长 ≤5 * - 不应包含 menuList/permissionTree (重负载字段) * - 必须保留 user / appCode / dbLinkId / tokenStatus (AI 工作流必读) + * - 字段映射: full.currentSystemId → summary.systemId, full.currentUser → summary.user * * v0.23+ (Task 9, webapi hardening): 加 --summary 模式, 减少 AI context window 占用 */ import { describe, expect, it } from 'vitest' import { buildContextSummary } from '../../src/commands/app/_context_summary.ts' +import type { AppContext } from '../../src/core/types.ts' describe('app context --summary (Task 9a)', () => { it('摘要模式不含完整 menuList/permissionTree', () => { const full = { appCode: 'tdd5', - systemId: '847', + currentSystemId: '847', dbLinkId: '208', - tokenStatus: 'ok', - user: { id: 'u1', account: 'admin' }, + tokenStatus: 'valid', + currentUser: { id: 'u1', account: 'admin' }, menuList: Array(50).fill({ enCode: 'm' }), permissionTree: { /* huge */ }, warnings: [], @@ -30,7 +32,7 @@ describe('app context --summary (Task 9a)', () => { const summary = buildContextSummary(full) expect(summary.appCode).toBe('tdd5') expect(summary.dbLinkId).toBe('208') - expect(summary.tokenStatus).toBe('ok') + expect(summary.tokenStatus).toBe('valid') expect(summary).not.toHaveProperty('menuList') expect(summary).not.toHaveProperty('permissionTree') expect(summary).toHaveProperty('user') @@ -40,12 +42,69 @@ describe('app context --summary (Task 9a)', () => { const full = { warnings: Array(10).fill({ kind: 'x', message: 'y' }), appCode: 'x', - systemId: 'y', + currentSystemId: 'y', dbLinkId: 'z', - tokenStatus: 'ok', - user: { id: '1', account: 'a' }, + tokenStatus: 'valid', + currentUser: { id: '1', account: 'a' }, } as any const s = buildContextSummary(full) expect(s.warnings.length).toBeLessThanOrEqual(5) }) -}) + + // Integration-style: 构造真实 AppContext literal (src/core/types.ts), 验证字段映射 + // 修复前 symptom: plan 假设 full.systemId / full.user / full.resourceCounts, 实际 AppContext + // 字段名是 currentSystemId / currentUser / 无 resourceCounts (要从数组派生) + it('buildContextSummary 真实 AppContext 字段映射正确', () => { + const full: AppContext = { + appCode: 'tdd5', + currentSystemId: '847134936094737349', + dbLinkId: '2081671840002990080', + tokenStatus: 'valid', + currentUser: { id: 'u1', account: 'admin', realName: 'Admin' }, + existingEnCodes: ['f1'], + unreleasedForms: [], + releasedForms: ['f1'], + modifiedAfterPublishForms: [], + workflowList: ['w1'], + existingTables: ['t1'], + menus: ['m1'], + topLevelMenus: [], + currentVersion: '0.1.0', + warnings: [], + } + const s = buildContextSummary(full) + expect(s.systemId).toBe('847134936094737349') + expect(s.user.account).toBe('admin') + expect(s.user.realName).toBe('Admin') + expect(s.tokenStatus).toBe('valid') + expect(s.resourceCounts).toEqual({ + forms: 1, // unreleased 0 + released 1 + modified 0 + flows: 1, // workflowList + menus: 1, // menus + tables: 1, // existingTables + dicts: 0, + }) + }) + + it('currentUser 缺省 → user 默认空对象', () => { + const full: AppContext = { + appCode: 'tdd5', + dbLinkId: '', + tokenStatus: 'expired', + existingEnCodes: [], + unreleasedForms: [], + releasedForms: [], + modifiedAfterPublishForms: [], + workflowList: [], + existingTables: [], + menus: [], + topLevelMenus: [], + currentSystemId: '', + currentVersion: '0.1.0', + warnings: [], + // currentUser: undefined + } + const s = buildContextSummary(full) + expect(s.user).toEqual({ id: '', account: '' }) + }) +}) \ No newline at end of file diff --git a/tests/unit/checkpoint_k_semantics.test.ts b/tests/unit/checkpoint_k_semantics.test.ts index 76055e9..dd53348 100644 --- a/tests/unit/checkpoint_k_semantics.test.ts +++ b/tests/unit/checkpoint_k_semantics.test.ts @@ -2,14 +2,16 @@ * tests/unit/checkpoint_k_semantics.test.ts * * 覆盖 src/commands/_gates/_checkpoint_k.ts - * (webapi hardening: K 关卡 phase 感知 — 设计阶段 not-applicable, 总结阶段回查资源) + * (webapi hardening: K 关卡 phase 感知 + designResources 落地校验) * * 设计: * - phase='design': summaryResources 为空 → not-applicable (退出 0) * - phase='summary': summaryResources 全部 lookup 成功 → ok - * - phase='summary': 某资源 lookup 失败 → failure + 列出 missing + * - phase='summary': 某资源 lookup 失败 → failure + 列出 missing (reason='no longer exists') + * - phase='summary': designResources 未落地 → failure + 列出 missing (reason='designed but not delivered') + * - phase='summary': designResources ⊆ summaryResources + 全部 lookup 成功 → ok * - * v0.23+ (Task 9, webapi hardening): K 关卡 phase 语义修复, 防止总结阶段引用已删资源 + * v0.23+ (Task 9, webapi hardening): K 关卡 phase 语义修复, 防止总结阶段引用已删资源或漏交付 */ import { describe, expect, it } from 'vitest' import { checkKCheckpoint } from '../../src/commands/_gates/_checkpoint_k.ts' @@ -42,7 +44,7 @@ describe('K 关卡语义 (Task 9b)', () => { expect(r.exitCode).toBe(0) }) - it('总结阶段某资源 lookup 失败 → failure + 列出 missing', async () => { + it('总结阶段某资源 lookup 失败 → failure + 列出 missing (no longer exists)', async () => { const r = await checkKCheckpoint({ phase: 'summary', appCode: 'tdd5', @@ -55,6 +57,52 @@ describe('K 关卡语义 (Task 9b)', () => { }) expect(r.status).toBe('failure') expect(r.exitCode).toBe(1) - expect(r.missing).toEqual([{ kind: 'flow', id: 'MISSING' }]) + expect(r.missing).toEqual([ + { kind: 'flow', id: 'MISSING', reason: 'no longer exists' }, + ]) }) -}) + + // 设计资源落地校验: designResources ⊆ summaryResources (设计阶段说要做的事, 总结必须看到交付) + it('设计阶段说有 3 form, 总结阶段只交 2 个 → missing F3 (designed but not delivered)', async () => { + const r = await checkKCheckpoint({ + phase: 'summary', + appCode: 'tdd5', + designResources: [ + { kind: 'form', id: 'F1' }, + { kind: 'form', id: 'F2' }, + { kind: 'form', id: 'F3' }, + ], + summaryResources: [ + { kind: 'form', id: 'F1' }, + { kind: 'form', id: 'F2' }, + ], + liveLookup: async (res) => res.id, + }) + expect(r.status).toBe('failure') + expect(r.exitCode).toBe(1) + expect(r.missing).toEqual([ + { kind: 'form', id: 'F3', reason: 'designed but not delivered' }, + ]) + }) + + // 完整通过: 设计资源全部交付 + 全部存活 + it('设计阶段 3 form + 总结阶段 3 form 全部 lookup 成功 → ok', async () => { + const r = await checkKCheckpoint({ + phase: 'summary', + appCode: 'tdd5', + designResources: [ + { kind: 'form', id: 'F1' }, + { kind: 'form', id: 'F2' }, + { kind: 'form', id: 'F3' }, + ], + summaryResources: [ + { kind: 'form', id: 'F1' }, + { kind: 'form', id: 'F2' }, + { kind: 'form', id: 'F3' }, + ], + liveLookup: async (res) => res.id, + }) + expect(r.status).toBe('ok') + expect(r.exitCode).toBe(0) + }) +}) \ No newline at end of file