@aivin-labs/cli 1.0.51 → 1.0.60

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 (32) hide show
  1. package/bin/cli.mjs +2215 -2211
  2. package/bin/lib/auth.mjs +119 -88
  3. package/bin/lib/context.mjs +58 -5
  4. package/bin/lib/loginHandoff.mjs +87 -0
  5. package/bin/lib/openFile.mjs +29 -4
  6. package/bin/lib/remote/agentContract.mjs +370 -0
  7. package/bin/lib/remote/agentEvidence.mjs +409 -0
  8. package/bin/lib/remote/autoStart.mjs +640 -623
  9. package/bin/lib/remote/client.mjs +55 -17
  10. package/bin/lib/remote/codingAgents.mjs +594 -293
  11. package/bin/lib/remote/constants.mjs +1 -1
  12. package/bin/lib/remote/credentials.mjs +131 -125
  13. package/bin/lib/remote/desktop/castAuth.mjs +44 -19
  14. package/bin/lib/remote/desktop/castConsent.mjs +79 -14
  15. package/bin/lib/remote/desktop/castInput.mjs +3 -0
  16. package/bin/lib/remote/desktop/castTrust.mjs +221 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +483 -443
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +1 -1
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +324 -40
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +59 -4
  21. package/bin/lib/remote/desktop/strings.mjs +26 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +1512 -1385
  23. package/bin/lib/remote/desktop/webrtcWorker.mjs +4 -0
  24. package/bin/lib/remote/dpapiHelper.mjs +91 -0
  25. package/bin/lib/remote/gui/index.mjs +422 -68
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +2418 -1530
  27. package/bin/lib/remote/humanInput.mjs +7 -0
  28. package/bin/lib/remote/localConfirm.mjs +2 -2
  29. package/bin/lib/remote/tokenStore.mjs +19 -2
  30. package/bin/lib/remote/toolHandlers.mjs +861 -859
  31. package/docs/CLI.md +1606 -1602
  32. package/package.json +1 -1
