devcontour-harness 0.1.0-alpha.26 → 0.1.0-alpha.28
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.
- package/README.md +15 -2
- package/docs/architecture.md +59 -0
- package/docs/compatibility.md +25 -12
- package/docs/connectors.md +5 -2
- package/docs/contracts.md +80 -25
- package/docs/release-notes/0.1.0-alpha.27.md +36 -0
- package/docs/release-notes/0.1.0-alpha.28.md +37 -0
- package/docs/review-protocol.md +10 -4
- package/docs/toolchains.md +83 -0
- package/docs/upgrade.md +22 -0
- package/lib/cli.js +13 -0
- package/lib/contracts/cli.d.ts +147 -19
- package/lib/contracts/cli.js +66 -0
- package/lib/contracts/diagnosis.d.ts +1 -1
- package/lib/contracts/events.d.ts +6 -6
- package/lib/contracts/execution.d.ts +268 -16
- package/lib/contracts/execution.js +3 -1
- package/lib/contracts/policy.d.ts +37 -5
- package/lib/contracts/policy.js +42 -2
- package/lib/contracts/profiles.d.ts +2 -0
- package/lib/contracts/published.d.ts +226 -20
- package/lib/contracts/result.d.ts +268 -12
- package/lib/contracts/result.js +66 -0
- package/lib/control/harness.d.ts +64 -7
- package/lib/control/harness.js +4 -0
- package/lib/control/recovery.d.ts +1 -1
- package/lib/control/review.js +6 -1
- package/lib/engine/engine.d.ts +117 -12
- package/lib/engine/joint-runner.d.ts +96 -6
- package/lib/engine/joint-runner.js +47 -1
- package/lib/engine/runner.d.ts +29 -0
- package/lib/engine/runner.js +200 -2
- package/lib/engine/worktree-cleanup.d.ts +131 -0
- package/lib/engine/worktree-cleanup.js +520 -0
- package/lib/environment/isolation.d.ts +1 -0
- package/lib/environment/isolation.js +2 -1
- package/lib/environment/os-tools.d.ts +4 -2
- package/lib/environment/os-tools.js +4 -2
- package/lib/environment/process.d.ts +5 -0
- package/lib/environment/process.js +40 -17
- package/lib/environment/resources.d.ts +9 -0
- package/lib/environment/resources.js +24 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/integrations/connector/commands.d.ts +2 -1
- package/lib/integrations/connector/commands.js +10 -2
- package/lib/integrations/connector/store.d.ts +1 -1
- package/lib/integrations/connector/store.js +11 -6
- package/lib/profiles/resolve.d.ts +8 -0
- package/lib/storage/document.d.ts +132 -12
- package/lib/toolchains/inspect.d.ts +1 -1
- package/lib/toolchains/inspect.js +29 -1
- package/lib/toolchains/probe.d.ts +16 -0
- package/lib/toolchains/probe.js +20 -0
- package/lib/verification/confirm.d.ts +3 -1
- package/lib/verification/confirm.js +16 -2
- package/lib/verification/dependencies.d.ts +3 -0
- package/lib/verification/dependencies.js +11 -0
- package/lib/verification/dependency-store.d.ts +117 -0
- package/lib/verification/dependency-store.js +811 -0
- package/lib/verification/gate-artifacts.d.ts +34 -0
- package/lib/verification/gate-artifacts.js +303 -0
- package/lib/verification/gates-at.js +18 -0
- package/lib/verification/gates.js +15 -0
- package/lib/verification/joint.d.ts +48 -3
- package/package.json +1 -1
- package/schemas/execution-document.schema.json +372 -0
- package/schemas/execution-policy.schema.json +56 -0
- package/schemas/joint-verification.schema.json +279 -0
package/lib/engine/runner.js
CHANGED
|
@@ -2,11 +2,14 @@ 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';
|
|
5
|
+
import { basename, 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, 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";
|
|
@@ -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(() =>
|
|
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))
|
|
@@ -1955,6 +2149,9 @@ export class Runner {
|
|
|
1955
2149
|
}
|
|
1956
2150
|
: {}),
|
|
1957
2151
|
...(this.options.environment ? { environment: this.options.environment } : {}),
|
|
2152
|
+
...(this.options.resourceDatabase
|
|
2153
|
+
? { resourceDatabase: this.options.resourceDatabase }
|
|
2154
|
+
: {}),
|
|
1958
2155
|
}, raw);
|
|
1959
2156
|
}
|
|
1960
2157
|
/**
|
|
@@ -2025,6 +2222,7 @@ export class Runner {
|
|
|
2025
2222
|
const gates = ordered(repo.gates, attempt.requiredGates ?? repo.gates.map((g) => g.id));
|
|
2026
2223
|
const execution = this.environment(attempt, 'integration', cwd);
|
|
2027
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'));
|
|
2028
2226
|
await runSteps(repo.prepare, cwd, join(artifacts, 'integration', 'prepare'), execution, signal);
|
|
2029
2227
|
const budget = { recheck: true };
|
|
2030
2228
|
for (const gate of gates)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { type AttemptState, type WorkState } from '../contracts/index.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Рабочие деревья закончившихся попыток. Обычно попытка убирает их сама; после
|
|
4
|
+
* падения процесса, отказа удаления или под прежними версиями они остаются и
|
|
5
|
+
* занимают диск. Удаление необратимо, поэтому правило одно: в сомнении дерево
|
|
6
|
+
* остаётся, а отказ назван. Убирается только то, что восстановимо: вершина
|
|
7
|
+
* достижима из ref, неподтверждённые правки доказанно лежат в патче. Игнорируемые
|
|
8
|
+
* файлы патч не сохраняет — они перечисляются в отчёте.
|
|
9
|
+
*/
|
|
10
|
+
export type WorktreeRefusal = 'active' | 'recoverable' | 'cleanup-pending' | 'cleanup-unreadable' | 'unknown-attempt' | 'untrusted' | 'embedded-repository' | 'scan-limit' | 'scan-failed' | 'read-only-path' | 'undecodable-path' | 'worktree-locked' | 'clean-filter' | 'tree-changed' | 'ignore-rules-changed' | 'hidden-changes' | 'staged-ignored' | 'staged-differs' | 'unreachable-head' | 'patch-unusable' | 'removal-incomplete' | 'not-registered';
|
|
11
|
+
export interface WorktreeCleanupEntry {
|
|
12
|
+
path: string;
|
|
13
|
+
repositoryId: string;
|
|
14
|
+
attemptId?: string;
|
|
15
|
+
/**
|
|
16
|
+
* remove — будет удалено (dry run); removed — удалено; refused — дерево не
|
|
17
|
+
* тронуто. failed — отказ шага: при `removalStarted` git мог удалить часть
|
|
18
|
+
* файлов и регистрацию, истинное состояние — в `registered` и `treePresent`,
|
|
19
|
+
* а `patch` указывает на сохранённые правки.
|
|
20
|
+
*/
|
|
21
|
+
action: 'remove' | 'removed' | 'refused' | 'failed';
|
|
22
|
+
reason?: WorktreeRefusal;
|
|
23
|
+
error?: string;
|
|
24
|
+
head?: string;
|
|
25
|
+
sizeKb?: number;
|
|
26
|
+
/** Файлов с неподтверждёнными правками. */
|
|
27
|
+
uncommitted?: number;
|
|
28
|
+
/** Игнорируемое в дереве: в патч не входит и исчезает вместе с деревом. */
|
|
29
|
+
ignored?: {
|
|
30
|
+
count: number;
|
|
31
|
+
paths: string[];
|
|
32
|
+
};
|
|
33
|
+
/** Патч этих правок (не для dry run): `git apply --index` поверх `head`. */
|
|
34
|
+
patch?: string;
|
|
35
|
+
/** Запись об удалении: при `removal-incomplete` её снимают вручную. */
|
|
36
|
+
record?: string;
|
|
37
|
+
removalStarted?: boolean;
|
|
38
|
+
/** Отсутствует, только если git не смог ответить. */
|
|
39
|
+
registered?: boolean;
|
|
40
|
+
treePresent?: boolean;
|
|
41
|
+
}
|
|
42
|
+
/** Почему попытку нельзя лишить дерева: идёт, или её работа ещё может продолжиться. */
|
|
43
|
+
export declare function attemptRefusal(attempt: AttemptState, work: WorkState | undefined, latest: boolean, running: boolean): WorktreeRefusal | undefined;
|
|
44
|
+
/** Незавершённая очистка: дерево — вход `cleanup --run`, его нельзя убирать мимо teardown. */
|
|
45
|
+
export declare function cleanupUnfinished(artifacts: string, receipts: string[]): Promise<boolean>;
|
|
46
|
+
/** Зарегистрированные рабочие деревья репозитория: настоящий путь → заперто ли. */
|
|
47
|
+
export declare function registered(repoPath: string): Promise<Map<string, {
|
|
48
|
+
locked: boolean;
|
|
49
|
+
}>>;
|
|
50
|
+
/** Вершина самого дерева: список деревьев снят раньше, а работа в дереве могла идти. */
|
|
51
|
+
export declare const treeHead: (dir: string) => Promise<string | undefined>;
|
|
52
|
+
export interface TreeScan {
|
|
53
|
+
embedded?: string;
|
|
54
|
+
readOnly?: string;
|
|
55
|
+
undecodable?: string;
|
|
56
|
+
limited: boolean;
|
|
57
|
+
/** Пути `.gitignore` относительно дерева. */
|
|
58
|
+
ignoreFiles: string[];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Настоящее дерево вместе с игнорируемым: вложенный репозиторий (`.git` файлом
|
|
62
|
+
* или каталогом, либо голый) git-командам внешнего не виден, если каталог
|
|
63
|
+
* игнорируется. В `node_modules` тоже смотрим: зависимость из git-источника или
|
|
64
|
+
* правка на месте бывает единственной копией работы. Обход ограничен: дошедший
|
|
65
|
+
* до предела обход не доказал ничего. Символические ссылки не проходятся.
|
|
66
|
+
*/
|
|
67
|
+
export declare function scanTree(root: string, limit: number): Promise<TreeScan>;
|
|
68
|
+
/** Что мешает удалить дерево, и что в нём лежит. Ничего не пишет. */
|
|
69
|
+
export declare function inspectTree(dir: string, repoPath: string, head: string | undefined, limit: number): Promise<{
|
|
70
|
+
refusal?: WorktreeRefusal;
|
|
71
|
+
uncommitted?: number;
|
|
72
|
+
ignored?: WorktreeCleanupEntry['ignored'];
|
|
73
|
+
/** Статус, по которому принято решение: перед удалением он сверяется. */
|
|
74
|
+
status?: string;
|
|
75
|
+
}>;
|
|
76
|
+
/**
|
|
77
|
+
* Дерево то же, что при проверках: та же вершина, тот же статус, те же правки.
|
|
78
|
+
* Узкое окно до удаления остаётся: запись после этой сверки не будет замечена.
|
|
79
|
+
*/
|
|
80
|
+
export declare function treeUnchanged(dir: string, head: string, status: string, edits: string | undefined): Promise<boolean>;
|
|
81
|
+
/**
|
|
82
|
+
* Неподтверждённые правки дерева — патчем к закреплённой вершине `head`, той же,
|
|
83
|
+
* что в записи об удалении. Индекс попытки не
|
|
84
|
+
* меняется: всё идёт через временные индексы. Формат закреплён против настроек
|
|
85
|
+
* пользователя, а патч проверен до удаления: наложенный на HEAD, он обязан дать
|
|
86
|
+
* то же дерево, что и правки. Иначе отказ, и дерево остаётся.
|
|
87
|
+
*/
|
|
88
|
+
export declare function savePatch(dir: string, artifacts: string, name: string, head: string): Promise<{
|
|
89
|
+
refusal: "embedded-repository";
|
|
90
|
+
edits?: undefined;
|
|
91
|
+
patch?: undefined;
|
|
92
|
+
} | {
|
|
93
|
+
refusal: "patch-unusable";
|
|
94
|
+
edits?: undefined;
|
|
95
|
+
patch?: undefined;
|
|
96
|
+
} | {
|
|
97
|
+
edits: string;
|
|
98
|
+
patch: string;
|
|
99
|
+
refusal?: undefined;
|
|
100
|
+
}>;
|
|
101
|
+
/** Дерево на диске — именно зарегистрированное дерево этого репозитория. */
|
|
102
|
+
export declare function trusted(dir: string, repoPath: string): boolean;
|
|
103
|
+
export declare function sizeKb(dir: string): Promise<number>;
|
|
104
|
+
/** Убрать дерево с пределом для больших деревьев: `command` ждёт по умолчанию 120 с. */
|
|
105
|
+
export declare function removeTree(repoPath: string, path: string, timeoutMs: number): Promise<void>;
|
|
106
|
+
export declare const recordFile: (artifacts: string, path: string) => string;
|
|
107
|
+
export interface RemovalRecord extends WorktreeCleanupEntry {
|
|
108
|
+
status: 'removing' | 'removed' | 'incomplete';
|
|
109
|
+
at: string;
|
|
110
|
+
previous?: RemovalRecord;
|
|
111
|
+
}
|
|
112
|
+
/** Запись об удалении этого дерева; нечитаемая запись — как незавершённое удаление. */
|
|
113
|
+
export declare function readRemoval(artifacts: string, path: string): Promise<RemovalRecord | undefined>;
|
|
114
|
+
/**
|
|
115
|
+
* Запись рядом с артефактами попытки: с какой вершины убрано и где патч. Пишется
|
|
116
|
+
* и до удаления: прерванное удаление не теряет указатель на патч и видно
|
|
117
|
+
* следующему запуску. Замена атомарна.
|
|
118
|
+
*/
|
|
119
|
+
export declare function recordRemoval(artifacts: string, entry: WorktreeCleanupEntry, status: RemovalRecord['status'], previous?: RemovalRecord): Promise<void>;
|
|
120
|
+
/**
|
|
121
|
+
* Один запуск очистки на каталог состояния: два запуска делили бы патчи и записи.
|
|
122
|
+
* Замок сверяет PID, поэтому каталог состояния должен принадлежать одному
|
|
123
|
+
* пространству PID: контейнер со своим пространством увидел бы чужой замок умершим.
|
|
124
|
+
*/
|
|
125
|
+
export declare function lockCleanup(file: string): Promise<() => Promise<void>>;
|
|
126
|
+
/** Что осталось после отказа удаления; `registered` — только если git ответил. */
|
|
127
|
+
export declare function treeState(repoPath: string, path: string): Promise<{
|
|
128
|
+
treePresent: boolean;
|
|
129
|
+
registered?: boolean | undefined;
|
|
130
|
+
}>;
|
|
131
|
+
export declare const isWithin: (path: string, root: string) => boolean;
|