devcontour-harness 0.1.0-alpha.44 → 0.1.0-alpha.46
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.
- package/README.md +20 -2
- package/docs/architecture.md +8 -0
- package/docs/contracts.md +122 -2
- package/docs/release-notes/0.1.0-alpha.45.md +77 -0
- package/docs/release-notes/0.1.0-alpha.46.md +63 -0
- package/docs/upgrade.md +98 -18
- package/lib/contracts/cli.d.ts +68 -0
- package/lib/contracts/cli.js +6 -1
- package/lib/contracts/events.d.ts +5 -0
- package/lib/contracts/events.js +2 -0
- package/lib/contracts/execution.d.ts +39 -0
- package/lib/contracts/execution.js +20 -2
- package/lib/contracts/handoff.d.ts +1 -0
- package/lib/contracts/handoff.js +6 -1
- package/lib/contracts/policy.d.ts +39 -0
- package/lib/contracts/policy.js +64 -0
- package/lib/contracts/profiles.d.ts +6 -0
- package/lib/contracts/published.d.ts +70 -0
- package/lib/contracts/result.d.ts +91 -0
- package/lib/contracts/result.js +31 -1
- package/lib/contracts/review.d.ts +1 -1
- package/lib/control/harness.d.ts +24 -2
- package/lib/control/workflow.d.ts +5 -1
- package/lib/control/workflow.js +18 -3
- package/lib/engine/engine.d.ts +30 -5
- package/lib/engine/engine.js +104 -13
- package/lib/engine/result.js +7 -3
- package/lib/engine/runner.d.ts +8 -0
- package/lib/engine/runner.js +96 -3
- package/lib/environment/git-trust.js +3 -0
- package/lib/environment/process.d.ts +2 -0
- package/lib/environment/process.js +7 -1
- package/lib/explain/state.js +1 -1
- package/lib/handoff/pack.js +7 -1
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/integrations/connector/history.js +1 -1
- package/lib/integrations/connector/summary.js +2 -1
- package/lib/profiles/resolve.d.ts +6 -0
- package/lib/projections/attempt.d.ts +4 -2
- package/lib/projections/attempt.js +14 -1
- package/lib/report/compute.js +4 -3
- package/lib/storage/document.d.ts +26 -2
- package/lib/verification/acceptance.d.ts +12 -0
- package/lib/verification/acceptance.js +62 -7
- package/lib/verification/applicability.d.ts +157 -0
- package/lib/verification/applicability.js +406 -0
- package/lib/verification/gates.d.ts +6 -0
- package/lib/verification/proof.d.ts +18 -4
- package/lib/verification/proof.js +52 -9
- package/package.json +1 -1
- package/schemas/execution-document.schema.json +73 -1
- package/schemas/execution-policy.schema.json +38 -0
- package/schemas/handoff-pack.schema.json +4 -0
- package/schemas/result-envelope.schema.json +138 -2
- package/schemas/run-event.schema.json +4 -0
- package/schemas/run-result.schema.json +138 -2
package/lib/engine/engine.js
CHANGED
|
@@ -10,12 +10,15 @@ 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
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();
|
|
20
|
+
/** Хост ждёт подтверждения перенесённой базы: выдача закрыта при любом `paused`. */
|
|
21
|
+
const awaitsBaseCheck = (control) => (control.waits ?? []).some((w) => w.kind === 'base-check');
|
|
19
22
|
/** Содержание поручения без номера редакции источника: одинаковое содержание — та же работа. */
|
|
20
23
|
const contentDigest = (order) => digestOf({ ...order, source: { connector: order.source.connector, ref: order.source.ref } });
|
|
21
24
|
/**
|
|
@@ -556,7 +559,10 @@ export class Engine {
|
|
|
556
559
|
* Снять паузу — решение человека (семантика DevContour `pause(false)`):
|
|
557
560
|
* снимает паузу оператора, штатной остановки и отказа runtime вместе с её
|
|
558
561
|
* классами отказов. Паузу операции reconfigure снимает только сама
|
|
559
|
-
* операция: `PAUSED`.
|
|
562
|
+
* операция: `PAUSED`. Это и явный маршрут человека «подтвердить базу и
|
|
563
|
+
* начать»: `resume` снимает ожидания `base-check`. Других путей снять их у
|
|
564
|
+
* движка нет — пока такое ожидание есть, `claim` не выдаёт работу при
|
|
565
|
+
* любом значении `paused`.
|
|
560
566
|
*/
|
|
561
567
|
resume() {
|
|
562
568
|
return this.tx('scheduler.started', (tx) => {
|
|
@@ -582,21 +588,35 @@ export class Engine {
|
|
|
582
588
|
return { control: next, changed: true };
|
|
583
589
|
});
|
|
584
590
|
}
|
|
585
|
-
/**
|
|
591
|
+
/**
|
|
592
|
+
* Снять паузу отказа после устранения причины: только названные классы.
|
|
593
|
+
* Пока есть ожидание `base-check`, пауза остаётся и переходит в паузу
|
|
594
|
+
* `base-check`: устранённый отказ не подтверждает перенесённую базу (это
|
|
595
|
+
* делает человек через `resume`), а пауза `runtime` без классов отказа
|
|
596
|
+
* звала бы чинить окружение. Новая причина — новая пауза: `pausedAt` —
|
|
597
|
+
* время перехода (как у перехода хоста DevContour).
|
|
598
|
+
*/
|
|
586
599
|
clearFailure(kinds) {
|
|
587
600
|
return this.tx('scheduler.started', (tx) => {
|
|
588
601
|
const control = tx.control();
|
|
589
602
|
const left = (control.pauseFailures ?? []).filter((k) => !kinds.includes(k));
|
|
590
603
|
if (left.length === (control.pauseFailures ?? []).length)
|
|
591
604
|
return control;
|
|
592
|
-
const
|
|
605
|
+
const cleared = !left.length && control.pauseReason === 'runtime';
|
|
606
|
+
const waits = cleared && awaitsBaseCheck(control);
|
|
593
607
|
const next = {
|
|
594
608
|
...control,
|
|
595
609
|
pauseFailures: left.length ? left : undefined,
|
|
596
|
-
...(
|
|
610
|
+
...(cleared
|
|
611
|
+
? waits
|
|
612
|
+
? { pauseReason: 'base-check', pausedAt: iso(this.now()) }
|
|
613
|
+
: { paused: false, pauseReason: undefined, pausedAt: undefined }
|
|
614
|
+
: {}),
|
|
597
615
|
};
|
|
598
616
|
tx.setControl(next);
|
|
599
|
-
if (
|
|
617
|
+
if (waits)
|
|
618
|
+
tx.emit({ type: 'control.paused', payload: { reason: 'base-check' } });
|
|
619
|
+
else if (cleared)
|
|
600
620
|
tx.emit({ type: 'control.resumed', payload: { reason: 'runtime' } });
|
|
601
621
|
return next;
|
|
602
622
|
});
|
|
@@ -833,6 +853,8 @@ export class Engine {
|
|
|
833
853
|
code: 'PAUSED',
|
|
834
854
|
message: 'Очередь на паузе: ' + (view.control().pauseReason ?? 'operator'),
|
|
835
855
|
});
|
|
856
|
+
else if (awaitsBaseCheck(view.control()))
|
|
857
|
+
out.push({ code: 'PAUSED', message: 'Очередь ждёт подтверждения перенесённой базы' });
|
|
836
858
|
const reconfigure = this.reconfiguring(view);
|
|
837
859
|
if (reconfigure)
|
|
838
860
|
out.push({
|
|
@@ -930,6 +952,10 @@ export class Engine {
|
|
|
930
952
|
throw new HarnessError('CONTROLLER_BUSY', 'Выдавать попытки может только действующий controller');
|
|
931
953
|
if (tx.control().paused || this.host.guards.claimBarrier(tx))
|
|
932
954
|
return undefined;
|
|
955
|
+
// Перенесённая база не подтверждена хостом: снятый мимо `resume` флаг
|
|
956
|
+
// паузы (например, восстановлением отказа) выдачу не открывает.
|
|
957
|
+
if (awaitsBaseCheck(tx.control()))
|
|
958
|
+
return undefined;
|
|
933
959
|
// Пока операция применяет политику, попытки не выдаются, даже если
|
|
934
960
|
// человек снял паузу: попытка под прежней политикой не нужна.
|
|
935
961
|
if (this.reconfiguring(tx))
|
|
@@ -1266,9 +1292,11 @@ export class Engine {
|
|
|
1266
1292
|
* поручений: покрытие — по фактическому собственному evidence на принятом
|
|
1267
1293
|
* SHA попытки под текущим основанием политики, для любой области. Evidence потребителя — проверка другого
|
|
1268
1294
|
* компонента и не в счёт; запись ревью не закрывает одноимённый test gate.
|
|
1269
|
-
*
|
|
1295
|
+
* Gate с `when`, признанный где-то неприменимым, решается по объединённому
|
|
1296
|
+
* diff набора `changes` (`uncoveredGates` проверки). Решение о приёмке набора
|
|
1297
|
+
* поручений — за хостом.
|
|
1270
1298
|
*/
|
|
1271
|
-
uncoveredGates(workIds) {
|
|
1299
|
+
uncoveredGates(workIds, changes, finalShas) {
|
|
1272
1300
|
return this.read((v) => {
|
|
1273
1301
|
const works = workIds.map((id) => v.work(id)).filter((w) => !!w);
|
|
1274
1302
|
const repositories = [...new Set(works.map((w) => w.order.repositoryId))].map((id) => this.repository(id));
|
|
@@ -1282,7 +1310,7 @@ export class Engine {
|
|
|
1282
1310
|
.attempts(w.id)
|
|
1283
1311
|
.filter((a) => a.policyDigest === this.host.basis.policyDigest(w, v))
|
|
1284
1312
|
.flatMap((a) => a.evidence),
|
|
1285
|
-
})));
|
|
1313
|
+
})), changes, finalShas);
|
|
1286
1314
|
});
|
|
1287
1315
|
}
|
|
1288
1316
|
/**
|
|
@@ -1436,6 +1464,42 @@ export class Engine {
|
|
|
1436
1464
|
// доказывала бы его (и названный testcase).
|
|
1437
1465
|
if ((evidence.kind === 'review') !== (evidence.gate === 'independent-review'))
|
|
1438
1466
|
throw new HarnessError('INVALID_INPUT', `Evidence вида ${evidence.kind} не может относиться к gate ${evidence.gate}`);
|
|
1467
|
+
// Неприменимость (`when.paths`) — только у gate с `when` области
|
|
1468
|
+
// попытки, под его текущим определением, без исполнения и не PASS;
|
|
1469
|
+
// сведения о ней — только у такой записи.
|
|
1470
|
+
if ((evidence.kind === 'not-applicable') !== (evidence.notApplicable !== undefined))
|
|
1471
|
+
throw new HarnessError('INVALID_INPUT', 'Сведения о неприменимости — только у записи вида not-applicable');
|
|
1472
|
+
if (evidence.kind === 'not-applicable') {
|
|
1473
|
+
const problem = evidence.passed ||
|
|
1474
|
+
evidence.consumer !== undefined ||
|
|
1475
|
+
evidence.recheck !== undefined ||
|
|
1476
|
+
evidence.tests !== undefined ||
|
|
1477
|
+
evidence.property !== undefined ||
|
|
1478
|
+
evidence.artifactFiles !== undefined ||
|
|
1479
|
+
!(a.requiredGates ?? []).includes(evidence.gate)
|
|
1480
|
+
? 'запись неприменимости не может быть PASS, исполнением или gate вне области'
|
|
1481
|
+
: // Решение — о SHA текущей фазы, diff заканчивается на нём.
|
|
1482
|
+
evidence.sha !==
|
|
1483
|
+
(evidence.phase === 'candidate' ? a.candidateSha : a.integrationSha) ||
|
|
1484
|
+
evidence.notApplicable.ranges.at(-1)?.to !== evidence.sha
|
|
1485
|
+
? 'запись неприменимости не относится к SHA фазы попытки'
|
|
1486
|
+
: // Исполненный gate не становится неприменимым на том же SHA.
|
|
1487
|
+
a.evidence.some((e) => e.kind === 'test' &&
|
|
1488
|
+
e.gate === evidence.gate &&
|
|
1489
|
+
e.phase === evidence.phase &&
|
|
1490
|
+
e.sha === evidence.sha &&
|
|
1491
|
+
e.consumer === undefined)
|
|
1492
|
+
? 'gate уже исполнялся на этом SHA: запись неприменимости не заменяет его исход'
|
|
1493
|
+
: notApplicableProblem({
|
|
1494
|
+
gates: this.repository(a.repositoryId).gates,
|
|
1495
|
+
gate: evidence.gate,
|
|
1496
|
+
record: evidence,
|
|
1497
|
+
proof: proofGates(w.order, contractDocuments(w.order, tx)),
|
|
1498
|
+
ran: [],
|
|
1499
|
+
});
|
|
1500
|
+
if (problem)
|
|
1501
|
+
throw new HarnessError('INVALID_INPUT', problem);
|
|
1502
|
+
}
|
|
1439
1503
|
// Повтор ссылается на провал того же gate этой попытки на том же SHA, и
|
|
1440
1504
|
// попытка повторяет не больше одного провала на фазу.
|
|
1441
1505
|
if (evidence.recheck) {
|
|
@@ -1489,6 +1553,7 @@ export class Engine {
|
|
|
1489
1553
|
passed: record.passed,
|
|
1490
1554
|
evidenceId: record.id,
|
|
1491
1555
|
...(record.consumer ? { consumer: record.consumer } : {}),
|
|
1556
|
+
...(record.kind === 'not-applicable' ? { notApplicable: true } : {}),
|
|
1492
1557
|
...(record.recheck ? { recheck: record.recheck } : {}),
|
|
1493
1558
|
},
|
|
1494
1559
|
});
|
|
@@ -1516,16 +1581,42 @@ export class Engine {
|
|
|
1516
1581
|
// попытка: новый корпус, принятый поручением, требует новой попытки.
|
|
1517
1582
|
if (a.checks && this.checksOf(w, tx) !== a.checks.effective)
|
|
1518
1583
|
throw new HarnessError('APPROVAL_STALE', 'Версия проверок поручения изменилась; нужна новая попытка');
|
|
1519
|
-
const
|
|
1584
|
+
const decisive = (kinds, phase, at, gate) => a.evidence.findLast((e) => kinds.includes(e.kind) &&
|
|
1520
1585
|
e.phase === phase &&
|
|
1521
1586
|
e.sha === at &&
|
|
1522
1587
|
e.gate === gate &&
|
|
1523
1588
|
e.consumer === undefined &&
|
|
1524
|
-
(!a.checks || e.checks === a.checks.effective))
|
|
1589
|
+
(!a.checks || e.checks === a.checks.effective));
|
|
1590
|
+
const last = (kind, phase, at, gate) => decisive([kind], phase, at, gate)?.passed === true;
|
|
1591
|
+
// Обязательный gate закрыт PASS или — только обычный gate с `when` —
|
|
1592
|
+
// записью неприменимости под текущим определением (`notApplicableProblem`).
|
|
1593
|
+
const repoGates = this.repository(a.repositoryId).gates;
|
|
1594
|
+
const named = proofGates(w.order, contractDocuments(w.order, tx));
|
|
1595
|
+
const shaOf = (phase) => phase === 'candidate' ? a.candidateSha : sha;
|
|
1596
|
+
const ran = Object.fromEntries(['candidate', 'integration'].map((phase) => [
|
|
1597
|
+
phase,
|
|
1598
|
+
(a.requiredGates ?? []).filter((gate) => decisive(['test'], phase, shaOf(phase), gate) !== undefined),
|
|
1599
|
+
]));
|
|
1525
1600
|
for (const gate of a.requiredGates ?? [])
|
|
1526
|
-
for (const phase of ['candidate', 'integration'])
|
|
1527
|
-
|
|
1528
|
-
|
|
1601
|
+
for (const phase of ['candidate', 'integration']) {
|
|
1602
|
+
// Исход исполнения решает всегда; неприменимость — только без него.
|
|
1603
|
+
const record = decisive(['test'], phase, shaOf(phase), gate) ??
|
|
1604
|
+
decisive(['not-applicable'], phase, shaOf(phase), gate);
|
|
1605
|
+
if (record?.kind === 'test' && record.passed)
|
|
1606
|
+
continue;
|
|
1607
|
+
const problem = record?.kind === 'not-applicable'
|
|
1608
|
+
? notApplicableProblem({
|
|
1609
|
+
gates: repoGates,
|
|
1610
|
+
gate,
|
|
1611
|
+
record,
|
|
1612
|
+
proof: named,
|
|
1613
|
+
ran: ran[phase],
|
|
1614
|
+
})
|
|
1615
|
+
: 'нет записи';
|
|
1616
|
+
if (problem)
|
|
1617
|
+
throw new HarnessError('GATE_FAILED', `Нет PASS: ${phase}/${gate}` +
|
|
1618
|
+
(record?.kind === 'not-applicable' ? ': ' + problem : ''));
|
|
1619
|
+
}
|
|
1529
1620
|
for (const phase of ['candidate', 'integration'])
|
|
1530
1621
|
if (!last('review', phase, phase === 'candidate' ? a.candidateSha : sha, 'independent-review'))
|
|
1531
1622
|
throw new HarnessError('REVIEW_REJECTED', `Нет независимого ревью: ${phase}`);
|
package/lib/engine/result.js
CHANGED
|
@@ -24,9 +24,11 @@ const ref = (e, attempt) => ({
|
|
|
24
24
|
id: e.id,
|
|
25
25
|
kind: e.kind === 'review'
|
|
26
26
|
? 'review'
|
|
27
|
-
: e.
|
|
28
|
-
? '
|
|
29
|
-
:
|
|
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
|
package/lib/engine/runner.d.ts
CHANGED
|
@@ -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. Проверка потребителя исполняет
|
package/lib/engine/runner.js
CHANGED
|
@@ -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, providerMovement, } 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
|
-
|
|
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,102 @@ 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
|
+
// Снимок провайдеров текущей попытки — закреплённый в хранилище до реализации.
|
|
1751
|
+
const providers = this.engine.read((v) => v.attempt(attempt.id)?.dependencies);
|
|
1752
|
+
const diffs = new Map();
|
|
1753
|
+
const changed = new Map();
|
|
1754
|
+
const moved = new Map();
|
|
1755
|
+
for (const gate of gates) {
|
|
1756
|
+
if (!gate.when || proof.has(gate.id))
|
|
1757
|
+
continue;
|
|
1758
|
+
const basis = gateBasis(this.policy, repo, gate, this.engine.version);
|
|
1759
|
+
const passed = greens.filter((x) => x.evidence.some((e) => e.kind === 'test' &&
|
|
1760
|
+
e.phase === 'integration' &&
|
|
1761
|
+
e.sha === x.integrationSha &&
|
|
1762
|
+
e.gate === gate.id &&
|
|
1763
|
+
e.consumer === undefined &&
|
|
1764
|
+
e.passed &&
|
|
1765
|
+
e.gateBasis === basis));
|
|
1766
|
+
const shas = [...new Set(passed.map((x) => x.integrationSha))].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
|
+
// Gate потребителя зависит и от провайдеров: их база с зелёного SHA
|
|
1776
|
+
// сравнивается со снимком попытки (`providerMovement`).
|
|
1777
|
+
const green = passed.find((x) => x.integrationSha === anchor);
|
|
1778
|
+
moved.set(gate.id, providerMovement(repo.dependsOn, green.dependencies, providers));
|
|
1779
|
+
if (!diffs.has(anchor))
|
|
1780
|
+
diffs.set(anchor, await changedPaths(cwd, [
|
|
1781
|
+
{ from: anchor, to: candidate },
|
|
1782
|
+
...(phase === 'integration' ? [{ from: anchor, to: sha }] : []),
|
|
1783
|
+
]));
|
|
1784
|
+
changed.set(gate.id, diffs.get(anchor));
|
|
1785
|
+
}
|
|
1786
|
+
const decisions = gateDecisions({
|
|
1787
|
+
repo,
|
|
1788
|
+
scope: gates,
|
|
1789
|
+
proof,
|
|
1790
|
+
changedFor: (gate) => changed.get(gate.id),
|
|
1791
|
+
providersMoved: (gate) => moved.get(gate.id),
|
|
1792
|
+
});
|
|
1793
|
+
for (const d of decisions)
|
|
1794
|
+
if (!d.run && d.record)
|
|
1795
|
+
this.engine.evidence(attempt.id, attempt.token, {
|
|
1796
|
+
kind: 'not-applicable',
|
|
1797
|
+
phase,
|
|
1798
|
+
sha,
|
|
1799
|
+
gate: d.gate.id,
|
|
1800
|
+
passed: false,
|
|
1801
|
+
command: [],
|
|
1802
|
+
exitCode: -1,
|
|
1803
|
+
log: '',
|
|
1804
|
+
digest: digestOf(d.record),
|
|
1805
|
+
summary: `Не применим: diff фазы (${d.record.count} путей) не задел when.paths и неявные входы gate`,
|
|
1806
|
+
notApplicable: d.record,
|
|
1807
|
+
});
|
|
1808
|
+
return decisions.filter((d) => d.run).map((d) => d.gate);
|
|
1809
|
+
}
|
|
1725
1810
|
async runOneGate(attempt, cwd, sha, phase, gate, artifacts, signal, execution, consumer, recheck) {
|
|
1726
1811
|
// Генеративный gate — всегда; gate эталонных наборов — когда манифест
|
|
1727
1812
|
// поручения ждёт от него отчёта (без договора — прежний уровень).
|
|
1728
1813
|
const run = this.propertyRun(attempt, gate, consumer);
|
|
1729
1814
|
const property = gate.property || expectsReference(run.expected) ? run : undefined;
|
|
1815
|
+
const basis = gate.when && !consumer
|
|
1816
|
+
? {
|
|
1817
|
+
gateBasis: gateBasis(this.policy, this.repo(attempt.repositoryId), gate, this.engine.version),
|
|
1818
|
+
}
|
|
1819
|
+
: {};
|
|
1730
1820
|
await runGate({
|
|
1731
1821
|
policy: this.policy,
|
|
1732
|
-
record: (e) => this.engine.evidence(attempt.id, attempt.token, e),
|
|
1822
|
+
record: (e) => this.engine.evidence(attempt.id, attempt.token, { ...e, ...basis }),
|
|
1733
1823
|
cwd,
|
|
1734
1824
|
sha,
|
|
1735
1825
|
phase,
|
|
@@ -2496,6 +2586,8 @@ export class Runner {
|
|
|
2496
2586
|
passed: e.passed,
|
|
2497
2587
|
summary: e.summary,
|
|
2498
2588
|
...(e.consumer ? { consumer: e.consumer } : {}),
|
|
2589
|
+
// Gate не исполнялся по when.paths: не провал и не PASS.
|
|
2590
|
+
...(e.kind === 'not-applicable' ? { notApplicable: true } : {}),
|
|
2499
2591
|
}))), '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
2592
|
}
|
|
2501
2593
|
const r = v.work(attempt.workId)?.recovery;
|
|
@@ -2650,7 +2742,8 @@ export class Runner {
|
|
|
2650
2742
|
await runSteps(repo.prepare, cwd, join(artifacts, 'integration', 'prepare'), execution, signal, attempt.baseSha);
|
|
2651
2743
|
prepared(execution);
|
|
2652
2744
|
const budget = { recheck: true };
|
|
2653
|
-
|
|
2745
|
+
const applicable = await this.applicableGates(attempt, work, repo, gates, 'integration', cwd, sha, attempt.baseSha);
|
|
2746
|
+
for (const gate of applicable)
|
|
2654
2747
|
await this.integrationGate(attempt, cwd, sha, gate, artifacts, signal, execution, budget);
|
|
2655
2748
|
await this.consumers(attempt, cwd, sha, artifacts, signal);
|
|
2656
2749
|
this.requirements(attempt, work, repoPath, cwd, sha, 'integration');
|
|
@@ -19,6 +19,9 @@ import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
|
19
19
|
* исполняемые настройки, которые git читает сам.
|
|
20
20
|
*/
|
|
21
21
|
export const gitHardening = [
|
|
22
|
+
// Объекты замены (`refs/replace/*`) пишет любой, кто пишет в репозиторий:
|
|
23
|
+
// git хоста читает только настоящие объекты (diff, требования, области).
|
|
24
|
+
'--no-replace-objects',
|
|
22
25
|
'-c',
|
|
23
26
|
// Older Git treats 'false' as a hook executable; empty disables the hook
|
|
24
27
|
// there and is false for versions supporting the built-in fsmonitor.
|
|
@@ -59,6 +59,8 @@ export declare function hostGitArgs(cwd: string, args: string[]): string[];
|
|
|
59
59
|
* содержимого файла, которое разбирают, усечение незаметно и опасно.
|
|
60
60
|
*/
|
|
61
61
|
export declare function gitOutput(cwd: string, ...args: string[]): Promise<string>;
|
|
62
|
+
/** Вывод git целиком и без обрезки пробелов: для `-z`-списков путей. */
|
|
63
|
+
export declare function gitRawOutput(cwd: string, ...args: string[]): Promise<string>;
|
|
62
64
|
/**
|
|
63
65
|
* Содержимое объектов git одним `cat-file --batch`: байты, без усечения и
|
|
64
66
|
* без процесса на объект. Отсутствующий объект — отказ.
|
|
@@ -264,6 +264,8 @@ export function hostGitArgs(cwd, args) {
|
|
|
264
264
|
const gitEnv = () => ({
|
|
265
265
|
...process.env,
|
|
266
266
|
GIT_TERMINAL_PROMPT: '0',
|
|
267
|
+
// Дублирует `--no-replace-objects` из `gitHardening` для дочерних git.
|
|
268
|
+
GIT_NO_REPLACE_OBJECTS: '1',
|
|
267
269
|
GIT_AUTHOR_NAME: 'devcontour-harness',
|
|
268
270
|
GIT_AUTHOR_EMAIL: 'harness@localhost',
|
|
269
271
|
GIT_COMMITTER_NAME: 'devcontour-harness',
|
|
@@ -274,6 +276,10 @@ const gitEnv = () => ({
|
|
|
274
276
|
* содержимого файла, которое разбирают, усечение незаметно и опасно.
|
|
275
277
|
*/
|
|
276
278
|
export async function gitOutput(cwd, ...args) {
|
|
279
|
+
return (await gitRawOutput(cwd, ...args)).trim();
|
|
280
|
+
}
|
|
281
|
+
/** Вывод git целиком и без обрезки пробелов: для `-z`-списков путей. */
|
|
282
|
+
export async function gitRawOutput(cwd, ...args) {
|
|
277
283
|
let text = '';
|
|
278
284
|
const result = await command(['git', ...hostGitArgs(cwd, args)], cwd, {
|
|
279
285
|
env: gitEnv(),
|
|
@@ -283,7 +289,7 @@ export async function gitOutput(cwd, ...args) {
|
|
|
283
289
|
});
|
|
284
290
|
if (result.code !== 0)
|
|
285
291
|
throw new Error(`git ${args[0]}: ${result.stderr.trim()}`);
|
|
286
|
-
return text
|
|
292
|
+
return text;
|
|
287
293
|
}
|
|
288
294
|
/**
|
|
289
295
|
* Содержимое объектов git одним `cat-file --batch`: байты, без усечения и
|
package/lib/explain/state.js
CHANGED
|
@@ -322,7 +322,7 @@ export function stopInputsOf(h, options) {
|
|
|
322
322
|
? [
|
|
323
323
|
{ kind: 'attempt', id: last.id },
|
|
324
324
|
...last.evidence
|
|
325
|
-
.filter((e) => !e.passed)
|
|
325
|
+
.filter((e) => !e.passed && e.kind !== 'not-applicable')
|
|
326
326
|
.map((e) => ({ kind: 'evidence', id: e.id, sha: e.sha })),
|
|
327
327
|
]
|
|
328
328
|
: [];
|
package/lib/handoff/pack.js
CHANGED
|
@@ -374,7 +374,13 @@ function build(h, options, maxBytes, measure) {
|
|
|
374
374
|
const repairsAll = h.workflows
|
|
375
375
|
.list()
|
|
376
376
|
.filter((j) => j.kind === 'graph' && graphIds.has(j.id) && j.status !== 'completed')
|
|
377
|
-
.map((j) => ({
|
|
377
|
+
.map((j) => ({
|
|
378
|
+
graphId: j.id,
|
|
379
|
+
key: j.key,
|
|
380
|
+
status: j.status,
|
|
381
|
+
used: j.repairs ?? 0,
|
|
382
|
+
budget: repairBudget,
|
|
383
|
+
}));
|
|
378
384
|
const repairs = repairsAll.slice(0, HANDOFF_LIMITS.repairs);
|
|
379
385
|
const controller = status.controller
|
|
380
386
|
? {
|
package/lib/index.d.ts
CHANGED
|
@@ -69,6 +69,7 @@ export { runGatesAt, type GatesAtContext, type GatesAtInput, type GatesAtResult,
|
|
|
69
69
|
export { dependencyStoreRoot, materializeStore, type StoreContext, type StoreReceipt, } from './verification/dependency-store.ts';
|
|
70
70
|
export { explicitPrerequisites, gatePrerequisites, orderedScope, standaloneScope, } from './verification/gate-scope.ts';
|
|
71
71
|
export { requirementProof, uncoveredGates, unprovenReason } from './verification/proof.ts';
|
|
72
|
+
export { changedPaths, coverageChanges, gateBasis, gateDecisions, gatePathRegExp, matchingPaths, notApplicableProblem, pathApplicability, proofGates, providerMovement, type ChangedPaths, type GateDecision, type PathDecision, type ProviderSnapshot, } from './verification/applicability.ts';
|
|
72
73
|
export { ReviewProbes, probeLimits, observeReproductions } from './agents/review-probe.ts';
|
|
73
74
|
export { composeRedactors, outputRedactor,
|
|
74
75
|
/**
|
package/lib/index.js
CHANGED
|
@@ -69,6 +69,7 @@ export { runGatesAt, } from "./verification/gates-at.js";
|
|
|
69
69
|
export { dependencyStoreRoot, materializeStore, } from "./verification/dependency-store.js";
|
|
70
70
|
export { explicitPrerequisites, gatePrerequisites, orderedScope, standaloneScope, } from "./verification/gate-scope.js";
|
|
71
71
|
export { requirementProof, uncoveredGates, unprovenReason } from "./verification/proof.js";
|
|
72
|
+
export { changedPaths, coverageChanges, gateBasis, gateDecisions, gatePathRegExp, matchingPaths, notApplicableProblem, pathApplicability, proofGates, providerMovement, } from "./verification/applicability.js";
|
|
72
73
|
export { ReviewProbes, probeLimits, observeReproductions } from "./agents/review-probe.js";
|
|
73
74
|
export { composeRedactors, outputRedactor,
|
|
74
75
|
/**
|
|
@@ -466,7 +466,7 @@ export class HistoryRecorder {
|
|
|
466
466
|
return { status: 'none' };
|
|
467
467
|
const gates = result.evidence
|
|
468
468
|
.filter((e) => e.kind !== 'review')
|
|
469
|
-
.map((e) => `${e.gate} [${e.phase}] ${e.passed ? 'passed' : 'failed'} @ ${e.sha.slice(0, 12)}`)
|
|
469
|
+
.map((e) => `${e.gate} [${e.phase}] ${e.kind === 'not-applicable' ? 'not applicable' : e.passed ? 'passed' : 'failed'} @ ${e.sha.slice(0, 12)}`)
|
|
470
470
|
.join('\n');
|
|
471
471
|
const accepted = result.outcome === 'accepted';
|
|
472
472
|
const body = accepted
|
|
@@ -12,7 +12,8 @@ export function summaryText(input) {
|
|
|
12
12
|
const tests = e.tests
|
|
13
13
|
? ` (${e.tests.filter((t) => t.status === 'passed').length}/${e.tests.length} тестов)`
|
|
14
14
|
: '';
|
|
15
|
-
|
|
15
|
+
const outcome = e.kind === 'not-applicable' ? 'not applicable' : e.passed ? 'passed' : 'failed';
|
|
16
|
+
return `- ${e.gate} [${e.phase}]: ${outcome}${tests} @ ${shortSha(e.sha)}`;
|
|
16
17
|
});
|
|
17
18
|
const reviews = r.evidence.filter((e) => e.kind === 'review');
|
|
18
19
|
const lines = [
|
|
@@ -126,6 +126,9 @@ export declare function repositoryFromProfile(profile: ResolvedProfile, own: Pic
|
|
|
126
126
|
command: string[];
|
|
127
127
|
timeoutMs: number;
|
|
128
128
|
artifacts?: string[] | undefined;
|
|
129
|
+
when?: {
|
|
130
|
+
paths: string[];
|
|
131
|
+
} | undefined;
|
|
129
132
|
property?: {
|
|
130
133
|
path?: string | undefined;
|
|
131
134
|
} | undefined;
|
|
@@ -142,6 +145,9 @@ export declare function repositoryFromProfile(profile: ResolvedProfile, own: Pic
|
|
|
142
145
|
path: string;
|
|
143
146
|
} | undefined;
|
|
144
147
|
artifacts?: string[] | undefined;
|
|
148
|
+
when?: {
|
|
149
|
+
paths: string[];
|
|
150
|
+
} | undefined;
|
|
145
151
|
property?: {
|
|
146
152
|
path?: string | undefined;
|
|
147
153
|
} | undefined;
|
|
@@ -24,7 +24,7 @@ export interface AttemptViewInput {
|
|
|
24
24
|
candidateSha?: string;
|
|
25
25
|
integrationSha?: string;
|
|
26
26
|
evidence: readonly {
|
|
27
|
-
kind: 'test' | 'review';
|
|
27
|
+
kind: 'test' | 'review' | 'not-applicable';
|
|
28
28
|
phase: 'candidate' | 'integration';
|
|
29
29
|
sha: string;
|
|
30
30
|
gate: string;
|
|
@@ -94,7 +94,7 @@ export interface AttemptView {
|
|
|
94
94
|
* Обязательные gates текущей фазы (интеграции — в `integrating`, иначе
|
|
95
95
|
* кандидата) по последней записи каждого gate на текущем SHA фазы, без
|
|
96
96
|
* проверок потребителей: прошли, не прошли, ещё без записи. Записи других
|
|
97
|
-
* gates и других SHA не считаются: `passed + failed + remaining = required`.
|
|
97
|
+
* gates и других SHA не считаются: `passed + failed + remaining (+ notApplicable) = required`.
|
|
98
98
|
*/
|
|
99
99
|
gates: {
|
|
100
100
|
phase: 'candidate' | 'integration';
|
|
@@ -102,6 +102,8 @@ export interface AttemptView {
|
|
|
102
102
|
passed: number;
|
|
103
103
|
failed: number;
|
|
104
104
|
remaining: number;
|
|
105
|
+
/** Не исполнены по `when.paths` (нет поля — таких нет); входят в `required`. */
|
|
106
|
+
notApplicable?: number;
|
|
105
107
|
};
|
|
106
108
|
/**
|
|
107
109
|
* Живость по последнему переходу обхода controller: `quiet` и `stalled`
|
|
@@ -15,6 +15,16 @@ export function attemptView(input, options) {
|
|
|
15
15
|
const sha = phase === 'integration' ? input.integrationSha : input.candidateSha;
|
|
16
16
|
const required = [...new Set(input.requiredGates ?? options.repositoryGates ?? [])];
|
|
17
17
|
const latest = new Map();
|
|
18
|
+
// Gate, не исполненный по `when.paths`: ни PASS, ни провал, но и не ждёт.
|
|
19
|
+
const notApplicable = new Set();
|
|
20
|
+
for (const e of input.evidence)
|
|
21
|
+
if (e.kind === 'not-applicable' &&
|
|
22
|
+
e.phase === phase &&
|
|
23
|
+
!e.consumer &&
|
|
24
|
+
sha !== undefined &&
|
|
25
|
+
e.sha === sha &&
|
|
26
|
+
required.includes(e.gate))
|
|
27
|
+
notApplicable.add(e.gate);
|
|
18
28
|
for (const e of input.evidence)
|
|
19
29
|
if (e.kind === 'test' &&
|
|
20
30
|
e.phase === phase &&
|
|
@@ -58,7 +68,10 @@ export function attemptView(input, options) {
|
|
|
58
68
|
required: required.length,
|
|
59
69
|
passed,
|
|
60
70
|
failed: latest.size - passed,
|
|
61
|
-
remaining: required.filter((g) => !latest.has(g)).length,
|
|
71
|
+
remaining: required.filter((g) => !latest.has(g) && !notApplicable.has(g)).length,
|
|
72
|
+
...(notApplicable.size
|
|
73
|
+
? { notApplicable: [...notApplicable].filter((g) => !latest.has(g)).length }
|
|
74
|
+
: {}),
|
|
62
75
|
},
|
|
63
76
|
...(input.liveness
|
|
64
77
|
? {
|
package/lib/report/compute.js
CHANGED
|
@@ -401,7 +401,8 @@ export function valueReport(input, options = {}) {
|
|
|
401
401
|
const defectAttempts = windowAttempts.filter((a) => failureBucketOf(a) === 'defect');
|
|
402
402
|
const failingOf = (a) => {
|
|
403
403
|
const kind = a.failureKind === 'gate' ? 'test' : a.failureKind === 'review' ? 'review' : null;
|
|
404
|
-
|
|
404
|
+
// Неприменимый gate (`when.paths`) не исполнялся и провалом не считается.
|
|
405
|
+
return a.evidence.filter((e) => !e.passed && e.kind !== 'not-applicable' && (kind === null || e.kind === kind));
|
|
405
406
|
};
|
|
406
407
|
const byKind = { gate: 0, review: 0, 'scope-violation': 0 };
|
|
407
408
|
const byPhase = { candidate: 0, integration: 0, unknown: 0 };
|
|
@@ -444,12 +445,12 @@ export function valueReport(input, options = {}) {
|
|
|
444
445
|
for (const e of a.evidence) {
|
|
445
446
|
if (e.kind !== 'review' || e.phase !== 'candidate')
|
|
446
447
|
continue;
|
|
447
|
-
|
|
448
|
+
// Неприменимый gate (`when.paths`) зелёного состава не нарушает.
|
|
449
|
+
const allGreen = required.every((g) => a.evidence.some((x) => (x.kind === 'not-applicable' || (x.kind === 'test' && x.passed)) &&
|
|
448
450
|
x.phase === 'candidate' &&
|
|
449
451
|
!x.consumer &&
|
|
450
452
|
x.gate === g &&
|
|
451
453
|
x.sha === e.sha &&
|
|
452
|
-
x.passed &&
|
|
453
454
|
(x.checks === undefined || e.checks === undefined || x.checks === e.checks)));
|
|
454
455
|
if (!allGreen)
|
|
455
456
|
continue;
|