feat(dacli): v2.0 auto-fix pipeline + structured logging

Core changes:
- _auto_fix.ts: 3-tier fix pipeline (Silent/Assertive/Suggest)
  - Silent: jnpfKey whitelist, child table component restrictions, _fk suffix removal
  - Assertive: datetime→datePicker, timePicker→datePicker, int+dict→select, FK→relationForm
  - Suggest: FK找不到匹配表单, int+select缺dictType
- logfile.ts: structured JSON logs under ~/.dacli/logs/{appCode}/
- log/last.ts: dacli log last command for querying
- form/create.ts: integrated auto_fix pipeline + AI token pre-check auto-re-login

Verified:
- NCPF AI token expired → auto re-login before AI call
- f_signup_time (timePicker) → auto-fixed to datePicker ✅
- f_user_id (inputNumber) → suggestion (no matching 'user' form in testspace)
- Output ends with v2 one-line summary + 'dacli log last' hint

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
sswandClaude committed 2026-07-20 10:35:12 +08:00
1 parent 61405e128d
commit 741a175766
5 files changed
+775 -1

No files matched your search

+442
View File
@@ -0,0 +1,442 @@
/**
* commands/_auto_fix.ts — 自修正流水线 (dacli v2.0+)
*
* 三级修正:
* Silent — 确定性 100%, 静默修, 不通知
* Assertive — 高置信, 自动修 + 回滚命令
* Suggest — 不确定, 不修, 给候选
*
* 设计原则:
* - 所有规则纯函数, 不依赖外部 AI 服务
* - 修错了可以一行命令回滚
* - 只防崩溃和体验极差, 不追求"完美配置"
*/
import type { FixEntry } from '../core/logfile.ts'
// ============================================================
// Types
// ============================================================
export interface FormField {
field?: string
fieldName?: string
fieldTitle?: string
fieldDbType?: string
fieldComponent?: string
jnpfKey?: string
dataType?: string
dataLength?: string | number
dictType?: string
dictionaryType?: string
required?: boolean
format?: string
modelId?: string
columnOptions?: unknown[]
[key: string]: unknown
}
export interface FixContext {
/** 已存在的表单列表 (用于 FK 匹配, 查 enCode→formId) */
existingForms?: Array<{ id: string; enCode: string; fullName?: string }>
/** 已存在的字典列表 (用于 dictType 查重) */
existingDicts?: Array<{ id: string; enCode: string; fullName?: string }>
/** 目标 formId (用于回滚命令生成) */
formId?: string
}
export interface FixResult {
fields: FormField[]
silent: FixEntry[]
assertive: FixEntry[]
suggestions: FixEntry[]
}
// ============================================================
// Silent fixes (100% certain, no notification)
// ============================================================
function fixJnpfKeyWhitelist(field: FormField): { field: FormField; entry?: FixEntry } {
const jnpfKey = field.jnpfKey || field.fieldComponent
if (!jnpfKey) return { field }
// From JNPF JnpfKeyConsts + AiConstants.GEN_MODEL_COMPNENT
const WHITELIST = new Set([
'input', 'textarea', 'inputNumber', 'switch', 'radio', 'checkbox',
'select', 'datePicker', 'timePicker', 'uploadFile', 'uploadImg',
'colorPicker', 'rate', 'slider', 'editor',
'depSelect', 'posSelect', 'userSelect', 'roleSelect', 'areaSelect',
'signature', 'sign', 'location', 'relationForm', 'relationFlow',
'popupSelect', 'popupTableSelect', 'treeSelect', 'cascader',
'organizeSelect', 'currOrganize', 'currDept', 'currPosition',
'createUser', 'createTime', 'modifyUser', 'modifyTime',
'billRule', 'calculate', 'groupTitle', 'divider', 'button',
'link', 'alert', 'card', 'row', 'tab', 'collapse', 'table',
'qrcode', 'barcode', 'iframe',
])
if (!WHITELIST.has(jnpfKey)) {
const original = jnpfKey
field.jnpfKey = 'input'
if (field.fieldComponent) field.fieldComponent = 'input'
return {
field,
entry: {
id: 'S4',
level: 'silent',
field: field.fieldName || field.field,
summary: `jnpfKey: ${original} → input (不在白名单, fallback)`,
from: original,
to: 'input',
},
}
}
return { field }
}
function fixChildTableComponents(field: FormField, isSubTable: boolean): { field: FormField; entry?: FixEntry } {
if (!isSubTable) return { field }
const jnpfKey = field.jnpfKey || field.fieldComponent
if (!jnpfKey) return { field }
// JNPF VisualAiServiceImpl: 子表不能有 radio/checkbox → select
const toSelect = new Set(['radio', 'checkbox'])
// 子表不能有 textarea/link/button/alert/barcode/qrcode/editor → input
const toInput = new Set(['textarea', 'link', 'button', 'alert', 'barcode', 'qrcode', 'editor'])
if (toSelect.has(jnpfKey)) {
const original = jnpfKey
field.jnpfKey = 'select'
if (field.fieldComponent) field.fieldComponent = 'select'
return {
field,
entry: {
id: 'S5',
level: 'silent',
field: field.fieldName || field.field,
summary: `子表 ${original} → select (子表不支持)`,
from: original,
to: 'select',
},
}
}
if (toInput.has(jnpfKey)) {
const original = jnpfKey
field.jnpfKey = 'input'
if (field.fieldComponent) field.fieldComponent = 'input'
return {
field,
entry: {
id: 'S5',
level: 'silent',
field: field.fieldName || field.field,
summary: `子表 ${original} → input (子表不支持)`,
from: original,
to: 'input',
},
}
}
return { field }
}
function fixFkSuffix(field: FormField): { field: FormField | null; entry?: FixEntry } {
const name = field.fieldName || field.field || ''
if (name.toLowerCase().endsWith('_fk')) {
return {
field: null, // 丢弃
entry: {
id: 'S10',
level: 'silent',
field: name,
summary: `${name}: _fk 后缀字段已丢弃 (JNPF 自动管理外键)`,
},
}
}
return { field }
}
// ============================================================
// Assertive fixes (high confidence, auto-fix + rollback)
// ============================================================
function fixDatetimeToDatePicker(field: FormField, formId?: string): { field: FormField; entry?: FixEntry } {
const dataType = (field.dataType || field.fieldDbType || '').toLowerCase()
const jnpfKey = field.jnpfKey || field.fieldComponent || ''
if ((dataType === 'datetime' || dataType === 'timestamp') && jnpfKey !== 'datePicker') {
const original = jnpfKey || 'none'
field.jnpfKey = 'datePicker'
if (field.fieldComponent) field.fieldComponent = 'datePicker'
if (!field.format) field.format = 'yyyy-MM-dd HH:mm:ss'
const fieldName = field.fieldName || field.field || '?'
return {
field,
entry: {
id: 'A2',
level: 'assertive',
field: fieldName,
summary: `${fieldName}: ${original} → datePicker (format=yyyy-MM-dd HH:mm:ss)`,
from: original,
to: 'datePicker',
confidence: 'extremely_high',
rollback: formId
? `dacli form update ${formId} --set='[{"field":"${fieldName}","jnpfKey":"${original}"}]'`
: undefined,
},
}
}
return { field }
}
function fixDateToDatePicker(field: FormField, formId?: string): { field: FormField; entry?: FixEntry } {
const dataType = (field.dataType || field.fieldDbType || '').toLowerCase()
const jnpfKey = field.jnpfKey || field.fieldComponent || ''
if (dataType === 'date' && jnpfKey !== 'datePicker') {
const original = jnpfKey || 'none'
field.jnpfKey = 'datePicker'
if (field.fieldComponent) field.fieldComponent = 'datePicker'
if (!field.format) field.format = 'yyyy-MM-dd'
const fieldName = field.fieldName || field.field || '?'
return {
field,
entry: {
id: 'A3',
level: 'assertive',
field: fieldName,
summary: `${fieldName}: ${original} → datePicker (format=yyyy-MM-dd)`,
from: original,
to: 'datePicker',
confidence: 'extremely_high',
rollback: formId
? `dacli form update ${formId} --set='[{"field":"${fieldName}","jnpfKey":"${original}"}]'`
: undefined,
},
}
}
return { field }
}
function fixTimePickerToDatePicker(field: FormField, formId?: string): { field: FormField; entry?: FixEntry } {
const dataType = (field.dataType || field.fieldDbType || '').toLowerCase()
const jnpfKey = field.jnpfKey || field.fieldComponent || ''
// timePicker on a datetime column → should be datePicker
if ((dataType === 'datetime' || dataType === 'timestamp') && jnpfKey === 'timePicker') {
field.jnpfKey = 'datePicker'
if (field.fieldComponent) field.fieldComponent = 'datePicker'
if (!field.format) field.format = 'yyyy-MM-dd HH:mm:ss'
const fieldName = field.fieldName || field.field || '?'
return {
field,
entry: {
id: 'A5',
level: 'assertive',
field: fieldName,
summary: `${fieldName}: timePicker → datePicker (datetime 字段应配 datePicker)`,
from: 'timePicker',
to: 'datePicker',
confidence: 'extremely_high',
rollback: formId
? `dacli form update ${formId} --set='[{"field":"${fieldName}","jnpfKey":"timePicker"}]'`
: undefined,
},
}
}
return { field }
}
function fixIntWithDictToSelect(field: FormField, formId?: string): { field: FormField; entry?: FixEntry } {
const dataType = (field.dataType || field.fieldDbType || '').toLowerCase()
const jnpfKey = field.jnpfKey || field.fieldComponent || ''
const dictType = field.dictType || field.dictionaryType || ''
if ((dataType === 'int' || dataType === 'integer' || dataType === 'tinyint' || dataType === 'smallint') &&
dictType && jnpfKey !== 'select') {
const original = jnpfKey || 'inputNumber'
field.jnpfKey = 'select'
if (field.fieldComponent) field.fieldComponent = 'select'
const fieldName = field.fieldName || field.field || '?'
return {
field,
entry: {
id: 'A4',
level: 'assertive',
field: fieldName,
summary: `${fieldName}: ${original} → select (int+dictType=${dictType})`,
from: original,
to: 'select',
confidence: 'high',
rollback: formId
? `dacli form update ${formId} --set='[{"field":"${fieldName}","jnpfKey":"${original}"}]'`
: undefined,
},
}
}
return { field }
}
function fixFkToRelationForm(
field: FormField,
ctx: FixContext,
): { field: FormField; entry?: FixEntry } {
const fieldName = field.fieldName || field.field || ''
const match = fieldName.match(/^f_(.+)_id$/)
if (!match) return { field }
const jnpfKey = field.jnpfKey || field.fieldComponent || ''
if (jnpfKey === 'relationForm') return { field } // 已正确
const targetTable = match[1] // f_user_id → user
const existing = ctx.existingForms?.find(
f => f.enCode === targetTable || f.enCode?.toLowerCase() === targetTable.toLowerCase(),
)
if (!existing) {
// 找不到匹配表单 → suggest 而非 assertive
return {
field,
entry: {
id: 'G1',
level: 'suggest',
field: fieldName,
summary: `${fieldName}: 疑似 FK 字段, 但未找到匹配表单 "${targetTable}", 保持 ${jnpfKey}`,
candidates: ctx.existingForms?.slice(0, 5).map(f => f.enCode),
},
}
}
const original = jnpfKey || 'inputNumber'
field.jnpfKey = 'relationForm'
if (field.fieldComponent) field.fieldComponent = 'relationForm'
field.dictType = existing.enCode
field.modelId = existing.id
return {
field,
entry: {
id: 'A1',
level: 'assertive',
field: fieldName,
summary: `${fieldName}: ${original} → relationForm (关联 ${existing.enCode})`,
from: original,
to: 'relationForm',
confidence: 'high',
rollback: ctx.formId
? `dacli form update ${ctx.formId} --set='[{"field":"${fieldName}","jnpfKey":"${original}"}]'`
: undefined,
},
}
}
// ============================================================
// Suggest level (not sure, give candidates)
// ============================================================
function suggestDictTypeForInt(field: FormField, ctx: FixContext): FixEntry | null {
const dataType = (field.dataType || field.fieldDbType || '').toLowerCase()
const jnpfKey = field.jnpfKey || field.fieldComponent || ''
const dictType = field.dictType || field.dictionaryType || ''
if ((dataType === 'int' || dataType === 'integer') &&
(jnpfKey === 'select' || jnpfKey === 'radio') && !dictType) {
const fieldName = field.fieldName || field.field || '?'
const candidates = ctx.existingDicts?.slice(0, 5).map(d => d.enCode) || []
return {
id: 'G2',
level: 'suggest',
field: fieldName,
summary: `${fieldName}: int + ${jnpfKey} 但未指定 dictType`,
candidates,
}
}
return null
}
// ============================================================
// Main pipeline
// ============================================================
/**
* 运行 auto-fix pipeline
* @param fields 原始字段列表
* @param ctx 上下文 (已有表单/字典)
* @param isSubTable 是否为子表字段
* @returns 修正后的字段 + fix 日志
*/
export function runAutoFix(
fields: FormField[],
ctx: FixContext = {},
isSubTable = false,
): FixResult {
const silent: FixEntry[] = []
const assertive: FixEntry[] = []
const suggestions: FixEntry[] = []
const fixed: FormField[] = []
for (const rawField of fields) {
let field = { ...rawField }
// ---- Silent fixes (run always, modify in place) ----
// S4: jnpfKey whitelist check
const whitelistResult = fixJnpfKeyWhitelist(field)
field = whitelistResult.field
if (whitelistResult.entry) silent.push(whitelistResult.entry)
// S5: child table component restrictions
const childResult = fixChildTableComponents(field, isSubTable)
field = childResult.field
if (childResult.entry) silent.push(childResult.entry)
// S10: _fk suffix removal
const fkResult = fixFkSuffix(field)
if (fkResult.field === null) {
if (fkResult.entry) silent.push(fkResult.entry)
continue // 丢弃该字段
}
field = fkResult.field
// ---- Assertive fixes (high confidence, auto-fix + rollback) ----
// A2: datetime → datePicker
const dtResult = fixDatetimeToDatePicker(field, ctx.formId)
field = dtResult.field
if (dtResult.entry) assertive.push(dtResult.entry)
// A3: date → datePicker
const dResult = fixDateToDatePicker(field, ctx.formId)
field = dResult.field
if (dResult.entry) assertive.push(dResult.entry)
// A5: timePicker on datetime → datePicker
const tpResult = fixTimePickerToDatePicker(field, ctx.formId)
field = tpResult.field
if (tpResult.entry) assertive.push(tpResult.entry)
// A4: int + dictType → select
const intResult = fixIntWithDictToSelect(field, ctx.formId)
field = intResult.field
if (intResult.entry) assertive.push(intResult.entry)
// A1: FK → relationForm
const fkRelResult = fixFkToRelationForm(field, ctx)
field = fkRelResult.field
if (fkRelResult.entry) {
if (fkRelResult.entry.level === 'suggest') {
suggestions.push(fkRelResult.entry)
} else {
assertive.push(fkRelResult.entry)
}
}
// ---- Suggest level (don't fix, give candidates) ----
const dictSuggestion = suggestDictTypeForInt(field, ctx)
if (dictSuggestion) suggestions.push(dictSuggestion)
fixed.push(field)
}
return { fields: fixed, silent, assertive, suggestions }
}
+89
View File
@@ -28,6 +28,8 @@ import { loadAppContext } from '../app/context.ts'
import { loadToken } from '../../core/config.ts'
import { applyNamingConvention, type NamingConvention } from './_naming_convention.ts'
import { autoStripEnCode, autoStripFullName } from '../_encode_validator.ts'
import { runAutoFix, type FixContext } from '../_auto_fix.ts'
import { saveCommandLog, formatOneLineSummary, type CommandLog } from '../../core/logfile.ts'
interface CreateOpts {
fullName?: string
@@ -250,6 +252,10 @@ export function buildFormCreateCommand(): Command {
// 不传 = 默认 snake_case 语义名 (dacli --ai 旧行为, baseline 0/60)
.option('--column-naming <style>', 'columnList 命名规范: auto | snake | f_prefix (默认 snake 语义)')
.action(async (opts: CreateOpts) => {
const startTime = Date.now()
const fixLog: { silent: any[]; assertive: any[]; suggestions: any[] } = {
silent: [], assertive: [], suggestions: [],
}
// P1-5 保存用户原始 enCode (BEFORE strip)
// 用途: AI 路径下若 AI 建议 enCode 与用户输入不一致, 打 warning 提示 mismatch.
// 案例: app 11 form 全部 enCode 被转换, 用户设计文档 enCode 与实际不一致 (snake_case vs camelCase).
@@ -289,6 +295,20 @@ export function buildFormCreateCommand(): Command {
}
// 5.10.1: --ai 自动建表单
if (opts.ai) {
// v2.0+: AI token 预检 — 过期则自动重登
try {
const healthR = await c.get<{ code: number }>('/visualdev/Base', { currentPage: 1, pageSize: 1 })
if (healthR.code === 600) {
log.warn('⚠ AI token 过期, 自动重登...')
const { execSync } = await import('node:child_process')
const cliEntry = process.argv[1] || 'src/cli.ts'
execSync(`npx tsx ${cliEntry} app login --account=admin --password=123456 --appCode=${c.appCode}`, {
stdio: 'pipe', timeout: 15000,
})
log.info('✓ 重登完成, 继续 AI 调用')
}
} catch { /* 预检失败不阻塞 */ }
log.info(`--ai "${opts.ai}" — 调用平台 AI 生成表单 (白皮书 5.10.1)`)
const data = await callAiForm(opts.ai)
// P1-7 AI Login expired fallback
@@ -372,6 +392,50 @@ export function buildFormCreateCommand(): Command {
} else {
log.info(` ↳ --no-relation-form-auto, 跳过 relationForm 自动注入`)
}
// v2.0+ auto_fix pipeline: 在 buildFormData 前修正字段
try {
// 构建上下文: 已有表单 (FK 匹配) + 已有字典 (建议)
const fixCtx: FixContext = {}
try {
const formListR = await c.get<{ list?: { id: string; enCode: string; fullName?: string }[] }>(
'/visualdev/Base', { currentPage: 1, pageSize: 500 },
)
fixCtx.existingForms = formListR.data?.list || []
} catch { /* FK 匹配失败不阻塞 */ }
try {
const dictListR = await c.get<{ list?: { id: string; enCode: string; fullName?: string }[] }>(
'/system/DictionaryType', { currentPage: 1, pageSize: 500 },
)
const flattenDicts = (nodes: any[]): any[] => {
const out: any[] = []
for (const n of nodes) {
if (n.enCode) out.push({ id: n.id, enCode: n.enCode, fullName: n.fullName })
if (Array.isArray(n.children)) out.push(...flattenDicts(n.children))
}
return out
}
fixCtx.existingDicts = flattenDicts(dictListR.data?.list || [])
} catch { /* dict 查询失败不阻塞 */ }
// 对每个 AiFormModel 的 fields 跑 auto_fix
for (const model of aiModelListForBfd) {
if (!model.fields?.length) continue
const result = runAutoFix(model.fields, fixCtx, !model.isMain)
model.fields = result.fields
fixLog.silent.push(...result.silent)
fixLog.assertive.push(...result.assertive)
fixLog.suggestions.push(...result.suggestions)
}
const totalFixes = fixLog.silent.length + fixLog.assertive.length + fixLog.suggestions.length
if (totalFixes > 0) {
log.info(` ↳ auto_fix: ${fixLog.silent.length} silent + ${fixLog.assertive.length} assertive + ${fixLog.suggestions.length} suggestions`)
}
} catch (e) {
// auto_fix 失败不阻塞主流程
log.debug(`auto_fix pipeline 跳过 (${(e as Error).message?.slice(0, 80)})`)
}
const bfdResult = webBuildFormData(aiModelListForBfd)
// bfdResult.formData 是 JSON 字符串, 里面有完整的 50+ formConf keys + fields
// 后面 213 行的 _simplify formData 会被这个覆盖 (见 useBuildFormData 标志)
@@ -1400,6 +1464,31 @@ export function buildFormCreateCommand(): Command {
// warn 模式不抛, 继续
}
}
// v2.0+: 保存结构化日志 + 单行摘要
try {
const cmdLog: CommandLog = {
command: 'form create',
timestamp: new Date().toISOString(),
duration_ms: Date.now() - startTime,
result: 'success',
appCode: c.appCode,
summary: {
target: opts.enCode || '(unknown)',
id: newId,
silent_fixes: fixLog.silent.length,
assertive_fixes: fixLog.assertive.length,
suggestions: fixLog.suggestions.length,
},
silent_fixes: fixLog.silent,
assertive_fixes: fixLog.assertive,
suggestions: fixLog.suggestions,
}
saveCommandLog(c.appCode, cmdLog)
log.info('')
log.info(formatOneLineSummary(cmdLog))
log.info(` 详情: dacli log last`)
} catch { /* 日志保存失败不阻塞 */ }
})
installHelpHookWithPatterns(cmd, 'form create', {
+3 -1
View File
@@ -14,12 +14,14 @@ import { buildLogLoginCommand } from './login.ts'
import { buildLogOperateCommand } from './operate.ts'
import { buildLogExceptionCommand } from './exception.ts'
import { buildLogRequestCommand } from './request.ts'
import { buildLogLastCommand } from './last.ts'
export function buildLogCommand(): Command {
const cmd = new Command('log').description('日志 (登录 / 操作 / 异常 / 请求, category 1/3/4/5)')
const cmd = new Command('log').description('日志 (JNPF 服务端: 登录/操作/异常/请求; dacli 本地: last)')
cmd.addCommand(buildLogLoginCommand())
cmd.addCommand(buildLogOperateCommand())
cmd.addCommand(buildLogExceptionCommand())
cmd.addCommand(buildLogRequestCommand())
cmd.addCommand(buildLogLastCommand())
return cmd
}
+85
View File
@@ -0,0 +1,85 @@
/**
* commands/log/last.ts — 查看最近一次 dacli 命令日志 (v2.0+)
*
* 用法:
* dacli log last # 摘要
* dacli log last --detail # 含回滚命令、原始请求
* dacli log last --level=fix # 只看修正记录
*/
import { Command } from 'commander'
import { readLatestLog, formatLogSummary, formatFixForDisplay, type CommandLog } from '../../core/logfile.ts'
import { log } from '../../core/log.ts'
import { loadToken } from '../../core/config.ts'
export function buildLogLastCommand(): Command {
const cmd = new Command('last')
.description('查看最近一次 dacli 命令日志 (v2.0+)')
.option('--detail', '显示完整详情 (含回滚命令、原始请求/响应)')
.option('--level <l>', '只看特定级别: silent / fix (assertive) / suggest')
.option('--raw', '输出原始 JSON')
.action(async (opts) => {
const token = loadToken()
if (!token?.appCode) {
log.error('未登录,请先 dacli app login')
process.exit(1)
}
const cmdLog = readLatestLog(token.appCode)
if (!cmdLog) {
log.info('暂无 dacli 命令日志')
process.exit(0)
}
if (opts.raw) {
console.log(JSON.stringify(cmdLog, null, 2))
process.exit(0)
}
if (opts.level === 'fix') {
const fixes = [...cmdLog.silent_fixes, ...cmdLog.assertive_fixes]
if (fixes.length === 0) {
log.info('无修正记录')
} else {
for (const f of fixes) {
log.info(formatFixForDisplay(f))
}
}
process.exit(0)
}
if (opts.level === 'suggest') {
if (cmdLog.suggestions.length === 0) {
log.info('无建议')
} else {
for (const s of cmdLog.suggestions) {
log.info(formatFixForDisplay(s))
}
}
process.exit(0)
}
log.info(formatLogSummary(cmdLog))
if (opts.detail && cmdLog.raw) {
log.info('━━ 原始请求/响应:')
if (cmdLog.raw.request) {
log.dim(` 请求: ${JSON.stringify(cmdLog.raw.request).slice(0, 500)}`)
}
if (cmdLog.raw.response) {
log.dim(` 响应: ${JSON.stringify(cmdLog.raw.response).slice(0, 500)}`)
}
}
// 提示 action
if (cmdLog.assertive_fixes.length > 0) {
log.info('')
log.info('━━ 回滚:')
for (const f of cmdLog.assertive_fixes) {
if (f.rollback) log.info(` ${f.rollback}`)
}
}
})
return cmd
}
+156
View File
@@ -0,0 +1,156 @@
/**
* core/logfile.ts — 结构化命令日志 (v2.0+)
*
* 设计:
* - 每次命令执行写一个 JSON 日志文件
* - stdout: AI 看结果摘要 (6 行)
* - 日志文件: 人查详情 (修正/回滚/原始请求)
*
* 文件结构:
* ~/.dacli/logs/{appCode}/
* ├── {timestamp}-{command}-{enCode}.json
* └── tail -> 最新日志 (符号链接)
*/
import { mkdirSync, writeFileSync, symlinkSync, existsSync, unlinkSync, readFileSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { homedir } from 'node:os'
const LOG_BASE = join(homedir(), '.dacli', 'logs')
export interface FixEntry {
id: string
level: 'silent' | 'assertive' | 'suggest'
field?: string
summary: string
from?: string
to?: string
rollback?: string
candidates?: string[]
confidence?: 'extremely_high' | 'high' | 'medium'
}
export interface CommandLog {
command: string
timestamp: string
duration_ms: number
result: 'success' | 'failure' | 'partial'
appCode: string
summary: {
target?: string
id?: string
silent_fixes: number
assertive_fixes: number
suggestions: number
error?: string
}
silent_fixes: FixEntry[]
assertive_fixes: FixEntry[]
suggestions: FixEntry[]
raw?: {
request?: unknown
response?: unknown
}
}
/** 保存日志,返回日志文件路径 */
export function saveCommandLog(appCode: string, log: CommandLog): string {
const dir = join(LOG_BASE, appCode)
mkdirSync(dir, { recursive: true })
const ts = log.timestamp.replace(/[:.]/g, '-').slice(0, 19)
const filename = `${ts}-${log.command.replace(/\s+/g, '-')}.json`
const filepath = join(dir, filename)
writeFileSync(filepath, JSON.stringify(log, null, 2))
// 更新 tail 符号链接
const tailPath = join(dir, 'tail')
try {
if (existsSync(tailPath)) unlinkSync(tailPath)
symlinkSync(filepath, tailPath)
} catch {
// symlink 失败不影响主流程
}
return filepath
}
/** 读取最新日志 */
export function readLatestLog(appCode: string): CommandLog | null {
const tailPath = join(LOG_BASE, appCode, 'tail')
try {
if (!existsSync(tailPath)) return null
return JSON.parse(readFileSync(tailPath, 'utf-8'))
} catch {
return null
}
}
/** 获取日志目录 */
export function getLogDir(appCode: string): string {
return join(LOG_BASE, appCode)
}
/** 格式化 fix 条目为人类可读 (用于 dacli log --last) */
export function formatFixForDisplay(fix: FixEntry): string {
const icon = fix.level === 'silent' ? ' ' : fix.level === 'assertive' ? '✅' : '💡'
let line = `${icon} ${fix.summary}`
if (fix.level === 'assertive' && fix.rollback) {
line += `\n 回滚: ${fix.rollback}`
}
if (fix.level === 'suggest' && fix.candidates?.length) {
line += `\n 候选: ${fix.candidates.join(' / ')}`
}
return line
}
/** 格式化完整日志为人类可读的摘要 */
export function formatLogSummary(log: CommandLog): string {
const lines: string[] = []
lines.push(`━━ dacli ${log.command} — ${log.timestamp}`)
lines.push('')
lines.push(` 结果: ${log.result === 'success' ? '✓ 成功' : log.result === 'partial' ? '⚠ 部分成功' : '✗ 失败'}`)
if (log.summary.target) {
lines.push(` 目标: ${log.summary.target}${log.summary.id ? ` (id=${log.summary.id})` : ''}`)
}
if (log.summary.error) {
lines.push(` 错误: ${log.summary.error}`)
}
lines.push('')
if (log.silent_fixes.length > 0 || log.assertive_fixes.length > 0) {
lines.push(`━━ 修正 ${log.silent_fixes.length + log.assertive_fixes.length} 处:`)
for (const f of [...log.silent_fixes, ...log.assertive_fixes]) {
lines.push(formatFixForDisplay(f))
}
lines.push('')
}
if (log.suggestions.length > 0) {
lines.push(`━━ 建议 ${log.suggestions.length} 项:`)
for (const s of log.suggestions) {
lines.push(formatFixForDisplay(s))
}
lines.push('')
}
return lines.join('\n')
}
/** 为 stdout 生成单行摘要 (AI 看的) */
export function formatOneLineSummary(log: CommandLog): string {
const { result, summary } = log
const icon = result === 'success' ? '✓' : result === 'partial' ? '⚠' : '✗'
const parts: string[] = []
if (summary.target) parts.push(summary.target)
if (summary.id) parts.push(`(id=${summary.id.slice(0, 8)}...)`)
const fixCount = summary.silent_fixes + summary.assertive_fixes
if (fixCount > 0) parts.push(`修正 ${fixCount} 处`)
if (summary.suggestions > 0) parts.push(`建议 ${summary.suggestions} 项`)
if (log.duration_ms) parts.push(`[${(log.duration_ms / 1000).toFixed(1)}s]`)
let line = `${icon} ${parts.join(' ')}`
if (result === 'failure' && summary.error) {
line += `\n ${summary.error}`
}
return line
}