@fitlab-ai/agent-infra 0.7.7 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +2 -0
  2. package/README.zh-CN.md +2 -0
  3. package/bin/cli.ts +42 -15
  4. package/dist/bin/cli.js +46 -16
  5. package/dist/lib/decide.js +110 -0
  6. package/dist/lib/run/host.js +39 -0
  7. package/dist/lib/run/index.js +193 -0
  8. package/dist/lib/run/prompt.js +2 -0
  9. package/dist/lib/run/skills.js +29 -0
  10. package/dist/lib/run/tui.js +35 -0
  11. package/dist/lib/sandbox/capture.js +158 -0
  12. package/dist/lib/sandbox/commands/create.js +58 -9
  13. package/dist/lib/sandbox/commands/enter.js +7 -3
  14. package/dist/lib/sandbox/credentials.js +42 -3
  15. package/dist/lib/sandbox/runtimes/base.dockerfile +13 -0
  16. package/dist/lib/server/adapters/_contract.js +9 -0
  17. package/dist/lib/server/adapters/feishu/index.js +40 -0
  18. package/dist/lib/server/adapters/feishu/transport.js +95 -0
  19. package/dist/lib/server/auth.js +19 -0
  20. package/dist/lib/server/config.js +183 -0
  21. package/dist/lib/server/daemon.js +96 -0
  22. package/dist/lib/server/index.js +47 -0
  23. package/dist/lib/server/logger.js +34 -0
  24. package/dist/lib/server/plugin-loader.js +73 -0
  25. package/dist/lib/server/process-control.js +200 -0
  26. package/dist/lib/server/protocol.js +69 -0
  27. package/dist/lib/server/redact.js +12 -0
  28. package/dist/lib/server/runner.js +75 -0
  29. package/dist/lib/server/streamer.js +44 -0
  30. package/dist/lib/task/commands/decisions.js +258 -0
  31. package/dist/lib/task/commands/log.js +38 -41
  32. package/dist/lib/task/commands/status.js +144 -45
  33. package/dist/lib/task/index.js +9 -0
  34. package/dist/lib/task/ledger.js +66 -0
  35. package/dist/lib/task/sections.js +30 -1
  36. package/lib/decide.ts +124 -0
  37. package/lib/run/host.ts +47 -0
  38. package/lib/run/index.ts +237 -0
  39. package/lib/run/prompt.ts +1 -0
  40. package/lib/run/skills.ts +34 -0
  41. package/lib/run/tui.ts +40 -0
  42. package/lib/sandbox/capture.ts +215 -0
  43. package/lib/sandbox/commands/create.ts +64 -12
  44. package/lib/sandbox/commands/enter.ts +8 -2
  45. package/lib/sandbox/credentials.ts +57 -3
  46. package/lib/sandbox/runtimes/base.dockerfile +13 -0
  47. package/lib/server/adapters/_contract.ts +42 -0
  48. package/lib/server/adapters/feishu/index.ts +47 -0
  49. package/lib/server/adapters/feishu/transport.ts +128 -0
  50. package/lib/server/auth.ts +28 -0
  51. package/lib/server/config.ts +228 -0
  52. package/lib/server/daemon.ts +110 -0
  53. package/lib/server/index.ts +50 -0
  54. package/lib/server/logger.ts +48 -0
  55. package/lib/server/plugin-loader.ts +84 -0
  56. package/lib/server/process-control.ts +225 -0
  57. package/lib/server/protocol.ts +79 -0
  58. package/lib/server/redact.ts +12 -0
  59. package/lib/server/runner.ts +95 -0
  60. package/lib/server/server.schema.json +127 -0
  61. package/lib/server/streamer.ts +57 -0
  62. package/lib/task/commands/decisions.ts +272 -0
  63. package/lib/task/commands/log.ts +38 -39
  64. package/lib/task/commands/status.ts +200 -58
  65. package/lib/task/index.ts +9 -0
  66. package/lib/task/ledger.ts +73 -0
  67. package/lib/task/sections.ts +30 -1
  68. package/package.json +8 -3
  69. package/templates/.agents/QUICKSTART.zh-CN.md +2 -2
  70. package/templates/.agents/rules/issue-fields.github.en.md +1 -1
  71. package/templates/.agents/rules/issue-fields.github.zh-CN.md +1 -1
  72. package/templates/.agents/rules/next-step-output.en.md +5 -1
  73. package/templates/.agents/rules/next-step-output.zh-CN.md +5 -1
  74. package/templates/.agents/rules/no-mid-flow-questions.en.md +7 -2
  75. package/templates/.agents/rules/no-mid-flow-questions.zh-CN.md +7 -2
  76. package/templates/.agents/rules/pr-sync.github.en.md +3 -3
  77. package/templates/.agents/rules/pr-sync.github.zh-CN.md +3 -3
  78. package/templates/.agents/rules/review-handshake.en.md +5 -1
  79. package/templates/.agents/rules/review-handshake.zh-CN.md +5 -1
  80. package/templates/.agents/rules/task-management.en.md +2 -2
  81. package/templates/.agents/rules/task-management.zh-CN.md +2 -2
  82. package/templates/.agents/scripts/lib/post-review-commit.js +15 -18
  83. package/templates/.agents/scripts/validate-artifact.js +8 -0
  84. package/templates/.agents/skills/analyze-task/SKILL.en.md +15 -3
  85. package/templates/.agents/skills/analyze-task/SKILL.zh-CN.md +15 -3
  86. package/templates/.agents/skills/analyze-task/config/verify.en.json +2 -1
  87. package/templates/.agents/skills/analyze-task/config/verify.zh-CN.json +2 -1
  88. package/templates/.agents/skills/code-task/SKILL.en.md +2 -2
  89. package/templates/.agents/skills/code-task/SKILL.zh-CN.md +3 -3
  90. package/templates/.agents/skills/code-task/reference/dual-mode.en.md +1 -1
  91. package/templates/.agents/skills/code-task/reference/dual-mode.zh-CN.md +1 -1
  92. package/templates/.agents/skills/code-task/reference/fix-mode.en.md +3 -3
  93. package/templates/.agents/skills/code-task/reference/fix-mode.zh-CN.md +4 -4
  94. package/templates/.agents/skills/complete-task/SKILL.en.md +1 -0
  95. package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +1 -0
  96. package/templates/.agents/skills/complete-task/config/verify.en.json +2 -1
  97. package/templates/.agents/skills/complete-task/config/verify.zh-CN.json +2 -1
  98. package/templates/.agents/skills/create-pr/reference/comment-publish.en.md +1 -1
  99. package/templates/.agents/skills/create-pr/reference/comment-publish.zh-CN.md +1 -1
  100. package/templates/.agents/skills/create-task/SKILL.en.md +1 -3
  101. package/templates/.agents/skills/create-task/SKILL.zh-CN.md +1 -3
  102. package/templates/.agents/skills/import-codescan/SKILL.en.md +0 -3
  103. package/templates/.agents/skills/import-codescan/SKILL.zh-CN.md +0 -3
  104. package/templates/.agents/skills/import-dependabot/SKILL.en.md +0 -1
  105. package/templates/.agents/skills/import-dependabot/SKILL.zh-CN.md +0 -1
  106. package/templates/.agents/skills/import-issue/SKILL.en.md +1 -2
  107. package/templates/.agents/skills/import-issue/SKILL.zh-CN.md +1 -2
  108. package/templates/.agents/skills/plan-task/SKILL.en.md +1 -2
  109. package/templates/.agents/skills/plan-task/SKILL.zh-CN.md +1 -2
  110. package/templates/.agents/skills/review-analysis/SKILL.en.md +2 -2
  111. package/templates/.agents/skills/review-analysis/SKILL.zh-CN.md +2 -2
  112. package/templates/.agents/skills/review-analysis/config/verify.en.json +1 -1
  113. package/templates/.agents/skills/review-analysis/config/verify.zh-CN.json +1 -1
  114. package/templates/.agents/skills/review-analysis/reference/output-templates.en.md +11 -11
  115. package/templates/.agents/skills/review-analysis/reference/output-templates.zh-CN.md +11 -11
  116. package/templates/.agents/skills/review-analysis/reference/report-template.en.md +4 -4
  117. package/templates/.agents/skills/review-analysis/reference/report-template.zh-CN.md +4 -4
  118. package/templates/.agents/skills/review-analysis/reference/review-criteria.en.md +5 -5
  119. package/templates/.agents/skills/review-analysis/reference/review-criteria.zh-CN.md +5 -5
  120. package/templates/.agents/skills/review-code/SKILL.en.md +4 -4
  121. package/templates/.agents/skills/review-code/SKILL.zh-CN.md +4 -4
  122. package/templates/.agents/skills/review-code/config/verify.en.json +1 -1
  123. package/templates/.agents/skills/review-code/config/verify.zh-CN.json +1 -1
  124. package/templates/.agents/skills/review-code/reference/output-templates.en.md +16 -16
  125. package/templates/.agents/skills/review-code/reference/output-templates.zh-CN.md +12 -12
  126. package/templates/.agents/skills/review-code/reference/report-template.en.md +4 -4
  127. package/templates/.agents/skills/review-code/reference/report-template.zh-CN.md +4 -4
  128. package/templates/.agents/skills/review-code/reference/review-criteria.en.md +5 -5
  129. package/templates/.agents/skills/review-code/reference/review-criteria.zh-CN.md +5 -5
  130. package/templates/.agents/skills/review-plan/SKILL.en.md +2 -2
  131. package/templates/.agents/skills/review-plan/SKILL.zh-CN.md +2 -2
  132. package/templates/.agents/skills/review-plan/config/verify.en.json +1 -1
  133. package/templates/.agents/skills/review-plan/config/verify.zh-CN.json +1 -1
  134. package/templates/.agents/skills/review-plan/reference/output-templates.en.md +11 -11
  135. package/templates/.agents/skills/review-plan/reference/output-templates.zh-CN.md +11 -11
  136. package/templates/.agents/skills/review-plan/reference/report-template.en.md +4 -4
  137. package/templates/.agents/skills/review-plan/reference/report-template.zh-CN.md +4 -4
  138. package/templates/.agents/skills/review-plan/reference/review-criteria.en.md +5 -5
  139. package/templates/.agents/skills/review-plan/reference/review-criteria.zh-CN.md +5 -5
  140. package/templates/.agents/templates/task.en.md +3 -3
  141. package/templates/.agents/templates/task.zh-CN.md +3 -3
  142. package/templates/.github/workflows/metadata-sync.yml +0 -18
