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.
@@ -329,7 +329,7 @@ export function protectedWriteDenies(roots) {
329
329
  // Любой подкаталог, и появившийся во время проверки: `node_modules/.idea`
330
330
  // этим правилом тоже закрыт, но пакеты лежат уровнем ниже.
331
331
  if (safe)
332
- denies.push(join(dir, '*', name));
332
+ denies.push(anchoredAtRoot(root, join(dir, '*', name)));
333
333
  }
334
334
  let entries = [];
335
335
  try {
@@ -354,6 +354,41 @@ export function protectedWriteDenies(roots) {
354
354
  }
355
355
  return [...new Set(denies)];
356
356
  }
357
+ /**
358
+ * Шаблон запрета под каталогом `dir` внутри `root`, база которого — `root`.
359
+ *
360
+ * srt закрепляет базу шаблона (статический префикс до первого символа глоба)
361
+ * и всех её предков запретом `file-write-unlink`/`file-write-create`: иначе
362
+ * каталог можно было бы перенести из-под запрета. Шаблон `<dir>/*\/.idea`
363
+ * закреплял так каждый существующий каталог дерева до глубины перечисления:
364
+ * проверка не могла удалить или переименовать даже свой прежний вывод
365
+ * (`.reports/expo-export`, оставленный самопроверкой исполнителя), и
366
+ * `expo export` падал с `EPERM rmdir`.
367
+ *
368
+ * Один символ первого сегмента под `root` записывается классом (`.reports` →
369
+ * `[.]reports`): шаблон совпадает с теми же путями (класс из одного символа —
370
+ * этот символ), а статический префикс обрывается в `root`, и закреплены
371
+ * только `root` и его предки, как у шаблонов `root/**\/<имя>`. Перенос
372
+ * каталога с подложенным внутри `.idea` по-прежнему ловит сверка снимков
373
+ * (`protectedSnapshot`) — как и новый каталог, которого при сборке политики
374
+ * не было. Символ — печатный ASCII: класс Seatbelt сравнивает байты, и
375
+ * многобайтовый символ в классе совпал бы не с тем. Сегмент без такого
376
+ * символа остаётся прежним шаблоном.
377
+ */
378
+ export function anchoredAtRoot(root, pattern) {
379
+ const rest = relative(root, pattern);
380
+ if (!rest || rest.startsWith('..') || pattern !== join(root, rest))
381
+ return pattern;
382
+ const first = rest.split(sep)[0];
383
+ // `*` и прочие символы глоба отсюда не приходят (`glob` проверен выше);
384
+ // `^` в начале класса — отрицание, `\` и `-` — служебные.
385
+ const at = [...first].findIndex((c) => /^[\x20-\x7e]$/.test(c) && !/[\^\\\-*?[\]]/.test(c));
386
+ if (first === '*' || at < 0)
387
+ return pattern;
388
+ const chars = [...first];
389
+ const anchored = chars.slice(0, at).join('') + `[${chars[at]}]` + chars.slice(at + 1).join('');
390
+ return join(root, anchored, rest.slice(first.length));
391
+ }
357
392
  /** Запреты для `.git` корня: файл рабочего дерева целиком, у каталога — перенаправления. */
