homeagent-runner 0.0.0-stage → 0.4.5

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 (50) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/CONTRIBUTING.md +65 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +329 -0
  5. package/README.md +271 -2
  6. package/SECURITY.md +59 -0
  7. package/THIRD_PARTY_NOTICES.md +45 -0
  8. package/bin/runner.mjs +2 -0
  9. package/dist/runner/agent.js +254 -0
  10. package/dist/runner/cli.js +66 -0
  11. package/dist/runner/config-location.js +67 -0
  12. package/dist/runner/config.js +43 -0
  13. package/dist/runner/context.js +86 -0
  14. package/dist/runner/credentials.js +68 -0
  15. package/dist/runner/editor.js +262 -0
  16. package/dist/runner/files.js +298 -0
  17. package/dist/runner/git.js +333 -0
  18. package/dist/runner/lock.js +28 -0
  19. package/dist/runner/output-log.js +59 -0
  20. package/dist/runner/patch.js +103 -0
  21. package/dist/runner/permissions.js +93 -0
  22. package/dist/runner/policy.js +87 -0
  23. package/dist/runner/process-tree.js +28 -0
  24. package/dist/runner/processes.js +367 -0
  25. package/dist/runner/service.js +53 -0
  26. package/dist/runner/setup.js +79 -0
  27. package/dist/runner/tools.js +118 -0
  28. package/dist/shared/permissions.js +40 -0
  29. package/dist/shared/protocol.js +98 -0
  30. package/dist/shared/tools.js +108 -0
  31. package/docs/ARCHITECTURE.md +92 -0
  32. package/docs/CLIENTS.md +130 -0
  33. package/docs/COMPARISON.md +36 -0
  34. package/docs/DEPLOYMENT.md +295 -0
  35. package/docs/DEVELOPMENT_WORKFLOW.md +126 -0
  36. package/docs/OPEN_SOURCE.md +129 -0
  37. package/docs/README.md +26 -0
  38. package/docs/TOOLS.md +105 -0
  39. package/docs/VALIDATION.md +172 -0
  40. package/docs/WEBCODEX_CODE_AUDIT.md +107 -0
  41. package/docs/screenshots/dashboard.png +0 -0
  42. package/docs/screenshots/jobs.png +0 -0
  43. package/docs/screenshots/permissions.png +0 -0
  44. package/docs/webcodex-parity-map.json +75 -0
  45. package/docs/webcodex-source-inventory.json +2254 -0
  46. package/licenses/npm-runtime.txt +3673 -0
  47. package/package.json +45 -4
  48. package/public/icon.png +0 -0
  49. package/runtime/windows-process-tree.cs +105 -0
  50. package/runtime/windows-process-tree.ps1 +19 -0
