@agent-deck/backend 2.1.0 → 2.2.0
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/dist/.tsbuildinfo +1 -1
- package/dist/agent-run/adapter.d.ts +134 -0
- package/dist/agent-run/adapter.d.ts.map +1 -0
- package/dist/agent-run/adapter.js +70 -0
- package/dist/agent-run/adapter.js.map +1 -0
- package/dist/agent-run/claude-probe.d.ts +30 -0
- package/dist/agent-run/claude-probe.d.ts.map +1 -0
- package/dist/agent-run/claude-probe.js +85 -0
- package/dist/agent-run/claude-probe.js.map +1 -0
- package/dist/agent-run/claude.d.ts +49 -0
- package/dist/agent-run/claude.d.ts.map +1 -0
- package/dist/agent-run/claude.js +104 -0
- package/dist/agent-run/claude.js.map +1 -0
- package/dist/agent-run/codex.d.ts +86 -0
- package/dist/agent-run/codex.d.ts.map +1 -0
- package/dist/agent-run/codex.js +377 -0
- package/dist/agent-run/codex.js.map +1 -0
- package/dist/agent-run/cursor.d.ts +80 -0
- package/dist/agent-run/cursor.d.ts.map +1 -0
- package/dist/agent-run/cursor.js +462 -0
- package/dist/agent-run/cursor.js.map +1 -0
- package/dist/agent-run/index.d.ts +15 -0
- package/dist/agent-run/index.d.ts.map +1 -0
- package/dist/agent-run/index.js +31 -0
- package/dist/agent-run/index.js.map +1 -0
- package/dist/agent-run/muse.d.ts +134 -0
- package/dist/agent-run/muse.d.ts.map +1 -0
- package/dist/agent-run/muse.js +512 -0
- package/dist/agent-run/muse.js.map +1 -0
- package/dist/agent-run/provenance.d.ts +28 -0
- package/dist/agent-run/provenance.d.ts.map +1 -0
- package/dist/agent-run/provenance.js +118 -0
- package/dist/agent-run/provenance.js.map +1 -0
- package/dist/agent-run/records.d.ts +182 -0
- package/dist/agent-run/records.d.ts.map +1 -0
- package/dist/agent-run/records.js +359 -0
- package/dist/agent-run/records.js.map +1 -0
- package/dist/agent-run/service.d.ts +206 -0
- package/dist/agent-run/service.d.ts.map +1 -0
- package/dist/agent-run/service.js +503 -0
- package/dist/agent-run/service.js.map +1 -0
- package/dist/agent-run-api/auth.d.ts +22 -0
- package/dist/agent-run-api/auth.d.ts.map +1 -0
- package/dist/agent-run-api/auth.js +54 -0
- package/dist/agent-run-api/auth.js.map +1 -0
- package/dist/agent-run-api/finalization-store.d.ts +62 -0
- package/dist/agent-run-api/finalization-store.d.ts.map +1 -0
- package/dist/agent-run-api/finalization-store.js +126 -0
- package/dist/agent-run-api/finalization-store.js.map +1 -0
- package/dist/agent-run-api/git-finalize.d.ts +98 -0
- package/dist/agent-run-api/git-finalize.d.ts.map +1 -0
- package/dist/agent-run-api/git-finalize.js +639 -0
- package/dist/agent-run-api/git-finalize.js.map +1 -0
- package/dist/agent-run-api/host.d.ts +10 -0
- package/dist/agent-run-api/host.d.ts.map +1 -0
- package/dist/agent-run-api/host.js +27 -0
- package/dist/agent-run-api/host.js.map +1 -0
- package/dist/agent-run-api/run-index.d.ts +40 -0
- package/dist/agent-run-api/run-index.d.ts.map +1 -0
- package/dist/agent-run-api/run-index.js +69 -0
- package/dist/agent-run-api/run-index.js.map +1 -0
- package/dist/audit/store.d.ts +22 -3
- package/dist/audit/store.d.ts.map +1 -1
- package/dist/audit/store.js +67 -6
- package/dist/audit/store.js.map +1 -1
- package/dist/auth/client-grants.d.ts +28 -3
- package/dist/auth/client-grants.d.ts.map +1 -1
- package/dist/auth/client-grants.js +40 -10
- package/dist/auth/client-grants.js.map +1 -1
- package/dist/auth/hosted-mode.d.ts +2 -0
- package/dist/auth/hosted-mode.d.ts.map +1 -1
- package/dist/auth/hosted-mode.js +27 -1
- package/dist/auth/hosted-mode.js.map +1 -1
- package/dist/routes/agent-grants.d.ts.map +1 -1
- package/dist/routes/agent-grants.js +63 -1
- package/dist/routes/agent-grants.js.map +1 -1
- package/dist/routes/agent-runs.d.ts +40 -0
- package/dist/routes/agent-runs.d.ts.map +1 -0
- package/dist/routes/agent-runs.js +755 -0
- package/dist/routes/agent-runs.js.map +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +6 -0
- package/dist/server/index.js.map +1 -1
- package/dist/trusted-session/auth.d.ts +12 -1
- package/dist/trusted-session/auth.d.ts.map +1 -1
- package/dist/trusted-session/auth.js +1 -0
- package/dist/trusted-session/auth.js.map +1 -1
- package/dist/trusted-session/policy-hook.d.ts.map +1 -1
- package/dist/trusted-session/policy-hook.js +25 -9
- package/dist/trusted-session/policy-hook.js.map +1 -1
- package/dist/trusted-session/route-policy-registry.d.ts.map +1 -1
- package/dist/trusted-session/route-policy-registry.js +11 -0
- package/dist/trusted-session/route-policy-registry.js.map +1 -1
- package/package.json +13 -2
- package/static-ui/assets/{index-ynIby2JK.js → index-eHjUHhT-.js} +58 -58
- package/static-ui/index.html +1 -1
|
@@ -0,0 +1,639 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.defaultGitRunner = exports.FinalizationError = void 0;
|
|
7
|
+
exports.sha256Hex = sha256Hex;
|
|
8
|
+
exports.manifestDigestOf = manifestDigestOf;
|
|
9
|
+
exports.repositoryIdOf = repositoryIdOf;
|
|
10
|
+
exports.isValidManifestPath = isValidManifestPath;
|
|
11
|
+
exports.createGitFinalizer = createGitFinalizer;
|
|
12
|
+
const node_child_process_1 = require("node:child_process");
|
|
13
|
+
const node_crypto_1 = require("node:crypto");
|
|
14
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
15
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
16
|
+
/**
|
|
17
|
+
* NOT-486: the Git mechanism behind run finalization.
|
|
18
|
+
*
|
|
19
|
+
* Policy (who may finalize which run, idempotency, audit) lives in the route;
|
|
20
|
+
* this module only proves a reviewed manifest against the repository and
|
|
21
|
+
* turns it into one local commit. It runs a fixed set of plumbing commands —
|
|
22
|
+
* never a caller-supplied argument list — with repository hooks and fsmonitor
|
|
23
|
+
* disabled, and it never checks out, resets, cleans, pushes, or deletes a
|
|
24
|
+
* working-tree file.
|
|
25
|
+
*
|
|
26
|
+
* Staging happens in a private index file. The real index is locked
|
|
27
|
+
* (`index.lock`, Git's own protocol) for the whole operation and replaced
|
|
28
|
+
* only after the ref moved, so a failure or cancellation before the commit
|
|
29
|
+
* leaves the real index, the ref, and every working-tree file untouched.
|
|
30
|
+
*/
|
|
31
|
+
/** Paths Agent Deck owns in a workspace (the folder binding); never candidates, never committable. */
|
|
32
|
+
const RESERVED_PREFIX = '.agent-deck/';
|
|
33
|
+
/** A stable failure; `message` never carries a host path or file content. */
|
|
34
|
+
class FinalizationError extends Error {
|
|
35
|
+
code;
|
|
36
|
+
constructor(code, message) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.code = code;
|
|
39
|
+
this.name = 'FinalizationError';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
exports.FinalizationError = FinalizationError;
|
|
43
|
+
/** Inherited variables that would redirect Git away from the captured workspace. */
|
|
44
|
+
const BLOCKED_GIT_ENV = [
|
|
45
|
+
'GIT_DIR',
|
|
46
|
+
'GIT_WORK_TREE',
|
|
47
|
+
'GIT_INDEX_FILE',
|
|
48
|
+
'GIT_OBJECT_DIRECTORY',
|
|
49
|
+
'GIT_ALTERNATE_OBJECT_DIRECTORIES',
|
|
50
|
+
'GIT_COMMON_DIR',
|
|
51
|
+
'GIT_NAMESPACE',
|
|
52
|
+
'GIT_PREFIX',
|
|
53
|
+
'GIT_EXEC_PATH',
|
|
54
|
+
];
|
|
55
|
+
const defaultGitRunner = (args, options) => new Promise((resolve) => {
|
|
56
|
+
const env = {};
|
|
57
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
58
|
+
if (value !== undefined && !BLOCKED_GIT_ENV.includes(key)) {
|
|
59
|
+
env[key] = value;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const child = (0, node_child_process_1.spawn)('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-c', 'core.quotePath=false', ...args], {
|
|
63
|
+
cwd: options.cwd,
|
|
64
|
+
env: { ...env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0', ...options.env },
|
|
65
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
66
|
+
});
|
|
67
|
+
const out = [];
|
|
68
|
+
let stderr = '';
|
|
69
|
+
child.stdout.on('data', (chunk) => out.push(chunk));
|
|
70
|
+
child.stderr.on('data', (chunk) => {
|
|
71
|
+
stderr += chunk.toString('utf8');
|
|
72
|
+
});
|
|
73
|
+
child.on('error', (error) => resolve({ code: -1, stdout: Buffer.alloc(0), stderr: String(error) }));
|
|
74
|
+
child.on('close', (code) => resolve({ code: code ?? -1, stdout: Buffer.concat(out), stderr }));
|
|
75
|
+
child.stdin.on('error', () => { });
|
|
76
|
+
child.stdin.end(options.input ?? '');
|
|
77
|
+
});
|
|
78
|
+
exports.defaultGitRunner = defaultGitRunner;
|
|
79
|
+
function sha256Hex(data) {
|
|
80
|
+
return (0, node_crypto_1.createHash)('sha256').update(data).digest('hex');
|
|
81
|
+
}
|
|
82
|
+
function byPath(a, b) {
|
|
83
|
+
return a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
|
|
84
|
+
}
|
|
85
|
+
/** Order-independent digest of a manifest (sorted by path). */
|
|
86
|
+
function manifestDigestOf(files) {
|
|
87
|
+
const sorted = [...files].sort(byPath).map((file) => [file.path, file.sha256, file.mode]);
|
|
88
|
+
return sha256Hex(JSON.stringify(sorted));
|
|
89
|
+
}
|
|
90
|
+
function baselineDigestOf(baseline) {
|
|
91
|
+
return sha256Hex(JSON.stringify({
|
|
92
|
+
version: baseline.version,
|
|
93
|
+
headRef: baseline.headRef,
|
|
94
|
+
baseCommit: baseline.baseCommit,
|
|
95
|
+
dirty: baseline.dirty.map((entry) => [entry.path, entry.state]),
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
/** Opaque repository identity for audit: never the host path itself. */
|
|
99
|
+
function repositoryIdOf(baseline) {
|
|
100
|
+
return `repo_${sha256Hex(`agent-deck-repository\u0000${baseline.commonDir}`).slice(0, 24)}`;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Repository-relative POSIX path that names a regular location inside the
|
|
104
|
+
* worktree: not absolute, no `.`/`..`/empty segment, no `.git` segment, no
|
|
105
|
+
* backslash or control character, outside Agent Deck's reserved folder.
|
|
106
|
+
*/
|
|
107
|
+
function isValidManifestPath(value) {
|
|
108
|
+
if (!value || value.startsWith('/') || /^[A-Za-z]:/.test(value)) {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
if (/[\u0000-\u001f\u007f\\]/.test(value)) {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
if (value === '.agent-deck' || value.startsWith(RESERVED_PREFIX)) {
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
return value
|
|
118
|
+
.split('/')
|
|
119
|
+
.every((segment) => segment !== '' && segment !== '.' && segment !== '..' && segment.toLowerCase() !== '.git');
|
|
120
|
+
}
|
|
121
|
+
function encodeState(state) {
|
|
122
|
+
switch (state.kind) {
|
|
123
|
+
case 'file':
|
|
124
|
+
return `file:${state.mode}:${state.sha256}`;
|
|
125
|
+
case 'symlink':
|
|
126
|
+
return `symlink:${state.sha256}`;
|
|
127
|
+
default:
|
|
128
|
+
return state.kind;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* True when some parent segment of `rel` is a symlink, or is not a directory.
|
|
133
|
+
* Reading through such a path could leave the worktree.
|
|
134
|
+
*/
|
|
135
|
+
function hasUnsafeParent(root, rel) {
|
|
136
|
+
const segments = rel.split('/');
|
|
137
|
+
let current = root;
|
|
138
|
+
for (const segment of segments.slice(0, -1)) {
|
|
139
|
+
current = node_path_1.default.join(current, segment);
|
|
140
|
+
let stat;
|
|
141
|
+
try {
|
|
142
|
+
stat = node_fs_1.default.lstatSync(current);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return false; // A missing parent: the path itself is absent.
|
|
146
|
+
}
|
|
147
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
if (node_fs_1.default.existsSync(node_path_1.default.join(current, '.git'))) {
|
|
151
|
+
return true; // Inside a nested repository or submodule checkout.
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
function readState(root, rel) {
|
|
157
|
+
if (hasUnsafeParent(root, rel)) {
|
|
158
|
+
return { kind: 'other' };
|
|
159
|
+
}
|
|
160
|
+
const full = node_path_1.default.join(root, rel);
|
|
161
|
+
let stat;
|
|
162
|
+
try {
|
|
163
|
+
stat = node_fs_1.default.lstatSync(full);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return { kind: 'absent' };
|
|
167
|
+
}
|
|
168
|
+
if (stat.isSymbolicLink()) {
|
|
169
|
+
return { kind: 'symlink', sha256: sha256Hex(node_fs_1.default.readlinkSync(full)) };
|
|
170
|
+
}
|
|
171
|
+
if (stat.isDirectory()) {
|
|
172
|
+
return { kind: 'directory' };
|
|
173
|
+
}
|
|
174
|
+
if (!stat.isFile()) {
|
|
175
|
+
return { kind: 'other' };
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
kind: 'file',
|
|
179
|
+
mode: (stat.mode & 0o111) !== 0 ? '100755' : '100644',
|
|
180
|
+
sha256: sha256Hex(node_fs_1.default.readFileSync(full)),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
function decodePath(raw) {
|
|
184
|
+
const text = raw.toString('utf8');
|
|
185
|
+
return Buffer.from(text, 'utf8').equals(raw) ? text : null;
|
|
186
|
+
}
|
|
187
|
+
function splitNul(buffer) {
|
|
188
|
+
const parts = [];
|
|
189
|
+
let start = 0;
|
|
190
|
+
for (let i = 0; i < buffer.length; i += 1) {
|
|
191
|
+
if (buffer[i] === 0) {
|
|
192
|
+
parts.push(buffer.subarray(start, i));
|
|
193
|
+
start = i + 1;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (start < buffer.length) {
|
|
197
|
+
parts.push(buffer.subarray(start));
|
|
198
|
+
}
|
|
199
|
+
return parts;
|
|
200
|
+
}
|
|
201
|
+
function createGitFinalizer(deps = {}) {
|
|
202
|
+
const runGit = deps.runGit ?? exports.defaultGitRunner;
|
|
203
|
+
/** Serialization per repository + ref inside this process; a busy key fails closed. */
|
|
204
|
+
const busy = new Set();
|
|
205
|
+
const git = async (cwd, args, options = {}) => {
|
|
206
|
+
const result = await runGit(args, {
|
|
207
|
+
cwd,
|
|
208
|
+
...(options.indexFile ? { env: { GIT_INDEX_FILE: options.indexFile } } : {}),
|
|
209
|
+
...(options.input !== undefined ? { input: options.input } : {}),
|
|
210
|
+
});
|
|
211
|
+
if (result.code !== 0 && !(options.allow ?? []).includes(result.code)) {
|
|
212
|
+
throw new FinalizationError('finalization_failed', `git ${args[0]} failed`);
|
|
213
|
+
}
|
|
214
|
+
return result;
|
|
215
|
+
};
|
|
216
|
+
const text = (result) => result.stdout.toString('utf8').trim();
|
|
217
|
+
const locate = async (cwd) => {
|
|
218
|
+
const result = await runGit(['rev-parse', '--path-format=absolute', '--show-toplevel', '--absolute-git-dir', '--git-common-dir', '--git-path', 'index'], { cwd });
|
|
219
|
+
const lines = result.stdout.toString('utf8').split('\n').filter(Boolean);
|
|
220
|
+
if (result.code !== 0 || lines.length !== 4) {
|
|
221
|
+
throw new FinalizationError('finalization_invalid', 'cwd is not inside a Git worktree');
|
|
222
|
+
}
|
|
223
|
+
const real = (value) => {
|
|
224
|
+
try {
|
|
225
|
+
return node_fs_1.default.realpathSync(value);
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return value;
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
return {
|
|
232
|
+
repoRoot: real(lines[0]),
|
|
233
|
+
gitDir: real(lines[1]),
|
|
234
|
+
commonDir: real(lines[2]),
|
|
235
|
+
indexPath: node_path_1.default.join(real(node_path_1.default.dirname(lines[3])), node_path_1.default.basename(lines[3])),
|
|
236
|
+
};
|
|
237
|
+
};
|
|
238
|
+
const readHead = async (root) => {
|
|
239
|
+
const symbolic = await git(root, ['symbolic-ref', '-q', 'HEAD'], { allow: [1] });
|
|
240
|
+
const headRef = symbolic.code === 0 ? text(symbolic) : 'HEAD';
|
|
241
|
+
const commit = await git(root, ['rev-parse', '--verify', '-q', 'HEAD^{commit}'], { allow: [1, 128] });
|
|
242
|
+
return { headRef, commit: commit.code === 0 ? text(commit) : null };
|
|
243
|
+
};
|
|
244
|
+
const indexIsClean = async (root, indexFile) => {
|
|
245
|
+
const diff = await git(root, ['diff-index', '--cached', '--quiet', 'HEAD', '--'], {
|
|
246
|
+
allow: [1],
|
|
247
|
+
...(indexFile ? { indexFile } : {}),
|
|
248
|
+
});
|
|
249
|
+
if (diff.code !== 0) {
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
const unmerged = await git(root, ['ls-files', '-u', '-z'], indexFile ? { indexFile } : {});
|
|
253
|
+
return unmerged.stdout.length === 0;
|
|
254
|
+
};
|
|
255
|
+
/** Dirty paths (tracked changes and untracked files), excluding Agent Deck's reserved folder. */
|
|
256
|
+
const dirtyPaths = async (root, indexFile) => {
|
|
257
|
+
const status = await git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames', '--ignore-submodules=none'], indexFile ? { indexFile } : {});
|
|
258
|
+
const paths = [];
|
|
259
|
+
for (const record of splitNul(status.stdout)) {
|
|
260
|
+
if (record.length < 4) {
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const decoded = decodePath(record.subarray(3));
|
|
264
|
+
if (decoded === null) {
|
|
265
|
+
throw new FinalizationError('path_invalid', 'A changed path is not valid UTF-8');
|
|
266
|
+
}
|
|
267
|
+
const rel = decoded.endsWith('/') ? decoded.slice(0, -1) : decoded;
|
|
268
|
+
if (rel === '.agent-deck' || rel.startsWith(RESERVED_PREFIX)) {
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
paths.push(decoded);
|
|
272
|
+
}
|
|
273
|
+
return [...new Set(paths)].sort();
|
|
274
|
+
};
|
|
275
|
+
/** Paths that are, or sit inside, a submodule (gitlink) in `commit`. */
|
|
276
|
+
const gitlinksAmong = async (root, commit, paths) => {
|
|
277
|
+
if (paths.length === 0) {
|
|
278
|
+
return new Set();
|
|
279
|
+
}
|
|
280
|
+
const names = new Set();
|
|
281
|
+
for (const p of paths) {
|
|
282
|
+
const segments = p.split('/');
|
|
283
|
+
for (let i = 1; i <= segments.length; i += 1) {
|
|
284
|
+
names.add(segments.slice(0, i).join('/'));
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
// Non-recursive: each named entry itself (a directory shows as one tree entry).
|
|
288
|
+
const listed = await git(root, ['ls-tree', '-z', commit, '--', ...names]);
|
|
289
|
+
const links = new Set();
|
|
290
|
+
for (const record of splitNul(listed.stdout)) {
|
|
291
|
+
const line = record.toString('utf8');
|
|
292
|
+
const tab = line.indexOf('\t');
|
|
293
|
+
if (tab > 0 && line.startsWith('160000 ') && names.has(line.slice(tab + 1))) {
|
|
294
|
+
links.add(line.slice(tab + 1));
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
const hits = new Set();
|
|
298
|
+
for (const p of paths) {
|
|
299
|
+
for (const link of links) {
|
|
300
|
+
if (p === link || p.startsWith(`${link}/`)) {
|
|
301
|
+
hits.add(p);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return hits;
|
|
306
|
+
};
|
|
307
|
+
const assertWorkspace = async (baseline) => {
|
|
308
|
+
let located;
|
|
309
|
+
try {
|
|
310
|
+
located = await locate(baseline.repoRoot);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
throw new FinalizationError('finalization_invalid', 'The run workspace is no longer a Git worktree');
|
|
314
|
+
}
|
|
315
|
+
if (located.repoRoot !== baseline.repoRoot || located.gitDir !== baseline.gitDir) {
|
|
316
|
+
throw new FinalizationError('finalization_invalid', 'The run workspace no longer matches its baseline');
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
const assertHead = async (baseline) => {
|
|
320
|
+
const head = await readHead(baseline.repoRoot);
|
|
321
|
+
if (head.headRef !== baseline.headRef || head.commit !== baseline.baseCommit) {
|
|
322
|
+
throw new FinalizationError('base_mismatch', 'HEAD no longer matches the run baseline commit');
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
const candidate = async (baseline, indexFile) => {
|
|
326
|
+
await assertWorkspace(baseline);
|
|
327
|
+
await assertHead(baseline);
|
|
328
|
+
if (!(await indexIsClean(baseline.repoRoot, indexFile))) {
|
|
329
|
+
throw new FinalizationError('index_dirty', 'The Git index has staged or unmerged changes');
|
|
330
|
+
}
|
|
331
|
+
const root = baseline.repoRoot;
|
|
332
|
+
const current = await dirtyPaths(root, indexFile);
|
|
333
|
+
const recorded = new Map(baseline.dirty.map((entry) => [entry.path, entry.state]));
|
|
334
|
+
for (const [rel, state] of recorded) {
|
|
335
|
+
if (encodeState(readState(root, rel)) !== state) {
|
|
336
|
+
throw new FinalizationError('baseline_mismatch', 'A path that was dirty before the run has changed');
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
const produced = current.filter((rel) => !recorded.has(rel));
|
|
340
|
+
const links = await gitlinksAmong(root, baseline.baseCommit, produced.map((rel) => rel.replace(/\/$/, '')));
|
|
341
|
+
const files = [];
|
|
342
|
+
for (const raw of produced) {
|
|
343
|
+
const rel = raw.replace(/\/$/, '');
|
|
344
|
+
if (raw.endsWith('/') || !isValidManifestPath(rel) || links.has(rel)) {
|
|
345
|
+
throw new FinalizationError('path_invalid', 'The run changed a submodule, nested repository, or invalid path');
|
|
346
|
+
}
|
|
347
|
+
const state = readState(root, rel);
|
|
348
|
+
if (state.kind === 'file') {
|
|
349
|
+
files.push({ path: rel, sha256: state.sha256, mode: state.mode });
|
|
350
|
+
}
|
|
351
|
+
else if (state.kind === 'absent') {
|
|
352
|
+
files.push({ path: rel, sha256: null, mode: null });
|
|
353
|
+
}
|
|
354
|
+
else {
|
|
355
|
+
throw new FinalizationError('path_invalid', 'The run produced a symlink or non-regular path');
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
files.sort(byPath);
|
|
359
|
+
return { baseCommit: baseline.baseCommit, files, manifestDigest: manifestDigestOf(files) };
|
|
360
|
+
};
|
|
361
|
+
const recover = async (baseline, runId, pending) => {
|
|
362
|
+
try {
|
|
363
|
+
for (const name of node_fs_1.default.readdirSync(baseline.gitDir)) {
|
|
364
|
+
if (name.startsWith(`agent-deck-finalize-${runId}-`)) {
|
|
365
|
+
node_fs_1.default.rmSync(node_path_1.default.join(baseline.gitDir, name), { force: true });
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
// Workspace gone: nothing of ours remains to remove.
|
|
371
|
+
}
|
|
372
|
+
const lockPath = `${baseline.indexPath}.lock`;
|
|
373
|
+
if (pending.lockIno !== null) {
|
|
374
|
+
try {
|
|
375
|
+
if (node_fs_1.default.lstatSync(lockPath).ino === pending.lockIno) {
|
|
376
|
+
node_fs_1.default.rmSync(lockPath, { force: true });
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
catch {
|
|
380
|
+
// No lock left behind.
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (!pending.commit) {
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
const ref = await runGit(['rev-parse', '--verify', '-q', baseline.headRef], { cwd: baseline.repoRoot });
|
|
387
|
+
return ref.code === 0 && ref.stdout.toString('utf8').trim() === pending.commit;
|
|
388
|
+
};
|
|
389
|
+
return {
|
|
390
|
+
async captureBaseline(cwd) {
|
|
391
|
+
const located = await locate(cwd);
|
|
392
|
+
const head = await readHead(located.repoRoot);
|
|
393
|
+
if (!head.commit) {
|
|
394
|
+
throw new FinalizationError('finalization_invalid', 'The Git worktree has no commit at HEAD');
|
|
395
|
+
}
|
|
396
|
+
if (head.headRef !== 'HEAD' && !head.headRef.startsWith('refs/heads/')) {
|
|
397
|
+
throw new FinalizationError('finalization_invalid', 'HEAD must be a local branch or detached');
|
|
398
|
+
}
|
|
399
|
+
if (!(await indexIsClean(located.repoRoot))) {
|
|
400
|
+
throw new FinalizationError('index_dirty', 'The Git index has staged or unmerged changes');
|
|
401
|
+
}
|
|
402
|
+
const dirty = (await dirtyPaths(located.repoRoot)).map((raw) => {
|
|
403
|
+
const rel = raw.replace(/\/$/, '');
|
|
404
|
+
return { path: rel, state: encodeState(readState(located.repoRoot, rel)) };
|
|
405
|
+
});
|
|
406
|
+
const unsigned = {
|
|
407
|
+
version: 1,
|
|
408
|
+
...located,
|
|
409
|
+
headRef: head.headRef,
|
|
410
|
+
baseCommit: head.commit,
|
|
411
|
+
dirty,
|
|
412
|
+
};
|
|
413
|
+
return { ...unsigned, digest: baselineDigestOf(unsigned) };
|
|
414
|
+
},
|
|
415
|
+
candidate: (baseline) => candidate(baseline),
|
|
416
|
+
async finalize(baseline, input, options = {}) {
|
|
417
|
+
const root = baseline.repoRoot;
|
|
418
|
+
const checkpoint = async (stage) => {
|
|
419
|
+
if (stage === 'ref-updated') {
|
|
420
|
+
// History already moved: nothing after this point may report failure.
|
|
421
|
+
await Promise.resolve(deps.pause?.(stage, input.runId)).catch(() => { });
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
await deps.pause?.(stage, input.runId);
|
|
425
|
+
if (options.signal?.aborted) {
|
|
426
|
+
throw new FinalizationError('finalization_canceled', 'Finalization was canceled before the commit');
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
// Syntactic and baseline gates: nothing touched yet.
|
|
430
|
+
const seen = new Set();
|
|
431
|
+
for (const file of input.files) {
|
|
432
|
+
if (!isValidManifestPath(file.path) || seen.has(file.path)) {
|
|
433
|
+
throw new FinalizationError('path_invalid', 'The manifest has an invalid or duplicate path');
|
|
434
|
+
}
|
|
435
|
+
seen.add(file.path);
|
|
436
|
+
}
|
|
437
|
+
if (input.baselineDigest !== baseline.digest) {
|
|
438
|
+
throw new FinalizationError('baseline_mismatch', 'baselineDigest does not match the run baseline');
|
|
439
|
+
}
|
|
440
|
+
if (input.expectedBaseCommit !== baseline.baseCommit) {
|
|
441
|
+
throw new FinalizationError('base_mismatch', 'expectedBaseCommit does not match the run baseline commit');
|
|
442
|
+
}
|
|
443
|
+
const key = `${baseline.commonDir}\u0000${baseline.headRef}`;
|
|
444
|
+
if (busy.has(key)) {
|
|
445
|
+
throw new FinalizationError('git_lock_conflict', 'Another finalization holds this repository ref');
|
|
446
|
+
}
|
|
447
|
+
busy.add(key);
|
|
448
|
+
const lockPath = `${baseline.indexPath}.lock`;
|
|
449
|
+
const privateIndex = node_path_1.default.join(baseline.gitDir, `agent-deck-finalize-${input.runId}-${(0, node_crypto_1.randomBytes)(4).toString('hex')}.index`);
|
|
450
|
+
let lockFd = null;
|
|
451
|
+
let committed = false;
|
|
452
|
+
try {
|
|
453
|
+
const refLock = baseline.headRef === 'HEAD'
|
|
454
|
+
? node_path_1.default.join(baseline.gitDir, 'HEAD.lock')
|
|
455
|
+
: node_path_1.default.join(baseline.commonDir, `${baseline.headRef}.lock`);
|
|
456
|
+
if (node_fs_1.default.existsSync(refLock)) {
|
|
457
|
+
throw new FinalizationError('git_lock_conflict', 'The branch ref is locked by another Git process');
|
|
458
|
+
}
|
|
459
|
+
try {
|
|
460
|
+
lockFd = node_fs_1.default.openSync(lockPath, 'wx');
|
|
461
|
+
}
|
|
462
|
+
catch (error) {
|
|
463
|
+
if (error.code === 'EEXIST') {
|
|
464
|
+
throw new FinalizationError('git_lock_conflict', 'The Git index is locked by another Git process');
|
|
465
|
+
}
|
|
466
|
+
throw new FinalizationError('finalization_failed', 'Could not lock the Git index');
|
|
467
|
+
}
|
|
468
|
+
options.onLocked?.(node_fs_1.default.fstatSync(lockFd).ino);
|
|
469
|
+
if (node_fs_1.default.existsSync(baseline.indexPath)) {
|
|
470
|
+
node_fs_1.default.copyFileSync(baseline.indexPath, privateIndex);
|
|
471
|
+
}
|
|
472
|
+
else {
|
|
473
|
+
await git(root, ['read-tree', baseline.baseCommit], { indexFile: privateIndex });
|
|
474
|
+
}
|
|
475
|
+
await checkpoint('locked');
|
|
476
|
+
// Workspace, HEAD, index, baseline, then the exact manifest.
|
|
477
|
+
for (const file of input.files) {
|
|
478
|
+
if (hasUnsafeParent(root, file.path)) {
|
|
479
|
+
throw new FinalizationError('path_invalid', 'A manifest path crosses a symlink or nested repository');
|
|
480
|
+
}
|
|
481
|
+
const state = readState(root, file.path);
|
|
482
|
+
if (state.kind === 'symlink' || state.kind === 'directory' || state.kind === 'other') {
|
|
483
|
+
throw new FinalizationError('path_invalid', 'A manifest path is a symlink, directory, or special file');
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if ((await gitlinksAmong(root, baseline.baseCommit, input.files.map((file) => file.path))).size > 0) {
|
|
487
|
+
throw new FinalizationError('path_invalid', 'A manifest path is a submodule');
|
|
488
|
+
}
|
|
489
|
+
const snapshot = await candidate(baseline, privateIndex);
|
|
490
|
+
const expected = new Map(snapshot.files.map((file) => [file.path, file]));
|
|
491
|
+
for (const file of input.files) {
|
|
492
|
+
if (!expected.has(file.path)) {
|
|
493
|
+
throw new FinalizationError('path_unexpected', 'The manifest names a path the run did not change');
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
for (const file of snapshot.files) {
|
|
497
|
+
if (!seen.has(file.path)) {
|
|
498
|
+
throw new FinalizationError('path_unexpected', 'The run changed a path that is absent from the manifest');
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
for (const file of input.files) {
|
|
502
|
+
const current = expected.get(file.path);
|
|
503
|
+
if (current.sha256 !== file.sha256 || current.mode !== file.mode) {
|
|
504
|
+
throw new FinalizationError('digest_mismatch', 'A manifest digest or mode differs from the working tree');
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
await checkpoint('validated');
|
|
508
|
+
// Stage exactly the manifest into the private index, from verified bytes.
|
|
509
|
+
const zero = '0'.repeat(baseline.baseCommit.length);
|
|
510
|
+
const blobs = new Map();
|
|
511
|
+
const lines = [];
|
|
512
|
+
for (const file of [...input.files].sort(byPath)) {
|
|
513
|
+
if (file.sha256 === null) {
|
|
514
|
+
if (readState(root, file.path).kind !== 'absent') {
|
|
515
|
+
throw new FinalizationError('digest_mismatch', 'A path the manifest deletes exists again');
|
|
516
|
+
}
|
|
517
|
+
lines.push(`0 ${zero}\t${file.path}`);
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
const bytes = node_fs_1.default.readFileSync(node_path_1.default.join(root, file.path));
|
|
521
|
+
if (sha256Hex(bytes) !== file.sha256) {
|
|
522
|
+
throw new FinalizationError('digest_mismatch', 'A file changed after the manifest was checked');
|
|
523
|
+
}
|
|
524
|
+
const oid = text(await git(root, ['hash-object', '-w', '--no-filters', '--stdin'], { input: bytes }));
|
|
525
|
+
blobs.set(file.path, oid);
|
|
526
|
+
lines.push(`${file.mode} ${oid}\t${file.path}`);
|
|
527
|
+
}
|
|
528
|
+
await git(root, ['update-index', '-z', '--index-info'], {
|
|
529
|
+
indexFile: privateIndex,
|
|
530
|
+
input: Buffer.from(lines.map((line) => `${line}\u0000`).join(''), 'utf8'),
|
|
531
|
+
});
|
|
532
|
+
// Re-read the staged set and blob digests: exactly the manifest, nothing else.
|
|
533
|
+
const staged = await git(root, ['diff-index', '--cached', '-z', '--raw', '--no-abbrev', '--no-renames', 'HEAD', '--'], {
|
|
534
|
+
indexFile: privateIndex,
|
|
535
|
+
});
|
|
536
|
+
const records = splitNul(staged.stdout).map((part) => part.toString('utf8'));
|
|
537
|
+
const mismatch = new FinalizationError('digest_mismatch', 'The staged set differs from the manifest');
|
|
538
|
+
const stagedPaths = new Map();
|
|
539
|
+
for (let i = 0; i + 1 < records.length; i += 2) {
|
|
540
|
+
// `:<src mode> <dst mode> <src oid> <dst oid> <status>` then the path.
|
|
541
|
+
const match = /^:\d+ (\d+) [0-9a-f]+ ([0-9a-f]+) ([A-Z])/.exec(records[i]);
|
|
542
|
+
if (!match) {
|
|
543
|
+
throw mismatch;
|
|
544
|
+
}
|
|
545
|
+
stagedPaths.set(records[i + 1], { mode: match[1], oid: match[2], status: match[3] });
|
|
546
|
+
}
|
|
547
|
+
if (stagedPaths.size !== input.files.length) {
|
|
548
|
+
throw mismatch;
|
|
549
|
+
}
|
|
550
|
+
for (const file of input.files) {
|
|
551
|
+
const entry = stagedPaths.get(file.path);
|
|
552
|
+
if (!entry) {
|
|
553
|
+
throw mismatch;
|
|
554
|
+
}
|
|
555
|
+
if (file.sha256 === null) {
|
|
556
|
+
if (entry.status !== 'D') {
|
|
557
|
+
throw mismatch;
|
|
558
|
+
}
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
if (entry.mode !== file.mode || entry.oid !== blobs.get(file.path)) {
|
|
562
|
+
throw mismatch;
|
|
563
|
+
}
|
|
564
|
+
const blob = await git(root, ['cat-file', 'blob', entry.oid]);
|
|
565
|
+
if (sha256Hex(blob.stdout) !== file.sha256) {
|
|
566
|
+
throw mismatch;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
await checkpoint('staged');
|
|
570
|
+
const tree = text(await git(root, ['write-tree'], { indexFile: privateIndex }));
|
|
571
|
+
const commit = text(await git(root, ['commit-tree', tree, '-p', input.expectedBaseCommit, '-F', '-'], {
|
|
572
|
+
input: input.commitMessage,
|
|
573
|
+
}));
|
|
574
|
+
options.onCommitObject?.(commit, tree);
|
|
575
|
+
await checkpoint('commit-object');
|
|
576
|
+
// Compare-and-swap: the ref moves only from expectedBaseCommit.
|
|
577
|
+
const updateArgs = baseline.headRef === 'HEAD'
|
|
578
|
+
? ['update-ref', '--no-deref', '-m', `agent-deck finalize ${input.runId}`, 'HEAD', commit, input.expectedBaseCommit]
|
|
579
|
+
: ['update-ref', '-m', `agent-deck finalize ${input.runId}`, baseline.headRef, commit, input.expectedBaseCommit];
|
|
580
|
+
const updated = await runGit(updateArgs, { cwd: root });
|
|
581
|
+
if (updated.code !== 0) {
|
|
582
|
+
const now = await runGit(['rev-parse', '--verify', '-q', baseline.headRef], { cwd: root });
|
|
583
|
+
if (now.stdout.toString('utf8').trim() !== input.expectedBaseCommit) {
|
|
584
|
+
throw new FinalizationError('ref_race', 'The branch moved before the commit could be recorded');
|
|
585
|
+
}
|
|
586
|
+
if (node_fs_1.default.existsSync(refLock)) {
|
|
587
|
+
throw new FinalizationError('git_lock_conflict', 'The branch ref is locked by another Git process');
|
|
588
|
+
}
|
|
589
|
+
throw new FinalizationError('finalization_failed', 'git update-ref failed');
|
|
590
|
+
}
|
|
591
|
+
committed = true;
|
|
592
|
+
await checkpoint('ref-updated');
|
|
593
|
+
// The real index adopts the private one (Git's lock-and-rename), so it matches the new HEAD.
|
|
594
|
+
try {
|
|
595
|
+
node_fs_1.default.writeSync(lockFd, node_fs_1.default.readFileSync(privateIndex));
|
|
596
|
+
node_fs_1.default.fsyncSync(lockFd);
|
|
597
|
+
node_fs_1.default.closeSync(lockFd);
|
|
598
|
+
lockFd = null;
|
|
599
|
+
node_fs_1.default.renameSync(lockPath, baseline.indexPath);
|
|
600
|
+
}
|
|
601
|
+
catch {
|
|
602
|
+
// History is already correct; a stale index refreshes on the next Git command.
|
|
603
|
+
}
|
|
604
|
+
return {
|
|
605
|
+
commit,
|
|
606
|
+
tree,
|
|
607
|
+
parent: input.expectedBaseCommit,
|
|
608
|
+
manifestDigest: manifestDigestOf(input.files),
|
|
609
|
+
fileCount: input.files.length,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
catch (error) {
|
|
613
|
+
if (committed) {
|
|
614
|
+
throw error;
|
|
615
|
+
}
|
|
616
|
+
if (error instanceof FinalizationError) {
|
|
617
|
+
throw error;
|
|
618
|
+
}
|
|
619
|
+
throw new FinalizationError('finalization_failed', 'Finalization failed before the commit');
|
|
620
|
+
}
|
|
621
|
+
finally {
|
|
622
|
+
if (lockFd !== null) {
|
|
623
|
+
try {
|
|
624
|
+
node_fs_1.default.closeSync(lockFd);
|
|
625
|
+
}
|
|
626
|
+
catch {
|
|
627
|
+
// Already closed.
|
|
628
|
+
}
|
|
629
|
+
node_fs_1.default.rmSync(lockPath, { force: true });
|
|
630
|
+
}
|
|
631
|
+
node_fs_1.default.rmSync(privateIndex, { force: true });
|
|
632
|
+
node_fs_1.default.rmSync(`${privateIndex}.lock`, { force: true });
|
|
633
|
+
busy.delete(key);
|
|
634
|
+
}
|
|
635
|
+
},
|
|
636
|
+
recover,
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
//# sourceMappingURL=git-finalize.js.map
|