devcontour-harness 0.1.0-alpha.37 → 0.1.0-alpha.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +56 -2
  2. package/docs/architecture.md +64 -5
  3. package/docs/contracts.md +45 -22
  4. package/docs/release-notes/0.1.0-alpha.38.md +31 -0
  5. package/docs/release-notes/0.1.0-alpha.39.md +38 -0
  6. package/docs/release-notes/0.1.0-alpha.40.md +27 -0
  7. package/docs/release-notes/0.1.0-alpha.41.md +49 -0
  8. package/docs/release-notes/0.1.0-alpha.42.md +44 -0
  9. package/docs/release-notes/0.1.0-alpha.43.md +40 -0
  10. package/docs/release-notes/0.1.0-alpha.44.md +44 -0
  11. package/docs/upgrade.md +197 -17
  12. package/lib/agents/review-probe.d.ts +3 -1
  13. package/lib/agents/review-probe.js +8 -4
  14. package/lib/contracts/cli.d.ts +48 -4
  15. package/lib/contracts/events.d.ts +60 -5
  16. package/lib/contracts/events.js +16 -1
  17. package/lib/contracts/execution.d.ts +37 -0
  18. package/lib/contracts/execution.js +24 -3
  19. package/lib/contracts/policy.d.ts +19 -0
  20. package/lib/contracts/policy.js +30 -0
  21. package/lib/contracts/published.d.ts +29 -2
  22. package/lib/contracts/report.d.ts +8 -0
  23. package/lib/contracts/report.js +7 -1
  24. package/lib/contracts/result.d.ts +2 -0
  25. package/lib/contracts/result.js +6 -0
  26. package/lib/control/harness.d.ts +5 -0
  27. package/lib/engine/engine.d.ts +36 -3
  28. package/lib/engine/engine.js +140 -21
  29. package/lib/engine/joint-runner.d.ts +2 -0
  30. package/lib/engine/joint-runner.js +14 -4
  31. package/lib/engine/runner.d.ts +11 -0
  32. package/lib/engine/runner.js +82 -13
  33. package/lib/environment/isolation.d.ts +41 -1
  34. package/lib/environment/isolation.js +203 -7
  35. package/lib/environment/lifecycle.d.ts +46 -2
  36. package/lib/environment/lifecycle.js +81 -2
  37. package/lib/report/compute.js +19 -6
  38. package/lib/report/document.js +3 -3
  39. package/lib/storage/document.d.ts +2 -0
  40. package/lib/testing/store-contract.d.ts +8 -2
  41. package/lib/testing/store-contract.js +56 -1
  42. package/lib/verification/confirm.js +6 -4
  43. package/lib/verification/gates-at.js +3 -1
  44. package/lib/verification/gates.d.ts +36 -2
  45. package/lib/verification/gates.js +71 -11
  46. package/lib/verification/joint.d.ts +179 -1
  47. package/lib/verification/joint.js +23 -3
  48. package/package.json +1 -1
  49. package/schemas/execution-document.schema.json +4 -0
  50. package/schemas/execution-policy.schema.json +5 -0
  51. package/schemas/joint-verification.schema.json +4 -0
  52. package/schemas/run-event.schema.json +96 -0
  53. package/schemas/value-report.schema.json +20 -0
