@aivin-labs/cli 1.0.51 → 1.0.57

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.
@@ -0,0 +1,370 @@
1
+ import { createHash } from 'crypto';
2
+ import YAML from 'yaml';
3
+
4
+ /**
5
+ * Ba file Markdown đi giữa Agentic, daemon và agent lập trình (11/11/2026): `CONTRACT.md` (Agentic viết, bất biến), `TEST_CHECK.md` (bộ check
6
+ * test của dự án khách, Agentic là bên duy nhất ghi), `REPORT.md` (agent viết cuối job). Mỗi file = frontmatter YAML cho máy + thân cho người
7
+ * và AI đọc. Quy tắc giữ khuôn:
8
+ * - frontmatter chỉ chứa giá trị ngắn (mã, enum, số, đường dẫn, đúng/sai) — câu chữ ở thân file, vì YAML hay hỏng nhất ở chuỗi tự do;
9
+ * - mỗi ca kiểm là một khối `#### <mã> <tên>` + mỗi trường một dòng `- <nhãn>: <giá trị>` (không bảng Markdown);
10
+ * - YAML đọc chặt: không khoá trùng, không alias, schema core (YAML 1.2 — `yes` / `on` vẫn là chữ).
11
+ * Module này chỉ đọc + kiểm; gộp kết quả vào `TEST_CHECK.md` là việc của Agentic (BE).
12
+ */
13
+
14
+ export const Risk = Object.freeze({ READ_ONLY: 'read_only', STANDARD: 'standard', STRICT: 'strict' });
15
+ export const CheckKind = Object.freeze({
16
+ COMMAND_PASSED: 'command_passed', DIFF_IN_SCOPE: 'diff_in_scope', PROTECTED_UNTOUCHED: 'protected_untouched',
17
+ TESTS_NOT_REDUCED: 'tests_not_reduced', NO_NEW_SKIPS: 'no_new_skips', CHECK_FILE_COVERED: 'check_file_covered', OUTPUTS_COMPLETE: 'outputs_complete',
18
+ });
19
+ export const ReportStatus = Object.freeze({ DONE: 'done', PARTIAL: 'partial', BLOCKED: 'blocked' });
20
+ /** Kết quả một ca trong `REPORT.md` (agent tự khai — daemon đo lại ca `auto`). */
21
+ export const CASE_RESULTS = Object.freeze(['pass', 'fail', 'blocked', 'not_tested']);
22
+ /** Trạng thái một ca trong `TEST_CHECK.md` — `stale` do Agentic đặt khi luồng đổi code sau lần `pass`. */
23
+ export const CASE_STATUSES = Object.freeze([...CASE_RESULTS, 'stale']);
24
+ /** 8 nhóm khả năng phải xét cho mỗi quy tắc. */
25
+ export const CHECK_GROUPS = Object.freeze(['main', 'boundary', 'error', 'regression', 'permission', 'legacy_data', 'concurrency', 'non_functional']);
26
+ export const CHECK_METHODS = Object.freeze(['auto', 'agent', 'manual']);
27
+ export const OUTPUT_KINDS = Object.freeze(['git_branch', 'report_md']);
28
+ const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
29
+ const MODES = ['plan', 'manual', 'accept_edits'];
30
+
31
+ /** Các mục bắt buộc ở thân `REPORT.md`, theo thứ tự. */
32
+ export const REPORT_SECTIONS = Object.freeze(['Đã đổi gì', 'Vì sao', 'Phần chưa làm', 'Ca kiểm mới', 'Rủi ro còn lại']);
33
+ const NOT_DONE_SECTION = 'Phần chưa làm';
34
+ const NEW_CHECKS_SECTION = 'Ca kiểm mới';
35
+
36
+ /** Nhãn trường của một khối ca kiểm → tên máy. */
37
+ const FIELD_LABELS = Object.freeze({
38
+ 'nhóm': 'group', 'ưu tiên': 'priority', 'cách kiểm': 'method', 'tình huống': 'scenario', 'mong đợi': 'expected',
39
+ 'trạng thái': 'status', job: 'job', commit: 'commit', 'bằng chứng': 'evidence',
40
+ });
41
+ const REQUIRED_CASE_FIELDS = ['group', 'priority', 'method', 'scenario', 'expected'];
42
+
43
+ const MAX_FILE_CHARS = 256 * 1024;
44
+ /** Chuỗi trong frontmatter dài hơn thế là câu chữ — phải xuống thân file. */
45
+ const MAX_SHORT_VALUE = 300;
46
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
47
+ const CHECK_ID_RE = /^CK-\d{1,6}$/;
48
+ const NEW_CHECK_ID_RE = /^NEW-\d{1,4}$/;
49
+ const SHA256_RE = /^[0-9a-f]{64}$/;
50
+ /** Tên công cụ cho `--allowedTools`: `Read`, `Bash(npm test *)`… — không dấu xuống dòng, ngoặc không lồng. */
51
+ const TOOL_RULE_RE = /^[A-Za-z][A-Za-z0-9_]{0,40}(\([^()\r\n]{1,200}\))?$/;
52
+ /** Shell không kèm mẫu lệnh = chạy được mọi lệnh — hợp đồng phải khai mẫu (`Bash(npm test *)`). */
53
+ const UNBOUNDED_SHELL = new Set(['Bash', 'PowerShell']);
54
+
55
+ export const sha256 = (text) => createHash('sha256').update(String(text), 'utf8').digest('hex');
56
+ const nfc = (s) => String(s ?? '').normalize('NFC');
57
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
58
+
59
+ /** Tách frontmatter (giữa hai dòng `---` ở đầu file) và thân. Không có frontmatter → `{ error }`. */
60
+ export function splitFrontmatter(text) {
61
+ const src = nfc(text).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
62
+ if (src.length > MAX_FILE_CHARS) return { error: `file is larger than ${MAX_FILE_CHARS} characters` };
63
+ if (!src.startsWith('---\n')) return { error: 'file must start with a frontmatter block (a line "---")' };
64
+ const end = src.indexOf('\n---', 3);
65
+ if (end < 0 || (src[end + 4] !== undefined && src[end + 4] !== '\n')) return { error: 'frontmatter is not closed by a line "---"' };
66
+ return { yaml: src.slice(4, end + 1), body: src.slice(end + 5).replace(/^\n+/, '') };
67
+ }
68
+
69
+ /** Đọc YAML chặt → object, hoặc `{ errors }`. */
70
+ function parseYaml(yaml) {
71
+ const doc = YAML.parseDocument(yaml, { schema: 'core', uniqueKeys: true, strict: true, prettyErrors: false });
72
+ if (doc.errors.length) return { errors: doc.errors.map((e) => `frontmatter: ${e.message.split('\n')[0]}`) };
73
+ let data;
74
+ try { data = doc.toJS({ maxAliasCount: 0 }); } catch (e) { return { errors: [`frontmatter: ${e.message}`] }; }
75
+ if (!isObj(data)) return { errors: ['frontmatter must be a mapping of fields'] };
76
+ return { data };
77
+ }
78
+
79
+ /** Mọi chuỗi trong frontmatter phải ngắn, một dòng. */
80
+ function checkShortValues(value, at, errors) {
81
+ if (typeof value === 'string') {
82
+ if (value.includes('\n') || value.length > MAX_SHORT_VALUE) errors.push(`${at}: frontmatter holds short values only — move sentences to the body`);
83
+ } else if (Array.isArray(value)) value.forEach((v, i) => checkShortValues(v, `${at}[${i}]`, errors));
84
+ else if (isObj(value)) for (const [k, v] of Object.entries(value)) checkShortValues(v, at ? `${at}.${k}` : k, errors);
85
+ }
86
+
87
+ /** Bộ kiểm trường nhỏ gọn: mỗi hàm đẩy lỗi vào `errors`, trả giá trị đã chuẩn hoá (hoặc giá trị mặc định). */
88
+ function fieldCheckers(errors) {
89
+ const fail = (at, msg) => { errors.push(`${at}: ${msg}`); return undefined; };
90
+ return {
91
+ fail,
92
+ id: (v, at, { optional = false } = {}) => (v === undefined || v === '' ? (optional ? undefined : fail(at, 'is required')) : ID_RE.test(String(v)) ? String(v) : fail(at, 'must be a short id (letters, digits, _ . -)')),
93
+ oneOf: (v, at, list, dflt) => (v === undefined ? (dflt !== undefined ? dflt : fail(at, `is required (${list.join(' | ')})`)) : list.includes(v) ? v : fail(at, `must be one of ${list.join(' | ')}`)),
94
+ int: (v, at, { min = 0, max = Number.MAX_SAFE_INTEGER, dflt } = {}) => (v === undefined && dflt !== undefined ? dflt : Number.isInteger(v) && v >= min && v <= max ? v : fail(at, `must be a whole number from ${min} to ${max}`)),
95
+ num: (v, at, { min = 0, max, dflt } = {}) => (v === undefined && dflt !== undefined ? dflt : typeof v === 'number' && Number.isFinite(v) && v > min && v <= max ? v : fail(at, `must be a number above ${min}, at most ${max}`)),
96
+ bool: (v, at, dflt) => (v === undefined && dflt !== undefined ? dflt : typeof v === 'boolean' ? v : fail(at, 'must be true or false')),
97
+ strList: (v, at, { dflt = [], test, what = 'text' } = {}) => {
98
+ if (v === undefined) return dflt;
99
+ if (!Array.isArray(v) || v.some((s) => typeof s !== 'string' || !s || (test && !test(s)))) return fail(at, `must be a list of ${what}`);
100
+ return v;
101
+ },
102
+ list: (v, at) => (v === undefined ? [] : Array.isArray(v) && v.every(isObj) ? v : fail(at, 'must be a list of mappings') || []),
103
+ obj: (v, at, { optional = false } = {}) => (v === undefined && optional ? undefined : isObj(v) ? v : fail(at, 'must be a mapping') || {}),
104
+ };
105
+ }
106
+
107
+ /** Đường dẫn tương đối, không thoát khỏi thư mục làm việc. */
108
+ const isRelativePath = (p) => typeof p === 'string' && !!p && !/^([a-z]:|[\\/])/i.test(p) && !p.split(/[\\/]/).includes('..');
109
+
110
+ /**
111
+ * Đọc + kiểm `CONTRACT.md`. `expectedSha` (từ BE) phải khớp mã băm của toàn bộ file. Trả `{ ok, errors, contract, body, sha256 }` —
112
+ * `contract` đã điền mặc định. Không ném lỗi.
113
+ */
114
+ export function parseContract(text, { expectedSha } = {}) {
115
+ const errors = [];
116
+ const digest = sha256(text);
117
+ if (expectedSha !== undefined && String(expectedSha).toLowerCase() !== digest) errors.push('contract sha256 does not match — the file is not the one Aivin issued');
118
+ const split = splitFrontmatter(text);
119
+ if (split.error) return { ok: false, errors: [...errors, split.error], sha256: digest };
120
+ const parsed = parseYaml(split.yaml);
121
+ if (parsed.errors) return { ok: false, errors: [...errors, ...parsed.errors], sha256: digest };
122
+ const fm = parsed.data;
123
+ checkShortValues(fm, '', errors);
124
+ const f = fieldCheckers(errors);
125
+
126
+ const risk = f.oneOf(fm.risk, 'risk', Object.values(Risk));
127
+ const scopeIn = f.obj(fm.scope, 'scope', { optional: true });
128
+ const scope = scopeIn ? {
129
+ deny_paths: f.strList(scopeIn.deny_paths, 'scope.deny_paths', { what: 'path patterns' }) || [],
130
+ protected_paths: f.strList(scopeIn.protected_paths, 'scope.protected_paths', { what: 'path patterns' }) || [],
131
+ } : undefined;
132
+
133
+ const verify = f.list(fm.verify, 'verify').map((v, i) => ({
134
+ id: f.id(v.id, `verify[${i}].id`),
135
+ argv: f.strList(v.argv, `verify[${i}].argv`, { dflt: undefined, what: 'command words (argv)' }),
136
+ timeout_ms: f.int(v.timeout_ms, `verify[${i}].timeout_ms`, { min: 1000, max: 3_600_000, dflt: 300_000 }),
137
+ report: v.report === undefined ? undefined : isRelativePath(v.report) ? v.report : f.fail(`verify[${i}].report`, 'must be a relative path inside the project'),
138
+ }));
139
+ verify.forEach((v, i) => { if (!v.argv?.length) errors.push(`verify[${i}].argv: is required`); });
140
+ const verifyIds = new Set();
141
+ for (const v of verify) { if (v.id && verifyIds.has(v.id)) errors.push(`verify: id ${v.id} is used twice`); verifyIds.add(v.id); }
142
+
143
+ const kinds = Object.values(CheckKind);
144
+ const acceptance = f.list(fm.acceptance, 'acceptance').map((a, i) => {
145
+ const at = `acceptance[${i}]`;
146
+ const item = { key: f.id(a.key, `${at}.key`), required: f.bool(a.required, `${at}.required`, true) };
147
+ if (a.check !== undefined) item.check = f.oneOf(a.check, `${at}.check`, kinds);
148
+ if (a.verifier !== undefined) item.verifier = f.id(a.verifier, `${at}.verifier`);
149
+ if (!a.check && !a.verifier) errors.push(`${at}: needs check (measured by the device) or verifier (judged by Aivin)`);
150
+ if (item.check === CheckKind.COMMAND_PASSED) {
151
+ item.command_id = f.id(a.command_id, `${at}.command_id`);
152
+ if (item.command_id && !verifyIds.has(item.command_id)) errors.push(`${at}.command_id: no verify command with id ${item.command_id}`);
153
+ }
154
+ return item;
155
+ });
156
+
157
+ const limitsIn = f.obj(fm.limits, 'limits', { optional: true }) || {};
158
+ const limits = {
159
+ max_fix_rounds: f.int(limitsIn.max_fix_rounds, 'limits.max_fix_rounds', { max: 10, dflt: 2 }),
160
+ max_budget_usd: limitsIn.max_budget_usd === undefined
161
+ ? f.fail('limits.max_budget_usd', 'is required (a job without a budget can spend without end)')
162
+ : f.num(limitsIn.max_budget_usd, 'limits.max_budget_usd', { max: 200 }),
163
+ max_wall_ms: f.int(limitsIn.max_wall_ms, 'limits.max_wall_ms', { min: 60_000, max: 12 * 3_600_000, dflt: 30 * 60_000 }),
164
+ effort: f.oneOf(limitsIn.effort, 'limits.effort', EFFORTS, 'high'),
165
+ };
166
+
167
+ const permIn = f.obj(fm.permissions, 'permissions', { optional: true }) || {};
168
+ const permissions = {
169
+ mode: f.oneOf(permIn.mode, 'permissions.mode', MODES, risk === Risk.READ_ONLY ? 'plan' : 'manual'),
170
+ allowed_tools: f.strList(permIn.allowed_tools, 'permissions.allowed_tools', { test: (s) => TOOL_RULE_RE.test(s), what: 'tool rules like Read or Bash(npm test *)' }) || [],
171
+ };
172
+ for (const t of permissions.allowed_tools) if (UNBOUNDED_SHELL.has(t)) errors.push(`permissions.allowed_tools: ${t} without a command pattern allows every command — write e.g. ${t}(npm test *)`);
173
+ if (risk === Risk.READ_ONLY && permissions.mode !== 'plan') errors.push('permissions.mode: read_only work runs in plan mode');
174
+
175
+ const outputs = f.list(fm.outputs, 'outputs').map((o, i) => ({
176
+ id: f.id(o.id, `outputs[${i}].id`), kind: f.oneOf(o.kind, `outputs[${i}].kind`, OUTPUT_KINDS),
177
+ required: f.bool(o.required, `outputs[${i}].required`, true), consumer: f.id(o.consumer, `outputs[${i}].consumer`, { optional: true }),
178
+ }));
179
+
180
+ const tcIn = f.obj(fm.test_check, 'test_check', { optional: true });
181
+ const testCheck = tcIn ? {
182
+ file_id: f.id(tcIn.file_id, 'test_check.file_id', { optional: true }),
183
+ sha256: tcIn.sha256 === undefined || tcIn.sha256 === '' ? undefined : SHA256_RE.test(String(tcIn.sha256)) ? String(tcIn.sha256) : f.fail('test_check.sha256', 'must be 64 hex characters'),
184
+ flows: f.strList(tcIn.flows, 'test_check.flows', { test: (s) => ID_RE.test(s), what: 'flow ids' }) || [],
185
+ } : undefined;
186
+
187
+ const wsIn = f.obj(fm.workspace, 'workspace', { optional: true }) || {};
188
+ const workspace = {
189
+ cwd: typeof wsIn.cwd === 'string' && wsIn.cwd ? wsIn.cwd : undefined,
190
+ base_ref: wsIn.base_ref === undefined ? 'HEAD'
191
+ : typeof wsIn.base_ref === 'string' && /^[A-Za-z0-9_./^~-]{1,100}$/.test(wsIn.base_ref) && !wsIn.base_ref.startsWith('-') ? wsIn.base_ref
192
+ : f.fail('workspace.base_ref', 'must be a git ref') || 'HEAD',
193
+ isolation: f.oneOf(wsIn.isolation, 'workspace.isolation', ['worktree', 'none'], 'worktree'),
194
+ };
195
+
196
+ // Quy tắc cứng: việc có sửa (standard / strict) phải có lệnh kiểm chứng và phạm vi.
197
+ if (risk && risk !== Risk.READ_ONLY) {
198
+ if (!verify.length) errors.push('verify: standard and strict work need at least one verify command');
199
+ if (!scope) errors.push('scope: standard and strict work need a scope (deny_paths, protected_paths)');
200
+ }
201
+ if (!split.body.trim() || !/^# \S/m.test(split.body)) errors.push('body: needs a title line "# …" with the goal, why and criteria below it');
202
+
203
+ const contract = {
204
+ contract_id: f.id(fm.contract_id, 'contract_id'), version: f.int(fm.version, 'version', { min: 1 }),
205
+ feature_group: f.id(fm.feature_group, 'feature_group', { optional: true }),
206
+ project_id: typeof fm.project_id === 'string' ? fm.project_id : undefined, task_id: typeof fm.task_id === 'string' ? fm.task_id : undefined,
207
+ risk, spec_refs: Array.isArray(fm.spec_refs) ? fm.spec_refs : [], depends_on: Array.isArray(fm.depends_on) ? fm.depends_on : [],
208
+ test_check: testCheck, workspace, scope: scope || { deny_paths: [], protected_paths: [] }, verify, acceptance, limits, permissions, outputs,
209
+ };
210
+ return { ok: !errors.length, errors, contract, body: split.body, sha256: digest };
211
+ }
212
+
213
+ /** Các dòng H1..H4 của thân: [{ level, text, line }]. Bỏ qua phần trong khối ```. */
214
+ function headings(lines) {
215
+ const out = [];
216
+ let fence = false;
217
+ lines.forEach((l, i) => {
218
+ if (/^\s*```/.test(l)) fence = !fence;
219
+ const m = !fence && /^(#{1,4}) +(.+?)\s*$/.exec(l);
220
+ if (m) out.push({ level: m[1].length, text: m[2], line: i });
221
+ });
222
+ return out;
223
+ }
224
+
225
+ const sameTitle = (a, b) => nfc(a).trim().toLowerCase() === nfc(b).trim().toLowerCase();
226
+
227
+ /**
228
+ * Các khối ca kiểm dưới `## Luồng <id>` / `### BR-xx <tên>` / `#### <mã> <tên>` + dòng `- <nhãn>: <giá trị>`. `idRe`: mã hợp lệ của khối
229
+ * (CK-… trong TEST_CHECK.md, NEW-… cho ca mới trong REPORT.md). Trả `{ flows, cases, errors }`.
230
+ */
231
+ export function parseCheckBlocks(lines, { idRe = CHECK_ID_RE, at = 'body' } = {}) {
232
+ const errors = [];
233
+ const flows = [];
234
+ const cases = [];
235
+ let flow = null;
236
+ let rule = null;
237
+ let current = null;
238
+ let fence = false;
239
+ const closeCase = () => {
240
+ if (!current) return;
241
+ for (const k of REQUIRED_CASE_FIELDS) if (!current[k]) errors.push(`${at}: ${current.id} misses "${Object.keys(FIELD_LABELS).find((l) => FIELD_LABELS[l] === k)}"`);
242
+ if (current.group && !CHECK_GROUPS.includes(current.group)) errors.push(`${at}: ${current.id} group must be one of ${CHECK_GROUPS.join(' | ')}`);
243
+ if (current.priority && !/^p[0-3]$/.test(current.priority)) errors.push(`${at}: ${current.id} priority must be p0 … p3`);
244
+ if (current.method && !CHECK_METHODS.includes(current.method)) errors.push(`${at}: ${current.id} method must be one of ${CHECK_METHODS.join(' | ')}`);
245
+ if (current.status && !CASE_STATUSES.includes(current.status)) errors.push(`${at}: ${current.id} status must be one of ${CASE_STATUSES.join(' | ')}`);
246
+ current = null;
247
+ };
248
+ const seen = new Set();
249
+ lines.forEach((raw, i) => {
250
+ const l = nfc(raw);
251
+ if (/^\s*```/.test(l)) fence = !fence;
252
+ if (fence) return;
253
+ let m;
254
+ if ((m = /^## +Luồng +([A-Za-z0-9][A-Za-z0-9_.-]{0,63})\s*$/i.exec(l))) {
255
+ closeCase();
256
+ flow = { id: m[1], goal: undefined, not_applicable: undefined, rules: [] };
257
+ rule = null;
258
+ flows.push(flow);
259
+ } else if ((m = /^### +(BR-\d{1,6})\b *(.*)$/.exec(l))) {
260
+ closeCase();
261
+ if (!flow) { errors.push(`${at} line ${i + 1}: rule ${m[1]} is outside a "## Luồng <id>" section`); return; }
262
+ rule = { id: m[1], title: m[2].trim(), cases: [] };
263
+ flow.rules.push(rule);
264
+ } else if ((m = /^#### +(\S+) *(.*)$/.exec(l))) {
265
+ closeCase();
266
+ if (!idRe.test(m[1])) { errors.push(`${at} line ${i + 1}: "${m[1]}" is not a valid check id`); return; }
267
+ if (!rule) { errors.push(`${at} line ${i + 1}: check ${m[1]} is outside a "### BR-xx" rule`); return; }
268
+ if (seen.has(m[1])) errors.push(`${at}: check ${m[1]} appears twice`);
269
+ seen.add(m[1]);
270
+ current = { id: m[1], title: m[2].trim(), flow_id: flow.id, rule_id: rule.id };
271
+ rule.cases.push(current);
272
+ cases.push(current);
273
+ } else if (/^#{1,3} /.test(l)) {
274
+ closeCase();
275
+ } else if (current && (m = /^- +([^:]+?) *: *(.*)$/.exec(l))) {
276
+ const key = FIELD_LABELS[m[1].trim().toLowerCase()];
277
+ if (!key) errors.push(`${at}: ${current.id} has an unknown field "${m[1].trim()}"`);
278
+ else if (current[key] !== undefined) errors.push(`${at}: ${current.id} has "${m[1].trim()}" twice`);
279
+ else current[key] = m[2].trim();
280
+ } else if (flow && !rule && (m = /^(Mục tiêu|Không áp dụng) *: *(.*)$/i.exec(l))) {
281
+ if (/^mục/i.test(m[1])) flow.goal = m[2].trim(); else flow.not_applicable = m[2].trim();
282
+ }
283
+ });
284
+ closeCase();
285
+ return { flows, cases, errors };
286
+ }
287
+
288
+ /** Đọc + kiểm `TEST_CHECK.md`. Trả `{ ok, errors, meta, flows, cases, sha256 }`. */
289
+ export function parseTestCheck(text) {
290
+ const digest = sha256(text);
291
+ const split = splitFrontmatter(text);
292
+ if (split.error) return { ok: false, errors: [split.error], flows: [], cases: [], sha256: digest };
293
+ const parsed = parseYaml(split.yaml);
294
+ if (parsed.errors) return { ok: false, errors: parsed.errors, flows: [], cases: [], sha256: digest };
295
+ const errors = [];
296
+ checkShortValues(parsed.data, '', errors);
297
+ const f = fieldCheckers(errors);
298
+ const meta = { project_id: typeof parsed.data.project_id === 'string' ? parsed.data.project_id : undefined, version: f.int(parsed.data.version, 'version', { min: 1 }) };
299
+ const blocks = parseCheckBlocks(split.body.split('\n'));
300
+ return { ok: !errors.length && !blocks.errors.length, errors: [...errors, ...blocks.errors], meta, flows: blocks.flows, cases: blocks.cases, sha256: digest };
301
+ }
302
+
303
+ /**
304
+ * Đọc + kiểm `REPORT.md` của agent. Frontmatter: `status`, `needs_scope_change`, `results` (mã ca → kết quả); thân đủ 5 mục, mục
305
+ * "Phần chưa làm" không trống khi chưa `done`; ca mới trong "Ca kiểm mới" mang mã tạm `NEW-n`. Trả `{ ok, errors, report, new_checks }`.
306
+ */
307
+ export function parseReport(text, { contractId } = {}) {
308
+ const split = splitFrontmatter(text);
309
+ if (split.error) return { ok: false, errors: [split.error] };
310
+ const parsed = parseYaml(split.yaml);
311
+ if (parsed.errors) return { ok: false, errors: parsed.errors };
312
+ const fm = parsed.data;
313
+ const errors = [];
314
+ checkShortValues(fm, '', errors);
315
+ const f = fieldCheckers(errors);
316
+ const results = {};
317
+ if (fm.results !== undefined && !isObj(fm.results)) errors.push('results: must be a mapping like CK-031: pass');
318
+ for (const [id, r] of Object.entries(isObj(fm.results) ? fm.results : {})) {
319
+ if (!CHECK_ID_RE.test(id)) errors.push(`results: "${id}" is not a check id (CK-…)`);
320
+ else if (!CASE_RESULTS.includes(r)) errors.push(`results.${id}: must be one of ${CASE_RESULTS.join(' | ')}`);
321
+ else results[id] = r;
322
+ }
323
+ const report = {
324
+ job_id: typeof fm.job_id === 'string' ? fm.job_id : undefined,
325
+ contract_id: typeof fm.contract_id === 'string' ? fm.contract_id : undefined,
326
+ check_file_version: fm.check_file_version === undefined || fm.check_file_version === null ? undefined : f.int(fm.check_file_version, 'check_file_version', { min: 1 }),
327
+ status: f.oneOf(fm.status, 'status', Object.values(ReportStatus)),
328
+ needs_scope_change: f.bool(fm.needs_scope_change, 'needs_scope_change', false),
329
+ results,
330
+ };
331
+ if (contractId && report.contract_id !== contractId) errors.push(`contract_id: must be ${contractId}`);
332
+
333
+ const lines = split.body.split('\n');
334
+ const h1 = headings(lines).filter((h) => h.level === 1);
335
+ const sections = {};
336
+ REPORT_SECTIONS.forEach((name) => {
337
+ const at = h1.findIndex((h) => sameTitle(h.text, name));
338
+ if (at < 0) { errors.push(`body: missing section "# ${name}"`); return; }
339
+ const from = h1[at].line + 1;
340
+ const to = h1[at + 1] ? h1[at + 1].line : lines.length;
341
+ sections[name] = lines.slice(from, to);
342
+ });
343
+ if (report.status && report.status !== ReportStatus.DONE && !(sections[NOT_DONE_SECTION] || []).join('').trim()) {
344
+ errors.push(`body: "# ${NOT_DONE_SECTION}" must say what is left when status is ${report.status}`);
345
+ }
346
+ const blocks = parseCheckBlocks(sections[NEW_CHECKS_SECTION] || [], { idRe: NEW_CHECK_ID_RE, at: NEW_CHECKS_SECTION });
347
+ errors.push(...blocks.errors);
348
+ return { ok: !errors.length, errors, report, new_checks: blocks.cases };
349
+ }
350
+
351
+ /** Khuôn `REPORT.md` đưa cho agent (đúng thứ tự mục; ví dụ một ca mới). */
352
+ export function reportTemplate({ jobId, contractId, checkFileVersion }) {
353
+ return [
354
+ '---',
355
+ `job_id: ${jobId}`,
356
+ `contract_id: ${contractId}`,
357
+ ...(checkFileVersion ? [`check_file_version: ${checkFileVersion}`] : []),
358
+ 'status: done | partial | blocked',
359
+ 'needs_scope_change: false',
360
+ 'results:',
361
+ ' CK-031: pass | fail | blocked | not_tested',
362
+ '---',
363
+ '',
364
+ `# ${REPORT_SECTIONS[0]}`, '', `# ${REPORT_SECTIONS[1]}`, '', `# ${REPORT_SECTIONS[2]}`, '- (empty only when status is done)', '',
365
+ `# ${REPORT_SECTIONS[3]}`, '', '## Luồng checkout', '', '### BR-07', '', '#### NEW-1 <short title>',
366
+ `- nhóm: ${CHECK_GROUPS.join(' | ')}`, '- ưu tiên: p0 | p1 | p2 | p3', `- cách kiểm: ${CHECK_METHODS.join(' | ')}`,
367
+ '- tình huống: <one line>', '- mong đợi: <one line>', '',
368
+ `# ${REPORT_SECTIONS[4]}`, '',
369
+ ].join('\n');
370
+ }