devcontour-harness 0.1.0-alpha.25 → 0.1.0-alpha.27

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 (80) hide show
  1. package/README.md +16 -2
  2. package/docs/architecture.md +59 -0
  3. package/docs/compatibility.md +25 -11
  4. package/docs/connectors.md +72 -3
  5. package/docs/contracts.md +60 -24
  6. package/docs/release-notes/0.1.0-alpha.26.md +35 -0
  7. package/docs/release-notes/0.1.0-alpha.27.md +36 -0
  8. package/docs/review-protocol.md +16 -2
  9. package/docs/toolchains.md +83 -0
  10. package/docs/upgrade.md +10 -0
  11. package/lib/agents/cli-adapter.d.ts +6 -0
  12. package/lib/agents/cli-adapter.js +12 -2
  13. package/lib/agents/review-probe.d.ts +5 -0
  14. package/lib/agents/review-probe.js +29 -9
  15. package/lib/agents/schemas.d.ts +4 -0
  16. package/lib/agents/schemas.js +3 -1
  17. package/lib/cli.js +22 -5
  18. package/lib/contracts/cli.d.ts +184 -1
  19. package/lib/contracts/cli.js +102 -2
  20. package/lib/contracts/failure.js +1 -1
  21. package/lib/contracts/policy.d.ts +30 -0
  22. package/lib/contracts/policy.js +23 -0
  23. package/lib/contracts/published.d.ts +8 -0
  24. package/lib/contracts/review.d.ts +69 -0
  25. package/lib/contracts/review.js +29 -14
  26. package/lib/contracts/work.d.ts +6 -0
  27. package/lib/contracts/work.js +13 -12
  28. package/lib/control/harness.d.ts +12 -0
  29. package/lib/control/harness.js +4 -0
  30. package/lib/control/review.js +14 -2
  31. package/lib/engine/joint-runner.js +34 -1
  32. package/lib/engine/runner.d.ts +29 -0
  33. package/lib/engine/runner.js +207 -5
  34. package/lib/engine/worktree-cleanup.d.ts +131 -0
  35. package/lib/engine/worktree-cleanup.js +520 -0
  36. package/lib/environment/bounded-read.d.ts +12 -0
  37. package/lib/environment/bounded-read.js +40 -0
  38. package/lib/environment/isolation.d.ts +1 -0
  39. package/lib/environment/isolation.js +2 -1
  40. package/lib/environment/os-tools.d.ts +4 -2
  41. package/lib/environment/os-tools.js +4 -2
  42. package/lib/environment/process.d.ts +5 -0
  43. package/lib/environment/process.js +40 -17
  44. package/lib/environment/resources.d.ts +9 -0
  45. package/lib/environment/resources.js +24 -0
  46. package/lib/index.d.ts +1 -0
  47. package/lib/index.js +1 -0
  48. package/lib/integrations/connector/commands.d.ts +37 -8
  49. package/lib/integrations/connector/commands.js +61 -8
  50. package/lib/integrations/connector/config.d.ts +37 -0
  51. package/lib/integrations/connector/config.js +37 -5
  52. package/lib/integrations/connector/delivery.js +17 -1
  53. package/lib/integrations/connector/index.d.ts +2 -2
  54. package/lib/integrations/connector/index.js +1 -1
  55. package/lib/integrations/connector/snapshot.d.ts +10 -8
  56. package/lib/integrations/connector/snapshot.js +78 -8
  57. package/lib/integrations/connector/source.d.ts +8 -2
  58. package/lib/integrations/connector/source.js +32 -6
  59. package/lib/integrations/connector/store.d.ts +1 -1
  60. package/lib/integrations/connector/store.js +11 -6
  61. package/lib/integrations/connector/summary.d.ts +6 -0
  62. package/lib/integrations/connector/summary.js +5 -0
  63. package/lib/integrations/connector/testing.js +18 -0
  64. package/lib/integrations/relay-v1/index.js +6 -4
  65. package/lib/integrations/relay-v2/protocol.js +8 -6
  66. package/lib/profiles/resolve.d.ts +6 -0
  67. package/lib/toolchains/inspect.d.ts +1 -1
  68. package/lib/toolchains/inspect.js +29 -1
  69. package/lib/toolchains/probe.d.ts +16 -0
  70. package/lib/toolchains/probe.js +20 -0
  71. package/lib/verification/confirm.d.ts +3 -1
  72. package/lib/verification/confirm.js +26 -4
  73. package/lib/verification/dependencies.d.ts +3 -0
  74. package/lib/verification/dependencies.js +11 -0
  75. package/lib/verification/dependency-store.d.ts +117 -0
  76. package/lib/verification/dependency-store.js +811 -0
  77. package/lib/verification/gates-at.js +18 -0
  78. package/lib/verification/gates.js +24 -7
  79. package/package.json +2 -2
  80. package/schemas/execution-policy.schema.json +34 -0