@@ -0,0 +1,95 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ export type RunnerResult = {
6
+ exitCode: number | null;
7
+ signal: NodeJS.Signals | null;
8
+ stdout: string;
9
+ stderr: string;
10
+ };
11
+
12
+ export type RunnerOptions = {
13
+ spawn?: (file: string, args: string[], onChunk?: (chunk: string) => void | Promise<void>) => Promise<RunnerResult>;
14
+ onChunk?: (chunk: string) => void | Promise<void>;
15
+ };
16
+
17
+ function resolveCommand(file: string): string {
18
+ if (process.platform !== 'win32' || path.extname(file)) {
19
+ return file;
20
+ }
21
+
22
+ const pathValue = process.env.Path || process.env.PATH || '';
23
+ const extensions = (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
24
+ for (const dir of pathValue.split(path.delimiter).filter(Boolean)) {
25
+ for (const extension of extensions) {
26
+ const lowerCandidate = path.join(dir, `${file}${extension.toLowerCase()}`);
27
+ if (fs.existsSync(lowerCandidate)) return lowerCandidate;
28
+ const upperCandidate = path.join(dir, `${file}${extension.toUpperCase()}`);
29
+ if (fs.existsSync(upperCandidate)) return upperCandidate;
30
+ }
31
+ }
32
+
33
+ return file;
34
+ }
35
+
36
+ function needsShell(file: string): boolean {
37
+ return process.platform === 'win32' && /\.(?:bat|cmd)$/i.test(file);
38
+ }
39
+
40
+ function spawnCapture(
41
+ file: string,
42
+ args: string[],
43
+ onChunk?: (chunk: string) => void | Promise<void>
44
+ ): Promise<RunnerResult> {
45
+ return new Promise((resolve, reject) => {
46
+ const resolvedFile = resolveCommand(file);
47
+ const child = spawn(resolvedFile, args, {
48
+ stdio: ['ignore', 'pipe', 'pipe'],
49
+ shell: needsShell(resolvedFile)
50
+ });
51
+ let stdout = '';
52
+ let stderr = '';
53
+ let settled = false;
54
+ let pendingChunks = Promise.resolve();
55
+
56
+ const rejectOnce = (error: unknown): void => {
57
+ if (settled) return;
58
+ settled = true;
59
+ reject(error);
60
+ };
61
+
62
+ const resolveOnce = (result: RunnerResult): void => {
63
+ if (settled) return;
64
+ settled = true;
65
+ resolve(result);
66
+ };
67
+
68
+ const enqueueChunk = (chunk: string): void => {
69
+ if (!onChunk) return;
70
+ pendingChunks = pendingChunks.then(() => onChunk(chunk));
71
+ pendingChunks.catch(rejectOnce);
72
+ };
73
+
74
+ child.stdout.setEncoding('utf8');
75
+ child.stderr.setEncoding('utf8');
76
+ child.stdout.on('data', (chunk) => {
77
+ stdout += chunk;
78
+ enqueueChunk(chunk);
79
+ });
80
+ child.stderr.on('data', (chunk) => {
81
+ stderr += chunk;
82
+ enqueueChunk(chunk);
83
+ });
84
+ child.on('error', rejectOnce);
85
+ child.on('close', (exitCode, signal) => {
86
+ pendingChunks
87
+ .then(() => resolveOnce({ exitCode, signal, stdout, stderr }))
88
+ .catch(rejectOnce);
89
+ });
90
+ });
91
+ }
92
+
93
+ export async function runAi(args: string[], options: RunnerOptions = {}): Promise<RunnerResult> {
94
+ return (options.spawn ?? spawnCapture)('ai', args, options.onChunk);
95
+ }
@@ -0,0 +1,127 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://github.com/fitlab-ai/agent-infra/lib/server/server.schema.json",
4
+ "title": "agent-infra server configuration",
5
+ "description": "Schema for .agents/server.json. Secrets (appSecret, tokens, passwords) must NOT be committed here — put them in .agents/server.local.json or AGENT_INFRA_SERVER_* environment variables.",
6
+ "type": "object",
7
+ "additionalProperties": true,
8
+ "properties": {
9
+ "$schema": {
10
+ "type": "string"
11
+ },
12
+ "log": {
13
+ "type": "object",
14
+ "additionalProperties": false,
15
+ "properties": {
16
+ "path": {
17
+ "type": "string",
18
+ "description": "Log file path. Defaults to ~/.agent-infra/logs/<project>/<repo-hash>/server.log (outside the repo; the repo-hash isolates checkouts that share a project). Relative paths resolve against the repo root; absolute paths are used as-is."
19
+ },
20
+ "rotateAtBytes": {
21
+ "type": "integer",
22
+ "minimum": 0,
23
+ "description": "Rotate the log to <path>.1 at startup if it already exceeds this size.",
24
+ "default": 52428800
25
+ }
26
+ }
27
+ },
28
+ "heartbeatMs": {
29
+ "type": "integer",
30
+ "minimum": 1,
31
+ "description": "Interval between daemon heartbeat log lines, in milliseconds.",
32
+ "default": 30000
33
+ },
34
+ "adapters": {
35
+ "type": "object",
36
+ "description": "Per-adapter configuration. Only adapters with enabled=true are loaded.",
37
+ "properties": {
38
+ "feishu": {
39
+ "type": "object",
40
+ "description": "Feishu (Lark) IM adapter. The appSecret must NOT be committed here — put it in .agents/server.local.json or AGENT_INFRA_SERVER_adapters__feishu__appSecret.",
41
+ "properties": {
42
+ "enabled": {
43
+ "type": "boolean",
44
+ "default": false
45
+ },
46
+ "appId": {
47
+ "type": "string",
48
+ "description": "Feishu self-built app App ID."
49
+ },
50
+ "domain": {
51
+ "type": "string",
52
+ "enum": ["feishu", "lark"],
53
+ "default": "feishu",
54
+ "description": "Open platform domain: feishu (default) or lark."
55
+ }
56
+ },
57
+ "required": ["enabled"]
58
+ }
59
+ },
60
+ "additionalProperties": {
61
+ "type": "object",
62
+ "properties": {
63
+ "enabled": {
64
+ "type": "boolean",
65
+ "default": false
66
+ }
67
+ },
68
+ "required": ["enabled"]
69
+ }
70
+ },
71
+ "command": {
72
+ "type": "object",
73
+ "description": "Command protocol defaults and skill allow-list.",
74
+ "additionalProperties": false,
75
+ "properties": {
76
+ "defaultTui": {
77
+ "type": "string",
78
+ "enum": ["claude", "codex", "gemini", "opencode"],
79
+ "default": "codex"
80
+ },
81
+ "skillTuiDefaults": {
82
+ "type": "object",
83
+ "additionalProperties": {
84
+ "type": "string",
85
+ "enum": ["claude", "codex", "gemini", "opencode"]
86
+ }
87
+ },
88
+ "allowedSkills": {
89
+ "type": "array",
90
+ "items": { "type": "string" }
91
+ }
92
+ }
93
+ },
94
+ "auth": {
95
+ "type": "object",
96
+ "description": "Adapter-qualified user roles. Keys look like feishu:ou_xxx.",
97
+ "additionalProperties": false,
98
+ "properties": {
99
+ "users": {
100
+ "type": "object",
101
+ "additionalProperties": {
102
+ "type": "object",
103
+ "additionalProperties": true,
104
+ "properties": {
105
+ "role": {
106
+ "type": "string",
107
+ "enum": ["read", "write", "exec"]
108
+ },
109
+ "name": { "type": "string" }
110
+ },
111
+ "required": ["role"]
112
+ }
113
+ }
114
+ }
115
+ },
116
+ "stream": {
117
+ "type": "object",
118
+ "additionalProperties": false,
119
+ "properties": {
120
+ "throttleMs": { "type": "integer", "minimum": 0, "default": 1500 },
121
+ "chunkChars": { "type": "integer", "minimum": 1, "default": 4000 },
122
+ "tailChars": { "type": "integer", "minimum": 1, "default": 8000 },
123
+ "timeoutMs": { "type": "integer", "minimum": 1, "default": 1800000 }
124
+ }
125
+ }
126
+ }
127
+ }
@@ -0,0 +1,57 @@
1
+ import { redactSecrets } from './redact.ts';
2
+ import type { RunnerResult } from './runner.ts';
3
+
4
+ export type StreamOptions = {
5
+ title: string;
6
+ chunkChars?: number;
7
+ throttleMs?: number;
8
+ };
9
+
10
+ function chunks(text: string, size: number): string[] {
11
+ if (text.length === 0) return [];
12
+ const out: string[] = [];
13
+ for (let i = 0; i < text.length; i += size) {
14
+ out.push(text.slice(i, i + size));
15
+ }
16
+ return out;
17
+ }
18
+
19
+ export async function streamCommand(
20
+ options: StreamOptions,
21
+ run: (emit?: (chunk: string) => Promise<void>) => Promise<RunnerResult>,
22
+ send: (text: string) => Promise<void>
23
+ ): Promise<RunnerResult> {
24
+ await send(`started ${options.title}`);
25
+ const size = options.chunkChars ?? 4000;
26
+ const throttleMs = options.throttleMs ?? 0;
27
+ let streamed = false;
28
+ let buffer = '';
29
+ let lastFlush = 0;
30
+
31
+ const flush = async (): Promise<void> => {
32
+ if (!buffer) return;
33
+ const text = redactSecrets(buffer);
34
+ buffer = '';
35
+ lastFlush = Date.now();
36
+ for (const chunk of chunks(text, size)) {
37
+ await send(chunk);
38
+ }
39
+ };
40
+
41
+ const emit = async (chunk: string): Promise<void> => {
42
+ streamed = true;
43
+ buffer += chunk;
44
+ const due = throttleMs === 0 || Date.now() - lastFlush >= throttleMs;
45
+ if (buffer.length >= size || due) {
46
+ await flush();
47
+ }
48
+ };
49
+
50
+ const result = await run(emit);
51
+ if (!streamed) {
52
+ buffer += [result.stdout, result.stderr].filter(Boolean).join('\n');
53
+ }
54
+ await flush();
55
+ await send(`finished ${options.title} exitCode=${result.exitCode} signal=${result.signal ?? 'null'}`);
56
+ return result;
57
+ }
@@ -0,0 +1,272 @@
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 };
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import { formatTable } from '../../table.ts';
3
3
  import { resolveTaskRef } from '../resolve-ref.ts';
