devcontour-harness 0.1.0-alpha.25 → 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 (43) hide show
  1. package/README.md +9 -2
  2. package/docs/compatibility.md +2 -0
  3. package/docs/connectors.md +69 -3
  4. package/docs/contracts.md +15 -1
  5. package/docs/release-notes/0.1.0-alpha.26.md +35 -0
  6. package/docs/review-protocol.md +9 -1
  7. package/lib/agents/cli-adapter.d.ts +6 -0
  8. package/lib/agents/cli-adapter.js +12 -2
  9. package/lib/agents/review-probe.d.ts +5 -0
  10. package/lib/agents/review-probe.js +29 -9
  11. package/lib/agents/schemas.d.ts +4 -0
  12. package/lib/agents/schemas.js +3 -1
  13. package/lib/cli.js +9 -5
  14. package/lib/contracts/cli.d.ts +60 -1
  15. package/lib/contracts/cli.js +36 -2
  16. package/lib/contracts/failure.js +1 -1
  17. package/lib/contracts/review.d.ts +69 -0
  18. package/lib/contracts/review.js +29 -14
  19. package/lib/contracts/work.d.ts +6 -0
  20. package/lib/contracts/work.js +13 -12
  21. package/lib/control/review.js +9 -2
  22. package/lib/engine/runner.js +7 -3
  23. package/lib/environment/bounded-read.d.ts +12 -0
  24. package/lib/environment/bounded-read.js +40 -0
  25. package/lib/integrations/connector/commands.d.ts +35 -7
  26. package/lib/integrations/connector/commands.js +52 -7
  27. package/lib/integrations/connector/config.d.ts +37 -0
  28. package/lib/integrations/connector/config.js +37 -5
  29. package/lib/integrations/connector/delivery.js +17 -1
  30. package/lib/integrations/connector/index.d.ts +2 -2
  31. package/lib/integrations/connector/index.js +1 -1
  32. package/lib/integrations/connector/snapshot.d.ts +10 -8
  33. package/lib/integrations/connector/snapshot.js +78 -8
  34. package/lib/integrations/connector/source.d.ts +8 -2
  35. package/lib/integrations/connector/source.js +32 -6
  36. package/lib/integrations/connector/summary.d.ts +6 -0
  37. package/lib/integrations/connector/summary.js +5 -0
  38. package/lib/integrations/connector/testing.js +18 -0
  39. package/lib/integrations/relay-v1/index.js +6 -4
  40. package/lib/integrations/relay-v2/protocol.js +8 -6
  41. package/lib/verification/confirm.js +10 -2
  42. package/lib/verification/gates.js +24 -7
  43. package/package.json +2 -2
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { API_VERSION, STATE_VERSION } from "./version.js";
3
3
  import { digestSchema, gitShaSchema, idSchema, isoTimeSchema, runtimeNameSchema, targetRefSchema, } from "./primitives.js";
4
- import { errorCodes } from "./errors.js";
4
+ import { HarnessError, errorCodes } from "./errors.js";
5
5
  import { controlStateSchema, controllerLeaseSchema, workStatusSchema } from "./execution.js";
6
6
  import { runEventSchema } from "./events.js";
7
7
  import { deliveryStateSchema, resultEnvelopeSchema } from "./result.js";
@@ -573,11 +573,18 @@ export const eventsDataSchema = z.strictObject({
573
573
  /** Номер для следующего `--after`. */
574
574
  next: z.number().int().min(0),
575
575
  });
