@imdeadpool/guardex 7.1.1 → 8.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.
Files changed (51) hide show
  1. package/README.md +123 -322
  2. package/package.json +23 -5
  3. package/skills/gitguardex/SKILL.md +83 -3
  4. package/src/agents/finish.js +15 -0
  5. package/src/ci-init/index.js +0 -1
  6. package/src/cli/args.js +142 -3
  7. package/src/cli/commands/branch.js +294 -14
  8. package/src/cli/commands/claude.js +15 -0
  9. package/src/cli/commands/doctor.js +26 -0
  10. package/src/cli/commands/onboard.js +293 -0
  11. package/src/cli/commands/prompt.js +15 -3
  12. package/src/cli/commands/review.js +18 -0
  13. package/src/cli/commands/setup.js +8 -6
  14. package/src/cli/commands/status.js +12 -0
  15. package/src/cli/main.js +2 -0
  16. package/src/cli/shared-locks.js +304 -0
  17. package/src/context.js +21 -3
  18. package/src/core/runtime.js +33 -1
  19. package/src/doctor/index.js +58 -6
  20. package/src/finish/heartbeat.js +169 -0
  21. package/src/finish/index.js +165 -18
  22. package/src/finish/progress.js +316 -0
  23. package/src/finish/review-gate.js +453 -32
  24. package/src/github-api.js +59 -0
  25. package/src/mcp/collect.js +155 -19
  26. package/src/mcp/server.js +35 -19
  27. package/src/output/index.js +210 -0
  28. package/src/pr-checks.js +121 -0
  29. package/src/pr-review.js +581 -51
  30. package/src/pr.js +143 -21
  31. package/src/provider-binary.js +101 -0
  32. package/src/review-diff.js +116 -0
  33. package/src/review-fix.js +229 -0
  34. package/src/sandbox/index.js +11 -5
  35. package/src/scaffold/index.js +4 -16
  36. package/src/shared-git-state.js +566 -0
  37. package/templates/AGENTS.multiagent-safety.md +63 -11
  38. package/templates/AGENTS.multiagent-safety.min.md +1 -0
  39. package/templates/codex/skills/gitguardex/SKILL.md +83 -3
  40. package/templates/githooks/post-checkout +4 -9
  41. package/templates/githooks/pre-commit +17 -1
  42. package/templates/github/workflows/README.md +30 -23
  43. package/templates/scripts/agent-autofinish-watch.sh +280 -0
  44. package/templates/scripts/agent-branch-finish.sh +354 -23
  45. package/templates/scripts/agent-branch-start.sh +49 -22
  46. package/templates/scripts/agent-claude-stop-finish.sh +194 -0
  47. package/templates/scripts/agent-file-locks.py +198 -29
  48. package/templates/scripts/agent-preflight.sh +14 -2
  49. package/templates/scripts/agent-stalled-report.sh +40 -0
  50. package/templates/scripts/codex-agent.sh +10 -63
  51. package/templates/github/workflows/cr.yml +0 -46
@@ -502,19 +502,9 @@ function removeLegacyManagedRepoFile(repoRoot, relativePath, options = {}) {
502
502
  return { status: dryRun ? 'would-remove' : 'removed', file: relativePath };
503
503
  }
504
504
 
