devcontour-harness 0.1.0-alpha.21 → 0.1.0-alpha.23

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 (42) hide show
  1. package/README.md +21 -2
  2. package/docs/architecture.md +10 -1
  3. package/docs/compatibility.md +11 -11
  4. package/docs/contracts.md +17 -2
  5. package/docs/quickstart.md +1 -1
  6. package/docs/release-notes/0.1.0-alpha.22.md +57 -0
  7. package/docs/release-notes/0.1.0-alpha.23.md +122 -0
  8. package/docs/toolchains.md +2 -1
  9. package/docs/upgrade.md +17 -17
  10. package/lib/agents/cli-adapter.js +1 -0
  11. package/lib/agents/review-probe.d.ts +1 -0
  12. package/lib/agents/review-probe.js +4 -0
  13. package/lib/cli.js +1 -1
  14. package/lib/contracts/cli.d.ts +20 -0
  15. package/lib/contracts/cli.js +11 -0
  16. package/lib/contracts/ports.d.ts +6 -0
  17. package/lib/control/base-move.d.ts +2 -0
  18. package/lib/control/base-move.js +13 -2
  19. package/lib/control/doctor.d.ts +10 -0
  20. package/lib/control/doctor.js +19 -3
  21. package/lib/control/harness.d.ts +6 -0
  22. package/lib/control/harness.js +2 -0
  23. package/lib/engine/joint-runner.d.ts +5 -0
  24. package/lib/engine/joint-runner.js +28 -5
  25. package/lib/engine/runner.d.ts +18 -0
  26. package/lib/engine/runner.js +73 -10
  27. package/lib/environment/checkout-root.d.ts +78 -0
  28. package/lib/environment/checkout-root.js +133 -0
  29. package/lib/environment/git-trust.js +4 -0
  30. package/lib/environment/isolation.d.ts +48 -9
  31. package/lib/environment/isolation.js +132 -37
  32. package/lib/index.d.ts +5 -0
  33. package/lib/index.js +5 -0
  34. package/lib/verification/confirm.d.ts +7 -4
  35. package/lib/verification/confirm.js +4 -2
  36. package/lib/verification/gates-at.d.ts +9 -5
  37. package/lib/verification/gates-at.js +30 -5
  38. package/lib/verification/gates.d.ts +13 -4
  39. package/lib/verification/gates.js +15 -2
  40. package/lib/verification/spike.d.ts +7 -4
  41. package/lib/verification/spike.js +4 -2
  42. package/package.json +1 -1
@@ -1,6 +1,9 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { isAbsolute, join, resolve } from 'node:path';
2
+ import { mkdir } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
3
4
  import { git, hostGitArgs } from "../environment/process.js";