@@ -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(),
@@ -254,6 +254,18 @@ export declare class Harness {
254
254
  status: "cleaned";
255
255
  receipts: string[];
256
256
  }>;
257
+ /** Убрать рабочие деревья закончившихся попыток; ветки и артефакты остаются. */
258
+ cleanupWorktrees(options?: {
259
+ dryRun?: boolean;
260
+ }): Promise<{
261
+ dryRun: boolean;
262
+ removed: number;
263
+ removable: number;
264
+ refused: number;
265
+ failed: number;
266
+ reclaimedKb: number;
267
+ worktrees: import("../engine/worktree-cleanup.ts").WorktreeCleanupEntry[];
268
+ }>;
257
269
  private repoPath;
258
270
  /**
259
271
  * Снимок контекста для ревью плана: без нужного графу источника — отказ
@@ -136,6 +136,10 @@ export class Harness {
136
136
  cleanup(runId) {
137
137
  return this.runner.finishCleanup(runId);
138
138
  }
139
+ /** Убрать рабочие деревья закончившихся попыток; ветки и артефакты остаются. */
140
+ cleanupWorktrees(options = {}) {
141
+ return this.runner.cleanupWorktrees(options);
142
+ }
139
143
  repoPath(path) {
140
144
  return isAbsolute(path) ? path : resolve(this.options.baseDir, path);
141
145
  }