@@ -0,0 +1,298 @@
1
+ import { constants } from 'node:fs';
2
+ import { open, mkdir, rename, lstat, unlink } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { AppError } from '../shared/protocol.js';
6
+ import { inside } from './config.js';
7
+ export const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
8
+ const MAX_FILE = 1024 * 1024;
9
+ export class Files {
10
+ policy;
11
+ constructor(policy) {
12
+ this.policy = policy;
13
+ }
14
+ async bounded(handle, max) {
15
+ const buffer = Buffer.alloc(max + 1);
16
+ let size = 0;
17
+ while (size < buffer.length) {
18
+ const next = await handle.read(buffer, size, buffer.length - size, size);
19
+ if (!next.bytesRead)
20
+ break;
21
+ size += next.bytesRead;
22
+ }
23
+ if (size > max)
24
+ throw new AppError('file_limit', 'File grew beyond the read limit');
25
+ return buffer.subarray(0, size);
26
+ }
27
+ async readSafe(filename, max = MAX_FILE) {
28
+ const handle = await open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
29
+ try {
30
+ const stat = await handle.stat();
31
+ if (!stat.isFile() || stat.nlink > 1 || stat.size > max)
32
+ throw new AppError('file_limit', 'Expected a regular file within the size limit');
33
+ return await this.bounded(handle, max);
34
+ }
35
+ finally {
36
+ await handle.close();
37
+ }
38
+ }
39
+ async read(project, args) {
40
+ const filename = await this.policy.resolve(project, args.path);
41
+ const handle = await open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
42
+ try {
43
+ const stat = await handle.stat();
44
+ if (!stat.isFile() || stat.nlink > 1)
45
+ throw new AppError('not_file', 'Expected a regular file');
46
+ const revisionOf = (value) => sha256(JSON.stringify([value.dev, value.ino, value.size, value.mtimeMs, value.ctimeMs]));
47
+ const revision = revisionOf(stat);
48
+ if (args.expectedRevision && args.expectedRevision !== revision)
49
+ throw new AppError('conflict', 'File changed between paged reads; restart from offset zero');
50
+ const buffer = Buffer.alloc(args.length);
51
+ const { bytesRead } = await handle.read(buffer, 0, args.length, args.offset);
52
+ const bytes = buffer.subarray(0, bytesRead);
53
+ const digest = stat.size <= MAX_FILE ? sha256(await this.bounded(handle, MAX_FILE)) : undefined;
54
+ if (revisionOf(await handle.stat()) !== revision)
55
+ throw new AppError('conflict', 'File changed during this read');
56
+ return { text: bytes.toString('utf8'), offset: args.offset, nextOffset: args.offset + bytesRead, size: stat.size, eof: args.offset + bytesRead >= stat.size, revision, sha256: digest };
57
+ }
58
+ finally {
59
+ await handle.close();
60
+ }
61
+ }
62
+ async atomic(filename, content) {
63
+ const temporary = path.join(path.dirname(filename), `.ha-${randomUUID()}.tmp`);
64
+ let mode = 0o600;
65
+ try {
66
+ mode = (await lstat(filename)).mode & 0o777;
67
+ }
68
+ catch (error) {
69
+ if (error.code !== 'ENOENT')
70
+ throw error;
71
+ }
72
+ try {
73
+ const handle = await open(temporary, 'wx', mode);
74
+ try {
75
+ await handle.writeFile(content);
76
+ await handle.sync();
77
+ }
78
+ finally {
79
+ await handle.close();
80
+ }
81
+ await rename(temporary, filename);
82
+ }
83
+ finally {
84
+ await unlink(temporary).catch(() => { });
85
+ }
86
+ }
87
+ async snapshot(project, input, allowMissing = false, max = MAX_FILE) {
88
+ const filename = await this.policy.resolve(project, input, allowMissing);
89
+ try {
90
+ const bytes = await this.readSafe(filename, max);
91
+ const stat = await lstat(filename);
92
+ return { filename, bytes, sha256: sha256(bytes), mode: stat.mode & 0o777 };
93
+ }
94
+ catch (error) {
95
+ if (allowMissing && error.code === 'ENOENT')
96
+ return { filename, bytes: null, sha256: null, mode: 0o600 };
97
+ throw error;
98
+ }
99
+ }
100
+ async readFiles(project, args) {
101
+ const results = [];
102
+ let remaining = args.maxBytes;
103
+ for (const item of args.files) {
104
+ if (remaining <= 0) {
105
+ results.push({ path: item.path, error: 'result_budget', suggestedCall: { name: 'read_files', arguments: { projectId: project.id, files: [item], maxBytes: args.maxBytes } } });
106
+ continue;
107
+ }
108
+ try {
109
+ const snapshot = await this.snapshot(project, item.path, false, 8 * MAX_FILE);
110
+ if (item.expectedSha256 && snapshot.sha256 !== item.expectedSha256)
111
+ throw new AppError('conflict', 'File changed since the earlier read');
112
+ if (snapshot.bytes.includes(0))
113
+ throw new AppError('binary_file', 'Use a binary artifact tool for this file');
114
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(snapshot.bytes);
115
+ const lines = text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
116
+ const end = Math.min(item.endLine ?? item.startLine + 199, item.startLine + 999, lines.length);
117
+ if (item.endLine !== undefined && item.endLine < item.startLine)
118
+ throw new AppError('invalid_range', 'endLine precedes startLine');
119
+ let selected = '', line = item.startLine - 1;
120
+ while (line < end) {
121
+ const next = lines[line];
122
+ if (Buffer.byteLength(selected) + Buffer.byteLength(next) > remaining)
123
+ break;
124
+ selected += next;
125
+ line++;
126
+ }
127
+ const used = Buffer.byteLength(selected);
128
+ remaining -= used;
129
+ const truncated = line < Math.min(item.endLine ?? lines.length, lines.length);
130
+ const response = { path: item.path, text: selected, startLine: item.startLine, endLine: line, totalLines: lines.length, sha256: snapshot.sha256, bytes: snapshot.bytes.length, truncated, nextStartLine: truncated && line >= item.startLine ? line + 1 : null };
131
+ if (line < end && !used)
132
+ response.error = 'line_exceeds_budget';
133
+ results.push(response);
134
+ }
135
+ catch (error) {
136
+ results.push({ path: item.path, error: error instanceof AppError ? error.code : 'read_failed', message: error instanceof Error ? error.message : 'Read failed' });
137
+ }
138
+ }
139
+ return { files: results, bytesReturned: args.maxBytes - remaining, budgetBytes: args.maxBytes };
140
+ }
141
+ async write(project, args) {
142
+ const filename = await this.policy.resolve(project, args.path, true);
143
+ let prior = Buffer.alloc(0);
144
+ if (args.append || args.expectedSha256) {
145
+ try {
146
+ prior = await this.readSafe(filename);
147
+ }
148
+ catch (error) {
149
+ if (!args.expectedSha256 && error.code === 'ENOENT') { }
150
+ else
151
+ throw error;
152
+ }
153
+ }
154
+ if (args.expectedSha256 && sha256(prior) !== args.expectedSha256)
155
+ throw new AppError('conflict', 'File changed since it was read');
156
+ const next = args.append ? Buffer.concat([prior, Buffer.from(args.content)]) : Buffer.from(args.content);
157
+ if (next.length > MAX_FILE)
158
+ throw new AppError('file_limit', 'Result exceeds 1 MiB; split the file');
159
+ await this.atomic(filename, next);
160
+ return { written: next.length, sha256: sha256(next) };
161
+ }
162
+ async edit(project, args) {
163
+ const filename = await this.policy.resolve(project, args.path);
164
+ const bytes = await this.readSafe(filename);
165
+ if (args.expectedSha256 && sha256(bytes) !== args.expectedSha256)
166
+ throw new AppError('conflict', 'File changed since it was read');
167
+ const text = bytes.toString('utf8');
168
+ const index = text.indexOf(args.oldText);
169
+ if (index < 0 || text.indexOf(args.oldText, index + 1) >= 0)
170
+ throw new AppError('not_unique', 'oldText must match exactly once');
171
+ const next = Buffer.from(text.slice(0, index) + args.newText + text.slice(index + args.oldText.length));
172
+ if (next.length > MAX_FILE)
173
+ throw new AppError('file_limit', 'Result exceeds file limit');
174
+ await this.atomic(filename, next);
175
+ return { written: next.length, sha256: sha256(next) };
176
+ }
177
+ async list(project, args) {
178
+ const directory = await this.policy.resolve(project, args.path);
179
+ const dir = await openDirectory(directory);
180
+ const entries = [];
181
+ let truncated = false, index = 0, scanned = 0, sourceTruncated = false;
182
+ try {
183
+ for await (const item of dir) {
184
+ if (++scanned > 100000) {
185
+ sourceTruncated = true;
186
+ break;
187
+ }
188
+ if (project.deniedNames.some(name => name.toLowerCase() === item.name.toLowerCase()) || item.isSymbolicLink())
189
+ continue;
190
+ const candidate = path.join(directory, item.name);
191
+ if ((this.policy.config.protectedPaths ?? []).some(privatePath => path.resolve(privatePath) === path.resolve(candidate) || inside(privatePath, candidate)))
192
+ continue;
193
+ if (index++ < (args.offset ?? 0))
194
+ continue;
195
+ if (entries.length >= args.limit) {
196
+ truncated = true;
197
+ break;
198
+ }
199
+ entries.push({ name: item.name, type: item.isDirectory() ? 'directory' : item.isFile() ? 'file' : 'other' });
200
+ }
201
+ }
202
+ finally {
203
+ await dir.close().catch(() => { });
204
+ }
205
+ return { entries: entries.sort((a, b) => a.name.localeCompare(b.name)), offset: args.offset ?? 0, nextOffset: truncated && !sourceTruncated ? (args.offset ?? 0) + entries.length : null, truncated: truncated || sourceTruncated, sourceTruncated };
206
+ }
207
+ async info(project, input) {
208
+ const stat = await lstat(await this.policy.resolve(project, input));
209
+ return { type: stat.isDirectory() ? 'directory' : 'file', size: stat.size, modified: stat.mtime.toISOString() };
210
+ }
211
+ async mkdir(project, input) {
212
+ await mkdir(await this.policy.resolve(project, input, true), { recursive: true });
213
+ return { created: true };
214
+ }
215
+ async move(project, source, destination) {
216
+ const from = await this.policy.resolve(project, source), to = await this.policy.resolve(project, destination, true);
217
+ if (from === project.root || to === project.root)
218
+ throw new AppError('root_move', 'Cannot move a project root');
219
+ if ([this.policy.config.stateDir, ...(this.policy.config.protectedPaths ?? [])].some(privatePath => inside(from, privatePath) || inside(to, privatePath)))
220
+ throw new AppError('private_state', 'Cannot move a directory containing Runner configuration or private state');
221
+ try {
222
+ await lstat(to);
223
+ throw new AppError('exists', 'Destination already exists');
224
+ }
225
+ catch (error) {
226
+ if (error.code !== 'ENOENT')
227
+ throw error;
228
+ }
229
+ await rename(from, to);
230
+ return { moved: true };
231
+ }
232
+ async search(project, args, signal, sourcePaths) {
233
+ const start = await this.policy.resolve(project, args.path), pending = sourcePaths ? sourcePaths.slice(0, 10000).map(name => path.join(project.root, name)) : [start];
234
+ const matches = [];
235
+ let scanned = 0, truncated = false, resultBytes = 0, budgetExhausted = false;
236
+ const normalize = (value) => args.caseSensitive ? value : value.toLowerCase();
237
+ const query = normalize(args.query);
238
+ while (pending.length && matches.length < args.limit && !budgetExhausted) {
239
+ if (signal?.aborted)
240
+ throw new AppError('cancelled', 'Search cancelled');
241
+ if (++scanned > 10000) {
242
+ truncated = true;
243
+ break;
244
+ }
245
+ const filename = pending.pop();
246
+ let stat;
247
+ try {
248
+ await this.policy.resolve(project, filename);
249
+ stat = await lstat(filename);
250
+ }
251
+ catch {
252
+ continue;
253
+ }
254
+ const relative = path.relative(project.root, filename);
255
+ const normalized = relative.split(path.sep).join('/');
256
+ if (!stat.isDirectory() && ((args.include?.length && !args.include.some(pattern => path.matchesGlob(normalized, pattern))) || args.exclude?.some(pattern => path.matchesGlob(normalized, pattern))))
257
+ continue;
258
+ if (!args.content && normalize(relative).includes(query))
259
+ matches.push({ path: relative });
260
+ if (stat.isDirectory()) {
261
+ const dir = await openDirectory(filename);
262
+ for await (const entry of dir) {
263
+ if (pending.length + scanned >= 10000) {
264
+ truncated = true;
265
+ break;
266
+ }
267
+ if (!entry.isSymbolicLink() && entry.name !== 'node_modules' && !project.deniedNames.includes(entry.name))
268
+ pending.push(path.join(filename, entry.name));
269
+ }
270
+ }
271
+ else if (args.content && stat.isFile() && stat.size <= MAX_FILE) {
272
+ try {
273
+ const buffer = await this.readSafe(filename);
274
+ if (buffer.includes(0))
275
+ continue;
276
+ const lines = buffer.toString('utf8').split('\n');
277
+ for (let i = 0; i < lines.length && matches.length < args.limit; i++)
278
+ if (normalize(lines[i]).includes(query)) {
279
+ const context = args.contextLines ? { startLine: Math.max(0, i - args.contextLines) + 1, text: lines.slice(Math.max(0, i - args.contextLines), i + args.contextLines + 1).map(line => line.slice(0, 1000)).join('\n') } : undefined;
280
+ const match = { path: relative, line: i + 1, text: lines[i].slice(0, 1000), ...(context ? { context } : {}) };
281
+ const size = Buffer.byteLength(JSON.stringify(match));
282
+ if (resultBytes + size > 262144) {
283
+ budgetExhausted = true;
284
+ break;
285
+ }
286
+ resultBytes += size;
287
+ matches.push(match);
288
+ }
289
+ }
290
+ catch { /* Unreadable files do not abort a bounded search. */ }
291
+ }
292
+ }
293
+ return { matches, scanned, gitIgnoreApplied: sourcePaths !== undefined, truncated: budgetExhausted || truncated || pending.length > 0 || matches.length >= args.limit || (sourcePaths?.length ?? 0) > 10000 };
294
+ }
295
+ }
296
+ // opendir streams large directories without allocating an unbounded listing.
297
+ import { opendir as openDirectory } from 'node:fs/promises';
298
+ //# sourceMappingURL=files.js.map
@@ -0,0 +1,333 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { lstat, readFile, realpath, open, copyFile, rename, unlink } from 'node:fs/promises';
3
+ import { randomUUID } from 'node:crypto';
4
+ import path from 'node:path';
5
+ import { AppError } from '../shared/protocol.js';
6
+ import { toolEnvironment } from './processes.js';
7
+ import { Files } from './files.js';
8
+ import { inside } from './config.js';
9
+ import { spawnOwnedProcess, stopOwnedProcess } from './process-tree.js';
10
+ export class Git {
11
+ policy;
12
+ constructor(policy) {
13
+ this.policy = policy;
14
+ }
15
+ async run(project, args, signal, extra = [], environment = {}, network = false) {
16
+ const nullFile = process.platform === 'win32' ? 'NUL' : '/dev/null';
17
+ return new Promise((resolve, reject) => {
18
+ const argv = ['--no-pager', '-c', `core.worktree=${project.root}`, '-c', 'core.bare=false', '-c', `core.hooksPath=${nullFile}`, '-c', 'core.fsmonitor=false', '-c', 'commit.gpgsign=false', '-c', 'core.pager=', '-c', 'diff.external=', ...extra, '-C', project.root, ...args];
19
+ const options = {
20
+ env: { ...toolEnvironment(), ...(network ? { SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK, GCM_INTERACTIVE: 'Never' } : { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: nullFile }), GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', GIT_LITERAL_PATHSPECS: '1', ...environment },
21
+ windowsHide: true, shell: false, ...(network ? {} : { signal }),
22
+ };
23
+ if (signal?.aborted) {
24
+ reject(new AppError('cancelled', 'Git operation cancelled before start'));
25
+ return;
26
+ }
27
+ const child = network ? spawnOwnedProcess('git', argv, options) : spawn('git', argv, options);
28
+ if (network && process.platform !== 'win32')
29
+ child.once('exit', () => {
30
+ if (child.pid) {
31
+ try {
32
+ process.kill(-child.pid, 'SIGKILL');
33
+ }
34
+ catch { }
35
+ }
36
+ });
37
+ const stop = () => { void stopOwnedProcess(child).catch(() => child.kill()); };
38
+ if (network)
39
+ signal?.addEventListener('abort', stop, { once: true });
40
+ const chunks = [];
41
+ let size = 0, truncated = false;
42
+ const capture = (chunk) => { const accepted = chunk.subarray(0, Math.max(0, 262144 - size)); if (accepted.length)
43
+ chunks.push(accepted); size += accepted.length; if (accepted.length !== chunk.length)
44
+ truncated = true; };
45
+ child.stdout.on('data', capture);
46
+ child.stderr.on('data', capture);
47
+ let timedOut = false;
48
+ const timer = setTimeout(() => { timedOut = true; if (network)
49
+ stop();
50
+ else
51
+ child.kill(); }, network ? 35000 : 20000).unref();
52
+ child.on('error', error => { clearTimeout(timer); signal?.removeEventListener('abort', stop); reject(error); });
53
+ child.on('close', code => {
54
+ clearTimeout(timer);
55
+ signal?.removeEventListener('abort', stop);
56
+ if (signal?.aborted) {
57
+ reject(new AppError('cancelled', 'Git operation cancelled; inspect repository and remote state before retrying'));
58
+ return;
59
+ }
60
+ if (timedOut) {
61
+ reject(new AppError('git_timeout', 'Git operation timed out; inspect repository and remote state before retrying'));
62
+ return;
63
+ }
64
+ const output = Buffer.concat(chunks).toString('utf8') + (truncated ? '\n[output truncated]' : '');
65
+ if (code === 0)
66
+ resolve(output);
67
+ else
68
+ reject(new AppError('git_failed', output || 'Git operation failed'));
69
+ });
70
+ });
71
+ }
72
+ async metadata(project) {
73
+ await this.policy.resolve(project, '.');
74
+ const entry = path.join(project.root, '.git'), stat = await lstat(entry);
75
+ if (stat.isSymbolicLink())
76
+ throw new AppError('git_boundary', 'Symbolic Git metadata is not supported');
77
+ if (stat.isDirectory())
78
+ return entry;
79
+ if (!stat.isFile() || stat.nlink > 1 || !project.gitCommonDir || stat.size > 8192)
80
+ throw new AppError('git_boundary', 'A linked worktree requires an explicitly configured gitCommonDir');
81
+ const text = await readFile(entry, 'utf8');
82
+ const match = /^gitdir: (.+)\r?\n?$/.exec(text);
83
+ if (!match)
84
+ throw new AppError('git_boundary', 'Invalid linked worktree metadata');
85
+ const directory = path.resolve(project.root, match[1]);
86
+ const common = await realpath(project.gitCommonDir), base = path.join(common, 'worktrees');
87
+ if ((await lstat(base)).isSymbolicLink())
88
+ throw new AppError('git_boundary', 'Worktree registry cannot be a symbolic link');
89
+ if (!inside(base, directory) || directory === base)
90
+ throw new AppError('git_boundary', 'Linked Git metadata is outside configured common directory');
91
+ let current = base;
92
+ for (const part of path.relative(base, directory).split(path.sep)) {
93
+ current = path.join(current, part);
94
+ if ((await lstat(current)).isSymbolicLink())
95
+ throw new AppError('git_boundary', 'Linked Git metadata cannot contain symbolic links');
96
+ }
97
+ if (await realpath(directory) !== directory)
98
+ throw new AppError('git_boundary', 'Linked Git directory changed');
99
+ const backlink = path.resolve(directory, (await readFile(path.join(directory, 'gitdir'), 'utf8')).trim());
100
+ const actualCommon = await realpath(path.resolve(directory, (await readFile(path.join(directory, 'commondir'), 'utf8')).trim()));
101
+ if (backlink !== entry || actualCommon !== common)
102
+ throw new AppError('git_boundary', 'Linked worktree backlink or common directory mismatch');
103
+ return directory;
104
+ }
105
+ async commitPaths(project, directory, args, signal) {
106
+ const files = new Files(this.policy), selected = [], paths = new Set();
107
+ for (const item of args.files) {
108
+ const snapshot = await files.snapshot(project, item.path, true);
109
+ if (snapshot.sha256 !== item.expectedSha256)
110
+ throw new AppError('conflict', `File snapshot changed: ${item.path}`);
111
+ const relative = path.relative(project.root, snapshot.filename).split(path.sep).join('/');
112
+ if (!relative || paths.has(process.platform === 'win32' ? relative.toLowerCase() : relative))
113
+ throw new AppError('git_path', 'Select unique explicit files, not directories');
114
+ paths.add(process.platform === 'win32' ? relative.toLowerCase() : relative);
115
+ selected.push({ ...item, path: relative });
116
+ }
117
+ const lockPath = path.join(directory, 'index.lock'), indexPath = path.join(directory, 'index');
118
+ let lock;
119
+ try {
120
+ lock = await open(lockPath, 'wx', 0o600);
121
+ }
122
+ catch (error) {
123
+ if (error.code === 'EEXIST')
124
+ throw new AppError('git_busy', 'Git index is locked; inspect the active Git operation before retrying');
125
+ throw error;
126
+ }
127
+ const candidate = path.join(directory, `homeagent-${randomUUID()}.index`), postIndex = `${candidate}.post`;
128
+ let committed = '', finalized = false;
129
+ try {
130
+ const head = (await this.run(project, ['rev-parse', 'HEAD'], signal)).trim();
131
+ const reference = (await this.run(project, ['rev-parse', '--symbolic-full-name', 'HEAD'], signal)).trim();
132
+ if (head !== args.expectedHead)
133
+ throw new AppError('head_changed', 'HEAD changed since review');
134
+ const list = selected.map(item => item.path);
135
+ if ((await this.run(project, ['diff', '--cached', '--name-only', '-z', '--', ...list], signal)).length)
136
+ throw new AppError('staged_conflict', 'A selected path already has staged changes; review them explicitly before committing');
137
+ const candidateEnv = { GIT_INDEX_FILE: candidate };
138
+ await this.run(project, ['read-tree', head], signal, [], candidateEnv);
139
+ await this.run(project, ['add', '--', ...list], signal, [], candidateEnv);
140
+ if (!(await this.run(project, ['diff', '--cached', '--name-only', '--', ...list], signal, [], candidateEnv)).trim())
141
+ throw new AppError('nothing_to_commit', 'Selected snapshots contain no changes');
142
+ const tree = (await this.run(project, ['write-tree'], signal, [], candidateEnv)).trim();
143
+ const commit = (await this.run(project, ['commit-tree', tree, '-p', head, '-m', args.message], signal, [], candidateEnv)).trim();
144
+ await copyFile(indexPath, postIndex);
145
+ await this.run(project, ['reset', '-q', commit, '--', ...list], signal, [], { GIT_INDEX_FILE: postIndex });
146
+ for (const item of selected) {
147
+ if ((await files.snapshot(project, item.path, true)).sha256 !== item.expectedSha256)
148
+ throw new AppError('conflict', `File changed during commit preparation: ${item.path}`);
149
+ }
150
+ if ((await this.run(project, ['rev-parse', '--symbolic-full-name', 'HEAD'], signal)).trim() !== reference)
151
+ throw new AppError('head_changed', 'Active branch changed during commit preparation');
152
+ const bytes = await readFile(postIndex);
153
+ await lock.writeFile(bytes);
154
+ await lock.sync();
155
+ await lock.close();
156
+ if (signal?.aborted)
157
+ throw new AppError('cancelled', 'Commit cancelled before ref update');
158
+ try {
159
+ await this.run(project, ['update-ref', '-m', 'HomeAgent selected-file commit', reference, commit, head]);
160
+ committed = commit;
161
+ }
162
+ catch (error) {
163
+ const observed = (await this.run(project, ['rev-parse', reference]).catch(() => 'unknown')).trim();
164
+ if (observed === head)
165
+ throw error;
166
+ committed = commit;
167
+ if (observed !== commit)
168
+ throw new AppError('commit_reconcile_required', 'Ref update outcome is uncertain; inspect HEAD and the prepared index before retrying');
169
+ }
170
+ // Once the ref changes, finalize the prepared index even if the HTTP caller disconnects.
171
+ await rename(lockPath, indexPath);
172
+ finalized = true;
173
+ return { commit, parent: head, files: list, preservedUnrelatedStagedChanges: true };
174
+ }
175
+ catch (error) {
176
+ if (committed)
177
+ throw new AppError('commit_reconcile_required', `Commit ${committed} exists, but index finalization needs operator inspection. Do not retry blindly.`);
178
+ throw error;
179
+ }
180
+ finally {
181
+ await lock.close().catch(() => { });
182
+ if (!committed || finalized)
183
+ await unlink(lockPath).catch(() => { });
184
+ for (const temporary of [candidate, `${candidate}.lock`, postIndex, `${postIndex}.lock`])
185
+ await unlink(temporary).catch(() => { });
186
+ }
187
+ }
188
+ async listFiles(project, scope, signal) {
189
+ await this.metadata(project);
190
+ await this.policy.resolve(project, scope);
191
+ const output = await this.run(project, ['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', scope], signal);
192
+ if (output.includes('[output truncated]'))
193
+ throw new AppError('search_source_limit', 'Git file list exceeded the source budget; narrow the search path');
194
+ return [...new Set(output.split('\0').filter(Boolean))];
195
+ }
196
+ async invoke(project, name, args, signal) {
197
+ if (args.repository && args.repository !== '.') {
198
+ const root = await this.policy.resolve(project, String(args.repository));
199
+ project = { ...project, root: await realpath(root) };
200
+ }
201
+ const gitDirectory = await this.metadata(project);
202
+ if (await this.run(project, ['rev-parse', '--show-toplevel'], signal).then(value => path.resolve(value.trim())) !== project.root)
203
+ throw new AppError('git_boundary', 'Git repository root does not match the project');
204
+ if (name === 'git_status')
205
+ return this.run(project, ['status', '--porcelain=v1', '--untracked-files=normal', '--ignore-submodules=all'], signal);
206
+ if (name === 'git_log')
207
+ return this.run(project, ['log', `-${args.limit}`, '--format=%h %aI %an %s'], signal);
208
+ if (name === 'git_branches') {
209
+ const head = (await this.run(project, ['rev-parse', 'HEAD'], signal)).trim();
210
+ const branch = (await this.run(project, ['rev-parse', '--abbrev-ref', 'HEAD'], signal)).trim();
211
+ const branches = (await this.run(project, ['for-each-ref', '--count=100', '--format=%(refname:short)', 'refs/heads'], signal)).trim().split('\n').filter(Boolean);
212
+ return { head, branch, branches, status: await this.run(project, ['status', '--porcelain=v1', '--untracked-files=normal', '--ignore-submodules=all'], signal) };
213
+ }
214
+ if (name === 'git_diff') {
215
+ const paths = [];
216
+ {
217
+ if (args.path)
218
+ await this.policy.resolve(project, String(args.path), true);
219
+ const changed = await this.run(project, ['diff', '--name-only', '-z', ...(args.staged ? ['--cached'] : []), '--', ...(args.path ? [String(args.path)] : [])], signal);
220
+ if (changed.includes('[output truncated]'))
221
+ throw new AppError('diff_limit', 'Narrow the diff to a specific path');
222
+ for (const name of changed.split('\0').filter(Boolean)) {
223
+ try {
224
+ await this.policy.resolve(project, name, true);
225
+ paths.push(name);
226
+ }
227
+ catch { }
228
+ }
229
+ if (!paths.length)
230
+ return '';
231
+ if (paths.length > 100)
232
+ throw new AppError('diff_limit', 'More than 100 eligible changed files; narrow the path');
233
+ }
234
+ return this.run(project, ['diff', '--no-ext-diff', '--no-textconv', '--ignore-submodules=all', ...(args.staged ? ['--cached'] : []), '--', ...paths], signal);
235
+ }
236
+ // Git clean/process filters can execute commands during staging. Refuse configured filters.
237
+ let filters = '';
238
+ try {
239
+ filters = await this.run(project, ['config', '--includes', '--get-regexp', '^filter\\..*\\.(clean|process)$'], signal);
240
+ }
241
+ catch (error) {
242
+ if (!(error instanceof AppError && error.message === 'Git operation failed'))
243
+ throw error;
244
+ }
245
+ if (filters.trim())
246
+ throw new AppError('git_filter', 'Git writes refuse repositories with clean/process filters');
247
+ for (const critical of ['config', 'index', 'objects', 'refs']) {
248
+ try {
249
+ if ((await lstat(path.join(gitDirectory, critical))).isSymbolicLink())
250
+ throw new AppError('git_boundary', 'Symlinked Git metadata is not supported');
251
+ }
252
+ catch (error) {
253
+ if (error.code !== 'ENOENT')
254
+ throw error;
255
+ }
256
+ }
257
+ if (['git_fetch', 'git_pull', 'git_push'].includes(name)) {
258
+ if (!project.allowGitNetwork)
259
+ throw new AppError('git_network_disabled', 'The owner must enable Git network operations in device permissions');
260
+ if (name === 'git_push' && !project.allowGitPush)
261
+ throw new AppError('git_push_disabled', 'Git push is separately disabled by the owner');
262
+ const remote = String(args.remote ?? 'origin');
263
+ if (!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/.test(remote))
264
+ throw new AppError('invalid_remote', 'Select a configured remote name, not a URL or option');
265
+ const url = (await this.run(project, ['remote', 'get-url', ...(name === 'git_push' ? ['--push'] : []), remote], signal)).trim();
266
+ if (!/^(?:https:\/\/|ssh:\/\/|[A-Za-z0-9_.-]+@[^/:\s]+:)/i.test(url))
267
+ throw new AppError('git_protocol', 'Controlled network Git accepts configured HTTPS/SSH remotes only');
268
+ const branch = args.branch ? String(args.branch) : undefined;
269
+ if (branch) {
270
+ if (branch.startsWith('-'))
271
+ throw new AppError('invalid_branch', 'Branch cannot start with an option');
272
+ await this.run(project, ['check-ref-format', '--branch', branch], signal);
273
+ }
274
+ if (name === 'git_pull' && (await this.run(project, ['status', '--porcelain=v1', '--untracked-files=normal'], signal)).trim())
275
+ throw new AppError('dirty_worktree', 'Pull requires a clean worktree and index');
276
+ const flags = ['-c', 'protocol.allow=never', '-c', 'protocol.https.allow=always', '-c', 'protocol.ssh.allow=always', '-c', 'submodule.recurse=false'];
277
+ let filterKeys = '';
278
+ try {
279
+ filterKeys = await this.run(project, ['config', '--includes', '--null', '--name-only', '--get-regexp', '^filter\\..*\\.(clean|smudge|process)$'], signal, [], {}, true);
280
+ }
281
+ catch (error) {
282
+ if (!(error instanceof AppError && error.message === 'Git operation failed'))
283
+ throw error;
284
+ }
285
+ for (const key of filterKeys.split('\0').filter(Boolean)) {
286
+ if (!/^filter\.[A-Za-z0-9_.-]+\.(?:clean|smudge|process)$/i.test(key))
287
+ throw new AppError('git_filter', 'Unsupported Git filter configuration; use an explicitly trusted command if needed');
288
+ flags.push('-c', `${key}=`, '-c', `${key.slice(0, key.lastIndexOf('.'))}.required=false`);
289
+ }
290
+ if (name === 'git_push') {
291
+ const destination = branch ?? (await this.run(project, ['branch', '--show-current'], signal)).trim();
292
+ if (!destination || destination.startsWith('-'))
293
+ throw new AppError('invalid_branch', 'Push requires a named branch');
294
+ await this.run(project, ['check-ref-format', '--branch', destination], signal);
295
+ return this.run(project, ['push', '--no-verify', '--recurse-submodules=no', remote, `HEAD:refs/heads/${destination}`], signal, flags, {}, true);
296
+ }
297
+ return this.run(project, [name === 'git_pull' ? 'pull' : 'fetch', ...(name === 'git_pull' ? ['--ff-only', '--no-rebase'] : []), '--recurse-submodules=no', remote, ...(branch ? [branch] : [])], signal, flags, {}, true);
298
+ }
299
+ if (name === 'git_commit_paths')
300
+ return this.commitPaths(project, gitDirectory, args, signal);
301
+ if (name === 'git_switch_branch') {
302
+ const branch = String(args.branch);
303
+ if (branch.startsWith('-'))
304
+ throw new AppError('invalid_branch', 'Branch cannot start with an option prefix');
305
+ await this.run(project, ['check-ref-format', '--branch', branch], signal);
306
+ if ((await this.run(project, ['status', '--porcelain=v1', '--untracked-files=normal', '--ignore-submodules=all'], signal)).trim())
307
+ throw new AppError('dirty_worktree', 'Switching branches requires a clean working tree and index');
308
+ await this.run(project, ['switch', ...(args.create ? ['-c'] : []), branch], signal);
309
+ return this.invoke(project, 'git_branches', {}, signal);
310
+ }
311
+ if (name === 'git_add') {
312
+ const paths = args.paths;
313
+ for (const file of paths) {
314
+ const resolved = await this.policy.resolve(project, file, true);
315
+ if (resolved === project.root)
316
+ throw new AppError('git_path', 'Stage explicit files or subdirectories, not the entire project root');
317
+ try {
318
+ if ((await lstat(resolved)).isDirectory())
319
+ throw new AppError('git_path', 'Stage explicit files so excluded descendants cannot be included implicitly');
320
+ }
321
+ catch (error) {
322
+ if (error.code !== 'ENOENT')
323
+ throw error;
324
+ }
325
+ }
326
+ return this.run(project, ['add', '--', ...paths], signal);
327
+ }
328
+ if (name === 'git_commit')
329
+ return this.run(project, ['-c', 'core.editor=false', 'commit', '--no-verify', '--no-gpg-sign', '-m', String(args.message)], signal);
330
+ throw new AppError('unknown_tool', 'Unknown Git tool');
331
+ }
332
+ }
333
+ //# sourceMappingURL=git.js.map
@@ -0,0 +1,28 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { chmodSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { AppError } from '../shared/protocol.js';
5
+ /** OS-backed SQLite locks disappear on process death; no stale PID deletion or PID-reuse guesswork. */
6
+ export class RunnerLock {
7
+ db;
8
+ constructor(directory) {
9
+ const filename = path.join(directory, 'runner-lock.sqlite');
10
+ const db = new DatabaseSync(filename);
11
+ try {
12
+ db.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE');
13
+ if (process.platform !== 'win32')
14
+ chmodSync(filename, 0o600);
15
+ this.db = db;
16
+ }
17
+ catch {
18
+ db.close();
19
+ throw new AppError('runner_already_running', 'Another Runner or pairing process owns this stateDir. Stop it before starting another instance.');
20
+ }
21
+ }
22
+ close() { if (this.db) {
23
+ this.db.exec('ROLLBACK');
24
+ this.db.close();
25
+ this.db = undefined;
26
+ } }
27
+ }
28
+ //# sourceMappingURL=lock.js.map