devcontour-harness 0.1.0-alpha.42 → 0.1.0-alpha.45

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 (65) hide show
  1. package/README.md +25 -2
  2. package/docs/architecture.md +38 -3
  3. package/docs/contracts.md +117 -3
  4. package/docs/release-notes/0.1.0-alpha.43.md +40 -0
  5. package/docs/release-notes/0.1.0-alpha.44.md +44 -0
  6. package/docs/release-notes/0.1.0-alpha.45.md +77 -0
  7. package/docs/upgrade.md +107 -17
  8. package/lib/contracts/cli.d.ts +115 -4
  9. package/lib/contracts/cli.js +6 -1
  10. package/lib/contracts/events.d.ts +65 -5
  11. package/lib/contracts/events.js +18 -1
  12. package/lib/contracts/execution.d.ts +76 -0
  13. package/lib/contracts/execution.js +35 -2
  14. package/lib/contracts/policy.d.ts +39 -0
  15. package/lib/contracts/policy.js +64 -0
  16. package/lib/contracts/profiles.d.ts +6 -0
  17. package/lib/contracts/published.d.ts +97 -2
  18. package/lib/contracts/report.d.ts +8 -0
  19. package/lib/contracts/report.js +7 -1
  20. package/lib/contracts/result.d.ts +93 -0
  21. package/lib/contracts/result.js +37 -1
  22. package/lib/contracts/review.d.ts +1 -1
  23. package/lib/control/harness.d.ts +29 -2
  24. package/lib/engine/engine.d.ts +54 -6
  25. package/lib/engine/engine.js +191 -24
  26. package/lib/engine/joint-runner.d.ts +2 -0
  27. package/lib/engine/joint-runner.js +13 -3
  28. package/lib/engine/result.js +7 -3
  29. package/lib/engine/runner.d.ts +8 -0
  30. package/lib/engine/runner.js +91 -3
  31. package/lib/environment/git-trust.js +3 -0
  32. package/lib/environment/isolation.d.ts +1 -1
  33. package/lib/environment/isolation.js +38 -4
  34. package/lib/environment/process.d.ts +2 -0
  35. package/lib/environment/process.js +7 -1
  36. package/lib/explain/state.js +1 -1
  37. package/lib/index.d.ts +1 -0
  38. package/lib/index.js +1 -0
  39. package/lib/integrations/connector/history.js +1 -1
  40. package/lib/integrations/connector/summary.js +2 -1
  41. package/lib/profiles/resolve.d.ts +6 -0
  42. package/lib/projections/attempt.d.ts +4 -2
  43. package/lib/projections/attempt.js +14 -1
  44. package/lib/report/compute.js +7 -3
  45. package/lib/report/document.js +1 -1
  46. package/lib/storage/document.d.ts +28 -2
  47. package/lib/testing/store-contract.d.ts +8 -2
  48. package/lib/testing/store-contract.js +56 -1
  49. package/lib/verification/acceptance.d.ts +12 -0
  50. package/lib/verification/acceptance.js +62 -7
  51. package/lib/verification/applicability.d.ts +134 -0
  52. package/lib/verification/applicability.js +373 -0
  53. package/lib/verification/gates.d.ts +6 -0
  54. package/lib/verification/joint.d.ts +179 -1
  55. package/lib/verification/joint.js +23 -3
  56. package/lib/verification/proof.d.ts +18 -4
  57. package/lib/verification/proof.js +52 -9
  58. package/package.json +1 -1
  59. package/schemas/execution-document.schema.json +77 -1
  60. package/schemas/execution-policy.schema.json +38 -0
  61. package/schemas/joint-verification.schema.json +4 -0
  62. package/schemas/result-envelope.schema.json +138 -2
  63. package/schemas/run-event.schema.json +100 -0
  64. package/schemas/run-result.schema.json +138 -2
  65. package/schemas/value-report.schema.json +20 -0
@@ -1,5 +1,6 @@
1
- import { type ReproductionRecord, type AttemptState, type RunEventPayload, type CancelActor, type ContextLimit, type EnvironmentCause, type RetryActor, type Author, type CallRecord, type ContractDocument, type EvidenceRecord, type ExecutionHost, type ExecutionPolicy, type ExecutionTransaction, type ExecutionView, type FailureKind, type GraphState, type InputActor, type InputAnswer, type InputOutcome, type InputRequest, type ContextSnapshot, type JointVerification, type JointVerificationState, type NotPromise, type Prerequisite, type PropertyRecovery, type ReviewRecord, type TechnicalApproval, type TransactionKind, type WorkGraph, type WorkState } from '../contracts/index.ts';
1
+ import { type ReproductionRecord, type AttemptState, type RunEventPayload, type CancelActor, type ContextLimit, type EnvironmentCause, type RetryActor, type JointBudgetReset, type JointResetActor, type Author, type CallRecord, type ContractDocument, type EvidenceRecord, type ExecutionHost, type ExecutionPolicy, type ExecutionTransaction, type ExecutionView, type FailureKind, type GraphState, type InputActor, type InputAnswer, type InputOutcome, type InputRequest, type ContextSnapshot, type JointVerification, type JointVerificationState, type NotPromise, type Prerequisite, type PropertyRecovery, type ReviewRecord, type TechnicalApproval, type TransactionKind, type WorkGraph, type WorkState } from '../contracts/index.ts';
2
2
  import { type BudgetContext, type CallMeta } from './budget.ts';
