@imdeadpool/guardex 8.4.0 → 8.4.2
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/CONTRIBUTING.md +13 -4
- package/README.md +223 -1
- package/THIRD-PARTY-NOTICES.md +29 -0
- package/bin/multiagent-safety.js +9 -12
- package/package.json +4 -2
- package/skills/gitguardex/SKILL.md +28 -0
- package/skills/pr-lens/SKILL.md +87 -0
- package/src/abide.js +534 -0
- package/src/agents/activity.js +23 -4
- package/src/agents/inspect.js +15 -6
- package/src/agents/launch.js +6 -1
- package/src/agents/process-lease.js +84 -0
- package/src/agents/sessions.js +96 -16
- package/src/agents/start.js +18 -9
- package/src/agents/status.js +35 -14
- package/src/agents/supervise.js +87 -0
- package/src/budget/index.js +6 -1
- package/src/cli/args.js +71 -77
- package/src/cli/commands/agents.js +38 -10
- package/src/cli/commands/branch.js +116 -103
- package/src/cli/commands/claude.js +604 -50
- package/src/cli/commands/codex.js +359 -0
- package/src/cli/commands/context.js +52 -0
- package/src/cli/commands/mcp.js +5 -1
- package/src/cli/commands/pr.js +138 -3
- package/src/cli/commands/review.js +3 -1
- package/src/cli/commands/setup.js +25 -0
- package/src/cli/commands/status.js +128 -60
- package/src/cli/commands/storage.js +24 -0
- package/src/cli/commands/usage.js +48 -0
- package/src/cli/commands/watch.js +157 -47
- package/src/cli/commands/worktree-copy-ignored.js +38 -0
- package/src/cli/commands/worktree-estimate.js +69 -0
- package/src/cli/commands/worktree-hooks.js +62 -0
- package/src/cli/commands/worktree-navigation.js +71 -0
- package/src/cli/commands/worktree-provision.js +92 -0
- package/src/cli/main.js +229 -110
- package/src/cli/shared/gate-flags.js +131 -0
- package/src/cli/shared/scaffolding.js +31 -3
- package/src/cli/shared-locks.js +3 -1
- package/src/cockpit/pane-actions.js +43 -7
- package/src/context.js +373 -17
- package/src/doctor/index.js +29 -35
- package/src/finish/events.js +254 -0
- package/src/finish/index.js +322 -62
- package/src/finish/post-branch-finish-cleanup.js +316 -22
- package/src/finish/preflight.js +44 -1
- package/src/finish/progress.js +36 -0
- package/src/finish/review-gate.js +317 -127
- package/src/finish/review-receipt.js +156 -0
- package/src/finish/with-claims-lock.py +29 -0
- package/src/git/index.js +179 -42
- package/src/hooks/index.js +68 -3
- package/src/mcp/collect.js +61 -5
- package/src/mcp/server.js +4 -0
- package/src/output/index.js +167 -1
- package/src/pr-lens-publish.js +93 -0
- package/src/pr-lens.js +184 -0
- package/src/pr-respond.js +860 -0
- package/src/pr-review.js +519 -159
- package/src/pr.js +73 -14
- package/src/provider-binary.js +21 -0
- package/src/review-diff-context.js +90 -0
- package/src/review-fix.js +23 -17
- package/src/scaffold/agent-worktree-prep.js +14 -12
- package/src/scaffold/dependency-store.js +234 -0
- package/src/scaffold/index.js +13 -1
- package/src/scaffold/provision-approvals.js +83 -0
- package/src/scaffold/provision-config.js +169 -40
- package/src/shared-git-state.js +11 -1
- package/src/speckit/index.js +12 -1
- package/src/storage/run-artifacts.js +185 -0
- package/src/toolchain/index.js +322 -2
- package/src/worktree-copy-ignored.js +200 -0
- package/src/worktree-hook-worker.js +29 -0
- package/src/worktree-hooks.js +333 -0
- package/src/worktree-navigation.js +248 -0
- package/src/worktree-picker.js +89 -0
- package/src/worktree-quota.js +100 -0
- package/src/worktree-start.js +100 -0
- package/templates/AGENTS.multiagent-safety.md +8 -0
- package/templates/AGENTS.multiagent-safety.min.md +3 -1
- package/templates/codex/skills/gitguardex/SKILL.md +28 -0
- package/templates/codex/skills/opensrc/SKILL.md +24 -0
- package/templates/githooks/post-merge +16 -2
- package/templates/scripts/agent-autofinish-watch.sh +17 -18
- package/templates/scripts/agent-branch-finish.sh +180 -19
- package/templates/scripts/agent-branch-merge.sh +7 -32
- package/templates/scripts/agent-branch-start.sh +202 -43
- package/templates/scripts/agent-claude-stop-finish.sh +4 -27
- package/templates/scripts/agent-file-locks.py +257 -29
- package/templates/scripts/agent-preflight.sh +3 -0
- package/templates/scripts/agent-worktree-prune.sh +975 -63
- package/templates/scripts/codex-agent.sh +55 -5
- package/templates/scripts/lib/guardex-base-branch.sh +207 -0
- package/templates/scripts/openspec/init-change-workspace.sh +10 -18
- package/templates/scripts/review-bot-watch.sh +171 -4
package/src/finish/index.js
CHANGED
|
@@ -29,7 +29,7 @@ const {
|
|
|
29
29
|
parseSyncArgs,
|
|
30
30
|
} = require('../cli/args');
|
|
31
31
|
const submoduleModule = require('../submodule');
|
|
32
|
-
const { runPreflight, summarizePreflight } = require('./preflight');
|
|
32
|
+
const { runPreflight, summarizePreflight, branchPreflightDuringCi } = require('./preflight');
|
|
33
33
|
const { runReviewGate } = require('./review-gate');
|
|
34
34
|
const { createFinishProgress, summarizeFinishRun } = require('./progress');
|
|
35
35
|
|
|
@@ -85,56 +85,56 @@ function shouldSkipBranchPreflight(options = {}) {
|
|
|
85
85
|
* @throws {Error} When the lock-claim or allow-delete subprocess exits non-zero.
|
|
86
86
|
*/
|
|
87
87
|
function claimLocksForAutoCommit(repoRoot, worktreePath, branch) {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
88
|
+
// Use --name-status for both staged and unstaged diffs so changed and
|
|
89
|
+
// deleted files are derived from two git calls instead of four.
|
|
90
|
+
const changedFiles = [];
|
|
91
|
+
const deletedFiles = [];
|
|
92
|
+
for (const args of [
|
|
93
|
+
['diff', '--name-status', '--', '.', `:(exclude)${LOCK_FILE_RELATIVE}`],
|
|
94
|
+
['diff', '--cached', '--name-status', '--', '.', `:(exclude)${LOCK_FILE_RELATIVE}`]
|
|
95
|
+
]) {
|
|
96
|
+
for (const line of gitOutputLines(worktreePath, args)) {
|
|
97
|
+
const tab = line.indexOf('\t');
|
|
98
|
+
if (tab === -1) continue;
|
|
99
|
+
const status = line.slice(0, tab);
|
|
100
|
+
const rest = line.slice(tab + 1);
|
|
101
|
+
// Renames (R100\told\tnew): take the destination name after the second tab.
|
|
102
|
+
const file = rest.includes('\t') ? rest.slice(rest.indexOf('\t') + 1) : rest;
|
|
103
|
+
// Claim deleted files too so ownership is established before the
|
|
104
|
+
// allow-delete step (mirrors the old --name-only which included deletions).
|
|
105
|
+
changedFiles.push(file);
|
|
106
|
+
if (status === 'D') {
|
|
107
|
+
deletedFiles.push(file);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const allChanged = uniquePreserveOrder([
|
|
113
|
+
...changedFiles,
|
|
91
114
|
...gitOutputLines(worktreePath, ['ls-files', '--others', '--exclude-standard']),
|
|
92
115
|
]);
|
|
116
|
+
const allDeleted = uniquePreserveOrder(deletedFiles);
|
|
93
117
|
|
|
94
|
-
if (
|
|
95
|
-
const claim = runPackageAsset('lockTool', ['claim', '--branch', branch, ...
|
|
118
|
+
if (allChanged.length > 0) {
|
|
119
|
+
const claim = runPackageAsset('lockTool', ['claim', '--branch', branch, ...allChanged], {
|
|
96
120
|
cwd: repoRoot,
|
|
97
121
|
stdio: 'pipe',
|
|
98
122
|
});
|
|
99
123
|
if (claim.status !== 0) {
|
|
100
124
|
throw new Error(
|
|
101
|
-
`Lock claim failed for ${branch}: ${(
|
|
102
|
-
claim.stderr || claim.stdout || ''
|
|
103
|
-
).trim()}`,
|
|
125
|
+
`Lock claim failed for ${branch}: ${(claim.stderr || claim.stdout || '').trim()}`,
|
|
104
126
|
);
|
|
105
127
|
}
|
|
106
128
|
}
|
|
107
129
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
'diff',
|
|
111
|
-
'--name-only',
|
|
112
|
-
'--diff-filter=D',
|
|
113
|
-
'--',
|
|
114
|
-
'.',
|
|
115
|
-
':(exclude).omx/state/agent-file-locks.json',
|
|
116
|
-
]),
|
|
117
|
-
...gitOutputLines(worktreePath, [
|
|
118
|
-
'diff',
|
|
119
|
-
'--cached',
|
|
120
|
-
'--name-only',
|
|
121
|
-
'--diff-filter=D',
|
|
122
|
-
'--',
|
|
123
|
-
'.',
|
|
124
|
-
':(exclude).omx/state/agent-file-locks.json',
|
|
125
|
-
]),
|
|
126
|
-
]);
|
|
127
|
-
|
|
128
|
-
if (deletedFiles.length > 0) {
|
|
129
|
-
const allowDelete = runPackageAsset('lockTool', ['allow-delete', '--branch', branch, ...deletedFiles], {
|
|
130
|
+
if (allDeleted.length > 0) {
|
|
131
|
+
const allowDelete = runPackageAsset('lockTool', ['allow-delete', '--branch', branch, ...allDeleted], {
|
|
130
132
|
cwd: repoRoot,
|
|
131
133
|
stdio: 'pipe',
|
|
132
134
|
});
|
|
133
135
|
if (allowDelete.status !== 0) {
|
|
134
136
|
throw new Error(
|
|
135
|
-
`Delete-lock grant failed for ${branch}: ${(
|
|
136
|
-
allowDelete.stderr || allowDelete.stdout || ''
|
|
137
|
-
).trim()}`,
|
|
137
|
+
`Delete-lock grant failed for ${branch}: ${(allowDelete.stderr || allowDelete.stdout || '').trim()}`,
|
|
138
138
|
);
|
|
139
139
|
}
|
|
140
140
|
}
|
|
@@ -167,6 +167,9 @@ function autoCommitWorktreeForFinish(repoRoot, worktreePath, branch, options) {
|
|
|
167
167
|
return { changed: true, committed: false, dryRun: true };
|
|
168
168
|
}
|
|
169
169
|
|
|
170
|
+
const { runLifecycleHookSync } = require('../worktree-hooks');
|
|
171
|
+
runLifecycleHookSync(repoRoot, 'pre-commit', { worktreePath, branch });
|
|
172
|
+
// Hooks may generate files; claim through GX before staging.
|
|
170
173
|
claimLocksForAutoCommit(repoRoot, worktreePath, branch);
|
|
171
174
|
|
|
172
175
|
const addResult = run('git', ['-C', worktreePath, 'add', '-A'], { stdio: 'pipe' });
|
|
@@ -198,17 +201,111 @@ function autoCommitWorktreeForFinish(repoRoot, worktreePath, branch, options) {
|
|
|
198
201
|
);
|
|
199
202
|
}
|
|
200
203
|
|
|
204
|
+
try {
|
|
205
|
+
runLifecycleHookSync(repoRoot, 'post-commit', { worktreePath, branch });
|
|
206
|
+
} catch (error) {
|
|
207
|
+
console.error(`[${TOOL_NAME}] Commit succeeded; post-commit hook failed: ${error.message}`);
|
|
208
|
+
}
|
|
201
209
|
return { changed: true, committed: true, message: commitMessage };
|
|
202
210
|
}
|
|
203
211
|
|
|
212
|
+
/** Maximum backoff between watch cycles: 15 minutes. */
|
|
213
|
+
const BACKOFF_CAP_SECONDS = 900;
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Run the cleanup watch loop, calling `runCycle` on each iteration.
|
|
217
|
+
*
|
|
218
|
+
* Failed cycles are caught and logged (with cycle number and error message).
|
|
219
|
+
* Consecutive failures trigger exponential backoff on the sleep interval
|
|
220
|
+
* (interval × 2^n, capped at {@link BACKOFF_CAP_SECONDS}). After
|
|
221
|
+
* `maxFailures` consecutive failures the function returns 1 so the caller can
|
|
222
|
+
* signal a permanently-broken setup to a supervisor such as systemd. A
|
|
223
|
+
* successful cycle resets the consecutive-failure counter and backoff.
|
|
224
|
+
*
|
|
225
|
+
* SIGINT / SIGTERM are detected via the sleep subprocess's `.signal` field;
|
|
226
|
+
* when either arrives the loop exits cleanly (returns 0).
|
|
227
|
+
*
|
|
228
|
+
* @param {function(): void} runCycle
|
|
229
|
+
* Runs one prune cycle; throws on failure.
|
|
230
|
+
* @param {object} opts
|
|
231
|
+
* @param {number} opts.intervalSeconds Nominal interval between cycles (seconds).
|
|
232
|
+
* @param {number} opts.maxFailures Exit non-zero after this many consecutive failures.
|
|
233
|
+
* @param {string} opts.repoRoot Working directory for the sleep subprocess.
|
|
234
|
+
* @param {number} [opts.idleMinutes] Idle threshold (passed through to log line only).
|
|
235
|
+
* @param {number} [opts.maxBranches] Branch cap (passed through to log line only).
|
|
236
|
+
* @param {boolean} [opts.once] Exit after one cycle regardless.
|
|
237
|
+
* @param {function(number): {status: number|null, signal?: string|null}} [opts._runSleep]
|
|
238
|
+
* Injectable sleep function for unit tests. Default: spawnSync('sleep', [n]).
|
|
239
|
+
* @returns {number} 0 on clean exit, 1 when maxFailures is reached.
|
|
240
|
+
*/
|
|
241
|
+
function runCleanupWatchLoop(runCycle, opts) {
|
|
242
|
+
const {
|
|
243
|
+
intervalSeconds,
|
|
244
|
+
maxFailures,
|
|
245
|
+
repoRoot,
|
|
246
|
+
once,
|
|
247
|
+
idleMinutes = 0,
|
|
248
|
+
maxBranches = 0,
|
|
249
|
+
} = opts;
|
|
250
|
+
const runSleep =
|
|
251
|
+
opts._runSleep ||
|
|
252
|
+
((s) => run('sleep', [String(s)], { cwd: repoRoot }));
|
|
253
|
+
|
|
254
|
+
let cycle = 0;
|
|
255
|
+
let consecutiveFailures = 0;
|
|
256
|
+
|
|
257
|
+
while (true) {
|
|
258
|
+
cycle += 1;
|
|
259
|
+
console.log(
|
|
260
|
+
`[${TOOL_NAME}] Cleanup watch cycle=${cycle} (interval=${intervalSeconds}s, idleMinutes=${idleMinutes}, maxBranches=${maxBranches > 0 ? maxBranches : 'unbounded'}).`,
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
try {
|
|
264
|
+
runCycle();
|
|
265
|
+
consecutiveFailures = 0;
|
|
266
|
+
} catch (error) {
|
|
267
|
+
consecutiveFailures += 1;
|
|
268
|
+
console.error(
|
|
269
|
+
`[${TOOL_NAME}] Cleanup watch cycle=${cycle} FAILED (consecutive=${consecutiveFailures}): ${error.message}`,
|
|
270
|
+
);
|
|
271
|
+
if (consecutiveFailures >= maxFailures) {
|
|
272
|
+
console.error(
|
|
273
|
+
`[${TOOL_NAME}] Cleanup watch exiting after ${consecutiveFailures} consecutive failures (--max-failures=${maxFailures}).`,
|
|
274
|
+
);
|
|
275
|
+
return 1;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (once) {
|
|
280
|
+
// Propagate failure: exit 1 when the cycle failed (mirrors one-shot mode).
|
|
281
|
+
return consecutiveFailures > 0 ? 1 : 0;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const backoffSeconds =
|
|
285
|
+
consecutiveFailures > 0
|
|
286
|
+
? Math.min(intervalSeconds * 2 ** consecutiveFailures, BACKOFF_CAP_SECONDS)
|
|
287
|
+
: intervalSeconds;
|
|
288
|
+
|
|
289
|
+
const sleepResult = runSleep(backoffSeconds);
|
|
290
|
+
if (sleepResult.signal === 'SIGINT' || sleepResult.signal === 'SIGTERM') {
|
|
291
|
+
return 0;
|
|
292
|
+
}
|
|
293
|
+
if (sleepResult.status !== 0) {
|
|
294
|
+
throw new Error(`Cleanup watch sleep failed (interval=${backoffSeconds}s)`);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
204
299
|
/**
|
|
205
300
|
* Run the worktree-prune sweep with options parsed from `rawArgs`. In watch
|
|
206
|
-
* mode loops
|
|
207
|
-
* delegating each cycle to the `worktreePrune` package asset.
|
|
301
|
+
* mode loops until stopped (or until `--once`), printing the cycle header and
|
|
302
|
+
* delegating each cycle to the `worktreePrune` package asset. Failed cycles
|
|
303
|
+
* are logged and the loop continues with exponential backoff; after
|
|
304
|
+
* `--max-failures` consecutive failures the watcher exits non-zero.
|
|
208
305
|
*
|
|
209
306
|
* @param {ReadonlyArray<string>} rawArgs CLI argv slice for the cleanup command.
|
|
210
307
|
* @returns {void}
|
|
211
|
-
* @throws {Error} When the
|
|
308
|
+
* @throws {Error} When the watch sleep subprocess itself fails (not the prune cycle).
|
|
212
309
|
*/
|
|
213
310
|
function cleanup(rawArgs) {
|
|
214
311
|
if (rawArgs.some((arg) => arg === '--help' || arg === '-h') || (rawArgs.length === 1 && rawArgs[0] === 'help')) {
|
|
@@ -227,11 +324,17 @@ OPTIONS
|
|
|
227
324
|
--keep-clean-worktrees Preserve clean, unmerged agent worktrees (default)
|
|
228
325
|
--include-clean-linked-worktrees
|
|
229
326
|
Also prune clean linked worktrees outside managed agent directories
|
|
230
|
-
--include-
|
|
327
|
+
--include-merged-linked-worktrees
|
|
328
|
+
Also prune linked worktrees outside managed agent directories,
|
|
329
|
+
but only merged agent lanes (what the cleanup bot uses)
|
|
330
|
+
--include-pr-merged Treat branches from merged PRs as merged (default; needs gh)
|
|
331
|
+
--no-include-pr-merged Judge merged by git ancestry only (misses squash merges)
|
|
231
332
|
--idle-minutes <n> Only consider worktrees idle for at least n minutes
|
|
232
333
|
--watch Repeat cleanup cycles (defaults idle threshold to 60)
|
|
233
334
|
--interval <seconds> Watch interval in seconds (minimum: 5; default: 60)
|
|
234
335
|
--once Run one cleanup cycle when used with --watch
|
|
336
|
+
--max-failures <n> Exit watch non-zero after n consecutive failures
|
|
337
|
+
(default: 10; also env GUARDEX_CLEANUP_WATCH_MAX_FAILURES)
|
|
235
338
|
--max-branches <n> Limit branches processed per cycle
|
|
236
339
|
-h, --help Show this help`);
|
|
237
340
|
process.exitCode = 0;
|
|
@@ -261,6 +364,9 @@ OPTIONS
|
|
|
261
364
|
if (options.includeCleanLinkedWorktrees) {
|
|
262
365
|
args.push('--include-clean-linked-worktrees');
|
|
263
366
|
}
|
|
367
|
+
if (options.includeMergedLinkedWorktrees) {
|
|
368
|
+
args.push('--include-merged-linked-worktrees');
|
|
369
|
+
}
|
|
264
370
|
if (options.includePrMerged) {
|
|
265
371
|
args.push('--include-pr-merged');
|
|
266
372
|
}
|
|
@@ -287,22 +393,14 @@ OPTIONS
|
|
|
287
393
|
};
|
|
288
394
|
|
|
289
395
|
if (options.watch) {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
break;
|
|
299
|
-
}
|
|
300
|
-
const sleepResult = run('sleep', [String(options.intervalSeconds)], { cwd: repoRoot });
|
|
301
|
-
if (sleepResult.status !== 0) {
|
|
302
|
-
throw new Error(`Cleanup watch sleep failed (interval=${options.intervalSeconds}s)`);
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
process.exitCode = 0;
|
|
396
|
+
process.exitCode = runCleanupWatchLoop(runCleanupCycle, {
|
|
397
|
+
intervalSeconds: options.intervalSeconds,
|
|
398
|
+
maxFailures: options.maxFailures,
|
|
399
|
+
idleMinutes: options.idleMinutes,
|
|
400
|
+
maxBranches: options.maxBranches,
|
|
401
|
+
repoRoot,
|
|
402
|
+
once: options.once,
|
|
403
|
+
});
|
|
306
404
|
return;
|
|
307
405
|
}
|
|
308
406
|
|
|
@@ -379,8 +477,12 @@ function shouldSweepOrphans(options, failed) {
|
|
|
379
477
|
}
|
|
380
478
|
|
|
381
479
|
function finish(rawArgs, defaults = {}) {
|
|
480
|
+
if (rawArgs[0] === 'events') return require('./events').finishEvents(rawArgs.slice(1));
|
|
382
481
|
const activeCwd = process.cwd();
|
|
383
482
|
const options = parseFinishArgs(rawArgs, defaults);
|
|
483
|
+
if (options.gateReview && options.mergeMode !== 'pr') {
|
|
484
|
+
throw new Error('--gate-review requires a PR finish; direct/local modes are incompatible.');
|
|
485
|
+
}
|
|
384
486
|
const repoRoot = resolveRepoRoot(options.target);
|
|
385
487
|
|
|
386
488
|
const worktreeEntries = listAgentWorktrees(repoRoot);
|
|
@@ -571,9 +673,15 @@ function finish(rawArgs, defaults = {}) {
|
|
|
571
673
|
// green CI + GitHub-mergeable verdict BEFORE the shell merge runs. Throws on
|
|
572
674
|
// failure, which the catch below turns into a finish failure (no merge).
|
|
573
675
|
let gateResult;
|
|
676
|
+
if (shouldSkipBranchPreflight(options)) {
|
|
677
|
+
finishArgs.push('--no-preflight');
|
|
678
|
+
}
|
|
574
679
|
if (options.mergeMode === 'pr' && options.gateReview) {
|
|
575
680
|
gateResult = runReviewGate({
|
|
576
681
|
repoRoot, worktreePath, branch, baseBranch, options, progress,
|
|
682
|
+
preflight: branchPreflightDuringCi(repoRoot, finishArgs, {
|
|
683
|
+
activeCwd, agentQuiet: options.agentQuiet, progress,
|
|
684
|
+
}),
|
|
577
685
|
});
|
|
578
686
|
} else {
|
|
579
687
|
progress.skip('review', 'review gate disabled');
|
|
@@ -581,10 +689,6 @@ function finish(rawArgs, defaults = {}) {
|
|
|
581
689
|
progress.skip('ci', 'review gate disabled; repository policy controls merge readiness');
|
|
582
690
|
}
|
|
583
691
|
|
|
584
|
-
if (shouldSkipBranchPreflight(options)) {
|
|
585
|
-
finishArgs.push('--no-preflight');
|
|
586
|
-
}
|
|
587
|
-
|
|
588
692
|
// Streamed, not piped: the script can sit for minutes waiting on the PR
|
|
589
693
|
// merge, and buffering means the operator sees nothing until it exits —
|
|
590
694
|
// and sees NOTHING AT ALL if the process is killed while waiting, since
|
|
@@ -603,7 +707,10 @@ function finish(rawArgs, defaults = {}) {
|
|
|
603
707
|
GUARDEX_FINISH_ACTIVE_CWD: activeCwd,
|
|
604
708
|
GUARDEX_FINISH_CHECKLIST: '1',
|
|
605
709
|
GUARDEX_FINISH_GATE_DONE: options.gateReview ? '1' : '0',
|
|
606
|
-
|
|
710
|
+
GUARDEX_FINISH_PREFLIGHT_ONLY: '0',
|
|
711
|
+
GUARDEX_FINISH_REVIEWED_HEAD: gateResult?.reviewedHeadSha || '',
|
|
712
|
+
GUARDEX_FINISH_REVIEWED_BASE: gateResult?.reviewedBaseSha || '',
|
|
713
|
+
GUARDEX_FINISH_REQUIRE_PREFLIGHT: gateResult?.requiresLocalPreflight ? '1' : '0',
|
|
607
714
|
...progress.eventEnv,
|
|
608
715
|
},
|
|
609
716
|
});
|
|
@@ -623,7 +730,7 @@ function finish(rawArgs, defaults = {}) {
|
|
|
623
730
|
if (finishResult.stderr) process.stderr.write(finishResult.stderr);
|
|
624
731
|
}
|
|
625
732
|
if (finishResult.status !== 0) {
|
|
626
|
-
throw new Error(`agent-branch-finish exited with status ${finishResult.status}`);
|
|
733
|
+
throw new Error(`agent-branch-finish exited with status (${finishResult.status}); re-run: gx branch finish --branch "${branch}"`);
|
|
627
734
|
}
|
|
628
735
|
|
|
629
736
|
succeeded += 1;
|
|
@@ -678,6 +785,158 @@ function finish(rawArgs, defaults = {}) {
|
|
|
678
785
|
process.exitCode = 0;
|
|
679
786
|
}
|
|
680
787
|
|
|
788
|
+
/**
|
|
789
|
+
* Restore the lock-registry backup after a sync, merging any concurrent
|
|
790
|
+
* claims that arrived during the operation instead of overwriting them.
|
|
791
|
+
*
|
|
792
|
+
* Attempts to hold the same cross-worktree OS advisory lock the Python
|
|
793
|
+
* claims tool uses (`<common-git-dir>/agent-file-locks.lock`, via
|
|
794
|
+
* `with-claims-lock.py`) so the read → merge → rename window is serialised
|
|
795
|
+
* against concurrent `gx locks claim` calls. Falls back to a lock-free merge
|
|
796
|
+
* when python3 or the helper script is unavailable.
|
|
797
|
+
*
|
|
798
|
+
* Merge rule (current-first):
|
|
799
|
+
* 1. Start with the current on-disk state as the base, which preserves:
|
|
800
|
+
* - concurrent claims added by other agents during the sync, and
|
|
801
|
+
* - intentional releases (entries absent from current were removed
|
|
802
|
+
* while the lock file was reset, and must not be re-introduced).
|
|
803
|
+
* 2. Add backup-only entries (those in backup but absent from current)
|
|
804
|
+
* so original pre-sync claims by other agents survive the reset.
|
|
805
|
+
* 3. Drop current-only entries that belong to `syncBranch`, the branch
|
|
806
|
+
* performing the sync. These are ghost claims left by a failed prior
|
|
807
|
+
* commit/finish step and must not be re-introduced.
|
|
808
|
+
*
|
|
809
|
+
* @param {string} repoRoot Working-tree root of the repository.
|
|
810
|
+
* @param {string} lockPath Absolute path to `.omx/state/agent-file-locks.json`.
|
|
811
|
+
* @param {string} backup Raw JSON text saved before the sync began.
|
|
812
|
+
* @param {string} [syncBranch] The agent branch performing the sync. When
|
|
813
|
+
* provided, current-only entries whose `branch` field matches are dropped
|
|
814
|
+
* (ghost-claim prevention). Omit when the caller does not know the branch.
|
|
815
|
+
*/
|
|
816
|
+
function restoreLockBackupSafe(repoRoot, lockPath, backup, syncBranch) {
|
|
817
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
|
|
818
|
+
|
|
819
|
+
// Resolve the common .git dir so we can find the cross-worktree flock path
|
|
820
|
+
// (the same mutex scripts/agent-file-locks.py uses via cross_worktree_lock).
|
|
821
|
+
const commonResult = gitRun(repoRoot, ['rev-parse', '--git-common-dir'], { allowFailure: true });
|
|
822
|
+
const flockPath =
|
|
823
|
+
commonResult.status === 0
|
|
824
|
+
? path.resolve(repoRoot, String(commonResult.stdout || '').trim(), 'agent-file-locks.lock')
|
|
825
|
+
: null;
|
|
826
|
+
|
|
827
|
+
const withLockScript = path.join(__dirname, 'with-claims-lock.py');
|
|
828
|
+
|
|
829
|
+
if (flockPath && fs.existsSync(withLockScript)) {
|
|
830
|
+
// Write the backup to a temp file so the inline Node script can read it
|
|
831
|
+
// instead of receiving it as a command-line argument. Embedding it in the
|
|
832
|
+
// argument would fail with E2BIG once the registry exceeds ~128 KiB on Linux.
|
|
833
|
+
const backupTmpPath = `${lockPath}.${process.pid}.backup.tmp`;
|
|
834
|
+
fs.writeFileSync(backupTmpPath, backup, 'utf8');
|
|
835
|
+
|
|
836
|
+
// Compact inline Node script executed under the OS flock.
|
|
837
|
+
// Applies a current-first merge: starts with current on-disk state
|
|
838
|
+
// (preserves concurrent claims and intentional releases), adds backup-only
|
|
839
|
+
// entries (pre-sync claims by other agents), and drops current-only entries
|
|
840
|
+
// that belong to syncBranch (ghost claims from a failed prior step).
|
|
841
|
+
// Uses Object.create(null) to avoid prototype-property false positives on
|
|
842
|
+
// filenames like "constructor". Writes via temp+rename for atomicity.
|
|
843
|
+
const mergeScript = [
|
|
844
|
+
'var fs=require("fs"),p=require("path");',
|
|
845
|
+
`var lp=${JSON.stringify(lockPath)},bkp=${JSON.stringify(backupTmpPath)},sb=${JSON.stringify(syncBranch || '')};`,
|
|
846
|
+
'var b={},c={};',
|
|
847
|
+
'b=JSON.parse(fs.readFileSync(bkp,"utf8"));',
|
|
848
|
+
'try{fs.unlinkSync(bkp);}catch(e){}',
|
|
849
|
+
'try{c=JSON.parse(fs.readFileSync(lp,"utf8"));}catch(e){if(e.code!=="ENOENT")throw e;}',
|
|
850
|
+
'var bl=b.locks||{},cl=c.locks||{};',
|
|
851
|
+
'var ml=Object.create(null);',
|
|
852
|
+
// Step 1: start with current state, dropping current-only ghost claims
|
|
853
|
+
// (entries in current but NOT in backup that belong to syncBranch).
|
|
854
|
+
'Object.keys(cl).forEach(function(k){',
|
|
855
|
+
' var e=cl[k];',
|
|
856
|
+
' if(sb&&e&&e.branch===sb&&!Object.prototype.hasOwnProperty.call(bl,k))return;',
|
|
857
|
+
' ml[k]=e;',
|
|
858
|
+
'});',
|
|
859
|
+
// Step 2: add backup-only entries (pre-sync claims not yet in current).
|
|
860
|
+
'Object.keys(bl).forEach(function(k){',
|
|
861
|
+
' if(!Object.prototype.hasOwnProperty.call(ml,k))ml[k]=bl[k];',
|
|
862
|
+
'});',
|
|
863
|
+
'var out=JSON.stringify(Object.assign({},b,{locks:ml}),null,2)+"\\n";',
|
|
864
|
+
'var tmp=lp+".tmp";',
|
|
865
|
+
'fs.mkdirSync(p.dirname(lp),{recursive:true});',
|
|
866
|
+
'fs.writeFileSync(tmp,out,"utf8");',
|
|
867
|
+
'fs.renameSync(tmp,lp);',
|
|
868
|
+
].join('');
|
|
869
|
+
|
|
870
|
+
let result;
|
|
871
|
+
try {
|
|
872
|
+
result = run('python3', [withLockScript, flockPath, process.execPath, '-e', mergeScript], {
|
|
873
|
+
cwd: repoRoot,
|
|
874
|
+
});
|
|
875
|
+
} finally {
|
|
876
|
+
// Clean up the backup temp file if python3 did not (e.g. it crashed
|
|
877
|
+
// before the inline script ran). Ignore ENOENT — the script removed it.
|
|
878
|
+
try {
|
|
879
|
+
fs.unlinkSync(backupTmpPath);
|
|
880
|
+
} catch (_) {}
|
|
881
|
+
}
|
|
882
|
+
if (result.status === 0) return;
|
|
883
|
+
// Distinguish: if python3 could not be spawned at all (e.g. not installed,
|
|
884
|
+
// result.error is ENOENT), treat it as unavailable and fall through to the
|
|
885
|
+
// lock-free merge below — the mutex was never acquired so no claims are at
|
|
886
|
+
// risk. Only throw when python3 was spawned successfully but exited non-zero,
|
|
887
|
+
// which means the flock may still be held.
|
|
888
|
+
if (!result.error) {
|
|
889
|
+
throw new Error(
|
|
890
|
+
`Lock-registry restore failed while acquiring or holding the claims lock (status ${result.status})`
|
|
891
|
+
);
|
|
892
|
+
}
|
|
893
|
+
// python3 spawn failed — fall through to lock-free fallback
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// Fallback: merge without flock. Only reached when python3 or the helper
|
|
897
|
+
// script is unavailable (flockPath resolved but withLockScript absent, no
|
|
898
|
+
// common .git dir, or python3 could not be spawned). Best-effort — no mutex
|
|
899
|
+
// protection — but still preserves new entries instead of silently
|
|
900
|
+
// overwriting them. Applies the same current-first merge as the flock path.
|
|
901
|
+
// Uses Object.create(null) so filenames like "constructor" / "toString"
|
|
902
|
+
// cannot match inherited properties. Per-process unique temp name prevents
|
|
903
|
+
// two concurrent fallback restores from clobbering each other's temp file.
|
|
904
|
+
let merged;
|
|
905
|
+
try {
|
|
906
|
+
const backupState = JSON.parse(backup);
|
|
907
|
+
const backupLocks = backupState.locks || {};
|
|
908
|
+
let currentState = {};
|
|
909
|
+
try {
|
|
910
|
+
currentState = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
|
|
911
|
+
} catch (_) {}
|
|
912
|
+
const currentLocks = currentState.locks || {};
|
|
913
|
+
const mergedLocks = Object.create(null);
|
|
914
|
+
// Step 1: start with current state, dropping current-only ghost claims
|
|
915
|
+
// (entries in current but NOT in backup that belong to syncBranch).
|
|
916
|
+
for (const [k, v] of Object.entries(currentLocks)) {
|
|
917
|
+
if (
|
|
918
|
+
syncBranch &&
|
|
919
|
+
v &&
|
|
920
|
+
v.branch === syncBranch &&
|
|
921
|
+
!Object.prototype.hasOwnProperty.call(backupLocks, k)
|
|
922
|
+
) {
|
|
923
|
+
continue; // ghost claim — skip
|
|
924
|
+
}
|
|
925
|
+
mergedLocks[k] = v;
|
|
926
|
+
}
|
|
927
|
+
// Step 2: add backup-only entries (pre-sync claims not yet in current).
|
|
928
|
+
for (const [k, v] of Object.entries(backupLocks)) {
|
|
929
|
+
if (!Object.prototype.hasOwnProperty.call(mergedLocks, k)) mergedLocks[k] = v;
|
|
930
|
+
}
|
|
931
|
+
merged = JSON.stringify({ ...backupState, locks: { ...mergedLocks } }, null, 2) + '\n';
|
|
932
|
+
} catch (_) {
|
|
933
|
+
merged = backup; // raw fallback when backup is not valid JSON
|
|
934
|
+
}
|
|
935
|
+
const tmpPath = `${lockPath}.${process.pid}.tmp`;
|
|
936
|
+
fs.writeFileSync(tmpPath, merged, 'utf8');
|
|
937
|
+
fs.renameSync(tmpPath, lockPath);
|
|
938
|
+
}
|
|
939
|
+
|
|
681
940
|
/**
|
|
682
941
|
* Sync the current (or all) agent branches against the configured base
|
|
683
942
|
* branch using either rebase or merge. Supports `--check`, `--dry-run`,
|
|
@@ -822,8 +1081,7 @@ function sync(rawArgs) {
|
|
|
822
1081
|
syncOperation(repoRoot, strategy, baseRef, options.ffOnly);
|
|
823
1082
|
} finally {
|
|
824
1083
|
if (lockBackup !== null) {
|
|
825
|
-
|
|
826
|
-
fs.writeFileSync(lockPath, lockBackup, 'utf8');
|
|
1084
|
+
restoreLockBackupSafe(repoRoot, lockPath, lockBackup, branch);
|
|
827
1085
|
}
|
|
828
1086
|
}
|
|
829
1087
|
const after = aheadBehind(repoRoot, branch, baseRef);
|
|
@@ -856,4 +1114,6 @@ module.exports = {
|
|
|
856
1114
|
autoCommitWorktreeForFinish,
|
|
857
1115
|
shouldSweepOrphans,
|
|
858
1116
|
shouldSkipBranchPreflight,
|
|
1117
|
+
restoreLockBackupSafe,
|
|
1118
|
+
runCleanupWatchLoop,
|
|
859
1119
|
};
|