505
- // A managed block longer than this many non-blank lines is treated as the full
506
- // contract. The minimal block is ~8 lines and the full contract is ~171, so any
507
- // threshold between the two is safe; 40 leaves a wide margin on both sides.
508
- const FULL_BLOCK_LINE_THRESHOLD = 40;
509
-
510
- function countNonBlankLines(text) {
511
- return text.split('\n').filter((line) => line.trim().length > 0).length;
512
- }
513
-
514
- // Default install ships the minimal block; the full 171-line contract is opt-in
515
- // via `options.contract` (--contract / --full). Once a repo has the full block,
516
- // it is never silently downgraded: an existing managed block over the line
517
- // threshold keeps refreshing from the full template even without the flag.
505
+ // The full contract is deliberately non-sticky: normal setup refreshes return
506
+ // to the token-light minimal block. Repositories that need the expanded policy
507
+ // must opt in explicitly with --contract on that refresh.
518
508
  function ensureAgentsSnippet(repoRoot, dryRun, options = {}) {
519
509
  const agentsPath = path.join(repoRoot, 'AGENTS.md');
520
510
  const managedRegex = new RegExp(
@@ -524,9 +514,7 @@ function ensureAgentsSnippet(repoRoot, dryRun, options = {}) {
524
514
 
525
515
  const existing = fs.existsSync(agentsPath) ? fs.readFileSync(agentsPath, 'utf8') : null;
526
516
  const existingBlock = existing ? existing.match(managedRegex) : null;
527
- const existingIsFull = Boolean(existingBlock)
528
- && countNonBlankLines(existingBlock[0]) > FULL_BLOCK_LINE_THRESHOLD;
529
- const wantFull = Boolean(options.contract) || existingIsFull;
517
+ const wantFull = Boolean(options.contract);
530
518
 
531
519
  const templateFile = wantFull
532
520
  ? 'AGENTS.multiagent-safety.md'
@@ -0,0 +1,566 @@
1
+ 'use strict';
2
+
3
+ // Optional cross-machine coordination backed by ordinary Git refs. The remote
4
+ // is the serialization point: an explicit force-with-lease compare-and-swap
5
+ // lets exactly one writer create or replace a lock ref. No daemon, database,
6
+ // credentials file, or executable payload is introduced.
7
+
8
+ const cp = require('node:child_process');
9
+ const crypto = require('node:crypto');
10
+ const os = require('node:os');
11
+ const path = require('node:path');
12
+
13
+ const MODE_KEY = 'multiagent.sharedState';
14
+ const REMOTE_KEY = 'multiagent.sharedStateRemote';
15
+ const MODE_ENV = 'GUARDEX_SHARED_STATE';
16
+ const REMOTE_ENV = 'GUARDEX_SHARED_STATE_REMOTE';
17
+ const MODE = 'git';
18
+ const DEFAULT_REMOTE = 'origin';
19
+ const LOCK_REF_PREFIX = 'refs/gitguardex/locks/';
20
+ const MAX_REMOTE_LOCKS = 1000;
21
+
22
+ class SharedGitStateError extends Error {
23
+ constructor(code, message, details = {}) {
24
+ super(message);
25
+ this.name = 'SharedGitStateError';
26
+ this.code = code;
27
+ Object.assign(this, details);
28
+ }
29
+ }
30
+
31
+ function spawnGit(repoRoot, args, { input, env, allowFailure = false } = {}) {
32
+ const result = cp.spawnSync('git', ['-c', 'core.hooksPath=/dev/null', ...args], {
33
+ cwd: repoRoot,
34
+ encoding: 'utf8',
35
+ input,
36
+ env: env ? { ...process.env, ...env } : process.env,
37
+ timeout: 15000,
38
+ maxBuffer: 8 * 1024 * 1024
39
+ });
40
+ if (!result || result.status !== 0) {
41
+ if (allowFailure) return result || { status: 1, stdout: '', stderr: 'git did not start' };
42
+ const detail = String(
43
+ (result && (result.stderr || result.stdout)) || 'git did not start'
44
+ ).trim();
45
+ throw new SharedGitStateError('git', detail || `git ${args[0] || ''} failed`);
46
+ }
47
+ if (allowFailure) return result;
48
+ return String(result.stdout || '').trim();
49
+ }
50
+
51
+ function configValue(repoRoot, key) {
52
+ const result = spawnGit(repoRoot, ['config', '--local', '--get', key], { allowFailure: true });
53
+ return result.status === 0 ? String(result.stdout || '').trim() : '';
54
+ }
55
+
56
+ function envHas(env, key) {
57
+ return Object.prototype.hasOwnProperty.call(env, key);
58
+ }
59
+
60
+ function settings(repoRoot, env = process.env) {
61
+ const rawMode = envHas(env, MODE_ENV) ? env[MODE_ENV] : configValue(repoRoot, MODE_KEY);
62
+ const rawRemote = envHas(env, REMOTE_ENV) ? env[REMOTE_ENV] : configValue(repoRoot, REMOTE_KEY);
63
+ return {
64
+ enabled:
65
+ String(rawMode || '')
66
+ .trim()
67
+ .toLowerCase() === MODE,
68
+ mode: String(rawMode || '')
69
+ .trim()
70
+ .toLowerCase(),
71
+ remote: String(rawRemote || DEFAULT_REMOTE).trim() || DEFAULT_REMOTE
72
+ };
73
+ }
74
+
75
+ function assertRemoteName(remote) {
76
+ if (
77
+ typeof remote !== 'string' ||
78
+ remote.length > 128 ||
79
+ remote.startsWith('-') ||
80
+ /[\0-\x20\x7f]/.test(remote)
81
+ ) {
82
+ throw new SharedGitStateError('invalid', 'shared Git remote must be a configured remote name');
83
+ }
84
+ }
85
+
86
+ function enable(repoRoot, remote = DEFAULT_REMOTE) {
87
+ assertRemoteName(remote);
88
+ if (envHas(process.env, MODE_ENV) && settings(repoRoot).mode !== MODE) {
89
+ throw new SharedGitStateError(
90
+ 'invalid',
91
+ `${MODE_ENV} overrides repository config; set it to '${MODE}' or unset it first`
92
+ );
93
+ }
94
+ if (envHas(process.env, REMOTE_ENV) && String(process.env[REMOTE_ENV] || '').trim() !== remote) {
95
+ throw new SharedGitStateError(
96
+ 'invalid',
97
+ `${REMOTE_ENV} overrides --remote; make the values match or unset the environment variable`
98
+ );
99
+ }
100
+ const probe = spawnGit(repoRoot, ['remote', 'get-url', remote], { allowFailure: true });
101
+ if (probe.status !== 0) {
102
+ throw new SharedGitStateError('invalid', `shared Git remote '${remote}' is not configured`);
103
+ }
104
+ const pushUrls = spawnGit(repoRoot, ['remote', 'get-url', '--push', '--all', remote], {
105
+ allowFailure: true
106
+ });
107
+ const pushUrlCount =
108
+ pushUrls.status === 0
109
+ ? String(pushUrls.stdout || '')
110
+ .split('\n')
111
+ .filter(Boolean).length
112
+ : 0;
113
+ if (pushUrlCount !== 1) {
114
+ throw new SharedGitStateError(
115
+ 'invalid',
116
+ `shared Git remote '${remote}' must resolve to exactly one push URL`
117
+ );
118
+ }
119
+ const readable = spawnGit(repoRoot, ['ls-remote', '--refs', remote], { allowFailure: true });
120
+ if (readable.status !== 0) {
121
+ throw unavailable(remote, readable);
122
+ }
123
+ spawnGit(repoRoot, ['config', '--local', REMOTE_KEY, remote]);
124
+ // Write the enabling flag last so a partial config update stays disabled.
125
+ spawnGit(repoRoot, ['config', '--local', MODE_KEY, MODE]);
126
+ return settings(repoRoot);
127
+ }
128
+
129
+ function disable(repoRoot) {
130
+ if (envHas(process.env, MODE_ENV) && settings(repoRoot).enabled) {
131
+ throw new SharedGitStateError(
132
+ 'invalid',
133
+ `${MODE_ENV} enables shared Git state; unset it before running shared-disable`
134
+ );
135
+ }
136
+ spawnGit(repoRoot, ['config', '--local', '--unset-all', MODE_KEY], { allowFailure: true });
137
+ spawnGit(repoRoot, ['config', '--local', '--unset-all', REMOTE_KEY], { allowFailure: true });
138
+ return settings(repoRoot);
139
+ }
140
+
141
+ function unavailable(remote) {
142
+ // Git commonly echoes credential-bearing remote URLs in stderr. Never copy
143
+ // raw transport errors into agent logs; the configured remote name is safe.
144
+ return new SharedGitStateError(
145
+ 'unavailable',
146
+ `shared Git state unavailable on '${remote}'; check network, authentication, and custom-ref permissions`
147
+ );
148
+ }
149
+
150
+ function requireEnabled(repoRoot) {
151
+ const value = settings(repoRoot);
152
+ if (!value.enabled) {
153
+ throw new SharedGitStateError('disabled', 'shared Git state is not enabled');
154
+ }
155
+ assertRemoteName(value.remote);
156
+ return value;
157
+ }
158
+
159
+ function normalizeRepoPath(repoRoot, rawPath) {
160
+ if (typeof rawPath !== 'string' || !rawPath || /[\u0000-\u001f\u007f-\u009f]/u.test(rawPath)) {
161
+ throw new SharedGitStateError('invalid', 'lock path must be a non-empty path');
162
+ }
163
+ const absolute = path.isAbsolute(rawPath)
164
+ ? path.resolve(rawPath)
165
+ : path.resolve(repoRoot, rawPath);
166
+ const relative = path.relative(path.resolve(repoRoot), absolute);
167
+ if (
168
+ !relative ||
169
+ relative === '..' ||
170
+ relative.startsWith(`..${path.sep}`) ||
171
+ path.isAbsolute(relative)
172
+ ) {
173
+ throw new SharedGitStateError('invalid', `path is outside repository: ${rawPath}`);
174
+ }
175
+ return relative.split(path.sep).join('/');
176
+ }
177
+
178
+ function lockRef(file) {
179
+ return `${LOCK_REF_PREFIX}${crypto.createHash('sha256').update(file).digest('hex')}`;
180
+ }
181
+
182
+ function machineId(env = process.env) {
183
+ const source = String(env.GUARDEX_MACHINE_ID || os.hostname() || 'unknown');
184
+ return crypto.createHash('sha256').update(source).digest('hex').slice(0, 16);
185
+ }
186
+
187
+ function ownerMatches(entry, branch, agent = '') {
188
+ if (!entry || entry.branch !== branch) return false;
189
+ const existingAgent = String(entry.agent || '');
190
+ return !agent || !existingAgent || existingAgent === agent;
191
+ }
192
+
193
+ function ownerLabel(entry) {
194
+ return entry.agent ? `${entry.branch} as ${entry.agent}` : entry.branch;
195
+ }
196
+
197
+ function validateMetadata(value) {
198
+ const stringField = (name, max, { allowEmpty = false } = {}) => {
199
+ const field = value && value[name];
200
+ if (
201
+ typeof field !== 'string' ||
202
+ field.length > max ||
203
+ (!allowEmpty && !field) ||
204
+ /[\u0000-\u001f\u007f-\u009f]/u.test(field)
205
+ ) {
206
+ throw new SharedGitStateError('invalid', `invalid shared Git lock metadata field: ${name}`);
207
+ }
208
+ return field;
209
+ };
210
+ if (!value || value.version !== 1 || value.kind !== 'gitguardex-file-lock') {
211
+ throw new SharedGitStateError('invalid', 'invalid shared Git lock metadata schema');
212
+ }
213
+ const file = stringField('file', 4096);
214
+ if (
215
+ path.posix.isAbsolute(file) ||
216
+ path.posix.normalize(file) !== file ||
217
+ file === '..' ||
218
+ file.startsWith('../')
219
+ ) {
220
+ throw new SharedGitStateError('invalid', 'invalid shared Git lock metadata path');
221
+ }
222
+ const claimedAt = stringField('claimedAt', 64);
223
+ if (Number.isNaN(Date.parse(claimedAt))) {
224
+ throw new SharedGitStateError('invalid', 'invalid shared Git lock timestamp');
225
+ }
226
+ return {
227
+ version: 1,
228
+ kind: 'gitguardex-file-lock',
229
+ file,
230
+ branch: stringField('branch', 512),
231
+ agent: stringField('agent', 256, { allowEmpty: true }),
232
+ allowDelete: value.allowDelete === true,
233
+ claimedAt,
234
+ machine: stringField('machine', 64)
235
+ };
236
+ }
237
+
238
+ function parseRemoteRefs(output, prefix) {
239
+ if (!output) return [];
240
+ const rows = [];
241
+ for (const line of output.split('\n')) {
242
+ const [oid, ref, extra] = line.trim().split(/\s+/);
243
+ if (
244
+ extra ||
245
+ !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(oid || '') ||
246
+ !ref ||
247
+ !ref.startsWith(prefix)
248
+ ) {
249
+ throw new SharedGitStateError(
250
+ 'invalid',
251
+ 'remote returned an invalid shared Git ref advertisement'
252
+ );
253
+ }
254
+ rows.push({ oid, ref });
255
+ }
256
+ return rows;
257
+ }
258
+
259
+ function listRemoteRefs(repoRoot, remote, pattern, prefix) {
260
+ const result = spawnGit(repoRoot, ['ls-remote', '--refs', remote, pattern], {
261
+ allowFailure: true
262
+ });
263
+ if (result.status !== 0) throw unavailable(remote, result);
264
+ return parseRemoteRefs(String(result.stdout || '').trim(), prefix);
265
+ }
266
+
267
+ function parseCommitMetadata(raw) {
268
+ const separator = raw.indexOf('\n\n');
269
+ if (separator < 0)
270
+ throw new SharedGitStateError('invalid', 'shared Git lock object is not a commit');
271
+ const body = raw.slice(separator + 2).trim();
272
+ if (!body || body.length > 16 * 1024) {
273
+ throw new SharedGitStateError('invalid', 'shared Git lock metadata has an invalid size');
274
+ }
275
+ let parsed;
276
+ try {
277
+ parsed = JSON.parse(body);
278
+ } catch {
279
+ throw new SharedGitStateError('invalid', 'shared Git lock metadata is not valid JSON');
280
+ }
281
+ return validateMetadata(parsed);
282
+ }
283
+
284
+ function readCommitLock(repoRoot, oid, ref) {
285
+ const raw = spawnGit(repoRoot, ['cat-file', 'commit', oid]);
286
+ const metadata = parseCommitMetadata(raw);
287
+ if (lockRef(metadata.file) !== ref) {
288
+ throw new SharedGitStateError(
289
+ 'invalid',
290
+ 'shared Git lock ref does not match its file metadata'
291
+ );
292
+ }
293
+ return { oid, ref, ...metadata };
294
+ }
295
+
296
+ function readAdvertisedLock(repoRoot, config, advertised) {
297
+ const token = `${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
298
+ const localRef = `refs/gitguardex/cache/${token}`;
299
+ try {
300
+ const fetched = spawnGit(
301
+ repoRoot,
302
+ [
303
+ 'fetch',
304
+ '--quiet',
305
+ '--no-tags',
306
+ '--no-write-fetch-head',
307
+ config.remote,
308
+ `${advertised.ref}:${localRef}`
309
+ ],
310
+ { allowFailure: true }
311
+ );
312
+ if (fetched.status !== 0) throw unavailable(config.remote, fetched);
313
+ const oid = spawnGit(repoRoot, ['rev-parse', '--verify', localRef]);
314
+ return readCommitLock(repoRoot, oid, advertised.ref);
315
+ } finally {
316
+ spawnGit(repoRoot, ['update-ref', '-d', localRef], { allowFailure: true });
317
+ }
318
+ }
319
+
320
+ function getLock(repoRoot, rawFile) {
321
+ const config = requireEnabled(repoRoot);
322
+ const file = normalizeRepoPath(repoRoot, rawFile);
323
+ const ref = lockRef(file);
324
+ const refs = listRemoteRefs(repoRoot, config.remote, ref, LOCK_REF_PREFIX);
325
+ return refs.length ? readAdvertisedLock(repoRoot, config, refs[0]) : null;
326
+ }
327
+
328
+ function listLocks(repoRoot) {
329
+ const config = requireEnabled(repoRoot);
330
+ const refs = listRemoteRefs(repoRoot, config.remote, `${LOCK_REF_PREFIX}*`, LOCK_REF_PREFIX);
331
+ if (refs.length > MAX_REMOTE_LOCKS) {
332
+ throw new SharedGitStateError(
333
+ 'invalid',
334
+ `shared Git state exceeds ${MAX_REMOTE_LOCKS} lock refs`
335
+ );
336
+ }
337
+ if (refs.length === 0) return [];
338
+
339
+ // Fetch all advertised lock commits in one round-trip. A random local cache
340
+ // namespace prevents concurrent gx processes from sharing mutable refs.
341
+ const token = `${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
342
+ const localPrefix = `refs/gitguardex/cache/${token}/`;
343
+ let localRefs = [];
344
+ try {
345
+ const fetched = spawnGit(
346
+ repoRoot,
347
+ [
348
+ 'fetch',
349
+ '--quiet',
350
+ '--no-tags',
351
+ '--no-write-fetch-head',
352
+ config.remote,
353
+ `${LOCK_REF_PREFIX}*:${localPrefix}*`
354
+ ],
355
+ { allowFailure: true }
356
+ );
357
+ if (fetched.status !== 0) throw unavailable(config.remote, fetched);
358
+ const listed = spawnGit(repoRoot, [
359
+ 'for-each-ref',
360
+ '--format=%(objectname) %(refname)',
361
+ localPrefix
362
+ ]);
363
+ localRefs = parseRemoteRefs(listed, localPrefix);
364
+ if (localRefs.length > MAX_REMOTE_LOCKS) {
365
+ throw new SharedGitStateError(
366
+ 'invalid',
367
+ `shared Git state exceeds ${MAX_REMOTE_LOCKS} lock refs`
368
+ );
369
+ }
370
+ return localRefs.map(({ oid, ref }) => {
371
+ const remoteRef = `${LOCK_REF_PREFIX}${ref.slice(localPrefix.length)}`;
372
+ return readCommitLock(repoRoot, oid, remoteRef);
373
+ });
374
+ } finally {
375
+ if (localRefs.length === 0) {
376
+ const listed = spawnGit(
377
+ repoRoot,
378
+ ['for-each-ref', '--format=%(objectname) %(refname)', localPrefix],
379
+ { allowFailure: true }
380
+ );
381
+ if (listed.status === 0) {
382
+ localRefs = parseRemoteRefs(String(listed.stdout || '').trim(), localPrefix);
383
+ }
384
+ }
385
+ for (const entry of localRefs) {
386
+ spawnGit(repoRoot, ['update-ref', '-d', entry.ref], { allowFailure: true });
387
+ }
388
+ }
389
+ }
390
+
391
+ function createMetadataCommit(repoRoot, metadata) {
392
+ const tree = spawnGit(repoRoot, ['mktree'], { input: '' });
393
+ const identity = {
394
+ GIT_AUTHOR_NAME: 'GitGuardex shared state',
395
+ GIT_AUTHOR_EMAIL: 'shared-state@gitguardex.invalid',
396
+ GIT_COMMITTER_NAME: 'GitGuardex shared state',
397
+ GIT_COMMITTER_EMAIL: 'shared-state@gitguardex.invalid'
398
+ };
399
+ return spawnGit(repoRoot, ['commit-tree', tree], {
400
+ input: `${JSON.stringify(metadata)}\n`,
401
+ env: identity
402
+ });
403
+ }
404
+
405
+ function pushWithLease(repoRoot, config, sourceOid, ref, expectedOid = '') {
406
+ const result = spawnGit(
407
+ repoRoot,
408
+ [
409
+ 'push',
410
+ '--porcelain',
411
+ `--force-with-lease=${ref}:${expectedOid}`,
412
+ config.remote,
413
+ `${sourceOid}:${ref}`
414
+ ],
415
+ { allowFailure: true }
416
+ );
417
+ if (result.status !== 0) throw unavailable(config.remote, result);
418
+ }
419
+
420
+ function deleteWithLease(repoRoot, config, ref, expectedOid) {
421
+ const result = spawnGit(
422
+ repoRoot,
423
+ ['push', '--porcelain', `--force-with-lease=${ref}:${expectedOid}`, config.remote, `:${ref}`],
424
+ { allowFailure: true }
425
+ );
426
+ if (result.status !== 0) throw unavailable(config.remote, result);
427
+ }
428
+
429
+ function claimLock(repoRoot, { file: rawFile, branch, agent = '', allowDelete = false }) {
430
+ const config = requireEnabled(repoRoot);
431
+ const file = normalizeRepoPath(repoRoot, rawFile);
432
+ if (!branch || typeof branch !== 'string' || /[\0\r\n]/.test(branch)) {
433
+ throw new SharedGitStateError('invalid', 'shared Git lock requires a branch');
434
+ }
435
+ let previous = getLock(repoRoot, file);
436
+ for (let attempt = 0; attempt < 2; attempt += 1) {
437
+ if (previous && !ownerMatches(previous, branch, agent)) {
438
+ throw new SharedGitStateError(
439
+ 'conflict',
440
+ `shared Git lock for '${file}' is owned by ${ownerLabel(previous)}`,
441
+ { owner: previous }
442
+ );
443
+ }
444
+ const metadata = validateMetadata({
445
+ version: 1,
446
+ kind: 'gitguardex-file-lock',
447
+ file,
448
+ branch,
449
+ agent: agent || (previous && previous.agent) || '',
450
+ allowDelete: allowDelete || Boolean(previous && previous.allowDelete),
451
+ claimedAt: new Date().toISOString(),
452
+ machine: machineId()
453
+ });
454
+ const oid = createMetadataCommit(repoRoot, metadata);
455
+ try {
456
+ pushWithLease(repoRoot, config, oid, lockRef(file), previous ? previous.oid : '');
457
+ return { current: { oid, ref: lockRef(file), ...metadata }, previous };
458
+ } catch (error) {
459
+ const current = getLock(repoRoot, file);
460
+ if (current && (!previous || current.oid !== previous.oid)) {
461
+ previous = current;
462
+ continue;
463
+ }
464
+ throw error;
465
+ }
466
+ }
467
+ throw new SharedGitStateError('conflict', `shared Git lock for '${file}' changed concurrently`);
468
+ }
469
+
470
+ function releaseLock(repoRoot, { file: rawFile, branch, agent = '' }) {
471
+ const config = requireEnabled(repoRoot);
472
+ const file = normalizeRepoPath(repoRoot, rawFile);
473
+ let existing = getLock(repoRoot, file);
474
+ if (!existing) return { released: false, previous: null };
475
+ for (let attempt = 0; attempt < 2; attempt += 1) {
476
+ if (!ownerMatches(existing, branch, agent)) {
477
+ throw new SharedGitStateError(
478
+ 'conflict',
479
+ `shared Git lock for '${file}' is owned by ${ownerLabel(existing)}`,
480
+ { owner: existing }
481
+ );
482
+ }
483
+ try {
484
+ deleteWithLease(repoRoot, config, existing.ref, existing.oid);
485
+ return { released: true, previous: existing };
486
+ } catch (error) {
487
+ const current = getLock(repoRoot, file);
488
+ if (!current) return { released: true, previous: existing };
489
+ if (current.oid !== existing.oid) {
490
+ existing = current;
491
+ continue;
492
+ }
493
+ throw error;
494
+ }
495
+ }
496
+ throw new SharedGitStateError('conflict', `shared Git lock for '${file}' changed concurrently`);
497
+ }
498
+
499
+ function restoreClaim(repoRoot, claim) {
500
+ if (!claim || !claim.current) return;
501
+ const config = requireEnabled(repoRoot);
502
+ const source = claim.previous && claim.previous.oid;
503
+ if (source) {
504
+ pushWithLease(repoRoot, config, source, claim.current.ref, claim.current.oid);
505
+ } else {
506
+ deleteWithLease(repoRoot, config, claim.current.ref, claim.current.oid);
507
+ }
508
+ }
509
+
510
+ function restoreRelease(repoRoot, release) {
511
+ if (!release || !release.released || !release.previous) return;
512
+ const config = requireEnabled(repoRoot);
513
+ pushWithLease(repoRoot, config, release.previous.oid, release.previous.ref, '');
514
+ }
515
+
516
+ function validateLock(repoRoot, { file, branch, agent = '' }) {
517
+ const entry = getLock(repoRoot, file);
518
+ const normalized = normalizeRepoPath(repoRoot, file);
519
+ if (!entry) {
520
+ throw new SharedGitStateError('missing', `shared Git lock is missing for '${normalized}'`);
521
+ }
522
+ if (!ownerMatches(entry, branch, agent)) {
523
+ throw new SharedGitStateError(
524
+ 'conflict',
525
+ `shared Git lock for '${normalized}' is owned by ${ownerLabel(entry)}`,
526
+ { owner: entry }
527
+ );
528
+ }
529
+ return entry;
530
+ }
531
+
532
+ function listRemoteAgentBranches(repoRoot) {
533
+ const config = requireEnabled(repoRoot);
534
+ const prefix = 'refs/heads/agent/';
535
+ const refs = listRemoteRefs(repoRoot, config.remote, `${prefix}*`, prefix);
536
+ if (refs.length > MAX_REMOTE_LOCKS) {
537
+ throw new SharedGitStateError(
538
+ 'invalid',
539
+ `shared Git radar exceeds ${MAX_REMOTE_LOCKS} agent branches`
540
+ );
541
+ }
542
+ return refs.map(({ oid, ref }) => ({ oid, branch: ref.slice('refs/heads/'.length) }));
543
+ }
544
+
545
+ module.exports = {
546
+ SharedGitStateError,
547
+ MODE_KEY,
548
+ REMOTE_KEY,
549
+ MODE_ENV,
550
+ REMOTE_ENV,
551
+ LOCK_REF_PREFIX,
552
+ settings,
553
+ enable,
554
+ disable,
555
+ normalizeRepoPath,
556
+ lockRef,
557
+ ownerMatches,
558
+ getLock,
559
+ listLocks,
560
+ claimLock,
561
+ releaseLock,
562
+ restoreClaim,
563
+ restoreRelease,
564
+ validateLock,
565
+ listRemoteAgentBranches
566
+ };