diff --git a/src/commands/app/context.ts b/src/commands/app/context.ts new file mode 100644 index 0000000..d28c3e5 --- /dev/null +++ b/src/commands/app/context.ts @@ -0,0 +1,222 @@ +/** + * commands/app/context.ts — `dacli app context` + * + * AI 环境快照 (P0.1, 详见 doc/ai-optimization-plan.md §2.1 + doc/ai-error-analysis.md §B) + * + * 设计要点: + * - 单次调用产出 AI 干活的最小依赖集: dbLinkId / 已有 enCode / 草稿 vs 发布 / 已有表 / 菜单 / token 状态 + * - 内部直接调 JnpfClient.get/postJson, 不 shell out 调子命令 + * - 失败容错: form/dm/menu 任一 API 失败时不抛错, 仅写入 warnings, 其他部分继续输出 + * - --json 走单行 JSON (AI 友好, 不带换行缩进) + * + * 输出接口: src/core/types.ts AppContext + */ +import { Command } from 'commander' +import { JnpfClient } from '../../core/client.ts' +import { installAiHelpHook } from '../../core/help.ts' +import { log } from '../../core/log.ts' +import { loadToken } from '../../core/config.ts' +import type { AppContext, FormSummary } from '../../core/types.ts' + +// 复用 cli.ts 的 VERSION 常量 — 避免重复硬编码, 也避免外部依赖 (cat package.json) +// 路径相对 src/commands/app/context.ts → ../../../src/cli.ts +// 不直接 import cli.ts 是为避免循环依赖 (cli.ts 启动时 import 各 command) +// 用 fileURL + 文本扫描 + 正则提 VERSION +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, join, resolve } from 'node:path' + +const PAGE_SIZE = 500 // 一次拉完, 避免分页遗漏 + +interface ContextOpts { + json?: boolean + app?: string +} + +/** 从 src/cli.ts 源码中提取 const VERSION = '...' */ +function readCliVersion(): string { + try { + const here = dirname(fileURLToPath(import.meta.url)) + // src/commands/app/context.ts → src/cli.ts + const cliPath = resolve(here, '../../cli.ts') + const src = readFileSync(cliPath, 'utf-8') + const m = src.match(/const\s+VERSION\s*=\s*['"]([^'"]+)['"]/) + return m?.[1] || 'unknown' + } catch { + return 'unknown' + } +} + +/** token 7 天过期 (与 JNPF 后端一致, 详见 doc/jnpf-token-expiry.md) */ +function calcTokenExpiry(loginAt?: string): string | undefined { + if (!loginAt) return undefined + try { + const t = new Date(loginAt) + t.setUTCDate(t.getUTCDate() + 7) + return t.toISOString() + } catch { + return undefined + } +} + +/** 安全拉 form list — 失败返回 null + 警告 */ +async function tryFetchForms(c: JnpfClient): Promise<{ forms: FormSummary[]; warning?: string }> { + try { + const r = await c.get<{ list: FormSummary[]; pagination?: { total: number } }>('/visualdev/Base', { + currentPage: 1, + pageSize: PAGE_SIZE, + }) + if (r.code !== 200) { + return { forms: [], warning: `form list 失败 (code=${r.code}): ${r.msg}` } + } + return { forms: r.data?.list || [] } + } catch (e) { + return { forms: [], warning: `form list 异常: ${(e as Error).message}` } + } +} + +/** 安全拉 dm list — 失败返回 null + 警告 */ +async function tryFetchTables( + c: JnpfClient, +): Promise<{ tables: string[]; warning?: string }> { + try { + const dbLinkId = c.dbLinkId || '0' + const r = await c.get<{ list: { table: string }[] }>( + `/system/DataModel/${dbLinkId}/Tables`, + { currentPage: 1, pageSize: PAGE_SIZE }, + ) + if (r.code !== 200) { + return { tables: [], warning: `dm list 失败 (code=${r.code}): ${r.msg}` } + } + const list = r.data?.list || [] + return { tables: list.map((t) => t.table) } + } catch (e) { + return { tables: [], warning: `dm list 异常: ${(e as Error).message}` } + } +} + +/** 安全拉 menu list — 失败返回 null + 警告 */ +async function tryFetchMenus( + c: JnpfClient, +): Promise<{ menus: string[]; warning?: string }> { + try { + const r = await c.get('/system/Menu/ModuleBySystem') + if (r.code !== 200) { + return { menus: [], warning: `menu list 失败 (code=${r.code}): ${r.msg}` } + } + const list = (Array.isArray(r.data) ? r.data : (r.data as { list?: unknown[] })?.list) || [] + const encs = (list as Array<{ enCode?: string }>).map((m) => m.enCode).filter((s): s is string => !!s) + return { menus: encs } + } catch (e) { + return { menus: [], warning: `menu list 异常: ${(e as Error).message}` } + } +} + +export function buildAppContextCommand(): Command { + const cmd = new Command('context') + .description('输出当前应用环境快照 (dbLinkId/enCode/表/菜单/token 状态). AI 新会话第一步先跑此命令.') + .option('--json', '单行 JSON 输出 (AI 友好)', false) + .option('--app ', '覆盖 token 中的 appCode (供快速切换测试)') + .action(async (opts: ContextOpts) => { + // 1. 先读 token — 不需要登录就能给出基础信息 (appCode/dbLinkId/tokenStatus) + const cached = loadToken() + const appCode = opts.app || cached?.appCode || '' + const dbLinkId = cached?.dbLinkId || '' + const tokenStatus: AppContext['tokenStatus'] = cached ? 'valid' : 'expired' + const tokenExpiry = calcTokenExpiry(cached?.loginAt) + const warnings: string[] = [] + + // 2. 尝试构造 client 拉 form/dm/menu — 失败容错 + let forms: FormSummary[] = [] + let tables: string[] = [] + let menus: string[] = [] + + try { + // 如果有缓存 token, 复用; 没有则尝试登录 (失败也不致命, 后续 API 调用会再失败) + const c = await JnpfClient.fromToken(opts.app ? { appCode: opts.app } : {}) + // 应用 --app 覆盖 + if (opts.app) c.appCode = opts.app + + const f = await tryFetchForms(c) + forms = f.forms + if (f.warning) warnings.push(f.warning) + + const t = await tryFetchTables(c) + tables = t.tables + if (t.warning) warnings.push(t.warning) + + const m = await tryFetchMenus(c) + menus = m.menus + if (m.warning) warnings.push(m.warning) + } catch (e) { + // 登录失败 / 网络不通 — 仍然输出能拿到的部分 + warnings.push(`client 初始化失败: ${(e as Error).message}`) + } + + // 3. 切分 form 状态 + const existingEnCodes = Array.from(new Set(forms.map((f) => f.enCode).filter((s): s is string => !!s))) + const unreleasedForms = forms + .filter((f) => f.state === 0) + .map((f) => `${f.id}:${f.enCode || '(no-enCode)'}`) + const releasedForms = forms + .filter((f) => f.state === 1) + .map((f) => `${f.id}:${f.enCode || '(no-enCode)'}`) + + const ctx: AppContext = { + appCode, + dbLinkId, + tokenStatus, + tokenExpiry, + existingEnCodes, + unreleasedForms, + releasedForms, + existingTables: tables, + menus, + currentVersion: readCliVersion(), + warnings, + } + + // 4. 输出 + if (opts.json) { + // 单行 JSON (AI 友好, 便于 grep/管道) + console.log(JSON.stringify(ctx)) + return + } + + // 人读友好模式 + log.info(`app : ${ctx.appCode || '(未登录)'}`) + log.info(`dbLinkId: ${ctx.dbLinkId || '(unknown)'}`) + log.info(`token : ${ctx.tokenStatus}${ctx.tokenExpiry ? ' (expires ' + ctx.tokenExpiry + ')' : ''}`) + log.info(`version : ${ctx.currentVersion}`) + log.info(`enCodes : ${ctx.existingEnCodes.length} 个`) + log.info(`forms : ${ctx.releasedForms.length} 发布 / ${ctx.unreleasedForms.length} 草稿`) + log.info(`tables : ${ctx.existingTables.length} 张`) + log.info(`menus : ${ctx.menus.length} 个`) + if (warnings.length) { + log.warn(`采集警告 ${warnings.length} 条:`) + for (const w of warnings) log.dim(` - ${w}`) + } + }) + + installAiHelpHook(cmd, { + purpose: + '输出当前应用环境快照 (appCode/dbLinkId/token 状态/enCode/表/菜单). ' + + 'AI 新会话第一步先跑此命令, 所有参数从此快照取, 不要猜测.', + optional: { + '--json': '单行 JSON 输出 (推荐 AI 使用)', + '--app': '覆盖 token 中的 appCode (供快速切换测试)', + }, + example: ['dacli app context --json', 'dacli app context --app=tds --json'], + source: { + api: 'GET /api/visualdev/Base, /api/system/DataModel/{dbLinkId}/Tables, /api/system/Menu/ModuleBySystem', + ref: 'doc/ai-optimization-plan.md §2.1, doc/ai-error-analysis.md §B', + }, + notes: [ + 'AI 新会话第一步先跑此命令', + '所有参数从此快照取, 不要猜测 (尤其 dbLinkId / enCode 唯一性 / 表存在性)', + '输出含 warnings 字段: 任一 API 失败时会填入, AI 据此判断上下文是否完整', + ], + }) + + return cmd +} diff --git a/src/commands/app/index.ts b/src/commands/app/index.ts index 6e78b64..b7619f8 100644 --- a/src/commands/app/index.ts +++ b/src/commands/app/index.ts @@ -12,6 +12,7 @@ * login 登录 JNPF (原顶层 login) * status 显示登录状态 (原顶层 status) * switch 切换当前应用 (原顶层 switchapp / switch-app) + * context AI 环境快照 (P0.1, 详见 doc/ai-optimization-plan.md §2.1) */ import { Command } from 'commander' import { buildAppListCommand } from './list.ts' @@ -22,6 +23,7 @@ import { buildAppClearCommand } from './clear.ts' import { buildAppLoginCommand } from './login.ts' import { buildAppStatusCommand } from './status.ts' import { buildAppSwitchCommand } from './switch.ts' +import { buildAppContextCommand } from './context.ts' export function buildAppCommand(): Command { const cmd = new Command('app').description('应用 (JNPF 多 app 生命周期, appCenter)') @@ -33,5 +35,6 @@ export function buildAppCommand(): Command { cmd.addCommand(buildAppLoginCommand()) cmd.addCommand(buildAppStatusCommand()) cmd.addCommand(buildAppSwitchCommand()) + cmd.addCommand(buildAppContextCommand()) return cmd } diff --git a/src/core/types.ts b/src/core/types.ts index 66ed10e..7ccf1fa 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -64,3 +64,34 @@ export class DacliError extends Error { this.raw = raw } } + +/** + * dacli app context 命令输出 — AI 环境快照 + * + * 每次新会话第一步跑 `dacli app context --json`, 所有参数从此快照取, + * 不要猜测 (尤其 dbLinkId / enCode 唯一性 / 表存在性 / form 发布状态). + */ +export interface AppContext { + /** 当前应用编码 (e.g. "developSystem", "tds") */ + appCode: string + /** 业务库 id (空 = 主库或未知) */ + dbLinkId: string + /** token 状态: valid=有缓存, expired=无缓存, unknown=无法判断 */ + tokenStatus: 'valid' | 'expired' | 'unknown' + /** token 预计过期时间 (loginAt + 7d), ISO 格式 */ + tokenExpiry?: string + /** 当前应用下所有表单 enCode (去重) */ + existingEnCodes: string[] + /** 草稿态 (state=0) 表单 id+enCode 摘要 */ + unreleasedForms: string[] + /** 已发布 (state=1) 表单 id+enCode 摘要 */ + releasedForms: string[] + /** 业务库下所有已存在表名 (snake_case) */ + existingTables: string[] + /** 当前应用下所有菜单 enCode */ + menus: string[] + /** 当前 dacli 版本 (来自 cli.ts VERSION 常量) */ + currentVersion: string + /** 采集过程警告 (任一 API 失败时填充, AI 据此判断上下文是否完整) */ + warnings: string[] +}