576
+ /** Зависимости, принятые человеком по базовой линии: решение, а не доказательство. */
577
+ const baselineViewSchema = z.strictObject({
578
+ sha: gitShaSchema,
579
+ reason: z.string(),
580
+ tasks: z.array(z.string()),
581
+ });
576
582
  export const runDataSchema = z.strictObject({
577
583
  graphId: idSchema,
578
584
  digest: digestSchema,
579
585
  /** Граф уже был зарегистрирован этой редакцией: работа продолжена. */
580
586
  resumed: z.boolean(),
587
+ baseline: baselineViewSchema.optional(),
581
588
  works: z.array(z.strictObject({
582
589
  id: idSchema,
583
590
  status: workStatusSchema,
@@ -687,17 +694,28 @@ export const sourceCheckDataSchema = z.strictObject({
687
694
  ownership: ownershipSchema,
688
695
  problems: z.array(z.string()),
689
696
  });
697
+ /** Закреплённый локальный пакет `tasks[].context`: то, что называет manifest снимка. */
698
+ export const localContextManifestSchema = z.strictObject({
699
+ id: idSchema,
700
+ digest: digestSchema,
701
+ files: z.number().int().nonnegative(),
702
+ references: z.number().int().nonnegative(),
703
+ bytes: z.number().int().nonnegative(),
704
+ });
690
705
  export const sourceSnapshotDataSchema = z.strictObject({
691
706
  connector: idSchema,
692
707
  graphId: idSchema,
693
708
  graphDigest: digestSchema,
694
709
  contextDigest: digestSchema,
710
+ /** Пакеты `tasks[].context`; без них поля нет. */
711
+ localContext: z.array(localContextManifestSchema).optional(),
695
712
  /** Semantic digest набора задач (`graph.source.revision`); не Git SHA. */
696
713
  revision: digestSchema,
697
714
  created: z.boolean(),
698
715
  eligible: z.boolean(),
699
716
  problems: z.array(z.string()),
700
717
  truncated: z.array(z.string()),
718
+ baseline: baselineViewSchema.optional(),
701
719
  tasks: z.array(z.strictObject({
702
720
  identity: z.string(),
703
721
  key: z.string(),
@@ -727,7 +745,13 @@ export const sourceStatusDataSchema = z.strictObject({
727
745
  connector: idSchema,
728
746
  provider: providerSchema,
729
747
  projectId: z.string(),
730
- snapshot: z.strictObject({ revision: digestSchema, graphId: idSchema }).optional(),
748
+ snapshot: z
749
+ .strictObject({
750
+ revision: digestSchema,
751
+ graphId: idSchema,
752
+ baseline: baselineViewSchema.optional(),
753
+ })
754
+ .optional(),
731
755
  ownership: ownershipSchema,
732
756
  tasks: z.array(z.strictObject({
733
757
  index: z.number().int(),
@@ -847,5 +871,15 @@ export const cliErrorSchema = z.strictObject({
847
871
  message: z.string(),
848
872
  issues: z.array(z.strictObject({ path: z.array(z.union([z.string(), z.number()])), message: z.string() })),
849
873
  });
874
+ /**
875
+ * Нарушение схемы внутри harness (ответ команды вне договора, собственная
876
+ * запись) — дефект, а не ошибка ввода: INTERNAL с путями полей вместо дампа
877
+ * ZodError в сообщении.
878
+ */
879
+ export const contractViolation = (error) => new HarnessError('INTERNAL', 'Данные harness не соответствуют его договору (дефект harness, а не настроек): ' +
880
+ error.issues.map((i) => `${i.path.join('.') || '(корень)'}: ${i.message}`).join('; '), error.issues.map((i) => ({
881
+ path: i.path.filter((p) => typeof p !== 'symbol'),
882
+ message: i.message,
883
+ })));
850
884
  /** Входной документ контракта для `review-contract` — см. `checks.ts`. */
851
885
  export { contractDocumentSchema } from "./checks.js";
@@ -46,7 +46,7 @@ export function failureFingerprint(kind, message) {
46
46
  // Предел выше всей диагностики проверки (оба потока и упавшие testcases,
47
47
  // каждое со своим лимитом): при прежних 300 символах ошибка stderr
48
48
  // оказывалась за пределом, и разные провалы получали один отпечаток.
49
- .slice(0, 2000);
49
+ .slice(0, 4000);
50
50
  return createHash('sha256')
51
51
  .update(kind + '\n' + normalized)
52
52
  .digest('hex')
@@ -83,6 +83,12 @@ export declare const alreadySatisfiedSchema: z.ZodObject<{
83
83
  evidence: z.ZodString;
84
84
  }, z.core.$strict>;
85
85
  export type AlreadySatisfied = z.infer<typeof alreadySatisfiedSchema>;
86
+ /**
87
+ * Предел находок и переходов в одном ответе reviewer и в раунде истории. Без
88
+ * предела каждый лишний элемент ответа давал отдельные ошибки разбора и
89
+ * гигабайты кучи. Реальные ответы на порядки меньше.
90
+ */
91
+ export declare const REVIEW_ITEMS_LIMIT = 500;
86
92
  export declare const reviewResultSchema: z.ZodObject<{
87
93
  execution: z.ZodOptional<z.ZodObject<{
88
94
  commands: z.ZodArray<z.ZodObject<{
@@ -143,6 +149,69 @@ export declare const reviewResultSchema: z.ZodObject<{
143
149
  }, z.core.$strict>>>;
144
150
  }, z.core.$strip>;
145
151
  export type ReviewResult = z.infer<typeof reviewResultSchema>;
152
+ /**
153
+ * Записанный ответ reviewer (`review.json`). Предел `reviewResultSchema` —
154
+ * граница приёма: файлы прежних версий с длинными списками читаются и дальше.
155
+ */
156
+ export declare const storedReviewResultSchema: z.ZodObject<{
157
+ execution: z.ZodOptional<z.ZodObject<{
158
+ commands: z.ZodArray<z.ZodObject<{
159
+ command: z.ZodString;
160
+ exitCode: z.ZodNumber;
161
+ summary: z.ZodString;
162
+ }, z.core.$strict>>;
163
+ noCommandsReason: z.ZodNullable<z.ZodString>;
164
+ }, z.core.$strict>>;
165
+ approved: z.ZodBoolean;
166
+ summary: z.ZodString;
167
+ discoveries: z.ZodDefault<z.ZodArray<z.ZodObject<{
168
+ kind: z.ZodEnum<{
169
+ bug: "bug";
170
+ debt: "debt";
171
+ }>;
172
+ title: z.ZodString;
173
+ path: z.ZodString;
174
+ line: z.ZodNumber;
175
+ observation: z.ZodString;
176
+ consequence: z.ZodString;
177
+ reproduction: z.ZodString;
178
+ }, z.core.$strict>>>;
179
+ alreadySatisfied: z.ZodOptional<z.ZodNullable<z.ZodObject<{
180
+ gates: z.ZodArray<z.ZodString>;
181
+ evidence: z.ZodString;
182
+ }, z.core.$strict>>>;
183
+ findings: z.ZodArray<z.ZodObject<{
184
+ severity: z.ZodEnum<{
185
+ blocking: "blocking";
186
+ note: "note";
187
+ }>;
188
+ message: z.ZodString;
189
+ path: z.ZodOptional<z.ZodNullable<z.ZodString>>;
190
+ line: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
191
+ rule: z.ZodOptional<z.ZodNullable<z.ZodString>>;
192
+ consequence: z.ZodOptional<z.ZodNullable<z.ZodString>>;
193
+ evidence: z.ZodOptional<z.ZodNullable<z.ZodString>>;
194
+ reproduction: z.ZodCatch<z.ZodOptional<z.ZodNullable<z.ZodObject<{
195
+ property: z.ZodNullable<z.ZodString>;
196
+ input: z.ZodString;
197
+ inputClass: z.ZodOptional<z.ZodNullable<z.ZodString>>;
198
+ expected: z.ZodNullable<z.ZodString>;
199
+ actual: z.ZodNullable<z.ZodString>;
200
+ command: z.ZodNullable<z.ZodArray<z.ZodString>>;
201
+ executed: z.ZodBoolean;
202
+ run: z.ZodOptional<z.ZodNullable<z.ZodString>>;
203
+ }, z.core.$strip>>>>;
204
+ }, z.core.$strip>>;
205
+ previous: z.ZodDefault<z.ZodArray<z.ZodObject<{
206
+ id: z.ZodString;
207
+ status: z.ZodEnum<{
208
+ open: "open";
209
+ closed: "closed";
210
+ withdrawn: "withdrawn";
211
+ }>;
212
+ basis: z.ZodString;
213
+ }, z.core.$strict>>>;
214
+ }, z.core.$strip>;
146
215
  /** Идентичность находки: предмет, класс и текст. Новый текст — новая находка. */
147
216
  export declare const findingId: (subject: string, finding: {
148
217
  rule?: string | null;
@@ -74,23 +74,30 @@ export const alreadySatisfiedSchema = z.strictObject({
74
74
  gates: gateScopeSchema(z.string().min(1).max(200)).min(1),
75
75
  evidence: z.string().min(1).max(4000),
76
76
  });
77
+ const reviewResultFindingSchema = z.object({
78
+ severity: z.enum(['blocking', 'note']),
79
+ message: z.string(),
80
+ path: z.string().nullable().optional(),
81
+ line: z.number().int().positive().nullable().optional(),
82
+ rule: z.string().nullable().optional(),
83
+ consequence: z.string().nullable().optional(),
84
+ evidence: z.string().nullable().optional(),
85
+ // Негодное воспроизведение отбрасывает только его, а не весь оплаченный вердикт.
86
+ reproduction: reproductionSchema.nullable().optional().catch(null),
87
+ });
88
+ /**
89
+ * Предел находок и переходов в одном ответе reviewer и в раунде истории. Без
90
+ * предела каждый лишний элемент ответа давал отдельные ошибки разбора и
91
+ * гигабайты кучи. Реальные ответы на порядки меньше.
92
+ */
93
+ export const REVIEW_ITEMS_LIMIT = 500;
77
94
  export const reviewResultSchema = z.object({
78
95
  execution: reviewExecutionSchema.optional(),
79
96
  approved: z.boolean(),
80
97
  summary: z.string(),
81
98
  discoveries: z.array(discoverySchema).max(20).default([]),
82
- findings: z.array(z.object({
83
- severity: z.enum(['blocking', 'note']),
84
- message: z.string(),
85
- path: z.string().nullable().optional(),
86
- line: z.number().int().positive().nullable().optional(),
87
- rule: z.string().nullable().optional(),
88
- consequence: z.string().nullable().optional(),
89
- evidence: z.string().nullable().optional(),
90
- // Негодное воспроизведение отбрасывает только его, а не весь оплаченный вердикт.
91
- reproduction: reproductionSchema.nullable().optional().catch(null),
92
- })),
93
- previous: z.array(findingTransitionSchema).default([]),
99
+ findings: z.array(reviewResultFindingSchema).max(REVIEW_ITEMS_LIMIT),
100
+ previous: z.array(findingTransitionSchema).max(REVIEW_ITEMS_LIMIT).default([]),
94
101
  /**
95
102
  * Подтверждение reviewer, что приёмка поручения уже выполнена на базе без
96
103
  * изменений (исполнитель сдал пустой результат): gates, чьё прошедшее
@@ -99,6 +106,14 @@ export const reviewResultSchema = z.object({
99
106
  */
100
107
  alreadySatisfied: alreadySatisfiedSchema.nullable().optional(),
101
108
  });
109
+ /**
110
+ * Записанный ответ reviewer (`review.json`). Предел `reviewResultSchema` —
111
+ * граница приёма: файлы прежних версий с длинными списками читаются и дальше.
112
+ */
113
+ export const storedReviewResultSchema = reviewResultSchema.extend({
114
+ findings: z.array(reviewResultFindingSchema),
115
+ previous: z.array(findingTransitionSchema).default([]),
116
+ });
102
117
  /** Идентичность находки: предмет, класс и текст. Новый текст — новая находка. */
103
118
  export const findingId = (subject, finding) => digestOf({ subject, rule: finding.rule ?? null, message: finding.message });
104
119
  export const reviewFindingSchema = z.strictObject({
@@ -220,7 +235,7 @@ export const reviewRoundSchema = z.strictObject({
220
235
  */
221
236
  protocol: z.enum(['valid', 'invalid', 'unsafe']),
222
237
  /** Открытые находки, состояние которых reviewer должен был назвать. */
223
- expected: z.array(digestSchema).max(500),
238
+ expected: z.array(digestSchema).max(REVIEW_ITEMS_LIMIT),
224
239
  issues: z.array(protocolIssueSchema).max(50).optional(),
225
240
  transitions: z
226
241
  .array(z.strictObject({
@@ -229,7 +244,7 @@ export const reviewRoundSchema = z.strictObject({
229
244
  to: z.enum(findingStatuses),
230
245
  basis: z.string().max(4000),
231
246
  }))
232
- .max(500)
247
+ .max(REVIEW_ITEMS_LIMIT)
233
248
  .optional(),
234
249
  /** Согласованная постановка поручения на момент раунда. */
235
250
  spec: digestSchema.optional(),
@@ -32,6 +32,12 @@ export declare const consumerSchema: z.ZodObject<{
32
32
  repositoryId: z.ZodString;
33
33
  gates: z.ZodArray<z.ZodString>;
34
34
  }, z.core.$strict>;
35
+ /**
36
+ * Область записи: изменения вне неё отклоняют попытку. `["."]` — весь
37
+ * репозиторий (защищённые и генерируемые пути и область роли по-прежнему
38
+ * ограничивают запись); `.` допустим только как единственный элемент.
39
+ */
40
+ export declare const writeScopeSchema: z.ZodArray<z.ZodUnion<readonly [z.ZodLiteral<".">, z.ZodString]>>;
35
41
  /**
36
42
  * Исполняемое поручение. Это снимок постановки, а не редактируемая задача:
37
43
  * изменение любого поля — новая редакция источника и новый digest, и прежнее
@@ -33,6 +33,18 @@ export const consumerSchema = z.strictObject({
33
33
  repositoryId: idSchema,
34
34
  gates: gateScopeSchema(gateRefSchema).min(1),
35
35
  });
36
+ /**
37
+ * Область записи: изменения вне неё отклоняют попытку. `["."]` — весь
38
+ * репозиторий (защищённые и генерируемые пути и область роли по-прежнему
39
+ * ограничивают запись); `.` допустим только как единственный элемент.
40
+ */
41
+ export const writeScopeSchema = z
42
+ .array(z.union([z.literal('.'), relativePathSchema]))
43
+ .min(1)
44
+ .max(100)
45
+ .refine((paths) => !paths.includes('.') || paths.length === 1, {
46
+ message: 'Весь репозиторий (".") — единственный элемент области записи',
47
+ });
36
48
  /**
37
49
  * Исполняемое поручение. Это снимок постановки, а не редактируемая задача:
38
50
  * изменение любого поля — новая редакция источника и новый digest, и прежнее
@@ -49,18 +61,7 @@ export const workOrderSchema = z.strictObject({
49
61
  repositoryId: idSchema,
50
62
  /** Связанные репозитории поручения уровня workspace; пусто — один репозиторий. */
51
63
  relatedRepositories: z.array(idSchema).max(10).default([]),
52
- /**
53
- * Область записи: изменения вне неё отклоняют попытку. `["."]` — весь
54
- * репозиторий (защищённые и генерируемые пути и область роли по-прежнему
55
- * ограничивают запись); `.` допустим только как единственный элемент.
56
- */
57
- writeScope: z
58
- .array(z.union([z.literal('.'), relativePathSchema]))
59
- .min(1)
60
- .max(100)
61
- .refine((paths) => !paths.includes('.') || paths.length === 1, {
62
- message: 'Весь репозиторий (".") — единственный элемент области записи',
63
- }),
64
+ writeScope: writeScopeSchema,
64
65
  dependsOn: z.array(idSchema).max(100).default([]),
65
66
  /** Область доказательства: подмножество gates/групп политики. Нет поля — все gates репозитория. */
66
67
  gates: gateScopeSchema(gateRefSchema).optional(),
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { mkdir, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
- import { HarnessError, WORKSPACE_OWNER, contextDigest, findingId, mcpEnvironment, reviewIssues, reviewResultSchema, selectReviewer, } from "../contracts/index.js";
4
+ import { HarnessError, WORKSPACE_OWNER, contextDigest, findingId, mcpEnvironment, reviewIssues, issuePath, reviewResultSchema, selectReviewer, } from "../contracts/index.js";
5
5
  import { reviewOutputSchema } from "../agents/schemas.js";
6
6
  import { redactInspection } from "../agents/inspect.js";
7
7
  import { executionEnvironment } from "../environment/lifecycle.js";
@@ -112,7 +112,14 @@ export async function technicalReview(engine, policy, adapters, input) {
112
112
  if (response.status !== 'ok')
113
113
  throw new HarnessError('RUNTIME_UNAVAILABLE', `Ревью ${kind}: ${response.status}${response.diagnostics.reason ? ': ' + response.diagnostics.reason : ''}`);
114
114
  const parsed = reviewResultSchema.safeParse(response.output);
115
- const issues = parsed.success ? reviewIssues(parsed.data, open) : ['Ответ ревью вне схемы'];
115
+ const issue = parsed.error?.issues[0];
116
+ const issues = parsed.success
117
+ ? reviewIssues(parsed.data, open)
118
+ : [
119
+ execution
120
+ .redact(`Ответ ревью вне схемы: ${issuePath(issue?.path ?? [])}: ${issue?.message}`)
121
+ .slice(0, 500),
122
+ ];
116
123
  // Ответ применяется только целиком валидным (docs/review-protocol.md, §8):
117
124
  // невалидный не закрывает прежних находок и не заводит новых — раунд
118
125
  // записывается неодобренным с причинами, история остаётся прежней.
@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';
3
3
  import { existsSync } from 'node:fs';
4
4
  import { mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
5
5
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
6
- import { roleBinding, selectReviewer, mcpEnvironment, HarnessError, digestOf, contextDigest, implementationResultSchema, codeReviewHistory, codeReviewScope, checkCodeReview, logicalReview, DEFAULT_REVIEW_PROTOCOL_RETRIES, reviewResultSchema, sha256, } from "../contracts/index.js";
6
+ import { roleBinding, selectReviewer, mcpEnvironment, HarnessError, digestOf, contextDigest, implementationResultSchema, codeReviewHistory, codeReviewScope, checkCodeReview, logicalReview, DEFAULT_REVIEW_PROTOCOL_RETRIES, REVIEW_ITEMS_LIMIT, storedReviewResultSchema, sha256, } from "../contracts/index.js";
7
7
  import { git, hostGitArgs } from "../environment/process.js";
8
8
  import { protectedChanges, protectedSnapshot, SandboxPolicyError, } from "../environment/isolation.js";
9
9
  import { executionEnvironment, runSteps, withEnvironment } from "../environment/lifecycle.js";
@@ -13,7 +13,7 @@ import { redactDeep } from "../environment/redaction.js";
13
13
  import { alreadySatisfiedReviewOutputSchema, implementationOutputSchema, reviewOutputSchema, } from "../agents/schemas.js";
14
14
  import { reviewInspection } from "../agents/inspect.js";
15
15
  import { reviewerRunsChecks } from "../agents/cli-adapter.js";
16
- import { gateProbePrompt, observeReproductions, probeCommand, probeGates, probeLimits, probeRecord, readProbeJournal, recoverProbeLog, probeTool, } from "../agents/review-probe.js";
16
+ import { gateProbePrompt, observeReproductions, assertProbeSpec, probeCommand, probeGates, probeLimits, probeRecord, readProbeJournal, recoverProbeLog, probeTool, } from "../agents/review-probe.js";
17
17
  import { runGate } from "../verification/gates.js";
18
18
  import { orderedScope } from "../verification/gate-scope.js";
19
19
  import { alreadySatisfiedVerdict, contractCheckGates, withinWriteScope, } from "../verification/already-satisfied.js";
@@ -1378,6 +1378,7 @@ export class Runner {
1378
1378
  scope: { attempt: attempt.id, phase, sha, call },
1379
1379
  artifacts: join(dir, 'probe-runs'),
1380
1380
  };
1381
+ assertProbeSpec(spec);
1381
1382
  const specPath = join(dir, 'probe.json');
1382
1383
  await writeFile(specPath, JSON.stringify(spec, null, 2));
1383
1384
  const seconds = (ms) => Math.round(ms / 1000);
@@ -1503,6 +1504,9 @@ export class Runner {
1503
1504
  const expected = legacy
1504
1505
  ? []
1505
1506
  : history.findings.filter((f) => f.status === 'open').map((f) => f.id);
1507
+ // Раунд с таким списком не записался бы: остановка до вызова reviewer.
1508
+ if (expected.length > REVIEW_ITEMS_LIMIT)
1509
+ throw new TaskFailure('review-protocol', `REVIEW_PROTOCOL_INVALID: открытых находок ${expected.length}, предел раунда ревью ${REVIEW_ITEMS_LIMIT} (попытка ${attempt.id}); нового вызова нет`);
1506
1510
  const round = history.round + 1;
1507
1511
  // Запрос одинаков для всех вызовов логического ревью: меняется только
1508
1512
  // диагностика ошибки протокола.
@@ -1972,7 +1976,7 @@ export class Runner {
1972
1976
  return;
1973
1977
  const items = [];
1974
1978
  for (const e of reviews) {
1975
- const saved = reviewResultSchema.safeParse(JSON.parse(await readFile(e.log, 'utf8').catch(() => 'null')));
1979
+ const saved = storedReviewResultSchema.safeParse(JSON.parse(await readFile(e.log, 'utf8').catch(() => 'null')));
1976
1980
  if (!saved.success)
1977
1981
  continue;
1978
1982
  for (const f of saved.data.findings)
@@ -0,0 +1,12 @@
1
+ /** Файл больше предела: дальше предела он не читался. */
2
+ export declare class OversizedFile extends Error {
3
+ readonly limit: number;
4
+ constructor(limit: number);
5
+ }
6
+ /**
7
+ * Текст файла, который пишет чужой процесс, не больше `limit` байт. Память
8
+ * ограничена и тогда, когда файл растёт после проверки размера: читается
9
+ * не больше `limit + 1` байта. Symlink не разыменовывается, FIFO без писателя
10
+ * не держит `open` (O_NONBLOCK) и отклоняется как не обычный файл.
11
+ */
12
+ export declare function readBounded(path: string, limit: number): Promise<string>;
@@ -0,0 +1,40 @@
1
+ import { constants, open } from 'node:fs/promises';
2
+ /** Файл больше предела: дальше предела он не читался. */
3
+ export class OversizedFile extends Error {
4
+ limit;
5
+ constructor(limit) {
6
+ super(`файл больше предела ${limit} байт`);
7
+ this.limit = limit;
8
+ this.name = 'OversizedFile';
9
+ }
10
+ }
11
+ /**
12
+ * Текст файла, который пишет чужой процесс, не больше `limit` байт. Память
13
+ * ограничена и тогда, когда файл растёт после проверки размера: читается
14
+ * не больше `limit + 1` байта. Symlink не разыменовывается, FIFO без писателя
15
+ * не держит `open` (O_NONBLOCK) и отклоняется как не обычный файл.
16
+ */
17
+ export async function readBounded(path, limit) {
18
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
19
+ try {
20
+ const stat = await handle.stat();
21
+ if (!stat.isFile())
22
+ throw new Error('не обычный файл');
23
+ if (stat.size > limit)
24
+ throw new OversizedFile(limit);
25
+ const buffer = Buffer.allocUnsafe(limit + 1);
26
+ let size = 0;
27
+ for (;;) {
28
+ const { bytesRead } = await handle.read(buffer, size, buffer.length - size);
29
+ if (!bytesRead)
30
+ break;
31
+ size += bytesRead;
32
+ if (size > limit)
33
+ throw new OversizedFile(limit);
34
+ }
35
+ return buffer.toString('utf8', 0, size);
36
+ }
37
+ finally {
38
+ await handle.close();
39
+ }
40
+ }
@@ -4,6 +4,7 @@ import type { RunnerHooks } from '../../engine/runner.ts';
4
4
  import { type LoadedConfig } from './config.ts';
5
5
  import { RelaySink, type ReconcileDecision } from './delivery.ts';
6
6
  import { HistoryRecorder } from './history.ts';
7
+ import { type BaselineManifest } from './snapshot.ts';
7
8
  import { RelayWorkSource } from './source.ts';
8
9
  import { ConnectorStore } from './store.ts';
9
10
  import type { RelayTransport } from './transport.ts';
@@ -87,6 +88,11 @@ export declare class Connector {
87
88
  };
88
89
  stateDir?: string | undefined;
89
90
  contextDir?: string | undefined;
91
+ baseline?: {
92
+ sha: string;
93
+ tasks: string[];
94
+ reason: string;
95
+ } | undefined;
90
96
  } | {
91
97
  provider: "relay-v2-cli";
92
98
  relay: Record<string, unknown> & {
@@ -141,6 +147,11 @@ export declare class Connector {
141
147
  };
142
148
  stateDir?: string | undefined;
143
149
  contextDir?: string | undefined;
150
+ baseline?: {
151
+ sha: string;
152
+ tasks: string[];
153
+ reason: string;
154
+ } | undefined;
144
155
  };
145
156
  /** Каталог пакетов `tasks[].context`: `contextDir` конфигурации, иначе `work/context` рядом с ней. */
146
157
  get contextDir(): string;
@@ -154,12 +165,19 @@ export declare class Connector {
154
165
  /** Хуки runner для `HarnessOptions.hooks`: история до исполнения попытки. */
155
166
  hooks(): RunnerHooks;
156
167
  close(): void;
168
+ /**
169
+ * `baseline` — решение человека, поэтому файл конфигурации не должен быть
170
+ * доступен писателю поручения: он вне репозиториев политики или в их
171
+ * `protectedPaths` (runner отказывает попытке, которая их меняет).
172
+ */
173
+ baselineIssue(policy: ExecutionPolicy, baseDir: string): string | undefined;
174
+ assertBaselineProtected(policy: ExecutionPolicy, baseDir: string): void;
157
175
  /**
158
176
  * Подключение, идентичность, capabilities, совпадение проекта и mapping —
159
177
  * только чтением: без мутаций backend, без записи истории и без создания
160
178
  * состояния коннектора.
161
179
  */
162
- check(policy?: ExecutionPolicy): Promise<{
180
+ check(policy?: ExecutionPolicy, baseDir?: string): Promise<{
163
181
  history: {
164
182
  enabled: boolean;
165
183
  capability: boolean;
@@ -192,11 +210,6 @@ export declare class Connector {
192
210
  * semantic digest: повтор неизменной постановки ничего не меняет.
193
211
  */
194
212
  snapshot(outDir?: string): Promise<{
195
- revision: string;
196
- created: boolean;
197
- eligible: boolean;
198
- problems: string[];
199
- truncated: string[];
200
213
  tasks: {
201
214
  identity: string;
202
215
  key: string;
@@ -211,7 +224,19 @@ export declare class Connector {
211
224
  manifest: string;
212
225
  };
213
226
  snapshot: import("./snapshot.ts").BuiltSnapshot;
214
- localContext?: import("./snapshot.ts").LocalContextManifest[] | undefined;
227
+ baseline?: BaselineManifest | undefined;
228
+ revision: string;
229
+ created: boolean;
230
+ eligible: boolean;
231
+ problems: string[];
232
+ truncated: string[];
233
+ localContext?: {
234
+ id: string;
235
+ digest: string;
236
+ files: number;
237
+ references: number;
238
+ bytes: number;
239
+ }[] | undefined;
215
240
  connector: string;
216
241
  graphId: string;
217
242
  graphDigest: string;
@@ -226,11 +251,13 @@ export declare class Connector {
226
251
  prepareRun(h: Harness): Promise<{
227
252
  graph: WorkGraph;
228
253
  context: ContextSnapshot;
254
+ baseline?: BaselineManifest;
229
255
  }>;
230
256
  run(h: Harness, options?: {
231
257
  author?: Author;
232
258
  once?: boolean;
233
259
  }): Promise<{
260
+ baseline?: BaselineManifest | undefined;
234
261
  works: {
235
262
  blockers: {
236
263
  code: "NOT_READY" | "PAUSED" | "ATTEMPTS_EXHAUSTED" | "APPROVAL_STALE" | "APPROVAL_REQUIRED" | "BUDGET_EXHAUSTED" | "REVIEWER_SAME_VENDOR" | "REVIEWER_MISSING" | "INVALID_INPUT";
@@ -312,6 +339,7 @@ export declare class Connector {
312
339
  ref: string;
313
340
  }[];
314
341
  snapshot?: {
342
+ baseline?: BaselineManifest | undefined;
315
343
  revision: string;
316
344
  graphId: string;
317
345
  } | undefined;
@@ -1,7 +1,8 @@
1
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
- import { join, resolve } from 'node:path';
1
+ import { existsSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs';
2
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
3
3
  import { API_VERSION, HarnessError, } from "../../contracts/index.js";
4
4
  import { redactor } from "../../environment/redaction.js";
5
+ import { withinPaths } from "../../validate.js";
5
6
  import { connectorIdOf, loadConfig, orderIdOf, resolveFrom, storeFileOf, } from "./config.js";
6
7
  import { RelaySink } from "./delivery.js";
7
8
  import { HistoryRecorder } from "./history.js";
@@ -99,6 +100,33 @@ export class Connector {
99
100
  this.storeInstance?.close();
100
101
  this.storeInstance = undefined;
101
102
  }
103
+ /**
104
+ * `baseline` — решение человека, поэтому файл конфигурации не должен быть
105
+ * доступен писателю поручения: он вне репозиториев политики или в их
106
+ * `protectedPaths` (runner отказывает попытке, которая их меняет).
107
+ */
108
+ baselineIssue(policy, baseDir) {
109
+ const file = this.loaded.file;
110
+ if (!this.config.baseline || !file)
111
+ return undefined;
112
+ const real = realpathSync(file);
113
+ for (const repo of policy.repositories) {
114
+ const root = resolveFrom(baseDir, repo.path);
115
+ if (!existsSync(root))
116
+ continue;
117
+ const path = relative(realpathSync(root), real);
118
+ if (path === '..' || path.startsWith('..' + sep) || isAbsolute(path))
119
+ continue;
120
+ if (!withinPaths(path, repo.protectedPaths))
121
+ return `Конфигурация коннектора с baseline лежит в репозитории ${repo.id} вне protectedPaths (${path}): писатель поручения мог бы выдать себе baseline; перенесите файл или защитите путь в политике`;
122
+ }
123
+ return undefined;
124
+ }
125
+ assertBaselineProtected(policy, baseDir) {
126
+ const issue = this.baselineIssue(policy, baseDir);
127
+ if (issue)
128
+ throw new HarnessError('NOT_READY', issue);
129
+ }
102
130
  /* ---------------------------------------------------------------- */
103
131
  /* source-check */
104
132
  /* ---------------------------------------------------------------- */
@@ -107,9 +135,12 @@ export class Connector {
107
135
  * только чтением: без мутаций backend, без записи истории и без создания
108
136
  * состояния коннектора.
109
137
  */
110
- async check(policy) {
138
+ async check(policy, baseDir) {
111
139
  const config = this.config;
112
140
  const problems = [];
141
+ const unprotected = policy && baseDir && this.baselineIssue(policy, baseDir);
142
+ if (unprotected)
143
+ problems.push(unprotected);
113
144
  let identity;
114
145
  try {
115
146
  identity = await checkIdentity(this.transport, config);
@@ -221,6 +252,7 @@ export class Connector {
221
252
  eligible: snapshot.problems.length === 0,
222
253
  problems: snapshot.problems.map((p) => `${p.key}: ${p.code}: ${p.message}`),
223
254
  truncated: snapshot.manifest.truncated,
255
+ ...(snapshot.manifest.baseline ? { baseline: snapshot.manifest.baseline } : {}),
224
256
  tasks: snapshot.manifest.tasks.map((t) => ({
225
257
  identity: t.identity,
226
258
  key: t.key,
@@ -243,6 +275,7 @@ export class Connector {
243
275
  * закреплённый граф и контекст (те же байты, что видел reviewer плана).
244
276
  */
245
277
  async prepareRun(h) {
278
+ this.assertBaselineProtected(h.policy, h.options.baseDir);
246
279
  const fresh = await this.source.snapshot();
247
280
  const stored = this.store.latestSnapshot(fresh.graph.id);
248
281
  if (!stored)
@@ -266,11 +299,16 @@ export class Connector {
266
299
  .some((o) => o.status === 'delivered' && o.revision === digest);
267
300
  };
268
301
  assertEligible({ ...fresh, problems: fresh.problems.filter((p) => !own(p)) });
269
- return { graph: stored.graph, context: stored.context };
302
+ const { baseline } = stored.manifest;
303
+ return {
304
+ graph: stored.graph,
305
+ context: stored.context,
306
+ ...(baseline ? { baseline } : {}),
307
+ };
270
308
  }
271
309
  async run(h, options = {}) {
272
- const { graph, context } = await this.prepareRun(h);
273
- return h.run({
310
+ const { graph, context, baseline } = await this.prepareRun(h);
311
+ const data = await h.run({
274
312
  graph,
275
313
  context,
276
314
  author: options.author ?? 'external',
@@ -278,6 +316,7 @@ export class Connector {
278
316
  sink: this.sink,
279
317
  ...(options.once ? { once: true } : {}),
280
318
  });
319
+ return { ...data, ...(baseline ? { baseline } : {}) };
281
320
  }
282
321
  /* ---------------------------------------------------------------- */
283
322
  /* source-status / deliver / reconcile */
@@ -376,7 +415,13 @@ export class Connector {
376
415
  provider: this.config.provider,
377
416
  projectId: this.config.projectId,
378
417
  ...(manifest
379
- ? { snapshot: { revision: manifest.revision, graphId: manifest.graphId } }
418
+ ? {
419
+ snapshot: {
420
+ revision: manifest.revision,
421
+ graphId: manifest.graphId,
422
+ ...(manifest.baseline ? { baseline: manifest.baseline } : {}),
423
+ },
424
+ }
380
425
  : {}),
381
426
  ownership: { stateDir: this.stateDir, store: this.storeFile, note: OWNERSHIP_NOTE },
382
427
  tasks,