5
+ import { checkoutPath, chooseCheckoutRoot } from "../environment/checkout-root.js";
6
+ import { credentialPaths } from "../environment/isolation.js";
4
7
  /**
5
8
  * Сдвиг ref внутри транзакции проверки владения операцией: проверка и
6
9
  * `git update-ref` неразделимы — отмена или перехват операции либо видны
@@ -34,6 +37,12 @@ export async function moveBase(input) {
34
37
  ((repoPath, target, to, from) => git(repoPath, 'update-ref', target, to, from).then(() => undefined));
35
38
  const path = (p) => (isAbsolute(p) ? p : resolve(input.baseDir, p));
36
39
  const updated = [];
40
+ const placement = chooseCheckoutRoot({
41
+ stateDirs: [input.stateDir],
42
+ repositories: input.policy.repositories.map((r) => path(r.path)),
43
+ hidden: credentialPaths(),
44
+ ...(input.checkoutRoot ? { configured: input.checkoutRoot } : {}),
45
+ });
37
46
  for (const repo of input.policy.repositories.filter((r) => !input.only || r.id in input.only)) {
38
47
  const repoPath = path(repo.path);
39
48
  const head = input.only?.[repo.id] ?? (await git(repoPath, 'rev-parse', 'HEAD'));
@@ -59,7 +68,9 @@ export async function moveBase(input) {
59
68
  }
60
69
  // Обе линии несут работу: сводятся слиянием в отдельном worktree — target
61
70
  // ref checkout-веткой быть не может и продвигается только через CAS.
62
- const cwd = join(input.stateDir, 'worktrees', `base-${repo.id}-${Date.now()}`);
71
+ const name = `base-${repo.id}-${Date.now()}`;
72
+ const cwd = checkoutPath(placement, join(input.stateDir, 'worktrees', name), repo.id, 'base', name);
73
+ await mkdir(dirname(cwd), { recursive: true });
63
74
  await git(repoPath, 'worktree', 'add', '--detach', cwd, tip);
64
75
  try {
65
76
  await git(cwd, '-c', 'core.hooksPath=/dev/null', 'merge', '--no-ff', '--no-edit', '--no-gpg-sign', head);
@@ -20,9 +20,19 @@ export declare function doctor(policy: ExecutionPolicy | undefined, adapters: Pa
20
20
  toolchain?: {
21
21
  baseDir: string;
22
22
  inspect: ToolchainInspect;
23
+ },
24
+ /**
25
+ * Корень рабочих деревьев: выбор по каталогу состояния и репозиториям
26
+ * политики (`chooseCheckoutRoot`) или заданный хостом. Нужны политика и
27
+ * каталог состояния.
28
+ */
29
+ checkouts?: {
30
+ baseDir: string;
31
+ checkoutRoot?: string;
23
32
  }): Promise<{
24
33
  problems: string[];
25
34
  toolchains?: ToolchainReport[] | undefined;
35
+ checkouts?: import("../environment/checkout-root.ts").CheckoutRoot | undefined;
26
36
  state?: {
27
37
  stateVersion: number;
28
38
  compatible: boolean;
@@ -1,7 +1,8 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { isAbsolute, join, resolve } from 'node:path';
3
3
  import { API_VERSION, HarnessError, STATE_VERSION, } from "../contracts/index.js";
4
- import { isolationSupport } from "../environment/isolation.js";
4
+ import { credentialPaths, isolationSupport } from "../environment/isolation.js";
5
+ import { chooseCheckoutRoot } from "../environment/checkout-root.js";
5
6
  import { HARNESS_VERSION } from "../package.js";
6
7
  import { SqliteExecutionStore } from "../storage/sqlite.js";
7
8
  /** Runtime, которые политика действительно назначает writer или reviewer. */
@@ -43,7 +44,13 @@ export async function doctor(policy, adapters, stateDir,
43
44
  * версий. Передаётся явно (CLI — `inspectPolicy` из `./toolchains`): корень
44
45
  * пакета не тянет модуль toolchains сам.
45
46
  */
46
- toolchain) {
47
+ toolchain,
48
+ /**
49
+ * Корень рабочих деревьев: выбор по каталогу состояния и репозиториям
50
+ * политики (`chooseCheckoutRoot`) или заданный хостом. Нужны политика и
51
+ * каталог состояния.
52
+ */
53
+ checkouts) {
47
54
  const problems = [];
48
55
  const runtimes = [];
49
56
  // С политикой обязательны только назначенные ею runtime: сценарий одного
@@ -95,6 +102,14 @@ toolchain) {
95
102
  problems.push(error instanceof HarnessError ? error.message : String(error));
96
103
  }
97
104
  }
105
+ const checkoutRoot = policy && stateDir && checkouts
106
+ ? chooseCheckoutRoot({
107
+ stateDirs: [stateDir],
108
+ repositories: policy.repositories.map((r) => isAbsolute(r.path) ? r.path : resolve(checkouts.baseDir, r.path)),
109
+ hidden: credentialPaths(),
110
+ ...(checkouts.checkoutRoot ? { configured: checkouts.checkoutRoot } : {}),
111
+ })
112
+ : undefined;
98
113
  const toolchains = policy && toolchain ? await toolchain.inspect(policy, toolchain.baseDir) : undefined;
99
114
  for (const r of toolchains ?? [])
100
115
  for (const p of r.problems)
@@ -107,6 +122,7 @@ toolchain) {
107
122
  runtimes,
108
123
  sandbox: { os: sandbox.ok, ...(sandbox.ok ? {} : { reason: sandbox.detail }) },
109
124
  ...(state ? { state } : {}),
125
+ ...(checkoutRoot ? { checkouts: checkoutRoot } : {}),
110
126
  ...(toolchains ? { toolchains } : {}),
111
127
  problems,
112
128
  };