@@ -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 &&
@@ -605,9 +744,13 @@ export function protectedSnapshot(root) {
605
744
  if (stat.isSymbolicLink())
606
745
  return 'l:' + readlinkSync(path);
607
746
  // Не каталог и не ссылка — файл, FIFO, сокет, устройство: всё это
608
- // содержимое, пустым деревом не бывает.
747
+ // содержимое, пустым деревом не бывает. mtime возвращает `utimes`,
748
+ // ctime — нет: правка на месте в перенесённом наружу родителе с
749
+ // восстановленными размером и mtime всё равно меняет подпись. Ту же
750
+ // ctime меняют chmod/chown и новая жёсткая ссылка на файл — для
751
+ // защищённой конфигурации это тоже изменение.
609
752
  if (!stat.isDirectory())
610
- return `f:${stat.size}:${stat.mtimeMs}:${stat.ino}`;
753
+ return `f:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.ino}`;
611
754
  const mode = stat.mode & 0o7777;
612
755
  const names = readdirSync(path).sort();
613
756
  const inner = names.map((name) => signature(join(path, name)));
@@ -663,6 +806,36 @@ export function protectedSnapshot(root) {
663
806
  walk(root);
664
807
  return found;
665
808
  }
809
+ /**
810
+ * Исчез ли `path` из дерева сам, а не скрылся за подменённым родителем.
811
+ *
812
+ * Снимок не спускается в символьные ссылки на каталоги: родитель `sub`,
813
+ * перенесённый наружу и заменённый ссылкой на каталог вне дерева с другим
814
+ * `.git`, выглядел бы как исчезновение `sub/.git`, а git хоста прочитал бы
815
+ * подменённый `gitdir` через ссылку. Исчезновением считается только путь,
816
+ * у которого цепочка родителей от `root` — настоящие каталоги до первого
817
+ * отсутствующего звена (родитель удалён или перенесён наружу) или до
818
+ * самого пути. Ссылка или не каталог на месте родителя — подмена.
819
+ */
820
+ function removedInPlace(root, path) {
821
+ const parts = relative(root, path).split(sep).slice(0, -1);
822
+ let dir = root;
823
+ for (const part of parts) {
824
+ dir = join(dir, part);
825
+ let stat;
826
+ try {
827
+ stat = lstatSync(dir);
828
+ }
829
+ catch (error) {
830
+ if (missing(error))
831
+ return true;
832
+ return unreadable(root, dir, error);
833
+ }
834
+ if (stat.isSymbolicLink() || !stat.isDirectory())
835
+ return false;
836
+ }
837
+ return true;
838
+ }
666
839
  /**
667
840
  * Защищённые пути, которые появились или изменились после снимка `before`.
668
841
  *
@@ -670,6 +843,9 @@ export function protectedSnapshot(root) {
670
843
  * из снимка, а не пропуск: вызывающий решает, отказ ли это среды (снимок до
671
844
  * работы) или нарушение области (после).
672
845
  *
846
+ * Путь с содержимым, который был до снимка и исчез после, — нарушение
847
+ * (удаление `.idea` через перенос родителя).
848
+ *
673
849
  * Пустые каталоги (только каталоги, рекурсивно, без записи всем)
674
850
  * нарушением не считаются, если до снимка пути не было или он тоже был без
675
851
  * файлов: исполняемой конфигурации в них нет, а CLI исполнителя создаёт
@@ -677,9 +853,18 @@ export function protectedSnapshot(root) {
677
853
  * файлом. Путь, где раньше были файлы, по-прежнему нарушение при любом
678
854
  * изменении.
679
855
  */
680
- export function protectedChanges(before, root) {
856
+ export function protectedChanges(before, root,
857
+ /**
858
+ * Пути относительно `root`, которыми владеет подготовка фазы (вложенные
859
+ * `.git`, см. `preparationGuard`): не в счёт только их исчезновение
860
+ * (уборка фикстуры переносом родителя, см. `removedInPlace`). Изменение — в том числе подмена
861
+ * переносом другого `.git` на то же место — нарушение: подменённый
862
+ * `gitdir` подмодуля git хоста прочитал бы при следующей команде.
863
+ */
864
+ owned) {
681
865
  const after = protectedSnapshot(root);
682
- return [...after]
866
+ const mine = (path) => !owned?.has(relative(root, path)) || !removedInPlace(root, path);
867
+ const changed = [...after]
683
868
  .filter(([path, sig]) => {
684
869
  if (sig === 'missing')
685
870
  return false;
@@ -689,6 +874,17 @@ export function protectedChanges(before, root) {
689
874
  return was !== sig;
690
875
  })
691
876
  .map(([path]) => path);
877
+ // Исчезнувший защищённый путь с содержимым — тоже нарушение: ядро не
878
+ // закрепляет каталоги дерева, и `.idea` уходит вместе с перенесённым и
879
+ // удалённым родителем. Пустые служебные каталоги (только каталоги)
880
+ // исчезать могут.
881
+ const removed = [...before]
882
+ .filter(([path, sig]) => mine(path) &&
883
+ sig !== 'missing' &&
884
+ sig !== emptyTree &&
885
+ (after.get(path) ?? 'missing') === 'missing')
886
+ .map(([path]) => path);
887
+ return [...changed, ...removed];
692
888
  }
693
889
  /**
694
890
  * Предел пути 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);
@@ -634,6 +644,7 @@ export function valueReport(input, options = {}) {
634
644
  cancelledWithoutAttempt: 0,
635
645
  baseMoves: zero(['operator', 'controller', 'host']),
636
646
  baseMovesBound: 'lower',
647
+ jointResets: zero(['operator', 'host']),
637
648
  gaps: gapInWindow.size,
638
649
  };
639
650
  for (const e of windowEvents)
@@ -649,6 +660,8 @@ export function valueReport(input, options = {}) {
649
660
  }
650
661
  else if (e.type === 'base.moved')
651
662
  r.baseMoves[e.payload.by] += 1;
663
+ else if (e.type === 'joint.budget-reset')
664
+ r.jointResets[e.payload.by] += 1;
652
665
  // Окно начинается раньше записи: в нём есть попытки или события до неё.
653
666
  const before = (ms) => ms < recordedFrom;
654
667
  if (gapInWindow.size > 0 ||
@@ -966,7 +979,7 @@ export function valueReport(input, options = {}) {
966
979
  outcome: f.outcome,
967
980
  finishedAt: f.finishedAt ? toIso(at(f.finishedAt)) : null,
968
981
  attempts: f.attempts.length,
969
- counted: f.attempts.filter(counted).length,
982
+ counted: f.attempts.filter(isCounted).length,
970
983
  leadMs: f.outcome === 'accepted' ? leadOf(f).ms : null,
971
984
  knownUsd: cost.usd,
972
985
  unknownCalls: cost.unknown,
@@ -1328,7 +1341,7 @@ function summaryOf(r, failedAttempts) {
1328
1341
  text: fp.bound === 'lower'
1329
1342
  ? `${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
1343
  : `${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}.`,
1344
+ 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
1345
  measure: fp,
1333
1346
  },
1334
1347
  {
@@ -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',
@@ -109,7 +109,7 @@ export function reportBlocks(r) {
109
109
  ? `Accepted tasks that needed no human action: ${formatMeasureRatio(a.withoutAction)}. With a recorded human action (operator retry, cancellation or recovery decision): ${formatMeasureRatio(a.withAction)}.`
110
110
  : `Accepted tasks that needed no human action: not measurable yet (retries, resets and base moves have no recorded actor). Accepted tasks with an operator recovery decision: ${a.withAction.value ?? 0} of ${a.withAction.n}.`,
111
111
  rec
112
- ? `Human actions: operator recovery decisions ${a.actions.operatorDecisions}, operator retries ${ge}${rec.retries.operator} (resets ${ge}${rec.resets.operator}), operator cancellations ${ge}${rec.cancellations.operator}, operator base moves ≥ ${rec.baseMoves.operator}. Automatic: recovery retries ${ge}${rec.retries.recovery}, controller base moves ≥ ${rec.baseMoves.controller}, cancellations by a new graph revision ${ge}${rec.cancellations.graph}. By the host without a named actor: retries ${ge}${rec.retries.host}, cancellations ${ge}${rec.cancellations.host}, base moves ≥ ${rec.baseMoves.host}. Tasks cancelled without an active attempt: ${ge}${rec.cancelledWithoutAttempt}; cancelled attempts ${a.actions.cancelledAttempts}. Without a recorded actor: holds ${a.actions.holds} (held tasks count as unknown). Recorded from ${rec.from}.`
112
+ ? `Human actions: operator recovery decisions ${a.actions.operatorDecisions}, operator retries ${ge}${rec.retries.operator} (resets ${ge}${rec.resets.operator}), operator cancellations ${ge}${rec.cancellations.operator}, operator base moves ≥ ${rec.baseMoves.operator}. Automatic: recovery retries ${ge}${rec.retries.recovery}, controller base moves ≥ ${rec.baseMoves.controller}, cancellations by a new graph revision ${ge}${rec.cancellations.graph}. By the host without a named actor: retries ${ge}${rec.retries.host}, cancellations ${ge}${rec.cancellations.host}, base moves ≥ ${rec.baseMoves.host}. Joint verification budget resets: operator ${rec.jointResets?.operator ?? 0}, host ${rec.jointResets?.host ?? 0}. Tasks cancelled without an active attempt: ${ge}${rec.cancelledWithoutAttempt}; cancelled attempts ${a.actions.cancelledAttempts}. Without a recorded actor: holds ${a.actions.holds} (held tasks count as unknown). Recorded from ${rec.from}.`
113
113
  : `Human actions with a recorded actor: operator recovery decisions ${a.actions.operatorDecisions}. Without a recorded actor (not counted as human): holds ${a.actions.holds}, cancelled attempts ${a.actions.cancelledAttempts}. ${actionsLine([
114
114
  ['retries', a.actions.retries],
115
115
  ['resets', a.actions.resets],
@@ -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.',
@@ -1280,6 +1280,7 @@ export declare class DocumentView {
1280
1280
  tree: string;
1281
1281
  }> | undefined;
1282
1282
  manifestDigest?: string | undefined;
1283
+ interrupted?: true | undefined;
1283
1284
  impact?: {
1284
1285
  changed: string[];
1285
1286
  affected: string[];
@@ -1443,6 +1444,7 @@ export declare class DocumentView {
1443
1444
  tree: string;
1444
1445
  }> | undefined;
1445
1446
  manifestDigest?: string | undefined;
1447
+ interrupted?: true | undefined;
1446
1448
  impact?: {
1447
1449
  changed: string[];
1448
1450
  affected: string[];
@@ -1,4 +1,4 @@
1
- import { type ExecutionStore, type InputRequest } from '../contracts/index.ts';
1
+ import { type ExecutionStore, type InputRequest, type JointVerificationState } from '../contracts/index.ts';
2
2
  /**
3
3
  * Запрос исполнителя (`input-requests`) для проверок адаптера: вопрос с
4
4
  * вариантами, основание исходной попытки, без ответов (`pending`).
@@ -12,4 +12,10 @@ export declare function answeredInputRequest(request: InputRequest, text?: strin
12
12
  * повторный вызов с тем же каталогом — то же хранилище другим экземпляром.
13
13
  * Регистрация тестов — через переданную `test` (node:test).
14
14
  */
15
- export declare function executionStoreContract(name: string, test: (title: string, fn: () => void | Promise<void>) => unknown, open: (dir: string) => ExecutionStore, tempDir: () => string): void;
15
+ export declare function executionStoreContract(name: string, test: (title: string, fn: () => void | Promise<void>) => unknown, open: (dir: string) => ExecutionStore, tempDir: () => string, options?: {
16
+ /**
17
+ * Как хост заводит новую совместную проверку (у DevContour — операцией
18
+ * ChangeSet). По умолчанию — `putVerification` в транзакции начала.
19
+ */
20
+ startVerification?: (store: ExecutionStore, verification: JointVerificationState) => void;
21
+ }): void;