devcontour-harness 0.1.0-alpha.24 → 0.1.0-alpha.26

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 (50) hide show
  1. package/README.md +44 -2
  2. package/docs/architecture.md +13 -0
  3. package/docs/compatibility.md +2 -0
  4. package/docs/connectors.md +69 -3
  5. package/docs/contracts.md +15 -1
  6. package/docs/release-notes/0.1.0-alpha.25.md +33 -0
  7. package/docs/release-notes/0.1.0-alpha.26.md +35 -0
  8. package/docs/review-protocol.md +9 -1
  9. package/lib/agents/cli-adapter.d.ts +6 -0
  10. package/lib/agents/cli-adapter.js +12 -2
  11. package/lib/agents/review-probe.d.ts +5 -0
  12. package/lib/agents/review-probe.js +29 -9
  13. package/lib/agents/schemas.d.ts +4 -0
  14. package/lib/agents/schemas.js +3 -1
  15. package/lib/cli.js +9 -5
  16. package/lib/contracts/cli.d.ts +60 -1
  17. package/lib/contracts/cli.js +36 -2
  18. package/lib/contracts/failure.js +1 -1
  19. package/lib/contracts/ports.d.ts +17 -0
  20. package/lib/contracts/review.d.ts +69 -0
  21. package/lib/contracts/review.js +29 -14
  22. package/lib/contracts/work.d.ts +6 -0
  23. package/lib/contracts/work.js +13 -12
  24. package/lib/control/review.js +9 -2
  25. package/lib/engine/engine.js +4 -2
  26. package/lib/engine/prompt.js +8 -2
  27. package/lib/engine/runner.js +7 -3
  28. package/lib/environment/bounded-read.d.ts +12 -0
  29. package/lib/environment/bounded-read.js +40 -0
  30. package/lib/integrations/connector/commands.d.ts +35 -7
  31. package/lib/integrations/connector/commands.js +52 -7
  32. package/lib/integrations/connector/config.d.ts +37 -0
  33. package/lib/integrations/connector/config.js +37 -5
  34. package/lib/integrations/connector/delivery.js +17 -1
  35. package/lib/integrations/connector/index.d.ts +2 -2
  36. package/lib/integrations/connector/index.js +1 -1
  37. package/lib/integrations/connector/snapshot.d.ts +10 -8
  38. package/lib/integrations/connector/snapshot.js +78 -8
  39. package/lib/integrations/connector/source.d.ts +8 -2
  40. package/lib/integrations/connector/source.js +32 -6
  41. package/lib/integrations/connector/summary.d.ts +6 -0
  42. package/lib/integrations/connector/summary.js +5 -0
  43. package/lib/integrations/connector/testing.js +18 -0
  44. package/lib/integrations/relay-v1/index.js +6 -4
  45. package/lib/integrations/relay-v2/protocol.js +8 -6
  46. package/lib/verification/confirm.js +10 -2
  47. package/lib/verification/gates.js +34 -12
  48. package/lib/verification/joint.d.ts +120 -1
  49. package/lib/verification/joint.js +38 -1
  50. package/package.json +6 -3
@@ -1,5 +1,5 @@
1
1
  import { HarnessError, digestOf, } from "../../contracts/index.js";
2
- import { connectorIdOf, parseIdentity } from "./config.js";
2
+ import { baselineRecord, connectorIdOf, orderIdOf, parseIdentity, } from "./config.js";
3
3
  import { assertEligible, readFailure, semanticDigest, takeSnapshot, } from "./snapshot.js";
4
4
  import { TransportError } from "./transport.js";
5
5
  /**
@@ -10,8 +10,9 @@ import { TransportError } from "./transport.js";
10
10
  * - `revision` — текущий semantic digest задачи (или набора) для обнаружения
11
11
  * конфликта; ошибка сети/CLI — исключение, а не «записи нет»;
12
12
  * - `trusts` — только receipt, выданный этим коннектором (`issuer` = его ID),
13
- * digest которого совпадает с записью в его состоянии. Статус задачи done
14
- * доверием не является.
13
+ * digest которого совпадает с записью в его состоянии, либо запись базовой
14
+ * линии текущей конфигурации для задачи, которую подтверждает backend.
15
+ * Статус задачи done доверием не является.
15
16
  */
