devcontour-harness 0.1.0-alpha.42 → 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.
- package/README.md +16 -2
- package/docs/architecture.md +38 -3
- package/docs/contracts.md +10 -2
- package/docs/release-notes/0.1.0-alpha.43.md +40 -0
- package/docs/release-notes/0.1.0-alpha.44.md +44 -0
- package/docs/upgrade.md +65 -17
- package/lib/contracts/cli.d.ts +48 -4
- package/lib/contracts/events.d.ts +60 -5
- package/lib/contracts/events.js +16 -1
- package/lib/contracts/execution.d.ts +37 -0
- package/lib/contracts/execution.js +20 -0
- package/lib/contracts/published.d.ts +28 -2
- package/lib/contracts/report.d.ts +8 -0
- package/lib/contracts/report.js +7 -1
- package/lib/contracts/result.d.ts +2 -0
- package/lib/contracts/result.js +6 -0
- package/lib/control/harness.d.ts +5 -0
- package/lib/engine/engine.d.ts +36 -3
- package/lib/engine/engine.js +117 -16
- package/lib/engine/joint-runner.d.ts +2 -0
- package/lib/engine/joint-runner.js +13 -3
- package/lib/environment/isolation.d.ts +1 -1
- package/lib/environment/isolation.js +38 -4
- package/lib/report/compute.js +3 -0
- package/lib/report/document.js +1 -1
- package/lib/storage/document.d.ts +2 -0
- package/lib/testing/store-contract.d.ts +8 -2
- package/lib/testing/store-contract.js +56 -1
- package/lib/verification/joint.d.ts +179 -1
- package/lib/verification/joint.js +23 -3
- package/package.json +1 -1
- package/schemas/execution-document.schema.json +4 -0
- package/schemas/joint-verification.schema.json +4 -0
- package/schemas/run-event.schema.json +96 -0
- package/schemas/value-report.schema.json +20 -0
package/lib/engine/engine.js
CHANGED
|
@@ -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,
|
|
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();
|
|
@@ -3271,18 +3271,11 @@ export class Engine {
|
|
|
3271
3271
|
continue;
|
|
3272
3272
|
if (v.leaseUntil > this.now())
|
|
3273
3273
|
throw new HarnessError('NOT_READY', 'Совместная проверка уже выполняется');
|
|
3274
|
-
|
|
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
|
-
});
|
|
3274
|
+
this.closeExpiredJoint(tx, v);
|
|
3280
3275
|
}
|
|
3281
|
-
const
|
|
3282
|
-
|
|
3283
|
-
|
|
3284
|
-
if (previous.length >= this.policy.maxAttempts)
|
|
3285
|
-
throw new HarnessError('ATTEMPTS_EXHAUSTED', 'Исчерпан предел совместных проверок этого набора');
|
|
3276
|
+
const exhausted = this.jointExhausted(tx, input.workIds);
|
|
3277
|
+
if (exhausted)
|
|
3278
|
+
throw new HarnessError('ATTEMPTS_EXHAUSTED', exhausted);
|
|
3286
3279
|
const works = input.workIds.map((id) => tx.work(id));
|
|
3287
3280
|
if (works.some((w) => !w || w.status !== 'done' || !w.resultSha))
|
|
3288
3281
|
throw new HarnessError('NOT_READY', 'Сначала завершите все поручения набора');
|
|
@@ -3414,21 +3407,129 @@ export class Engine {
|
|
|
3414
3407
|
return publicJoint(next);
|
|
3415
3408
|
});
|
|
3416
3409
|
}
|
|
3417
|
-
/**
|
|
3418
|
-
|
|
3410
|
+
/**
|
|
3411
|
+
* Отказ проверки её владельцем; истёкший срок допустим, чужой токен — нет.
|
|
3412
|
+
* `interrupted` — проверку прервали остановка или потеря владения; движок
|
|
3413
|
+
* отмечает её прерванной только без evidence: результат gate тратит предел.
|
|
3414
|
+
*/
|
|
3415
|
+
jointFail(id, token, error, options = {}) {
|
|
3419
3416
|
return this.tx('workspace.failed', (tx) => {
|
|
3420
3417
|
const v = tx.verification(id);
|
|
3421
3418
|
if (!v || v.status !== 'active' || v.token !== token || v.engineVersion !== this.version)
|
|
3422
3419
|
return false;
|
|
3423
3420
|
const message = error.slice(0, 4000) || 'Совместная проверка не прошла';
|
|
3424
|
-
|
|
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
|
+
});
|
|
3425
3429
|
tx.emit({
|
|
3426
3430
|
type: 'joint.finished',
|
|
3427
|
-
payload: { verificationId: id, status: 'failed', error: message },
|
|
3431
|
+
payload: { verificationId: id, status: 'failed', error: message, ...interrupted },
|
|
3428
3432
|
});
|
|
3429
3433
|
return true;
|
|
3430
3434
|
});
|
|
3431
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
|
+
}
|
|
3432
3533
|
/**
|
|
3433
3534
|
* Актуальный результат совместной проверки набора: последняя проверка этого
|
|
3434
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, 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
|
-
|
|
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);
|
|
@@ -277,7 +277,7 @@ export declare function protectedChanges(before: Map<string, string>, root: stri
|
|
|
277
277
|
/**
|
|
278
278
|
* Пути относительно `root`, которыми владеет подготовка фазы (вложенные
|
|
279
279
|
* `.git`, см. `preparationGuard`): не в счёт только их исчезновение
|
|
280
|
-
* (уборка фикстуры переносом
|
|
280
|
+
* (уборка фикстуры переносом родителя, см. `removedInPlace`). Изменение — в том числе подмена
|
|
281
281
|
* переносом другого `.git` на то же место — нарушение: подменённый
|
|
282
282
|
* `gitdir` подмодуля git хоста прочитал бы при следующей команде.
|
|
283
283
|
*/
|
|
@@ -744,9 +744,13 @@ export function protectedSnapshot(root) {
|
|
|
744
744
|
if (stat.isSymbolicLink())
|
|
745
745
|
return 'l:' + readlinkSync(path);
|
|
746
746
|
// Не каталог и не ссылка — файл, FIFO, сокет, устройство: всё это
|
|
747
|
-
// содержимое, пустым деревом не бывает.
|
|
747
|
+
// содержимое, пустым деревом не бывает. mtime возвращает `utimes`,
|
|
748
|
+
// ctime — нет: правка на месте в перенесённом наружу родителе с
|
|
749
|
+
// восстановленными размером и mtime всё равно меняет подпись. Ту же
|
|
750
|
+
// ctime меняют chmod/chown и новая жёсткая ссылка на файл — для
|
|
751
|
+
// защищённой конфигурации это тоже изменение.
|
|
748
752
|
if (!stat.isDirectory())
|
|
749
|
-
return `f:${stat.size}:${stat.mtimeMs}:${stat.ino}`;
|
|
753
|
+
return `f:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.ino}`;
|
|
750
754
|
const mode = stat.mode & 0o7777;
|
|
751
755
|
const names = readdirSync(path).sort();
|
|
752
756
|
const inner = names.map((name) => signature(join(path, name)));
|
|
@@ -802,6 +806,36 @@ export function protectedSnapshot(root) {
|
|
|
802
806
|
walk(root);
|
|
803
807
|
return found;
|
|
804
808
|
}
|
|
809
|
+
/**
|
|
810
|
+
* Исчез ли `path` из дерева сам, а не скрылся за подменённым родителем.
|
|
811
|
+
*
|
|
812
|
+
* Снимок не спускается в символьные ссылки на каталоги: родитель `sub`,
|
|
813
|
+
* перенесённый наружу и заменённый ссылкой на каталог вне дерева с другим
|
|
814
|
+
* `.git`, выглядел бы как исчезновение `sub/.git`, а git хоста прочитал бы
|
|
815
|
+
* подменённый `gitdir` через ссылку. Исчезновением считается только путь,
|
|
816
|
+
* у которого цепочка родителей от `root` — настоящие каталоги до первого
|
|
817
|
+
* отсутствующего звена (родитель удалён или перенесён наружу) или до
|
|
818
|
+
* самого пути. Ссылка или не каталог на месте родителя — подмена.
|
|
819
|
+
*/
|
|
820
|
+
function removedInPlace(root, path) {
|
|
821
|
+
const parts = relative(root, path).split(sep).slice(0, -1);
|
|
822
|
+
let dir = root;
|
|
823
|
+
for (const part of parts) {
|
|
824
|
+
dir = join(dir, part);
|
|
825
|
+
let stat;
|
|
826
|
+
try {
|
|
827
|
+
stat = lstatSync(dir);
|
|
828
|
+
}
|
|
829
|
+
catch (error) {
|
|
830
|
+
if (missing(error))
|
|
831
|
+
return true;
|
|
832
|
+
return unreadable(root, dir, error);
|
|
833
|
+
}
|
|
834
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
835
|
+
return false;
|
|
836
|
+
}
|
|
837
|
+
return true;
|
|
838
|
+
}
|
|
805
839
|
/**
|
|
806
840
|
* Защищённые пути, которые появились или изменились после снимка `before`.
|
|
807
841
|
*
|
|
@@ -823,13 +857,13 @@ export function protectedChanges(before, root,
|
|
|
823
857
|
/**
|
|
824
858
|
* Пути относительно `root`, которыми владеет подготовка фазы (вложенные
|
|
825
859
|
* `.git`, см. `preparationGuard`): не в счёт только их исчезновение
|
|
826
|
-
* (уборка фикстуры переносом
|
|
860
|
+
* (уборка фикстуры переносом родителя, см. `removedInPlace`). Изменение — в том числе подмена
|
|
827
861
|
* переносом другого `.git` на то же место — нарушение: подменённый
|
|
828
862
|
* `gitdir` подмодуля git хоста прочитал бы при следующей команде.
|
|
829
863
|
*/
|
|
830
864
|
owned) {
|
|
831
865
|
const after = protectedSnapshot(root);
|
|
832
|
-
const mine = (path) => !owned?.has(relative(root, path));
|
|
866
|
+
const mine = (path) => !owned?.has(relative(root, path)) || !removedInPlace(root, path);
|
|
833
867
|
const changed = [...after]
|
|
834
868
|
.filter(([path, sig]) => {
|
|
835
869
|
if (sig === 'missing')
|
package/lib/report/compute.js
CHANGED
|
@@ -644,6 +644,7 @@ export function valueReport(input, options = {}) {
|
|
|
644
644
|
cancelledWithoutAttempt: 0,
|
|
645
645
|
baseMoves: zero(['operator', 'controller', 'host']),
|
|
646
646
|
baseMovesBound: 'lower',
|
|
647
|
+
jointResets: zero(['operator', 'host']),
|
|
647
648
|
gaps: gapInWindow.size,
|
|
648
649
|
};
|
|
649
650
|
for (const e of windowEvents)
|
|
@@ -659,6 +660,8 @@ export function valueReport(input, options = {}) {
|
|
|
659
660
|
}
|
|
660
661
|
else if (e.type === 'base.moved')
|
|
661
662
|
r.baseMoves[e.payload.by] += 1;
|
|
663
|
+
else if (e.type === 'joint.budget-reset')
|
|
664
|
+
r.jointResets[e.payload.by] += 1;
|
|
662
665
|
// Окно начинается раньше записи: в нём есть попытки или события до неё.
|
|
663
666
|
const before = (ms) => ms < recordedFrom;
|
|
664
667
|
if (gapInWindow.size > 0 ||
|
package/lib/report/document.js
CHANGED
|
@@ -109,7 +109,7 @@ export function reportBlocks(r) {
|
|
|
109
109
|
? `Accepted tasks that needed no human action: ${formatMeasureRatio(a.withoutAction)}. With a recorded human action (operator retry, cancellation or recovery decision): ${formatMeasureRatio(a.withAction)}.`
|
|
110
110
|
: `Accepted tasks that needed no human action: not measurable yet (retries, resets and base moves have no recorded actor). Accepted tasks with an operator recovery decision: ${a.withAction.value ?? 0} of ${a.withAction.n}.`,
|
|
111
111
|
rec
|
|
112
|
-
? `Human actions: operator recovery decisions ${a.actions.operatorDecisions}, operator retries ${ge}${rec.retries.operator} (resets ${ge}${rec.resets.operator}), operator cancellations ${ge}${rec.cancellations.operator}, operator base moves ≥ ${rec.baseMoves.operator}. Automatic: recovery retries ${ge}${rec.retries.recovery}, controller base moves ≥ ${rec.baseMoves.controller}, cancellations by a new graph revision ${ge}${rec.cancellations.graph}. By the host without a named actor: retries ${ge}${rec.retries.host}, cancellations ${ge}${rec.cancellations.host}, base moves ≥ ${rec.baseMoves.host}. Tasks cancelled without an active attempt: ${ge}${rec.cancelledWithoutAttempt}; cancelled attempts ${a.actions.cancelledAttempts}. Without a recorded actor: holds ${a.actions.holds} (held tasks count as unknown). Recorded from ${rec.from}.`
|
|
112
|
+
? `Human actions: operator recovery decisions ${a.actions.operatorDecisions}, operator retries ${ge}${rec.retries.operator} (resets ${ge}${rec.resets.operator}), operator cancellations ${ge}${rec.cancellations.operator}, operator base moves ≥ ${rec.baseMoves.operator}. Automatic: recovery retries ${ge}${rec.retries.recovery}, controller base moves ≥ ${rec.baseMoves.controller}, cancellations by a new graph revision ${ge}${rec.cancellations.graph}. By the host without a named actor: retries ${ge}${rec.retries.host}, cancellations ${ge}${rec.cancellations.host}, base moves ≥ ${rec.baseMoves.host}. Joint verification budget resets: operator ${rec.jointResets?.operator ?? 0}, host ${rec.jointResets?.host ?? 0}. Tasks cancelled without an active attempt: ${ge}${rec.cancelledWithoutAttempt}; cancelled attempts ${a.actions.cancelledAttempts}. Without a recorded actor: holds ${a.actions.holds} (held tasks count as unknown). Recorded from ${rec.from}.`
|
|
113
113
|
: `Human actions with a recorded actor: operator recovery decisions ${a.actions.operatorDecisions}. Without a recorded actor (not counted as human): holds ${a.actions.holds}, cancelled attempts ${a.actions.cancelledAttempts}. ${actionsLine([
|
|
114
114
|
['retries', a.actions.retries],
|
|
115
115
|
['resets', a.actions.resets],
|
|
@@ -1280,6 +1280,7 @@ export declare class DocumentView {
|
|
|
1280
1280
|
tree: string;
|
|
1281
1281
|
}> | undefined;
|
|
1282
1282
|
manifestDigest?: string | undefined;
|
|
1283
|
+
interrupted?: true | undefined;
|
|
1283
1284
|
impact?: {
|
|
1284
1285
|
changed: string[];
|
|
1285
1286
|
affected: string[];
|
|
@@ -1443,6 +1444,7 @@ export declare class DocumentView {
|
|
|
1443
1444
|
tree: string;
|
|
1444
1445
|
}> | undefined;
|
|
1445
1446
|
manifestDigest?: string | undefined;
|
|
1447
|
+
interrupted?: true | undefined;
|
|
1446
1448
|
impact?: {
|
|
1447
1449
|
changed: string[];
|
|
1448
1450
|
affected: string[];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ExecutionStore, type InputRequest } from '../contracts/index.ts';
|
|
1
|
+
import { type ExecutionStore, type InputRequest, type JointVerificationState } from '../contracts/index.ts';
|
|
2
2
|
/**
|
|
3
3
|
* Запрос исполнителя (`input-requests`) для проверок адаптера: вопрос с
|
|
4
4
|
* вариантами, основание исходной попытки, без ответов (`pending`).
|
|
@@ -12,4 +12,10 @@ export declare function answeredInputRequest(request: InputRequest, text?: strin
|
|
|
12
12
|
* повторный вызов с тем же каталогом — то же хранилище другим экземпляром.
|
|
13
13
|
* Регистрация тестов — через переданную `test` (node:test).
|
|
14
14
|
*/
|
|
15
|
-
export declare function executionStoreContract(name: string, test: (title: string, fn: () => void | Promise<void>) => unknown, open: (dir: string) => ExecutionStore, tempDir: () => string
|
|
15
|
+
export declare function executionStoreContract(name: string, test: (title: string, fn: () => void | Promise<void>) => unknown, open: (dir: string) => ExecutionStore, tempDir: () => string, options?: {
|
|
16
|
+
/**
|
|
17
|
+
* Как хост заводит новую совместную проверку (у DevContour — операцией
|
|
18
|
+
* ChangeSet). По умолчанию — `putVerification` в транзакции начала.
|
|
19
|
+
*/
|
|
20
|
+
startVerification?: (store: ExecutionStore, verification: JointVerificationState) => void;
|
|
21
|
+
}): void;
|
|
@@ -75,7 +75,7 @@ export function answeredInputRequest(request, text = 'ISO 8601') {
|
|
|
75
75
|
* повторный вызов с тем же каталогом — то же хранилище другим экземпляром.
|
|
76
76
|
* Регистрация тестов — через переданную `test` (node:test).
|
|
77
77
|
*/
|
|
78
|
-
export function executionStoreContract(name, test, open, tempDir) {
|
|
78
|
+
export function executionStoreContract(name, test, open, tempDir, options = {}) {
|
|
79
79
|
const work = (id, status = 'ready') => ({
|
|
80
80
|
id,
|
|
81
81
|
graphId: 'g',
|
|
@@ -237,6 +237,61 @@ export function executionStoreContract(name, test, open, tempDir) {
|
|
|
237
237
|
assert.equal(b.read((v) => v.local('input-requests', 'app', inputRequestId('run-1', 0))), undefined);
|
|
238
238
|
b.close();
|
|
239
239
|
});
|
|
240
|
+
test(`${name}: прерванная совместная проверка сохраняет interrupted и виден другому экземпляру`, () => {
|
|
241
|
+
const dir = tempDir();
|
|
242
|
+
const a = open(dir);
|
|
243
|
+
a.transact('run.phase', (tx) => {
|
|
244
|
+
tx.putWork(work('w1', 'done'));
|
|
245
|
+
tx.putWork(work('w2', 'done'));
|
|
246
|
+
});
|
|
247
|
+
const active = {
|
|
248
|
+
apiVersion: 'devcontour-harness/v1alpha1',
|
|
249
|
+
id: 'jv-interrupted',
|
|
250
|
+
token: 'token-'.padEnd(32, 'x'),
|
|
251
|
+
leaseUntil: 1,
|
|
252
|
+
startedAt: '2026-01-01T00:00:00.000Z',
|
|
253
|
+
status: 'active',
|
|
254
|
+
policyDigest: digestOf('policy'),
|
|
255
|
+
specDigest: digestOf('spec'),
|
|
256
|
+
workIds: ['w1', 'w2'],
|
|
257
|
+
evidence: [],
|
|
258
|
+
};
|
|
259
|
+
if (options.startVerification)
|
|
260
|
+
options.startVerification(a, active);
|
|
261
|
+
else
|
|
262
|
+
a.transact('workspace.verification.started', (tx) => tx.putVerification(active));
|
|
263
|
+
a.transact('workspace.failed', (tx) => tx.putVerification({
|
|
264
|
+
...active,
|
|
265
|
+
status: 'failed',
|
|
266
|
+
error: 'Совместная проверка отменена',
|
|
267
|
+
finishedAt: '2026-01-01T00:01:00.000Z',
|
|
268
|
+
interrupted: true,
|
|
269
|
+
}));
|
|
270
|
+
a.close();
|
|
271
|
+
const b = open(dir);
|
|
272
|
+
const stored = b.read((v) => v.verification(active.id));
|
|
273
|
+
assert.equal(stored?.status, 'failed');
|
|
274
|
+
assert.equal(stored?.status === 'failed' ? stored.interrupted : undefined, true, 'отметка прерывания не теряется: без неё прерванная проверка тратит предел набора');
|
|
275
|
+
b.close();
|
|
276
|
+
});
|
|
277
|
+
test(`${name}: сброс бюджета совместных проверок хранится у @workspace и виден другому экземпляру`, () => {
|
|
278
|
+
const dir = tempDir();
|
|
279
|
+
const a = open(dir);
|
|
280
|
+
assert.deepEqual(a.read((v) => v.locals('joint-budget-resets', WORKSPACE_OWNER)), []);
|
|
281
|
+
const reset = {
|
|
282
|
+
id: 'reset-1',
|
|
283
|
+
at: '2026-01-01T00:00:00.000Z',
|
|
284
|
+
workIds: ['a', 'b'],
|
|
285
|
+
reason: 'lease lost on host stop',
|
|
286
|
+
actor: 'operator',
|
|
287
|
+
settledVerificationIds: ['jv-1', 'jv-2'],
|
|
288
|
+
};
|
|
289
|
+
a.transact('workspace.budget-reset', (tx) => tx.putLocal('joint-budget-resets', WORKSPACE_OWNER, reset.id, reset));
|
|
290
|
+
a.close();
|
|
291
|
+
const b = open(dir);
|
|
292
|
+
assert.deepEqual(b.read((v) => v.locals('joint-budget-resets', WORKSPACE_OWNER)), [{ owner: WORKSPACE_OWNER, key: reset.id, value: reset }]);
|
|
293
|
+
b.close();
|
|
294
|
+
});
|
|
240
295
|
test(`${name}: запрос исполнителя хранится у владельца, версия видна другому экземпляру`, () => {
|
|
241
296
|
const dir = tempDir();
|
|
242
297
|
const a = open(dir);
|
|
@@ -16,7 +16,184 @@ export declare function jointPolicyDigest(policy: ExecutionPolicy): string;
|
|
|
16
16
|
export declare function jointSpecDigest(view: ExecutionView, workIds: string[]): string;
|
|
17
17
|
/** Один и тот же набор поручений — один предмет проверки, независимо от порядка. */
|
|
18
18
|
export declare const sameWorks: (a: string[], b: string[]) => boolean;
|
|
19
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* Проверка, прерванная до результата gates (остановка хоста, потеря
|
|
21
|
+
* владения): без evidence она не говорит ничего о комбинации и предел не тратит.
|
|
22
|
+
*/
|
|
23
|
+
export declare const jointInterrupted: (v: JointVerificationState) => boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Окно бюджета набора: проверки, не закрытые принятием хоста и не снятые
|
|
26
|
+
* явным сбросом (`joint-budget-resets`). Checkpoints доверенного хоста
|
|
27
|
+
* проверяются целиком.
|
|
28
|
+
*/
|
|
29
|
+
export declare function jointBudgetWindow(view: ExecutionView, workIds: string[], checkpoints: readonly JointBudgetCheckpoint[]): ({
|
|
30
|
+
status: "active";
|
|
31
|
+
apiVersion: "devcontour-harness/v1alpha1";
|
|
32
|
+
id: string;
|
|
33
|
+
startedAt: string;
|
|
34
|
+
policyDigest: string;
|
|
35
|
+
specDigest: string;
|
|
36
|
+
workIds: string[];
|
|
37
|
+
evidence: {
|
|
38
|
+
gate: string;
|
|
39
|
+
passed: boolean;
|
|
40
|
+
command: string[];
|
|
41
|
+
exitCode: number;
|
|
42
|
+
log: string;
|
|
43
|
+
digest: string;
|
|
44
|
+
summary: string;
|
|
45
|
+
artifacts: {
|
|
46
|
+
path: string;
|
|
47
|
+
digest: string;
|
|
48
|
+
}[];
|
|
49
|
+
artifactFiles?: {
|
|
50
|
+
dir: string;
|
|
51
|
+
files: {
|
|
52
|
+
path: string;
|
|
53
|
+
sha256: string;
|
|
54
|
+
bytes: number;
|
|
55
|
+
redacted?: true | undefined;
|
|
56
|
+
}[];
|
|
57
|
+
skipped: {
|
|
58
|
+
path: string;
|
|
59
|
+
reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
|
|
60
|
+
detail?: string | undefined;
|
|
61
|
+
}[];
|
|
62
|
+
skippedMore?: number | undefined;
|
|
63
|
+
} | undefined;
|
|
64
|
+
durationMs?: number | undefined;
|
|
65
|
+
}[];
|
|
66
|
+
token: string;
|
|
67
|
+
leaseUntil: number;
|
|
68
|
+
manifest?: Record<string, {
|
|
69
|
+
sha: string;
|
|
70
|
+
tree: string;
|
|
71
|
+
}> | undefined;
|
|
72
|
+
manifestDigest?: string | undefined;
|
|
73
|
+
impact?: {
|
|
74
|
+
changed: string[];
|
|
75
|
+
affected: string[];
|
|
76
|
+
gateIds: string[];
|
|
77
|
+
mode: "affected" | "all";
|
|
78
|
+
reason: string;
|
|
79
|
+
baseline?: string | undefined;
|
|
80
|
+
} | undefined;
|
|
81
|
+
engineVersion?: string | undefined;
|
|
82
|
+
} | {
|
|
83
|
+
status: "failed";
|
|
84
|
+
finishedAt: string;
|
|
85
|
+
error: string;
|
|
86
|
+
apiVersion: "devcontour-harness/v1alpha1";
|
|
87
|
+
id: string;
|
|
88
|
+
startedAt: string;
|
|
89
|
+
policyDigest: string;
|
|
90
|
+
specDigest: string;
|
|
91
|
+
workIds: string[];
|
|
92
|
+
evidence: {
|
|
93
|
+
gate: string;
|
|
94
|
+
passed: boolean;
|
|
95
|
+
command: string[];
|
|
96
|
+
exitCode: number;
|
|
97
|
+
log: string;
|
|
98
|
+
digest: string;
|
|
99
|
+
summary: string;
|
|
100
|
+
artifacts: {
|
|
101
|
+
path: string;
|
|
102
|
+
digest: string;
|
|
103
|
+
}[];
|
|
104
|
+
artifactFiles?: {
|
|
105
|
+
dir: string;
|
|
106
|
+
files: {
|
|
107
|
+
path: string;
|
|
108
|
+
sha256: string;
|
|
109
|
+
bytes: number;
|
|
110
|
+
redacted?: true | undefined;
|
|
111
|
+
}[];
|
|
112
|
+
skipped: {
|
|
113
|
+
path: string;
|
|
114
|
+
reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
|
|
115
|
+
detail?: string | undefined;
|
|
116
|
+
}[];
|
|
117
|
+
skippedMore?: number | undefined;
|
|
118
|
+
} | undefined;
|
|
119
|
+
durationMs?: number | undefined;
|
|
120
|
+
}[];
|
|
121
|
+
token: string;
|
|
122
|
+
leaseUntil: number;
|
|
123
|
+
manifest?: Record<string, {
|
|
124
|
+
sha: string;
|
|
125
|
+
tree: string;
|
|
126
|
+
}> | undefined;
|
|
127
|
+
manifestDigest?: string | undefined;
|
|
128
|
+
interrupted?: true | undefined;
|
|
129
|
+
impact?: {
|
|
130
|
+
changed: string[];
|
|
131
|
+
affected: string[];
|
|
132
|
+
gateIds: string[];
|
|
133
|
+
mode: "affected" | "all";
|
|
134
|
+
reason: string;
|
|
135
|
+
baseline?: string | undefined;
|
|
136
|
+
} | undefined;
|
|
137
|
+
engineVersion?: string | undefined;
|
|
138
|
+
} | {
|
|
139
|
+
status: "passed";
|
|
140
|
+
finishedAt: string;
|
|
141
|
+
manifest: Record<string, {
|
|
142
|
+
sha: string;
|
|
143
|
+
tree: string;
|
|
144
|
+
}>;
|
|
145
|
+
manifestDigest: string;
|
|
146
|
+
apiVersion: "devcontour-harness/v1alpha1";
|
|
147
|
+
id: string;
|
|
148
|
+
startedAt: string;
|
|
149
|
+
policyDigest: string;
|
|
150
|
+
specDigest: string;
|
|
151
|
+
workIds: string[];
|
|
152
|
+
evidence: {
|
|
153
|
+
gate: string;
|
|
154
|
+
passed: boolean;
|
|
155
|
+
command: string[];
|
|
156
|
+
exitCode: number;
|
|
157
|
+
log: string;
|
|
158
|
+
digest: string;
|
|
159
|
+
summary: string;
|
|
160
|
+
artifacts: {
|
|
161
|
+
path: string;
|
|
162
|
+
digest: string;
|
|
163
|
+
}[];
|
|
164
|
+
artifactFiles?: {
|
|
165
|
+
dir: string;
|
|
166
|
+
files: {
|
|
167
|
+
path: string;
|
|
168
|
+
sha256: string;
|
|
169
|
+
bytes: number;
|
|
170
|
+
redacted?: true | undefined;
|
|
171
|
+
}[];
|
|
172
|
+
skipped: {
|
|
173
|
+
path: string;
|
|
174
|
+
reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
|
|
175
|
+
detail?: string | undefined;
|
|
176
|
+
}[];
|
|
177
|
+
skippedMore?: number | undefined;
|
|
178
|
+
} | undefined;
|
|
179
|
+
durationMs?: number | undefined;
|
|
180
|
+
}[];
|
|
181
|
+
token: string;
|
|
182
|
+
leaseUntil: number;
|
|
183
|
+
impact?: {
|
|
184
|
+
changed: string[];
|
|
185
|
+
affected: string[];
|
|
186
|
+
gateIds: string[];
|
|
187
|
+
mode: "affected" | "all";
|
|
188
|
+
reason: string;
|
|
189
|
+
baseline?: string | undefined;
|
|
190
|
+
} | undefined;
|
|
191
|
+
engineVersion?: string | undefined;
|
|
192
|
+
})[];
|
|
193
|
+
/**
|
|
194
|
+
* Проверки набора, тратящие его предел: окно бюджета без прерванных до
|
|
195
|
+
* результата gates. Прерванная после evidence и отказ gate тратят.
|
|
196
|
+
*/
|
|
20
197
|
export declare function jointBudgetAttempts(view: ExecutionView, workIds: string[], checkpoints: readonly JointBudgetCheckpoint[]): ({
|
|
21
198
|
status: "active";
|
|
22
199
|
apiVersion: "devcontour-harness/v1alpha1";
|
|
@@ -116,6 +293,7 @@ export declare function jointBudgetAttempts(view: ExecutionView, workIds: string
|
|
|
116
293
|
tree: string;
|
|
117
294
|
}> | undefined;
|
|
118
295
|
manifestDigest?: string | undefined;
|
|
296
|
+
interrupted?: true | undefined;
|
|
119
297
|
impact?: {
|
|
120
298
|
changed: string[];
|
|
121
299
|
affected: string[];
|