|
| 1 | +import fs from 'node:fs'; |
| 2 | +import path from 'node:path'; |
| 3 | +import { formatTable } from '../../table.ts'; |
| 4 | +import { resolveTaskRef } from '../resolve-ref.ts'; |
| 5 | +import { parseLedger, HUMAN_DECISION_STATUSES, type LedgerRow } from '../ledger.ts'; |
| 6 | +import { extractSubSection } from '../sections.ts'; |
| 7 | + |
| 8 | +const USAGE = `Usage: ai task decisions <N | #N | TASK-id> [selector] [options] |
| 9 | +
|
| 10 | +Lists the human-decision (HD-) items recorded in a task's review disagreement |
| 11 | +ledger, or prints the full detail block for a single item. Read-only. |
| 12 | +
|
| 13 | + <ref> Bare numeric / '#N' short id, or a full TASK-YYYYMMDD-HHMMSS id. |
| 14 | + [selector] Ordinal (1-based) or HD id (e.g. 'HD-3') to show one item's detail. |
| 15 | +
|
| 16 | +Options: |
| 17 | + --all Include already-decided (human-decided) items, not just pending. |
| 18 | + --stage <s> Filter to one stage: analysis | plan | code. |
| 19 | + --format <fmt> Output format: text (default) | markdown. |
| 20 | + -h, --help Show this help. |
| 21 | +
|
| 22 | +Aliased as 'ai task d'. |
| 23 | +`; |
| 24 | + |
| 25 | +const STAGES = new Set(['analysis', 'plan', 'code']); |
| 26 | +const FORMATS = new Set(['text', 'markdown']); |
| 27 | +const HD_ID_RE = /^HD-\d+$/; |
| 28 | + |
| 29 | +function fail(message: string): void { |
| 30 | + process.stderr.write(`ai task decisions: ${message}\n`); |
| 31 | + process.exitCode = 1; |
| 32 | +} |
| 33 | + |
| 34 | +type ParsedArgs = { |
| 35 | + positionals: string[]; |
| 36 | + all: boolean; |
| 37 | + stage?: string; |
| 38 | + format: string; |
| 39 | +}; |
| 40 | + |
| 41 | +// Returns null and sets the exit code when an option is malformed. |
| 42 | +function parseArgs(args: string[]): ParsedArgs | null { |
| 43 | + const out: ParsedArgs = { positionals: [], all: false, format: 'text' }; |
| 44 | + for (let i = 0; i < args.length; i += 1) { |
| 45 | + const a = args[i]!; |
| 46 | + if (a === '--all') { |
| 47 | + out.all = true; |
| 48 | + } else if (a === '--stage') { |
| 49 | + const v = args[i + 1]; |
| 50 | + if (v === undefined) { |
| 51 | + fail('--stage requires a value (analysis|plan|code)'); |
| 52 | + return null; |
| 53 | + } |
| 54 | + out.stage = v; |
| 55 | + i += 1; |
| 56 | + } else if (a.startsWith('--stage=')) { |
| 57 | + out.stage = a.slice('--stage='.length); |
| 58 | + } else if (a === '--format') { |
| 59 | + const v = args[i + 1]; |
| 60 | + if (v === undefined) { |
| 61 | + fail('--format requires a value (text|markdown)'); |
| 62 | + return null; |
| 63 | + } |
| 64 | + out.format = v; |
| 65 | + i += 1; |
| 66 | + } else if (a.startsWith('--format=')) { |
| 67 | + out.format = a.slice('--format='.length); |
| 68 | + } else if (a.startsWith('-')) { |
| 69 | + fail(`unknown option '${a}'`); |
| 70 | + return null; |
| 71 | + } else { |
| 72 | + out.positionals.push(a); |
| 73 | + } |
| 74 | + } |
| 75 | + return out; |
| 76 | +} |
| 77 | + |
| 78 | +// Parse `<file>.md#anchor` evidence into its filename, when present. |
| 79 | +function evidenceFile(evidence: string): string | null { |
| 80 | + const m = /([\w.-]+\.md)#/.exec(evidence); |
| 81 | + return m ? m[1]! : null; |
| 82 | +} |
| 83 | + |
| 84 | +function roundOf(file: string): number { |
| 85 | + const m = /-r(\d+)\.md$/.exec(file); |
| 86 | + return m ? Number.parseInt(m[1]!, 10) : 1; |
| 87 | +} |
| 88 | + |
| 89 | +// Locate the `### HD-N` detail block for a row. Prefer the artifact named by the |
| 90 | +// row's evidence anchor; otherwise scan analysis/plan/code artifacts and return |
| 91 | +// the block from the highest-round file that contains it. Returns '' when none |
| 92 | +// is found (caller degrades gracefully — plan B3). |
| 93 | +function findDetailBlock(row: LedgerRow, taskDir: string): string { |
| 94 | + const hinted = evidenceFile(row.evidence); |
| 95 | + if (hinted) { |
| 96 | + const p = path.join(taskDir, hinted); |
| 97 | + if (fs.existsSync(p)) { |
| 98 | + const block = extractSubSection(fs.readFileSync(p, 'utf8'), row.id); |
| 99 | + if (block) return block; |
| 100 | + } |
| 101 | + } |
| 102 | + let best = ''; |
| 103 | + let bestRound = -1; |
| 104 | + let entries: string[]; |
| 105 | + try { |
| 106 | + entries = fs.readdirSync(taskDir); |
| 107 | + } catch { |
| 108 | + return ''; |
| 109 | + } |
| 110 | + for (const file of entries) { |
| 111 | + if (!/^(analysis|plan|code)(-r\d+)?\.md$/.test(file)) continue; |
| 112 | + const block = extractSubSection(fs.readFileSync(path.join(taskDir, file), 'utf8'), row.id); |
| 113 | + if (block && roundOf(file) > bestRound) { |
| 114 | + best = block; |
| 115 | + bestRound = roundOf(file); |
| 116 | + } |
| 117 | + } |
| 118 | + return best; |
| 119 | +} |
| 120 | + |
| 121 | +// Pull the `## 人工裁决` record lines that mention this HD id, so a decided item |
| 122 | +// shows the human's recorded ruling alongside its detail block. |
| 123 | +function findDecisionRecord(id: string, content: string): string[] { |
| 124 | + const lines = content.split('\n'); |
| 125 | + let i = 0; |
| 126 | + while (i < lines.length && !/^##\s+(人工裁决|Human Decisions?)\s*$/.test(lines[i]!)) i += 1; |
| 127 | + if (i >= lines.length) return []; |
| 128 | + const idRe = new RegExp(`(^|[^\\w-])${id}(?![\\w-])`); |
| 129 | + const out: string[] = []; |
| 130 | + for (let j = i + 1; j < lines.length; j += 1) { |
| 131 | + if (/^##\s/.test(lines[j]!)) break; |
| 132 | + if (lines[j]!.trim().startsWith('-') && idRe.test(lines[j]!)) out.push(lines[j]!); |
| 133 | + } |
| 134 | + return out; |
| 135 | +} |
| 136 | + |
| 137 | +function titleOf(row: LedgerRow, taskDir: string): string { |
| 138 | + const block = findDetailBlock(row, taskDir); |
| 139 | + if (block) { |
| 140 | + return block |
| 141 | + .split('\n')[0]! |
| 142 | + .replace(/^###\s+/, '') |
| 143 | + .replace(/\s*\[needs-human-decision\]\s*$/, '') |
| 144 | + .trim(); |
| 145 | + } |
| 146 | + return row.evidence || '(无详情)'; |
| 147 | +} |
| 148 | + |
| 149 | +function renderList(rows: LedgerRow[], format: string, taskDir: string): void { |
| 150 | + if (rows.length === 0) { |
| 151 | + process.stdout.write('无待裁决项。\n'); |
| 152 | + return; |
| 153 | + } |
| 154 | + const headers = ['#', 'ID', 'STAGE', 'SEVERITY', 'STATUS', 'EVIDENCE', 'TITLE']; |
| 155 | + const data = rows.map((r, i) => [ |
| 156 | + String(i + 1), |
| 157 | + r.id, |
| 158 | + r.stage, |
| 159 | + r.severity, |
| 160 | + r.status, |
| 161 | + r.evidence, |
| 162 | + titleOf(r, taskDir) |
| 163 | + ]); |
| 164 | + if (format === 'markdown') { |
| 165 | + const sep = headers.map(() => '---'); |
| 166 | + const md = [ |
| 167 | + `| ${headers.join(' | ')} |`, |
| 168 | + `| ${sep.join(' | ')} |`, |
| 169 | + ...data.map((row) => `| ${row.join(' | ')} |`) |
| 170 | + ]; |
| 171 | + process.stdout.write(`${md.join('\n')}\n`); |
| 172 | + return; |
| 173 | + } |
| 174 | + process.stdout.write(`${formatTable(headers, data).join('\n')}\n`); |
| 175 | +} |
| 176 | + |
| 177 | +function renderDetail( |
| 178 | + rows: LedgerRow[], |
| 179 | + selector: string, |
| 180 | + format: string, |
| 181 | + taskDir: string, |
| 182 | + content: string |
| 183 | +): void { |
| 184 | + let row: LedgerRow | undefined; |
| 185 | + if (/^\d+$/.test(selector)) { |
| 186 | + const idx = Number.parseInt(selector, 10) - 1; |
| 187 | + if (idx < 0 || idx >= rows.length) { |
| 188 | + fail(`ordinal '${selector}' out of range (1..${rows.length})`); |
| 189 | + return; |
| 190 | + } |
| 191 | + row = rows[idx]; |
| 192 | + } else { |
| 193 | + const want = selector.toUpperCase(); |
| 194 | + const matches = rows.filter((r) => r.id.toUpperCase() === want); |
| 195 | + if (matches.length === 0) { |
| 196 | + fail(`no decision item matches '${selector}'`); |
| 197 | + return; |
| 198 | + } |
| 199 | + if (matches.length > 1) { |
| 200 | + fail(`duplicate id '${selector}' in ledger; select by ordinal instead`); |
| 201 | + return; |
| 202 | + } |
| 203 | + row = matches[0]; |
| 204 | + } |
| 205 | + |
| 206 | + const r = row!; |
| 207 | + const block = findDetailBlock(r, taskDir); |
| 208 | + const lines: string[] = []; |
| 209 | + if (format === 'markdown') { |
| 210 | + lines.push(`**${r.id}** (${r.stage}/${r.severity}) · status=\`${r.status}\` · evidence: \`${r.evidence}\``, ''); |
| 211 | + } else { |
| 212 | + lines.push(`${r.id} (${r.stage}/${r.severity}) status=${r.status}`, `evidence: ${r.evidence}`, ''); |
| 213 | + } |
| 214 | + if (block) { |
| 215 | + lines.push(block); |
| 216 | + } else { |
| 217 | + lines.push( |
| 218 | + `(详情块未找到:未在任务产物中定位到 \`### ${r.id}\` 锚点,可能为历史产物或尚未写入;evidence 指向 ${r.evidence})` |
| 219 | + ); |
| 220 | + } |
| 221 | + if (r.status === 'human-decided') { |
| 222 | + const record = findDecisionRecord(r.id, content); |
| 223 | + if (record.length) { |
| 224 | + lines.push('', '人工裁定:', ...record); |
| 225 | + } |
| 226 | + } |
| 227 | + process.stdout.write(`${lines.join('\n')}\n`); |
| 228 | +} |
| 229 | + |
| 230 | +function decisions(args: string[] = []): void { |
| 231 | + if (args[0] === '--help' || args[0] === '-h') { |
| 232 | + process.stdout.write(USAGE); |
| 233 | + return; |
| 234 | + } |
| 235 | + const parsed = parseArgs(args); |
| 236 | + if (!parsed) return; |
| 237 | + if (parsed.positionals.length === 0) { |
| 238 | + process.stdout.write(USAGE); |
| 239 | + process.exitCode = 1; |
| 240 | + return; |
| 241 | + } |
| 242 | + if (parsed.stage !== undefined && !STAGES.has(parsed.stage)) { |
| 243 | + fail(`invalid --stage '${parsed.stage}' (expected analysis|plan|code)`); |
| 244 | + return; |
| 245 | + } |
| 246 | + if (!FORMATS.has(parsed.format)) { |
| 247 | + fail(`invalid --format '${parsed.format}' (expected text|markdown)`); |
| 248 | + return; |
| 249 | + } |
| 250 | + |
| 251 | + const resolved = resolveTaskRef(parsed.positionals[0]!); |
| 252 | + if (!resolved.ok) { |
| 253 | + fail(resolved.message); |
| 254 | + return; |
| 255 | + } |
| 256 | + |
| 257 | + const content = fs.readFileSync(resolved.taskMdPath, 'utf8'); |
| 258 | + let rows = parseLedger(content).filter((r) => HD_ID_RE.test(r.id)); |
| 259 | + rows = rows.filter((r) => |
| 260 | + parsed.all ? HUMAN_DECISION_STATUSES.has(r.status) : r.status === 'needs-human-decision' |
| 261 | + ); |
| 262 | + if (parsed.stage !== undefined) rows = rows.filter((r) => r.stage === parsed.stage); |
| 263 | + |
| 264 | + const selector = parsed.positionals[1]; |
| 265 | + if (selector === undefined) { |
| 266 | + renderList(rows, parsed.format, resolved.taskDir); |
| 267 | + } else { |
| 268 | + renderDetail(rows, selector, parsed.format, resolved.taskDir, content); |
| 269 | + } |
| 270 | +} |
| 271 | + |
| 272 | +export { decisions }; |
0 commit comments