3
+ import { type ChangedPaths } from '../verification/applicability.ts';
3
4
  /** Префикс причины неудавшегося продления: первая причина не затирается следствиями. */
4
5
  export declare const HEARTBEAT_FAILED = "\u041F\u0440\u043E\u0434\u043B\u0435\u043D\u0438\u0435 \u0432\u043B\u0430\u0434\u0435\u043D\u0438\u044F \u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C";
5
6
  export interface EngineOptions {
@@ -695,9 +696,11 @@ export declare class Engine {
695
696
  * поручений: покрытие — по фактическому собственному evidence на принятом
696
697
  * SHA попытки под текущим основанием политики, для любой области. Evidence потребителя — проверка другого
697
698
  * компонента и не в счёт; запись ревью не закрывает одноимённый test gate.
698
- * Решение о приёмке набора поручений — за хостом.
699
+ * Gate с `when`, признанный где-то неприменимым, решается по объединённому
700
+ * diff набора `changes` (`uncoveredGates` проверки). Решение о приёмке набора
701
+ * поручений — за хостом.
699
702
  */
700
- uncoveredGates(workIds: string[]): {
703
+ uncoveredGates(workIds: string[], changes?: Readonly<Record<string, ChangedPaths>>, finalShas?: Readonly<Record<string, string>>): {
701
704
  repositoryId: string;
702
705
  gates: string[];
703
706
  }[];
@@ -745,7 +748,7 @@ export declare class Engine {
745
748
  evidence(id: string, token: string, evidence: Omit<EvidenceRecord, 'id' | 'runId' | 'createdAt'>): {
746
749
  id: string;
747
750
  runId: string;
748
- kind: "review" | "test";
751
+ kind: "review" | "test" | "not-applicable";
749
752
  phase: "candidate" | "integration";
750
753
  sha: string;
751
754
  gate: string;
@@ -901,6 +904,18 @@ export declare class Engine {
901
904
  skippedMore?: number | undefined;
902
905
  } | undefined;
903
906
  checks?: string | undefined;
907
+ gateBasis?: string | undefined;
908
+ notApplicable?: {
909
+ gateDigest: string;
910
+ patterns: string[];
911
+ ranges: {
912
+ from: string;
913
+ to: string;
914
+ }[];
915
+ count: number;
916
+ files: string[];
917
+ pathsDigest: string;
918
+ } | undefined;
904
919
  alreadySatisfied?: {
905
920
  gates: string[];
906
921
  evidence: string;
@@ -4024,6 +4039,7 @@ export declare class Engine {
4024
4039
  }[];
4025
4040
  token: string;
4026
4041
  leaseUntil: number;
4042
+ interrupted?: true | undefined;
4027
4043
  engineVersion?: string | undefined;
4028
4044
  } | {
4029
4045
  manifest: Record<string, {
@@ -4178,6 +4194,7 @@ export declare class Engine {
4178
4194
  tree: string;
4179
4195
  }> | undefined;
4180
4196
  manifestDigest?: string | undefined;
4197
+ interrupted?: true | undefined;
4181
4198
  impact?: {
4182
4199
  changed: string[];
4183
4200
  affected: string[];
@@ -4238,8 +4255,39 @@ export declare class Engine {
4238
4255
  baseline?: string | undefined;
4239
4256
  } | undefined;
4240
4257
  };
4241
- /** Отказ проверки её владельцем; истёкший срок допустим, чужой токен — нет. */
4242
- jointFail(id: string, token: string, error: string): boolean;
4258
+ /**
4259
+ * Отказ проверки её владельцем; истёкший срок допустим, чужой токен — нет.
4260
+ * `interrupted` — проверку прервали остановка или потеря владения; движок
4261
+ * отмечает её прерванной только без evidence: результат gate тратит предел.
4262
+ */
4263
+ jointFail(id: string, token: string, error: string, options?: {
4264
+ interrupted?: boolean;
4265
+ }): boolean;
4266
+ /**
4267
+ * Закрыть истёкшую активную проверку отказом. Владение потеряно: без
4268
+ * evidence проверка прервана до результата gates, с evidence — обычный отказ.
4269
+ */
4270
+ private closeExpiredJoint;
4271
+ /**
4272
+ * Почему набор не может начать совместную проверку по бюджету, или
4273
+ * `undefined`. Предел тратят проверки с результатом gates и отказы до них;
4274
+ * прерванные до результата gates (`interrupted`) — только свой предел.
4275
+ */
4276
+ private jointExhausted;
4277
+ /**
4278
+ * Явный сброс бюджета совместных проверок набора оператором или хостом:
4279
+ * только при исчерпанном пределе и без живой проверки этого набора, с
4280
+ * причиной. Сброс снимает только проверки набора без результата gates
4281
+ * (прерванные и отказы до gates, в том числе записанные прежними версиями);
4282
+ * проверки с evidence тратят предел и после сброса, поэтому предел,
4283
+ * исчерпанный ими одними, сброс не снимает. Истёкшая незакрытая проверка
4284
+ * набора закрывается здесь же (как в `jointStart`). Запись — в
4285
+ * `joint-budget-resets`, событие — `joint.budget-reset`.
4286
+ */
4287
+ jointBudgetReset(workIds: string[], options: {
4288
+ reason: string;
4289
+ actor?: JointResetActor;
4290
+ }): JointBudgetReset;
4243
4291
  /**
4244
4292
  * Актуальный результат совместной проверки набора: последняя проверка этого
4245
4293
  * набора, успешная, с целым manifest, под текущей политикой, на неизменном
@@ -10,9 +10,10 @@ import { alreadySatisfiedVerdict, contractCheckGates } from "../verification/alr
10
10
  import { contractDocuments, corpusBindingHolds, effectiveChecks, episodeBasis, orderPropertyProblems, } from "../verification/checks.js";
11
11
  import { afterFailure, afterSuccess, blocksClaim, closeIfBasisChanged, } from "./property-recovery.js";
12
12
  import { REQUIREMENT_GATE } from "../verification/requirements.js";
13
+ import { notApplicableProblem, proofGates, } from "../verification/applicability.js";
13
14
  import { blockingRequest, inputManifestOf, requestById, requestsOf, unappliedInputs, } from "./input-requests.js";
14
15
  import { pinnedCorpus, propertyProofProblem } from "../verification/acceptance.js";
15
- import { jointImpact, jointPolicyDigest, jointSpecDigest, publicJoint, sameWorks, jointBudgetAttempts, } from "../verification/joint.js";
16
+ import { jointImpact, jointPolicyDigest, jointSpecDigest, publicJoint, sameWorks, jointBudgetWindow, jointInterrupted, } from "../verification/joint.js";
16
17
  /** Префикс причины неудавшегося продления: первая причина не затирается следствиями. */
17
18
  export const HEARTBEAT_FAILED = 'Продление владения не удалось';
18
19
  const iso = (ms) => new Date(ms).toISOString();
@@ -1266,9 +1267,11 @@ export class Engine {
1266
1267
  * поручений: покрытие — по фактическому собственному evidence на принятом
1267
1268
  * SHA попытки под текущим основанием политики, для любой области. Evidence потребителя — проверка другого
1268
1269
  * компонента и не в счёт; запись ревью не закрывает одноимённый test gate.
1269
- * Решение о приёмке набора поручений — за хостом.
1270
+ * Gate с `when`, признанный где-то неприменимым, решается по объединённому
1271
+ * diff набора `changes` (`uncoveredGates` проверки). Решение о приёмке набора
1272
+ * поручений — за хостом.
1270
1273
  */
1271
- uncoveredGates(workIds) {
1274
+ uncoveredGates(workIds, changes, finalShas) {
1272
1275
  return this.read((v) => {
1273
1276
  const works = workIds.map((id) => v.work(id)).filter((w) => !!w);
1274
1277
  const repositories = [...new Set(works.map((w) => w.order.repositoryId))].map((id) => this.repository(id));
@@ -1282,7 +1285,7 @@ export class Engine {
1282
1285
  .attempts(w.id)
1283
1286
  .filter((a) => a.policyDigest === this.host.basis.policyDigest(w, v))
1284
1287
  .flatMap((a) => a.evidence),
1285
- })));
1288
+ })), changes, finalShas);
1286
1289
  });
1287
1290
  }
1288
1291
  /**
@@ -1436,6 +1439,42 @@ export class Engine {
1436
1439
  // доказывала бы его (и названный testcase).
1437
1440
  if ((evidence.kind === 'review') !== (evidence.gate === 'independent-review'))
1438
1441
  throw new HarnessError('INVALID_INPUT', `Evidence вида ${evidence.kind} не может относиться к gate ${evidence.gate}`);
1442
+ // Неприменимость (`when.paths`) — только у gate с `when` области
1443
+ // попытки, под его текущим определением, без исполнения и не PASS;
1444
+ // сведения о ней — только у такой записи.
1445
+ if ((evidence.kind === 'not-applicable') !== (evidence.notApplicable !== undefined))
1446
+ throw new HarnessError('INVALID_INPUT', 'Сведения о неприменимости — только у записи вида not-applicable');
1447
+ if (evidence.kind === 'not-applicable') {
1448
+ const problem = evidence.passed ||
1449
+ evidence.consumer !== undefined ||
1450
+ evidence.recheck !== undefined ||
1451
+ evidence.tests !== undefined ||
1452
+ evidence.property !== undefined ||
1453
+ evidence.artifactFiles !== undefined ||
1454
+ !(a.requiredGates ?? []).includes(evidence.gate)
1455
+ ? 'запись неприменимости не может быть PASS, исполнением или gate вне области'
1456
+ : // Решение — о SHA текущей фазы, diff заканчивается на нём.
1457
+ evidence.sha !==
1458
+ (evidence.phase === 'candidate' ? a.candidateSha : a.integrationSha) ||
1459
+ evidence.notApplicable.ranges.at(-1)?.to !== evidence.sha
1460
+ ? 'запись неприменимости не относится к SHA фазы попытки'
1461
+ : // Исполненный gate не становится неприменимым на том же SHA.
1462
+ a.evidence.some((e) => e.kind === 'test' &&
1463
+ e.gate === evidence.gate &&
1464
+ e.phase === evidence.phase &&
1465
+ e.sha === evidence.sha &&
1466
+ e.consumer === undefined)
1467
+ ? 'gate уже исполнялся на этом SHA: запись неприменимости не заменяет его исход'
1468
+ : notApplicableProblem({
1469
+ gates: this.repository(a.repositoryId).gates,
1470
+ gate: evidence.gate,
1471
+ record: evidence,
1472
+ proof: proofGates(w.order, contractDocuments(w.order, tx)),
1473
+ ran: [],
1474
+ });
1475
+ if (problem)
1476
+ throw new HarnessError('INVALID_INPUT', problem);
1477
+ }
1439
1478
  // Повтор ссылается на провал того же gate этой попытки на том же SHA, и
1440
1479
  // попытка повторяет не больше одного провала на фазу.
1441
1480
  if (evidence.recheck) {
@@ -1489,6 +1528,7 @@ export class Engine {
1489
1528
  passed: record.passed,
1490
1529
  evidenceId: record.id,
1491
1530
  ...(record.consumer ? { consumer: record.consumer } : {}),
1531
+ ...(record.kind === 'not-applicable' ? { notApplicable: true } : {}),
1492
1532
  ...(record.recheck ? { recheck: record.recheck } : {}),
1493
1533
  },
1494
1534
  });
@@ -1516,16 +1556,42 @@ export class Engine {
1516
1556
  // попытка: новый корпус, принятый поручением, требует новой попытки.
1517
1557
  if (a.checks && this.checksOf(w, tx) !== a.checks.effective)
1518
1558
  throw new HarnessError('APPROVAL_STALE', 'Версия проверок поручения изменилась; нужна новая попытка');
1519
- const last = (kind, phase, at, gate) => a.evidence.findLast((e) => e.kind === kind &&
1559
+ const decisive = (kinds, phase, at, gate) => a.evidence.findLast((e) => kinds.includes(e.kind) &&
1520
1560
  e.phase === phase &&
1521
1561
  e.sha === at &&
1522
1562
  e.gate === gate &&
1523
1563
  e.consumer === undefined &&
1524
- (!a.checks || e.checks === a.checks.effective))?.passed === true;
1564
+ (!a.checks || e.checks === a.checks.effective));
1565
+ const last = (kind, phase, at, gate) => decisive([kind], phase, at, gate)?.passed === true;
1566
+ // Обязательный gate закрыт PASS или — только обычный gate с `when` —
1567
+ // записью неприменимости под текущим определением (`notApplicableProblem`).
1568
+ const repoGates = this.repository(a.repositoryId).gates;
1569
+ const named = proofGates(w.order, contractDocuments(w.order, tx));
1570
+ const shaOf = (phase) => phase === 'candidate' ? a.candidateSha : sha;
1571
+ const ran = Object.fromEntries(['candidate', 'integration'].map((phase) => [
1572
+ phase,
1573
+ (a.requiredGates ?? []).filter((gate) => decisive(['test'], phase, shaOf(phase), gate) !== undefined),
1574
+ ]));
1525
1575
  for (const gate of a.requiredGates ?? [])
1526
- for (const phase of ['candidate', 'integration'])
1527
- if (!last('test', phase, phase === 'candidate' ? a.candidateSha : sha, gate))
1528
- throw new HarnessError('GATE_FAILED', `Нет PASS: ${phase}/${gate}`);
1576
+ for (const phase of ['candidate', 'integration']) {
1577
+ // Исход исполнения решает всегда; неприменимость — только без него.
1578
+ const record = decisive(['test'], phase, shaOf(phase), gate) ??
1579
+ decisive(['not-applicable'], phase, shaOf(phase), gate);
1580
+ if (record?.kind === 'test' && record.passed)
1581
+ continue;
1582
+ const problem = record?.kind === 'not-applicable'
1583
+ ? notApplicableProblem({
1584
+ gates: repoGates,
1585
+ gate,
1586
+ record,
1587
+ proof: named,
1588
+ ran: ran[phase],
1589
+ })
1590
+ : 'нет записи';
1591
+ if (problem)
1592
+ throw new HarnessError('GATE_FAILED', `Нет PASS: ${phase}/${gate}` +
1593
+ (record?.kind === 'not-applicable' ? ': ' + problem : ''));
1594
+ }
1529
1595
  for (const phase of ['candidate', 'integration'])
1530
1596
  if (!last('review', phase, phase === 'candidate' ? a.candidateSha : sha, 'independent-review'))
1531
1597
  throw new HarnessError('REVIEW_REJECTED', `Нет независимого ревью: ${phase}`);
@@ -3271,18 +3337,11 @@ export class Engine {
3271
3337
  continue;
3272
3338
  if (v.leaseUntil > this.now())
3273
3339
  throw new HarnessError('NOT_READY', 'Совместная проверка уже выполняется');
3274
- const error = 'Истёк срок владения проверкой';
3275
- tx.putVerification({ ...v, status: 'failed', error, finishedAt: iso(this.now()) });
3276
- tx.emit({
3277
- type: 'joint.finished',
3278
- payload: { verificationId: v.id, status: 'failed', error },
3279
- });
3340
+ this.closeExpiredJoint(tx, v);
3280
3341
  }
3281
- const previous = jointBudgetAttempts(tx, input.workIds, this.host.basis.jointBudgetCheckpoints
3282
- ? this.host.basis.jointBudgetCheckpoints([...input.workIds], tx)
3283
- : []);
3284
- if (previous.length >= this.policy.maxAttempts)
3285
- throw new HarnessError('ATTEMPTS_EXHAUSTED', 'Исчерпан предел совместных проверок этого набора');
3342
+ const exhausted = this.jointExhausted(tx, input.workIds);
3343
+ if (exhausted)
3344
+ throw new HarnessError('ATTEMPTS_EXHAUSTED', exhausted);
3286
3345
  const works = input.workIds.map((id) => tx.work(id));
3287
3346
  if (works.some((w) => !w || w.status !== 'done' || !w.resultSha))
3288
3347
  throw new HarnessError('NOT_READY', 'Сначала завершите все поручения набора');
@@ -3414,21 +3473,129 @@ export class Engine {
3414
3473
  return publicJoint(next);
3415
3474
  });
3416
3475
  }
3417
- /** Отказ проверки её владельцем; истёкший срок допустим, чужой токен — нет. */
3418
- jointFail(id, token, error) {
3476
+ /**
3477
+ * Отказ проверки её владельцем; истёкший срок допустим, чужой токен — нет.
3478
+ * `interrupted` — проверку прервали остановка или потеря владения; движок
3479
+ * отмечает её прерванной только без evidence: результат gate тратит предел.
3480
+ */
3481
+ jointFail(id, token, error, options = {}) {
3419
3482
  return this.tx('workspace.failed', (tx) => {
3420
3483
  const v = tx.verification(id);
3421
3484
  if (!v || v.status !== 'active' || v.token !== token || v.engineVersion !== this.version)
3422
3485
  return false;
3423
3486
  const message = error.slice(0, 4000) || 'Совместная проверка не прошла';
3424
- tx.putVerification({ ...v, status: 'failed', error: message, finishedAt: iso(this.now()) });
3487
+ const interrupted = options.interrupted && v.evidence.length === 0 ? { interrupted: true } : {};
3488
+ tx.putVerification({
3489
+ ...v,
3490
+ status: 'failed',
3491
+ error: message,
3492
+ finishedAt: iso(this.now()),
3493
+ ...interrupted,
3494
+ });
3425
3495
  tx.emit({
3426
3496
  type: 'joint.finished',
3427
- payload: { verificationId: id, status: 'failed', error: message },
3497
+ payload: { verificationId: id, status: 'failed', error: message, ...interrupted },
3428
3498
  });
3429
3499
  return true;
3430
3500
  });
3431
3501
  }
3502
+ /**
3503
+ * Закрыть истёкшую активную проверку отказом. Владение потеряно: без
3504
+ * evidence проверка прервана до результата gates, с evidence — обычный отказ.
3505
+ */
3506
+ closeExpiredJoint(tx, v) {
3507
+ const error = 'Истёк срок владения проверкой';
3508
+ const interrupted = v.evidence.length === 0 ? { interrupted: true } : {};
3509
+ tx.putVerification({
3510
+ ...v,
3511
+ status: 'failed',
3512
+ error,
3513
+ finishedAt: iso(this.now()),
3514
+ ...interrupted,
3515
+ });
3516
+ tx.emit({
3517
+ type: 'joint.finished',
3518
+ payload: { verificationId: v.id, status: 'failed', error, ...interrupted },
3519
+ });
3520
+ }
3521
+ /**
3522
+ * Почему набор не может начать совместную проверку по бюджету, или
3523
+ * `undefined`. Предел тратят проверки с результатом gates и отказы до них;
3524
+ * прерванные до результата gates (`interrupted`) — только свой предел.
3525
+ */
3526
+ jointExhausted(tx, workIds) {
3527
+ const window = jointBudgetWindow(tx, workIds, this.host.basis.jointBudgetCheckpoints
3528
+ ? this.host.basis.jointBudgetCheckpoints([...workIds], tx)
3529
+ : []);
3530
+ const interrupted = window.filter(jointInterrupted).length;
3531
+ const counted = window.length - interrupted;
3532
+ if (counted >= this.policy.maxAttempts)
3533
+ return `Исчерпан предел совместных проверок этого набора: ${counted} из ${this.policy.maxAttempts}. Не считаются только проверки, прерванные остановкой или потерей владения до результата gates. Предел снимает принятие хостом успешной проверки набора; явный сброс (jointBudgetReset) с причиной снимает только проверки без результата gates`;
3534
+ if (interrupted >= MAX_NEUTRAL_FAILURES)
3535
+ return `Совместные проверки этого набора прерваны до результата gates ${interrupted} раз (предел ${MAX_NEUTRAL_FAILURES}): устраните причину остановок или потери владения и сбросьте бюджет явно (jointBudgetReset) с причиной`;
3536
+ return undefined;
3537
+ }
3538
+ /**
3539
+ * Явный сброс бюджета совместных проверок набора оператором или хостом:
3540
+ * только при исчерпанном пределе и без живой проверки этого набора, с
3541
+ * причиной. Сброс снимает только проверки набора без результата gates
3542
+ * (прерванные и отказы до gates, в том числе записанные прежними версиями);
3543
+ * проверки с evidence тратят предел и после сброса, поэтому предел,
3544
+ * исчерпанный ими одними, сброс не снимает. Истёкшая незакрытая проверка
3545
+ * набора закрывается здесь же (как в `jointStart`). Запись — в
3546
+ * `joint-budget-resets`, событие — `joint.budget-reset`.
3547
+ */
3548
+ jointBudgetReset(workIds, options) {
3549
+ const reason = options.reason?.trim() ?? '';
3550
+ if (!reason)
3551
+ throw new HarnessError('INVALID_INPUT', 'Сброс бюджета совместных проверок требует причины');
3552
+ if (!workIds.length || new Set(workIds).size !== workIds.length)
3553
+ throw new HarnessError('INVALID_INPUT', 'Нужен непустой набор разных поручений');
3554
+ return this.tx('workspace.budget-reset', (tx) => {
3555
+ for (const v of tx.verifications()) {
3556
+ if (v.status !== 'active' || !sameWorks(v.workIds, workIds))
3557
+ continue;
3558
+ if (v.leaseUntil > this.now())
3559
+ throw new HarnessError('NOT_READY', 'Совместная проверка этого набора ещё выполняется');
3560
+ this.closeExpiredJoint(tx, v);
3561
+ }
3562
+ if (!this.jointExhausted(tx, workIds))
3563
+ throw new HarnessError('NOT_READY', 'Предел совместных проверок этого набора не исчерпан; сброс не нужен');
3564
+ const window = jointBudgetWindow(tx, workIds, this.host.basis.jointBudgetCheckpoints
3565
+ ? this.host.basis.jointBudgetCheckpoints([...workIds], tx)
3566
+ : []);
3567
+ const gated = window.filter((v) => v.evidence.length > 0).length;
3568
+ if (gated >= this.policy.maxAttempts)
3569
+ throw new HarnessError('ATTEMPTS_EXHAUSTED', `Предел совместных проверок этого набора исчерпан проверками с результатом gates: ${gated} из ${this.policy.maxAttempts}. Сброс снимает только проверки без результата gates; дальше — принятие хостом успешной проверки или новый набор`);
3570
+ const settled = window.filter((v) => v.status === 'failed' && v.evidence.length === 0);
3571
+ // Успешная проверка без принятия (и без evidence) сбросом не снимается:
3572
+ // сброс, после которого набор всё равно исчерпан, не записывается. Пустой
3573
+ // снимок сюда же: предел исчерпан, значит, остаток — весь предел.
3574
+ const remaining = window.length - settled.length;
3575
+ if (remaining >= this.policy.maxAttempts)
3576
+ throw new HarnessError('ATTEMPTS_EXHAUSTED', `Сброс не освобождает предел совместных проверок этого набора: снимаются только отказы без результата gates (${settled.length}), а остальные проверки (${remaining}, в том числе успешные без принятия) тратят ${remaining} из ${this.policy.maxAttempts}; дальше — принятие хостом успешной проверки или новый набор`);
3577
+ const record = {
3578
+ id: this.id(),
3579
+ at: iso(this.now()),
3580
+ workIds: [...workIds].sort(),
3581
+ reason: reason.slice(0, 2000),
3582
+ actor: options.actor ?? 'host',
3583
+ settledVerificationIds: settled.map((v) => v.id),
3584
+ };
3585
+ tx.putLocal('joint-budget-resets', WORKSPACE_OWNER, record.id, record);
3586
+ tx.emit({
3587
+ type: 'joint.budget-reset',
3588
+ payload: {
3589
+ resetId: record.id,
3590
+ workIds: record.workIds,
3591
+ by: record.actor,
3592
+ settled: record.settledVerificationIds.length,
3593
+ reasonLength: record.reason.length,
3594
+ },
3595
+ });
3596
+ return record;
3597
+ });
3598
+ }
3432
3599
  /**
3433
3600
  * Актуальный результат совместной проверки набора: последняя проверка этого
3434
3601
  * набора, успешная, с целым 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, gateTimeoutMs, } 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));
@@ -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);
@@ -24,9 +24,11 @@ const ref = (e, attempt) => ({
24
24
  id: e.id,
25
25
  kind: e.kind === 'review'
26
26
  ? 'review'
27
- : e.consumer
28
- ? 'consumer'
29
- : 'test',
27
+ : e.kind === 'not-applicable'
28
+ ? 'not-applicable'
29
+ : e.consumer
30
+ ? 'consumer'
31
+ : 'test',
30
32
  phase: e.phase,
31
33
  gate: e.gate,
32
34
  sha: e.sha,
@@ -35,6 +37,8 @@ const ref = (e, attempt) => ({
35
37
  summary: e.summary.slice(0, 4000),
36
38
  ...(e.consumer ? { consumer: e.consumer } : {}),
37
39
  ...(e.checks ? { checks: e.checks } : {}),
40
+ // Gate не исполнялся по `when.paths`: правило и diff — получателю.
41
+ ...(e.notApplicable ? { notApplicable: e.notApplicable } : {}),
38
42
  // Список тестов собственной проверки интеграции — для доказательства
39
43
  // названного testcase у получателя.
40
44
  ...(e.kind === 'test' && !e.consumer && e.phase === 'integration' && e.tests
@@ -302,6 +302,14 @@ export declare class Runner {
302
302
  * прошёл, `confirmed` — провал подтвердился и засчитывается как прежде).
303
303
  */
304
304
  private integrationGate;
305
+ /**
306
+ * Gates фазы, которые исполняются; для остальных (gate с `when.paths`, чей
307
+ * путь diff фазы не задел, — `gateDecisions`) записывается `not-applicable`.
308
+ * Diff — из Git: кандидат — `base..candidate`; интеграция — ещё и
309
+ * `base..integration` (то, что принесло слияние с target). Попытка без
310
+ * изменений исполняет всё: её приёмка опирается на прохождение gates.
311
+ */
312
+ private applicableGates;
305
313
  private runOneGate;
306
314
  /**
307
315
  * Ожидаемая проверка генеративного gate. Проверка потребителя исполняет
@@ -21,6 +21,7 @@ import { GateTimeout, prepareWriterDependencies, draftTouchesInstall, runGate, w
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";
24
+ import { changedPaths, gateBasis, gateDecisions, proofGates, } from "../verification/applicability.js";
24
25
  import { alreadySatisfiedVerdict, contractCheckGates, withinWriteScope, } from "../verification/already-satisfied.js";
25
26
  import { assertDependencies, dependencyFreshness, removeSnapshots, snapshotDependencies, } from "../verification/dependencies.js";
26
27
  import { CleanupFailure, cleanupEnvironment } from "../environment/lifecycle.js";
@@ -1193,7 +1194,8 @@ export class Runner {
1193
1194
  rearm();
1194
1195
  this.engine.phase(attempt.id, attempt.token, 'verifying', { candidateSha: sha });
1195
1196
  const recheck = { recheck: true };
1196
- for (const gate of gates)
1197
+ const applicable = await this.applicableGates(attempt, work, repo, gates, 'candidate', cwd, sha, base);
1198
+ for (const gate of applicable)
1197
1199
  await this.candidateGate(attempt, cwd, sha, gate, artifacts, signal, execution, recheck).catch((error) => {
1198
1200
  // Без изменений непрошедший gate значит одно: работа не
1199
1201
  // сделана, — это пустой результат, а не дефект кода.
@@ -1722,14 +1724,97 @@ export class Runner {
1722
1724
  await this.gate(attempt, cwd, sha, 'integration', gate, artifacts, signal, execution, undefined, failed.id);
1723
1725
  }
1724
1726
  }
1727
+ /**
1728
+ * Gates фазы, которые исполняются; для остальных (gate с `when.paths`, чей
1729
+ * путь diff фазы не задел, — `gateDecisions`) записывается `not-applicable`.
1730
+ * Diff — из Git: кандидат — `base..candidate`; интеграция — ещё и
1731
+ * `base..integration` (то, что принесло слияние с target). Попытка без
1732
+ * изменений исполняет всё: её приёмка опирается на прохождение gates.
1733
+ */
1734
+ async applicableGates(attempt, work, repo, gates, phase, cwd, sha, base) {
1735
+ if (!gates.some((g) => g.when))
1736
+ return gates;
1737
+ const candidate = phase === 'candidate' ? sha : attempt.candidateSha;
1738
+ if (candidate === base)
1739
+ return gates;
1740
+ const proof = this.engine.read((v) => proofGates(work.order, contractDocuments(work.order, v)));
1741
+ // Последний зелёный SHA условного gate: integration принятой попытки
1742
+ // этого репозитория, где gate прошёл под тем же основанием (`gateBasis`),
1743
+ // и предок базы попытки. Diff фазы — от него: всё, что попало в target
1744
+ // после (в том числе мимо harness или в задачах с суженной областью),
1745
+ // входит в решение. Нет такого SHA — gate исполняется.
1746
+ const greens = this.engine.read((v) => v
1747
+ .attempts()
1748
+ .filter((x) => x.status === 'succeeded' && x.repositoryId === repo.id && x.integrationSha)
1749
+ .sort((x, y) => (y.finishedAt ?? '').localeCompare(x.finishedAt ?? '')));
1750
+ const diffs = new Map();
1751
+ const changed = new Map();
1752
+ for (const gate of gates) {
1753
+ if (!gate.when || proof.has(gate.id))
1754
+ continue;
1755
+ const basis = gateBasis(this.policy, repo, gate, this.engine.version);
1756
+ const shas = [
1757
+ ...new Set(greens
1758
+ .filter((x) => x.evidence.some((e) => e.kind === 'test' &&
1759
+ e.phase === 'integration' &&
1760
+ e.sha === x.integrationSha &&
1761
+ e.gate === gate.id &&
1762
+ e.consumer === undefined &&
1763
+ e.passed &&
1764
+ e.gateBasis === basis))
1765
+ .map((x) => x.integrationSha)),
1766
+ ].slice(0, 50);
1767
+ let anchor;
1768
+ for (const green of shas)
1769
+ if (await git(cwd, 'merge-base', '--is-ancestor', green, base).then(() => true, () => false)) {
1770
+ anchor = green;
1771
+ break;
1772
+ }
1773
+ if (!anchor)
1774
+ continue;
1775
+ if (!diffs.has(anchor))
1776
+ diffs.set(anchor, await changedPaths(cwd, [
1777
+ { from: anchor, to: candidate },
1778
+ ...(phase === 'integration' ? [{ from: anchor, to: sha }] : []),
1779
+ ]));
1780
+ changed.set(gate.id, diffs.get(anchor));
1781
+ }
1782
+ const decisions = gateDecisions({
1783
+ repo,
1784
+ scope: gates,
1785
+ proof,
1786
+ changedFor: (gate) => changed.get(gate.id),
1787
+ });
1788
+ for (const d of decisions)
1789
+ if (!d.run && d.record)
1790
+ this.engine.evidence(attempt.id, attempt.token, {
1791
+ kind: 'not-applicable',
1792
+ phase,
1793
+ sha,
1794
+ gate: d.gate.id,
1795
+ passed: false,
1796
+ command: [],
1797
+ exitCode: -1,
1798
+ log: '',
1799
+ digest: digestOf(d.record),
1800
+ summary: `Не применим: diff фазы (${d.record.count} путей) не задел when.paths и неявные входы gate`,
1801
+ notApplicable: d.record,
1802
+ });
1803
+ return decisions.filter((d) => d.run).map((d) => d.gate);
1804
+ }
1725
1805
  async runOneGate(attempt, cwd, sha, phase, gate, artifacts, signal, execution, consumer, recheck) {
1726
1806
  // Генеративный gate — всегда; gate эталонных наборов — когда манифест
1727
1807
  // поручения ждёт от него отчёта (без договора — прежний уровень).
1728
1808
  const run = this.propertyRun(attempt, gate, consumer);
1729
1809
  const property = gate.property || expectsReference(run.expected) ? run : undefined;
1810
+ const basis = gate.when && !consumer
1811
+ ? {
1812
+ gateBasis: gateBasis(this.policy, this.repo(attempt.repositoryId), gate, this.engine.version),
1813
+ }
1814
+ : {};
1730
1815
  await runGate({
1731
1816
  policy: this.policy,
1732
- record: (e) => this.engine.evidence(attempt.id, attempt.token, e),
1817
+ record: (e) => this.engine.evidence(attempt.id, attempt.token, { ...e, ...basis }),
1733
1818
  cwd,
1734
1819
  sha,
1735
1820
  phase,
@@ -2496,6 +2581,8 @@ export class Runner {
2496
2581
  passed: e.passed,
2497
2582
  summary: e.summary,
2498
2583
  ...(e.consumer ? { consumer: e.consumer } : {}),
2584
+ // Gate не исполнялся по when.paths: не провал и не PASS.
2585
+ ...(e.kind === 'not-applicable' ? { notApplicable: true } : {}),
2499
2586
  }))), 'Where a requirement names a testId, open that test. Reject it when the test does not exercise the stated scenario, or when it would still pass if the behaviour it claims to prove were broken. A matching name is not proof.');
2500
2587
  }
2501
2588
  const r = v.work(attempt.workId)?.recovery;
@@ -2650,7 +2737,8 @@ export class Runner {
2650
2737
  await runSteps(repo.prepare, cwd, join(artifacts, 'integration', 'prepare'), execution, signal, attempt.baseSha);
2651
2738
  prepared(execution);
2652
2739
  const budget = { recheck: true };
2653
- for (const gate of gates)
2740
+ const applicable = await this.applicableGates(attempt, work, repo, gates, 'integration', cwd, sha, attempt.baseSha);
2741
+ for (const gate of applicable)
2654
2742
  await this.integrationGate(attempt, cwd, sha, gate, artifacts, signal, execution, budget);
2655
2743
  await this.consumers(attempt, cwd, sha, artifacts, signal);
2656
2744
  this.requirements(attempt, work, repoPath, cwd, sha, 'integration');