Files
hose-use/src/domains/approval/parser.ts
T
gitea 4e36a1d9a5 feat(approval): introduce sqlite rule engine, deterministic gateway, and hose-aipro cli (v0.7.0)
- Pure Rule Model & AST Parser:
  - Eliminate redundant title field; model rules purely via scope (scene index) and natural language body.
  - Implement AST parser for inline clauses: [action]{硬性|弹性|建议|特殊}.
  - Validate and enforce preference references with @{级别} syntax, strictly blocking invalid grammar.

- Embedded SQLite Database & Repository:
  - Native bun:sqlite integration with zero external dependencies, stored at ~/.config/hose-use/approval.db.
  - 5 core schemas: rules, preferences, approval_runs, approval_findings, and aipro_logs.
  - Support deduplicated scope indexing (listScopes with 1-based indices) and scope drill-down (getScopeDetail).

- Bill Requisition & Backlog Query Extension:
  - Add formatFlowAsBill adapter in domains/bill/tools.ts.
  - Fall back to flow and backlog inspection when bills are not found in invoice endpoints, unlocking full structured inspection for requisitions (such as S26000001) and loan requests.

- Deterministic Approval Gateway & Lifecycle:
  - Enforce mandatory approval lifecycle: points -> checklist -> review -> decide.
  - Physical gateway blocking: forbid decision if audit checklist is missing or empty, or if pending points remain unverified.
  - Hard tier severance: automatically sever and throw GatewayBlockError on approval attempts violating {硬性} clauses.

- Dedicated hose-aipro Global CLI & Immutable Audit Ledger:
  - Register secondary global binary hose-aipro alongside hose-use in package.json and build-binary.mjs.
  - Automatically record every AI Pro invocation, document context, args snapshot, operator, status, and verdict in aipro_logs.
  - Provide intuitive subcommands: points, checklist, review, decide, logs, rules.
  - Bump project version to v0.7.0 and regenerate OpenAPI bundles.
2026-09-06 19:03:06 +08:00

150 lines
4.3 KiB
TypeScript

import {
ApprovalRuleValidationError,
isValidStrictnessTier,
ParsedRule,
RuleClause,
StrictnessTier,
VALID_STRICTNESS_TIERS
} from "./types.js";
const CLAUSE_REGEX = /\[([^\[\]]+)\]\{([^{}]+)\}/g;
const ORPHAN_BRACKET_REGEX = /\[([^\[\]]+)\](?!\s*\{)/g;
const PREFERENCE_REF_REGEX = /@\{([^{}]+)\}/g;
/**
* 解析并严格校验规则正文
*
* 规则正文格式:
* 采用自然语言,在需要约束的判定点使用 [动作句式]{严格程度} 包裹。
* 允许的严格程度:硬性 | 弹性 | 建议 | 特殊
*
* @throws {ApprovalRuleValidationError} 当语法不合规或严格程度非法时抛出
*/
export function parseRuleBody(body: string): ParsedRule {
if (!body || typeof body !== "string" || body.trim().length === 0) {
throw new ApprovalRuleValidationError("规则正文不能为空");
}
// 1. 括号闭合完整性检查
checkBracketBalance(body);
// 2. 检测悬空的中括号(即写了 [动作] 但漏掉了 {级别})
const orphanMatches = Array.from(body.matchAll(ORPHAN_BRACKET_REGEX));
if (orphanMatches.length > 0) {
const firstOrphan = orphanMatches[0]![0];
throw new ApprovalRuleValidationError(
`检测到未指定严格程度的标记 "${firstOrphan}",请紧跟花括号指定级别,如 "${firstOrphan}{硬性}"`
);
}
// 3. 提取所有 [动作句式]{级别}
const clauses: RuleClause[] = [];
const matches = Array.from(body.matchAll(CLAUSE_REGEX));
for (const match of matches) {
const raw = match[0];
const rawAction = match[1];
const rawTier = match[2];
const startIndex = match.index ?? 0;
const endIndex = startIndex + raw.length;
const action = rawAction ? rawAction.trim() : "";
const tier = rawTier ? rawTier.trim() : "";
if (action.length === 0) {
throw new ApprovalRuleValidationError(`动作句式不能为空: "${raw}"`);
}
if (!isValidStrictnessTier(tier)) {
throw new ApprovalRuleValidationError(
`非法严格程度 "${tier}",仅支持:${VALID_STRICTNESS_TIERS.join("、")}`
);
}
clauses.push({
action,
strictness: tier as StrictnessTier,
raw,
startIndex,
endIndex
});
}
// 4. 一条合法的业务规约必须至少包含一个裁决要点
if (clauses.length === 0) {
throw new ApprovalRuleValidationError(
`规则正文未包含任何有效的规则标记,格式须为 [动作句式]{${VALID_STRICTNESS_TIERS.join("|")}}`
);
}
// 5. 生成剥离语法标记后的纯净自然语言
const cleanText = body.replace(CLAUSE_REGEX, (_match, action) => action.trim());
return {
rawBody: body,
clauses,
cleanText
};
}
/**
* 校验规则正文,合规返回 true,不合规抛出 ApprovalRuleValidationError
*/
export function validateRuleBody(body: string): boolean {
parseRuleBody(body);
return true;
}
/**
* 解析并校验偏好配置文本中的 @{级别} 引用
*/
export function validatePreferenceText(text: string): boolean {
if (!text || typeof text !== "string") return true;
const matches = Array.from(text.matchAll(PREFERENCE_REF_REGEX));
for (const match of matches) {
const tier = match[1]?.trim() ?? "";
if (!isValidStrictnessTier(tier)) {
throw new ApprovalRuleValidationError(
`非法的偏好引用 "@{${tier}}",仅支持:${VALID_STRICTNESS_TIERS.map((t) => `@{${t}}`).join("、")}`
);
}
}
return true;
}
/**
* 括号成对匹配与平衡检查
*/
function checkBracketBalance(text: string): void {
let openSquare = 0;
let openCurly = 0;
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (char === "[") {
openSquare++;
} else if (char === "]") {
openSquare--;
if (openSquare < 0) {
throw new ApprovalRuleValidationError("检测到未匹配的多余右中括号 ']'");
}
} else if (char === "{") {
openCurly++;
} else if (char === "}") {
openCurly--;
if (openCurly < 0) {
throw new ApprovalRuleValidationError("检测到未匹配的多余右花括号 '}'");
}
}
}
if (openSquare > 0) {
throw new ApprovalRuleValidationError("检测到未闭合的左中括号 '['");
}
if (openCurly > 0) {
throw new ApprovalRuleValidationError("检测到未闭合的左花括号 '{'");
}
}