devcontour-harness 0.1.0-alpha.37 → 0.1.0-alpha.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +56 -2
  2. package/docs/architecture.md +64 -5
  3. package/docs/contracts.md +45 -22
  4. package/docs/release-notes/0.1.0-alpha.38.md +31 -0
  5. package/docs/release-notes/0.1.0-alpha.39.md +38 -0
  6. package/docs/release-notes/0.1.0-alpha.40.md +27 -0
  7. package/docs/release-notes/0.1.0-alpha.41.md +49 -0
  8. package/docs/release-notes/0.1.0-alpha.42.md +44 -0
  9. package/docs/release-notes/0.1.0-alpha.43.md +40 -0
  10. package/docs/release-notes/0.1.0-alpha.44.md +44 -0
  11. package/docs/upgrade.md +197 -17
  12. package/lib/agents/review-probe.d.ts +3 -1
  13. package/lib/agents/review-probe.js +8 -4
  14. package/lib/contracts/cli.d.ts +48 -4
  15. package/lib/contracts/events.d.ts +60 -5
  16. package/lib/contracts/events.js +16 -1
  17. package/lib/contracts/execution.d.ts +37 -0
  18. package/lib/contracts/execution.js +24 -3
  19. package/lib/contracts/policy.d.ts +19 -0
  20. package/lib/contracts/policy.js +30 -0
  21. package/lib/contracts/published.d.ts +29 -2
  22. package/lib/contracts/report.d.ts +8 -0
  23. package/lib/contracts/report.js +7 -1
  24. package/lib/contracts/result.d.ts +2 -0
  25. package/lib/contracts/result.js +6 -0
  26. package/lib/control/harness.d.ts +5 -0
  27. package/lib/engine/engine.d.ts +36 -3
  28. package/lib/engine/engine.js +140 -21
  29. package/lib/engine/joint-runner.d.ts +2 -0
  30. package/lib/engine/joint-runner.js +14 -4
  31. package/lib/engine/runner.d.ts +11 -0
  32. package/lib/engine/runner.js +82 -13
  33. package/lib/environment/isolation.d.ts +41 -1
  34. package/lib/environment/isolation.js +203 -7
  35. package/lib/environment/lifecycle.d.ts +46 -2
  36. package/lib/environment/lifecycle.js +81 -2
  37. package/lib/report/compute.js +19 -6
  38. package/lib/report/document.js +3 -3
  39. package/lib/storage/document.d.ts +2 -0
  40. package/lib/testing/store-contract.d.ts +8 -2
  41. package/lib/testing/store-contract.js +56 -1
  42. package/lib/verification/confirm.js +6 -4
  43. package/lib/verification/gates-at.js +3 -1
  44. package/lib/verification/gates.d.ts +36 -2
  45. package/lib/verification/gates.js +71 -11
  46. package/lib/verification/joint.d.ts +179 -1
  47. package/lib/verification/joint.js +23 -3
  48. package/package.json +1 -1
  49. package/schemas/execution-document.schema.json +4 -0
  50. package/schemas/execution-policy.schema.json +5 -0
  51. package/schemas/joint-verification.schema.json +4 -0
  52. package/schemas/run-event.schema.json +96 -0
  53. package/schemas/value-report.schema.json +20 -0
@@ -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);
@@ -3,9 +3,9 @@ import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { z } from 'zod';
6
- import { HarnessError, idSchema, } from "../contracts/index.js";
6
+ import { HarnessError, idSchema, gateTimeoutMs, } from "../contracts/index.js";
7
7
  import { OversizedFile, readBounded } from "../environment/bounded-read.js";
8
- import { executionEnvironment, runSteps, withEnvironment } from "../environment/lifecycle.js";
8
+ import { executionEnvironment, preparation, preparesTree, runSteps, withEnvironment, } from "../environment/lifecycle.js";
9
9
  import { git, hostGitArgs } from "../environment/process.js";
