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
@@ -12,7 +12,7 @@ import { afterFailure, afterSuccess, blocksClaim, closeIfBasisChanged, } from ".
12
12
  import { REQUIREMENT_GATE } from "../verification/requirements.js";
13
13
  import { blockingRequest, inputManifestOf, requestById, requestsOf, unappliedInputs, } from "./input-requests.js";
14
14
  import { pinnedCorpus, propertyProofProblem } from "../verification/acceptance.js";
15
- import { jointImpact, jointPolicyDigest, jointSpecDigest, publicJoint, sameWorks, jointBudgetAttempts, } from "../verification/joint.js";
15
+ import { jointImpact, jointPolicyDigest, jointSpecDigest, publicJoint, sameWorks, jointBudgetWindow, jointInterrupted, } from "../verification/joint.js";
16
16
  /** Префикс причины неудавшегося продления: первая причина не затирается следствиями. */
17
17
  export const HEARTBEAT_FAILED = 'Продление владения не удалось';
18
18
  const iso = (ms) => new Date(ms).toISOString();
@@ -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)
@@ -3253,18 +3271,11 @@ export class Engine {
3253
3271
  continue;
3254
3272
  if (v.leaseUntil > this.now())
3255
3273
  throw new HarnessError('NOT_READY', 'Совместная проверка уже выполняется');
3256
- const error = 'Истёк срок владения проверкой';
3257
- tx.putVerification({ ...v, status: 'failed', error, finishedAt: iso(this.now()) });
3258
- tx.emit({
3259
- type: 'joint.finished',
3260
- payload: { verificationId: v.id, status: 'failed', error },
3261
- });
3274
+ this.closeExpiredJoint(tx, v);
3262
3275
  }
3263
- const previous = jointBudgetAttempts(tx, input.workIds, this.host.basis.jointBudgetCheckpoints
3264
- ? this.host.basis.jointBudgetCheckpoints([...input.workIds], tx)
3265
- : []);
3266
- if (previous.length >= this.policy.maxAttempts)
3267
- throw new HarnessError('ATTEMPTS_EXHAUSTED', 'Исчерпан предел совместных проверок этого набора');
3276
+ const exhausted = this.jointExhausted(tx, input.workIds);
3277
+ if (exhausted)
3278
+ throw new HarnessError('ATTEMPTS_EXHAUSTED', exhausted);
3268
3279
  const works = input.workIds.map((id) => tx.work(id));
3269
3280
  if (works.some((w) => !w || w.status !== 'done' || !w.resultSha))
3270
3281
  throw new HarnessError('NOT_READY', 'Сначала завершите все поручения набора');
@@ -3396,21 +3407,129 @@ export class Engine {
3396
3407
  return publicJoint(next);
3397
3408
  });
3398
3409
  }
