devcontour-harness 0.1.0-alpha.37 → 0.1.0-alpha.42
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/README.md +42 -2
- package/docs/architecture.md +28 -4
- package/docs/contracts.md +35 -20
- package/docs/release-notes/0.1.0-alpha.38.md +31 -0
- package/docs/release-notes/0.1.0-alpha.39.md +38 -0
- package/docs/release-notes/0.1.0-alpha.40.md +27 -0
- package/docs/release-notes/0.1.0-alpha.41.md +49 -0
- package/docs/release-notes/0.1.0-alpha.42.md +44 -0
- package/docs/upgrade.md +132 -0
- package/lib/agents/review-probe.d.ts +3 -1
- package/lib/agents/review-probe.js +8 -4
- package/lib/contracts/execution.js +4 -3
- package/lib/contracts/policy.d.ts +19 -0
- package/lib/contracts/policy.js +30 -0
- package/lib/contracts/published.d.ts +1 -0
- package/lib/engine/engine.js +23 -5
- package/lib/engine/joint-runner.js +2 -2
- package/lib/engine/runner.d.ts +11 -0
- package/lib/engine/runner.js +82 -13
- package/lib/environment/isolation.d.ts +41 -1
- package/lib/environment/isolation.js +167 -5
- package/lib/environment/lifecycle.d.ts +46 -2
- package/lib/environment/lifecycle.js +81 -2
- package/lib/report/compute.js +16 -6
- package/lib/report/document.js +2 -2
- package/lib/verification/confirm.js +6 -4
- package/lib/verification/gates-at.js +3 -1
- package/lib/verification/gates.d.ts +36 -2
- package/lib/verification/gates.js +71 -11
- package/package.json +1 -1
- package/schemas/execution-policy.schema.json +5 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { readFile, readdir, writeFile, mkdir, mkdtemp, rm, realpath, lstat, chmod, } from 'node:fs/promises';
|
|
2
|
-
import { tmpdir } from 'node:os';
|
|
2
|
+
import { availableParallelism, loadavg, tmpdir } from 'node:os';
|
|
3
3
|
import { join, resolve, sep, delimiter, relative, dirname } from 'node:path';
|
|
4
4
|
import { accessSync, constants, existsSync } from 'node:fs';
|
|
5
5
|
import { createHash, randomUUID } from 'node:crypto';
|
|
6
6
|
import { XMLParser, XMLValidator } from 'fast-xml-parser';
|
|
7
|
-
import { sha256, } from "../contracts/index.js";
|
|
7
|
+
import { sha256, gateTimeoutMs, gateTimeoutText, } from "../contracts/index.js";
|
|
8
8
|
import { command, git, gitOutput } from "../environment/process.js";
|
|
9
9
|
import { isolation, isolatedCommand, srtTempDir, isolationSupport, protectedChanges, protectedSnapshot, SandboxPolicyError, sandboxDenials, snapshotLimit, watchSandboxLog, } from "../environment/isolation.js";
|
|
10
10
|
import { UntrustedCheckoutError } from "../environment/git-trust.js";
|
|
@@ -521,6 +521,35 @@ export function freshnessEnv(kind, env) {
|
|
|
521
521
|
? { TURBO_FORCE: 'true', GOFLAGS: [env.GOFLAGS, '-count=1'].filter(Boolean).join(' ') }
|
|
522
522
|
: {};
|
|
523
523
|
}
|
|
524
|
+
/**
|
|
525
|
+
* Нагрузка хоста на одно ядро (средняя за минуту), начиная с которой gate,
|
|
526
|
+
* исчерпавший свой предел времени, повторяется один раз на том же SHA
|
|
527
|
+
* (`GateTimeout.overloaded`). Под такой нагрузкой предел gate меряет очередь
|
|
528
|
+
* к процессору, а не его код; проверка, которая и на свободной машине не
|
|
529
|
+
* укладывается в предел, повтора не получает.
|
|
530
|
+
*/
|
|
531
|
+
export const HOST_LOAD_RECHECK_PER_CPU = 2;
|
|
532
|
+
/** Снимок нагрузки хоста; объект — чтобы тест мог подменить чтение. */
|
|
533
|
+
export const hostLoad = {
|
|
534
|
+
read: () => ({ load1: loadavg()[0] ?? 0, cpus: Math.max(1, availableParallelism()) }),
|
|
535
|
+
};
|
|
536
|
+
const loadText = (load) => `нагрузка хоста ${Math.round(load.load1 * 10) / 10} на ${load.cpus} ядер`;
|
|
537
|
+
/**
|
|
538
|
+
* Gate исчерпал свой предел времени (не отмена попытки). Класс отказа —
|
|
539
|
+
* прежний `gate`; нагрузка в момент таймаута решает, повторить ли gate один
|
|
540
|
+
* раз (`Runner`): повтор прошёл — исход `flaky`, попытка не тратится; снова
|
|
541
|
+
* таймаут — провал засчитан как прежде.
|
|
542
|
+
*/
|
|
543
|
+
export class GateTimeout extends TaskFailure {
|
|
544
|
+
load;
|
|
545
|
+
constructor(message, load) {
|
|
546
|
+
super('gate', message);
|
|
547
|
+
this.load = load;
|
|
548
|
+
}
|
|
549
|
+
get overloaded() {
|
|
550
|
+
return this.load.load1 / this.load.cpus >= HOST_LOAD_RECHECK_PER_CPU;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
524
553
|
/**
|
|
525
554
|
* Gate попытки. `test` принимается только по свежему (прежний отчёт удалён до
|
|
526
555
|
* запуска) непустому JUnit без failures, errors и skips на этом SHA; exit 0
|
|
@@ -590,6 +619,14 @@ export async function runGate(run) {
|
|
|
590
619
|
let kind = 'gate';
|
|
591
620
|
/** Причина отказа окружения (`attempt.diagnosed`), когда она известна здесь. */
|
|
592
621
|
let cause;
|
|
622
|
+
/**
|
|
623
|
+
* Нагрузка хоста, когда gate исчерпал свой предел времени: меньшая из
|
|
624
|
+
* снятых до запуска и в момент таймаута.
|
|
625
|
+
*/
|
|
626
|
+
let timedOut;
|
|
627
|
+
let loadBefore;
|
|
628
|
+
/** Провалы, записанные в JUnit до таймаута: повтор их не отменяет. */
|
|
629
|
+
let timedOutFailures = '';
|
|
593
630
|
// Заголовок лога — фактические каталог и argv запуска: digest лога входит в
|
|
594
631
|
// evidence, и запись называет, где и чем проверка исполнялась.
|
|
595
632
|
let passed = false, summary = '', log = `# harness gate ${gate.id}: cwd=${relative(root, gateCwd) || '.'} argv=${JSON.stringify(gate.command.map(redact))}${gate.kind === 'test' ? ` fresh=${redact(JSON.stringify(freshness))}` : ''}\n`, exitCode = -1, manifest;
|
|
@@ -597,6 +634,9 @@ export async function runGate(run) {
|
|
|
597
634
|
// Снимок защищённых путей до проверки: запреты песочницы видят только
|
|
598
635
|
// путь операции, перенос готового каталога ими не закрыт.
|
|
599
636
|
const before = run.policy.isolation.mode === 'os' ? protectedSnapshot(root) : undefined;
|
|
637
|
+
// Нагрузка до запуска: gate, который сам перегрузил процессор (пул
|
|
638
|
+
// потоков без предела), не должен заработать повтор своей нагрузкой.
|
|
639
|
+
loadBefore = hostLoad.read();
|
|
600
640
|
const result = await runCheck({ config: run.policy }, {
|
|
601
641
|
activity: {
|
|
602
642
|
kind: 'gate',
|
|
@@ -614,7 +654,7 @@ export async function runGate(run) {
|
|
|
614
654
|
...Object.fromEntries(Object.entries(propertyEnv).map(([k, v]) => [k.replace(/^DEVCONTOUR_/, 'HARNESS_'), v])),
|
|
615
655
|
},
|
|
616
656
|
redact,
|
|
617
|
-
timeoutMs: gate.
|
|
657
|
+
timeoutMs: gateTimeoutMs(gate, run.policy),
|
|
618
658
|
signal,
|
|
619
659
|
write: [cwd, ...(propertyDir ? [propertyDir] : [])],
|
|
620
660
|
readable: [...run.boundary.readable, ...(corpusDir ? [corpusDir] : [])],
|
|
@@ -630,7 +670,7 @@ export async function runGate(run) {
|
|
|
630
670
|
let planted = [];
|
|
631
671
|
try {
|
|
632
672
|
if (before)
|
|
633
|
-
planted = protectedChanges(before, root);
|
|
673
|
+
planted = protectedChanges(before, root, run.execution.prepared);
|
|
634
674
|
}
|
|
635
675
|
catch (error) {
|
|
636
676
|
if (error instanceof SandboxPolicyError)
|
|
@@ -639,15 +679,31 @@ export async function runGate(run) {
|
|
|
639
679
|
}
|
|
640
680
|
if (planted.length) {
|
|
641
681
|
kind = 'scope-violation';
|
|
642
|
-
throw new Error('проверка
|
|
682
|
+
throw new Error('проверка создала, изменила или удалила защищённые пути (конфигурация IDE, shell, git или Claude): ' +
|
|
643
683
|
planted
|
|
644
684
|
.slice(0, 5)
|
|
645
685
|
.map((p) => relative(root, p))
|
|
646
686
|
.join(', ') +
|
|
647
687
|
(planted.length > 5 ? ` и ещё ${planted.length - 5}` : ''));
|
|
648
688
|
}
|
|
689
|
+
if (result.timedOut && !signal.aborted) {
|
|
690
|
+
const now = hostLoad.read();
|
|
691
|
+
timedOut =
|
|
692
|
+
loadBefore && loadBefore.load1 / loadBefore.cpus < now.load1 / now.cpus ? loadBefore : now;
|
|
693
|
+
// Отчёт, записанный до таймаута, читается без гарантий: названный в нём
|
|
694
|
+
// провал — найденный дефект, и повтор gate его не отменяет.
|
|
695
|
+
const partial = reportPath
|
|
696
|
+
? await readReport(reportPath, cwd, redact).catch(() => undefined)
|
|
697
|
+
: undefined;
|
|
698
|
+
if (partial?.failures) {
|
|
699
|
+
manifest = partial;
|
|
700
|
+
timedOutFailures = failedCases(partial);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
649
703
|
if (result.timedOut || signal.aborted)
|
|
650
|
-
throw new Error('Проверка прервана или превысила timeout'
|
|
704
|
+
throw new Error('Проверка прервана или превысила timeout' +
|
|
705
|
+
(timedOut ? `: ${gateTimeoutText(gate, run.policy)}, ${loadText(timedOut)}` : '') +
|
|
706
|
+
(timedOutFailures ? `; до таймаута упали ${timedOutFailures}` : ''));
|
|
651
707
|
// Песочница так и не запустила команду по известному отказу запуска:
|
|
652
708
|
// код проекта не исполнялся, и его правка ничего не изменит. Это отказ
|
|
653
709
|
// среды, а не провал проверки; текст srt вроде «Shell 'bash' not found
|
|
@@ -891,7 +947,11 @@ export async function runGate(run) {
|
|
|
891
947
|
...(report?.corpus?.failed.map((c) => c.property) ?? []),
|
|
892
948
|
];
|
|
893
949
|
const declared = new Set(expected?.properties.map((p) => p.id) ?? []);
|
|
894
|
-
|
|
950
|
+
const message = `${phase}/${run.consumer ? run.consumer + ':' : ''}${gate.id}: ${evidence.summary}`;
|
|
951
|
+
// Таймаут без контрпримера свойства: повтор на том же SHA решает `Runner`.
|
|
952
|
+
if (timedOut && kind === 'gate' && !failing.length && !timedOutFailures)
|
|
953
|
+
throw new GateTimeout(message, timedOut);
|
|
954
|
+
throw new TaskFailure(kind, message, failing.length
|
|
895
955
|
? {
|
|
896
956
|
bound: [...new Set(failing.filter((id) => declared.has(id)))],
|
|
897
957
|
unbound: [...new Set(failing.filter((id) => !declared.has(id)))],
|
|
@@ -1048,7 +1108,7 @@ export async function prepareWriterDependencies(run) {
|
|
|
1048
1108
|
cwd: gateCwd,
|
|
1049
1109
|
env: run.execution.env,
|
|
1050
1110
|
redact,
|
|
1051
|
-
timeoutMs: gate.
|
|
1111
|
+
timeoutMs: gateTimeoutMs(gate, run.policy),
|
|
1052
1112
|
signal,
|
|
1053
1113
|
write: [run.cwd],
|
|
1054
1114
|
readable: run.boundary.readable,
|
|
@@ -1059,7 +1119,7 @@ export async function prepareWriterDependencies(run) {
|
|
|
1059
1119
|
});
|
|
1060
1120
|
log += checked.stdout + '\n' + checked.stderr;
|
|
1061
1121
|
if (checked.timedOut)
|
|
1062
|
-
failure = 'превышен timeout';
|
|
1122
|
+
failure = 'превышен timeout: ' + gateTimeoutText(gate, run.policy);
|
|
1063
1123
|
else if (checked.launchFailed)
|
|
1064
1124
|
failure = 'песочница ОС не запустила команду';
|
|
1065
1125
|
else if (checked.code !== 0)
|
|
@@ -1080,7 +1140,7 @@ export async function prepareWriterDependencies(run) {
|
|
|
1080
1140
|
let unreadable;
|
|
1081
1141
|
try {
|
|
1082
1142
|
if (guarded)
|
|
1083
|
-
planted = protectedChanges(guarded, root);
|
|
1143
|
+
planted = protectedChanges(guarded, root, run.execution.prepared);
|
|
1084
1144
|
}
|
|
1085
1145
|
catch (error) {
|
|
1086
1146
|
if (!(error instanceof SandboxPolicyError))
|
|
@@ -1090,7 +1150,7 @@ export async function prepareWriterDependencies(run) {
|
|
|
1090
1150
|
if (planted.length || unreadable) {
|
|
1091
1151
|
const message = `установка зависимостей до исполнителя (${gate.id}) ` +
|
|
1092
1152
|
(unreadable ??
|
|
1093
|
-
'
|
|
1153
|
+
'создала, изменила или удалила защищённые пути (конфигурация IDE, shell, git или Claude): ' +
|
|
1094
1154
|
planted
|
|
1095
1155
|
.slice(0, 5)
|
|
1096
1156
|
.map((p) => relative(root, p))
|
package/package.json
CHANGED