358
393
  function rootGitDenies(root) {
359
394
  const dotgit = join(root, '.git');
@@ -498,6 +533,100 @@ export function hiddenReadRule(policy, path) {
498
533
  return undefined;
499
534
  return `запрет чтения песочницы: ${hidden} закрыт проверке`;
500
535
  }
536
+ /**
537
+ * Каталоги, которые srt закрепляет от удаления и переноса запретами записи
538
+ * для корней `roots` (`protectedWriteDenies`): база каждого шаблона
539
+ * (статический префикс до первого символа глоба) и предки буквального пути.
540
+ * Возвращаются базы; закреплены и все их предки.
541
+ */
542
+ export function pinnedBases(roots) {
543
+ const denies = protectedWriteDenies(roots) ?? [];
544
+ return [
545
+ ...new Set(denies.map((d) => {
546
+ if (!glob.test(d))
547
+ return dirname(d);
548
+ const prefix = d.split(/[*?[\]]/)[0];
549
+ return prefix.endsWith(sep) ? prefix.slice(0, -1) : dirname(prefix);
550
+ })),
551
+ ];
552
+ }
553
+ /**
554
+ * Удаление или перенос существующего каталога внутри открытых проверке
555
+ * каталогов, в котором ей отказало ядро, — отказ среды, только когда:
556
+ *
557
+ * - каталог — база или предок запрета записи, пересчитанного по политике
558
+ * для корней, в которых работает проверка (`pinnedBases`): srt закрепляет
559
+ * его от переноса, и правка кода этого не снимет;
560
+ * - проверка упала с EPERM, назвав этот путь (абсолютно или относительно
561
+ * своего рабочего каталога) отдельным словом в той же строке, что и
562
+ * EPERM (`token`): отказ, который
563
+ * проверка пережила, — не причина её провала. Настоящий провал теста с
564
+ * проглоченной неудачной уборкой остаётся провалом gate, даже если в
565
+ * выводе есть другой EPERM и короткое имя каталога (`.claude`) где-то ещё.
566
+ *
567
+ * Отказ в создании сюда не входит: его дают и запреты имён, и они разобраны
568
+ * `mandatoryDenyRule`.
569
+ */
570
+ function pinnedDirectoryRule(policy, v, output, cwd, bases = pinnedBases) {
571
+ if (v.operation !== 'file-write-unlink' || output === undefined || cwd === undefined)
572
+ return undefined;
573
+ const lines = output.split(/\r?\n/).filter((line) => epermPattern.test(line));
574
+ if (!lines.length)
575
+ return undefined;
576
+ const roots = policy.write.filter((w) => cwd === w || cwd.startsWith(w + sep));
577
+ if (!roots.some((w) => v.path.startsWith(w + sep)))
578
+ return undefined;
579
+ const local = relative(cwd, v.path);
580
+ const spellings = [
581
+ v.path,
582
+ ...(v.path.startsWith('/private/') ? [v.path.slice('/private'.length)] : []),
583
+ ];
584
+ const named = (line) => spellings.some((p) => token(line, p, false)) ||
585
+ (!local.startsWith('..') && local !== '' && token(line, local, true));
586
+ if (!lines.some(named))
587
+ return undefined;
588
+ try {
589
+ if (!lstatSync(v.path).isDirectory())
590
+ return undefined;
591
+ }
592
+ catch {
593
+ return undefined;
594
+ }
595
+ let pinned;
596
+ try {
597
+ pinned = bases(roots);
598
+ }
599
+ catch {
600
+ return undefined;
601
+ }
602
+ if (!pinned.some((b) => b === v.path || b.startsWith(v.path + sep)))
603
+ return undefined;
604
+ return 'запрет sandbox-runtime на удаление или перенос каталога: каталог закреплён запретами записи внутри него';
605
+ }
606
+ const epermPattern = /\bEPERM\b|operation not permitted/i;
607
+ /**
608
+ * Путь отдельным словом строки: перед ним начало строки, пробел, кавычка,
609
+ * `(`, `[`, `=` или `<` (у относительного ещё `./`), после — конец строки,
610
+ * пробел, кавычка, `:`, `/`, `,`, `;`, `)`, `]`, `>` или точка в конце
611
+ * предложения (перед пробелом или концом строки). Так `.claude-old`,
612
+ * `.claude.bak` и `~/.claude/…` не называют `.claude`.
613
+ */
614
+ function token(line, path, relativePath) {
615
+ const before = /[\s'"`([=<]/;
616
+ const after = /[\s'"`:/,;)\]>]/;
617
+ const ends = (end) => end >= line.length ||
618
+ after.test(line[end]) ||
619
+ (line[end] === '.' && (end + 1 >= line.length || /\s/.test(line[end + 1])));
620
+ for (let i = line.indexOf(path); i !== -1; i = line.indexOf(path, i + 1)) {
621
+ if (!ends(i + path.length))
622
+ continue;
623
+ if (i === 0 || before.test(line[i - 1]))
624
+ return true;
625
+ if (relativePath && line.slice(i - 2, i) === './' && (i === 2 || before.test(line[i - 3])))
626
+ return true;
627
+ }
628
+ return false;
629
+ }
501
630
  /** Путь в выводе проверки в любом написании (macOS: /private/var и /var). */
502
631
  const mentions = (output, path) => output.includes(path) ||
503
632
  (path.startsWith('/private/') && output.includes(path.slice('/private'.length)));
@@ -518,7 +647,16 @@ const mentions = (output, path) => output.includes(path) ||
518
647
  */
519
648
  export function sandboxDenials(violations, policy, output, cwd) {
520
649
  const found = new Map();
521
- const eperm = output !== undefined && /\bEPERM\b|operation not permitted/i.test(output);
650
+ const eperm = output !== undefined && epermPattern.test(output);
651
+ // Базы закреплённых каталогов перечисляют дерево: один раз на разбор.
652
+ const bases = new Map();
653
+ const pinnedOnce = (roots) => {
654
+ const key = roots.join('\0');
655
+ let cached = bases.get(key);
656
+ if (!cached)
657
+ bases.set(key, (cached = pinnedBases(roots)));
658
+ return cached;
659
+ };
522
660
  const credentials = credentialPaths().flatMap((path) => {
523
661
  try {
524
662
  return [path, realpathSync(path)];
@@ -534,7 +672,8 @@ export function sandboxDenials(violations, policy, output, cwd) {
534
672
  if (found.has(v.path))
535
673
  continue;
536
674
  const rule = v.operation.startsWith('file-write')
537
- ? mandatoryDenyRule(policy, v.path)
675
+ ? (mandatoryDenyRule(policy, v.path) ??
676
+ pinnedDirectoryRule(policy, v, output, cwd, pinnedOnce))
538
677
  : v.operation.startsWith('file-read') &&
539
678
  !credential(v.path) &&
540
679
  eperm &&
@@ -670,6 +809,9 @@ export function protectedSnapshot(root) {
670
809
  * из снимка, а не пропуск: вызывающий решает, отказ ли это среды (снимок до
671
810
  * работы) или нарушение области (после).
672
811
  *
812
+ * Путь с содержимым, который был до снимка и исчез после, — нарушение
813
+ * (удаление `.idea` через перенос родителя).
814
+ *
673
815
  * Пустые каталоги (только каталоги, рекурсивно, без записи всем)
674
816
  * нарушением не считаются, если до снимка пути не было или он тоже был без
675
817
  * файлов: исполняемой конфигурации в них нет, а CLI исполнителя создаёт
@@ -677,9 +819,18 @@ export function protectedSnapshot(root) {
677
819
  * файлом. Путь, где раньше были файлы, по-прежнему нарушение при любом
678
820
  * изменении.
679
821
  */
680
- export function protectedChanges(before, root) {
822
+ export function protectedChanges(before, root,
823
+ /**
824
+ * Пути относительно `root`, которыми владеет подготовка фазы (вложенные
825
+ * `.git`, см. `preparationGuard`): не в счёт только их исчезновение
826
+ * (уборка фикстуры переносом родителя). Изменение — в том числе подмена
827
+ * переносом другого `.git` на то же место — нарушение: подменённый
828
+ * `gitdir` подмодуля git хоста прочитал бы при следующей команде.
829
+ */
830
+ owned) {
681
831
  const after = protectedSnapshot(root);
682
- return [...after]
832
+ const mine = (path) => !owned?.has(relative(root, path));
833
+ const changed = [...after]
683
834
  .filter(([path, sig]) => {
684
835
  if (sig === 'missing')
685
836
  return false;
@@ -689,6 +840,17 @@ export function protectedChanges(before, root) {
689
840
  return was !== sig;
690
841
  })
691
842
  .map(([path]) => path);
843
+ // Исчезнувший защищённый путь с содержимым — тоже нарушение: ядро не
844
+ // закрепляет каталоги дерева, и `.idea` уходит вместе с перенесённым и
845
+ // удалённым родителем. Пустые служебные каталоги (только каталоги)
846
+ // исчезать могут.
847
+ const removed = [...before]
848
+ .filter(([path, sig]) => mine(path) &&
849
+ sig !== 'missing' &&
850
+ sig !== emptyTree &&
851
+ (after.get(path) ?? 'missing') === 'missing')
852
+ .map(([path]) => path);
853
+ return [...changed, ...removed];
692
854
  }
693
855
  /**
694
856
  * Предел пути unix-сокета (`sun_path`, вместе с завершающим NUL): 104 байта
@@ -1,5 +1,6 @@
1
1
  import type { z } from 'zod';
2
2
  import { environmentSchema, lifecycleSchema, stepSchema, type ExecutionPolicy } from '../contracts/index.ts';
3
+ import { type Redactor } from './redaction.ts';
3
4
  export { redactor } from './redaction.ts';
4
5
  type Environment = z.infer<typeof environmentSchema>;
5
6
  type Lifecycle = z.infer<typeof lifecycleSchema>;
@@ -12,7 +13,9 @@ export declare class CleanupFailure extends Error {
12
13
  export declare function processAlive(pid: number): boolean;
13
14
  export declare function executionEnvironment(profiles: (Environment | undefined)[], devcontour?: NodeJS.ProcessEnv, source?: NodeJS.ProcessEnv): {
14
15
  env: NodeJS.ProcessEnv;
15
- redact: import("./redaction.ts").Redactor;
16
+ redact: Redactor;
17
+ /** Вложенные `.git`, созданные подготовкой фазы (`preparationGuard`). */
18
+ prepared?: PreparedProtected;
16
19
  };
17
20
  /** Наименьшая длина наследуемого значения без секретного имени, которое маскируется. */
18
21
  export declare const INHERITED_SECRET_MIN = 8;
@@ -28,10 +31,51 @@ export declare const inheritedSecret: (key: string, value: string) => boolean;
28
31
  * повод снимать маску с остальных: известный секрет иначе сохранялся бы в
29
32
  * команде и итоге проверки.
30
33
  */
31
- export declare function availableRedactor(profiles: (Environment | undefined)[], source?: NodeJS.ProcessEnv): import("./redaction.ts").Redactor;
34
+ export declare function availableRedactor(profiles: (Environment | undefined)[], source?: NodeJS.ProcessEnv): Redactor;
32
35
  export declare function runSteps(steps: Step[], cwd: string, dir: string, execution: ReturnType<typeof executionEnvironment>, signal: AbortSignal,
33
36
  /** SHA базы попытки: только с ним шаг установки может стать `dependency-network`. */
34
37
  trustedBase?: string): Promise<void>;
38
+ /**
39
+ * Защищённые пути, которыми владеет подготовка фазы: вложенные `.git`
40
+ * (подмодули, клоны зависимостей), созданные или изменённые её шагами. Пути —
41
+ * относительно корня дерева фазы. Сверки исполнителя, установки и gates той
42
+ * же фазы не считают нарушением только их исчезновение; изменение остаётся
43
+ * нарушением.
44
+ */
45
+ export type PreparedProtected = Set<string>;
46
+ /** Есть ли у фазы подготовка, которую стоит сверять. */
47
+ export declare function preparesTree(lifecycle: Lifecycle | undefined, prepare: readonly Step[], store: unknown): boolean;
48
+ /**
49
+ * Сверка защищённых путей вокруг подготовки фазы: шагов lifecycle `setup` и
50
+ * `ready`, хранилища зависимостей и шагов `prepare`. Их задаёт политика, и
51
+ * исполняются они обычным процессом хоста, вне песочницы, — запреты имён на
52
+ * них не действуют. Снимок снимается до `withEnvironment`, сверка — сразу
53
+ * после `prepare`, до черновика, установки и исполнителя.
54
+ *
55
+ * - Вложенный `.git`, созданный или изменённый подготовкой (`git submodule
56
+ * update --init`, клоны менеджеров зависимостей), разрешён и переходит во
57
+ * владение подготовки: проверка записывает его в `execution.prepared`, и
58
+ * сверки исполнителя, установки и gates этой фазы его исчезновение
59
+ * (уборка фикстуры переносом родителя) нарушением не считают. Изменение
60
+ * его содержимого или подмена другим `.git` — по-прежнему нарушение.
61
+ * - Любой другой защищённый путь — конфигурация IDE, агента, shell или
62
+ * корневого `.git` — созданный, изменённый или удалённый подготовкой, —
63
+ * отказ среды (`sandbox-policy`) с путями в сообщении: его чинит политика,
64
+ * а не код задачи.
65
+ *
66
+ * Без песочницы ОС (`os = false`) или без подготовки (`active = false`)
67
+ * сверки нет: обходить дерево незачем.
68
+ */
69
+ export declare function preparationGuard(os: boolean, root: string, active?: boolean): (execution?: {
70
+ prepared?: PreparedProtected;
71
+ }) => void;
72
+ /**
73
+ * Точка подмены для тестов: фазы берут сверку подготовки отсюда (как
74
+ * `hostLoad` у gate), и тест проверяет, что каждая фаза её вызывает.
75
+ */
76
+ export declare const preparation: {
77
+ guard: typeof preparationGuard;
78
+ };
35
79
  export declare function withEnvironment<T>(lifecycle: Lifecycle | undefined, cwd: string, dir: string, execution: ReturnType<typeof executionEnvironment>, signal: AbortSignal, action: () => Promise<T>, measure?: <R>(stage: string, action: () => Promise<R>) => Promise<R>): Promise<T>;
36
80
  /**
37
81
  * Завершить очистку окружения, прерванную падением процесса: по сохранённому
@@ -1,7 +1,8 @@
1
1
  import { mkdir, writeFile, readFile, realpath } from 'node:fs/promises';
2
- import { join, sep } from 'node:path';
2
+ import { basename, dirname, join, relative, sep } from 'node:path';
3
3
  import { digestOf, TaskFailure, } from "../contracts/index.js";
4
4
  import { dependencyNetworkFailure, dependencyNetworkMessage } from "./dependency-network.js";
5
+ import { protectedChanges, protectedSnapshot, SandboxPolicyError } from "./isolation.js";
5
6
  import { command } from "./process.js";
6
7
  import { redactor } from "./redaction.js";
7
8
  export { redactor } from "./redaction.js";
@@ -64,7 +65,8 @@ export function executionEnvironment(profiles, devcontour = {}, source = process
64
65
  if (key.startsWith('DEVCONTOUR_'))
65
66
  env['HARNESS_' + key.slice('DEVCONTOUR_'.length)] = value;
66
67
  }
67
- return { env, redact: redactor(secretValues) };
68
+ const result = { env, redact: redactor(secretValues) };
69
+ return result;
68
70
  }
69
71
  /** Имя переменной похоже на секрет. */
70
72
  const SECRET_NAME = /(TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|CREDENTIAL|AUTH|PRIVATE)/i;
@@ -129,6 +131,83 @@ trustedBase) {
129
131
  }
130
132
  }
131
133
  }
134
+ /** Есть ли у фазы подготовка, которую стоит сверять. */
135
+ export function preparesTree(lifecycle, prepare, store) {
136
+ return !!(lifecycle?.setup.length || lifecycle?.ready.length || prepare.length || store);
137
+ }
138
+ /**
139
+ * Вложенный `.git` (файл подмодуля или каталог клона) ниже корня дерева.
140
+ * Корневой `.git` с его `config` и `hooks` сюда не входит.
141
+ */
142
+ const nestedGit = (root, path) => basename(path).toLowerCase() === '.git' && dirname(path) !== root;
143
+ /**
144
+ * Сверка защищённых путей вокруг подготовки фазы: шагов lifecycle `setup` и
145
+ * `ready`, хранилища зависимостей и шагов `prepare`. Их задаёт политика, и
146
+ * исполняются они обычным процессом хоста, вне песочницы, — запреты имён на
147
+ * них не действуют. Снимок снимается до `withEnvironment`, сверка — сразу
148
+ * после `prepare`, до черновика, установки и исполнителя.
149
+ *
150
+ * - Вложенный `.git`, созданный или изменённый подготовкой (`git submodule
151
+ * update --init`, клоны менеджеров зависимостей), разрешён и переходит во
152
+ * владение подготовки: проверка записывает его в `execution.prepared`, и
153
+ * сверки исполнителя, установки и gates этой фазы его исчезновение
154
+ * (уборка фикстуры переносом родителя) нарушением не считают. Изменение
155
+ * его содержимого или подмена другим `.git` — по-прежнему нарушение.
156
+ * - Любой другой защищённый путь — конфигурация IDE, агента, shell или
157
+ * корневого `.git` — созданный, изменённый или удалённый подготовкой, —
158
+ * отказ среды (`sandbox-policy`) с путями в сообщении: его чинит политика,
159
+ * а не код задачи.
160
+ *
161
+ * Без песочницы ОС (`os = false`) или без подготовки (`active = false`)
162
+ * сверки нет: обходить дерево незачем.
163
+ */
164
+ export function preparationGuard(os, root, active = true) {
165
+ if (!os || !active)
166
+ return (() => { });
167
+ const environment = (message) => new TaskFailure('environment', message, undefined, 'sandbox-policy');
168
+ let before;
169
+ try {
170
+ before = protectedSnapshot(root);
171
+ }
172
+ catch (error) {
173
+ if (error instanceof SandboxPolicyError)
174
+ throw environment(error.message);
175
+ throw error;
176
+ }
177
+ const check = (execution) => {
178
+ let changed;
179
+ try {
180
+ changed = protectedChanges(before, root);
181
+ }
182
+ catch (error) {
183
+ if (error instanceof SandboxPolicyError)
184
+ throw environment(error.message);
185
+ throw error;
186
+ }
187
+ const refused = changed.filter((p) => !nestedGit(root, p));
188
+ if (refused.length)
189
+ throw environment('Подготовка окружения (lifecycle setup/ready, хранилище зависимостей, prepare) создала, ' +
190
+ 'изменила или удалила защищённые пути (конфигурация IDE, агента, shell или корневого git): ' +
191
+ refused
192
+ .slice(0, 5)
193
+ .map((p) => relative(root, p))
194
+ .join(', ') +
195
+ (refused.length > 5 ? ` и ещё ${refused.length - 5}` : '') +
196
+ '. Шаги подготовки задаёт политика, и исполняются они вне песочницы: такие пути в ' +
197
+ 'дереве проверки они не создают, не меняют и не удаляют — держите их вне worktree');
198
+ if (execution && changed.length) {
199
+ execution.prepared ??= new Set();
200
+ for (const p of changed)
201
+ execution.prepared.add(relative(root, p));
202
+ }
203
+ };
204
+ return check;
205
+ }
206
+ /**
207
+ * Точка подмены для тестов: фазы берут сверку подготовки отсюда (как
208
+ * `hostLoad` у gate), и тест проверяет, что каждая фаза её вызывает.
209
+ */
210
+ export const preparation = { guard: preparationGuard };
132
211
  // Teardown uses a fresh deadline: cancellation must not cancel cleanup itself.
133
212
  // The receipt is retained after crashes and can be explicitly resumed with environment-cleanup.
134
213
  export async function withEnvironment(lifecycle, cwd, dir, execution, signal, action, measure = (_stage, action) => action()) {
@@ -166,13 +166,17 @@ export function failureBucketOf(a) {
166
166
  * `attempt.diagnosed`): не засчитаны прерванные штатной остановкой, отказы до
167
167
  * работы (`blocked`), отказы окружения и провайдера (`environment`,
168
168
  * `provider-auth`) и истёкшее владение. Зависание (`stalled`) засчитано.
169
+ * Остановка вопросом (`needs-input`) не засчитана, только если движок вернул
170
+ * попытку (`givenBack` — по `attempt.diagnosed` с `counted: false`): сверх
171
+ * своего предела и до версии, вернувшей попытку, она засчитана.
169
172
  */
170
- const counted = (a) => a.status !== 'active' &&
173
+ const counted = (a, givenBack) => a.status !== 'active' &&
171
174
  a.interrupted !== 'shutdown' &&
172
175
  !a.blocked &&
173
176
  a.status !== 'expired' &&
174
177
  a.failureKind !== 'environment' &&
175
- a.failureKind !== 'provider-auth';
178
+ a.failureKind !== 'provider-auth' &&
179
+ !(a.failureKind === 'needs-input' && givenBack.has(a.id));
176
180
  /** Gate подготовки: установка зависимостей — его отказ часто сетевой (M6). */
177
181
  const setupGate = (gate) => /install|setup|bootstrap|deps|dependenc/i.test(gate);
178
182
  /** Отказ gate только в gates подготовки: возможно, сеть или реестр, а не код (M6). */
@@ -257,6 +261,12 @@ export function valueReport(input, options = {}) {
257
261
  const reviews = [...(input.reviews ?? [])].sort((a, b) => cmp(a.kind, b.kind) || cmp(a.subject, b.subject) || a.round - b.round || cmp(a.id, b.id));
258
262
  const events = [...(input.events ?? [])].sort((a, b) => a.seq - b.seq);
259
263
  const graphs = [...(input.graphs ?? [])].sort((a, b) => cmp(a.id, b.id));
264
+ // Остановки вопросом, вернувшие попытку: вердикт движка в `attempt.diagnosed`.
265
+ const givenBack = new Set();
266
+ for (const e of events)
267
+ if (e.type === 'attempt.diagnosed' && e.runId && e.payload.counted === false)
268
+ givenBack.add(e.runId);
269
+ const isCounted = (a) => counted(a, givenBack);
260
270
  const attemptsOf = new Map();
261
271
  for (const a of attempts) {
262
272
  const list = attemptsOf.get(a.workId) ?? [];
@@ -312,7 +322,7 @@ export function valueReport(input, options = {}) {
312
322
  const windowReviews = reviews.filter((r) => inWindow(w, r.at));
313
323
  const windowEvents = events.filter((e) => inWindow(w, e.at));
314
324
  const failedAttempts = windowAttempts.filter((a) => finishedStatuses.has(a.status));
315
- const isFirstPass = (f) => f.attempts.filter(counted).length === 1 && !!f.accepting && counted(f.accepting);
325
+ const isFirstPass = (f) => f.attempts.filter(isCounted).length === 1 && !!f.accepting && isCounted(f.accepting);
316
326
  /**
317
327
  * Первая попытка неизвестна: кроме принявшей, засчитаны только отказы без
318
328
  * класса — будь они отказами окружения, попытка была бы первой.
@@ -320,7 +330,7 @@ export function valueReport(input, options = {}) {
320
330
  const firstPassUnknown = (f) => {
321
331
  if (isFirstPass(f) || !f.accepting)
322
332
  return false;
323
- const others = f.attempts.filter((a) => a !== f.accepting && counted(a));
333
+ const others = f.attempts.filter((a) => a !== f.accepting && isCounted(a));
324
334
  return (others.length > 0 &&
325
335
  others.every((a) => {
326
336
  const b = failureBucketOf(a);
@@ -966,7 +976,7 @@ export function valueReport(input, options = {}) {
966
976
  outcome: f.outcome,
967
977
  finishedAt: f.finishedAt ? toIso(at(f.finishedAt)) : null,
968
978
  attempts: f.attempts.length,
969
- counted: f.attempts.filter(counted).length,
979
+ counted: f.attempts.filter(isCounted).length,
970
980
  leadMs: f.outcome === 'accepted' ? leadOf(f).ms : null,
971
981
  knownUsd: cost.usd,
972
982
  unknownCalls: cost.unknown,
@@ -1328,7 +1338,7 @@ function summaryOf(r, failedAttempts) {
1328
1338
  text: fp.bound === 'lower'
1329
1339
  ? `${plural(n, 'task')} accepted. At least ${fp.value} of them${pct(fp.value ?? 0, n)} on the first try; for ${plural(fp.unknown, 'more task')} it is unknown (failures without a class).`
1330
1340
  : `${plural(n, 'task')} accepted. ${fp.value} of them${pct(fp.value ?? 0, n)} on the first try.`,
1331
- basis: `Accepted: merged after all required checks and an independent review. First try: the accepting attempt was the only counted attempt (environment failures except stalls, blocked-before-work attempts, expired leases and shutdowns are not counted). Window: ${window}.`,
1341
+ basis: `Accepted: merged after all required checks and an independent review. First try: the accepting attempt was the only counted attempt (environment failures except stalls, blocked-before-work attempts, stops with a question that gave the attempt back, expired leases and shutdowns are not counted). Window: ${window}.`,
1332
1342
  measure: fp,
1333
1343
  },
1334
1344
  {
@@ -34,7 +34,7 @@ const causeLabels = {
34
34
  'sandbox-launch': 'sandbox did not start the command',
35
35
  'sandbox-network': 'sandbox closed the network',
36
36
  'sandbox-filesystem': 'sandbox denied file access',
37
- 'sandbox-policy': 'sandbox policy could not be built',
37
+ 'sandbox-policy': 'sandbox policy not built, or protected paths changed before work',
38
38
  'dependency-network': 'dependency install network or registry',
39
39
  'provider-auth': 'provider login',
40
40
  'provider-limit': 'provider limit or balance',
@@ -179,7 +179,7 @@ export function reportBlocks(r) {
179
179
  table(['Failure class', 'Attempts'], e.buckets.map((b) => [bucketLabels[b.bucket] ?? b.bucket, String(b.count)]), [1]);
180
180
  list([
181
181
  `Environment failures cost ${formatDuration(e.neutral.machineMs)} of machine time and ${money(e.neutral.costBound, e.neutral.knownUsd)} known spend; blocked before work (not counted as an attempt): ${e.neutral.blocked}; queue stops caused by the environment: ${e.neutral.runtimePauses}.`,
182
- `Integration check rechecks: ${e.rechecks.flaky} flaky (false rejection avoided), ${e.rechecks.confirmed} confirmed.`,
182
+ `Gate rechecks (integration failures after a green candidate, candidate timeouts under host load): ${e.rechecks.flaky} flaky (false rejection avoided), ${e.rechecks.confirmed} confirmed.`,
183
183
  e.causes
184
184
  ? `Environment sub-causes${e.causes.undiagnosed ? ` (${e.causes.undiagnosed} earlier ${e.causes.undiagnosed === 1 ? 'failure' : 'failures'} without a recorded sub-cause)` : ''}: ${e.causes.rows.length ? e.causes.rows.map((x) => `${causeLabels[x.cause] ?? x.cause} ${x.count}${x.counted ? ` (${x.counted} counted as an attempt)` : ''}`).join(', ') : 'none in the window'}.`
185
185
  : 'Environment sub-causes: not recorded yet.',
@@ -3,9 +3,9 @@ import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { z } from 'zod';
6
- import { HarnessError, idSchema, } from "../contracts/index.js";
6
+ import { HarnessError, idSchema, gateTimeoutMs, } from "../contracts/index.js";
7
7
  import { OversizedFile, readBounded } from "../environment/bounded-read.js";
8
- import { executionEnvironment, runSteps, withEnvironment } from "../environment/lifecycle.js";
8
+ import { executionEnvironment, preparation, preparesTree, runSteps, withEnvironment, } from "../environment/lifecycle.js";
9
9
  import { git, hostGitArgs } from "../environment/process.js";
10
10
  import { defaultResourceDatabase } from "../environment/resources.js";
11
11
  import { contractDocuments, obligationOf } from "./checks.js";
@@ -295,9 +295,10 @@ async function decide(ctx, work, ref, input, source) {
295
295
  DEVCONTOUR_TASK_ID: work.id,
296
296
  DEVCONTOUR_PHASE: 'case',
297
297
  }, ctx.environment ?? process.env);
298
- const limitMs = gate.timeoutMs * 3 + 120000;
298
+ const limitMs = gateTimeoutMs(gate, ctx.policy) * 3 + 120000;
299
299
  const deadline = Date.now() + limitMs;
300
300
  const signal = AbortSignal.timeout(limitMs);
301
+ const prepared = preparation.guard(ctx.policy.isolation.mode === 'os', dir, preparesTree(repo.lifecycle ?? ctx.policy.lifecycle, repo.prepare, repo.dependencyStore));
301
302
  await withEnvironment(repo.lifecycle ?? ctx.policy.lifecycle, dir, join(io, 'environment'), execution, signal, async () => {
302
303
  const boundary = ctx.boundary();
303
304
  await materializeStore({
@@ -311,6 +312,7 @@ async function decide(ctx, work, ref, input, source) {
311
312
  phaseMs: limitMs,
312
313
  }, { repo, cwd: dir, execution, signal, dir: io });
313
314
  await runSteps(repo.prepare, dir, join(io, 'prepare'), execution, signal);
315
+ prepared(execution);
314
316
  const request = join(io, 'case.json');
315
317
  await writeFile(request, JSON.stringify({ property: input.property, input: JSON.parse(text) }));
316
318
  for (let i = 0; i < 2; i++) {
@@ -327,7 +329,7 @@ async function decide(ctx, work, ref, input, source) {
327
329
  HARNESS_CASE_RESULT: out,
328
330
  },
329
331
  redact: execution.redact,
330
- timeoutMs: gate.timeoutMs,
332
+ timeoutMs: gateTimeoutMs(gate, ctx.policy),
331
333
  signal,
332
334
  write: [dir, io],
333
335
  readable: boundary.readable,
@@ -5,7 +5,7 @@ import { HarnessError, stallSweepOf, } from "../contracts/index.js";
5
5
  import { livenessPayload, superviseStalls } from "../engine/stall-sweep.js";
6
6
  import { TaskFailure } from "../engine/failure.js";
7
7
  import { git } from "../environment/process.js";
8
- import { executionEnvironment, runSteps, withEnvironment } from "../environment/lifecycle.js";
8
+ import { executionEnvironment, preparation, preparesTree, runSteps, withEnvironment, } from "../environment/lifecycle.js";
9
9
  import { defaultResourceDatabase, withResources } from "../environment/resources.js";
10
10
  import { removeSnapshots, snapshotDependencies } from "./dependencies.js";
11
11
  import { runGate } from "./gates.js";
@@ -146,9 +146,11 @@ async function gatesAt(ctx, input) {
146
146
  }),
147
147
  }, source);
148
148
  const boundary = ctx.boundary();
149
+ const prepared = preparation.guard(ctx.policy.isolation.mode === 'os', cwd, preparesTree(repo.lifecycle ?? ctx.policy.lifecycle, repo.prepare, repo.dependencyStore));
149
150
  await withEnvironment(repo.lifecycle ?? ctx.policy.lifecycle, cwd, join(artifacts, 'environment'), execution, signal, async () => {
150
151
  await materializeStore(store, { repo, cwd, execution, signal, dir: artifacts });
151
152
  await runSteps(repo.prepare, cwd, join(artifacts, 'prepare'), execution, signal);
153
+ prepared(execution);
152
154
  for (const gate of gates) {
153
155
  // Пропускается только gate, чья явная предпосылка (`dependsOn`) не
154
156
  // прошла. Провал неявной (более ранний check gate в режиме
@@ -1,5 +1,6 @@
1
1
  import { type Activity, type EvidenceRecord, type ExecutionPolicy, type GatePolicy } from '../contracts/index.ts';
2
2
  import { isolationSupport, type Isolation, type SandboxViolation } from '../environment/isolation.ts';
3
+ import { TaskFailure } from '../engine/failure.ts';
3
4
  import { type CheckManifest } from './property.ts';
4
5
  /** Длинное имя testcase заменяется хешем, а не обрезается: обрезка дала бы ложные совпадения. */
5
6
  export declare const TEST_ID_LIMIT = 1000;
@@ -181,9 +182,38 @@ export interface Boundary {
181
182
  readable: string[];
182
183
  checkouts?: string[];
183
184
  }
185
+ /**
186
+ * Нагрузка хоста на одно ядро (средняя за минуту), начиная с которой gate,
187
+ * исчерпавший свой предел времени, повторяется один раз на том же SHA
188
+ * (`GateTimeout.overloaded`). Под такой нагрузкой предел gate меряет очередь
189
+ * к процессору, а не его код; проверка, которая и на свободной машине не
190
+ * укладывается в предел, повтора не получает.
191
+ */
192
+ export declare const HOST_LOAD_RECHECK_PER_CPU = 2;
193
+ /** Снимок нагрузки хоста; объект — чтобы тест мог подменить чтение. */
194
+ export declare const hostLoad: {
195
+ read: () => HostLoad;
196
+ };
197
+ export interface HostLoad {
198
+ /** Средняя нагрузка за минуту (`os.loadavg()[0]`; на Windows — 0). */
199
+ load1: number;
200
+ /** Доступные процессу ядра. */
201
+ cpus: number;
202
+ }
203
+ /**
204
+ * Gate исчерпал свой предел времени (не отмена попытки). Класс отказа —
205
+ * прежний `gate`; нагрузка в момент таймаута решает, повторить ли gate один
206
+ * раз (`Runner`): повтор прошёл — исход `flaky`, попытка не тратится; снова
207
+ * таймаут — провал засчитан как прежде.
208
+ */
209
+ export declare class GateTimeout extends TaskFailure {
210
+ readonly load: HostLoad;
211
+ constructor(message: string, load: HostLoad);
212
+ get overloaded(): boolean;
213
+ }
184
214
  /** Что нужно для запуска gate попытки. */
185
215
  export interface GateRun {
186
- policy: Pick<ExecutionPolicy, 'isolation'>;
216
+ policy: Pick<ExecutionPolicy, 'isolation' | 'gateTimeoutFloorMs'>;
187
217
  /** Запись evidence под fencing попытки. */
188
218
  record: (evidence: Omit<EvidenceRecord, 'id' | 'runId' | 'createdAt'>) => EvidenceRecord;
189
219
  cwd: string;
@@ -196,6 +226,8 @@ export interface GateRun {
196
226
  execution: {
197
227
  env: NodeJS.ProcessEnv;
198
228
  redact: (value: string) => string;
229
+ /** Вложенные `.git`, созданные подготовкой фазы: их исчезновение сверка не считает. */
230
+ prepared?: ReadonlySet<string>;
199
231
  };
200
232
  /** Закрытое проверке (состояние controller, чужие checkout) и открытое внутри него. */
201
233
  boundary: Boundary;
@@ -239,7 +271,7 @@ export interface GateRun {
239
271
  export declare function runGate(run: GateRun): Promise<EvidenceRecord>;
240
272
  /** Что нужно для установки зависимостей в дереве исполнителя до его работы. */
241
273
  export interface WriterDependenciesRun {
242
- policy: Pick<ExecutionPolicy, 'isolation'>;
274
+ policy: Pick<ExecutionPolicy, 'isolation' | 'gateTimeoutFloorMs'>;
243
275
  /** Рабочее дерево исполнителя: база попытки, возможно с наложенным черновиком. */
244
276
  cwd: string;
245
277
  /** SHA базы попытки (HEAD дерева). */
@@ -261,6 +293,8 @@ export interface WriterDependenciesRun {
261
293
  execution: {
262
294
  env: NodeJS.ProcessEnv;
263
295
  redact: (value: string) => string;
296
+ /** Вложенные `.git`, созданные подготовкой фазы: их исчезновение сверка не считает. */
297
+ prepared?: ReadonlySet<string>;
264
298
  };
265
299
  boundary: Boundary;
266
300
  }