4
+ import { parseLedger, HUMAN_DECISION_STATUSES, type LedgerRow } from '../ledger.ts';
4
5
 
5
6
  const USAGE = `Usage: ai task log <N | #N | TASK-id>
6
7
 
@@ -12,7 +13,7 @@ completion time (or '(in progress)' while still running).
12
13
  Columns: # (row) / STEP / AGENT / STARTED / DONE / NOTE
13
14
  A human-executed step shows AGENT as 'human' and, when it has no start marker,
14
15
  a '-' STARTED placeholder. Review-step NOTE also carries two human counts in
15
- the verdict list, right after blockers/major/minor: manual-verify (env-blocked)
16
+ the verdict list, right after blockers/major/minor: manual-validation
16
17
  and human-decision (current ledger stage total).
17
18
  `;
18
19
 
@@ -20,7 +21,6 @@ const TABLE_HEADERS = ['#', 'STEP', 'AGENT', 'STARTED', 'DONE', 'NOTE'] as const
20
21
 
21
22
  // The activity-log H2 heading is language-dependent (zh template / en template).
22
23
  const HEADING_RE = /^##\s+(活动日志|Activity Log)\s*$/;
23
- const LEDGER_HEADING_RE = /^##\s+(审查分歧账本|Review Disagreement Ledger)\s*$/;
24
24
  const NEXT_H2_RE = /^##\s/;