@@ -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, REVIEW_ITEMS_LIMIT, 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";
@@ -51,6 +51,11 @@ export async function technicalReview(engine, policy, adapters, input) {
51
51
  if (!adapter)
52
52
  throw new HarnessError('RUNTIME_UNAVAILABLE', 'Runtime не подключён: ' + choice.reviewer.runtime);
53
53
  const open = lastFindings.filter((f) => f.status === 'open');
54
+ // Ответ обязан назвать каждую открытую находку по ID, а `previous` ограничен:
55
+ // такой раунд не одобрить, и вызов модели был бы оплачен впустую.
56
+ const named = new Set(open.map((f) => f.id)).size;
57
+ if (named > REVIEW_ITEMS_LIMIT)
58
+ throw new HarnessError('REVIEW_PROTOCOL_INVALID', `Ревью ${kind} ${subject}: открытых находок ${named}, предел раунда ревью ${REVIEW_ITEMS_LIMIT}; нового вызова нет`);
54
59
  const round = before + 1;
55
60
  const dir = input.artifactDir;
56
61
  await mkdir(dir, { recursive: true });
@@ -112,7 +117,14 @@ export async function technicalReview(engine, policy, adapters, input) {
112
117
  if (response.status !== 'ok')
113
118
  throw new HarnessError('RUNTIME_UNAVAILABLE', `Ревью ${kind}: ${response.status}${response.diagnostics.reason ? ': ' + response.diagnostics.reason : ''}`);
114
119
  const parsed = reviewResultSchema.safeParse(response.output);
115
- const issues = parsed.success ? reviewIssues(parsed.data, open) : ['Ответ ревью вне схемы'];
120
+ const issue = parsed.error?.issues[0];
121
+ const issues = parsed.success
122
+ ? reviewIssues(parsed.data, open)
123
+ : [
124
+ execution
125
+ .redact(`Ответ ревью вне схемы: ${issuePath(issue?.path ?? [])}: ${issue?.message}`)
126
+ .slice(0, 500),
127
+ ];
116
128
  // Ответ применяется только целиком валидным (docs/review-protocol.md, §8):
117
129
  // невалидный не закрывает прежних находок и не заводит новых — раунд
118
130
  // записывается неодобренным с причинами, история остаётся прежней.
@@ -8,6 +8,7 @@ import { credentialPaths } from "../environment/isolation.js";
8
8
  import { CleanupFailure, availableRedactor, executionEnvironment, withEnvironment, } from "../environment/lifecycle.js";
9
9
  import { composeRedactors } from "../environment/redaction.js";
10
10
  import { defaultResourceDatabase, withResources } from "../environment/resources.js";
11
+ import { dependencyStoreRoot, materializeStore } from "../verification/dependency-store.js";
11
12
  import { junitSummary, prepareReportPath, runCheck } from "../verification/gates.js";
12
13
  import { orderedWorkspaceGates, publicJoint } from "../verification/joint.js";
13
14
  /**
@@ -48,6 +49,7 @@ export class JointRunner {
48
49
  const controller = new AbortController();
49
50
  const signal = outer ? AbortSignal.any([outer, controller.signal]) : controller.signal;
50
51
  const timer = setTimeout(() => controller.abort(), this.policy.runTimeoutMs);
52
+ const deadline = Date.now() + this.policy.runTimeoutMs;
51
53
  const heartbeat = setInterval(() => {
52
54
  try {
53
55
  this.engine.jointHeartbeat(v.id, v.token);
@@ -136,7 +138,37 @@ export class JointRunner {
136
138
  };
137
139
  const first = paths[this.policy.repositories[0].id];
138
140
  await withEnvironment(this.policy.workspaceLifecycle, first, join(dir, 'environment'), executionEnvironment([this.policy.environment], common, source), signal, async () => {
139
- for (const gate of orderedWorkspaceGates(this.policy.workspaceGates).filter((g) => impact.gateIds.includes(g.id))) {
141
+ const gates = orderedWorkspaceGates(this.policy.workspaceGates).filter((g) => impact.gateIds.includes(g.id));
142
+ // У совместной проверки нет `prepare`: хранилище разворачивается
143
+ // здесь, в компоненты, чьи gates будут исполняться.
144
+ const stores = {};
145
+ for (const repo of this.policy.repositories) {
146
+ if (!repo.dependencyStore || !gates.some((g) => g.repositoryId === repo.id))
147
+ continue;
148
+ const receipt = await materializeStore({
149
+ policy: this.policy,
150
+ root: (id) => dependencyStoreRoot(placement, this.options.stateDir, id),
151
+ repoPath: (r) => this.repoPath(r),
152
+ boundary: {
153
+ hidden: [
154
+ this.options.stateDir,
155
+ ...this.policy.repositories.map((r) => this.repoPath(r)),
156
+ ],
157
+ ...(placement.root ? { checkouts: [placement.root] } : {}),
158
+ },
159
+ resourceDatabase: this.options.resourceDatabase ?? defaultResourceDatabase(),
160
+ deadline,
161
+ phaseMs: this.policy.runTimeoutMs,
162
+ }, {
163
+ repo,
164
+ cwd: paths[repo.id],
165
+ execution: executionEnvironment([this.policy.environment, repo.environment], common, source),
166
+ signal,
167
+ dir: join(dir, 'dependency-store', repo.id),
168
+ });
169
+ stores[repo.id] = receipt.env;
170
+ }
171
+ for (const gate of gates) {
140
172
  if (signal.aborted)
141
173
  throw new Error('Совместная проверка отменена');
142
174
  const cwd = paths[gate.repositoryId];
@@ -183,6 +215,7 @@ export class JointRunner {
183
215
  settingsDir: join(dir, gate.id),
184
216
  env: {
185
217
  ...environment.env,
218
+ ...stores[gate.repositoryId],
186
219
  ...(reportPath
187
220
  ? { DEVCONTOUR_REPORT_PATH: reportPath, HARNESS_REPORT_PATH: reportPath }
188
221
  : {}),
@@ -1,4 +1,5 @@
1
1
  import { type ImplementationResult, type AttemptState, type ContextSnapshot, type ExecutionPolicy, type RuntimeAdapter, type RuntimeName, type WorkState } from '../contracts/index.ts';
2
+ import { type WorktreeCleanupEntry } from './worktree-cleanup.ts';
2
3
  import { type CheckoutRoot } from '../environment/checkout-root.ts';
3
4
  import { type FailureKind } from './failure.ts';
4
5
  import { type Engine } from './engine.ts';
@@ -101,11 +102,15 @@ export declare class Runner {
101
102
  /** Каталог попыток репозитория. */
102
103
  private dirOf;
103
104
  private placement?;
105
+ /** Когда истекает текущий предел времени попытки: от остатка считается бюджет хранилища. */
106
+ private phaseDeadlines;
104
107
  /**
105
108
  * Действующий корень рабочих деревьев (`checkout-root.ts`): хост
106
109
  * показывает его в диагностике. Выбирается один раз на исполнитель.
107
110
  */
108
111
  checkoutRoot(): CheckoutRoot;
112
+ /** Хранилище зависимостей: те же корень и граница, что у деревьев попытки. */
113
+ private storeContext;
109
114
  /** Каталог рабочего дерева вида `kind`: вне дерева или прежний в каталоге попыток. */
110
115
  private checkout;
111
116
  repoPath(repo: Repo): string;
@@ -176,6 +181,8 @@ export declare class Runner {
176
181
  private adapter;
177
182
  /** Область записи кандидата: защищённые пути, пустой результат, выход за область поручения и роли. */
178
183
  private assertScope;
184
+ /** Хранилище зависимостей checkout до `prepare`; без него этапа нет и в замерах. */
185
+ private dependencyStore;
179
186
  /** Стадия попытки с замером: начало, конец и исход записываются под fencing. */
180
187
  private timed;
181
188
  /**
@@ -214,6 +221,28 @@ export declare class Runner {
214
221
  status: "cleaned";
215
222
  receipts: string[];
216
223
  }>;
224
+ /** Предел обхода дерева при очистке: дошедший до него обход отказывает. */
225
+ static cleanupScanLimit: number;
226
+ /** Предел удаления одного дерева: большие деревья удаляются минутами. */
227
+ static cleanupRemovalMs: number;
228
+ /**
229
+ * Убрать рабочие деревья закончившихся попыток. Ветки и достижимые коммиты
230
+ * остаются; неподтверждённые правки сохраняются патчем в артефактах попытки
231
+ * до удаления. В сомнении дерево остаётся: отказ назван поимённо и не срывает
232
+ * остальные деревья. Один запуск на каталог состояния; `dryRun` ничего не пишет.
233
+ */
234
+ cleanupWorktrees({ dryRun }?: {
235
+ dryRun?: boolean;
236
+ }): Promise<{
237
+ dryRun: boolean;
238
+ removed: number;
239
+ removable: number;
240
+ refused: number;
241
+ failed: number;
242
+ reclaimedKb: number;
243
+ worktrees: WorktreeCleanupEntry[];
244
+ }>;
245
+ private sweepWorktrees;
217
246
  private gate;
218
247
  /**
219
248
  * Gate интеграции с одним повтором на кандидата. Провал собственного gate на
@@ -2,18 +2,21 @@ import { execFileSync } from 'node:child_process';
2
2
  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
- 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";
5
+ import { basename, 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, REVIEW_ITEMS_LIMIT, storedReviewResultSchema, sha256, } from "../contracts/index.js";
7
7
  import { git, hostGitArgs } from "../environment/process.js";
8
+ import { worktreeKey } from "../environment/git-trust.js";
9
+ import { attemptRefusal, cleanupUnfinished, inspectTree, isWithin, lockCleanup, readRemoval, recordFile, recordRemoval, registered, removeTree, savePatch, sizeKb, treeHead, treeState, treeUnchanged, trusted, } from "./worktree-cleanup.js";
8
10
  import { protectedChanges, protectedSnapshot, SandboxPolicyError, } from "../environment/isolation.js";
9
11
  import { executionEnvironment, runSteps, withEnvironment } from "../environment/lifecycle.js";
12
+ import { dependencyStoreRoot, materializeStore, } from "../verification/dependency-store.js";
10
13
  import { checkoutPath, chooseCheckoutRoot, realish, } from "../environment/checkout-root.js";
11
14
  import { credentialPaths } from "../environment/isolation.js";
12
15
  import { redactDeep } from "../environment/redaction.js";
13
16
  import { alreadySatisfiedReviewOutputSchema, implementationOutputSchema, reviewOutputSchema, } from "../agents/schemas.js";
14
17
  import { reviewInspection } from "../agents/inspect.js";
15
18
  import { reviewerRunsChecks } from "../agents/cli-adapter.js";
16
- import { gateProbePrompt, observeReproductions, probeCommand, probeGates, probeLimits, probeRecord, readProbeJournal, recoverProbeLog, probeTool, } from "../agents/review-probe.js";
19
+ import { gateProbePrompt, observeReproductions, assertProbeSpec, probeCommand, probeGates, probeLimits, probeRecord, readProbeJournal, recoverProbeLog, probeTool, } from "../agents/review-probe.js";
17
20
  import { runGate } from "../verification/gates.js";
18
21
  import { orderedScope } from "../verification/gate-scope.js";
19
22
  import { alreadySatisfiedVerdict, contractCheckGates, withinWriteScope, } from "../verification/already-satisfied.js";
@@ -78,6 +81,8 @@ export class Runner {
78
81
  return this.options.stateDirFor?.(repositoryId) ?? this.options.stateDir;
79
82
  }
80
83
  placement;
84
+ /** Когда истекает текущий предел времени попытки: от остатка считается бюджет хранилища. */
85
+ phaseDeadlines = new Map();
81
86
  /**
82
87
  * Действующий корень рабочих деревьев (`checkout-root.ts`): хост
83
88
  * показывает его в диагностике. Выбирается один раз на исполнитель.
@@ -90,6 +95,18 @@ export class Runner {
90
95
  ...(this.options.checkoutRoot ? { configured: this.options.checkoutRoot } : {}),
91
96
  }));
92
97
  }
98
+ /** Хранилище зависимостей: те же корень и граница, что у деревьев попытки. */
99
+ storeContext(attempt) {
100
+ return {
101
+ policy: this.policy,
102
+ root: (id) => dependencyStoreRoot(this.checkoutRoot(), this.options.stateDir, id),
103
+ repoPath: (repo) => this.repoPath(repo),
104
+ boundary: this.boundary(),
105
+ resourceDatabase: this.options.resourceDatabase ?? defaultResourceDatabase(),
106
+ deadline: this.phaseDeadlines.get(attempt.id) ?? Date.now() + this.policy.runTimeoutMs,
107
+ phaseMs: this.policy.runTimeoutMs,
108
+ };
109
+ }
93
110
  /** Каталог рабочего дерева вида `kind`: вне дерева или прежний в каталоге попыток. */
94
111
  checkout(repositoryId, kind, ...rest) {
95
112
  return checkoutPath(this.checkoutRoot(), join(this.dirOf(repositoryId), kind, ...rest), repositoryId, kind, ...rest);
@@ -249,7 +266,10 @@ export class Runner {
249
266
  if (!attempt)
250
267
  break;
251
268
  const controller = new AbortController();
252
- const promise = this.execute(attempt, controller).finally(() => this.jobs.delete(attempt.id));
269
+ const promise = this.execute(attempt, controller).finally(() => {
270
+ this.jobs.delete(attempt.id);
271
+ this.phaseDeadlines.delete(attempt.id);
272
+ });
253
273
  this.jobs.set(attempt.id, { promise, controller });
254
274
  }
255
275
  }
@@ -543,6 +563,12 @@ export class Runner {
543
563
  throw new TaskFailure('scope-violation', 'Изменены файлы вне области поручения/роли: ' + outside.join(', '));
544
564
  return false;
545
565
  }
566
+ /** Хранилище зависимостей checkout до `prepare`; без него этапа нет и в замерах. */
567
+ async dependencyStore(attempt, repo, cwd, execution, signal, dir) {
568
+ if (!repo.dependencyStore)
569
+ return;
570
+ await this.timed(attempt, 'dependency-store', () => materializeStore(this.storeContext(attempt), { repo, cwd, execution, signal, dir }));
571
+ }
546
572
  /** Стадия попытки с замером: начало, конец и исход записываются под fencing. */
547
573
  async timed(attempt, stage, fn) {
548
574
  const id = this.engine.timingStarted(attempt.id, attempt.token, stage);
@@ -672,6 +698,7 @@ export class Runner {
672
698
  let timeout;
673
699
  const rearm = () => {
674
700
  clearTimeout(timeout);
701
+ this.phaseDeadlines.set(attempt.id, Date.now() + this.policy.runTimeoutMs);
675
702
  timeout = setTimeout(() => controller.abort(new DOMException('Исчерпан лимит времени прогона', 'TimeoutError')), this.policy.runTimeoutMs);
676
703
  };
677
704
  rearm();
@@ -756,6 +783,7 @@ export class Runner {
756
783
  ? [{ repositoryId: w.order.repositoryId, resultSha: w.resultSha }]
757
784
  : [];
758
785
  })),
786
+ store: this.storeContext(attempt),
759
787
  });
760
788
  snapshots.push(...dependencies);
761
789
  this.engine.dependencies(attempt.id, attempt.token, dependencies);
@@ -775,6 +803,7 @@ export class Runner {
775
803
  const gates = ordered(repo.gates, attempt.requiredGates ?? repo.gates.map((g) => g.id));
776
804
  const execution = this.environment(attempt, 'candidate', cwd);
777
805
  const candidate = await withEnvironment(repo.lifecycle ?? this.policy.lifecycle, cwd, join(artifacts, 'candidate', 'environment'), execution, signal, async () => {
806
+ await this.dependencyStore(attempt, repo, cwd, execution, signal, join(artifacts, 'candidate'));
778
807
  await runSteps(repo.prepare, cwd, join(artifacts, 'candidate', 'prepare'), execution, signal);
779
808
  const sha = attempt.reusedFrom
780
809
  ? await this.timed(attempt, 'implementation-reuse', () => this.reuseCandidate(attempt, work, repo, cwd, base, context))
@@ -1110,6 +1139,169 @@ export class Runner {
1110
1139
  JSON.parse(await readFile(file, 'utf8')).errors.join('; '));
1111
1140
  return { status: 'cleaned', receipts: cleaned };
1112
1141
  }
1142
+ /** Предел обхода дерева при очистке: дошедший до него обход отказывает. */
1143
+ static cleanupScanLimit = 2_000_000;
1144
+ /** Предел удаления одного дерева: большие деревья удаляются минутами. */
1145
+ static cleanupRemovalMs = 1_800_000;
1146
+ /**
1147
+ * Убрать рабочие деревья закончившихся попыток. Ветки и достижимые коммиты
1148
+ * остаются; неподтверждённые правки сохраняются патчем в артефактах попытки
1149
+ * до удаления. В сомнении дерево остаётся: отказ назван поимённо и не срывает
1150
+ * остальные деревья. Один запуск на каталог состояния; `dryRun` ничего не пишет.
1151
+ */
1152
+ async cleanupWorktrees({ dryRun = false } = {}) {
1153
+ const unlock = dryRun
1154
+ ? undefined
1155
+ : await lockCleanup(join(this.options.stateDir, 'worktree-cleanup.lock'));
1156
+ try {
1157
+ return await this.sweepWorktrees(dryRun);
1158
+ }
1159
+ finally {
1160
+ await unlock?.();
1161
+ }
1162
+ }
1163
+ async sweepWorktrees(dryRun) {
1164
+ const worktrees = [];
1165
+ const attempts = this.engine.read((v) => v.attempts().map((attempt) => {
1166
+ const work = v.work(attempt.workId);
1167
+ const latest = v.attempts(attempt.workId).every((a) => a.attempt <= attempt.attempt);
1168
+ return {
1169
+ attempt,
1170
+ refusal: attemptRefusal(attempt, work, latest, this.jobs.has(attempt.id)),
1171
+ };
1172
+ }));
1173
+ for (const repo of this.policy.repositories) {
1174
+ const repoPath = this.repoPath(repo);
1175
+ const live = await registered(repoPath);
1176
+ const owners = new Map();
1177
+ for (const item of attempts.filter((i) => i.attempt.repositoryId === repo.id)) {
1178
+ const dir = this.checkout(repo.id, 'worktrees', item.attempt.id);
1179
+ for (const path of [
1180
+ dir,
1181
+ dir + '-integration',
1182
+ ...(item.attempt.worktree
1183
+ ? [item.attempt.worktree, item.attempt.worktree + '-integration']
1184
+ : []),
1185
+ ])
1186
+ owners.set(worktreeKey(path), item);
1187
+ }
1188
+ const roots = [
1189
+ this.checkout(repo.id, 'worktrees'),
1190
+ join(this.dirOf(repo.id), 'worktrees'),
1191
+ ].map(worktreeKey);
1192
+ // Дерево без регистрации (удаление оборвалось после неё) git больше не
1193
+ // покажет: о нём знает только попытка.
1194
+ const paths = new Set([...live.keys(), ...owners.keys()]);
1195
+ for (const path of paths) {
1196
+ if (!existsSync(path) || !roots.some((root) => isWithin(path, root)))
1197
+ continue;
1198
+ const owner = owners.get(path);
1199
+ const entry = {
1200
+ path,
1201
+ repositoryId: repo.id,
1202
+ action: 'refused',
1203
+ ...(owner ? { attemptId: owner.attempt.id } : {}),
1204
+ };
1205
+ worktrees.push(entry);
1206
+ if (!owner) {
1207
+ entry.reason = 'unknown-attempt';
1208
+ continue;
1209
+ }
1210
+ const artifacts = join(this.dirOf(repo.id), 'artifacts', owner.attempt.id);
1211
+ let prior;
1212
+ try {
1213
+ entry.sizeKb = await sizeKb(path);
1214
+ prior = await readRemoval(artifacts, path);
1215
+ let refusal = owner.refusal;
1216
+ if (!refusal)
1217
+ try {
1218
+ if (await cleanupUnfinished(artifacts, await receipts(artifacts)))
1219
+ refusal = 'cleanup-pending';
1220
+ }
1221
+ catch {
1222
+ refusal = 'cleanup-unreadable';
1223
+ }
1224
+ if (prior && prior.status !== 'removed') {
1225
+ refusal ??= 'removal-incomplete';
1226
+ entry.record = recordFile(artifacts, path);
1227
+ if (prior.patch)
1228
+ entry.patch = prior.patch;
1229
+ if (prior.head)
1230
+ entry.head = prior.head;
1231
+ }
1232
+ if (!live.has(path))
1233
+ refusal ??= 'not-registered';
1234
+ if (live.get(path)?.locked)
1235
+ refusal ??= 'worktree-locked';
1236
+ if (!refusal && !trusted(path, repoPath))
1237
+ refusal = 'untrusted';
1238
+ let head;
1239
+ let decided;
1240
+ if (!refusal) {
1241
+ head = await treeHead(path);
1242
+ if (head)
1243
+ entry.head = head;
1244
+ const seen = await inspectTree(path, repoPath, head, Runner.cleanupScanLimit);
1245
+ refusal = seen.refusal;
1246
+ decided = seen.status;
1247
+ if (seen.uncommitted !== undefined)
1248
+ entry.uncommitted = seen.uncommitted;
1249
+ if (seen.ignored)
1250
+ entry.ignored = seen.ignored;
1251
+ }
1252
+ if (refusal) {
1253
+ entry.reason = refusal;
1254
+ continue;
1255
+ }
1256
+ if (dryRun) {
1257
+ entry.action = 'remove';
1258
+ continue;
1259
+ }
1260
+ let edits;
1261
+ if (entry.uncommitted) {
1262
+ const saved = await savePatch(path, artifacts, `uncommitted-${basename(path)}`, head);
1263
+ if (saved.refusal) {
1264
+ entry.reason = saved.refusal;
1265
+ continue;
1266
+ }
1267
+ entry.patch = saved.patch;
1268
+ edits = saved.edits;
1269
+ }
1270
+ if (!(await treeUnchanged(path, head, decided, edits))) {
1271
+ entry.reason = 'tree-changed';
1272
+ continue;
1273
+ }
1274
+ await recordRemoval(artifacts, entry, 'removing', prior);
1275
+ entry.removalStarted = true;
1276
+ await removeTree(repoPath, path, Runner.cleanupRemovalMs);
1277
+ entry.action = 'removed';
1278
+ await recordRemoval(artifacts, entry, 'removed', prior);
1279
+ }
1280
+ catch (error) {
1281
+ entry.action = 'failed';
1282
+ entry.error = error instanceof Error ? error.message : String(error);
1283
+ if (entry.removalStarted) {
1284
+ Object.assign(entry, await treeState(repoPath, path));
1285
+ await recordRemoval(artifacts, entry, 'incomplete', prior).catch((e) => {
1286
+ entry.error += `; запись не обновлена: ${e instanceof Error ? e.message : String(e)}`;
1287
+ });
1288
+ }
1289
+ }
1290
+ }
1291
+ }
1292
+ const count = (action) => worktrees.filter((w) => w.action === action).length;
1293
+ return {
1294
+ dryRun,
1295
+ removed: count('removed'),
1296
+ removable: count('remove'),
1297
+ refused: count('refused'),
1298
+ failed: count('failed'),
1299
+ reclaimedKb: worktrees
1300
+ .filter((w) => w.action === 'remove' || w.action === 'removed')
1301
+ .reduce((sum, w) => sum + (w.sizeKb ?? 0), 0),
1302
+ worktrees,
1303
+ };
1304
+ }
1113
1305
  async gate(attempt, cwd, sha, phase, gate, artifacts, signal, execution, consumer,
1114
1306
  /** ID записи провала, которую повторяет этот запуск (`recheckIntegration`). */
1115
1307
  recheck) {
@@ -1260,9 +1452,11 @@ export class Runner {
1260
1452
  environment: this.options.environment ?? process.env,
1261
1453
  signal,
1262
1454
  overrides: new Map([[provider, { path: cwd, sha }]]),
1455
+ store: this.storeContext(attempt),
1263
1456
  });
1264
1457
  const execution = this.environmentOf(attempt, 'integration', dir, [this.policy.environment, repo.environment], repo.id, dependencies);
1265
1458
  await withEnvironment(repo.lifecycle ?? this.policy.lifecycle, dir, join(own, 'environment'), execution, signal, async () => {
1459
+ await this.dependencyStore(attempt, repo, dir, execution, signal, own);
1266
1460
  await runSteps(repo.prepare, dir, join(own, 'prepare'), execution, signal);
1267
1461
  await pinned('подготовка');
1268
1462
  for (const gate of ordered(repo.gates, consumer.gates))
@@ -1378,6 +1572,7 @@ export class Runner {
1378
1572
  scope: { attempt: attempt.id, phase, sha, call },
1379
1573
  artifacts: join(dir, 'probe-runs'),
1380
1574
  };
1575
+ assertProbeSpec(spec);
1381
1576
  const specPath = join(dir, 'probe.json');
1382
1577
  await writeFile(specPath, JSON.stringify(spec, null, 2));
1383
1578
  const seconds = (ms) => Math.round(ms / 1000);
@@ -1503,6 +1698,9 @@ export class Runner {
1503
1698
  const expected = legacy
1504
1699
  ? []
1505
1700
  : history.findings.filter((f) => f.status === 'open').map((f) => f.id);
1701
+ // Раунд с таким списком не записался бы: остановка до вызова reviewer.
1702
+ if (expected.length > REVIEW_ITEMS_LIMIT)
1703
+ throw new TaskFailure('review-protocol', `REVIEW_PROTOCOL_INVALID: открытых находок ${expected.length}, предел раунда ревью ${REVIEW_ITEMS_LIMIT} (попытка ${attempt.id}); нового вызова нет`);
1506
1704
  const round = history.round + 1;
1507
1705
  // Запрос одинаков для всех вызовов логического ревью: меняется только
1508
1706
  // диагностика ошибки протокола.
@@ -1951,6 +2149,9 @@ export class Runner {
1951
2149
  }
1952
2150
  : {}),
1953
2151
  ...(this.options.environment ? { environment: this.options.environment } : {}),
2152
+ ...(this.options.resourceDatabase
2153
+ ? { resourceDatabase: this.options.resourceDatabase }
2154
+ : {}),
1954
2155
  }, raw);
1955
2156
  }
1956
2157
  /**
@@ -1972,7 +2173,7 @@ export class Runner {
1972
2173
  return;
1973
2174
  const items = [];
1974
2175
  for (const e of reviews) {
1975
- const saved = reviewResultSchema.safeParse(JSON.parse(await readFile(e.log, 'utf8').catch(() => 'null')));
2176
+ const saved = storedReviewResultSchema.safeParse(JSON.parse(await readFile(e.log, 'utf8').catch(() => 'null')));
1976
2177
  if (!saved.success)
1977
2178
  continue;
1978
2179
  for (const f of saved.data.findings)
@@ -2021,6 +2222,7 @@ export class Runner {
2021
2222
  const gates = ordered(repo.gates, attempt.requiredGates ?? repo.gates.map((g) => g.id));
2022
2223
  const execution = this.environment(attempt, 'integration', cwd);
2023
2224
  await withEnvironment(repo.lifecycle ?? this.policy.lifecycle, cwd, join(artifacts, 'integration', 'environment'), execution, signal, async () => {
2225
+ await this.dependencyStore(attempt, repo, cwd, execution, signal, join(artifacts, 'integration'));
2024
2226
  await runSteps(repo.prepare, cwd, join(artifacts, 'integration', 'prepare'), execution, signal);
2025
2227
  const budget = { recheck: true };
2026
2228
  for (const gate of gates)