@imdeadpool/guardex 8.4.24 → 8.4.26

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imdeadpool/guardex",
3
- "version": "8.4.24",
3
+ "version": "8.4.26",
4
4
  "description": "Guardian T-Rex for your multi-agent repo. Isolated worktrees, file locks, and PR-only merges stop parallel Codex & Claude agents from overwriting each other's work. Auto-wires Oh My Codex, Oh My Claude, OpenSpec, and Caveman.",
5
5
  "license": "MIT",
6
6
  "preferGlobal": true,
@@ -65,5 +65,5 @@
65
65
  "prepublishOnly": "node scripts/prepublish-bump-version.js",
66
66
  "postinstall": "node -e \"require('./src/heavy').installReport()\""
67
67
  },
68
- "gitHead": "4203a679068ffe9c5ddca41a3ee8f1a5af97cb1b"
68
+ "gitHead": "bf90aca41cc24d8b6dd8ec9e3706522196e664f0"
69
69
  }
@@ -353,7 +353,8 @@ function branch(rawArgs) {
353
353
  autoCommitWorktree ? 'checking worktree and pending changes' : 'resolving branch and finish policy',
354
354
  );
355
355
  const commitState = autoCommitWorktree
356
- ? autoCommitWorktreeForFinish(repoRoot, autoCommitWorktree, finishBranch, { noAutoCommit, commitMessage })
356
+ ? progress.trackFailure(() =>
357
+ autoCommitWorktreeForFinish(repoRoot, autoCommitWorktree, finishBranch, { noAutoCommit, commitMessage }))
357
358
  : { changed: false, committed: false };