25
25
  // `- {time} — **{step}** by {agent} — {note}` ; the separator is an em-dash
26
26
  // (U+2014). STEP/AGENT are non-greedy so a note that itself contains ' — ' or
@@ -30,7 +30,6 @@ const ENTRY_RE =
30
30
 
31
31
  type LogEntry = { time: string; step: string; agent: string; note: string };
32
32
  type ReviewStage = 'analysis' | 'plan' | 'code';
33
- type LedgerRow = { stage: string; status: string };
34
33
 
35
34
  // One rendered row = one step instance. `started`/`done` are timestamps; an empty
36
35
  // `done` with a non-empty `started` means the step is still in flight, while an
@@ -47,11 +46,6 @@ const STARTED_SUFFIX_RE = /\s*\[started\]\s*$/;
47
46
  // note these differ from the `.airc.json` long names claude-code/gemini-cli).
48
47
  // Any other executor token (a human name, possibly CJK) is treated as human.
49
48
  const KNOWN_AI_AGENTS = new Set(['claude', 'codex', 'gemini', 'opencode', 'cursor']);
50
- const HUMAN_DECISION_STATUSES = new Set(['needs-human-decision', 'human-decided']);
51
- const ENV_BLOCKED_RE = /\(\+\s*(\d+)\s+env-blocked\)/i;
52
- // Same match plus any leading whitespace, so folding the count into the verdict
53
- // text drops the redundant `(+ n env-blocked)` fragment without leaving a gap.
54
- const ENV_BLOCKED_STRIP_RE = /\s*\(\+\s*\d+\s+env-blocked\)/i;
55
49
  const REVIEW_STAGE_PREFIXES: { prefix: string; stage: ReviewStage }[] = [
56
50
  { prefix: 'Review Analysis', stage: 'analysis' },
57
51
  { prefix: 'Review Plan', stage: 'plan' },
@@ -111,27 +105,6 @@ function pairEntries(entries: LogEntry[]): StepRow[] {
111
105
  return rows;
112
106
  }
113
107
 
114
- function parseReviewLedger(content: string): LedgerRow[] {
115
- const lines = content.split('\n');
116
- let i = 0;
117
- while (i < lines.length && !LEDGER_HEADING_RE.test(lines[i]!)) i += 1;
118
- if (i >= lines.length) return [];
119
-
120
- const rows: LedgerRow[] = [];
121
- for (let j = i + 1; j < lines.length; j += 1) {
122
- if (NEXT_H2_RE.test(lines[j]!)) break;
123
- const line = lines[j]!.trim();
124
- if (!line.startsWith('|')) continue;
125
- const cells = line
126
- .split('|')
127
- .slice(1, -1)
128
- .map((cell) => cell.trim());
129
- if (cells.length < 6 || cells[0] === 'id' || /^-+$/.test(cells[0] ?? '')) continue;
130
- rows.push({ stage: cells[1]!, status: cells[4]! });
131
- }
132
- return rows;
133
- }
134
-
135
108
  function countHumanDecisionsByStage(rows: LedgerRow[]): Map<ReviewStage, number> {
136
109
  const counts = new Map<ReviewStage, number>();
137
110
  for (const row of rows) {
@@ -149,9 +122,31 @@ function reviewStageForStep(step: string): ReviewStage | undefined {
149
122
  return REVIEW_STAGE_PREFIXES.find(({ prefix }) => step.startsWith(prefix))?.stage;
150
123
  }
151
124
 
125
+ function splitArtifactSuffix(note: string): { verdict: string; suffix: string } {
126
+ const arrow = note.indexOf(' → ');
127
+ return arrow === -1 ? { verdict: note, suffix: '' } : { verdict: note.slice(0, arrow), suffix: note.slice(arrow) };
128
+ }
129
+
130
+ function fieldNumber(field: string, label: string): number | undefined {
131
+ const trimmed = field.trim();
132
+ const colon = trimmed.indexOf(':');
133
+ if (colon === -1) return undefined;
134
+ if (trimmed.slice(0, colon).trim().toLowerCase() !== label) return undefined;
135
+ const value = Number(trimmed.slice(colon + 1).trim());
136
+ return Number.isInteger(value) && value >= 0 ? value : undefined;
137
+ }
138
+
152
139
  function humanValidationCount(note: string): number {
153
- const match = ENV_BLOCKED_RE.exec(note);
154
- return match ? Number(match[1]) : 0;
140
+ const { verdict } = splitArtifactSuffix(note);
141
+ for (const field of verdict.split(',')) {
142
+ const value = fieldNumber(field, 'manual-validation');
143
+ if (value !== undefined) return value;
144
+ }
145
+ return 0;
146
+ }
147
+
148
+ function isHumanCountField(field: string): boolean {
149
+ return fieldNumber(field, 'manual-validation') !== undefined || fieldNumber(field, 'human-decision') !== undefined;
155
150
  }
156
151
 
157
152
  // A step is human-executed when its agent token is not a known AI token. Take
@@ -164,13 +159,17 @@ function isHumanAgent(agent: string): boolean {
164
159
 
165
160
  // Fold the two human counts into a review row's verdict NOTE: comma-joined, right
166
161
  // after the blockers/major/minor list and before the ` → artifact` link, mirroring
167
- // the review count line. The raw `(+ n env-blocked)` fragment is dropped so the
168
- // env-blocked number is not shown twice (it becomes the manual-verify count).
169
- function foldHumanCounts(note: string, decisions: number, envBlocked: number): string {
170
- const base = note.replace(ENV_BLOCKED_STRIP_RE, '');
171
- const group = `Manual-verify: ${envBlocked}, Human-decision: ${decisions}`;
172
- const arrow = base.indexOf(' → ');
173
- return arrow === -1 ? `${base}, ${group}` : `${base.slice(0, arrow)}, ${group}${base.slice(arrow)}`;
162
+ // the review count line. Review done notes already carry `Manual-validation` as a
163
+ // source field, so build the final verdict field list once instead of cleaning a
164
+ // previously rendered string.
165
+ function foldHumanCounts(note: string, decisions: number, manualValidation: number): string {
166
+ const { verdict, suffix } = splitArtifactSuffix(note);
167
+ const fields = verdict
168
+ .split(',')
169
+ .map((field) => field.trim())
170
+ .filter((field) => field !== '' && !isHumanCountField(field));
171
+ const group = `Manual-validation: ${manualValidation}, Human-decision: ${decisions}`;
172
+ return `${[...fields, group].join(', ')}${suffix}`;
174
173
  }
175
174
 
176
175
  function log(args: string[] = []): void {
@@ -200,7 +199,7 @@ function log(args: string[] = []): void {
200
199
  return;
201
200
  }
202
201
  const steps = pairEntries(entries);
203
- const humanDecisionCounts = countHumanDecisionsByStage(parseReviewLedger(content));
202
+ const humanDecisionCounts = countHumanDecisionsByStage(parseLedger(content));
204
203
  const rows = steps.map((s, idx) => {
205
204
  const stage = reviewStageForStep(s.step);
206
205
  const note = stage