10
10
  import { defaultResourceDatabase } from "../environment/resources.js";
11
11
  import { contractDocuments, obligationOf } from "./checks.js";
@@ -295,9 +295,10 @@ async function decide(ctx, work, ref, input, source) {
295
295
  DEVCONTOUR_TASK_ID: work.id,
296
296
  DEVCONTOUR_PHASE: 'case',
297
297
  }, ctx.environment ?? process.env);
298
- const limitMs = gate.timeoutMs * 3 + 120000;
298
+ const limitMs = gateTimeoutMs(gate, ctx.policy) * 3 + 120000;
299
299
  const deadline = Date.now() + limitMs;
300
300
  const signal = AbortSignal.timeout(limitMs);
301
+ const prepared = preparation.guard(ctx.policy.isolation.mode === 'os', dir, preparesTree(repo.lifecycle ?? ctx.policy.lifecycle, repo.prepare, repo.dependencyStore));
301
302
  await withEnvironment(repo.lifecycle ?? ctx.policy.lifecycle, dir, join(io, 'environment'), execution, signal, async () => {
302
303
  const boundary = ctx.boundary();
303
304
  await materializeStore({
@@ -311,6 +312,7 @@ async function decide(ctx, work, ref, input, source) {
311
312
  phaseMs: limitMs,
312
313
  }, { repo, cwd: dir, execution, signal, dir: io });
313
314
  await runSteps(repo.prepare, dir, join(io, 'prepare'), execution, signal);
315
+ prepared(execution);
314
316
  const request = join(io, 'case.json');
315
317
  await writeFile(request, JSON.stringify({ property: input.property, input: JSON.parse(text) }));
316
318
  for (let i = 0; i < 2; i++) {
@@ -327,7 +329,7 @@ async function decide(ctx, work, ref, input, source) {
327
329
  HARNESS_CASE_RESULT: out,
328
330
  },
329
331
  redact: execution.redact,
330
- timeoutMs: gate.timeoutMs,
332
+ timeoutMs: gateTimeoutMs(gate, ctx.policy),
331
333
  signal,
332
334
  write: [dir, io],
333
335
  readable: boundary.readable,
@@ -5,7 +5,7 @@ import { HarnessError, stallSweepOf, } from "../contracts/index.js";
5
5
  import { livenessPayload, superviseStalls } from "../engine/stall-sweep.js";
6
6
  import { TaskFailure } from "../engine/failure.js";
7
7
  import { git } from "../environment/process.js";
8
- import { executionEnvironment, runSteps, withEnvironment } from "../environment/lifecycle.js";
8
+ import { executionEnvironment, preparation, preparesTree, runSteps, withEnvironment, } from "../environment/lifecycle.js";
9
9
  import { defaultResourceDatabase, withResources } from "../environment/resources.js";
10
10
  import { removeSnapshots, snapshotDependencies } from "./dependencies.js";
11
11
  import { runGate } from "./gates.js";
@@ -146,9 +146,11 @@ async function gatesAt(ctx, input) {
146
146
  }),
147
147
  }, source);
148
148
  const boundary = ctx.boundary();
149
+ const prepared = preparation.guard(ctx.policy.isolation.mode === 'os', cwd, preparesTree(repo.lifecycle ?? ctx.policy.lifecycle, repo.prepare, repo.dependencyStore));
149
150
  await withEnvironment(repo.lifecycle ?? ctx.policy.lifecycle, cwd, join(artifacts, 'environment'), execution, signal, async () => {
150
151
  await materializeStore(store, { repo, cwd, execution, signal, dir: artifacts });
151
152
  await runSteps(repo.prepare, cwd, join(artifacts, 'prepare'), execution, signal);
153
+ prepared(execution);
152
154
  for (const gate of gates) {
153
155
  // Пропускается только gate, чья явная предпосылка (`dependsOn`) не
154
156
  // прошла. Провал неявной (более ранний check gate в режиме
@@ -1,5 +1,6 @@
1
1
  import { type Activity, type EvidenceRecord, type ExecutionPolicy, type GatePolicy } from '../contracts/index.ts';
2
2
  import { isolationSupport, type Isolation, type SandboxViolation } from '../environment/isolation.ts';
3
+ import { TaskFailure } from '../engine/failure.ts';
3
4
  import { type CheckManifest } from './property.ts';
4
5
  /** Длинное имя testcase заменяется хешем, а не обрезается: обрезка дала бы ложные совпадения. */
5
6
  export declare const TEST_ID_LIMIT = 1000;
@@ -181,9 +182,38 @@ export interface Boundary {
181
182
  readable: string[];
182
183
  checkouts?: string[];
183
184
  }
185
+ /**
186
+ * Нагрузка хоста на одно ядро (средняя за минуту), начиная с которой gate,
187
+ * исчерпавший свой предел времени, повторяется один раз на том же SHA
188
+ * (`GateTimeout.overloaded`). Под такой нагрузкой предел gate меряет очередь
189
+ * к процессору, а не его код; проверка, которая и на свободной машине не
190
+ * укладывается в предел, повтора не получает.
191
+ */
192
+ export declare const HOST_LOAD_RECHECK_PER_CPU = 2;
193
+ /** Снимок нагрузки хоста; объект — чтобы тест мог подменить чтение. */
194
+ export declare const hostLoad: {
195
+ read: () => HostLoad;
196
+ };
197
+ export interface HostLoad {
198
+ /** Средняя нагрузка за минуту (`os.loadavg()[0]`; на Windows — 0). */
199
+ load1: number;
200
+ /** Доступные процессу ядра. */
201
+ cpus: number;
202
+ }
203
+ /**
204
+ * Gate исчерпал свой предел времени (не отмена попытки). Класс отказа —
205
+ * прежний `gate`; нагрузка в момент таймаута решает, повторить ли gate один
206
+ * раз (`Runner`): повтор прошёл — исход `flaky`, попытка не тратится; снова
207
+ * таймаут — провал засчитан как прежде.
208
+ */
209
+ export declare class GateTimeout extends TaskFailure {
210
+ readonly load: HostLoad;
211
+ constructor(message: string, load: HostLoad);
212
+ get overloaded(): boolean;
213
+ }
184
214
  /** Что нужно для запуска gate попытки. */
185
215
  export interface GateRun {
186
- policy: Pick<ExecutionPolicy, 'isolation'>;
216
+ policy: Pick<ExecutionPolicy, 'isolation' | 'gateTimeoutFloorMs'>;
187
217
  /** Запись evidence под fencing попытки. */
188
218
  record: (evidence: Omit<EvidenceRecord, 'id' | 'runId' | 'createdAt'>) => EvidenceRecord;
189
219
  cwd: string;
@@ -196,6 +226,8 @@ export interface GateRun {
196
226
  execution: {
197
227
  env: NodeJS.ProcessEnv;
198
228
  redact: (value: string) => string;
229
+ /** Вложенные `.git`, созданные подготовкой фазы: их исчезновение сверка не считает. */
230
+ prepared?: ReadonlySet<string>;
199
231
  };
200
232
  /** Закрытое проверке (состояние controller, чужие checkout) и открытое внутри него. */
201
233
  boundary: Boundary;
@@ -239,7 +271,7 @@ export interface GateRun {
239
271
  export declare function runGate(run: GateRun): Promise<EvidenceRecord>;
240
272
  /** Что нужно для установки зависимостей в дереве исполнителя до его работы. */
241
273
  export interface WriterDependenciesRun {
242
- policy: Pick<ExecutionPolicy, 'isolation'>;
274
+ policy: Pick<ExecutionPolicy, 'isolation' | 'gateTimeoutFloorMs'>;
243
275
  /** Рабочее дерево исполнителя: база попытки, возможно с наложенным черновиком. */
244
276
  cwd: string;
245
277
  /** SHA базы попытки (HEAD дерева). */
@@ -261,6 +293,8 @@ export interface WriterDependenciesRun {
261
293
  execution: {
262
294
  env: NodeJS.ProcessEnv;
263
295
  redact: (value: string) => string;
296
+ /** Вложенные `.git`, созданные подготовкой фазы: их исчезновение сверка не считает. */
297
+ prepared?: ReadonlySet<string>;
264
298
  };
265
299
  boundary: Boundary;
266
300
  }
@@ -1,10 +1,10 @@
1
1
  import { readFile, readdir, writeFile, mkdir, mkdtemp, rm, realpath, lstat, chmod, } from 'node:fs/promises';
2
- import { tmpdir } from 'node:os';
2
+ import { availableParallelism, loadavg, tmpdir } from 'node:os';
3
3
  import { join, resolve, sep, delimiter, relative, dirname } from 'node:path';
4
4
  import { accessSync, constants, existsSync } from 'node:fs';
5
5
  import { createHash, randomUUID } from 'node:crypto';
6
6
  import { XMLParser, XMLValidator } from 'fast-xml-parser';
7
- import { sha256, } from "../contracts/index.js";
7
+ import { sha256, gateTimeoutMs, gateTimeoutText, } from "../contracts/index.js";
8
8
  import { command, git, gitOutput } from "../environment/process.js";
9
9
  import { isolation, isolatedCommand, srtTempDir, isolationSupport, protectedChanges, protectedSnapshot, SandboxPolicyError, sandboxDenials, snapshotLimit, watchSandboxLog, } from "../environment/isolation.js";
10
10
  import { UntrustedCheckoutError } from "../environment/git-trust.js";
@@ -521,6 +521,35 @@ export function freshnessEnv(kind, env) {
521
521
  ? { TURBO_FORCE: 'true', GOFLAGS: [env.GOFLAGS, '-count=1'].filter(Boolean).join(' ') }
522
522
  : {};
523
523
  }
524
+ /**
525
+ * Нагрузка хоста на одно ядро (средняя за минуту), начиная с которой gate,
526
+ * исчерпавший свой предел времени, повторяется один раз на том же SHA
527
+ * (`GateTimeout.overloaded`). Под такой нагрузкой предел gate меряет очередь
528
+ * к процессору, а не его код; проверка, которая и на свободной машине не
529
+ * укладывается в предел, повтора не получает.
530
+ */
531
+ export const HOST_LOAD_RECHECK_PER_CPU = 2;
532
+ /** Снимок нагрузки хоста; объект — чтобы тест мог подменить чтение. */
533
+ export const hostLoad = {
534
+ read: () => ({ load1: loadavg()[0] ?? 0, cpus: Math.max(1, availableParallelism()) }),
535
+ };
536
+ const loadText = (load) => `нагрузка хоста ${Math.round(load.load1 * 10) / 10} на ${load.cpus} ядер`;
537
+ /**
538
+ * Gate исчерпал свой предел времени (не отмена попытки). Класс отказа —
539
+ * прежний `gate`; нагрузка в момент таймаута решает, повторить ли gate один
540
+ * раз (`Runner`): повтор прошёл — исход `flaky`, попытка не тратится; снова
541
+ * таймаут — провал засчитан как прежде.
542
+ */
543
+ export class GateTimeout extends TaskFailure {
544
+ load;
545
+ constructor(message, load) {
546
+ super('gate', message);
547
+ this.load = load;
548
+ }
549
+ get overloaded() {
550
+ return this.load.load1 / this.load.cpus >= HOST_LOAD_RECHECK_PER_CPU;
551
+ }
552
+ }
524
553
  /**
525
554
  * Gate попытки. `test` принимается только по свежему (прежний отчёт удалён до
526
555
  * запуска) непустому JUnit без failures, errors и skips на этом SHA; exit 0
@@ -590,6 +619,14 @@ export async function runGate(run) {
590
619
  let kind = 'gate';
591
620
  /** Причина отказа окружения (`attempt.diagnosed`), когда она известна здесь. */
592
621
  let cause;
622
+ /**
623
+ * Нагрузка хоста, когда gate исчерпал свой предел времени: меньшая из
624
+ * снятых до запуска и в момент таймаута.
625
+ */
626
+ let timedOut;
627
+ let loadBefore;
628
+ /** Провалы, записанные в JUnit до таймаута: повтор их не отменяет. */
629
+ let timedOutFailures = '';
593
630
  // Заголовок лога — фактические каталог и argv запуска: digest лога входит в
594
631
  // evidence, и запись называет, где и чем проверка исполнялась.
595
632
  let passed = false, summary = '', log = `# harness gate ${gate.id}: cwd=${relative(root, gateCwd) || '.'} argv=${JSON.stringify(gate.command.map(redact))}${gate.kind === 'test' ? ` fresh=${redact(JSON.stringify(freshness))}` : ''}\n`, exitCode = -1, manifest;
@@ -597,6 +634,9 @@ export async function runGate(run) {
597
634
  // Снимок защищённых путей до проверки: запреты песочницы видят только
598
635
  // путь операции, перенос готового каталога ими не закрыт.
599
636
  const before = run.policy.isolation.mode === 'os' ? protectedSnapshot(root) : undefined;
637
+ // Нагрузка до запуска: gate, который сам перегрузил процессор (пул
638
+ // потоков без предела), не должен заработать повтор своей нагрузкой.
639
+ loadBefore = hostLoad.read();
600
640
  const result = await runCheck({ config: run.policy }, {
601
641
  activity: {
602
642
  kind: 'gate',
@@ -614,7 +654,7 @@ export async function runGate(run) {
614
654
  ...Object.fromEntries(Object.entries(propertyEnv).map(([k, v]) => [k.replace(/^DEVCONTOUR_/, 'HARNESS_'), v])),
615
655
  },
616
656
  redact,
617
- timeoutMs: gate.timeoutMs,
657
+ timeoutMs: gateTimeoutMs(gate, run.policy),
618
658
  signal,
619
659
  write: [cwd, ...(propertyDir ? [propertyDir] : [])],
620
660
  readable: [...run.boundary.readable, ...(corpusDir ? [corpusDir] : [])],
@@ -630,7 +670,7 @@ export async function runGate(run) {
630
670
  let planted = [];
631
671
  try {
632
672
  if (before)
633
- planted = protectedChanges(before, root);
673
+ planted = protectedChanges(before, root, run.execution.prepared);
634
674
  }
635
675
  catch (error) {
636
676
  if (error instanceof SandboxPolicyError)
@@ -639,15 +679,31 @@ export async function runGate(run) {
639
679
  }
640
680
  if (planted.length) {
641
681
  kind = 'scope-violation';
642
- throw new Error('проверка создала или изменила защищённые пути (конфигурация IDE, shell, git или Claude): ' +
682
+ throw new Error('проверка создала, изменила или удалила защищённые пути (конфигурация IDE, shell, git или Claude): ' +
643
683
  planted
644
684
  .slice(0, 5)
645
685
  .map((p) => relative(root, p))
646
686
  .join(', ') +
647
687
  (planted.length > 5 ? ` и ещё ${planted.length - 5}` : ''));
648
688
  }
689
+ if (result.timedOut && !signal.aborted) {
690
+ const now = hostLoad.read();
691
+ timedOut =
692
+ loadBefore && loadBefore.load1 / loadBefore.cpus < now.load1 / now.cpus ? loadBefore : now;
693
+ // Отчёт, записанный до таймаута, читается без гарантий: названный в нём
694
+ // провал — найденный дефект, и повтор gate его не отменяет.
695
+ const partial = reportPath
696
+ ? await readReport(reportPath, cwd, redact).catch(() => undefined)
697
+ : undefined;
698
+ if (partial?.failures) {
699
+ manifest = partial;
700
+ timedOutFailures = failedCases(partial);
701
+ }
702
+ }
649
703
  if (result.timedOut || signal.aborted)
650
- throw new Error('Проверка прервана или превысила timeout');
704
+ throw new Error('Проверка прервана или превысила timeout' +
705
+ (timedOut ? `: ${gateTimeoutText(gate, run.policy)}, ${loadText(timedOut)}` : '') +
706
+ (timedOutFailures ? `; до таймаута упали ${timedOutFailures}` : ''));
651
707
  // Песочница так и не запустила команду по известному отказу запуска:
652
708
  // код проекта не исполнялся, и его правка ничего не изменит. Это отказ
653
709
  // среды, а не провал проверки; текст srt вроде «Shell 'bash' not found
@@ -891,7 +947,11 @@ export async function runGate(run) {
891
947
  ...(report?.corpus?.failed.map((c) => c.property) ?? []),
892
948
  ];
893
949
  const declared = new Set(expected?.properties.map((p) => p.id) ?? []);
894
- throw new TaskFailure(kind, `${phase}/${run.consumer ? run.consumer + ':' : ''}${gate.id}: ${evidence.summary}`, failing.length
950
+ const message = `${phase}/${run.consumer ? run.consumer + ':' : ''}${gate.id}: ${evidence.summary}`;
951
+ // Таймаут без контрпримера свойства: повтор на том же SHA решает `Runner`.
952
+ if (timedOut && kind === 'gate' && !failing.length && !timedOutFailures)
953
+ throw new GateTimeout(message, timedOut);
954
+ throw new TaskFailure(kind, message, failing.length
895
955
  ? {
896
956
  bound: [...new Set(failing.filter((id) => declared.has(id)))],
897
957
  unbound: [...new Set(failing.filter((id) => !declared.has(id)))],
@@ -1048,7 +1108,7 @@ export async function prepareWriterDependencies(run) {
1048
1108
  cwd: gateCwd,
1049
1109
  env: run.execution.env,
1050
1110
  redact,
1051
- timeoutMs: gate.timeoutMs,
1111
+ timeoutMs: gateTimeoutMs(gate, run.policy),
1052
1112
  signal,
1053
1113
  write: [run.cwd],
1054
1114
  readable: run.boundary.readable,
@@ -1059,7 +1119,7 @@ export async function prepareWriterDependencies(run) {
1059
1119
  });
1060
1120
  log += checked.stdout + '\n' + checked.stderr;
1061
1121
  if (checked.timedOut)
1062
- failure = 'превышен timeout';
1122
+ failure = 'превышен timeout: ' + gateTimeoutText(gate, run.policy);
1063
1123
  else if (checked.launchFailed)
1064
1124
  failure = 'песочница ОС не запустила команду';
1065
1125
  else if (checked.code !== 0)
@@ -1080,7 +1140,7 @@ export async function prepareWriterDependencies(run) {
1080
1140
  let unreadable;
1081
1141
  try {
1082
1142
  if (guarded)
1083
- planted = protectedChanges(guarded, root);
1143
+ planted = protectedChanges(guarded, root, run.execution.prepared);
1084
1144
  }
1085
1145
  catch (error) {
1086
1146
  if (!(error instanceof SandboxPolicyError))
@@ -1090,7 +1150,7 @@ export async function prepareWriterDependencies(run) {
1090
1150
  if (planted.length || unreadable) {
1091
1151
  const message = `установка зависимостей до исполнителя (${gate.id}) ` +
1092
1152
  (unreadable ??
1093
- 'создала или изменила защищённые пути (конфигурация IDE, shell, git или Claude): ' +
1153
+ 'создала, изменила или удалила защищённые пути (конфигурация IDE, shell, git или Claude): ' +
1094
1154
  planted
1095
1155
  .slice(0, 5)
1096
1156
  .map((p) => relative(root, p))
@@ -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
- /** Незакрытые принятием попытки; checkpoints доверенного хоста проверяются целиком. */
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[];
@@ -1,4 +1,4 @@
1
- import { digestOf, HarnessError, } from "../contracts/index.js";
1
+ import { digestOf, HarnessError, WORKSPACE_OWNER, } from "../contracts/index.js";
2
2
  /**
3
3
  * Совместная проверка закреплённой комбинации SHA репозиториев.
4
4
  *
@@ -38,8 +38,17 @@ export function jointSpecDigest(view, workIds) {
38
38
  }
39
39
  /** Один и тот же набор поручений — один предмет проверки, независимо от порядка. */
40
40
  export const sameWorks = (a, b) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
41
- /** Незакрытые принятием попытки; checkpoints доверенного хоста проверяются целиком. */
42
- export function jointBudgetAttempts(view, workIds, checkpoints) {
41
+ /**
42
+ * Проверка, прерванная до результата gates (остановка хоста, потеря
43
+ * владения): без evidence она не говорит ничего о комбинации и предел не тратит.
44
+ */
45
+ export const jointInterrupted = (v) => v.status === 'failed' && v.interrupted === true && v.evidence.length === 0;
46
+ /**
47
+ * Окно бюджета набора: проверки, не закрытые принятием хоста и не снятые
48
+ * явным сбросом (`joint-budget-resets`). Checkpoints доверенного хоста
49
+ * проверяются целиком.
50
+ */
51
+ export function jointBudgetWindow(view, workIds, checkpoints) {
43
52
  const invalid = () => {
44
53
  throw new HarnessError('INVALID_INPUT', 'Невалидная принятая граница бюджета совместных проверок');
45
54
  };
@@ -73,8 +82,19 @@ export function jointBudgetAttempts(view, workIds, checkpoints) {
73
82
  settled.add(id);
74
83
  }
75
84
  }
85
+ for (const { value } of view.locals('joint-budget-resets', WORKSPACE_OWNER))
86
+ if (sameWorks(value.workIds, workIds))
87
+ for (const id of value.settledVerificationIds)
88
+ settled.add(id);
76
89
  return view.verifications().filter((v) => sameWorks(v.workIds, workIds) && !settled.has(v.id));
77
90
  }
91
+ /**
92
+ * Проверки набора, тратящие его предел: окно бюджета без прерванных до
93
+ * результата gates. Прерванная после evidence и отказ gate тратят.
94
+ */
95
+ export function jointBudgetAttempts(view, workIds, checkpoints) {
96
+ return jointBudgetWindow(view, workIds, checkpoints).filter((v) => !jointInterrupted(v));
97
+ }
78
98
  /** Gates совместной проверки в порядке их зависимостей. */
79
99
  export function orderedWorkspaceGates(gates) {
80
100
  const byId = new Map(gates.map((g) => [g.id, g]));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "devcontour-harness",
3
- "version": "0.1.0-alpha.37",
3
+ "version": "0.1.0-alpha.44",
4
4
  "description": "Headless execution harness: work graph, isolated attempts, gates, independent reviews and accepted results.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -4040,6 +4040,10 @@
4040
4040
  "type": "string",
4041
4041
  "minLength": 1
4042
4042
  },
4043
+ "interrupted": {
4044
+ "type": "boolean",
4045
+ "const": true
4046
+ },
4043
4047
  "token": {
4044
4048
  "type": "string",
4045
4049
  "minLength": 16,
@@ -2042,6 +2042,11 @@
2042
2042
  "minimum": 0,
2043
2043
  "maximum": 2
2044
2044
  },
2045
+ "gateTimeoutFloorMs": {
2046
+ "type": "integer",
2047
+ "minimum": 1000,
2048
+ "maximum": 600000
2049
+ },
2045
2050
  "stallSweep": {
2046
2051
  "type": "object",
2047
2052
  "properties": {