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.
@@ -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.timeoutMs,
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('проверка создала или изменила защищённые пути (конфигурация IDE, shell, git или Claude): ' +
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
- throw new TaskFailure(kind, `${phase}/${run.consumer ? run.consumer + ':' : ''}${gate.id}: ${evidence.summary}`, failing.length
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.timeoutMs,
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
- 'создала или изменила защищённые пути (конфигурация IDE, shell, git или Claude): ' +
1153
+ 'создала, изменила или удалила защищённые пути (конфигурация IDE, shell, git или Claude): ' +
1094
1154
  planted
1095
1155
  .slice(0, 5)
1096
1156
  .map((p) => relative(root, p))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "devcontour-harness",
3
- "version": "0.1.0-alpha.37",
3
+ "version": "0.1.0-alpha.42",
4
4
  "description": "Headless execution harness: work graph, isolated attempts, gates, independent reviews and accepted results.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -2042,6 +2042,11 @@
2042
2042
  "minimum": 0,
2043
2043
  "maximum": 2
2044
2044
  },
2045
+ "gateTimeoutFloorMs": {
2046
+ "type": "integer",
2047
+ "minimum": 1000,
2048
+ "maximum": 600000
2049
+ },
2045
2050
  "stallSweep": {
2046
2051
  "type": "object",
2047
2052
  "properties": {