devcontour-harness 0.1.0-alpha.26 → 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 (51) hide show
  1. package/README.md +9 -2
  2. package/docs/architecture.md +59 -0
  3. package/docs/compatibility.md +24 -12
  4. package/docs/connectors.md +5 -2
  5. package/docs/contracts.md +47 -25
  6. package/docs/release-notes/0.1.0-alpha.27.md +36 -0
  7. package/docs/review-protocol.md +10 -4
  8. package/docs/toolchains.md +83 -0
  9. package/docs/upgrade.md +10 -0
  10. package/lib/cli.js +13 -0
  11. package/lib/contracts/cli.d.ts +124 -0
  12. package/lib/contracts/cli.js +66 -0
  13. package/lib/contracts/policy.d.ts +30 -0
  14. package/lib/contracts/policy.js +23 -0
  15. package/lib/contracts/published.d.ts +8 -0
  16. package/lib/control/harness.d.ts +12 -0
  17. package/lib/control/harness.js +4 -0
  18. package/lib/control/review.js +6 -1
  19. package/lib/engine/joint-runner.js +34 -1
  20. package/lib/engine/runner.d.ts +29 -0
  21. package/lib/engine/runner.js +200 -2
  22. package/lib/engine/worktree-cleanup.d.ts +131 -0
  23. package/lib/engine/worktree-cleanup.js +520 -0
  24. package/lib/environment/isolation.d.ts +1 -0
  25. package/lib/environment/isolation.js +2 -1
  26. package/lib/environment/os-tools.d.ts +4 -2
  27. package/lib/environment/os-tools.js +4 -2
  28. package/lib/environment/process.d.ts +5 -0
  29. package/lib/environment/process.js +40 -17
  30. package/lib/environment/resources.d.ts +9 -0
  31. package/lib/environment/resources.js +24 -0
  32. package/lib/index.d.ts +1 -0
  33. package/lib/index.js +1 -0
  34. package/lib/integrations/connector/commands.d.ts +2 -1
  35. package/lib/integrations/connector/commands.js +10 -2
  36. package/lib/integrations/connector/store.d.ts +1 -1
  37. package/lib/integrations/connector/store.js +11 -6
  38. package/lib/profiles/resolve.d.ts +6 -0
  39. package/lib/toolchains/inspect.d.ts +1 -1
  40. package/lib/toolchains/inspect.js +29 -1
  41. package/lib/toolchains/probe.d.ts +16 -0
  42. package/lib/toolchains/probe.js +20 -0
  43. package/lib/verification/confirm.d.ts +3 -1
  44. package/lib/verification/confirm.js +16 -2
  45. package/lib/verification/dependencies.d.ts +3 -0
  46. package/lib/verification/dependencies.js +11 -0
  47. package/lib/verification/dependency-store.d.ts +117 -0
  48. package/lib/verification/dependency-store.js +811 -0
  49. package/lib/verification/gates-at.js +18 -0
  50. package/package.json +1 -1
  51. package/schemas/execution-policy.schema.json +34 -0
@@ -210,6 +210,18 @@ export declare const cliCommands: {
210
210
  }];
211
211
  readonly refusals: ["NOT_FOUND", "REVISION_CONFLICT"];
212
212
  };
213
+ readonly 'worktree-cleanup': {
214
+ readonly description: "Убрать рабочие деревья закончившихся попыток: ветки и достижимые коммиты остаются, неподтверждённые правки сохраняются проверенным патчем в артефактах попытки, игнорируемые файлы не сохраняются и перечисляются в ответе; индекс, который патч не сохранит, — отказ; в сомнении дерево остаётся, а отказ назван; модель не вызывается";
215
+ readonly writes: true;
216
+ readonly idempotency: "Повтор не находит уже убранных деревьев и ничего не меняет";
217
+ readonly args: [CliArgument, {
218
+ readonly name: "--dry-run";
219
+ readonly value: "flag";
220
+ readonly required: false;
221
+ readonly description: "Только показать, что было бы убрано, что исчезнет (игнорируемое) и почему отказано; ничего не пишет";
222
+ }];
223
+ readonly refusals: ["NOT_FOUND", "NOT_READY"];
224
+ };
213
225
  readonly cleanup: {
214
226
  readonly description: "Довести незавершённую очистку закончившейся попытки: повторить teardown по сохранённым receipt окружений и убрать её рабочие деревья; модели, gates и Git-приёмка не вызываются";
215
227
  readonly writes: true;
@@ -1784,6 +1796,62 @@ export declare const cleanupDataSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
1784
1796
  status: z.ZodLiteral<"cleaned">;
1785
1797
  receipts: z.ZodArray<z.ZodString>;
1786
1798
  }, z.core.$strict>], "status">;