16
17
  export class RelayWorkSource {
17
18
  options;
@@ -59,16 +60,41 @@ export class RelayWorkSource {
59
60
  const mapping = config.tasks.find((m) => m.ref === read.task.id || m.ref === read.task.key);
60
61
  return mapping ? semanticDigest(config, mapping, read) : undefined;
61
62
  }
62
- trusts(prerequisite) {
63
+ async trusts(prerequisite) {
63
64
  const receipt = prerequisite.receipt;
64
65
  if (receipt.kind !== 'trusted' || receipt.issuer !== this.id)
65
- return Promise.resolve(false);
66
+ return false;
66
67
  const stored = this.options.store
67
68
  .receipts(prerequisite.id)
68
69
  .find((r) => r.issuer === this.id &&
69
70
  digestOf(r) === receipt.digest &&
70
71
  r.resultSha === prerequisite.resultSha &&
71
72
  r.repositoryId === prerequisite.repositoryId);
72
- return Promise.resolve(Boolean(stored));
73
+ return Boolean(stored) || this.trustsBaseline(prerequisite, receipt.digest);
74
+ }
75
+ /**
76
+ * Предпосылка базовой линии сверяется с загруженной конфигурацией целиком.
77
+ * Digest не секрет: что ключ — именно задача предпосылки, подтверждает backend.
78
+ */
79
+ async trustsBaseline(prerequisite, digest) {
80
+ const config = this.options.config;
81
+ if (prerequisite.resultSha !== config.baseline?.sha)
82
+ return false;
83
+ const repositories = config.tasks.map((m) => m.repositoryId ?? config.repository.id);
84
+ if (!repositories.includes(prerequisite.repositoryId))
85
+ return false;
86
+ const key = config.baseline.tasks.find((k) => digestOf(baselineRecord(config, k, prerequisite.id, prerequisite.repositoryId)) === digest);
87
+ if (!key)
88
+ return false;
89
+ try {
90
+ const { task } = await this.options.transport.readTask(key);
91
+ return (task.key === key &&
92
+ orderIdOf(config.provider, config.projectId, task.id) === prerequisite.id);
93
+ }
94
+ catch (error) {
95
+ if (error instanceof TransportError && error.kind === 'not-found')
96
+ return false;
97
+ throw readFailure(error, 'Задача ' + key);
98
+ }
73
99
  }
74
100
  }
@@ -31,6 +31,12 @@ export declare function summaryText(input: {
31
31
  criteria: CriterionOutcome[];
32
32
  completion: string;
33
33
  historical?: boolean;
34
+ /** Зависимости задачи, принятые человеком по базовой линии (не доказаны). */
35
+ baseline?: {
36
+ tasks: string[];
37
+ sha: string;
38
+ reason: string;
39
+ };
34
40
  redact?: Redactor;
35
41
  }): {
36
42
  title: string;
@@ -29,6 +29,11 @@ export function summaryText(input) {
29
29
  ? [`- Причина: ${r.stopReason.code}: ${r.stopReason.message.slice(0, 500)}`]
30
30
  : []),
31
31
  `- Снимок постановки: ${input.task.identity} @ ${input.snapshot.revision} (CAS ${input.snapshot.casRevision})`,
32
+ ...(input.baseline
33
+ ? [
34
+ `- Зависимости без доказательства: ${input.baseline.tasks.join(', ')} приняты человеком по базовой линии @ ${shortSha(input.baseline.sha)}: ${input.baseline.reason}`,
35
+ ]
36
+ : []),
32
37
  '',
33
38
  '**Gates**',
34
39
  ...(gates.length ? gates : ['- нет записей']),
@@ -811,6 +811,7 @@ export function connectorSuite(backend, options = {}) {
811
811
  const snapD = await connD.snapshot(join(s.root, 'snapshot-d'));
812
812
  assert.equal(snapD.eligible, false);
813
813
  assert.ok(snapD.problems.some((p) => p.includes('DEPENDENCY_UNPROVEN')), snapD.problems.join('; '));
814
+ assert.ok(snapD.problems.some((p) => p.includes('baseline.tasks')), 'отказ называет выход: явное решение человека');
814
815
  const writer = s.calls.writer;
815
816
  await assert.rejects(connD.run(opened.h, { author: 'claude' }), refusedWith('NOT_READY'));
816
817
  assert.equal(s.calls.writer, writer);
@@ -818,6 +819,23 @@ export function connectorSuite(backend, options = {}) {
818
819
  finally {
819
820
  connD.close();
820
821
  }
822
+ // Человек принимает задачу явно: ключ backend, полный SHA, причина.
823
+ const sha = s.target();
824
+ cfgD.baseline = { sha, tasks: [c.key], reason: 'Closed before adoption' };
825
+ const connE = await openConnector(parseConfig(cfgD, s.root), {
826
+ stateDir: s.state,
827
+ transport: s.project.transport(),
828
+ });
829
+ try {
830
+ const snapE = await connE.snapshot(join(s.root, 'snapshot-e'));
831
+ assert.equal(snapE.eligible, true, snapE.problems.join('; '));
832
+ const accepted = snapE.snapshot.graph.prerequisites[0];
833
+ assert.equal(accepted.resultSha, sha);
834
+ assert.equal(await connE.source.trusts(accepted), true, 'ключ разрешён backend');
835
+ }
836
+ finally {
837
+ connE.close();
838
+ }
821
839
  }
822
840
  finally {
823
841
  await s.cleanup();
@@ -56,6 +56,8 @@ const envelopeSchema = z.union([
56
56
  }),
57
57
  }),
58
58
  ]);