@@ -0,0 +1,409 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { spawn } from 'child_process';
4
+ import { StringDecoder } from 'string_decoder';
5
+ import { CheckKind, parseReport, sha256 } from './agentContract.mjs';
6
+ import { safeGitArgv, safeGitEnv } from './gitSafe.mjs';
7
+ import { agentEnv, scrubEnv } from './sandbox.mjs';
8
+ import { killWindowsTree } from './winTree.mjs';
9
+
10
+ /**
11
+ * Daemon tự đo kết quả của một job có hợp đồng (11/11/2026) — không LLM, không tin lời tự khai trong `REPORT.md`. Sau khi agent xong:
12
+ * chạy lại từng lệnh `verify` của hợp đồng trong worktree, đọc JUnit, đo diff so với commit gốc, rồi chấm 7 bộ kiểm và ghi `evidence.json`.
13
+ * Daemon chỉ ĐO; kết luận đạt / trượt là việc của Agentic (chế độ shadow trước, enforce sau).
14
+ *
15
+ * Lệnh `verify` chạy theo argv, KHÔNG qua shell (không dính trích dẫn, không nối lệnh). Windows: `.cmd` / `.bat` (npm, yarn…) bắt buộc đi qua
16
+ * cmd.exe — chỉ nhận khi không tham số nào có ký tự đặc biệt của cmd. Lệnh verify vẫn chạy mã của repo (test là mã) — đó là chủ ý của
17
+ * hợp đồng; vì vậy `filter.<x>.clean` của repo khi git đọc cây làm việc không mở thêm đường chạy mã nào so với chính lệnh test.
18
+ */
19
+
20
+ export const EVIDENCE_FILE = 'evidence.json';
21
+ const MAX_LOG_BYTES = 20 * 1024 ** 2;
22
+ const LOG_TAIL_CHARS = 4000;
23
+ const MAX_DIFF_BYTES = 16 * 1024 ** 2;
24
+ const MAX_UNTRACKED_READ = 1024 ** 2;
25
+ const MAX_LISTED = 200;
26
+ const GIT_TIMEOUT_MS = 120_000;
27
+ const CMD_META_RE = /[&|<>^%!"\r\n()]/;
28
+
29
+ /** Tệp test theo quy ước phổ biến (JS/TS, Python, Go, Java, Rust…). */
30
+ const TEST_FILE_RE = /(^|\/)(tests?|__tests__|specs?)\/|[._-](test|spec)s?\.[a-z0-9]+$|(^|\/)test_[^/]+\.py$|_test\.(go|py)$|Tests?\.(java|kt|cs)$/i;
31
+ /** Một dòng khai báo ca test. */
32
+ const TEST_DECL_RE = /^\s*(it|test)(\.\w+)*\s*\(|^\s*(async\s+)?def\s+test_\w*|@(Test|ParameterizedTest)\b|^\s*func\s+Test[A-Z_]\w*\s*\(|#\[test\]|\[(Fact|Theory|Test)\]/;
33
+ /** Một dòng tắt / bỏ qua / chỉ chạy riêng ca test. */
34
+ const SKIP_RE = /\b(it|test|describe|context)\.(skip|only|todo)\b|\bx(it|test|describe)\s*\(|\bf(it|describe)\s*\(|@pytest\.mark\.(skip|skipif|xfail)\b|\bpytest\.skip\s*\(|@unittest\.skip|@(Ignore|Disabled)\b|\bt\.Skip(Now|f)?\s*\(|#\[ignore\]|\[(Fact|Theory)\s*\(\s*Skip\s*=/;
35
+
36
+ const caseInsensitive = process.platform === 'win32' || process.platform === 'darwin';
37
+
38
+ /**
39
+ * Mẫu đường dẫn kiểu gitignore → RegExp. `*` không qua `/`, `**` qua mọi tầng, mẫu không có `/` khớp tên tệp ở mọi tầng (`package.json`,
40
+ * `*.pem`), mẫu là thư mục khớp mọi thứ bên trong (`.github`, `.github/**`).
41
+ */
42
+ export function globToRegExp(pattern) {
43
+ let p = String(pattern).replace(/\\/g, '/').replace(/^\.\//, '');
44
+ const anchored = p.startsWith('/') || p.replace(/\/+$/, '').includes('/');
45
+ p = p.replace(/^\/+/, '').replace(/\/+$/, '');
46
+ let re = '';
47
+ for (let i = 0; i < p.length; i++) {
48
+ const c = p[i];
49
+ if (c === '*' && p[i + 1] === '*') {
50
+ const slashAfter = p[i + 2] === '/';
51
+ re += slashAfter ? '(?:.*/)?' : '.*';
52
+ i += slashAfter ? 2 : 1;
53
+ } else if (c === '*') re += '[^/]*';
54
+ else if (c === '?') re += '[^/]';
55
+ else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
56
+ }
57
+ return new RegExp(`^${anchored ? '' : '(?:.*/)?'}${re}(?:/.*)?$`, caseInsensitive ? 'i' : '');
58
+ }
59
+
60
+ export const matchesAny = (rel, patterns) => patterns.some((p) => globToRegExp(p).test(String(rel).replace(/\\/g, '/')));
61
+
62
+ const xmlText = (s) => String(s).replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&amp;/g, '&');
63
+ const attrOf = (tag, name) => { const m = new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)')`).exec(tag); return m ? xmlText(m[2] ?? m[3]) : undefined; };
64
+
65
+ /** JUnit XML (jest-junit, pytest --junitxml, surefire, go-junit-report…) → tổng + từng ca `{ name, classname, status }`. */
66
+ export function parseJUnit(xml) {
67
+ const cases = [];
68
+ const src = String(xml);
69
+ const re = /<testcase\b([^>]*?)(\/>|>([\s\S]*?)<\/testcase>)/g;
70
+ let m;
71
+ while ((m = re.exec(src))) {
72
+ const inner = m[3] || '';
73
+ const status = /<(failure|error)\b/.test(inner) ? (/<error\b/.test(inner) ? 'error' : 'fail') : /<skipped\b/.test(inner) ? 'skipped' : 'pass';
74
+ cases.push({ name: attrOf(m[1], 'name') || '', classname: attrOf(m[1], 'classname') || '', status });
75
+ }
76
+ const count = (s) => cases.filter((c) => c.status === s).length;
77
+ return { tests: cases.length, failures: count('fail'), errors: count('error'), skipped: count('skipped'), cases };
78
+ }
79
+
80
+ /** Windows: tìm tệp chạy theo PATH + PATHEXT (spawn không shell không tự thêm `.cmd`). */
81
+ function resolveWindowsCommand(cmd, env) {
82
+ if (/[\\/]/.test(cmd) || path.extname(cmd)) return cmd;
83
+ const exts = String(env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
84
+ for (const dir of String(env.PATH || env.Path || '').split(path.delimiter).filter(Boolean)) {
85
+ for (const ext of exts) {
86
+ const full = path.join(dir, cmd + ext.toLowerCase());
87
+ if (fs.existsSync(full)) return full;
88
+ }
89
+ }
90
+ return cmd;
91
+ }
92
+
93
+ /** argv của hợp đồng → [tệp chạy, tham số, tuỳ chọn spawn]. Ném lỗi khi không chạy an toàn được. */
94
+ export function verifySpawnArgs(argv, { platform = process.platform, env = process.env } = {}) {
95
+ const [cmd, ...rest] = argv;
96
+ if (platform !== 'win32') return [cmd, rest, {}];
97
+ const exe = resolveWindowsCommand(cmd, env);
98
+ if (!/\.(cmd|bat)$/i.test(exe)) return [exe, rest, {}];
99
+ const bad = argv.find((a) => CMD_META_RE.test(a));
100
+ if (bad !== undefined) throw new Error(`"${bad}" has a character cmd.exe would interpret — a .cmd command cannot take it safely`);
101
+ const quoted = [exe, ...rest].map((a) => (/[\s]/.test(a) || !a ? `"${a}"` : a)).join(' ');
102
+ return [env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${quoted}"`], { windowsVerbatimArguments: true }];
103
+ }
104
+
105
+ /** Chạy một lệnh `verify`: log đầy đủ ra tệp (có trần), hết giờ → giết cả cây. Không ném lỗi. */
106
+ export function runVerifyCommand(cmd, { cwd, logFile, signal, spawnImpl = spawn, env: baseEnv = process.env } = {}) {
107
+ return new Promise((resolve) => {
108
+ const startedAt = Date.now();
109
+ const env = { ...agentEnv(baseEnv), CI: 'true' };
110
+ let spawnArgs;
111
+ try { spawnArgs = verifySpawnArgs(cmd.argv, { env }); } catch (e) { resolve({ exit_code: null, error: e.message, duration_ms: 0 }); return; }
112
+ const [file, args, extra] = spawnArgs;
113
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
114
+ const log = fs.createWriteStream(logFile);
115
+ let written = 0;
116
+ let tail = '';
117
+ let timedOut = false;
118
+ let settled = false;
119
+ const decoder = new StringDecoder('utf8');
120
+ let child;
121
+ try {
122
+ child = spawnImpl(file, args, { cwd, env, windowsHide: true, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'], ...extra });
123
+ } catch (e) {
124
+ log.end();
125
+ resolve({ exit_code: null, error: `Cannot start: ${e.message}`, duration_ms: 0 });
126
+ return;
127
+ }
128
+ const kill = () => {
129
+ if (process.platform === 'win32') killWindowsTree(child, startedAt);
130
+ else { try { process.kill(-child.pid, 'SIGKILL'); } catch { try { child.kill('SIGKILL'); } catch { /* đã thoát */ } } }
131
+ };
132
+ const timer = setTimeout(() => { timedOut = true; kill(); }, cmd.timeout_ms);
133
+ const onAbort = () => kill();
134
+ signal?.addEventListener('abort', onAbort, { once: true });
135
+ const onData = (chunk) => {
136
+ if (written < MAX_LOG_BYTES) { log.write(chunk); written += chunk.length; }
137
+ tail = (tail + decoder.write(chunk)).slice(-LOG_TAIL_CHARS);
138
+ };
139
+ child.stdout?.on('data', onData);
140
+ child.stderr?.on('data', onData);
141
+ const done = (code, error) => {
142
+ if (settled) return;
143
+ settled = true;
144
+ clearTimeout(timer);
145
+ signal?.removeEventListener('abort', onAbort);
146
+ log.end();
147
+ resolve({
148
+ exit_code: code, timed_out: timedOut || undefined, cancelled: signal?.aborted || undefined, error,
149
+ duration_ms: Date.now() - startedAt, log_tail: tail.trim() || undefined, log_truncated: written >= MAX_LOG_BYTES || undefined,
150
+ });
151
+ };
152
+ child.on('error', (e) => done(null, `Cannot start: ${e.message}`));
153
+ child.on('close', (code) => done(code));
154
+ });
155
+ }
156
+
157
+ /** `git` chỉ đọc, đã khoá cấu hình của kho (gitSafe). Trả stdout (Buffer), hoặc ném lỗi có stderr. */
158
+ export function gitRead(cwd, sub, { maxBytes = MAX_DIFF_BYTES, spawnImpl = spawn } = {}) {
159
+ return new Promise((resolve, reject) => {
160
+ const child = spawnImpl('git', safeGitArgv(cwd, sub), { cwd, env: safeGitEnv(scrubEnv()), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
161
+ const out = [];
162
+ let size = 0;
163
+ let err = '';
164
+ const timer = setTimeout(() => child.kill(), GIT_TIMEOUT_MS);
165
+ child.stdout.on('data', (c) => { size += c.length; if (size <= maxBytes) out.push(c); else child.kill(); });
166
+ child.stderr.on('data', (c) => { err = (err + c).slice(-1000); });
167
+ child.on('error', (e) => { clearTimeout(timer); reject(e); });
168
+ child.on('close', (code) => {
169
+ clearTimeout(timer);
170
+ if (size > maxBytes) reject(new Error(`git ${sub[0]} output is larger than ${maxBytes} bytes`));
171
+ else if (code !== 0) reject(new Error(`git ${sub[0]} failed: ${err.trim() || `exit ${code}`}`));
172
+ else resolve(Buffer.concat(out));
173
+ });
174
+ });
175
+ }
176
+
177
+ /** Commit của một ref (đã kiểm là commit), hoặc null. */
178
+ export async function resolveCommit(cwd, ref = 'HEAD', opts) {
179
+ if (!ref || String(ref).startsWith('-')) return null;
180
+ try { return (await gitRead(cwd, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], opts)).toString().trim() || null; } catch { return null; }
181
+ }
182
+
183
+ const MAX_STATE_ENTRIES = 20_000;
184
+ /**
185
+ * Trạng thái thô của cây làm việc — từng mục `git status` (để biết agent có sửa thẳng vào bản checkout chính thay vì worktree). Kho quá
186
+ * bẩn (> 20.000 mục) hoặc không phải kho → null (bỏ qua phép so).
187
+ */
188
+ export async function worktreeState(cwd, opts) {
189
+ try {
190
+ const entries = (await gitRead(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=all'], opts)).toString('utf8').split('\0').filter(Boolean);
191
+ return entries.length > MAX_STATE_ENTRIES ? null : entries.sort();
192
+ } catch { return null; }
193
+ }
194
+
195
+ /** Bản checkout chính có đổi giữa hai lần chụp không — bỏ qua thư mục của worktree job (nằm trong kho thì hiện ra là thư mục chưa theo dõi). */
196
+ export function mainCheckoutChanged(before, after, { cwd, worktree }) {
197
+ if (!before || !after) return false;
198
+ const rel = worktree ? path.relative(cwd, worktree).replace(/\\/g, '/') : '';
199
+ const inside = !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
200
+ const keep = (e) => {
201
+ if (!inside) return true;
202
+ const p = e.slice(3).replace(/\/+$/, '');
203
+ return !(p === rel || p.startsWith(`${rel}/`) || rel.startsWith(`${p}/`));
204
+ };
205
+ const a = before.filter(keep);
206
+ const b = after.filter(keep);
207
+ return a.length !== b.length || a.some((x, i) => x !== b[i]);
208
+ }
209
+
210
+ /** Đường dẫn của mọi worktree thuộc kho chứa `cwd`. */
211
+ export async function listWorktrees(cwd, opts) {
212
+ try {
213
+ return (await gitRead(cwd, ['worktree', 'list', '--porcelain'], opts)).toString('utf8').split('\n')
214
+ .filter((l) => l.startsWith('worktree ')).map((l) => path.resolve(l.slice(9).trim()));
215
+ } catch { return []; }
216
+ }
217
+
218
+ /**
219
+ * Diff giữa commit gốc và cây làm việc hiện tại (gồm cả commit mới và phần chưa commit) + tệp mới chưa theo dõi. Trả
220
+ * `{ files: [{ path, status }], added: [{ path, text }], removed: [{ path, text }] }` — dòng thêm / bớt chỉ lấy ở tệp test (đủ cho các bộ kiểm).
221
+ */
222
+ export async function diffSince(cwd, base, opts) {
223
+ const nameStatus = (await gitRead(cwd, ['diff', '--name-status', '--no-renames', '-z', base, '--'], opts)).toString('utf8').split('\0').filter(Boolean);
224
+ const files = [];
225
+ for (let i = 0; i + 1 < nameStatus.length; i += 2) files.push({ path: nameStatus[i + 1], status: nameStatus[i][0] });
226
+ const untracked = (await gitRead(cwd, ['ls-files', '--others', '--exclude-standard', '-z'], opts)).toString('utf8').split('\0').filter(Boolean);
227
+ for (const p of untracked) files.push({ path: p, status: 'A' });
228
+
229
+ const added = [];
230
+ const removed = [];
231
+ const testFiles = files.filter((f) => TEST_FILE_RE.test(f.path));
232
+ const tracked = testFiles.filter((f) => !untracked.includes(f.path)).map((f) => f.path);
233
+ if (tracked.length) {
234
+ const patch = (await gitRead(cwd, ['diff', '-U0', '--no-renames', '--no-color', base, '--', ...tracked], opts)).toString('utf8');
235
+ // Tiêu đề của mỗi tệp nằm giữa `diff --git` và `@@` đầu tiên — dòng nội dung bắt đầu bằng `+++` / `---` không bị đọc nhầm là tiêu đề.
236
+ let file = null;
237
+ let header = false;
238
+ for (const line of patch.split('\n')) {
239
+ if (line.startsWith('diff --git ')) { header = true; file = null; continue; }
240
+ if (header) {
241
+ if (line.startsWith('@@')) header = false;
242
+ else if (line.startsWith('--- a/')) file = line.slice(6);
243
+ else if (line.startsWith('+++ b/')) file = line.slice(6);
244
+ continue;
245
+ }
246
+ if (!file) continue;
247
+ if (line.startsWith('+')) added.push({ path: file, text: line.slice(1) });
248
+ else if (line.startsWith('-')) removed.push({ path: file, text: line.slice(1) });
249
+ }
250
+ }
251
+ for (const f of testFiles.filter((x) => untracked.includes(x.path))) {
252
+ try {
253
+ const abs = path.join(cwd, f.path);
254
+ if (fs.statSync(abs).size > MAX_UNTRACKED_READ) continue;
255
+ for (const text of fs.readFileSync(abs, 'utf8').replace(/\r?\n$/, '').split(/\r?\n/)) added.push({ path: f.path, text });
256
+ } catch { /* tệp vừa bị xoá */ }
257
+ }
258
+ return { files, added, removed };
259
+ }
260
+
261
+ const listed = (items) => (items.length > MAX_LISTED ? [...items.slice(0, MAX_LISTED), `… ${items.length - MAX_LISTED} more`] : items);
262
+ const check = (kind, status, detail = {}) => ({ check: kind, status, ...detail });
263
+ const mentions = (c, id) => new RegExp(`(^|[^A-Za-z0-9])${id}($|[^0-9])`).test(`${c.classname} ${c.name}`);
264
+
265
+ /** Một bộ kiểm cho `check_file_covered`: mọi ca của các luồng trong hợp đồng có kết quả; ca `auto` phải chạy thật trong JUnit. */
266
+ function coverage({ contract, testCheck, report, junitCases }) {
267
+ const flows = contract.test_check?.flows || [];
268
+ if (!contract.test_check) return { result: check(CheckKind.CHECK_FILE_COVERED, 'not_applicable', { reason: 'contract has no test_check' }), tests: [] };
269
+ if (!testCheck) return { result: check(CheckKind.CHECK_FILE_COVERED, 'fail', { reason: 'TEST_CHECK.md was not delivered with the job' }), tests: [] };
270
+ const problems = [];
271
+ if (!testCheck.ok) problems.push(...testCheck.errors.map((e) => `TEST_CHECK.md ${e}`));
272
+ const tests = [];
273
+ for (const flowId of flows) {
274
+ const flow = testCheck.flows.find((f) => f.id === flowId);
275
+ if (!flow) { problems.push(`flow ${flowId} is not in TEST_CHECK.md`); continue; }
276
+ for (const rule of flow.rules) {
277
+ if (!rule.cases.length) problems.push(`${rule.id} has no check`);
278
+ for (const c of rule.cases) {
279
+ const claimed = report?.report?.results?.[c.id];
280
+ const entry = { check_id: c.id, flow_id: flowId, rule_id: rule.id, method: c.method, reported: claimed };
281
+ if (c.method === 'auto') {
282
+ const runs = junitCases.filter((j) => mentions(j, c.id));
283
+ entry.measured = !runs.length ? 'missing' : runs.some((j) => j.status === 'fail' || j.status === 'error') ? 'fail' : runs.every((j) => j.status === 'skipped') ? 'skipped' : 'pass';
284
+ if (entry.measured === 'missing') problems.push(`${c.id} (auto) did not run — no test name contains it`);
285
+ if (claimed && entry.measured !== 'missing' && claimed !== entry.measured) entry.mismatch = true;
286
+ } else {
287
+ entry.measured = 'not_measured';
288
+ if (!claimed) problems.push(`${c.id} (${c.method}) has no result in REPORT.md`);
289
+ }
290
+ tests.push(entry);
291
+ }
292
+ }
293
+ }
294
+ const mismatches = tests.filter((t) => t.mismatch).map((t) => `${t.check_id}: reported ${t.reported}, measured ${t.measured}`);
295
+ return { result: check(CheckKind.CHECK_FILE_COVERED, problems.length ? 'fail' : 'pass', { problems: listed(problems), ...(mismatches.length ? { mismatches: listed(mismatches) } : {}) }), tests };
296
+ }
297
+
298
+ /**
299
+ * Đo một job có hợp đồng; ghi `<jobDir>/evidence.json` và trả object bằng chứng. Không ném lỗi (lỗi đo → bộ kiểm `error`).
300
+ * `job`: { id, contractSha, worktree, cwd, baseCommit, mainStateBefore }; `contract`: kết quả parseContract().contract;
301
+ * `testCheck`: parseTestCheck() hoặc null; đọc `REPORT.md` + `CONTRACT.md` ngay trong `jobDir`.
302
+ */
303
+ export async function measureEvidence({ job, contract, testCheck, jobDir, signal, gitOpts, runCommand = runVerifyCommand }) {
304
+ const evidence = {
305
+ job_id: job.id, contract_id: contract.contract_id, contract_version: contract.version, contract_sha256: job.contractSha,
306
+ feature_group: contract.feature_group, mode: 'shadow', measured_at: new Date().toISOString(),
307
+ base_commit: job.baseCommit || null, head_commit: null, worktree: job.worktree || null,
308
+ commands: [], diff: null, checks: [], acceptance: [], tests: [], report: null,
309
+ };
310
+ const write = () => {
311
+ try { fs.writeFileSync(path.join(jobDir, EVIDENCE_FILE), JSON.stringify(evidence, null, 1)); } catch { /* vẫn trả về qua agent.status */ }
312
+ return evidence;
313
+ };
314
+
315
+ // Hợp đồng bị sửa trong lúc chạy → dừng, không đo gì nữa.
316
+ let contractNow = '';
317
+ try { contractNow = fs.readFileSync(path.join(jobDir, 'CONTRACT.md'), 'utf8'); } catch { /* bị xoá */ }
318
+ if (sha256(contractNow) !== job.contractSha) {
319
+ evidence.contract_tampered = true;
320
+ evidence.checks.push(check('contract_intact', 'fail', { reason: 'CONTRACT.md changed during the job — nothing else was measured' }));
321
+ return write();
322
+ }
323
+
324
+ let reportText = null;
325
+ try { reportText = fs.readFileSync(path.join(jobDir, 'REPORT.md'), 'utf8'); } catch { /* agent chưa ghi */ }
326
+ const report = reportText === null ? null : parseReport(reportText, { contractId: contract.contract_id });
327
+ evidence.report = reportText === null ? { present: false } : { present: true, valid: report.ok, errors: listed(report.errors), status: report.report?.status, needs_scope_change: report.report?.needs_scope_change, new_checks: report.new_checks?.length || 0 };
328
+
329
+ const tree = job.worktree || job.cwd;
330
+ const base = job.baseCommit;
331
+ let diff = null;
332
+ if (base) {
333
+ try {
334
+ diff = await diffSince(tree, base, gitOpts);
335
+ evidence.head_commit = await resolveCommit(tree, 'HEAD', gitOpts);
336
+ evidence.diff = { files: listed(diff.files.map((f) => `${f.status} ${f.path}`)), changed: diff.files.length };
337
+ } catch (e) {
338
+ evidence.diff = { error: e.message };
339
+ }
340
+ } else evidence.diff = { error: 'not a git repository (or no base commit) — diff checks cannot run' };
341
+
342
+ // Lệnh kiểm chứng, lần lượt, trong cây của job.
343
+ const junitCases = [];
344
+ for (const cmd of contract.verify) {
345
+ if (signal?.aborted) break;
346
+ const res = await runCommand(cmd, { cwd: tree, logFile: path.join(jobDir, 'logs', `${cmd.id}.log`), signal });
347
+ const entry = { id: cmd.id, argv: cmd.argv, ...res, log: `logs/${cmd.id}.log` };
348
+ if (cmd.report) {
349
+ try {
350
+ const j = parseJUnit(fs.readFileSync(path.join(tree, cmd.report), 'utf8'));
351
+ entry.junit = { tests: j.tests, failures: j.failures, errors: j.errors, skipped: j.skipped };
352
+ junitCases.push(...j.cases);
353
+ } catch { entry.junit = { missing: true }; }
354
+ }
355
+ evidence.commands.push(entry);
356
+ const problems = [];
357
+ if (res.error) problems.push(res.error);
358
+ if (res.timed_out) problems.push(`timed out after ${cmd.timeout_ms} ms`);
359
+ if (res.exit_code !== 0 && !res.error) problems.push(`exit code ${res.exit_code}`);
360
+ if (entry.junit?.missing) problems.push(`${cmd.report} was not written`);
361
+ else if (entry.junit && (entry.junit.failures || entry.junit.errors)) problems.push(`${entry.junit.failures + entry.junit.errors} failing tests`);
362
+ else if (entry.junit && !entry.junit.tests) problems.push(`${cmd.report} has no test cases`);
363
+ evidence.checks.push(check(CheckKind.COMMAND_PASSED, problems.length ? 'fail' : 'pass', { command_id: cmd.id, ...(problems.length ? { problems } : {}) }));
364
+ }
365
+
366
+ if (diff) {
367
+ const changed = diff.files.map((f) => f.path);
368
+ const denied = changed.filter((p) => matchesAny(p, contract.scope.deny_paths));
369
+ const outside = !!job.worktree && mainCheckoutChanged(job.mainStateBefore, await worktreeState(job.cwd, gitOpts), { cwd: job.cwd, worktree: job.worktree });
370
+ evidence.checks.push(check(CheckKind.DIFF_IN_SCOPE, denied.length || outside ? 'fail' : 'pass', {
371
+ ...(denied.length ? { denied: listed(denied) } : {}), ...(outside ? { reason: 'the main checkout changed — work must stay in the job worktree' } : {}),
372
+ }));
373
+ // Tệp được bảo vệ: không sửa / xoá bản đã có; thêm tệp mới (ví dụ test mới) thì được.
374
+ const touched = diff.files.filter((f) => f.status !== 'A' && matchesAny(f.path, contract.scope.protected_paths)).map((f) => `${f.status} ${f.path}`);
375
+ evidence.checks.push(check(CheckKind.PROTECTED_UNTOUCHED, touched.length ? 'fail' : 'pass', touched.length ? { touched: listed(touched) } : {}));
376
+ const declsAdded = diff.added.filter((l) => TEST_DECL_RE.test(l.text)).length;
377
+ const declsRemoved = diff.removed.filter((l) => TEST_DECL_RE.test(l.text));
378
+ const deletedTests = diff.files.filter((f) => f.status === 'D' && TEST_FILE_RE.test(f.path)).map((f) => f.path);
379
+ evidence.checks.push(check(CheckKind.TESTS_NOT_REDUCED, declsRemoved.length > declsAdded ? 'fail' : 'pass', {
380
+ added: declsAdded, removed: declsRemoved.length, ...(deletedTests.length ? { deleted_test_files: listed(deletedTests) } : {}),
381
+ ...(declsRemoved.length > declsAdded ? { removed_lines: listed(declsRemoved.map((l) => `${l.path}: ${l.text.trim().slice(0, 160)}`)) } : {}),
382
+ }));
383
+ const skips = diff.added.filter((l) => SKIP_RE.test(l.text)).map((l) => `${l.path}: ${l.text.trim().slice(0, 160)}`);
384
+ evidence.checks.push(check(CheckKind.NO_NEW_SKIPS, skips.length ? 'fail' : 'pass', skips.length ? { lines: listed(skips) } : {}));
385
+ } else {
386
+ for (const kind of [CheckKind.DIFF_IN_SCOPE, CheckKind.PROTECTED_UNTOUCHED, CheckKind.TESTS_NOT_REDUCED, CheckKind.NO_NEW_SKIPS]) {
387
+ evidence.checks.push(check(kind, 'error', { reason: evidence.diff?.error }));
388
+ }
389
+ }
390
+
391
+ const cov = coverage({ contract, testCheck, report, junitCases });
392
+ evidence.tests = cov.tests;
393
+ evidence.checks.push(cov.result);
394
+
395
+ const missing = [];
396
+ for (const o of contract.outputs.filter((x) => x.required)) {
397
+ if (o.kind === 'report_md' && !report?.ok) missing.push(`${o.id}: REPORT.md is ${report ? 'not in the agreed format' : 'missing'}`);
398
+ if (o.kind === 'git_branch' && !diff?.files.length) missing.push(`${o.id}: no code change in the job worktree`);
399
+ }
400
+ evidence.checks.push(check(CheckKind.OUTPUTS_COMPLETE, missing.length ? 'fail' : 'pass', missing.length ? { missing } : {}));
401
+
402
+ // Tiêu chí của hợp đồng → bộ kiểm đã đo; tiêu chí cần giám khảo (llm_rubric, người) để Agentic chấm.
403
+ for (const a of contract.acceptance) {
404
+ if (!a.check) { evidence.acceptance.push({ key: a.key, required: a.required, status: 'needs_verifier', verifier: a.verifier }); continue; }
405
+ const hit = evidence.checks.find((c) => c.check === a.check && (a.check !== CheckKind.COMMAND_PASSED || c.command_id === a.command_id));
406
+ evidence.acceptance.push({ key: a.key, required: a.required, check: a.check, status: hit ? hit.status : 'error' });
407
+ }
408
+ return write();
409
+ }