1799
+ export declare const worktreeCleanupDataSchema: z.ZodObject<{
1800
+ dryRun: z.ZodBoolean;
1801
+ removed: z.ZodNumber;
1802
+ removable: z.ZodNumber;
1803
+ refused: z.ZodNumber;
1804
+ failed: z.ZodNumber;
1805
+ reclaimedKb: z.ZodNumber;
1806
+ worktrees: z.ZodArray<z.ZodObject<{
1807
+ path: z.ZodString;
1808
+ repositoryId: z.ZodString;
1809
+ attemptId: z.ZodOptional<z.ZodString>;
1810
+ action: z.ZodEnum<{
1811
+ refused: "refused";
1812
+ failed: "failed";
1813
+ removed: "removed";
1814
+ remove: "remove";
1815
+ }>;
1816
+ reason: z.ZodOptional<z.ZodEnum<{
1817
+ active: "active";
1818
+ recoverable: "recoverable";
1819
+ "cleanup-pending": "cleanup-pending";
1820
+ "cleanup-unreadable": "cleanup-unreadable";
1821
+ "unknown-attempt": "unknown-attempt";
1822
+ untrusted: "untrusted";
1823
+ "embedded-repository": "embedded-repository";
1824
+ "scan-limit": "scan-limit";
1825
+ "scan-failed": "scan-failed";
1826
+ "read-only-path": "read-only-path";
1827
+ "undecodable-path": "undecodable-path";
1828
+ "worktree-locked": "worktree-locked";
1829
+ "clean-filter": "clean-filter";
1830
+ "tree-changed": "tree-changed";
1831
+ "ignore-rules-changed": "ignore-rules-changed";
1832
+ "hidden-changes": "hidden-changes";
1833
+ "staged-ignored": "staged-ignored";
1834
+ "staged-differs": "staged-differs";
1835
+ "unreachable-head": "unreachable-head";
1836
+ "patch-unusable": "patch-unusable";
1837
+ "removal-incomplete": "removal-incomplete";
1838
+ "not-registered": "not-registered";
1839
+ }>>;
1840
+ error: z.ZodOptional<z.ZodString>;
1841
+ head: z.ZodOptional<z.ZodString>;
1842
+ sizeKb: z.ZodOptional<z.ZodNumber>;
1843
+ uncommitted: z.ZodOptional<z.ZodNumber>;
1844
+ ignored: z.ZodOptional<z.ZodObject<{
1845
+ count: z.ZodNumber;
1846
+ paths: z.ZodArray<z.ZodString>;
1847
+ }, z.core.$strict>>;
1848
+ record: z.ZodOptional<z.ZodString>;
1849
+ removalStarted: z.ZodOptional<z.ZodBoolean>;
1850
+ registered: z.ZodOptional<z.ZodBoolean>;
1851
+ treePresent: z.ZodOptional<z.ZodBoolean>;
1852
+ patch: z.ZodOptional<z.ZodString>;
1853
+ }, z.core.$strict>>;
1854
+ }, z.core.$strict>;
1787
1855
  /** `init`: план или результат подготовки проекта. */
