|
| 1 | +import fs from 'node:fs'; |
| 2 | +import path from 'node:path'; |
| 3 | +import { execFileSync } from 'node:child_process'; |
| 4 | +import { VERSION } from './version.ts'; |
| 5 | +import { resolveTaskRef } from './task/resolve-ref.ts'; |
| 6 | + |
| 7 | +const TASK_ID_RE = /^TASK-\d{8}-\d{6}$/; |
| 8 | + |
| 9 | +type DecideOptions = { |
| 10 | + repoRoot?: string; |
| 11 | + now?: () => string; |
| 12 | + version?: string; |
| 13 | +}; |
| 14 | + |
| 15 | +function detectRepoRoot(): string { |
| 16 | + return execFileSync('git', ['rev-parse', '--show-toplevel'], { |
| 17 | + encoding: 'utf8', |
| 18 | + stdio: ['pipe', 'pipe', 'pipe'] |
| 19 | + }).trim(); |
| 20 | +} |
| 21 | + |
| 22 | +function defaultNow(): string { |
| 23 | + return new Intl.DateTimeFormat('sv-SE', { |
| 24 | + timeZoneName: 'longOffset', |
| 25 | + year: 'numeric', |
| 26 | + month: '2-digit', |
| 27 | + day: '2-digit', |
| 28 | + hour: '2-digit', |
| 29 | + minute: '2-digit', |
| 30 | + second: '2-digit', |
| 31 | + hour12: false |
| 32 | + }) |
| 33 | + .format(new Date()) |
| 34 | + .replace(' GMT', ''); |
| 35 | +} |
| 36 | + |
| 37 | +function taskPath(repoRoot: string, ref: string): string { |
| 38 | + if (!TASK_ID_RE.test(ref)) { |
| 39 | + const resolved = resolveTaskRef(ref); |
| 40 | + if (!resolved.ok) throw new Error(resolved.message); |
| 41 | + if (!resolved.taskDir.includes(`${path.join('.agents', 'workspace', 'active')}${path.sep}`)) { |
| 42 | + throw new Error(`task ${resolved.taskId} is not active`); |
| 43 | + } |
| 44 | + return resolved.taskMdPath; |
| 45 | + } |
| 46 | + const candidate = path.join(repoRoot, '.agents', 'workspace', 'active', ref, 'task.md'); |
| 47 | + if (!fs.existsSync(candidate)) throw new Error(`active task not found: ${ref}`); |
| 48 | + return candidate; |
| 49 | +} |
| 50 | + |
| 51 | +function replaceFrontmatterField(content: string, field: string, value: string): string { |
| 52 | + const re = new RegExp(`^${field}:.*$`, 'm'); |
| 53 | + if (re.test(content)) return content.replace(re, `${field}: ${value}`); |
| 54 | + return content.replace(/^---\n/, `---\n${field}: ${value}\n`); |
| 55 | +} |
| 56 | + |
| 57 | +function replaceLedgerRow(content: string, hdId: string): { content: string; found: boolean; pending: boolean } { |
| 58 | + const lines = content.split('\n'); |
| 59 | + let found = false; |
| 60 | + let pending = false; |
| 61 | + for (let i = 0; i < lines.length; i += 1) { |
| 62 | + const line = lines[i] as string; |
| 63 | + if (!line.trim().startsWith(`| ${hdId} |`)) continue; |
| 64 | + found = true; |
| 65 | + const cells = line.split('|').slice(1, -1).map((cell) => cell.trim()); |
| 66 | + if (cells[4] !== 'needs-human-decision') break; |
| 67 | + pending = true; |
| 68 | + cells[4] = 'human-decided'; |
| 69 | + cells[5] = `task.md#${hdId}`; |
| 70 | + lines[i] = `| ${cells.join(' | ')} |`; |
| 71 | + break; |
| 72 | + } |
| 73 | + return { content: lines.join('\n'), found, pending }; |
| 74 | +} |
| 75 | + |
| 76 | +function appendUnderHeading(content: string, heading: string, block: string): string { |
| 77 | + if (!content.includes(`${heading}\n`)) { |
| 78 | + return `${content.trimEnd()}\n\n${heading}\n\n${block}\n`; |
| 79 | + } |
| 80 | + const idx = content.indexOf(`${heading}\n`) + heading.length + 1; |
| 81 | + const before = content.slice(0, idx); |
| 82 | + const after = content.slice(idx); |
| 83 | + return `${before}\n${block}\n${after.replace(/^\n/, '')}`; |
| 84 | +} |
| 85 | + |
| 86 | +export async function decide(args: string[], options: DecideOptions = {}): Promise<number> { |
| 87 | + const [taskRef, hdId, ...decisionParts] = args; |
| 88 | + if (!taskRef || !hdId || decisionParts.length === 0) { |
| 89 | + process.stderr.write('Usage: ai decide <task-ref> <HD-id> <decision>\n'); |
| 90 | + return 1; |
| 91 | + } |
| 92 | + try { |
| 93 | + const repoRoot = options.repoRoot ?? detectRepoRoot(); |
| 94 | + const file = taskPath(repoRoot, taskRef); |
| 95 | + let content = fs.readFileSync(file, 'utf8'); |
| 96 | + const replaced = replaceLedgerRow(content, hdId); |
| 97 | + if (!replaced.found) throw new Error(`${hdId} not found in review ledger`); |
| 98 | + if (!replaced.pending) throw new Error(`${hdId} is not needs-human-decision`); |
| 99 | + content = replaced.content; |
| 100 | + const now = (options.now ?? defaultNow)(); |
| 101 | + content = replaceFrontmatterField(content, 'updated_at', now); |
| 102 | + content = replaceFrontmatterField(content, 'agent_infra_version', options.version ?? VERSION); |
| 103 | + const decision = decisionParts.join(' '); |
| 104 | + content = appendUnderHeading( |
| 105 | + content, |
| 106 | + '## 人工裁决', |
| 107 | + `### ${hdId}\n\n- **裁决时间**:${now}\n- **裁决结果**:${decision}` |
| 108 | + ); |
| 109 | + content = appendUnderHeading( |
| 110 | + content, |
| 111 | + '## 活动日志', |
| 112 | + `- ${now} — **Human Decision** by human — ${hdId} decided` |
| 113 | + ); |
| 114 | + fs.writeFileSync(file, content); |
| 115 | + return 0; |
| 116 | + } catch (error) { |
| 117 | + process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`); |
| 118 | + return 1; |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +export async function cmdDecide(args: string[]): Promise<void> { |
| 123 | + process.exitCode = await decide(args); |
| 124 | +} |
0 commit comments