dsh-sansheng-liubu/sansheng/src/records.js

117 lines
4.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { randomUUID } from 'node:crypto'
import { canonical, sha256 } from './digest.js'
import { budgetOf } from './gate.js'
const MUTATIONS = new Set(['draft', 'start', 'revise', 'task', 'pass', 'rework', 'complete', 'pause', 'resume', 'stop'])
export const DISPATCH_STATUS = Object.freeze({
prepared: '已准备',
in_flight: '发送中',
confirmed: '已确认',
rejected: '被拒绝',
failed: '未执行',
unknown: '待核实',
cancelled: '已取消',
})
export function isGoalMutation(action) {
return MUTATIONS.has(String(action ?? ''))
}
export function newId(prefix) {
return `${prefix}-${randomUUID().replace(/-/g, '').slice(0, 8)}`
}
/** 一次宿主启动的标识:派发记录带上它,重启后就能分辨「本次启动的」与「上次遗留的」。 */
export function newBootId() {
return `boot-${Date.now().toString(36)}-${randomUUID().replace(/-/g, '').slice(0, 6)}`
}
function textOfResult(result) {
if (result === undefined || result === null) return ''
if (typeof result === 'string') return result
const content = Array.isArray(result.content) ? result.content : []
return content.filter(part => part?.type === 'text').map(part => String(part.text ?? '')).join('\n')
}
/** 工具结果里的失败标记;不同版本可能用 isError 或 error 字段。 */
export function isToolError(result) {
if (result === undefined || result === null) return false
if (result.isError === true || result.error !== undefined) return true
return false
}
/**
* 区分"执行器没报错"与"业务真的变了"。
* 原生 group_goal 的业务拒绝是普通字符串,isError 不置位;所以必须看目标 revision/id 前后快照。
* 返回 { status:'confirmed'|'rejected', note }。
*/
export function classifyGoalOutcome({ action, before, after, result }) {
if (isToolError(result)) {
return { status: 'rejected', note: textOfResult(result) || '原生调用返回失败。' }
}
const beforeId = before?.id ?? null
const afterId = after?.id ?? null
const beforeRevision = Number(before?.revision ?? -1)
const afterRevision = Number(after?.revision ?? -1)
const changed = after !== undefined && (
afterId !== beforeId
|| afterRevision > beforeRevision
// Q10:draft 必须是“新建了目标”,start 必须是“从非 active 进入 active”。
// 目标本来就在 drafting/active 时,重复 draft/start 即使原生返回成功也不能算确认。
|| (action === 'draft' && afterId !== null && afterId !== beforeId)
|| (action === 'start' && before?.status !== 'active' && after?.status === 'active')
)
if (changed) return { status: 'confirmed', note: null }
const text = textOfResult(result)
return {
status: 'rejected',
note: text === '' ? '原生目标状态没有变化,按业务拒绝处理。' : text.slice(0, 500),
}
}
function stageIndexOf(stageList, predicate) {
const index = stageList.findIndex(predicate)
return index === -1 ? undefined : index
}
/**
* 从目标前后快照里认出这次 rework 落在哪个阶段、预算用到第几轮。
* 纯函数,便于单测;找不到增量时返回 undefined(例如调用被上游拒绝)。
*/
export function detectRework({ before, after, reason }) {
if (!after || !before || after.id !== before.id) return undefined
if ((after.revision ?? 0) <= (before.revision ?? 0)) return undefined
const afterStages = after.stages ?? []
const beforeStages = before.stages ?? []
const stageIndex = stageIndexOf(afterStages, (stage, index) => {
const old = beforeStages[index]
return (Number(stage.reworks) || 0) > (Number(old?.reworks) || 0)
})
if (stageIndex === undefined) return undefined
const stage = afterStages[stageIndex]
return {
stageIndex,
stageNo: stageIndex + 1,
stageTitle: stage.title,
reason: String(reason ?? '').trim() || String(stage.feedback ?? '').trim(),
reworksInStage: Number(stage.reworks) || 0,
}
}
/** 派发记录前缀(状态展示用)。 */
export function describeDispatch(record) {
const status = DISPATCH_STATUS[record.status] ?? record.status
const stage = Number.isInteger(record.stageIndex) ? ` 阶段${record.stageIndex}` : ''
return `${record.id} ${record.action}${stage} → ${status}`
}
/** 派发 payload 的稳定摘要:同 requestId 不同 payload 必须拒绝。 */
export function payloadDigestOf({ action, roomId, args, actorBotId, stageIndex }) {
return sha256(canonical({ action, roomId, args: args ?? {}, actorBotId: actorBotId ?? null, stageIndex: stageIndex ?? null }))
}
export function budgetAfter(goal, project, recorded = []) {
return budgetOf(goal, project, recorded)
}