1788
1856
  export declare const initDataSchema: z.ZodObject<{
1789
1857
  mode: z.ZodEnum<{
@@ -3888,6 +3956,62 @@ export declare const cliDataSchemas: {
3888
3956
  status: z.ZodLiteral<"cleaned">;
3889
3957
  receipts: z.ZodArray<z.ZodString>;
3890
3958
  }, z.core.$strict>], "status">;
3959
+ readonly 'worktree-cleanup': z.ZodObject<{
3960
+ dryRun: z.ZodBoolean;
3961
+ removed: z.ZodNumber;
3962
+ removable: z.ZodNumber;
3963
+ refused: z.ZodNumber;
3964
+ failed: z.ZodNumber;
3965
+ reclaimedKb: z.ZodNumber;
3966
+ worktrees: z.ZodArray<z.ZodObject<{
3967
+ path: z.ZodString;
3968
+ repositoryId: z.ZodString;
3969
+ attemptId: z.ZodOptional<z.ZodString>;
3970
+ action: z.ZodEnum<{
3971
+ refused: "refused";
3972
+ failed: "failed";
3973
+ removed: "removed";
3974
+ remove: "remove";
3975
+ }>;
3976
+ reason: z.ZodOptional<z.ZodEnum<{
3977
+ active: "active";
3978
+ recoverable: "recoverable";
3979
+ "cleanup-pending": "cleanup-pending";
3980
+ "cleanup-unreadable": "cleanup-unreadable";
3981
+ "unknown-attempt": "unknown-attempt";
3982
+ untrusted: "untrusted";
3983
+ "embedded-repository": "embedded-repository";
3984
+ "scan-limit": "scan-limit";
3985
+ "scan-failed": "scan-failed";
3986
+ "read-only-path": "read-only-path";
3987
+ "undecodable-path": "undecodable-path";
3988
+ "worktree-locked": "worktree-locked";
3989
+ "clean-filter": "clean-filter";
3990
+ "tree-changed": "tree-changed";
3991
+ "ignore-rules-changed": "ignore-rules-changed";
3992
+ "hidden-changes": "hidden-changes";
3993
+ "staged-ignored": "staged-ignored";
3994
+ "staged-differs": "staged-differs";
3995
+ "unreachable-head": "unreachable-head";
3996
+ "patch-unusable": "patch-unusable";
3997
+ "removal-incomplete": "removal-incomplete";
3998
+ "not-registered": "not-registered";
3999
+ }>>;
4000
+ error: z.ZodOptional<z.ZodString>;
4001
+ head: z.ZodOptional<z.ZodString>;
4002
+ sizeKb: z.ZodOptional<z.ZodNumber>;
4003
+ uncommitted: z.ZodOptional<z.ZodNumber>;
4004
+ ignored: z.ZodOptional<z.ZodObject<{
4005
+ count: z.ZodNumber;
4006
+ paths: z.ZodArray<z.ZodString>;
4007
+ }, z.core.$strict>>;
4008
+ record: z.ZodOptional<z.ZodString>;
4009
+ removalStarted: z.ZodOptional<z.ZodBoolean>;
4010
+ registered: z.ZodOptional<z.ZodBoolean>;
4011
+ treePresent: z.ZodOptional<z.ZodBoolean>;
4012
+ patch: z.ZodOptional<z.ZodString>;
4013
+ }, z.core.$strict>>;
4014
+ }, z.core.$strict>;
3891
4015
  readonly profile: z.ZodObject<{
3892
4016
  pin: z.ZodObject<{
3893
4017
  id: z.ZodString;
@@ -250,6 +250,21 @@ export const cliCommands = {
250
250
  ],
251
251
  refusals: ['NOT_FOUND', 'REVISION_CONFLICT'],
252
252
  },
253
+ 'worktree-cleanup': {
254
+ description: 'Убрать рабочие деревья закончившихся попыток: ветки и достижимые коммиты остаются, неподтверждённые правки сохраняются проверенным патчем в артефактах попытки, игнорируемые файлы не сохраняются и перечисляются в ответе; индекс, который патч не сохранит, — отказ; в сомнении дерево остаётся, а отказ назван; модель не вызывается',
255
+ writes: true,
256
+ idempotency: 'Повтор не находит уже убранных деревьев и ничего не меняет',
257
+ args: [
258
+ state,
259
+ {
260
+ name: '--dry-run',
261
+ value: 'flag',
262
+ required: false,
263
+ description: 'Только показать, что было бы убрано, что исчезнет (игнорируемое) и почему отказано; ничего не пишет',
264
+ },
265
+ ],
266
+ refusals: ['NOT_FOUND', 'NOT_READY'],
267
+ },
253
268
  cleanup: {
254
269
  description: 'Довести незавершённую очистку закончившейся попытки: повторить teardown по сохранённым receipt окружений и убрать её рабочие деревья; модели, gates и Git-приёмка не вызываются',
255
270
  writes: true,
@@ -802,6 +817,56 @@ export const cleanupDataSchema = z.discriminatedUnion('status', [
802
817
  /** Очищено: receipts окружений, по которым повторён teardown. */
803
818
  z.strictObject({ status: z.literal('cleaned'), receipts: z.array(z.string()) }),
804
819
  ]);
820
+ export const worktreeCleanupDataSchema = z.strictObject({
821
+ dryRun: z.boolean(),
822
+ removed: z.number().int(),
823
+ removable: z.number().int(),
824
+ refused: z.number().int(),
825
+ failed: z.number().int(),
826
+ reclaimedKb: z.number().int(),
827
+ worktrees: z.array(z.strictObject({
828
+ path: z.string(),
829
+ repositoryId: z.string(),
830
+ attemptId: z.string().optional(),
831
+ action: z.enum(['remove', 'removed', 'refused', 'failed']),
832
+ reason: z
833
+ .enum([
834
+ 'active',
835
+ 'recoverable',
836
+ 'cleanup-pending',
837
+ 'cleanup-unreadable',
838
+ 'unknown-attempt',
839
+ 'untrusted',
840
+ 'embedded-repository',
841
+ 'scan-limit',
842
+ 'scan-failed',
843
+ 'read-only-path',
844
+ 'undecodable-path',
845
+ 'worktree-locked',
846
+ 'clean-filter',
847
+ 'tree-changed',
848
+ 'ignore-rules-changed',
849
+ 'hidden-changes',
850
+ 'staged-ignored',
851
+ 'staged-differs',
852
+ 'unreachable-head',
853
+ 'patch-unusable',
854
+ 'removal-incomplete',
855
+ 'not-registered',
856
+ ])
857
+ .optional(),
858
+ error: z.string().optional(),
859
+ head: z.string().optional(),
860
+ sizeKb: z.number().int().optional(),
861
+ uncommitted: z.number().int().optional(),
862
+ ignored: z.strictObject({ count: z.number().int(), paths: z.array(z.string()) }).optional(),
863
+ record: z.string().optional(),
864
+ removalStarted: z.boolean().optional(),
865
+ registered: z.boolean().optional(),
866
+ treePresent: z.boolean().optional(),
867
+ patch: z.string().optional(),
868
+ })),
869
+ });
805
870
  /** `init`: план или результат подготовки проекта. */
806
871
  export const initDataSchema = z.strictObject({
807
872
  mode: z.enum(['plan', 'apply']),
@@ -851,6 +916,7 @@ export const cliDataSchemas = {
851
916
  result: resultEnvelopeSchema,
852
917
  deliver: resultEnvelopeSchema,
853
918
  cleanup: cleanupDataSchema,
919
+ 'worktree-cleanup': worktreeCleanupDataSchema,
854
920
  profile: profileDataSchema,
855
921
  doctor: doctorDataSchema,
856
922
  init: initDataSchema,
@@ -217,6 +217,20 @@ export declare const roleBindingSchema: z.ZodObject<{
217
217
  }, z.core.$strict>>;
218
218
  requiresContract: z.ZodDefault<z.ZodBoolean>;
219
219
  }, z.core.$strict>;
220
+ /**
221
+ * Хранилище зависимостей репозитория: harness сам держит seed менеджера пакетов
222
+ * по lockfile целевой ветки и разворачивает его в каждый checkout (см.
223
+ * `verification/dependency-store.ts`). Нет поля — поведение и digest прежние.
224
+ */
225
+ export declare const dependencyStoreSchema: z.ZodObject<{
226
+ manager: z.ZodEnum<{
227
+ pnpm: "pnpm";
228
+ }>;
229
+ lockfile: z.ZodDefault<z.ZodString>;
230
+ maxBytes: z.ZodDefault<z.ZodNumber>;
231
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
232
+ }, z.core.$strict>;
233
+ export type DependencyStorePolicy = z.infer<typeof dependencyStoreSchema>;
220
234
  export declare const repositoryPolicySchema: z.ZodObject<{
221
235
  id: z.ZodString;
222
236
  roles: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
@@ -378,6 +392,14 @@ export declare const repositoryPolicySchema: z.ZodObject<{
378
392
  command: z.ZodArray<z.ZodString>;
379
393
  timeoutMs: z.ZodDefault<z.ZodNumber>;
380
394
  }, z.core.$strict>>>;
395
+ dependencyStore: z.ZodOptional<z.ZodObject<{
396
+ manager: z.ZodEnum<{
397
+ pnpm: "pnpm";
398
+ }>;
399
+ lockfile: z.ZodDefault<z.ZodString>;
400
+ maxBytes: z.ZodDefault<z.ZodNumber>;
401
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
402
+ }, z.core.$strict>>;
381
403
  dependencyBuild: z.ZodDefault<z.ZodArray<z.ZodObject<{
382
404
  id: z.ZodString;
383
405
  command: z.ZodArray<z.ZodString>;
@@ -630,6 +652,14 @@ export declare const executionPolicySchema: z.ZodObject<{
630
652
  command: z.ZodArray<z.ZodString>;
631
653
  timeoutMs: z.ZodDefault<z.ZodNumber>;
632
654
  }, z.core.$strict>>>;
655
+ dependencyStore: z.ZodOptional<z.ZodObject<{
656
+ manager: z.ZodEnum<{
657
+ pnpm: "pnpm";
658
+ }>;
659
+ lockfile: z.ZodDefault<z.ZodString>;
660
+ maxBytes: z.ZodDefault<z.ZodNumber>;
661
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
662
+ }, z.core.$strict>>;
633
663
  dependencyBuild: z.ZodDefault<z.ZodArray<z.ZodObject<{
634
664
  id: z.ZodString;
635
665
  command: z.ZodArray<z.ZodString>;
@@ -98,6 +98,27 @@ export const roleBindingSchema = z.strictObject({
98
98
  review: reviewRuleSchema.optional(),
99
99
  requiresContract: z.boolean().default(false),
100
100
  });
101
+ /**
102
+ * Хранилище зависимостей репозитория: harness сам держит seed менеджера пакетов
103
+ * по lockfile целевой ветки и разворачивает его в каждый checkout (см.
104
+ * `verification/dependency-store.ts`). Нет поля — поведение и digest прежние.
105
+ */
106
+ export const dependencyStoreSchema = z.strictObject({
107
+ manager: z.enum(['pnpm']),
108
+ /** Lockfile относительно корня репозитория. */
109
+ lockfile: relativePathSchema.default('pnpm-lock.yaml'),
110
+ /** Предел логического размера seeds репозитория на диске. */
111
+ maxBytes: z
112
+ .number()
113
+ .int()
114
+ .min(1024 * 1024)
115
+ .default(8 * 1024 * 1024 * 1024),
116
+ /**
117
+ * Верхний предел сборки seed вместе с ожиданием чужой сборки. Действует ещё и
118
+ * доля остатка времени фазы: хранилище не расходует время попытки до отказа.
119
+ */
120
+ timeoutMs: z.number().int().positive().max(3_600_000).default(600000),
121
+ });
101
122
  export const repositoryPolicySchema = z.strictObject({
102
123
  id: idSchema,
103
124
  /**
@@ -119,6 +140,8 @@ export const repositoryPolicySchema = z.strictObject({
119
140
  environment: environmentSchema.optional(),
120
141
  lifecycle: lifecycleSchema.optional(),
121
142
  prepare: z.array(stepSchema).default([]),
143
+ /** Необязательное поле без умолчания: политика без него сохраняет digest. */
144
+ dependencyStore: dependencyStoreSchema.optional(),
122
145
  dependencyBuild: z.array(stepSchema).default([]),
123
146
  dependencyArtifacts: z.array(relativePathSchema).default([]),
124
147
  preflight: z.array(stepSchema).default([]),
@@ -272,6 +272,14 @@ export declare const publishedSchemas: {
272
272
  command: z.ZodArray<z.ZodString>;
273
273
  timeoutMs: z.ZodDefault<z.ZodNumber>;
274
274
  }, z.core.$strict>>>;
275
+ dependencyStore: z.ZodOptional<z.ZodObject<{
276
+ manager: z.ZodEnum<{
277
+ pnpm: "pnpm";
278
+ }>;
279
+ lockfile: z.ZodDefault<z.ZodString>;
280
+ maxBytes: z.ZodDefault<z.ZodNumber>;
281
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
282
+ }, z.core.$strict>>;
275
283
  dependencyBuild: z.ZodDefault<z.ZodArray<z.ZodObject<{
276
284
  id: z.ZodString;
277
285
  command: z.ZodArray<z.ZodString>;
@@ -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, issuePath, 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 });
@@ -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 на