59
+ /** Предел массива в ответе Relay: страница запрашивается по 100 элементов. */
60
+ const MAX_ITEMS = 10_000;
59
61
  const columnSchema = z.enum(['inbox', 'ready', 'in-progress', 'review', 'done', 'cancelled']);
60
62
  const revisionSchema = z.number().int().nonnegative();
61
63
  const idString = z.string().min(1);
@@ -66,12 +68,12 @@ const taskSummarySchema = z.object({
66
68
  column: columnSchema,
67
69
  revision: revisionSchema,
68
70
  parentId: z.string().nullable(),
69
- dependencies: z.array(z.string()),
71
+ dependencies: z.array(z.string()).max(MAX_ITEMS),
70
72
  canComplete: z.boolean().optional(),
71
73
  });
72
74
  const taskViewSchema = taskSummarySchema.extend({ description: z.string() });
73
75
  const offsetPage = (item) => z.object({
74
- items: z.array(item),
76
+ items: z.array(item).max(MAX_ITEMS),
75
77
  total: z.number().int().nonnegative(),
76
78
  nextOffset: z.number().int().nonnegative().nullable(),
77
79
  version: z.string().min(1),
@@ -101,7 +103,7 @@ const commentSummarySchema = z.object({
101
103
  });
102
104
  const commentSchema = commentSummarySchema.extend({ description: z.string() });
103
105
  const commentsPageSchema = z.object({
104
- items: z.array(commentSummarySchema),
106
+ items: z.array(commentSummarySchema).max(MAX_ITEMS),
105
107
  nextCursor: z.string().nullable(),
106
108
  snapshot: z.number().int().nonnegative(),
107
109
  });
@@ -121,7 +123,7 @@ const documentDetailSchema = entitySummarySchema.extend({
121
123
  const healthSchema = z.object({ status: z.string(), contractVersion: z.number().int() });
122
124
  const contextSchema = z.object({
123
125
  projectId: z.string().min(1),
124
- capabilities: z.array(z.string()).optional(),
126
+ capabilities: z.array(z.string()).max(MAX_ITEMS).optional(),
125
127
  });
126
128
  const sessionSchema = z.object({
127
129
  id: idString,
@@ -31,6 +31,8 @@ export const columnSchema = z.enum([
31
31
  'done',
32
32
  'cancelled',
33
33
  ]);
34
+ /** Предел массива в ответе Relay-2: размер всего ответа ограничен транспортом. */
35
+ const MAX_ITEMS = 10_000;
34
36
  /** Общий envelope записи: `{id, kind, key, revision, …, data}`. */
35
37
  const envelope = (kind, data) => z.object({
36
38
  id: z.string().min(1),
@@ -60,14 +62,14 @@ export const taskSchema = envelope('task', z.object({
60
62
  description: nullableText,
61
63
  column: columnSchema,
62
64
  parentId: z.string().nullable(),
63
- dependencies: z.array(z.string()),
64
- acceptanceCriteria: z.array(criterionSchema),
65
- comments: z.array(commentSchema).optional(),
65
+ dependencies: z.array(z.string()).max(MAX_ITEMS),
66
+ acceptanceCriteria: z.array(criterionSchema).max(MAX_ITEMS),
67
+ comments: z.array(commentSchema).max(MAX_ITEMS).optional(),
66
68
  }));
67
69
  export const progressSchema = z.object({
68
70
  completed: z.boolean(),
69
71
  canComplete: z.boolean(),
70
- blockers: z.array(z.string()),
72
+ blockers: z.array(z.string()).max(MAX_ITEMS),
71
73
  });
72
74
  export const documentSchema = envelope('document', z.object({ name: z.string(), body: z.string() }));
73
75
  export const sessionSchema = envelope('work-session', z.object({
@@ -96,7 +98,7 @@ export const doctorSchema = z.object({
96
98
  projectId: z.string().min(1),
97
99
  generation: z.number().int().nonnegative(),
98
100
  valid: z.boolean(),
99
- issues: z.array(z.unknown()),
101
+ issues: z.array(z.unknown()).max(MAX_ITEMS),
100
102
  });
101
103
  export const pageMetaSchema = z.object({
102
104
  page: z.object({
@@ -104,7 +106,7 @@ export const pageMetaSchema = z.object({
104
106
  consistency: z.string().optional(),
105
107
  }),
106
108
  });
107
- export const itemsSchema = z.object({ items: z.array(z.unknown()) });
109
+ export const itemsSchema = z.object({ items: z.array(z.unknown()).max(MAX_ITEMS) });
108
110
  /** Стабильный код Relay-2 → класс отказа транспорта. Exit code — только грубый класс. */
109
111
  export function classifyCode(code, exit, mutation) {
110
112
  switch (code) {
@@ -1,9 +1,10 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
2
+ 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
6
  import { HarnessError, idSchema, } from "../contracts/index.js";
7
+ import { OversizedFile, readBounded } from "../environment/bounded-read.js";
7
8
  import { executionEnvironment, runSteps, withEnvironment } from "../environment/lifecycle.js";
8
9
  import { git, hostGitArgs } from "../environment/process.js";
9
10
  import { contractDocuments, obligationOf } from "./checks.js";
@@ -57,6 +58,8 @@ export const caseInputSchema = z.strictObject({
57
58
  });
58
59
  /** Точка после записи версии и до принятия: тест моделирует в ней сбой. */
59
60
  export const caseHooks = { afterRecord: () => undefined };
61
+ /** Файл результата пишет проверяемый код; случай корпуса — не больше 64 КиБ. */
62
+ const CASE_RESULT_LIMIT = 1024 * 1024;
60
63
  const caseResult = z.object({
61
64
  property: z.string(),
62
65
  valid: z.boolean().optional(),
@@ -323,7 +326,12 @@ async function decide(ctx, work, ref, input, source) {
323
326
  runs.push({ property: input.property, error: 'timeout' });
324
327
  break;
325
328
  }
326
- const parsed = caseResult.safeParse(JSON.parse(await readFile(out, 'utf8').catch(() => 'null')));
329
+ const raw = await readBounded(out, CASE_RESULT_LIMIT).catch((error) => {
330
+ if (error instanceof OversizedFile)
331
+ throw error;
332
+ return 'null';
333
+ });
334
+ const parsed = caseResult.safeParse(JSON.parse(raw));
327
335
  runs.push(parsed.success ? parsed.data : { property: input.property, error: 'нет результата' });
328
336
  }
329
337
  });
@@ -145,6 +145,9 @@ export function junitSummary(xml, redact = (value) => value) {
145
145
  throw new Error('JUnit не содержит выполненных testcases');
146
146
  return summary;
147
147
  }
148
+ const ansiEscape = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
149
+ /** Путь с расширением и координаты, после необязательного префикса `пакет скрипт: `. */
150
+ const compilerError = /^(?:\S+(?: \S+)?: )?[^\s:]+?\.[A-Za-z][A-Za-z0-9]{0,9}(?:\(\d+,\d+\): |:\d+(?::\d+)?(?:: | - ))(?:fatal )?error(?: [A-Z]+\d+)?:/;
148
151
  /**
149
152
  * Короткая выжимка вывода провалившейся проверки.
150
153
  *
@@ -152,7 +155,8 @@ export function junitSummary(xml, redact = (value) => value) {
152
155
  * доступен, а в отказ попадал только «Код выхода 1». Два разных провала одной
153
156
  * проверки выглядели одной причиной — предел одинаковых повторов исчерпывался
154
157
  * на несвязанных ошибках, и подсказка повтора не содержала ничего, кроме кода
155
- * возврата. Берутся последние содержательные строки обоих потоков: ошибку
158
+ * возврата. Берутся последние содержательные строки обоих потоков и первая
159
+ * ошибка компилятора с координатами перед ними: ошибку
156
160
  * одни инструменты пишут в stdout, другие в stderr, и одинаковое
157
161
  * предупреждение в одном потоке не должно закрывать ошибку в другом. Секреты
158
162
  * снимаются тем же redact, что и в логе; объём ограничен.
@@ -161,15 +165,28 @@ function diagnostic(stderr, stdout, redact) {
161
165
  // У каждого потока свой бюджет: общий лимит, заполняемый по очереди,
162
166
  // позволял нескольким длинным строкам одного потока вытеснить ошибку
163
167
  // другого. Redact — до обрезки, иначе префикс секрета остаётся.
168
+ const clip = (line) => (line.length > 140 ? line.slice(0, 140) + '…' : line);
164
169
  const tail = (text) => {
165
- const joined = text
170
+ const lines = text
166
171
  .split('\n')
167
172
  .map((line) => (redact ? redact(line) : line).trim())
168
- .filter(Boolean)
169
- .slice(-4)
170
- .map((line) => (line.length > 140 ? line.slice(0, 140) + '…' : line))
171
- .join(' | ');
172
- return joined.length > 290 ? '…' + joined.slice(-290) : joined;
173
+ .filter(Boolean);
174
+ const last = lines.slice(-4);
175
+ const joined = last.map(clip).join(' | ');
176
+ const ending = joined.length > 290 ? '…' + joined.slice(-290) : joined;
177
+ // Компилятор печатает причину раньше итогов package manager, и хвост её
178
+ // вытесняет. Первая ошибка дописывается к хвосту, а не заменяет его: отпечаток
179
+ // отказа различает провалы по хвосту, а распознавание по строке — эвристика.
180
+ // Цвет снимается до redact, иначе обрезка оставит склеенный им префикс секрета.
181
+ // Проверяется обрезанная строка: это ограничивает разбор и гарантирует, что
182
+ // найденное попадёт в итог.
183
+ const cause = text
184
+ .split('\n')
185
+ .map((line) => line.replace(ansiEscape, ''))
186
+ .map((line) => clip((redact ? redact(line) : line).trim()))
187
+ .find((line) => compilerError.test(line));
188
+ const visible = cause && ending.replace(ansiEscape, '').includes(cause.replace(/…$/, ''));
189
+ return cause && !visible ? cause + ' | ' + ending : ending;
173
190
  };
174
191
  return [tail(stdout), tail(stderr)].filter(Boolean).join(' | ');
175
192
  }
@@ -537,6 +554,16 @@ export async function runGate(run) {
537
554
  if (result.timedOut || signal.aborted)
538
555
  throw new Error('Проверка прервана или превысила timeout');
539
556
  if (result.code !== 0) {
557
+ // Сохраняем валидный отчёт и при отказе команды, до классификации
558
+ // песочницы: после очистки worktree иначе остаётся только хвост лога.
559
+ const counts = reportPath
560
+ ? await readReport(reportPath, cwd, redact).catch(() => undefined)
561
+ : undefined;
562
+ if (counts) {
563
+ manifest = counts;
564
+ await mkdir(artifactDir, { recursive: true });
565
+ await writeFile(join(artifactDir, `${gate.id}.xml`), redact(counts.xml));
566
+ }
540
567
  const blocked = run.policy.isolation.mode === 'os'
541
568
  ? sandboxBlockedHosts(result.stdout + '\n' + result.stderr, run.policy.isolation.domains)
542
569
  : [];
@@ -560,11 +587,6 @@ export async function runGate(run) {
560
587
  (denied.length > 3 ? ` и ещё ${denied.length - 3}` : '') +
561
588
  `. Код выхода ${result.code}: ${diagnostic(result.stderr, result.stdout, redact)}`);
562
589
  }
563
- const counts = reportPath
564
- ? await readReport(reportPath, cwd, redact).catch(() => undefined)
565
- : undefined;
566
- if (counts)
567
- manifest = counts;
568
590
  throw new Error([
569
591
  `Код выхода ${result.code}`,
570
592
  counts?.failures ? `упали ${failedCases(counts)}` : '',
@@ -1,4 +1,4 @@
1
- import { type ExecutionPolicy, type ExecutionView, type JointVerification, type JointVerificationState } from '../contracts/index.ts';
1
+ import { type ExecutionPolicy, type ExecutionView, type JointVerification, type JointVerificationState, type JointBudgetCheckpoint } from '../contracts/index.ts';
2
2
  /**
3
3
  * Совместная проверка закреплённой комбинации SHA репозиториев.
4
4
  *
@@ -16,6 +16,125 @@ 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 доверенного хоста проверяются целиком. */
20
+ export declare function jointBudgetAttempts(view: ExecutionView, workIds: string[], checkpoints: readonly JointBudgetCheckpoint[]): ({
21
+ status: "active";
22
+ apiVersion: "devcontour-harness/v1alpha1";
23
+ id: string;
24
+ startedAt: string;
25
+ policyDigest: string;
26
+ specDigest: string;
27
+ workIds: string[];
28
+ evidence: {
29
+ gate: string;
30
+ passed: boolean;
31
+ command: string[];
32
+ exitCode: number;
33
+ log: string;
34
+ digest: string;
35
+ summary: string;
36
+ artifacts: {
37
+ path: string;
38
+ digest: string;
39
+ }[];
40
+ durationMs?: number | undefined;
41
+ }[];
42
+ token: string;
43
+ leaseUntil: number;
44
+ manifest?: Record<string, {
45
+ sha: string;
46
+ tree: string;
47
+ }> | undefined;
48
+ manifestDigest?: string | undefined;
49
+ impact?: {
50
+ changed: string[];
51
+ affected: string[];
52
+ gateIds: string[];
53
+ mode: "all" | "affected";
54
+ reason: string;
55
+ baseline?: string | undefined;
56
+ } | undefined;
57
+ engineVersion?: string | undefined;
58
+ } | {
59
+ status: "failed";
60
+ finishedAt: string;
61
+ error: string;
62
+ apiVersion: "devcontour-harness/v1alpha1";
63
+ id: string;
64
+ startedAt: string;
65
+ policyDigest: string;
66
+ specDigest: string;
67
+ workIds: string[];
68
+ evidence: {
69
+ gate: string;
70
+ passed: boolean;
71
+ command: string[];
72
+ exitCode: number;
73
+ log: string;
74
+ digest: string;
75
+ summary: string;
76
+ artifacts: {
77
+ path: string;
78
+ digest: string;
79
+ }[];
80
+ durationMs?: number | undefined;
81
+ }[];
82
+ token: string;
83
+ leaseUntil: number;
84
+ manifest?: Record<string, {
85
+ sha: string;
86
+ tree: string;
87
+ }> | undefined;
88
+ manifestDigest?: string | undefined;
89
+ impact?: {
90
+ changed: string[];
91
+ affected: string[];
92
+ gateIds: string[];
93
+ mode: "all" | "affected";
94
+ reason: string;
95
+ baseline?: string | undefined;
96
+ } | undefined;
97
+ engineVersion?: string | undefined;
98
+ } | {
99
+ status: "passed";
100
+ finishedAt: string;
101
+ manifest: Record<string, {
102
+ sha: string;
103
+ tree: string;
104
+ }>;
105
+ manifestDigest: string;
106
+ apiVersion: "devcontour-harness/v1alpha1";
107
+ id: string;
108
+ startedAt: string;
109
+ policyDigest: string;
110
+ specDigest: string;
111
+ workIds: string[];
112
+ evidence: {
113
+ gate: string;
114
+ passed: boolean;
115
+ command: string[];
116
+ exitCode: number;
117
+ log: string;
118
+ digest: string;
119
+ summary: string;
120
+ artifacts: {
121
+ path: string;
122
+ digest: string;
123
+ }[];
124
+ durationMs?: number | undefined;
125
+ }[];
126
+ token: string;
127
+ leaseUntil: number;
128
+ impact?: {
129
+ changed: string[];
130
+ affected: string[];
131
+ gateIds: string[];
132
+ mode: "all" | "affected";
133
+ reason: string;
134
+ baseline?: string | undefined;
135
+ } | undefined;
136
+ engineVersion?: string | undefined;
137
+ })[];
19
138
  /** Gates совместной проверки в порядке их зависимостей. */
20
139
  export declare function orderedWorkspaceGates(gates: ExecutionPolicy['workspaceGates']): ({
21
140
  kind: "test";
@@ -1,4 +1,4 @@
1
- import { digestOf, } from "../contracts/index.js";
1
+ import { digestOf, HarnessError, } from "../contracts/index.js";
2
2
  /**
3
3
  * Совместная проверка закреплённой комбинации SHA репозиториев.
4
4
  *
@@ -38,6 +38,43 @@ 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) {
43
+ const invalid = () => {
44
+ throw new HarnessError('INVALID_INPUT', 'Невалидная принятая граница бюджета совместных проверок');
45
+ };
46
+ if (!Array.isArray(checkpoints))
47
+ invalid();
48
+ const settled = new Set();
49
+ const anchors = new Set();
50
+ for (const checkpoint of checkpoints) {
51
+ if (!checkpoint ||
52
+ typeof checkpoint.verificationId !== 'string' ||
53
+ !checkpoint.verificationId.length ||
54
+ !Array.isArray(checkpoint.settledVerificationIds))
55
+ invalid();
56
+ const { verificationId, settledVerificationIds: ids } = checkpoint;
57
+ const anchor = view.verification(verificationId);
58
+ if (anchors.has(verificationId) ||
59
+ !anchor ||
60
+ anchor.status !== 'passed' ||
61
+ !sameWorks(anchor.workIds, workIds) ||
62
+ !ids.length ||
63
+ new Set(ids).size !== ids.length ||
64
+ !ids.includes(verificationId))
65
+ invalid();
66
+ anchors.add(verificationId);
67
+ for (const id of ids) {
68
+ if (typeof id !== 'string' || !id.length)
69
+ invalid();
70
+ const v = view.verification(id);
71
+ if (!v || (v.status !== 'passed' && v.status !== 'failed') || !sameWorks(v.workIds, workIds))
72
+ invalid();
73
+ settled.add(id);
74
+ }
75
+ }
76
+ return view.verifications().filter((v) => sameWorks(v.workIds, workIds) && !settled.has(v.id));
77
+ }
41
78
  /** Gates совместной проверки в порядке их зависимостей. */
42
79
  export function orderedWorkspaceGates(gates) {
43
80
  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.24",
3
+ "version": "0.1.0-alpha.26",
4
4
  "description": "Headless execution harness: work graph, isolated attempts, gates, independent reviews and accepted results.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -82,9 +82,12 @@
82
82
  "schemas:check": "node --import tsx scripts/build-schemas.ts --check",
83
83
  "lint": "eslint .",
84
84
  "test": "node scripts/test.mjs",
85
+ "test:fast": "node scripts/test.mjs --fast",
86
+ "test:affected": "node scripts/test.mjs --affected",
85
87
  "test:integration": "node --import tsx --test --test-concurrency=1 --test-timeout=1800000 tests/integration/*.test.ts",
86
88
  "test:package": "npm run build && node scripts/smoke-package.mjs",
87
- "check": "npm run lint && npm run typecheck && npm run schemas:check && npm run build && npm test && node scripts/smoke-package.mjs",
89
+ "check": "node scripts/static-checks.mjs && npm run build && node scripts/test.mjs --release && node scripts/smoke-package.mjs",
90
+ "check:fast": "node scripts/static-checks.mjs && node scripts/test.mjs --affected",
88
91
  "format": "prettier --write .",
89
92
  "format:check": "prettier --check .",
90
93
  "check:install": "node scripts/install-check.mjs"
@@ -92,7 +95,7 @@
92
95
  "dependencies": {
93
96
  "@anthropic-ai/sandbox-runtime": "0.0.77",
94
97
  "fast-xml-parser": "5.11.1",
95
- "zod": "4.6.5"
98
+ "zod": "4.6.7"
96
99
  },
97
100
  "devDependencies": {
98
101
  "@types/node": "24.13.5",