@krisada-m/ksd-intelligence 0.0.0-stage → 1.1.0
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.
- package/.antigravity-plugin/plugin.json +20 -0
- package/LICENSE +21 -0
- package/README.md +195 -2
- package/agy-skills/erosiano-review/SKILL.md +17 -0
- package/dist/adapters/agy/skills.js +252 -0
- package/dist/adapters/cli/check-changed.js +3 -0
- package/dist/adapters/cli/main.js +1013 -0
- package/dist/adapters/cli/policy-bin.js +10 -0
- package/dist/adapters/cli/review-verdict.js +3 -0
- package/dist/adapters/omp/extension.js +884 -0
- package/dist/adapters/omp/skills.js +130 -0
- package/dist/adapters/ui/hud.js +389 -0
- package/dist/adapters/ui/tree.js +471 -0
- package/dist/core/audit/index.js +2 -0
- package/dist/core/audit/log.js +505 -0
- package/dist/core/audit/summary.js +188 -0
- package/dist/core/changes/changes.js +591 -0
- package/dist/core/changes/git.js +266 -0
- package/dist/core/changes/plan.js +109 -0
- package/dist/core/changes/render.js +356 -0
- package/dist/core/engine/build.js +178 -0
- package/dist/core/engine/child.js +389 -0
- package/dist/core/engine/host.js +206 -0
- package/dist/core/engine/lock.js +133 -0
- package/dist/core/engine/protocol.js +43 -0
- package/dist/core/engine/runtime.js +44 -0
- package/dist/core/engine/status.js +452 -0
- package/dist/core/engine/typescript.js +194 -0
- package/dist/core/engine/workspace.js +72 -0
- package/dist/core/graph/graph.js +127 -0
- package/dist/core/graph/limits.js +16 -0
- package/dist/core/impact/query.js +1292 -0
- package/dist/core/impact/render.js +590 -0
- package/dist/core/impact/session.js +694 -0
- package/dist/core/indexing/declarations.js +455 -0
- package/dist/core/indexing/differential.js +345 -0
- package/dist/core/indexing/doctor.js +120 -0
- package/dist/core/indexing/indexer.js +811 -0
- package/dist/core/indexing/keys.js +451 -0
- package/dist/core/indexing/lexical.js +212 -0
- package/dist/core/indexing/packages.js +57 -0
- package/dist/core/indexing/program.js +171 -0
- package/dist/core/indexing/resolve.js +1004 -0
- package/dist/core/indexing/stamp.js +52 -0
- package/dist/core/indexing/surface.js +335 -0
- package/dist/core/indexing/ui-progress.js +37 -0
- package/dist/core/indexing/verify.js +76 -0
- package/dist/core/kernel/config.js +383 -0
- package/dist/core/kernel/glob.js +105 -0
- package/dist/core/kernel/guards.js +4 -0
- package/dist/core/kernel/types.js +3 -0
- package/dist/core/kernel/verdict.js +142 -0
- package/dist/core/knowledge/anchors.js +139 -0
- package/dist/core/knowledge/knowledge.js +95 -0
- package/dist/core/knowledge/learning.js +102 -0
- package/dist/core/knowledge/render.js +76 -0
- package/dist/core/knowledge/store.js +109 -0
- package/dist/core/knowledge/yaml.js +87 -0
- package/dist/core/search/lexical.js +382 -0
- package/dist/core/search/render.js +98 -0
- package/dist/core/search/segments.js +118 -0
- package/dist/core/verify/parse.js +127 -0
- package/dist/core/verify/render.js +67 -0
- package/dist/core/verify/report.js +40 -0
- package/dist/core/verify/revision.js +79 -0
- package/dist/core/verify/run.js +117 -0
- package/dist/core/verify/store.js +66 -0
- package/dist/core/verify/verify.js +173 -0
- package/dist/core/workspace/init.js +267 -0
- package/dist/core/workspace/probe.js +56 -0
- package/dist/core/workspace/scan.js +420 -0
- package/dist/engineering/baseline.js +337 -0
- package/dist/engineering/change-scope.js +500 -0
- package/dist/engineering/check-changed.js +40 -0
- package/dist/engineering/config.js +129 -0
- package/dist/engineering/dist/policy.d.ts +17 -0
- package/dist/engineering/dist/policy.js +150 -0
- package/dist/engineering/dist/runtime.d.ts +40 -0
- package/dist/engineering/dist/runtime.js +77 -0
- package/dist/engineering/dist/sdlc.d.ts +7 -0
- package/dist/engineering/dist/sdlc.js +27 -0
- package/dist/engineering/eslint-rules/index.js +107 -0
- package/dist/engineering/index.d.ts +7 -0
- package/dist/engineering/index.js +319 -0
- package/dist/engineering/intelligence.js +44 -0
- package/dist/engineering/package.json +36 -0
- package/dist/engineering/policy.js +2 -0
- package/dist/engineering/practice-tool.js +72 -0
- package/dist/engineering/practices.js +283 -0
- package/dist/engineering/practices.json +2453 -0
- package/dist/engineering/review-verdict.js +262 -0
- package/dist/engineering/sdlc.js +2 -0
- package/dist/index.js +20 -0
- package/dist/storage/records.js +245 -0
- package/dist/storage/sqlite.js +314 -0
- package/dist/workflow/catalog.js +69 -0
- package/dist/workflow/classify.js +55 -0
- package/dist/workflow/loader.js +140 -0
- package/dist/workflow/packs.js +469 -0
- package/dist/workflow/registry.js +359 -0
- package/dist/workflow/render.js +61 -0
- package/dist/workflow/router.js +141 -0
- package/dist/workflow/sources.js +229 -0
- package/dist/workflow/types.js +44 -0
- package/dist/workflow/updates.js +532 -0
- package/engineering.lock.json +94 -0
- package/package.json +81 -4
- package/rules/engineering.md +20 -0
- package/scripts/agy-mcp.mjs +27 -0
- package/scripts/mcp/engineering.mjs +91 -0
- package/scripts/mcp/stdio.mjs +304 -0
- package/scripts/mcp/tools.mjs +491 -0
- package/skills/ksd-intelligence/SKILL.md +54 -0
- package/skills/matt-sdlc/SKILL.md +42 -0
- package/skills/osmani-quality/SKILL.md +38 -0
- package/skills/poteto-mode/SKILL.md +40 -0
- package/skills/pstack-analysis/SKILL.md +36 -0
- package/skills.lock.json +71 -0
- package/skills.registry.json +181 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
export const MAX_FAILURES = 10;
|
|
2
|
+
function sumMatches(text, re) {
|
|
3
|
+
let total = null;
|
|
4
|
+
for (const match of text.matchAll(re)) {
|
|
5
|
+
total = (total ?? 0) + Number(match[1]);
|
|
6
|
+
}
|
|
7
|
+
return total;
|
|
8
|
+
}
|
|
9
|
+
// node:test (TAP and spec reporters): `# tests 3` / `ℹ tests 3`, summed over every summary block.
|
|
10
|
+
function nodeTestCounts(text) {
|
|
11
|
+
const tests = sumMatches(text, /^\s*(?:#|ℹ)\s*tests\s+(\d+)\s*$/gm);
|
|
12
|
+
if (tests === null)
|
|
13
|
+
return null;
|
|
14
|
+
return {
|
|
15
|
+
tests,
|
|
16
|
+
passed: sumMatches(text, /^\s*(?:#|ℹ)\s*pass\s+(\d+)\s*$/gm) ?? 0,
|
|
17
|
+
failed: sumMatches(text, /^\s*(?:#|ℹ)\s*fail\s+(\d+)\s*$/gm) ?? 0,
|
|
18
|
+
skipped: sumMatches(text, /^\s*(?:#|ℹ)\s*(?:skipped|todo)\s+(\d+)\s*$/gm) ?? 0,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
// Jest: `Tests: 1 failed, 2 skipped, 3 passed, 6 total`.
|
|
22
|
+
function jestCounts(text) {
|
|
23
|
+
const line = /^\s*Tests:\s+(.*\b\d+ total)\s*$/m.exec(text)?.[1];
|
|
24
|
+
if (line === undefined)
|
|
25
|
+
return null;
|
|
26
|
+
const pick = (word) => Number(new RegExp(`(\\d+) ${word}`).exec(line)?.[1] ?? 0);
|
|
27
|
+
return {
|
|
28
|
+
tests: pick('total'),
|
|
29
|
+
passed: pick('passed'),
|
|
30
|
+
failed: pick('failed'),
|
|
31
|
+
skipped: pick('skipped') + pick('todo'),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
// Vitest: ` Tests 1 failed | 2 passed (3)`.
|
|
35
|
+
function vitestCounts(text) {
|
|
36
|
+
const match = /^\s*Tests\s+(.*?)\s*\((\d+)\)\s*$/m.exec(text);
|
|
37
|
+
if (match?.[1] === undefined || match[2] === undefined)
|
|
38
|
+
return null;
|
|
39
|
+
const line = match[1];
|
|
40
|
+
const pick = (word) => Number(new RegExp(`(\\d+) ${word}`).exec(line)?.[1] ?? 0);
|
|
41
|
+
return {
|
|
42
|
+
tests: Number(match[2]),
|
|
43
|
+
passed: pick('passed'),
|
|
44
|
+
failed: pick('failed'),
|
|
45
|
+
skipped: pick('skipped') + pick('todo'),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
// Mocha: `3 passing`, `1 failing`, `2 pending`.
|
|
49
|
+
function mochaCounts(text) {
|
|
50
|
+
const passed = sumMatches(text, /^\s*(\d+) passing\b/gm);
|
|
51
|
+
if (passed === null)
|
|
52
|
+
return null;
|
|
53
|
+
const failed = sumMatches(text, /^\s*(\d+) failing\b/gm) ?? 0;
|
|
54
|
+
const skipped = sumMatches(text, /^\s*(\d+) pending\b/gm) ?? 0;
|
|
55
|
+
return { tests: passed + failed + skipped, passed, failed, skipped };
|
|
56
|
+
}
|
|
57
|
+
const NO_TESTS_RE = /^\s*(?:0 tests?\b|no tests? (?:found|ran|executed|to run)\b)/im;
|
|
58
|
+
/** Counts from a check's console output; recognised runners only, never guessed. */
|
|
59
|
+
export function parseOutput(text) {
|
|
60
|
+
const counts = nodeTestCounts(text) ??
|
|
61
|
+
jestCounts(text) ??
|
|
62
|
+
vitestCounts(text) ??
|
|
63
|
+
mochaCounts(text) ??
|
|
64
|
+
(NO_TESTS_RE.test(text) ? { tests: 0, passed: 0, failed: 0, skipped: 0 } : null);
|
|
65
|
+
const failures = [];
|
|
66
|
+
for (const match of text.matchAll(/^\s*not ok \d+ - (.+?)\s*$/gm)) {
|
|
67
|
+
const name = match[1];
|
|
68
|
+
if (name === undefined || failures.includes(name))
|
|
69
|
+
continue;
|
|
70
|
+
failures.push(name);
|
|
71
|
+
if (failures.length === MAX_FAILURES)
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
return { counts, failures };
|
|
75
|
+
}
|
|
76
|
+
function decodeXml(value) {
|
|
77
|
+
return value
|
|
78
|
+
.replace(/</g, '<')
|
|
79
|
+
.replace(/>/g, '>')
|
|
80
|
+
.replace(/"/g, '"')
|
|
81
|
+
.replace(/'/g, "'")
|
|
82
|
+
.replace(/&/g, '&');
|
|
83
|
+
}
|
|
84
|
+
/** Counts from JUnit XML: one `<testcase>` per test, failed when it holds `<failure>` or `<error>`. */
|
|
85
|
+
export function parseJunit(xml) {
|
|
86
|
+
const counts = { tests: 0, passed: 0, failed: 0, skipped: 0 };
|
|
87
|
+
const failures = [];
|
|
88
|
+
for (const match of xml.matchAll(/<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g)) {
|
|
89
|
+
const attrs = match[1] ?? '';
|
|
90
|
+
const body = match[2] ?? '';
|
|
91
|
+
counts.tests++;
|
|
92
|
+
if (/<(?:failure|error)\b/.test(body)) {
|
|
93
|
+
counts.failed++;
|
|
94
|
+
const name = decodeXml(/\bname="([^"]*)"/.exec(attrs)?.[1] ?? '(unnamed)');
|
|
95
|
+
if (failures.length < MAX_FAILURES)
|
|
96
|
+
failures.push(name);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (/<skipped\b/.test(body)) {
|
|
100
|
+
counts.skipped++;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
counts.passed++;
|
|
104
|
+
}
|
|
105
|
+
return { counts, failures };
|
|
106
|
+
}
|
|
107
|
+
/** Counts from a TAP file: top-level test points only (indented lines are subtests). */
|
|
108
|
+
export function parseTap(text) {
|
|
109
|
+
const counts = { tests: 0, passed: 0, failed: 0, skipped: 0 };
|
|
110
|
+
const failures = [];
|
|
111
|
+
for (const match of text.matchAll(/^(not )?ok\b(?: \d+)?(?: - )?([^#\n]*)(#.*)?$/gm)) {
|
|
112
|
+
counts.tests++;
|
|
113
|
+
const directive = match[3] ?? '';
|
|
114
|
+
if (/#\s*(?:skip|todo)\b/i.test(directive)) {
|
|
115
|
+
counts.skipped++;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (match[1] === undefined) {
|
|
119
|
+
counts.passed++;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
counts.failed++;
|
|
123
|
+
if (failures.length < MAX_FAILURES)
|
|
124
|
+
failures.push((match[2] ?? '').trim() || '(unnamed)');
|
|
125
|
+
}
|
|
126
|
+
return { counts, failures };
|
|
127
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { isCurrent } from './verify.js';
|
|
2
|
+
export const VERIFY_BUDGET = 6_000;
|
|
3
|
+
function counts(report) {
|
|
4
|
+
if (report.counts === undefined)
|
|
5
|
+
return 'tests: not reported by the output';
|
|
6
|
+
const { tests, passed, failed, skipped } = report.counts;
|
|
7
|
+
return `tests ${tests} · passed ${passed} · failed ${failed} · skipped ${skipped}`;
|
|
8
|
+
}
|
|
9
|
+
/** Line 1 carries name, status, revision and dirty state; the rest is evidence. */
|
|
10
|
+
export function renderVerifyReport(report, engine) {
|
|
11
|
+
const revision = report.revision === 'unknown' ? 'no commit' : report.revision.slice(0, 12);
|
|
12
|
+
const lines = [
|
|
13
|
+
`VERIFY ${report.check} — ${report.status} · ${revision}${report.dirty ? ' · dirty' : ''}`,
|
|
14
|
+
report.summary,
|
|
15
|
+
];
|
|
16
|
+
if (report.source === 'check') {
|
|
17
|
+
const exit = report.exitCode === undefined ? 'exit none' : `exit ${report.exitCode}`;
|
|
18
|
+
const seconds = ((report.durationMs ?? 0) / 1000).toFixed(1);
|
|
19
|
+
lines.push(`${exit} · ${seconds} s · ${counts(report)}`);
|
|
20
|
+
if (report.command !== undefined)
|
|
21
|
+
lines.push(`Command: ${report.command}`);
|
|
22
|
+
}
|
|
23
|
+
if (report.source === 'junit' || report.source === 'tap') {
|
|
24
|
+
lines.push(`From ${report.artifacts.join(', ')} (${report.source}) · ${counts(report)}`);
|
|
25
|
+
}
|
|
26
|
+
if (report.failures.length > 0) {
|
|
27
|
+
lines.push(`Failing (${report.failures.length})`, ...report.failures.map((name) => ` ${name}`));
|
|
28
|
+
}
|
|
29
|
+
const tail = report.outputTail.length === 0
|
|
30
|
+
? []
|
|
31
|
+
: [`Output (last ${report.outputTail.length} lines)`, ...report.outputTail];
|
|
32
|
+
const closing = [];
|
|
33
|
+
if (report.status === 'NOT_VERIFIED') {
|
|
34
|
+
closing.push('Next: say the result is not verified; do not report tests as passing.');
|
|
35
|
+
}
|
|
36
|
+
else if (report.status !== 'PASS') {
|
|
37
|
+
closing.push('Next: report this status as it is; fix and call ei_verify again only after a change.');
|
|
38
|
+
}
|
|
39
|
+
else if (report.dirty) {
|
|
40
|
+
closing.push('Next: report PASS for this working tree; it is not committed.');
|
|
41
|
+
}
|
|
42
|
+
closing.push(`— ${report.redacted ? 'secrets redacted · ' : ''}engine ${engine}`);
|
|
43
|
+
const text = [...lines, ...tail, ...closing].join('\n');
|
|
44
|
+
if (text.length <= VERIFY_BUDGET)
|
|
45
|
+
return text;
|
|
46
|
+
// Over budget: the output tail goes first; line 1, summary and failures stay.
|
|
47
|
+
return [...lines, '… (output tail omitted: over budget)', ...closing]
|
|
48
|
+
.join('\n')
|
|
49
|
+
.slice(0, VERIFY_BUDGET);
|
|
50
|
+
}
|
|
51
|
+
export function renderVerifyOutcome(outcome, engine) {
|
|
52
|
+
if (outcome.kind === 'failure')
|
|
53
|
+
return `${outcome.code}: ${outcome.message}`;
|
|
54
|
+
return renderVerifyReport(outcome.value, engine);
|
|
55
|
+
}
|
|
56
|
+
export function changesVerificationNote(reports, revision, checkNames) {
|
|
57
|
+
const current = reports.filter((report) => isCurrent(report, revision));
|
|
58
|
+
if (current.length > 0) {
|
|
59
|
+
const parts = current.map((report) => `${report.check} ${report.status}`);
|
|
60
|
+
return { line: `Verified for this tree: ${parts.join(' · ')} (ei_verify)` };
|
|
61
|
+
}
|
|
62
|
+
if (checkNames.length === 0)
|
|
63
|
+
return {};
|
|
64
|
+
return {
|
|
65
|
+
nextHint: ` No test result is recorded for this tree: call ei_verify (${checkNames.join(', ')}).`,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const MAX_TAIL_LINES = 40;
|
|
2
|
+
/**
|
|
3
|
+
* Status of a finished run. Only exit code 0 with no failed test is PASS, and a run whose
|
|
4
|
+
* output reports zero tests is SKIPPED: printed words never turn a failure into a pass.
|
|
5
|
+
*/
|
|
6
|
+
export function runStatus(run, counts) {
|
|
7
|
+
if (run.spawnError !== null) {
|
|
8
|
+
return { status: 'ERROR', summary: `could not start: ${run.spawnError}` };
|
|
9
|
+
}
|
|
10
|
+
if (run.timedOut) {
|
|
11
|
+
return { status: 'ERROR', summary: 'timed out; process group killed' };
|
|
12
|
+
}
|
|
13
|
+
if (run.cancelled)
|
|
14
|
+
return { status: 'ERROR', summary: 'cancelled; process group killed' };
|
|
15
|
+
if (run.exitCode !== 0) {
|
|
16
|
+
const how = run.exitCode === null ? `signal ${run.signal ?? 'unknown'}` : `exit ${run.exitCode}`;
|
|
17
|
+
return { status: 'FAIL', summary: `${how}` };
|
|
18
|
+
}
|
|
19
|
+
if (counts !== null && counts.failed > 0) {
|
|
20
|
+
return { status: 'FAIL', summary: `exit 0 but ${counts.failed} failed` };
|
|
21
|
+
}
|
|
22
|
+
if (counts !== null && counts.tests === 0) {
|
|
23
|
+
return { status: 'SKIPPED', summary: 'exit 0 but zero tests ran' };
|
|
24
|
+
}
|
|
25
|
+
return { status: 'PASS', summary: 'exit 0' };
|
|
26
|
+
}
|
|
27
|
+
/** Status of a result file: there is no exit code, so the counts decide. */
|
|
28
|
+
export function fileStatus(counts) {
|
|
29
|
+
if (counts.failed > 0)
|
|
30
|
+
return { status: 'FAIL', summary: `${counts.failed} failed` };
|
|
31
|
+
if (counts.tests === 0)
|
|
32
|
+
return { status: 'SKIPPED', summary: 'zero tests in the report' };
|
|
33
|
+
return { status: 'PASS', summary: `${counts.passed} passed` };
|
|
34
|
+
}
|
|
35
|
+
export function tailLines(text, max = MAX_TAIL_LINES) {
|
|
36
|
+
const lines = text.replace(/\r\n?/g, '\n').replace(/\n+$/, '').split('\n');
|
|
37
|
+
if (lines.length === 1 && lines[0] === '')
|
|
38
|
+
return [];
|
|
39
|
+
return lines.slice(-max);
|
|
40
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { lstat } from 'node:fs/promises';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { matchAny } from '../kernel/glob.js';
|
|
7
|
+
const execFileAsync = promisify(execFile);
|
|
8
|
+
async function git(root, args) {
|
|
9
|
+
try {
|
|
10
|
+
const { stdout } = await execFileAsync('git', [...args], {
|
|
11
|
+
cwd: root,
|
|
12
|
+
encoding: 'buffer',
|
|
13
|
+
maxBuffer: 256 * 2 ** 20,
|
|
14
|
+
});
|
|
15
|
+
return stdout;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function porcelainPaths(status, prefix) {
|
|
22
|
+
const entries = status.toString('utf8').split('\0');
|
|
23
|
+
const paths = [];
|
|
24
|
+
for (let i = 0; i < entries.length; i++) {
|
|
25
|
+
const entry = entries[i] ?? '';
|
|
26
|
+
if (entry.length < 4)
|
|
27
|
+
continue;
|
|
28
|
+
// Porcelain paths are relative to the git top level; keep those under the workspace root.
|
|
29
|
+
const path = entry.slice(3);
|
|
30
|
+
if (path.startsWith(prefix))
|
|
31
|
+
paths.push(path.slice(prefix.length));
|
|
32
|
+
// Renames and copies carry the old path as the next NUL field.
|
|
33
|
+
if (entry[0] === 'R' || entry[0] === 'C')
|
|
34
|
+
i++;
|
|
35
|
+
}
|
|
36
|
+
return paths.sort();
|
|
37
|
+
}
|
|
38
|
+
/** HEAD and the uncommitted state of the work tree; `changedPaths` are relative to `root`. */
|
|
39
|
+
export async function readRevision(root) {
|
|
40
|
+
const head = await git(root, ['rev-parse', '--verify', 'HEAD']);
|
|
41
|
+
const sha = head === null ? 'unknown' : head.toString('utf8').trim();
|
|
42
|
+
const prefix = (await git(root, ['rev-parse', '--show-prefix']))?.toString('utf8').trim() ?? '';
|
|
43
|
+
const status = await git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);
|
|
44
|
+
const changedPaths = status === null ? [] : porcelainPaths(status, prefix);
|
|
45
|
+
const hash = createHash('sha256').update(sha).update('\0');
|
|
46
|
+
if (status !== null)
|
|
47
|
+
hash.update(status);
|
|
48
|
+
const diff = sha === 'unknown' ? null : await git(root, ['diff', 'HEAD', '--binary']);
|
|
49
|
+
if (diff !== null)
|
|
50
|
+
hash.update(diff);
|
|
51
|
+
// Untracked files are not in the diff; their size and mtime stand in for content.
|
|
52
|
+
for (const path of changedPaths) {
|
|
53
|
+
const stat = await lstat(join(root, path)).catch(() => null);
|
|
54
|
+
hash.update(`\0${path}\0${stat === null ? 'gone' : `${stat.size}:${stat.mtimeMs}`}`);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
sha,
|
|
58
|
+
dirty: status === null || changedPaths.length > 0,
|
|
59
|
+
treeState: hash.digest('hex'),
|
|
60
|
+
changedPaths,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Newest change time (ms) of the files a report covers: the last commit touching them, or
|
|
65
|
+
* the mtime of any uncommitted file under them (a deleted one counts as now).
|
|
66
|
+
*/
|
|
67
|
+
export async function newestCoveredChange(root, covers, revision, now = Date.now()) {
|
|
68
|
+
const pathspecs = covers.map((glob) => glob.startsWith('!') ? `:(exclude,glob)${glob.slice(1)}` : `:(glob)${glob}`);
|
|
69
|
+
const log = await git(root, ['log', '-1', '--format=%ct', '--', ...pathspecs]);
|
|
70
|
+
const committed = log === null ? 0 : Number(log.toString('utf8').trim() || 0) * 1000;
|
|
71
|
+
let newest = committed;
|
|
72
|
+
for (const path of revision.changedPaths) {
|
|
73
|
+
if (!matchAny(covers, path))
|
|
74
|
+
continue;
|
|
75
|
+
const stat = await lstat(join(root, path)).catch(() => null);
|
|
76
|
+
newest = Math.max(newest, stat === null ? now : stat.mtimeMs);
|
|
77
|
+
}
|
|
78
|
+
return newest;
|
|
79
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { isSecretEnvName } from '../audit/log.js';
|
|
3
|
+
export const MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
|
|
4
|
+
/** The inherited environment minus every variable whose name looks like a credential. */
|
|
5
|
+
export function checkEnvironment(env) {
|
|
6
|
+
const out = {};
|
|
7
|
+
for (const [key, value] of Object.entries(env)) {
|
|
8
|
+
if (value === undefined || isSecretEnvName(key))
|
|
9
|
+
continue;
|
|
10
|
+
out[key] = value;
|
|
11
|
+
}
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
function killGroup(pid) {
|
|
15
|
+
if (pid === undefined)
|
|
16
|
+
return;
|
|
17
|
+
try {
|
|
18
|
+
// Negative pid: the whole process group, so grandchildren (npm → sh → node) die too.
|
|
19
|
+
process.kill(-pid, 'SIGKILL');
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// ESRCH: the group is already gone.
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
class TailBuffer {
|
|
26
|
+
cap;
|
|
27
|
+
chunks = [];
|
|
28
|
+
size = 0;
|
|
29
|
+
truncated = false;
|
|
30
|
+
constructor(cap) {
|
|
31
|
+
this.cap = cap;
|
|
32
|
+
}
|
|
33
|
+
push(chunk) {
|
|
34
|
+
this.chunks.push(chunk);
|
|
35
|
+
this.size += chunk.length;
|
|
36
|
+
while (this.size > this.cap && this.chunks.length > 0) {
|
|
37
|
+
const first = this.chunks[0];
|
|
38
|
+
if (first === undefined)
|
|
39
|
+
break;
|
|
40
|
+
const excess = this.size - this.cap;
|
|
41
|
+
this.truncated = true;
|
|
42
|
+
if (first.length <= excess) {
|
|
43
|
+
this.chunks.shift();
|
|
44
|
+
this.size -= first.length;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
this.chunks[0] = first.subarray(excess);
|
|
48
|
+
this.size -= excess;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
text() {
|
|
52
|
+
return Buffer.concat(this.chunks).toString('utf8');
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Runs one allowlisted check without a shell: argv comes only from the owner's config.
|
|
57
|
+
* Timeout or cancel kills the whole process group; so does a normal exit, so no orphan survives.
|
|
58
|
+
*/
|
|
59
|
+
export function runCheck(check, root, options = {}) {
|
|
60
|
+
const startedAt = new Date();
|
|
61
|
+
const started = performance.now();
|
|
62
|
+
const tail = new TailBuffer(options.maxOutputBytes ?? MAX_OUTPUT_BYTES);
|
|
63
|
+
const [file, ...args] = check.command;
|
|
64
|
+
return new Promise((resolve) => {
|
|
65
|
+
let timedOut = false;
|
|
66
|
+
let cancelled = false;
|
|
67
|
+
let spawnError = null;
|
|
68
|
+
let settled = false;
|
|
69
|
+
const child = spawn(file ?? '', args, {
|
|
70
|
+
cwd: root,
|
|
71
|
+
env: checkEnvironment(options.env ?? process.env),
|
|
72
|
+
shell: false,
|
|
73
|
+
detached: true,
|
|
74
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
75
|
+
windowsHide: true,
|
|
76
|
+
});
|
|
77
|
+
const timer = setTimeout(() => {
|
|
78
|
+
timedOut = true;
|
|
79
|
+
killGroup(child.pid);
|
|
80
|
+
}, check.timeoutSec * 1000);
|
|
81
|
+
const onAbort = () => {
|
|
82
|
+
cancelled = true;
|
|
83
|
+
killGroup(child.pid);
|
|
84
|
+
};
|
|
85
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
86
|
+
if (options.signal?.aborted)
|
|
87
|
+
onAbort();
|
|
88
|
+
child.stdout.on('data', (chunk) => tail.push(chunk));
|
|
89
|
+
child.stderr.on('data', (chunk) => tail.push(chunk));
|
|
90
|
+
const finish = (exitCode, signal) => {
|
|
91
|
+
if (settled)
|
|
92
|
+
return;
|
|
93
|
+
settled = true;
|
|
94
|
+
clearTimeout(timer);
|
|
95
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
96
|
+
resolve({
|
|
97
|
+
startedAt: startedAt.toISOString(),
|
|
98
|
+
durationMs: Math.round(performance.now() - started),
|
|
99
|
+
exitCode,
|
|
100
|
+
signal,
|
|
101
|
+
timedOut,
|
|
102
|
+
cancelled,
|
|
103
|
+
spawnError,
|
|
104
|
+
output: tail.text(),
|
|
105
|
+
outputTruncated: tail.truncated,
|
|
106
|
+
pid: child.pid ?? null,
|
|
107
|
+
});
|
|
108
|
+
};
|
|
109
|
+
child.on('error', (error) => {
|
|
110
|
+
spawnError = error.code ?? error.message;
|
|
111
|
+
finish(null, null);
|
|
112
|
+
});
|
|
113
|
+
// A leader that exits while background children hold the pipes would block 'close'.
|
|
114
|
+
child.on('exit', () => killGroup(child.pid));
|
|
115
|
+
child.on('close', (code, signal) => finish(code, signal));
|
|
116
|
+
});
|
|
117
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { isRecord } from '../kernel/guards.js';
|
|
5
|
+
import { VERIFY_NAME_RE } from '../kernel/config.js';
|
|
6
|
+
export const REPORTS_PER_CHECK = 10;
|
|
7
|
+
const VERIFY_DIR = 'verify';
|
|
8
|
+
function checkDir(cacheDir, check) {
|
|
9
|
+
// Names are validated before they reach here; this keeps a bad one out of the path anyway.
|
|
10
|
+
if (!VERIFY_NAME_RE.test(check))
|
|
11
|
+
throw new Error(`verify store: invalid check name "${check}"`);
|
|
12
|
+
return join(cacheDir, VERIFY_DIR, check);
|
|
13
|
+
}
|
|
14
|
+
/** Stores an already-redacted report and keeps the newest {@link REPORTS_PER_CHECK}. */
|
|
15
|
+
export function saveReport(cacheDir, report) {
|
|
16
|
+
const dir = checkDir(cacheDir, report.check);
|
|
17
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
18
|
+
const stamp = report.startedAt.replace(/[:.]/g, '-');
|
|
19
|
+
const file = `${stamp}-${randomBytes(4).toString('hex')}.json`;
|
|
20
|
+
writeFileSync(join(dir, file), `${JSON.stringify(report)}\n`, { mode: 0o600 });
|
|
21
|
+
const files = readdirSync(dir)
|
|
22
|
+
.filter((name) => name.endsWith('.json'))
|
|
23
|
+
.sort();
|
|
24
|
+
for (const old of files.slice(0, Math.max(0, files.length - REPORTS_PER_CHECK))) {
|
|
25
|
+
rmSync(join(dir, old), { force: true });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function isReport(value) {
|
|
29
|
+
return (isRecord(value) &&
|
|
30
|
+
typeof value.check === 'string' &&
|
|
31
|
+
typeof value.revision === 'string' &&
|
|
32
|
+
typeof value.treeState === 'string' &&
|
|
33
|
+
typeof value.status === 'string' &&
|
|
34
|
+
typeof value.startedAt === 'string');
|
|
35
|
+
}
|
|
36
|
+
/** Newest stored report per check, sorted by check name; unreadable files are skipped. */
|
|
37
|
+
export function latestReports(cacheDir) {
|
|
38
|
+
const root = join(cacheDir, VERIFY_DIR);
|
|
39
|
+
let checks;
|
|
40
|
+
try {
|
|
41
|
+
checks = readdirSync(root).filter((name) => VERIFY_NAME_RE.test(name));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
const out = [];
|
|
47
|
+
for (const check of checks.sort()) {
|
|
48
|
+
const files = readdirSync(join(root, check))
|
|
49
|
+
.filter((name) => name.endsWith('.json'))
|
|
50
|
+
.sort()
|
|
51
|
+
.reverse();
|
|
52
|
+
for (const file of files) {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(readFileSync(join(root, check, file), 'utf8'));
|
|
55
|
+
if (!isReport(parsed))
|
|
56
|
+
continue;
|
|
57
|
+
out.push(parsed);
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// A torn or foreign file: try the next older one.
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import { join, sep } from 'node:path';
|
|
3
|
+
import { redactSecrets } from '../audit/log.js';
|
|
4
|
+
import { VERIFY_NAME_RE } from '../kernel/config.js';
|
|
5
|
+
import { isRecord } from '../kernel/guards.js';
|
|
6
|
+
import { parseJunit, parseOutput, parseTap } from './parse.js';
|
|
7
|
+
import { fileStatus, runStatus, tailLines } from './report.js';
|
|
8
|
+
import { newestCoveredChange, readRevision } from './revision.js';
|
|
9
|
+
import { runCheck } from './run.js';
|
|
10
|
+
import { latestReports, saveReport } from './store.js';
|
|
11
|
+
const CONFIG_FILE = 'ei.config.json';
|
|
12
|
+
const MAX_REPORT_FILE_BYTES = 20 * 1024 * 1024;
|
|
13
|
+
/** Accepts exactly one of `check` or `report`, each a bare configured name; nothing else. */
|
|
14
|
+
export function validateVerifyInput(raw) {
|
|
15
|
+
if (!isRecord(raw))
|
|
16
|
+
return { ok: false, message: 'expected { check } or { report }' };
|
|
17
|
+
const keys = Object.keys(raw).filter((key) => raw[key] !== undefined);
|
|
18
|
+
const extra = keys.filter((key) => key !== 'check' && key !== 'report');
|
|
19
|
+
if (extra.length > 0) {
|
|
20
|
+
return { ok: false, message: `unknown field(s): ${extra.sort().join(', ')}` };
|
|
21
|
+
}
|
|
22
|
+
if (keys.length !== 1)
|
|
23
|
+
return { ok: false, message: 'give exactly one of check or report' };
|
|
24
|
+
const key = keys[0] === 'report' ? 'report' : 'check';
|
|
25
|
+
const name = raw[key];
|
|
26
|
+
if (typeof name !== 'string' || !VERIFY_NAME_RE.test(name)) {
|
|
27
|
+
return {
|
|
28
|
+
ok: false,
|
|
29
|
+
message: `${key} must be a configured name (letters, digits, . _ : -); nothing ran`,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
return { ok: true, request: key === 'report' ? { report: name } : { check: name } };
|
|
33
|
+
}
|
|
34
|
+
function notVerified(name, revision, summary, source = 'none') {
|
|
35
|
+
return {
|
|
36
|
+
check: name,
|
|
37
|
+
revision: revision.sha,
|
|
38
|
+
startedAt: new Date().toISOString(),
|
|
39
|
+
status: 'NOT_VERIFIED',
|
|
40
|
+
artifacts: [],
|
|
41
|
+
summary,
|
|
42
|
+
redacted: false,
|
|
43
|
+
source,
|
|
44
|
+
dirty: revision.dirty,
|
|
45
|
+
treeState: revision.treeState,
|
|
46
|
+
failures: [],
|
|
47
|
+
outputTail: [],
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function redact(text, env) {
|
|
51
|
+
const out = redactSecrets(text, env);
|
|
52
|
+
return { text: out, changed: out !== text };
|
|
53
|
+
}
|
|
54
|
+
async function verifyCheck(workspace, name, revision, options) {
|
|
55
|
+
const check = workspace.config.verification.checks?.find((entry) => entry.name === name);
|
|
56
|
+
if (check === undefined) {
|
|
57
|
+
return notVerified(name, revision, `"${name}" is not in verification.checks; nothing ran`);
|
|
58
|
+
}
|
|
59
|
+
// The allowlist must be the owner's committed text, not an edit made in this session.
|
|
60
|
+
if (revision.changedPaths.includes(CONFIG_FILE)) {
|
|
61
|
+
return notVerified(name, revision, `${CONFIG_FILE} has uncommitted changes; commit it to approve the allowlist. Nothing ran`);
|
|
62
|
+
}
|
|
63
|
+
const env = options.env ?? process.env;
|
|
64
|
+
const run = await (options.runner ?? runCheck)(check, workspace.root, {
|
|
65
|
+
env,
|
|
66
|
+
signal: options.signal,
|
|
67
|
+
});
|
|
68
|
+
const output = redact(run.output, env);
|
|
69
|
+
const command = redact(check.command.join(' '), env);
|
|
70
|
+
const parsed = parseOutput(output.text);
|
|
71
|
+
const { status, summary } = runStatus(run, parsed.counts);
|
|
72
|
+
return {
|
|
73
|
+
check: name,
|
|
74
|
+
command: command.text,
|
|
75
|
+
revision: revision.sha,
|
|
76
|
+
startedAt: run.startedAt,
|
|
77
|
+
status,
|
|
78
|
+
...(run.exitCode === null ? {} : { exitCode: run.exitCode }),
|
|
79
|
+
artifacts: [],
|
|
80
|
+
summary: run.outputTruncated ? `${summary}; output over 2 MB, tail kept` : summary,
|
|
81
|
+
redacted: output.changed || command.changed,
|
|
82
|
+
source: 'check',
|
|
83
|
+
dirty: revision.dirty,
|
|
84
|
+
treeState: revision.treeState,
|
|
85
|
+
durationMs: run.durationMs,
|
|
86
|
+
...(parsed.counts === null ? {} : { counts: parsed.counts }),
|
|
87
|
+
failures: parsed.failures,
|
|
88
|
+
outputTail: tailLines(output.text),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
async function verifyReportFile(workspace, name, revision, options) {
|
|
92
|
+
const entry = workspace.config.verification.reports?.find((report) => report.name === name);
|
|
93
|
+
if (entry === undefined) {
|
|
94
|
+
return notVerified(name, revision, `"${name}" is not in verification.reports; nothing read`);
|
|
95
|
+
}
|
|
96
|
+
const rootReal = await realpath(workspace.root);
|
|
97
|
+
const fileReal = await realpath(join(workspace.root, entry.path)).catch(() => null);
|
|
98
|
+
if (fileReal === null) {
|
|
99
|
+
return notVerified(name, revision, `${entry.path} not found`, entry.format);
|
|
100
|
+
}
|
|
101
|
+
if (!fileReal.startsWith(`${rootReal}${sep}`)) {
|
|
102
|
+
return notVerified(name, revision, `${entry.path} resolves outside the repository`, entry.format);
|
|
103
|
+
}
|
|
104
|
+
const info = await stat(fileReal);
|
|
105
|
+
if (!info.isFile() || info.size > MAX_REPORT_FILE_BYTES) {
|
|
106
|
+
return notVerified(name, revision, `${entry.path} is not a file under 20 MB`, entry.format);
|
|
107
|
+
}
|
|
108
|
+
const others = {
|
|
109
|
+
...revision,
|
|
110
|
+
changedPaths: revision.changedPaths.filter((p) => p !== entry.path),
|
|
111
|
+
};
|
|
112
|
+
const newest = await newestCoveredChange(workspace.root, entry.covers, others);
|
|
113
|
+
if (info.mtimeMs <= newest) {
|
|
114
|
+
return notVerified(name, revision, `${entry.path} is older than the last change to the files it covers; stale, not used`, entry.format);
|
|
115
|
+
}
|
|
116
|
+
const env = options.env ?? process.env;
|
|
117
|
+
const text = redact(await readFile(fileReal, 'utf8'), env);
|
|
118
|
+
const parsed = entry.format === 'junit' ? parseJunit(text.text) : parseTap(text.text);
|
|
119
|
+
const counts = parsed.counts ?? { tests: 0, passed: 0, failed: 0, skipped: 0 };
|
|
120
|
+
const { status, summary } = fileStatus(counts);
|
|
121
|
+
return {
|
|
122
|
+
check: name,
|
|
123
|
+
revision: revision.sha,
|
|
124
|
+
startedAt: info.mtime.toISOString(),
|
|
125
|
+
status,
|
|
126
|
+
artifacts: [entry.path],
|
|
127
|
+
summary,
|
|
128
|
+
redacted: text.changed,
|
|
129
|
+
source: entry.format,
|
|
130
|
+
dirty: revision.dirty,
|
|
131
|
+
treeState: revision.treeState,
|
|
132
|
+
counts,
|
|
133
|
+
failures: parsed.failures,
|
|
134
|
+
outputTail: [],
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Runs one owner-allowlisted check or reads one configured result file, and stores the
|
|
139
|
+
* redacted report. The request carries a name only; argv and paths come from the config.
|
|
140
|
+
*/
|
|
141
|
+
export async function runVerification(workspace, request, options = {}) {
|
|
142
|
+
const name = 'check' in request ? request.check : request.report;
|
|
143
|
+
if (!VERIFY_NAME_RE.test(name)) {
|
|
144
|
+
return { kind: 'failure', code: 'INVALID_INPUT', message: 'invalid name; nothing ran' };
|
|
145
|
+
}
|
|
146
|
+
const revision = await readRevision(workspace.root);
|
|
147
|
+
if (!workspace.config.verification.enabled) {
|
|
148
|
+
return {
|
|
149
|
+
kind: 'result',
|
|
150
|
+
value: notVerified(name, revision, 'verification is disabled in ei.config.json; nothing ran'),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
const report = 'check' in request
|
|
154
|
+
? await verifyCheck(workspace, name, revision, options)
|
|
155
|
+
: await verifyReportFile(workspace, name, revision, options);
|
|
156
|
+
if (report.status !== 'NOT_VERIFIED')
|
|
157
|
+
saveReport(workspace.cacheDir, report);
|
|
158
|
+
return { kind: 'result', value: report };
|
|
159
|
+
}
|
|
160
|
+
/** A stored report describes the current tree only when HEAD and every uncommitted byte match. */
|
|
161
|
+
export function isCurrent(report, revision) {
|
|
162
|
+
return report.revision === revision.sha && report.treeState === revision.treeState;
|
|
163
|
+
}
|
|
164
|
+
/** Stored reports and the current tree for `ei_changes`; undefined when verification is off. */
|
|
165
|
+
export async function loadVerificationState(workspace) {
|
|
166
|
+
if (!workspace.config.verification.enabled)
|
|
167
|
+
return undefined;
|
|
168
|
+
return {
|
|
169
|
+
reports: latestReports(workspace.cacheDir),
|
|
170
|
+
revision: await readRevision(workspace.root),
|
|
171
|
+
checkNames: (workspace.config.verification.checks ?? []).map((check) => check.name),
|
|
172
|
+
};
|
|
173
|
+
}
|