3399
- /** Отказ проверки её владельцем; истёкший срок допустим, чужой токен — нет. */
3400
- jointFail(id, token, error) {
3410
+ /**
3411
+ * Отказ проверки её владельцем; истёкший срок допустим, чужой токен — нет.
3412
+ * `interrupted` — проверку прервали остановка или потеря владения; движок
3413
+ * отмечает её прерванной только без evidence: результат gate тратит предел.
3414
+ */
3415
+ jointFail(id, token, error, options = {}) {
3401
3416
  return this.tx('workspace.failed', (tx) => {
3402
3417
  const v = tx.verification(id);
3403
3418
  if (!v || v.status !== 'active' || v.token !== token || v.engineVersion !== this.version)
3404
3419
  return false;
3405
3420
  const message = error.slice(0, 4000) || 'Совместная проверка не прошла';
3406
- tx.putVerification({ ...v, status: 'failed', error: message, finishedAt: iso(this.now()) });
3421
+ const interrupted = options.interrupted && v.evidence.length === 0 ? { interrupted: true } : {};
3422
+ tx.putVerification({
3423
+ ...v,
3424
+ status: 'failed',
3425
+ error: message,
3426
+ finishedAt: iso(this.now()),
3427
+ ...interrupted,
3428
+ });
3407
3429
  tx.emit({
3408
3430
  type: 'joint.finished',
3409
- payload: { verificationId: id, status: 'failed', error: message },
3431
+ payload: { verificationId: id, status: 'failed', error: message, ...interrupted },
3410
3432
  });
3411
3433
  return true;
3412
3434
  });
3413
3435
  }
3436
+ /**
3437
+ * Закрыть истёкшую активную проверку отказом. Владение потеряно: без
3438
+ * evidence проверка прервана до результата gates, с evidence — обычный отказ.
3439
+ */
3440
+ closeExpiredJoint(tx, v) {
3441
+ const error = 'Истёк срок владения проверкой';
3442
+ const interrupted = v.evidence.length === 0 ? { interrupted: true } : {};
3443
+ tx.putVerification({
3444
+ ...v,
3445
+ status: 'failed',
3446
+ error,
3447
+ finishedAt: iso(this.now()),
3448
+ ...interrupted,
3449
+ });
3450
+ tx.emit({
3451
+ type: 'joint.finished',
3452
+ payload: { verificationId: v.id, status: 'failed', error, ...interrupted },
3453
+ });
3454
+ }
3455
+ /**
3456
+ * Почему набор не может начать совместную проверку по бюджету, или
3457
+ * `undefined`. Предел тратят проверки с результатом gates и отказы до них;
3458
+ * прерванные до результата gates (`interrupted`) — только свой предел.
3459
+ */
3460
+ jointExhausted(tx, workIds) {
3461
+ const window = jointBudgetWindow(tx, workIds, this.host.basis.jointBudgetCheckpoints
3462
+ ? this.host.basis.jointBudgetCheckpoints([...workIds], tx)
3463
+ : []);
3464
+ const interrupted = window.filter(jointInterrupted).length;
3465
+ const counted = window.length - interrupted;
3466
+ if (counted >= this.policy.maxAttempts)
3467
+ return `Исчерпан предел совместных проверок этого набора: ${counted} из ${this.policy.maxAttempts}. Не считаются только проверки, прерванные остановкой или потерей владения до результата gates. Предел снимает принятие хостом успешной проверки набора; явный сброс (jointBudgetReset) с причиной снимает только проверки без результата gates`;
3468
+ if (interrupted >= MAX_NEUTRAL_FAILURES)
3469
+ return `Совместные проверки этого набора прерваны до результата gates ${interrupted} раз (предел ${MAX_NEUTRAL_FAILURES}): устраните причину остановок или потери владения и сбросьте бюджет явно (jointBudgetReset) с причиной`;
3470
+ return undefined;
3471
+ }
3472
+ /**
3473
+ * Явный сброс бюджета совместных проверок набора оператором или хостом:
3474
+ * только при исчерпанном пределе и без живой проверки этого набора, с
3475
+ * причиной. Сброс снимает только проверки набора без результата gates
3476
+ * (прерванные и отказы до gates, в том числе записанные прежними версиями);
3477
+ * проверки с evidence тратят предел и после сброса, поэтому предел,
3478
+ * исчерпанный ими одними, сброс не снимает. Истёкшая незакрытая проверка
3479
+ * набора закрывается здесь же (как в `jointStart`). Запись — в
3480
+ * `joint-budget-resets`, событие — `joint.budget-reset`.
3481
+ */
3482
+ jointBudgetReset(workIds, options) {
3483
+ const reason = options.reason?.trim() ?? '';
3484
+ if (!reason)
3485
+ throw new HarnessError('INVALID_INPUT', 'Сброс бюджета совместных проверок требует причины');
3486
+ if (!workIds.length || new Set(workIds).size !== workIds.length)
3487
+ throw new HarnessError('INVALID_INPUT', 'Нужен непустой набор разных поручений');
3488
+ return this.tx('workspace.budget-reset', (tx) => {
3489
+ for (const v of tx.verifications()) {
3490
+ if (v.status !== 'active' || !sameWorks(v.workIds, workIds))
3491
+ continue;
3492
+ if (v.leaseUntil > this.now())
3493
+ throw new HarnessError('NOT_READY', 'Совместная проверка этого набора ещё выполняется');
3494
+ this.closeExpiredJoint(tx, v);
3495
+ }
3496
+ if (!this.jointExhausted(tx, workIds))
3497
+ throw new HarnessError('NOT_READY', 'Предел совместных проверок этого набора не исчерпан; сброс не нужен');
3498
+ const window = jointBudgetWindow(tx, workIds, this.host.basis.jointBudgetCheckpoints
3499
+ ? this.host.basis.jointBudgetCheckpoints([...workIds], tx)
3500
+ : []);
3501
+ const gated = window.filter((v) => v.evidence.length > 0).length;
3502
+ if (gated >= this.policy.maxAttempts)
3503
+ throw new HarnessError('ATTEMPTS_EXHAUSTED', `Предел совместных проверок этого набора исчерпан проверками с результатом gates: ${gated} из ${this.policy.maxAttempts}. Сброс снимает только проверки без результата gates; дальше — принятие хостом успешной проверки или новый набор`);
3504
+ const settled = window.filter((v) => v.status === 'failed' && v.evidence.length === 0);
3505
+ // Успешная проверка без принятия (и без evidence) сбросом не снимается:
3506
+ // сброс, после которого набор всё равно исчерпан, не записывается. Пустой
3507
+ // снимок сюда же: предел исчерпан, значит, остаток — весь предел.
3508
+ const remaining = window.length - settled.length;
3509
+ if (remaining >= this.policy.maxAttempts)
3510
+ throw new HarnessError('ATTEMPTS_EXHAUSTED', `Сброс не освобождает предел совместных проверок этого набора: снимаются только отказы без результата gates (${settled.length}), а остальные проверки (${remaining}, в том числе успешные без принятия) тратят ${remaining} из ${this.policy.maxAttempts}; дальше — принятие хостом успешной проверки или новый набор`);
3511
+ const record = {
3512
+ id: this.id(),
3513
+ at: iso(this.now()),
3514
+ workIds: [...workIds].sort(),
3515
+ reason: reason.slice(0, 2000),
3516
+ actor: options.actor ?? 'host',
3517
+ settledVerificationIds: settled.map((v) => v.id),
3518
+ };
3519
+ tx.putLocal('joint-budget-resets', WORKSPACE_OWNER, record.id, record);
3520
+ tx.emit({
3521
+ type: 'joint.budget-reset',
3522
+ payload: {
3523
+ resetId: record.id,
3524
+ workIds: record.workIds,
3525
+ by: record.actor,
3526
+ settled: record.settledVerificationIds.length,
3527
+ reasonLength: record.reason.length,
3528
+ },
3529
+ });
3530
+ return record;
3531
+ });
3532
+ }
3414
3533
  /**
3415
3534
  * Актуальный результат совместной проверки набора: последняя проверка этого
3416
3535
  * набора, успешная, с целым manifest, под текущей политикой, на неизменном
@@ -130,6 +130,7 @@ export declare class JointRunner {
130
130
  tree: string;
131
131
  }> | undefined;
132
132
  manifestDigest?: string | undefined;
133
+ interrupted?: true | undefined;
133
134
  impact?: {
134
135
  changed: string[];
135
136
  affected: string[];
@@ -288,6 +289,7 @@ export declare class JointRunner {
288
289
  tree: string;
289
290
  }> | undefined;
290
291
  manifestDigest?: string | undefined;
292
+ interrupted?: true | undefined;
291
293
  impact?: {
292
294
  changed: string[];
293
295
  affected: string[];
@@ -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, HarnessError, 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";
@@ -62,11 +62,15 @@ export class JointRunner {
62
62
  const signal = outer ? AbortSignal.any([outer, controller.signal]) : controller.signal;
63
63
  const timer = setTimeout(() => controller.abort(), this.policy.runTimeoutMs);
64
64
  const deadline = Date.now() + this.policy.runTimeoutMs;
65
+ // Владение потеряно: продление отказало устаревшим владением.
66
+ let leaseLost = false;
65
67
  const heartbeat = setInterval(() => {
66
68
  try {
67
69
  this.engine.jointHeartbeat(v.id, v.token);
68
70
  }
69
- catch {
71
+ catch (error) {
72
+ if (error instanceof HarnessError && error.code === 'LEASE_STALE')
73
+ leaseLost = true;
70
74
  controller.abort();
71
75
  }
72
76
  }, Math.max(1000, this.policy.leaseMs / 3));
@@ -213,7 +217,7 @@ export class JointRunner {
213
217
  argv: gate.command,
214
218
  cwd: gateCwd,
215
219
  signal,
216
- timeoutMs: gate.timeoutMs,
220
+ timeoutMs: gateTimeoutMs(gate, this.policy),
217
221
  write: [cwd],
218
222
  readable: [
219
223
  ...Object.values(paths),
@@ -313,7 +317,13 @@ export class JointRunner {
313
317
  ? outer.reason.message
314
318
  : undefined;
315
319
  const message = redact(stalled ?? (error instanceof Error ? error.message : String(error)));
316
- this.engine.jointFail(v.id, v.token, message);
320
+ // Прервана, а не провалена: остановка хоста (внешний сигнал, не обход
321
+ // зависших) или потеря владения. Без evidence движок не тратит на неё
322
+ // предел набора; результат gate (evidence) тратит всегда.
323
+ const interrupted = (outer?.aborted && !stalled) ||
324
+ leaseLost ||
325
+ (error instanceof HarnessError && error.code === 'LEASE_STALE');
326
+ this.engine.jointFail(v.id, v.token, message, interrupted ? { interrupted: true } : {});
317
327
  const failed = this.engine.read((view) => view.verification(v.id));
318
328
  if (failed?.status === 'failed')
319
329
  return publicJoint(failed);
@@ -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
+ * (уборка фикстуры переносом родителя, см. `removedInPlace`). Изменение — в том числе подмена
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 слушает свои сокеты во временном каталоге