@@ -29,6 +29,12 @@ export interface HarnessOptions {
29
29
  policySource?: PolicySource;
30
30
  /** База блокировок ресурсов; по умолчанию — общая для машины. */
31
31
  resourceDatabase?: string;
32
+ /**
33
+ * Корень рабочих деревьев попыток и совместных проверок; без него —
34
+ * `chooseCheckoutRoot` (кэш пользователя, если каталог состояния внутри
35
+ * репозитория, иначе каталог состояния).
36
+ */
37
+ checkoutRoot?: string;
32
38
  /**
33
39
  * Дополнения хоста к попыткам (например, история работы внешнего
34
40
  * хранилища задач до исполнения). Приёмку не решают: отказ хука — отказ
@@ -71,6 +71,7 @@ export class Harness {
71
71
  ...(options.environment ? { environment: options.environment } : {}),
72
72
  ...(options.resourceDatabase ? { resourceDatabase: options.resourceDatabase } : {}),
73
73
  ...(options.hooks ? { hooks: options.hooks } : {}),
74
+ ...(options.checkoutRoot ? { checkoutRoot: options.checkoutRoot } : {}),
74
75
  });
75
76
  this.joint = new JointRunner({
76
77
  engine: this.engine,
@@ -78,6 +79,7 @@ export class Harness {
78
79
  baseDir: options.baseDir,
79
80
  ...(options.environment ? { environment: options.environment } : {}),
80
81
  ...(options.resourceDatabase ? { resourceDatabase: options.resourceDatabase } : {}),
82
+ ...(options.checkoutRoot ? { checkoutRoot: options.checkoutRoot } : {}),
81
83
  });
82
84
  }
83
85
  close() {
@@ -7,6 +7,11 @@ export interface JointRunnerOptions {
7
7
  baseDir: string;
8
8
  environment?: NodeJS.ProcessEnv;
9
9
  resourceDatabase?: string;
10
+ /**
11
+ * Корень снимков компонентов (`<checkoutRoot>/.joint/<id>/components`: ID репозитория с точки не начинается); без
12
+ * него — `chooseCheckoutRoot` по каталогу состояния и каталогу проверки.
13
+ */
14
+ checkoutRoot?: string;
10
15
  /** Каталог проверки (по умолчанию `<stateDir>/joint/<id>`). */
11
16
  directory?: (verification: JointVerificationState) => string;
12
17
  /** Дополнительные переменные окружения gates этой проверки (у хоста — его идентификаторы). */
@@ -1,8 +1,10 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
3
- import { isAbsolute, join, resolve, sep } from 'node:path';
3
+ import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
4
4
  import { digestOf, } from "../contracts/index.js";
5
5
  import { git } from "../environment/process.js";
6
+ import { chooseCheckoutRoot } from "../environment/checkout-root.js";
7
+ import { credentialPaths } from "../environment/isolation.js";
6
8
  import { CleanupFailure, availableRedactor, executionEnvironment, withEnvironment, } from "../environment/lifecycle.js";
7
9
  import { composeRedactors } from "../environment/redaction.js";
8
10
  import { defaultResourceDatabase, withResources } from "../environment/resources.js";
@@ -55,6 +57,17 @@ export class JointRunner {
55
57
  }
56
58
  }, Math.max(1000, this.policy.leaseMs / 3));
57
59
  const dir = this.options.directory?.(v) ?? join(this.options.stateDir, 'joint', v.id);
60
+ // Снимки компонентов — вне дерева, если каталог проверки лежит внутри
61
+ // репозитория: gate, ищущий конфигурацию вверх, не упирается в закрытый checkout.
62
+ const placement = chooseCheckoutRoot({
63
+ stateDirs: [this.options.stateDir, dir],
64
+ repositories: this.policy.repositories.map((r) => this.repoPath(r)),
65
+ hidden: credentialPaths(),
66
+ ...(this.options.checkoutRoot ? { configured: this.options.checkoutRoot } : {}),
67
+ });
68
+ const components = placement.root
69
+ ? join(placement.root, '.joint', v.id, 'components')
70
+ : join(dir, 'components');
58
71
  const worktrees = [];
59
72
  const source = this.options.environment ?? process.env;
60
73
  // Незавершённая очистка окружения оставляет снимки: их разбирает cleanup.