358
359
  if (commitState.committed && !agentQuiet) {
359
360
  console.log(`[${TOOL_NAME}] Auto-committed '${finishBranch}' before finish.`);
@@ -367,7 +368,7 @@ function branch(rawArgs) {
367
368
  // the merge never happens.
368
369
  let gateResult;
369
370
  if (gateReview) {
370
- gateResult = runReviewGate({
371
+ gateResult = progress.trackFailure(() => runReviewGate({
371
372
  repoRoot,
372
373
  branch: finishBranch,
373
374
  // Must match how the shell resolves --base when it is omitted, which
@@ -390,7 +391,7 @@ function branch(rawArgs) {
390
391
  },
391
392
  progress,
392
393
  preflight: branchPreflightDuringCi(repoRoot, scriptArgs, { activeCwd, agentQuiet, progress }),
393
- });
394
+ }));
394
395
  } else {
395
396
  progress.skip('review', 'review gate disabled');
396
397
  progress.skip('autofix', 'review gate disabled');
@@ -0,0 +1,24 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { run } = require('../core/runtime');
4
+
5
+ const EVENT_DIRECTORY = ['.omx', 'state', 'finish-runs'];
6
+
7
+ // Git lists the primary checkout first. A bare repository has no primary HUD.
8
+ function primaryCheckout(repoRoot) {
9
+ try {
10
+ const result = run('git', ['worktree', 'list', '--porcelain', '-z'], {
11
+ cwd: repoRoot,
12
+ timeout: 1000
13
+ });
14
+ if (result?.status !== 0) return repoRoot;
15
+ const [entry, ...fields] = result.stdout.split('\0\0', 1)[0].split('\0');
16
+ const primary = entry.startsWith('worktree ') ? entry.slice(9) : '';
17
+ if (!path.isAbsolute(primary) || fields.includes('bare')) return repoRoot;
18
+ return fs.realpathSync(primary);
19
+ } catch (_error) {
20
+ return repoRoot;
21
+ }
22
+ }
23
+
24
+ module.exports = { EVENT_DIRECTORY, primaryCheckout };
@@ -2,15 +2,14 @@ const fs = require('node:fs');
2
2
  const path = require('node:path');
3
3
  const { createHash } = require('node:crypto');
4
4
  const { setTimeout: delay } = require('node:timers/promises');
5
+ const { EVENT_DIRECTORY, primaryCheckout } = require('./event-location');
5
6
 
6
7
  const MAX_READ_BYTES = 256 * 1024;
7
8
  const RUN_ID = /^finish-[a-z0-9]+-[0-9]+-[a-f0-9]{8}$/;
8
9
 
9
- // Observation only: event files never authorize a merge or replace gate checks.
10
- function readEventPage(repoRoot, runId, cursor = '', stateOptions) {
11
- if (!RUN_ID.test(runId)) throw new Error('Invalid finish run ID');
10
+ function eventFileInCheckout(repoRoot, runId) {
12
11
  let directory = fs.realpathSync(repoRoot);
13
- for (const part of ['.omx', 'state', 'finish-runs']) {
12
+ for (const part of EVENT_DIRECTORY) {
14
13
  directory = path.join(directory, part);
15
14
  const stat = fs.lstatSync(directory);
16
15
  if (!stat.isDirectory() || stat.isSymbolicLink()) {
@@ -18,7 +17,28 @@ function readEventPage(repoRoot, runId, cursor = '', stateOptions) {
18
17
  }
19
18
  }
20
19
  const file = path.join(directory, `${runId}.jsonl`);
21
- const entry = fs.lstatSync(file);
20
+ return { file, entry: fs.lstatSync(file) };
21
+ }
22
+
23
+ function locateEventFile(repoRoot, runId) {
24
+ try {
25
+ // Keep old worktree-local runs and the writer's fail-open fallback readable.
26
+ return eventFileInCheckout(repoRoot, runId);
27
+ } catch (error) {
28
+ const primary = primaryCheckout(repoRoot);
29
+ if (primary === repoRoot) throw error;
30
+ try {
31
+ return eventFileInCheckout(primary, runId);
32
+ } catch (primaryError) {
33
+ throw error.code === 'ENOENT' ? primaryError : error;
34
+ }
35
+ }
36
+ }
37
+
38
+ // Observation only: event files never authorize a merge or replace gate checks.
39
+ function readEventPage(repoRoot, runId, cursor = '', stateOptions) {
40
+ if (!RUN_ID.test(runId)) throw new Error('Invalid finish run ID');
41
+ const { file, entry } = locateEventFile(repoRoot, runId);
22
42
  if (!entry.isFile() || entry.isSymbolicLink()) throw new Error('Unsafe finish event file');
23
43
  const fd = fs.openSync(
24
44
  file,
@@ -128,6 +128,7 @@ function startHeartbeat({
128
128
  runId: String(event.runId || ''),
129
129
  branch: String(event.branch || ''),
130
130
  baseBranch: String(event.baseBranch || ''),
131
+ ...(event.recovery ? { recovery: event.recovery } : {}),
131
132
  };
132
133
  stdio.push(eventDescriptor);
133
134
  }
@@ -569,7 +569,7 @@ function finish(rawArgs, defaults = {}) {
569
569
  progress.start('prepare', worktreePath ? 'checking worktree and pending changes' : 'checking branch');
570
570
  let commitState = { changed: false, committed: false };
571
571
  if (worktreePath) {
572
- commitState = autoCommitWorktreeForFinish(repoRoot, worktreePath, branch, options);
572
+ commitState = progress.trackFailure(() => autoCommitWorktreeForFinish(repoRoot, worktreePath, branch, options));
573
573
  }
574
574
 
575
575
  if (terse) {
@@ -694,12 +694,12 @@ function finish(rawArgs, defaults = {}) {
694
694
  finishArgs.push('--no-preflight');
695
695
  }
696
696
  if (options.mergeMode === 'pr' && options.gateReview) {
697
- gateResult = runReviewGate({
697
+ gateResult = progress.trackFailure(() => runReviewGate({
698
698
  repoRoot, worktreePath, branch, baseBranch, options, progress,
699
699
  preflight: branchPreflightDuringCi(repoRoot, finishArgs, {
700
700
  activeCwd, agentQuiet: options.agentQuiet, progress,
701
701
  }),
702
- });
702
+ }));
703
703
  } else {
704
704
  progress.skip('review', 'review gate disabled');
705
705
  progress.skip('autofix', 'review gate disabled');
@@ -20,6 +20,28 @@ const SYMBOLS = {
20
20
 
21
21
  const TIMED_STAGES = new Set(['review', 'autofix']);
22
22
 
23
+ const RECOVERY_ACTIONS = {
24
+ prepare: 'Inspect the worktree and pending changes before retrying finish.',
25
+ preflight: 'Inspect the local check output and correct the failure before retrying finish.',
26
+ pr: 'Check whether the branch was pushed and the PR already exists before retrying finish.',
27
+ review: 'Check the current PR head and base and the posted review before retrying gated finish.',
28
+ autofix: 'Check the repair commit and whether it was pushed before applying another fix.',
29
+ ci: 'Refresh checks and required approvals on the current PR head before retrying gated finish.',
30
+ merge: 'Check whether GitHub already merged the PR before retrying gated finish.',
31
+ cleanup: 'Confirm the PR merged and the worktree is safe to remove before retrying cleanup.',
32
+ };
33
+
34
+ function recoveryFields(stage, state, detail) {
35
+ if (state !== 'running' && state !== 'failed') return {};
36
+ return {
37
+ recovery: {
38
+ outcome: state === 'failed' ? 'failed' : 'unconfirmed',
39
+ reason: state === 'failed' ? (detail || 'Stage failed') : 'No completed outcome recorded yet',
40
+ nextAction: RECOVERY_ACTIONS[stage],
41
+ },
42
+ };
43
+ }
44
+
23
45
  function createRunId(branch) {
24
46
  const digest = crypto.createHash('sha256').update(String(branch || '')).digest('hex').slice(0, 8);
25
47
  return `finish-${Date.now().toString(36)}-${process.pid}-${digest}`;
@@ -44,8 +66,14 @@ function createPrivateDirectory(repoRoot, components) {
44
66
 
45
67
  function createEventStream(repoRoot, branch, baseBranch) {
46
68
  if (!repoRoot) return null;
69
+ const primary = primaryCheckout(repoRoot);
70
+ return openEventStream(repoRoot, primary, branch, baseBranch)
71
+ || (primary !== repoRoot ? openEventStream(repoRoot, repoRoot, branch, baseBranch) : null);
72
+ }
73
+
74
+ function openEventStream(repoRoot, stateRoot, branch, baseBranch) {
47
75
  try {
48
- const directory = createPrivateDirectory(repoRoot, ['.omx', 'state', 'finish-runs']);
76
+ const directory = createPrivateDirectory(stateRoot, EVENT_DIRECTORY);
49
77
  const directoryDescriptor = fs.openSync(
50
78
  directory,
51
79
  fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
@@ -142,6 +170,8 @@ function createFinishProgress({
142
170
  const stageStartedAt = new Map();
143
171
  let activeTimedStage = '';
144
172
  let stopActiveHeartbeat = null;
173
+ let lastPrimaryStage = 'prepare';
174
+ let failures = 0;
145
175
 
146
176
  output(`[gx:finish] ╭─ 🚀 GX FINISH · ${branch || 'current branch'} → ${baseBranch || 'configured base'}`);
147
177
  if (eventStream) {
@@ -183,6 +213,10 @@ function createFinishProgress({
183
213
  if (stage.state === state && stage.detail === normalizedDetail) return false;
184
214
  stage.state = state;
185
215
  stage.detail = normalizedDetail;
216
+ // Skips do not advance the gate. Preflight can overlap CI and reports
217
+ // its own failures; it must not inherit a subsequent gate exception.
218
+ if (state !== 'skipped' && id !== 'preflight') lastPrimaryStage = id;
219
+ if (state === 'failed') failures += 1;
186
220
  const connector = id === 'cleanup' && state !== 'running' ? '╰─' : '├─';
187
221
  output(
188
222
  `[gx:finish] ${connector} ${SYMBOLS[state]} ${stage.index}/${STAGES.length} ${stage.label}`
@@ -196,6 +230,7 @@ function createFinishProgress({
196
230
  total: STAGES.length,
197
231
  label: stage.label,
198
232
  detail: normalizedDetail,
233
+ ...recoveryFields(id, state, normalizedDetail),
199
234
  });
200
235
  }
201
236
  return true;
@@ -225,7 +260,7 @@ function createFinishProgress({
225
260
  startAt,
226
261
  ...(eventStream ? {
227
262
  eventDescriptor: eventStream.descriptor,
228
- event: eventStream.event,
263
+ event: { ...eventStream.event, ...recoveryFields(id, 'running', normalizedDetail) },
229
264
  } : {}),
230
265
  });
231
266
  } catch (_error) {
@@ -243,8 +278,36 @@ function createFinishProgress({
243
278
  update(id, state, detail, displaySuffix);
244
279
  }
245
280
 
281
+ // Gate checks may throw after a stage reports success (e.g. the base moves).
282
+ // Preserve the error without replacing a more specific phase failure.
283
+ function trackFailure(operation) {
284
+ const previousFailures = failures;
285
+ try {
286
+ return operation();
287
+ } catch (error) {
288
+ if (failures === previousFailures) {
289
+ const reason = String(error?.message || 'Finish stopped').split('\n', 1)[0].slice(0, 500);
290
+ const stage = stageMap.get(lastPrimaryStage);
291
+ if (stage.state === 'complete') {
292
+ // A later guard can stop finish without undoing a completed check.
293
+ eventStream?.write({
294
+ ...stage,
295
+ stage: lastPrimaryStage,
296
+ total: STAGES.length,
297
+ kind: 'guard-failure',
298
+ ...recoveryFields(lastPrimaryStage, 'failed', reason),
299
+ });
300
+ } else {
301
+ settle(lastPrimaryStage, 'failed', reason);
302
+ }
303
+ }
304
+ throw error;
305
+ }
306
+ }
307
+
246
308
  return {
247
309
  start,
310
+ trackFailure,
248
311
  complete: (id, detail) => settle(id, 'complete', detail),
249
312
  skip: (id, detail) => settle(id, 'skipped', detail),
250
313
  fail: (id, detail) => settle(id, 'failed', detail),
@@ -276,7 +339,7 @@ function persistFinishOutput(eventFile, stdout, stderr) {
276
339
  throw new Error('unsafe finish log name');
277
340
  }
278
341
  const root = path.resolve(path.dirname(eventFile), '../../..');
279
- const directory = createPrivateDirectory(root, ['.omx', 'state', 'finish-runs']);
342
+ const directory = createPrivateDirectory(root, EVENT_DIRECTORY);
280
343
  if (path.resolve(eventFile) !== path.join(directory, name)) throw new Error('unsafe finish log path');
281
344
  const file = path.join(directory, `${name}.output.log`);
282
345
  const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT
@@ -349,4 +412,5 @@ module.exports = {
349
412
  const crypto = require('node:crypto');
350
413
  const fs = require('node:fs');
351
414
  const path = require('node:path');
415
+ const { EVENT_DIRECTORY, primaryCheckout } = require('./event-location');
352
416
  const { formatElapsed, startHeartbeat: startStageHeartbeat } = require('./heartbeat');
@@ -723,6 +723,36 @@ function postReviewPayload(pr, payload, repoRoot, runner = run) {
723
723
  }
724
724
  }
725
725
 
726
+ function syncReviewTitle(pr, { commit, base, value, truncated }, repoRoot, runner) {
727
+ const options = { cwd: repoRoot, timeout: 15_000 };
728
+ const current = runner(
729
+ GH_BIN,
730
+ ['pr', 'view', pr, '--json', 'title,state,headRefOid,baseRefOid'],
731
+ options
732
+ );
733
+ if (current.status !== 0) return;
734
+ const live = JSON.parse(current.stdout);
735
+ if (
736
+ live.state !== 'OPEN' ||
737
+ live.headRefOid !== commit ||
738
+ (base && live.baseRefOid !== base) ||
739
+ typeof live.title !== 'string'
740
+ ) return;
741
+
742
+ const managedPrefix = /^(?:\[(?:I(?:\d{1,3}|\?) R(?:\d{1,3}|\?)|Impact \d{1,3}\/100)\] )+/;
743
+ const original = live.title.replace(managedPrefix, '');
744
+ // Keep the leading conventional-commit type parseable after a squash merge.
745
+ const conventional = original.match(/^[a-z][a-z0-9-]*(?:\([^()\n]+\))?!?: /)?.[0] || '';
746
+ const subject = original.slice(conventional.length).replace(managedPrefix, '');
747
+ const { impactScore = null, riskScore = null } = (!truncated && value) || {};
748
+ const score = impactScore !== null || riskScore !== null
749
+ ? `[I${impactScore ?? '?'} R${riskScore ?? '?'}] `
750
+ : '';
751
+ const title = conventional + score + subject;
752
+ if (subject && title !== live.title)
753
+ runner(GH_BIN, ['pr', 'edit', pr, `--title=${title}`], options);
754
+ }
755
+
726
756
  /**
727
757
  * Post one review. Findings whose fingerprint is already on the PR are skipped
728
758
  * so repeated `gx ship` attempts stop stacking identical comments.
@@ -793,15 +823,21 @@ function postGithubReview(pr, context, repoRoot, runner = run) {
793
823
  const outcome = { posted: fresh.length, duplicates, degraded, commit };
794
824
  // Review receipts verify the live server-side review on retry. No receipt
795
825
  // can come from a degraded post, missing ID, or a different commit.
796
- if (!degraded) {
797
- try {
798
- const posted = JSON.parse(result.stdout);
799
- if (Number.isSafeInteger(posted.id) && posted.id > 0 && posted.commit_id === commit) {
826
+ try {
827
+ const posted = JSON.parse(result.stdout);
828
+ if (commit && posted.commit_id === commit) {
829
+ if (!degraded && Number.isSafeInteger(posted.id) && posted.id > 0) {
800
830
  outcome.reviewId = posted.id;
801
831
  outcome.reviewBodyHash = crypto.createHash('sha256').update(payload.body).digest('hex');
802
832
  }
803
- } catch { /* the review remains posted; only reuse is unavailable */ }
804
- }
833
+ syncReviewTitle(
834
+ pr,
835
+ { commit, base: context.reviewedBaseSha || context.expectedBaseSha, value: context.value, truncated },
836
+ repoRoot,
837
+ runner
838
+ );
839
+ }
840
+ } catch { /* Unavailable metadata or title permissions cannot invalidate a posted review. */ }
805
841
  return outcome;
806
842
  }
807
843
 
@@ -1189,7 +1225,7 @@ function runPrReview(options, deps = {}) {
1189
1225
  };
1190
1226
  }
1191
1227
 
1192
- const outcome = postGithubReview(pr, payload, repoRoot, runner);
1228
+ const outcome = postGithubReview(pr, { ...payload, expectedBaseSha: options.expectedBaseSha }, repoRoot, runner);
1193
1229
  history?.save(value);
1194
1230
  return {
1195
1231
  posted: true,
@@ -107,9 +107,27 @@ finish_event() {
107
107
  local label="${4:-}"
108
108
  local detail="${5:-}"
109
109
  local timestamp=""
110
+ local recovery="" outcome="" reason="" next_action=""
110
111
  [[ -n "$FINISH_EVENT_FILE" && -n "$FINISH_RUN_ID" ]] || return 0
112
+ if [[ "$state" == "running" || "$state" == "failed" ]]; then
113
+ case "$stage" in
114
+ preflight) next_action="Inspect the local check output and correct the failure before retrying finish." ;;
115
+ pr) next_action="Check whether the branch was pushed and the PR already exists before retrying finish." ;;
116
+ merge) next_action="Check whether GitHub already merged the PR before retrying gated finish." ;;
117
+ cleanup) next_action="Confirm the PR merged and the worktree is safe to remove before retrying cleanup." ;;
118
+ esac
119
+ if [[ "$state" == "failed" ]]; then
120
+ outcome="failed"
121
+ reason="${detail:-Stage failed}"
122
+ else
123
+ outcome="unconfirmed"
124
+ reason="No completed outcome recorded yet"
125
+ fi
126
+ recovery="$(printf ',"recovery":{"outcome":"%s","reason":"%s","nextAction":"%s"}' \
127
+ "$outcome" "$(finish_json_escape "$reason")" "$(finish_json_escape "$next_action")")"
128
+ fi
111
129
  timestamp="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
112
- printf '{"schemaVersion":1,"runId":"%s","timestamp":"%s","branch":"%s","baseBranch":"%s","stage":"%s","state":"%s","index":%s,"total":8,"label":"%s","detail":"%s"}\n' \
130
+ printf '{"schemaVersion":1,"runId":"%s","timestamp":"%s","branch":"%s","baseBranch":"%s","stage":"%s","state":"%s","index":%s,"total":8,"label":"%s","detail":"%s"%s}\n' \
113
131
  "$(finish_json_escape "$FINISH_RUN_ID")" \
114
132
  "$timestamp" \
115
133
  "$(finish_json_escape "$FINISH_EVENT_BRANCH")" \
@@ -119,6 +137,7 @@ finish_event() {
119
137
  "$number" \
120
138
  "$(finish_json_escape "$label")" \
121
139
  "$(finish_json_escape "$detail")" \
140
+ "$recovery" \
122
141
  >> "$FINISH_EVENT_FILE" 2>/dev/null || true
123
142
  }
124
143
 
@@ -350,7 +369,7 @@ run_preflight() {
350
369
  echo "[agent-branch-finish] Pre-flight passed." >&2
351
370
  return 0
352
371
  fi
353
- finish_progress failed preflight "failed"
372
+ finish_progress failed preflight "preflight exited with status ${preflight_status}"
354
373
  echo "[agent-branch-finish] Pre-flight FAILED; refusing push. Override with --no-preflight if you really mean it." >&2
355
374
  return 1
356
375
  }