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.
@@ -7,7 +7,7 @@ import { dirname, join, relative, resolve, sep } from 'node:path';
7
7
  import { createInterface } from 'node:readline';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { z } from 'zod';
10
- import { idSchema, relativePathSchema, sha256, TaskFailure, } from "../contracts/index.js";
10
+ import { idSchema, relativePathSchema, sha256, TaskFailure, gateTimeoutMs, } from "../contracts/index.js";
11
11
  import { dependencyNetworkFailure, dependencyNetworkMessage, } from "../environment/dependency-network.js";
12
12
  import { osToolEnv } from "../environment/os-tools.js";
13
13
  import { redactor } from "../environment/redaction.js";
@@ -76,7 +76,11 @@ export const probeSpec = z.object({
76
76
  /** Фаза и SHA ревью: записываются в каждый запуск gate. */
77
77
  phase: z.string().optional(),
78
78
  sha: z.string().optional(),
79
- /** SHA базы попытки: только с ним gate установки может стать `dependency-network`. */
79
+ /**
80
+ * SHA базы ревью: у кандидата — база попытки, у интеграции — target, на
81
+ * который сделано слияние (первый родитель integration SHA). Только с ним
82
+ * gate установки может стать `dependency-network`.
83
+ */
80
84
  trustedBase: z.string().optional(),
81
85
  /**
82
86
  * Вызов reviewer, которому принадлежит журнал: попытка harness, фаза, SHA
@@ -789,13 +793,13 @@ export function serveReviewProbes(probes, input = process.stdin, output = proces
789
793
  return { lines, pending };
790
794
  }
791
795
  /** Объявленные gates репозитория в виде спецификации probe. */
792
- export function probeGates(gates) {
796
+ export function probeGates(gates, policy = {}) {
793
797
  return gates.map((g) => ({
794
798
  id: g.id,
795
799
  kind: g.kind,
796
800
  command: g.command,
797
801
  ...(g.cwd ? { cwd: g.cwd } : {}),
798
- timeoutMs: g.timeoutMs,
802
+ timeoutMs: gateTimeoutMs(g, policy),
799
803
  ...(g.report ? { report: { type: g.report.type, path: g.report.path } } : {}),
800
804
  ...(g.property ? { property: true } : {}),
801
805
  }));
@@ -303,9 +303,10 @@ export const evidenceRecordSchema = z.strictObject({
303
303
  /** Проверка потребителя: компонент, в дереве которого она выполнена. */
304
304
  consumer: idSchema.optional(),
305
305
  /**
306
- * Повтор провала gate интеграции на том же SHA: `of` — ID повторённой
307
- * записи; `flaky` — повтор прошёл (первый провал вызван средой), `confirmed`
308
- * — провал подтвердился.
306
+ * Повтор провала gate на том же SHA — интеграции (провал при зелёном
307
+ * кандидате) или кандидата (таймаут под высокой нагрузкой хоста), не больше
308
+ * одного на фазу попытки: `of` — ID повторённой записи; `flaky` — повтор
309
+ * прошёл (первый провал вызван средой), `confirmed` — провал подтвердился.
309
310
  */
310
311
  recheck: z
311
312
  .strictObject({
@@ -995,6 +995,7 @@ export declare const executionPolicySchema: z.ZodObject<{
995
995
  reserveMs: z.ZodDefault<z.ZodNumber>;
996
996
  }, z.core.$strict>>;
997
997
  reviewProtocolRetries: z.ZodOptional<z.ZodNumber>;
998
+ gateTimeoutFloorMs: z.ZodOptional<z.ZodNumber>;
998
999
  stallSweep: z.ZodOptional<z.ZodObject<{
999
1000
  intervalMs: z.ZodDefault<z.ZodNumber>;
1000
1001
  quietMs: z.ZodDefault<z.ZodNumber>;
@@ -1145,4 +1146,22 @@ export declare const mcpEnvironment: (profile?: {
1145
1146
  values: {};
1146
1147
  secrets: {};
1147
1148
  };
1149
+ /**
1150
+ * Действующий предел времени исполнения gate: объявленный `timeoutMs`, не
1151
+ * меньше `gateTimeoutFloorMs` политики, если он задан.
1152
+ */
1153
+ export declare function gateTimeoutMs(gate: {
1154
+ timeoutMs: number;
1155
+ }, policy: {
1156
+ gateTimeoutFloorMs?: number | undefined;
1157
+ }): number;
1158
+ /**
1159
+ * Предел времени gate для текста отказа: действующий в секундах и, если его
1160
+ * поднял `gateTimeoutFloorMs`, объявленный.
1161
+ */
1162
+ export declare function gateTimeoutText(gate: {
1163
+ timeoutMs: number;
1164
+ }, policy: {
1165
+ gateTimeoutFloorMs?: number | undefined;
1166
+ }): string;
1148
1167
  export {};
@@ -282,6 +282,14 @@ export const executionPolicySchema = z.strictObject({
282
282
  * digest и pins прежней политики не меняются. См. docs/review-protocol.md.
283
283
  */
284
284
  reviewProtocolRetries: z.number().int().min(0).max(2).optional(),
285
+ /**
286
+ * Нижняя граница предела времени каждого исполнения gate (мс, 1000–600000):
287
+ * действующий предел — max(gate.timeoutMs, gateTimeoutFloorMs). Объявленный
288
+ * предел gate не меняется; поле защищает короткие пределы от нагрузки хоста.
289
+ * Нет поля — действует объявленный предел; умолчание не подставляется, и
290
+ * digest прежних политик не меняется.
291
+ */
292
+ gateTimeoutFloorMs: z.number().int().min(1000).max(600_000).optional(),
285
293
  /**
286
294
  * Обход зависших попыток controller: каждые `intervalMs` он оценивает
287
295
  * движение исполняющегося (вывод, команды, стадии, процессор дерева):
@@ -447,6 +455,10 @@ export function policyIssues(policy) {
447
455
  const issues = [];
448
456
  const add = (code, path, message) => issues.push({ code, path, message });
449
457
  const repos = new Map();
458
+ // Нижняя граница предела gate не длиннее предела вызова: иначе одна
459
+ // проверка законно переживала бы весь срок вызова, который её запустил.
460
+ if (policy.gateTimeoutFloorMs !== undefined && policy.gateTimeoutFloorMs > policy.runTimeoutMs)
461
+ add('INVALID_INPUT', ['gateTimeoutFloorMs'], `gateTimeoutFloorMs (${policy.gateTimeoutFloorMs} мс) больше runTimeoutMs (${policy.runTimeoutMs} мс)`);
450
462
  // Тариф однозначен: у модели не бывает двух тарифов на один момент.
451
463
  const tariffs = new Set();
452
464
  policy.prices.forEach((p, i) => {
@@ -647,3 +659,21 @@ export const mcpEnvironment = (profile) => ({
647
659
  values: {},
648
660
  secrets: {},
649
661
  });
662
+ /**
663
+ * Действующий предел времени исполнения gate: объявленный `timeoutMs`, не
664
+ * меньше `gateTimeoutFloorMs` политики, если он задан.
665
+ */
666
+ export function gateTimeoutMs(gate, policy) {
667
+ return Math.max(gate.timeoutMs, policy.gateTimeoutFloorMs ?? 0);
668
+ }
669
+ /**
670
+ * Предел времени gate для текста отказа: действующий в секундах и, если его
671
+ * поднял `gateTimeoutFloorMs`, объявленный.
672
+ */
673
+ export function gateTimeoutText(gate, policy) {
674
+ const seconds = (ms) => `${Math.round(ms / 100) / 10} с`;
675
+ const effective = gateTimeoutMs(gate, policy);
676
+ return effective > gate.timeoutMs
677
+ ? `предел ${seconds(effective)} (объявлен ${seconds(gate.timeoutMs)}, поднят gateTimeoutFloorMs)`
678
+ : `предел ${seconds(effective)}`;
679
+ }
@@ -613,6 +613,7 @@ export declare const publishedSchemas: {
613
613
  reserveMs: z.ZodDefault<z.ZodNumber>;
614
614
  }, z.core.$strict>>;
615
615
  reviewProtocolRetries: z.ZodOptional<z.ZodNumber>;
616
+ gateTimeoutFloorMs: z.ZodOptional<z.ZodNumber>;
616
617
  stallSweep: z.ZodOptional<z.ZodObject<{
617
618
  intervalMs: z.ZodDefault<z.ZodNumber>;
618
619
  quietMs: z.ZodDefault<z.ZodNumber>;
@@ -32,6 +32,19 @@ const contentDigest = (order) => digestOf({ ...order, source: { connector: order
32
32
  * отпечатков и общим бюджетом восстановлений.
33
33
  */
34
34
  const uncounted = (kind, blocked) => blocked || kind === 'environment' || kind === 'provider-auth';
35
+ /**
36
+ * Остановка вопросом (`needs-input`) — не неудача работы: попытка
37
+ * возвращается в предел, а предел незасчитанных отказов не тратится; ответ
38
+ * на последней попытке продолжает работу без сброса. Ответ может дать
39
+ * модель (режим согласования `agent`), поэтому возврат ограничен: поручение
40
+ * получает не больше `maxAttempts` таких остановок за всю жизнь — сброс их
41
+ * не возвращает. Счёт — по записям попыток поручения (`earlier` — прежние
42
+ * остановки вопросом, кроме прерванных остановкой controller); остановка
43
+ * сверх предела засчитывается как обычная попытка.
44
+ */
45
+ const returnsAttempt = (kind, earlier, maxAttempts) => kind === 'needs-input' && earlier < maxAttempts;
46
+ /** Прежние остановки вопросом поручения, кроме попытки `except`. */
47
+ const inputStopsOf = (attempts, except) => attempts.filter((x) => x.id !== except && x.failureKind === 'needs-input' && x.interrupted !== 'shutdown').length;
35
48
  /**
36
49
  * Причина отказа для `attempt.diagnosed`: отказ не окружения — `none`;
37
50
  * окружения — названная в точке обнаружения или по классу отказа.
@@ -1424,7 +1437,7 @@ export class Engine {
1424
1437
  if ((evidence.kind === 'review') !== (evidence.gate === 'independent-review'))
1425
1438
  throw new HarnessError('INVALID_INPUT', `Evidence вида ${evidence.kind} не может относиться к gate ${evidence.gate}`);
1426
1439
  // Повтор ссылается на провал того же gate этой попытки на том же SHA, и
1427
- // попытка повторяет не больше одного провала.
1440
+ // попытка повторяет не больше одного провала на фазу.
1428
1441
  if (evidence.recheck) {
1429
1442
  const of = evidence.recheck.of;
1430
1443
  const first = a.evidence.find((e) => e.id === of);
@@ -1437,7 +1450,7 @@ export class Engine {
1437
1450
  first.sha !== evidence.sha ||
1438
1451
  first.consumer !== evidence.consumer ||
1439
1452
  namesFailingCases(first) ||
1440
- a.evidence.some((e) => e.recheck))
1453
+ a.evidence.some((e) => e.recheck && e.phase === evidence.phase))
1441
1454
  throw new HarnessError('INVALID_INPUT', 'Повтор gate не относится к провалу этой попытки');
1442
1455
  if (evidence.recheck.outcome !== (evidence.passed ? 'flaky' : 'confirmed'))
1443
1456
  throw new HarnessError('INVALID_INPUT', 'Исход повтора gate не согласован с записью');
@@ -1685,6 +1698,7 @@ export class Engine {
1685
1698
  : {}),
1686
1699
  };
1687
1700
  tx.putAttempt(failed);
1701
+ const givesBack = returnsAttempt(kind, inputStopsOf(tx.attempts(w.id), id), this.policy.maxAttempts);
1688
1702
  const next = structuredClone(w);
1689
1703
  const before = next.recovery?.status;
1690
1704
  const episode = afterFailure(next, tx.attempts(w.id).map((x) => (x.id === id ? failed : x)), failed, iso(this.now()), this.episodeOf(next, tx));
@@ -1707,8 +1721,12 @@ export class Engine {
1707
1721
  failureFingerprint: fingerprint,
1708
1722
  }),
1709
1723
  activeRunId: undefined,
1710
- attempt: (interrupted || uncounted(kind, blocked)) && w.attempt > 0 ? w.attempt - 1 : w.attempt,
1711
- // Отказ до работы (blocked) и штатная остановка предел не тратят.
1724
+ attempt: (interrupted || uncounted(kind, blocked) || givesBack) && w.attempt > 0
1725
+ ? w.attempt - 1
1726
+ : w.attempt,
1727
+ // Отказ до работы (blocked), штатная остановка и вопрос предел
1728
+ // незасчитанных отказов не тратят; вопрос сверх своего предела
1729
+ // засчитан как попытка.
1712
1730
  ...(uncounted(kind, blocked) && !blocked && !interrupted
1713
1731
  ? { neutralFailures: (w.neutralFailures ?? 0) + 1 }
1714
1732
  : {}),
@@ -1730,7 +1748,7 @@ export class Engine {
1730
1748
  payload: {
1731
1749
  failureKind: kind,
1732
1750
  cause: interrupted ? 'shutdown' : causeOf(kind, options.cause, blocked),
1733
- counted: !interrupted && !uncounted(kind, blocked),
1751
+ counted: !interrupted && !uncounted(kind, blocked) && !givesBack,
1734
1752
  },
1735
1753
  });
1736
1754
  if (options.input && !interrupted)
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
3
3
  import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
4
- import { digestOf, stallSweepOf, } from "../contracts/index.js";
4
+ import { digestOf, stallSweepOf, gateTimeoutMs, } from "../contracts/index.js";
5
5
  import { git } from "../environment/process.js";
6
6
  import { livenessPayload, superviseStalls } from "./stall-sweep.js";
7
7
  import { chooseCheckoutRoot } from "../environment/checkout-root.js";
@@ -213,7 +213,7 @@ export class JointRunner {
213
213
  argv: gate.command,
214
214
  cwd: gateCwd,
215
215
  signal,
216
- timeoutMs: gate.timeoutMs,
216
+ timeoutMs: gateTimeoutMs(gate, this.policy),
217
217
  write: [cwd],
218
218
  readable: [
219
219
  ...Object.values(paths),
@@ -281,6 +281,17 @@ export declare class Runner {
281
281
  }>;
282
282
  private sweepWorktrees;
283
283
  private gate;
284
+ /**
285
+ * Gate кандидата с одним повтором на попытку — только когда gate исчерпал
286
+ * свой предел времени под высокой нагрузкой хоста (`GateTimeout.overloaded`).
287
+ * Такой таймаут меряет очередь к процессору, а не код: без повтора он
288
+ * засчитывался провалом gate и стоил новой реализации. Повтор — тот же gate
289
+ * на том же SHA; обе записи остаются, у повтора — `recheck` со ссылкой на
290
+ * первую и исходом. Повторный таймаут — провал, засчитанный как прежде.
291
+ * Прочие провалы, контрпример свойства и таймаут на свободной машине не
292
+ * повторяются.
293
+ */
294
+ private candidateGate;
284
295
  /**
285
296
  * Gate интеграции с одним повтором на кандидата. Провал собственного gate на
286
297
  * integration, когда тот же gate прошёл на кандидате, часто вызван средой
@@ -8,7 +8,7 @@ import { git, hostGitArgs } from "../environment/process.js";
8
8
  import { worktreeKey } from "../environment/git-trust.js";
9
9
  import { attemptRefusal, cleanupUnfinished, inspectTree, isWithin, lockCleanup, readRemoval, recordFile, recordRemoval, registered, removeTree, savePatch, sizeKb, treeHead, treeState, treeUnchanged, trusted, } from "./worktree-cleanup.js";
10
10
  import { protectedChanges, protectedSnapshot, SandboxPolicyError, } from "../environment/isolation.js";
11
- import { executionEnvironment, runSteps, withEnvironment } from "../environment/lifecycle.js";
11
+ import { executionEnvironment, preparation, preparesTree, runSteps, withEnvironment, } from "../environment/lifecycle.js";
12
12
  import { dependencyStoreRoot, materializeStore, } from "../verification/dependency-store.js";
13
13
  import { checkoutPath, chooseCheckoutRoot, realish, } from "../environment/checkout-root.js";
14
14
  import { credentialPaths } from "../environment/isolation.js";
@@ -17,7 +17,7 @@ import { alreadySatisfiedReviewOutputSchema, implementationOutputSchema, reviewO
17
17
  import { reviewInspection } from "../agents/inspect.js";
18
18
  import { reviewerRunsChecks } from "../agents/cli-adapter.js";
19
19
  import { gateProbePrompt, observeReproductions, assertProbeSpec, probeCommand, probeGates, probeLimits, probeRecord, readProbeJournal, recoverProbeLog, probeTool, } from "../agents/review-probe.js";
20
- import { prepareWriterDependencies, draftTouchesInstall, runGate, writerDependenciesNote, writerDependencyGates, } from "../verification/gates.js";
20
+ import { GateTimeout, prepareWriterDependencies, draftTouchesInstall, runGate, writerDependenciesNote, writerDependencyGates, } from "../verification/gates.js";
21
21
  import { ActivityScope, activityScope } from "../environment/activity.js";
22
22
  import { StallSweep, StalledError, stallMessage, livenessPayload, } from "./stall-sweep.js";
23
23
  import { orderedScope } from "../verification/gate-scope.js";
@@ -1012,9 +1012,11 @@ export class Runner {
1012
1012
  attempt = { ...attempt, baseSha: base, worktree: cwd };
1013
1013
  const gates = ordered(repo.gates, attempt.requiredGates ?? repo.gates.map((g) => g.id));
1014
1014
  const execution = this.environment(attempt, 'candidate', cwd);
1015
+ const prepared = preparation.guard(this.policy.isolation.mode === 'os', cwd, preparesTree(repo.lifecycle ?? this.policy.lifecycle, repo.prepare, repo.dependencyStore));
1015
1016
  const candidate = await withEnvironment(repo.lifecycle ?? this.policy.lifecycle, cwd, join(artifacts, 'candidate', 'environment'), execution, signal, async () => {
1016
1017
  await this.dependencyStore(attempt, repo, cwd, execution, signal, join(artifacts, 'candidate'));
1017
1018
  await runSteps(repo.prepare, cwd, join(artifacts, 'candidate', 'prepare'), execution, signal, base);
1019
+ prepared(execution);
1018
1020
  // Черновик прежней попытки — до установки: манифесты, которые он
1019
1021
  // меняет, исполнитель увидит уже установленными.
1020
1022
  if (!attempt.reusedFrom)
@@ -1124,7 +1126,7 @@ export class Runner {
1124
1126
  let planted = [];
1125
1127
  try {
1126
1128
  if (guarded)
1127
- planted = protectedChanges(guarded, cwd);
1129
+ planted = protectedChanges(guarded, cwd, execution.prepared);
1128
1130
  }
1129
1131
  catch (error) {
1130
1132
  if (error instanceof SandboxPolicyError)
@@ -1132,7 +1134,7 @@ export class Runner {
1132
1134
  throw error;
1133
1135
  }
1134
1136
  if (planted.length)
1135
- throw new TaskFailure('scope-violation', 'Исполнитель создал или изменил защищённые пути (конфигурация IDE, shell, git или Claude): ' +
1137
+ throw new TaskFailure('scope-violation', 'Исполнитель создал, изменил или удалил защищённые пути (конфигурация IDE, shell, git или Claude): ' +
1136
1138
  planted
1137
1139
  .slice(0, 5)
1138
1140
  .map((p) => relative(cwd, p))
@@ -1190,8 +1192,9 @@ export class Runner {
1190
1192
  });
1191
1193
  rearm();
1192
1194
  this.engine.phase(attempt.id, attempt.token, 'verifying', { candidateSha: sha });
1195
+ const recheck = { recheck: true };
1193
1196
  for (const gate of gates)
1194
- await this.gate(attempt, cwd, sha, 'candidate', gate, artifacts, signal, execution).catch((error) => {
1197
+ await this.candidateGate(attempt, cwd, sha, gate, artifacts, signal, execution, recheck).catch((error) => {
1195
1198
  // Без изменений непрошедший gate значит одно: работа не
1196
1199
  // сделана, — это пустой результат, а не дефект кода.
1197
1200
  if (sha !== base || !(error instanceof TaskFailure))
@@ -1636,6 +1639,44 @@ export class Runner {
1636
1639
  : `${phase}-test:${gate.id}`;
1637
1640
  await this.timed(attempt, stage, () => this.runOneGate(attempt, cwd, sha, phase, gate, artifacts, signal, execution, consumer, recheck));
1638
1641
  }
1642
+ /**
1643
+ * Gate кандидата с одним повтором на попытку — только когда gate исчерпал
1644
+ * свой предел времени под высокой нагрузкой хоста (`GateTimeout.overloaded`).
1645
+ * Такой таймаут меряет очередь к процессору, а не код: без повтора он
1646
+ * засчитывался провалом gate и стоил новой реализации. Повтор — тот же gate
1647
+ * на том же SHA; обе записи остаются, у повтора — `recheck` со ссылкой на
1648
+ * первую и исходом. Повторный таймаут — провал, засчитанный как прежде.
1649
+ * Прочие провалы, контрпример свойства и таймаут на свободной машине не
1650
+ * повторяются.
1651
+ */
1652
+ async candidateGate(attempt, cwd, sha, gate, artifacts, signal, execution, budget) {
1653
+ try {
1654
+ await this.gate(attempt, cwd, sha, 'candidate', gate, artifacts, signal, execution);
1655
+ }
1656
+ catch (error) {
1657
+ if (!budget.recheck || signal.aborted || !(error instanceof GateTimeout))
1658
+ throw error;
1659
+ if (!error.overloaded)
1660
+ throw error;
1661
+ const { failed, spent } = this.engine.read((v) => {
1662
+ const evidence = v.attempt(attempt.id)?.evidence ?? [];
1663
+ return {
1664
+ failed: evidence.findLast((e) => e.kind === 'test' &&
1665
+ e.gate === gate.id &&
1666
+ e.phase === 'candidate' &&
1667
+ e.sha === sha &&
1668
+ !e.consumer),
1669
+ // Бюджет — по состоянию, как правило движка (один повтор на фазу
1670
+ // попытки), а не только по счётчику этого прохода проверок.
1671
+ spent: evidence.some((e) => e.recheck && e.phase === 'candidate'),
1672
+ };
1673
+ });
1674
+ if (!failed || failed.passed || namesFailingCases(failed) || spent)
1675
+ throw error;
1676
+ budget.recheck = false;
1677
+ await this.gate(attempt, cwd, sha, 'candidate', gate, artifacts, signal, execution, undefined, failed.id);
1678
+ }
1679
+ }
1639
1680
  /**
1640
1681
  * Gate интеграции с одним повтором на кандидата. Провал собственного gate на
1641
1682
  * integration, когда тот же gate прошёл на кандидате, часто вызван средой
@@ -1664,11 +1705,13 @@ export class Runner {
1664
1705
  return {
1665
1706
  failed: evidence.findLast((e) => own(e, 'integration', sha)),
1666
1707
  candidatePassed: evidence.findLast((e) => own(e, 'candidate', attempt.candidateSha))?.passed === true,
1667
- // Один повтор на кандидата: переиспользованный следующей попыткой
1668
- // кандидат второго не получает.
1708
+ // Один повтор интеграции на кандидата: переиспользованный следующей
1709
+ // попыткой кандидат второго не получает. Повтор gate кандидата
1710
+ // (таймаут под нагрузкой) — своей фазы и этот бюджет не тратит.
1669
1711
  spent: v
1670
1712
  .attempts(attempt.workId)
1671
- .some((x) => x.candidateSha === attempt.candidateSha && x.evidence.some((e) => e.recheck)),
1713
+ .some((x) => x.candidateSha === attempt.candidateSha &&
1714
+ x.evidence.some((e) => e.recheck && e.phase === 'integration')),
1672
1715
  };
1673
1716
  });
1674
1717
  // Контрпример свойства или провал случая корпуса не повторяется: удачный
@@ -1778,9 +1821,11 @@ export class Runner {
1778
1821
  store: this.storeContext(attempt),
1779
1822
  });
1780
1823
  const execution = this.environmentOf(attempt, 'integration', dir, [this.policy.environment, repo.environment], repo.id, dependencies);
1824
+ const prepared = preparation.guard(this.policy.isolation.mode === 'os', dir, preparesTree(repo.lifecycle ?? this.policy.lifecycle, repo.prepare, repo.dependencyStore));
1781
1825
  await withEnvironment(repo.lifecycle ?? this.policy.lifecycle, dir, join(own, 'environment'), execution, signal, async () => {
1782
1826
  await this.dependencyStore(attempt, repo, dir, execution, signal, own);
1783
1827
  await runSteps(repo.prepare, dir, join(own, 'prepare'), execution, signal);
1828
+ prepared(execution);
1784
1829
  await pinned('подготовка');
1785
1830
  for (const gate of ordered(repo.gates, consumer.gates))
1786
1831
  await this.gate(attempt, dir, sha, 'integration', gate, artifacts, signal, execution, {
@@ -1848,7 +1893,14 @@ export class Runner {
1848
1893
  * ограничивает срок. Спецификация лежит в каталоге ревью; значения
1849
1894
  * переменных окружения CLI передаёт серверу по имени, на диск они не пишутся.
1850
1895
  */
1851
- async reviewProbe(attempt, work, cwd, dir, phase, sha, gates,
1896
+ async reviewProbe(attempt, work, cwd, dir, phase, sha,
1897
+ /**
1898
+ * База ревью (та же, что `Base commit` запроса): у кандидата — база
1899
+ * попытки, у интеграции — target, на который сделано слияние (первый
1900
+ * родитель integration SHA). Проверки reviewer сравнивают с ней входы
1901
+ * установки зависимостей (`trustedBase`).
1902
+ */
1903
+ base, gates,
1852
1904
  /** Номер вызова reviewer логического ревью: записывается в каждый запуск probe. */
1853
1905
  call,
1854
1906
  /**
@@ -1887,10 +1939,10 @@ export class Runner {
1887
1939
  settingsDir: join(dir, 'probe-settings'),
1888
1940
  log: join(dir, 'probes.jsonl'),
1889
1941
  // Объявленные gates — по ID: argv, cwd и путь отчёта выбирает controller.
1890
- gates: probeGates(gates),
1942
+ gates: probeGates(gates, this.policy),
1891
1943
  phase,
1892
1944
  sha,
1893
- ...(attempt.baseSha ? { trustedBase: attempt.baseSha } : {}),
1945
+ trustedBase: base,
1894
1946
  scope: { attempt: attempt.id, phase, sha, call },
1895
1947
  artifacts: join(dir, 'probe-runs'),
1896
1948
  };
@@ -2074,7 +2126,7 @@ export class Runner {
2074
2126
  }
2075
2127
  const callDir = call === 1 ? dir : join(dir, `call-${call}`);
2076
2128
  await mkdir(callDir, { recursive: true });
2077
- const probe = await this.reviewProbe(attempt, work, cwd, callDir, phase, sha, gates, call, shared);
2129
+ const probe = await this.reviewProbe(attempt, work, cwd, callDir, phase, sha, base, gates, call, shared);
2078
2130
  const response = await this.call(this.adapter(attempt.reviewer), {
2079
2131
  task: 'review-code',
2080
2132
  attempt,
@@ -2577,19 +2629,36 @@ export class Runner {
2577
2629
  throw new TaskFailure('merge', error instanceof Error ? error.message : String(error));
2578
2630
  }
2579
2631
  const sha = await git(cwd, 'rev-parse', 'HEAD');
2632
+ // Кандидат с изменениями даёт ровно слияние «target + кандидат». Иначе
2633
+ // (кандидат уже достижим из target — «Already up to date» — или merge
2634
+ // сделал fast-forward) проверять и продвигать нечего: проверки и ревью
2635
+ // интеграции видели бы не слияние этого поручения.
2636
+ if (attempt.candidateSha !== attempt.baseSha) {
2637
+ const parents = (await git(cwd, 'rev-list', '--parents', '-n', '1', sha)).split(' ');
2638
+ if (parents.length !== 3 ||
2639
+ parents[0] !== sha ||
2640
+ parents[1] !== base ||
2641
+ parents[2] !== attempt.candidateSha)
2642
+ throw new TaskFailure('merge', `Интеграция не создала слияние кандидата ${attempt.candidateSha} с целевой веткой ${repo.targetRef} (${base}): получен ${sha} с родителями ${parents.slice(1).join(', ') || 'нет'}; кандидат, вероятно, уже входит в целевую ветку`);
2643
+ }
2580
2644
  this.engine.phase(attempt.id, attempt.token, 'integrating', { integrationSha: sha });
2581
2645
  const gates = ordered(repo.gates, attempt.requiredGates ?? repo.gates.map((g) => g.id));
2582
2646
  const execution = this.environment(attempt, 'integration', cwd);
2647
+ const prepared = preparation.guard(this.policy.isolation.mode === 'os', cwd, preparesTree(repo.lifecycle ?? this.policy.lifecycle, repo.prepare, repo.dependencyStore));
2583
2648
  await withEnvironment(repo.lifecycle ?? this.policy.lifecycle, cwd, join(artifacts, 'integration', 'environment'), execution, signal, async () => {
2584
2649
  await this.dependencyStore(attempt, repo, cwd, execution, signal, join(artifacts, 'integration'));
2585
2650
  await runSteps(repo.prepare, cwd, join(artifacts, 'integration', 'prepare'), execution, signal, attempt.baseSha);
2651
+ prepared(execution);
2586
2652
  const budget = { recheck: true };
2587
2653
  for (const gate of gates)
2588
2654
  await this.integrationGate(attempt, cwd, sha, gate, artifacts, signal, execution, budget);
2589
2655
  await this.consumers(attempt, cwd, sha, artifacts, signal);
2590
2656
  this.requirements(attempt, work, repoPath, cwd, sha, 'integration');
2591
2657
  rearm();
2592
- await this.review(attempt, work, cwd, attempt.baseSha, sha, 'integration', artifacts, signal, context);
2658
+ // База ревью интеграции — target, на который сделано слияние (первый
2659
+ // родитель integration SHA), а не база попытки: работа, принятая в
2660
+ // target после начала попытки, в diff этого поручения не входит.
2661
+ await this.review(attempt, work, cwd, base, sha, 'integration', artifacts, signal, context);
2593
2662
  }, (stage, action) => this.timed(attempt, 'integration-environment:' + stage, action));
2594
2663
  if ((await git(cwd, 'rev-parse', 'HEAD')) !== sha ||
2595
2664
  (await git(cwd, 'status', '--porcelain', '--untracked-files=no')))
@@ -163,6 +163,28 @@ export declare class SandboxPolicyError extends Error {
163
163
  name: string;
164
164
  }
165
165
  export declare function protectedWriteDenies(roots: string[]): string[] | undefined;
166
+ /**
167
+ * Шаблон запрета под каталогом `dir` внутри `root`, база которого — `root`.
168
+ *
169
+ * srt закрепляет базу шаблона (статический префикс до первого символа глоба)
170
+ * и всех её предков запретом `file-write-unlink`/`file-write-create`: иначе
171
+ * каталог можно было бы перенести из-под запрета. Шаблон `<dir>/*\/.idea`
172
+ * закреплял так каждый существующий каталог дерева до глубины перечисления:
173
+ * проверка не могла удалить или переименовать даже свой прежний вывод
174
+ * (`.reports/expo-export`, оставленный самопроверкой исполнителя), и
175
+ * `expo export` падал с `EPERM rmdir`.
176
+ *
177
+ * Один символ первого сегмента под `root` записывается классом (`.reports` →
178
+ * `[.]reports`): шаблон совпадает с теми же путями (класс из одного символа —
179
+ * этот символ), а статический префикс обрывается в `root`, и закреплены
180
+ * только `root` и его предки, как у шаблонов `root/**\/<имя>`. Перенос
181
+ * каталога с подложенным внутри `.idea` по-прежнему ловит сверка снимков
182
+ * (`protectedSnapshot`) — как и новый каталог, которого при сборке политики
183
+ * не было. Символ — печатный ASCII: класс Seatbelt сравнивает байты, и
184
+ * многобайтовый символ в классе совпал бы не с тем. Сегмент без такого
185
+ * символа остаётся прежним шаблоном.
186
+ */
187
+ export declare function anchoredAtRoot(root: string, pattern: string): string;
166
188
  /**
167
189
  * Явные запреты для Linux. srt там закрывает только уже существующие пути и
168
190
  * сам пропускает `node_modules`; файл `.git` рабочего дерева добавляется.
@@ -198,6 +220,13 @@ export declare function watchSandboxLog(tag: string): Promise<{
198
220
  * побеждает, закрытое внутри открытого — снова закрыто).
199
221
  */
200
222
  export declare function hiddenReadRule(policy: Isolation, path: string): string | undefined;
223
+ /**
224
+ * Каталоги, которые srt закрепляет от удаления и переноса запретами записи
225
+ * для корней `roots` (`protectedWriteDenies`): база каждого шаблона
226
+ * (статический префикс до первого символа глоба) и предки буквального пути.
227
+ * Возвращаются базы; закреплены и все их предки.
228
+ */
229
+ export declare function pinnedBases(roots: string[]): string[];
201
230
  /**
202
231
  * Отказы песочницы, которые подтвердило ядро и которые правкой кода не снять.
203
232
  *
@@ -234,6 +263,9 @@ export declare function protectedSnapshot(root: string): Map<string, string>;
234
263
  * из снимка, а не пропуск: вызывающий решает, отказ ли это среды (снимок до
235
264
  * работы) или нарушение области (после).
236
265
  *
266
+ * Путь с содержимым, который был до снимка и исчез после, — нарушение
267
+ * (удаление `.idea` через перенос родителя).
268
+ *
237
269
  * Пустые каталоги (только каталоги, рекурсивно, без записи всем)
238
270
  * нарушением не считаются, если до снимка пути не было или он тоже был без
239
271
  * файлов: исполняемой конфигурации в них нет, а CLI исполнителя создаёт
@@ -241,7 +273,15 @@ export declare function protectedSnapshot(root: string): Map<string, string>;
241
273
  * файлом. Путь, где раньше были файлы, по-прежнему нарушение при любом
242
274
  * изменении.
243
275
  */
244
- export declare function protectedChanges(before: Map<string, string>, root: string): string[];
276
+ export declare function protectedChanges(before: Map<string, string>, root: string,
277
+ /**
278
+ * Пути относительно `root`, которыми владеет подготовка фазы (вложенные
279
+ * `.git`, см. `preparationGuard`): не в счёт только их исчезновение
280
+ * (уборка фикстуры переносом родителя). Изменение — в том числе подмена
281
+ * переносом другого `.git` на то же место — нарушение: подменённый
282
+ * `gitdir` подмодуля git хоста прочитал бы при следующей команде.
283
+ */
284
+ owned?: ReadonlySet<string>): string[];
245
285
  /**
246
286
  * Предел пути unix-сокета (`sun_path`, вместе с завершающим NUL): 104 байта
247
287
  * на macOS, 108 на Linux. srt слушает свои сокеты во временном каталоге