@@ -66,7 +79,10 @@ export class JointRunner {
66
79
  resourceDatabase: this.options.resourceDatabase ?? defaultResourceDatabase(),
67
80
  }, [...new Set(this.policy.workspaceGates.flatMap((g) => g.resources ?? []))], `${this.options.stateDir}:${v.id}`, signal, async (signal, resources) => {
68
81
  await this.options.prepare?.(signal);
69
- await mkdir(join(dir, 'components'), { recursive: true });
82
+ // Каталог проверки (impact, manifest, логи) — и тогда, когда
83
+ // компоненты лежат под корнем вне дерева.
84
+ await mkdir(dir, { recursive: true });
85
+ await mkdir(components, { recursive: true });
70
86
  const works = this.engine.read((view) => v.workIds.map((id) => view.work(id)));
71
87
  const manifest = {};
72
88
  const paths = {};
@@ -78,7 +94,7 @@ export class JointRunner {
78
94
  await git(path, 'merge-base', '--is-ancestor', w.resultSha, sha).catch(() => {
79
95
  throw new Error(`Результат ${w.id} отсутствует в ${repo.targetRef} ${repo.id}`);
80
96
  });
81
- const cwd = join(dir, 'components', repo.id);
97
+ const cwd = join(components, repo.id);
82
98
  await git(path, 'worktree', 'add', '--detach', cwd, sha);
83
99
  worktrees.push({ repo: path, cwd });
84
100
  manifest[repo.id] = { sha, tree: await git(cwd, 'rev-parse', 'HEAD^{tree}') };
@@ -163,6 +179,7 @@ export class JointRunner {
163
179
  this.options.stateDir,
164
180
  ...this.policy.repositories.map((r) => this.repoPath(r)),
165
181
  ],
182
+ ...(placement.root ? { checkouts: [placement.root] } : {}),
166
183
  settingsDir: join(dir, gate.id),
167
184
  env: {
168
185
  ...environment.env,
@@ -246,8 +263,14 @@ export class JointRunner {
246
263
  if (!preserve) {
247
264
  for (const w of worktrees)
248
265
  await git(w.repo, 'worktree', 'remove', '--force', w.cwd).catch(() => undefined);
249
- if (dir.startsWith(this.options.stateDir + sep))
250
- await rm(join(dir, 'components'), { recursive: true, force: true }).catch(() => undefined);
266
+ // Убирается только каталог, созданный здесь: в каталоге состояния или
267
+ // под корнем вне дерева.
268
+ const owned = placement.root ?? this.options.stateDir;
269
+ if (components.startsWith(owned + sep))
270
+ await rm(placement.root ? dirname(components) : components, {
271
+ recursive: true,
272
+ force: true,
273
+ }).catch(() => undefined);
251
274
  }
252
275
  }
253
276
  }
@@ -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 CheckoutRoot } from '../environment/checkout-root.ts';
2
3
  import { type FailureKind } from './failure.ts';
3
4
  import { type Engine } from './engine.ts';
4
5
  import { CorpusStore } from '../verification/corpus.ts';
@@ -13,6 +14,15 @@ export interface RunnerOptions {
13
14
  * туда и его попытки.
14
15
  */
15
16
  stateDirFor?: (repositoryId: string) => string;
17
+ /**
18
+ * Корень рабочих деревьев, снимков зависимостей и проверок потребителей
19
+ * (`<checkoutRoot>/<repositoryId>/worktrees/<attempt>`…). Без него —
20
+ * `chooseCheckoutRoot`: каталог кэша пользователя, если каталог состояния
21
+ * лежит внутри репозитория, иначе прежнее место в каталоге состояния.
22
+ * Лучше на том же томе, что репозитории: менеджеры пакетов ставят
23
+ * зависимости жёсткими ссылками и reflink.
24
+ */
25
+ checkoutRoot?: string;
16
26
  /** Каталог, от которого разрешаются относительные пути репозиториев политики. */
17
27
  baseDir: string;
18
28
  adapters: Partial<Record<RuntimeName, RuntimeAdapter>>;
@@ -90,6 +100,14 @@ export declare class Runner {
90
100
  constructor(options: RunnerOptions);
91
101
  /** Каталог попыток репозитория. */
92
102
  private dirOf;
103
+ private placement?;
104
+ /**
105
+ * Действующий корень рабочих деревьев (`checkout-root.ts`): хост
106
+ * показывает его в диагностике. Выбирается один раз на исполнитель.
107
+ */
108
+ checkoutRoot(): CheckoutRoot;
109
+ /** Каталог рабочего дерева вида `kind`: вне дерева или прежний в каталоге попыток. */
110
+ private checkout;
93
111
  repoPath(repo: Repo): string;
94
112
  private repo;
95
113
  /**
@@ -2,11 +2,13 @@ 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 { isAbsolute, join, relative, resolve } from 'node:path';
5
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
6
6
  import { roleBinding, selectReviewer, mcpEnvironment, HarnessError, digestOf, contextDigest, implementationResultSchema, codeReviewHistory, codeReviewScope, checkCodeReview, logicalReview, DEFAULT_REVIEW_PROTOCOL_RETRIES, reviewResultSchema, sha256, } from "../contracts/index.js";
7
7
  import { git, hostGitArgs } from "../environment/process.js";
8
- import { protectedChanges, protectedSnapshot } from "../environment/isolation.js";
8
+ import { protectedChanges, protectedSnapshot, SandboxPolicyError, } from "../environment/isolation.js";
9
9
  import { executionEnvironment, runSteps, withEnvironment } from "../environment/lifecycle.js";
10
+ import { checkoutPath, chooseCheckoutRoot, realish, } from "../environment/checkout-root.js";
11
+ import { credentialPaths } from "../environment/isolation.js";
10
12
  import { redactDeep } from "../environment/redaction.js";
11
13
  import { alreadySatisfiedReviewOutputSchema, implementationOutputSchema, reviewOutputSchema, } from "../agents/schemas.js";
12
14
  import { reviewInspection } from "../agents/inspect.js";
@@ -75,6 +77,23 @@ export class Runner {
75
77
  dirOf(repositoryId) {
76
78
  return this.options.stateDirFor?.(repositoryId) ?? this.options.stateDir;
77
79
  }
80
+ placement;
81
+ /**
82
+ * Действующий корень рабочих деревьев (`checkout-root.ts`): хост
83
+ * показывает его в диагностике. Выбирается один раз на исполнитель.
84
+ */
85
+ checkoutRoot() {
86
+ return (this.placement ??= chooseCheckoutRoot({
87
+ stateDirs: [this.options.stateDir, ...this.policy.repositories.map((r) => this.dirOf(r.id))],
88
+ repositories: this.policy.repositories.map((r) => this.repoPath(r)),
89
+ hidden: credentialPaths(),
90
+ ...(this.options.checkoutRoot ? { configured: this.options.checkoutRoot } : {}),
91
+ }));
92
+ }
93
+ /** Каталог рабочего дерева вида `kind`: вне дерева или прежний в каталоге попыток. */
94
+ checkout(repositoryId, kind, ...rest) {
95
+ return checkoutPath(this.checkoutRoot(), join(this.dirOf(repositoryId), kind, ...rest), repositoryId, kind, ...rest);
96
+ }
78
97
  repoPath(repo) {
79
98
  return isAbsolute(repo.path) ? repo.path : resolve(this.options.baseDir, repo.path);
80
99
  }
@@ -90,7 +109,11 @@ export class Runner {
90
109
  */
91
110
  boundary(dependencies = []) {
92
111
  const repos = this.policy.repositories.map((r) => this.repoPath(r));
112
+ const root = this.checkoutRoot().root;
93
113
  return {
114
+ // Корень вне дерева закрыт целиком, как каталог состояния: свои
115
+ // деревья открыты более конкретным разрешением.
116
+ checkouts: root ? [root] : [],
94
117
  hidden: [
95
118
  ...new Set([
96
119
  this.options.stateDir,
@@ -374,6 +397,7 @@ export class Runner {
374
397
  mode: this.policy.isolation.mode,
375
398
  writable: review ? [] : [input.cwd],
376
399
  denied: boundary.hidden,
400
+ ...(boundary.checkouts.length ? { checkouts: boundary.checkouts } : {}),
377
401
  readable: [
378
402
  input.cwd,
379
403
  ...boundary.readable,
@@ -668,7 +692,7 @@ export class Runner {
668
692
  controller.abort();
669
693
  }
670
694
  }, Math.max(1000, this.policy.leaseMs / 3));
671
- const cwd = join(this.dirOf(repo.id), 'worktrees', attempt.id);
695
+ const cwd = this.checkout(repo.id, 'worktrees', attempt.id);
672
696
  const integrationCwd = cwd + '-integration';
673
697
  const artifacts = join(this.dirOf(repo.id), 'artifacts', attempt.id);
674
698
  const worktrees = [];
@@ -720,7 +744,7 @@ export class Runner {
720
744
  const dependencies = await snapshotDependencies({
721
745
  repos: this.repositories(),
722
746
  repositoryId: repo.id,
723
- dir: join(this.dirOf(repo.id), 'dependencies', attempt.id),
747
+ dir: this.checkout(repo.id, 'dependencies', attempt.id),
724
748
  artifacts,
725
749
  runId: attempt.id,
726
750
  policy: this.policy,
@@ -743,7 +767,7 @@ export class Runner {
743
767
  // берётся ли кандидат предыдущей попытки вместо нового кода.
744
768
  const reuse = this.engine.implementationBasis(attempt.id, attempt.token, implementationBasis(work, attempt, base, this.engine.version));
745
769
  attempt = { ...attempt, ...(reuse.reusedFrom ? { reusedFrom: reuse.reusedFrom } : {}) };
746
- await mkdir(join(this.dirOf(repo.id), 'worktrees'), { recursive: true });
770
+ await mkdir(dirname(cwd), { recursive: true });
747
771
  await git(repoPath, 'worktree', 'add', '-b', `${this.options.branchPrefix ?? 'harness/run-'}${attempt.id}`, cwd, reuse.reusedFrom?.candidateSha ?? base);
748
772
  worktrees.push(cwd);
749
773
  this.engine.phase(attempt.id, attempt.token, 'running', { baseSha: base, worktree: cwd });
@@ -766,7 +790,18 @@ export class Runner {
766
790
  // Защищённые пути до работы исполнителя: перенос каталога,
767
791
  // собранного там, где запрет песочницы не действует, виден
768
792
  // только сверкой.
769
- const guarded = this.policy.isolation.mode === 'os' ? protectedSnapshot(cwd) : undefined;
793
+ // Непрочитанный до работы путь — отказ среды: исполнитель
794
+ // его ещё не трогал.
795
+ let guarded;
796
+ try {
797
+ if (this.policy.isolation.mode === 'os')
798
+ guarded = protectedSnapshot(cwd);
799
+ }
800
+ catch (error) {
801
+ if (error instanceof SandboxPolicyError)
802
+ throw new TaskFailure('environment', error.message);
803
+ throw error;
804
+ }
770
805
  const response = await this.call(this.adapter(attempt.runtime), {
771
806
  task: 'implement',
772
807
  attempt,
@@ -804,7 +839,18 @@ export class Runner {
804
839
  result.data.summary.slice(0, 500));
805
840
  this.engine.heartbeat(attempt.id, attempt.token);
806
841
  signal.throwIfAborted();
807
- const planted = guarded ? protectedChanges(guarded, cwd) : [];
842
+ // После работы непрочитанный путь закрыл исполнитель —
843
+ // нарушение области, как и созданный защищённый путь.
844
+ let planted = [];
845
+ try {
846
+ if (guarded)
847
+ planted = protectedChanges(guarded, cwd);
848
+ }
849
+ catch (error) {
850
+ if (error instanceof SandboxPolicyError)
851
+ throw new TaskFailure('scope-violation', error.message);
852
+ throw error;
853
+ }
808
854
  if (planted.length)
809
855
  throw new TaskFailure('scope-violation', 'Исполнитель создал или изменил защищённые пути (конфигурация IDE, shell, git или Claude): ' +
810
856
  planted
@@ -1038,10 +1084,14 @@ export class Runner {
1038
1084
  ],
1039
1085
  snapshots: [],
1040
1086
  };
1087
+ // Окружения прежних попыток лежат в каталоге состояния, новых — под
1088
+ // корнем рабочих деревьев вне дерева.
1089
+ const outside = this.checkoutRoot().root;
1041
1090
  const roots = [
1042
1091
  ...new Set([
1043
1092
  await realpath(this.options.stateDir),
1044
1093
  await realpath(this.dirOf(attempt.repositoryId)),
1094
+ ...(outside ? [realish(outside)] : []),
1045
1095
  ]),
1046
1096
  ];
1047
1097
  const cleaned = [];
@@ -1184,9 +1234,9 @@ export class Runner {
1184
1234
  const repo = this.repo(consumer.repositoryId);
1185
1235
  const checkout = this.repoPath(repo);
1186
1236
  const id = `${attempt.id}-consumer-${repo.id}-${randomUUID().slice(0, 8)}`;
1187
- const dir = join(this.dirOf(repo.id), 'consumers', id);
1237
+ const dir = this.checkout(repo.id, 'consumers', id);
1188
1238
  const own = join(artifacts, 'integration', 'consumer', repo.id);
1189
- await mkdir(join(this.dirOf(repo.id), 'consumers'), { recursive: true });
1239
+ await mkdir(dirname(dir), { recursive: true });
1190
1240
  await git(checkout, 'worktree', 'add', '--detach', dir, repo.targetRef);
1191
1241
  let dependencies = [];
1192
1242
  let failure;
@@ -1203,7 +1253,7 @@ export class Runner {
1203
1253
  dependencies = await snapshotDependencies({
1204
1254
  repos: this.repositories(),
1205
1255
  repositoryId: repo.id,
1206
- dir: join(this.dirOf(repo.id), 'dependencies', id),
1256
+ dir: this.checkout(repo.id, 'dependencies', id),
1207
1257
  artifacts: own,
1208
1258
  runId: attempt.id,
1209
1259
  policy: this.policy,
@@ -1310,6 +1360,7 @@ export class Runner {
1310
1360
  cwd,
1311
1361
  controller: boundary.hidden,
1312
1362
  readable: [cwd, ...boundary.readable],
1363
+ ...(boundary.checkouts.length ? { checkouts: boundary.checkouts } : {}),
1313
1364
  isolation: this.policy.isolation,
1314
1365
  commandTimeoutMs: limits.commandTimeoutMs,
1315
1366
  budgetMs,
@@ -1873,6 +1924,12 @@ export class Runner {
1873
1924
  stateDir: this.options.stateDir,
1874
1925
  repoPath: (repo) => this.repoPath(repo),
1875
1926
  boundary: () => this.boundary(),
1927
+ // Прежнее место эксперимента — общий каталог состояния: меняется только корень вне дерева.
1928
+ ...(this.checkoutRoot().root
1929
+ ? {
1930
+ checkout: (repositoryId, kind, id) => this.checkout(repositoryId, kind, id),
1931
+ }
1932
+ : {}),
1876
1933
  ...(this.options.environment ? { environment: this.options.environment } : {}),
1877
1934
  }, raw);
1878
1935
  }
@@ -1887,6 +1944,12 @@ export class Runner {
1887
1944
  stateDir: this.options.stateDir,
1888
1945
  repoPath: (repo) => this.repoPath(repo),
1889
1946
  boundary: () => this.boundary(),
1947
+ // Прежнее место эксперимента — общий каталог состояния: меняется только корень вне дерева.
1948
+ ...(this.checkoutRoot().root
1949
+ ? {
1950
+ checkout: (repositoryId, kind, id) => this.checkout(repositoryId, kind, id),
1951
+ }
1952
+ : {}),
1890
1953
  ...(this.options.environment ? { environment: this.options.environment } : {}),
1891
1954
  }, raw);
1892
1955
  }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Где harness создаёт рабочие деревья попыток, снимки зависимостей, деревья
3
+ * переноса базы, проверки на SHA и проверки потребителей.
4
+ *
5
+ * Прежде они лежали в каталоге состояния. При встроенном размещении каталог
6
+ * состояния находится внутри репозитория человека (`<W>/.devcontour-local`),
7
+ * и тогда checkout кандидата оказывался вложен в его рабочее дерево. Песочница
8
+ * закрывает `<W>` целиком и открывает только сам checkout, а инструменты,
9
+ * которые ищут конфигурацию вверх по дереву (browserslist, Metro, postcss,
10
+ * tsconfig, prettier), доходили до `<W>/package.json` и получали EPERM вместо
11
+ * ENOENT. Без песочницы они бы прочитали конфигурацию рабочего дерева
12
+ * человека — кандидат проверялся бы не сам по себе.
13
+ *
14
+ * Поэтому корень рабочих деревьев выбирается так:
15
+ * - корень, заданный хостом (`checkoutRoot`), — как есть, если он не внутри
16
+ * репозитория, закрытого пути или каталога состояния (иначе отказ);
17
+ * - каталог состояния внутри репозитория политики или внутри закрытого
18
+ * песочницей пути — каталог кэша пользователя вне дерева: macOS
19
+ * `~/Library/Caches/devcontour-harness/<hash>`, Linux
20
+ * `$XDG_CACHE_HOME/devcontour-harness/<hash>` или
21
+ * `~/.cache/devcontour-harness/<hash>`; `<hash>` — устойчивый хэш
22
+ * настоящего пути каталога состояния;
23
+ * - иначе — прежнее место (отдельное размещение не меняется).
24
+ *
25
+ * Кэш на другом томе, чем репозиторий, ломает жёсткие ссылки и reflink
26
+ * менеджеров пакетов (pnpm store): тогда корень остаётся прежним, а причина
27
+ * видна в `note` (doctor хоста её показывает). Так же — кэш внутри
28
+ * репозитория, закрытого пути или каталога состояния (`XDG_CACHE_HOME=<W>/.cache`)
29
+ * и каталог кэша, который оказался ссылкой или принадлежит другому
30
+ * пользователю: каталоги кэша создаются с правами 0700.
31
+ *
32
+ * Корни кэша не убираются, когда workspace переносят или удаляют: каталоги
33
+ * `<кэш>/devcontour-harness/<hash>` без живого каталога состояния можно удалить
34
+ * вручную, когда harness не запущен.
35
+ */
36
+ export type CheckoutPlacement = 'configured' | 'in-place' | 'cache' | 'cross-volume';
37
+ export interface CheckoutRoot {
38
+ /** Корень вне каталога состояния; без него — прежнее место. */
39
+ root?: string;
40
+ placement: CheckoutPlacement;
41
+ /** Пояснение для диагностики: почему корень такой. */
42
+ note?: string;
43
+ }
44
+ export interface CheckoutRootInput {
45
+ /** Каталоги состояния (общий и каталоги попыток репозиториев); первый задаёт хэш. */
46
+ stateDirs: string[];
47
+ /** Пути репозиториев политики. */
48
+ repositories: string[];
49
+ /** Что ещё закрыто песочницей (учётные данные, каталоги хоста). */
50
+ hidden?: string[];
51
+ /** Корень, заданный хостом. */
52
+ configured?: string;
53
+ platform?: NodeJS.Platform;
54
+ env?: NodeJS.ProcessEnv;
55
+ home?: string;
56
+ /** Номер тома пути (`stat.dev`); тест подменяет его. */
57
+ device?: (path: string) => number | undefined;
58
+ /**
59
+ * Создать каталоги кэша (0700). Без записи (`false`, диагностика) —
60
+ * только проверка существующих.
61
+ */
62
+ create?: boolean;
63
+ /** Владелец каталогов кэша; по умолчанию — текущий пользователь. */
64
+ uid?: number;
65
+ }
66
+ /** Настоящий путь и для ещё не созданного каталога: от ближайшего существующего предка. */
67
+ export declare function realish(path: string): string;
68
+ /** Каталог кэша пользователя для рабочих деревьев (без хэша). */
69
+ export declare function checkoutCacheBase(platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv, home?: string): string;
70
+ /** Устойчивый хэш каталога состояния: тот же путь — тот же корень. */
71
+ export declare const stateHash: (stateDir: string) => string;
72
+ export declare function chooseCheckoutRoot(input: CheckoutRootInput): CheckoutRoot;
73
+ /**
74
+ * Каталог рабочего дерева вида `kind` (`worktrees`, `dependencies`,
75
+ * `gates-at`…). Корень вне дерева: `<root>/<repositoryId>/<kind>/…`; иначе —
76
+ * прежний путь `legacy`.
77
+ */
78
+ export declare function checkoutPath(choice: CheckoutRoot, legacy: string, repositoryId: string, kind: string, ...rest: string[]): string;