@imdeadpool/guardex 7.1.0 → 8.1.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 (58) hide show
  1. package/README.md +122 -322
  2. package/package.json +25 -5
  3. package/scripts/prepublish-bump-version.js +191 -0
  4. package/skills/gitguardex/SKILL.md +83 -3
  5. package/src/agents/activity.js +279 -0
  6. package/src/agents/finish.js +15 -0
  7. package/src/ci-init/index.js +0 -1
  8. package/src/cli/args.js +203 -6
  9. package/src/cli/commands/agents.js +17 -0
  10. package/src/cli/commands/branch.js +267 -14
  11. package/src/cli/commands/claude.js +15 -0
  12. package/src/cli/commands/doctor.js +26 -0
  13. package/src/cli/commands/onboard.js +293 -0
  14. package/src/cli/commands/prompt.js +15 -3
  15. package/src/cli/commands/review.js +18 -0
  16. package/src/cli/commands/setup.js +8 -6
  17. package/src/cli/commands/status.js +12 -0
  18. package/src/cli/main.js +2 -0
  19. package/src/cli/shared-locks.js +304 -0
  20. package/src/context.js +21 -3
  21. package/src/core/runtime.js +33 -1
  22. package/src/doctor/index.js +58 -5
  23. package/src/finish/heartbeat.js +169 -0
  24. package/src/finish/index.js +106 -4
  25. package/src/finish/progress.js +262 -0
  26. package/src/finish/review-gate.js +453 -32
  27. package/src/github-api.js +59 -0
  28. package/src/mcp/collect.js +111 -12
  29. package/src/mcp/server.js +10 -4
  30. package/src/output/index.js +210 -0
  31. package/src/pr-checks.js +121 -0
  32. package/src/pr-review.js +581 -51
  33. package/src/pr.js +143 -21
  34. package/src/provider-binary.js +101 -0
  35. package/src/review-diff.js +116 -0
  36. package/src/review-fix.js +229 -0
  37. package/src/sandbox/index.js +11 -5
  38. package/src/scaffold/agent-worktree-prep.js +9 -2
  39. package/src/scaffold/index.js +4 -16
  40. package/src/scaffold/provision-config.js +314 -0
  41. package/src/shared-git-state.js +566 -0
  42. package/src/terminal/kitty.js +20 -0
  43. package/src/terminal/tmux.js +9 -0
  44. package/templates/AGENTS.multiagent-safety.md +73 -11
  45. package/templates/AGENTS.multiagent-safety.min.md +1 -0
  46. package/templates/codex/skills/gitguardex/SKILL.md +83 -3
  47. package/templates/githooks/post-checkout +4 -9
  48. package/templates/githooks/pre-commit +17 -1
  49. package/templates/github/workflows/README.md +30 -23
  50. package/templates/scripts/agent-autofinish-watch.sh +280 -0
  51. package/templates/scripts/agent-branch-finish.sh +363 -26
  52. package/templates/scripts/agent-branch-start.sh +76 -25
  53. package/templates/scripts/agent-claude-stop-finish.sh +194 -0
  54. package/templates/scripts/agent-file-locks.py +390 -52
  55. package/templates/scripts/agent-preflight.sh +14 -2
  56. package/templates/scripts/agent-stalled-report.sh +40 -0
  57. package/templates/scripts/codex-agent.sh +10 -63
  58. package/templates/github/workflows/cr.yml +0 -46
@@ -16,6 +16,7 @@ const path = require('node:path');
16
16
 
17
17
  const { findProjects } = require('../cockpit/projects-finder');
18
18
  const { findOpenPrForBranch, listOpenPrsForRepo } = require('../pr');
19
+ const sharedGitState = require('../shared-git-state');
19
20
 
20
21
  const PROTECTED_BRANCHES = new Set(['main', 'master', 'dev']);
21
22
  const LOCK_FILE_RELATIVE = path.join('.omx', 'state', 'agent-file-locks.json');
@@ -237,7 +238,7 @@ function buildAgentRecord(mainRoot, wt, locks, prInfo, nowMs) {
237
238
  && record.dirty.length === 0;
238
239
  if (wt.isPrimary) {
239
240
  record.warning =
240
- 'on the PRIMARY checkout, not an isolated worktree — edits here risk auto-stash/revert when another lane switches branches. Use `gx branch start`.';
241
+ 'on the PRIMARY checkout, not an isolated worktree — clean branch switches may be auto-reverted, while dirty work is left in place for manual recovery. Use `gx branch start`.';
241
242
  }
242
243
  return record;
243
244
  }
@@ -254,16 +255,59 @@ function isAgentLane(wt) {
254
255
  function collectRepoAgents(repoPath, { includePrs = true } = {}) {
255
256
  const mainRoot = mainRepoRoot(repoPath) || repoPath;
256
257
  const lanes = listWorktrees(mainRoot).filter(isAgentLane);
257
- if (lanes.length === 0) return []; // no lanes -> no gh call for this repo
258
+ const shared = sharedGitState.settings(mainRoot);
259
+ const sharedLocks = shared.enabled ? sharedGitState.listLocks(mainRoot) : [];
260
+ const remoteBranches = shared.enabled ? sharedGitState.listRemoteAgentBranches(mainRoot) : [];
261
+ const sharedLocksByBranch = {};
262
+ for (const entry of sharedLocks) {
263
+ (sharedLocksByBranch[entry.branch] = sharedLocksByBranch[entry.branch] || []).push(entry);
264
+ }
265
+ const remoteByBranch = new Map(remoteBranches.map((entry) => [entry.branch, entry]));
266
+ const remoteLaneBranches = new Set([
267
+ ...remoteBranches.map((entry) => entry.branch),
268
+ ...Object.keys(sharedLocksByBranch)
269
+ ]);
270
+ if (lanes.length === 0 && remoteLaneBranches.size === 0) return []; // no lanes -> no gh call for this repo
258
271
  // ONE gh call for the whole repo, only when there is at least one lane.
259
272
  const prInfo = includePrs ? prMapForRepo(mainRoot) : null;
260
273
  const nowMs = Date.now();
261
- return lanes.map((wt) => {
274
+ const localBranches = new Set(lanes.map((wt) => wt.branch));
275
+ const records = lanes.map((wt) => {
262
276
  // Each worktree owns its OWN lock file; a lane's locks are the entries in
263
277
  // its own worktree keyed to its branch.
264
- const locks = locksByBranch(wt.path)[wt.branch] || [];
278
+ const localLocks = locksByBranch(wt.path)[wt.branch] || [];
279
+ const remoteLocks = (sharedLocksByBranch[wt.branch] || []).map((entry) => entry.file);
280
+ const locks = [...new Set([...localLocks, ...remoteLocks])].sort();
265
281
  return buildAgentRecord(mainRoot, wt, locks, prInfo, nowMs);
266
282
  });
283
+ for (const branch of remoteLaneBranches) {
284
+ if (localBranches.has(branch)) continue;
285
+ const remoteBranch = remoteByBranch.get(branch);
286
+ const locks = sharedLocksByBranch[branch] || [];
287
+ const commit = remoteBranch ? lastCommit(mainRoot, remoteBranch.oid) : null;
288
+ records.push({
289
+ repo: repoName(mainRoot),
290
+ repoPath: mainRoot,
291
+ branch,
292
+ agent: parseAgentName(branch),
293
+ task: humanizeSlug(branch),
294
+ worktree: null,
295
+ onPrimaryCheckout: false,
296
+ pushed: Boolean(remoteBranch),
297
+ dirty: [],
298
+ locks: locks.map((entry) => entry.file).sort(),
299
+ lastCommit: commit,
300
+ pr: prInfo ? prInfo.map[branch] || null : null,
301
+ prLookupError: prInfo ? prInfo.error : null,
302
+ ageDays: commit ? daysSince(commit.date, nowMs) : null,
303
+ // A remote machine's dirty state is unknowable, so never call it stale.
304
+ stale: false,
305
+ remote: true,
306
+ shared: true,
307
+ machines: [...new Set(locks.map((entry) => entry.machine).filter(Boolean))]
308
+ });
309
+ }
310
+ return records;
267
311
  }
268
312
 
269
313
  function collectAllAgents({ roots, includePrs = true, limit } = {}) {
@@ -311,22 +355,66 @@ function whoOwns(file, { cwd = process.cwd(), repoPath } = {}) {
311
355
  if (!mainRoot) return { file, owner: null, error: 'not a git repo' };
312
356
  const rel = path.isAbsolute(file) ? path.relative(mainRoot, file) : file;
313
357
  const owners = [];
314
- const seenBranch = new Set();
358
+ const seenOwner = new Set();
315
359
  for (const wt of listWorktrees(mainRoot)) {
316
360
  const map = readLockMap(wt.path);
317
361
  const entry = map[rel] || map[file];
318
- if (entry && entry.branch && !seenBranch.has(entry.branch)) {
319
- seenBranch.add(entry.branch);
362
+ const key = entry && `${entry.branch}\0${entry.agent || ''}`;
363
+ if (entry && entry.branch && !seenOwner.has(key)) {
364
+ seenOwner.add(key);
320
365
  owners.push({
321
366
  branch: entry.branch,
322
- agent: parseAgentName(entry.branch),
367
+ agent: entry.agent || parseAgentName(entry.branch),
323
368
  claimed_at: entry.claimed_at || null,
324
- worktree: wt.path,
369
+ worktree: wt.path
370
+ });
371
+ }
372
+ }
373
+ if (sharedGitState.settings(mainRoot).enabled) {
374
+ const entry = sharedGitState.getLock(mainRoot, rel);
375
+ const key = entry && `${entry.branch}\0${entry.agent || ''}`;
376
+ if (entry && !seenOwner.has(key)) {
377
+ owners.push({
378
+ branch: entry.branch,
379
+ agent: entry.agent || parseAgentName(entry.branch),
380
+ claimed_at: entry.claimedAt,
381
+ worktree: null,
382
+ remote: true,
383
+ machine: entry.machine
325
384
  });
326
385
  }
327
386
  }
328
387
  if (owners.length === 0) return { file: rel, owner: null };
329
- return { file: rel, owner: owners.length === 1 ? owners[0] : null, owners, conflict: owners.length > 1 };
388
+ return {
389
+ file: rel,
390
+ owner: owners.length === 1 ? owners[0] : null,
391
+ owners,
392
+ conflict: owners.length > 1
393
+ };
394
+ }
395
+
396
+ // Slim "radar" projection of a lane for list_agents — who-is-on-what at a
397
+ // glance, ~80% smaller than the full record. File LISTS collapse to counts and
398
+ // the worktree path is dropped; an agent that needs detail (worktree path,
399
+ // exact dirty/lock files, full PR) calls repo_state / my_context, or passes
400
+ // detail:true to list_agents. Pure.
401
+ function radarRecord(a) {
402
+ const r = { repo: a.repo, branch: a.branch };
403
+ if (a.agent) r.agent = a.agent;
404
+ if (a.task && a.task !== a.branch) r.task = a.task;
405
+ if (a.dirty && a.dirty.length) r.dirty = a.dirty.length;
406
+ if (a.locks && a.locks.length) r.locks = a.locks.length;
407
+ if (a.pr && a.pr.number != null) r.pr = a.pr.number;
408
+ if (a.prLookupError) r.prLookupError = a.prLookupError;
409
+ if (a.lastCommit && a.lastCommit.date) r.last = a.lastCommit.date.slice(0, 10);
410
+ if (a.stale) {
411
+ r.stale = true;
412
+ if (a.ageDays != null) r.ageDays = a.ageDays; // age is the actionable bit for a prune candidate
413
+ }
414
+ if (a.warning) r.onPrimary = true; // lane editing the primary checkout (unsafe)
415
+ if (a.remote) r.remote = true;
416
+ if (a.pushed === false) r.unpushed = true;
417
+ return r;
330
418
  }
331
419
 
332
420
  function myContext({ cwd = process.cwd(), includePr = true } = {}) {
@@ -336,6 +424,15 @@ function myContext({ cwd = process.cwd(), includePr = true } = {}) {
336
424
  const branch = git(here, ['rev-parse', '--abbrev-ref', 'HEAD']);
337
425
  const self = listWorktrees(mainRoot).find((w) => path.resolve(w.path) === path.resolve(here));
338
426
  const lc = branch ? lastCommit(mainRoot, branch) : null;
427
+ const localLocks = branch ? locksByBranch(here)[branch] || [] : [];
428
+ const shared = sharedGitState.settings(mainRoot);
429
+ const remoteLocks =
430
+ shared.enabled && branch
431
+ ? sharedGitState
432
+ .listLocks(mainRoot)
433
+ .filter((entry) => entry.branch === branch)
434
+ .map((entry) => entry.file)
435
+ : [];
339
436
  return {
340
437
  repo: repoName(mainRoot),
341
438
  repoPath: mainRoot,
@@ -345,10 +442,11 @@ function myContext({ cwd = process.cwd(), includePr = true } = {}) {
345
442
  onPrimaryCheckout: self ? Boolean(self.isPrimary) : null,
346
443
  protected: isProtectedBranch(branch),
347
444
  dirty: dirtyFiles(here),
348
- locks: branch ? locksByBranch(here)[branch] || [] : [], // this lane's own claims
445
+ locks: [...new Set([...localLocks, ...remoteLocks])].sort(),
446
+ sharedGitState: shared.enabled ? { enabled: true, remote: shared.remote } : { enabled: false },
349
447
  pr: includePr && branch ? safePr(mainRoot, branch) : null,
350
448
  lastCommit: lc,
351
- ageDays: lc ? daysSince(lc.date, Date.now()) : null,
449
+ ageDays: lc ? daysSince(lc.date, Date.now()) : null
352
450
  };
353
451
  }
354
452
 
@@ -358,6 +456,7 @@ module.exports = {
358
456
  repoState,
359
457
  whoOwns,
360
458
  myContext,
459
+ radarRecord,
361
460
  indexPrsByBranch,
362
461
  daysSince,
363
462
  STALE_DAYS,
package/src/mcp/server.js CHANGED
@@ -19,7 +19,7 @@ const TOOLS = [
19
19
  {
20
20
  name: 'list_agents',
21
21
  description:
22
- 'List every active agent lane across all discovered repos: repo, branch, worktree, task, dirty (files changed RIGHT NOW), held file locks, last commit, ageDays, the PR it is shipping (with prLookupError set when the gh lookup itself failed, vs no open PR), stale (old + no PR + clean = a prune candidate), and warnings — e.g. a lane editing the primary checkout (the harness should act on that warning by moving to `gx branch start`). Use this to see who is working on what before you start. Read-only.',
22
+ 'List every active agent lane across all discovered repos. Returns a COMPACT radar by default — per lane: repo, branch, agent, task, dirty (count of files changed right now), locks (count), pr (number), last (commit date), and flags stale / onPrimary / unpushed when set. Use it to see who is working on what before you start. For full detail on a lane (worktree path, the actual dirty/lock file lists, full PR), call repo_state or my_context, or pass detail:true here (where the onPrimary flag appears as warning + onPrimaryCheckout instead). Read-only.',
23
23
  inputSchema: {
24
24
  type: 'object',
25
25
  properties: {
@@ -33,6 +33,7 @@ const TOOLS = [
33
33
  description: 'Override repo search roots. Default: ~/Documents, ~/code, ~/src, ~/projects.',
34
34
  },
35
35
  limit: { type: 'number', description: 'Max number of repos to scan.' },
36
+ detail: { type: 'boolean', description: 'Return full lane records (worktree path, dirty/lock file lists, full PR) instead of the compact radar. Default false.' },
36
37
  },
37
38
  },
38
39
  },
@@ -71,14 +72,19 @@ const TOOLS = [
71
72
 
72
73
  function callTool(name, args = {}) {
73
74
  switch (name) {
74
- case 'list_agents':
75
+ case 'list_agents': {
75
76
  // PRs on by default: one gh call per repo that has active lanes (most
76
77
  // repos have none, so they cost nothing). Pass include_prs:false to skip.
77
- return collect.collectAllAgents({
78
+ const full = collect.collectAllAgents({
78
79
  roots: args.roots,
79
80
  includePrs: args.include_prs !== false,
80
81
  limit: args.limit,
81
82
  });
83
+ // Compact radar by default (~80% fewer tokens); detail:true keeps the
84
+ // full records for callers that need worktree paths / file lists.
85
+ if (args.detail) return full;
86
+ return { ...full, agents: full.agents.map(collect.radarRecord) };
87
+ }
82
88
  case 'repo_state':
83
89
  return collect.repoState(args.repo || process.cwd(), { includePrs: args.include_prs !== false });
84
90
  case 'who_owns':
@@ -118,7 +124,7 @@ function dispatch(msg) {
118
124
  const name = params && params.name;
119
125
  const args = (params && params.arguments) || {};
120
126
  const result = callTool(name, args);
121
- return ok(id, { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] });
127
+ return ok(id, { content: [{ type: 'text', text: JSON.stringify(result) }] });
122
128
  }
123
129
  if (method === 'ping') return ok(id, {});
124
130
  if (isNotification) return null; // e.g. notifications/initialized
@@ -1,4 +1,6 @@
1
1
  const {
2
+ cp,
3
+ fs,
2
4
  path,
3
5
  packageJson,
4
6
  TOOL_NAME,
@@ -640,6 +642,208 @@ function printAutoFinishSummary(summary, options = {}) {
640
642
  }
641
643
  }
642
644
 
645
+ // ---------------------------------------------------------------------------
646
+ // Optional output compression (headroom / GUARDEX_COMPRESS_CMD)
647
+ //
648
+ // gitguardex is a published package, so the headroom compressor is never a hard
649
+ // dependency. When GUARDEX_COMPRESS_CMD is set to a stdin->stdout filter
650
+ // command, gx routes its large narrative output through it before printing so
651
+ // the blob costs fewer tokens once it lands in an AI agent's context. The
652
+ // default path (env unset) is byte-for-byte identical to plain console.log, and
653
+ // every failure mode falls back to the original text — fail-open, mirroring
654
+ // headroom's own proxy posture.
655
+ //
656
+ // Guards: only compress in terse (agent / non-TTY) mode, only blocks at or
657
+ // above COMPRESS_MIN_CHARS, and never machine-readable (JSON) payloads whose
658
+ // exact stdout other tools parse.
659
+ // ---------------------------------------------------------------------------
660
+
661
+ const COMPRESS_MIN_CHARS = 400;
662
+
663
+ // tokenizeCommand splits a command string into an argv array, honoring single
664
+ // quotes, double quotes (with \" and \\ escapes), and backslash escaping, so a
665
+ // value like sh -c "tr a-z A-Z" parses to ['sh','-c','tr a-z A-Z'] instead of
666
+ // being naively split on whitespace. Returns null on an unterminated quote
667
+ // (malformed) so callers fall back to plain output rather than run a half-parsed
668
+ // command. No shell-metacharacter handling (globs, $vars, pipes): tokens are
669
+ // passed to spawnSync with shell:false as literal argv.
670
+ function tokenizeCommand(raw) {
671
+ const text = String(raw);
672
+ const tokens = [];
673
+ let current = '';
674
+ let started = false;
675
+ let quote = null; // "'" or '"' while inside a quoted run
676
+ for (let i = 0; i < text.length; i += 1) {
677
+ const ch = text[i];
678
+ if (quote === "'") {
679
+ if (ch === "'") quote = null;
680
+ else current += ch;
681
+ continue;
682
+ }
683
+ if (quote === '"') {
684
+ if (ch === '"') quote = null;
685
+ else if (ch === '\\' && (text[i + 1] === '"' || text[i + 1] === '\\')) {
686
+ current += text[i + 1];
687
+ i += 1;
688
+ started = true;
689
+ } else current += ch;
690
+ continue;
691
+ }
692
+ if (ch === "'" || ch === '"') {
693
+ quote = ch;
694
+ started = true;
695
+ continue;
696
+ }
697
+ if (ch === '\\') {
698
+ if (i + 1 >= text.length) return null; // dangling backslash -> malformed
699
+ current += text[i + 1];
700
+ i += 1;
701
+ started = true;
702
+ continue;
703
+ }
704
+ if (/\s/.test(ch)) {
705
+ if (started) {
706
+ tokens.push(current);
707
+ current = '';
708
+ started = false;
709
+ }
710
+ continue;
711
+ }
712
+ current += ch;
713
+ started = true;
714
+ }
715
+ if (quote) return null; // unterminated quote -> malformed
716
+ if (started) tokens.push(current);
717
+ return tokens;
718
+ }
719
+
720
+ // resolveCompressCommand parses GUARDEX_COMPRESS_CMD into an argv array via
721
+ // tokenizeCommand (shell-quote aware), run with shell:false so no shell
722
+ // interpolation. Returns null when unset/empty/malformed so callers fall
723
+ // straight through to plain output.
724
+ function resolveCompressCommand(env = process.env) {
725
+ const raw = String(env.GUARDEX_COMPRESS_CMD || '').trim();
726
+ if (!raw) {
727
+ return null;
728
+ }
729
+ const argv = tokenizeCommand(raw);
730
+ if (!argv || argv.length === 0) {
731
+ return null;
732
+ }
733
+ return argv;
734
+ }
735
+
736
+ // looksMachineReadable keeps JSON / structured payloads (status --json, lock
737
+ // files, MCP responses) from ever being compressed; those have exact stdout
738
+ // contracts downstream parsers depend on. This is a first-character heuristic
739
+ // (leading `{` or `[`), which fully covers the current narrative call-sites
740
+ // (the markdown AGENTS snippet). A future caller that pipes other
741
+ // machine-readable formats (NUL-delimited, TSV, YAML) through compressBlock
742
+ // must guard that itself.
743
+ function looksMachineReadable(text) {
744
+ const head = String(text || '').trimStart()[0];
745
+ return head === '{' || head === '[';
746
+ }
747
+
748
+ // isExecutableOnPath resolves whether `command` can be found, mirroring how a
749
+ // shell would locate it: an explicit path (contains a separator) is checked
750
+ // directly; a bare name is searched across PATH entries (honoring PATHEXT on
751
+ // Windows). Defensive — returns null (unknown) on any unexpected error rather
752
+ // than throwing, so callers can degrade to "configured, presence unknown".
753
+ function isExecutableOnPath(command, env = process.env) {
754
+ try {
755
+ const cmd = String(command || '').trim();
756
+ if (!cmd) {
757
+ return false;
758
+ }
759
+ const exts =
760
+ process.platform === 'win32'
761
+ ? String(env.PATHEXT || '.COM;.EXE;.BAT;.CMD')
762
+ .split(';')
763
+ .map((ext) => ext.trim())
764
+ .filter(Boolean)
765
+ : [''];
766
+ const candidates = (base) =>
767
+ exts.some((ext) => {
768
+ try {
769
+ return fs.existsSync(ext ? base + ext : base);
770
+ } catch {
771
+ return false;
772
+ }
773
+ });
774
+ if (cmd.includes('/') || cmd.includes(path.sep)) {
775
+ return candidates(cmd);
776
+ }
777
+ const dirs = String(env.PATH || '').split(path.delimiter).filter(Boolean);
778
+ return dirs.some((dir) => candidates(path.join(dir, cmd)));
779
+ } catch {
780
+ return null;
781
+ }
782
+ }
783
+
784
+ // describeCompressor reports the GUARDEX_COMPRESS_CMD token-compression setup so
785
+ // `gx status` can surface it. The feature fails open (silently prints raw output
786
+ // when the compressor is missing), which makes a misconfiguration invisible and
787
+ // quietly wastes tokens — this gives an operator a way to confirm it is wired.
788
+ // `available` is true/false when resolvable, or null when presence is unknown.
789
+ function describeCompressor(env = process.env) {
790
+ const argv = resolveCompressCommand(env);
791
+ if (!argv) {
792
+ return { configured: false, command: null, available: null };
793
+ }
794
+ return { configured: true, command: argv[0], available: isExecutableOnPath(argv[0], env) };
795
+ }
796
+
797
+ // compressBlock returns `text` unchanged unless a compressor is configured AND
798
+ // we are in terse (agent / non-TTY) mode AND the block is large enough AND it
799
+ // is not machine-readable. Any failure (missing binary, non-zero exit, empty
800
+ // output, timeout) falls back to the original text. Never throws. Pass
801
+ // options.force to bypass the terse-mode gate (used by tests).
802
+ function compressBlock(text, options = {}) {
803
+ const input = String(text == null ? '' : text);
804
+ const env = options.env || process.env;
805
+ const argv = resolveCompressCommand(env);
806
+ if (!argv) {
807
+ return input;
808
+ }
809
+ if (!options.force && !isTerseMode()) {
810
+ return input;
811
+ }
812
+ if (input.length < COMPRESS_MIN_CHARS) {
813
+ return input;
814
+ }
815
+ if (looksMachineReadable(input)) {
816
+ return input;
817
+ }
818
+ let result;
819
+ try {
820
+ result = cp.spawnSync(argv[0], argv.slice(1), {
821
+ input,
822
+ encoding: 'utf8',
823
+ maxBuffer: 64 * 1024 * 1024,
824
+ timeout: Number(env.GUARDEX_COMPRESS_TIMEOUT_MS) || 5000,
825
+ });
826
+ } catch {
827
+ return input;
828
+ }
829
+ if (!result || result.error) {
830
+ return input;
831
+ }
832
+ // Non-zero exit OR signal-killed (status === null, e.g. timeout/OOM) -> fall
833
+ // back, even if the process emitted partial stdout before dying.
834
+ if (result.signal || (typeof result.status === 'number' && result.status !== 0)) {
835
+ return input;
836
+ }
837
+ const out = String(result.stdout || '');
838
+ return out.trim().length > 0 ? out : input;
839
+ }
840
+
841
+ // printCompressible writes a large narrative block to stdout, compressed when a
842
+ // compressor is configured (see compressBlock). Default path === console.log.
843
+ function printCompressible(text, options = {}) {
844
+ console.log(compressBlock(text, options));
845
+ }
846
+
643
847
  module.exports = {
644
848
  runtimeVersion,
645
849
  supportsAnsiColors,
@@ -664,4 +868,10 @@ module.exports = {
664
868
  detectRecoverableAutoFinishConflict,
665
869
  summarizeAutoFinishDetail,
666
870
  printAutoFinishSummary,
871
+ tokenizeCommand,
872
+ resolveCompressCommand,
873
+ isExecutableOnPath,
874
+ describeCompressor,
875
+ compressBlock,
876
+ printCompressible,
667
877
  };
@@ -0,0 +1,121 @@
1
+ // Normalize GitHub's PR check rollup across workflow reruns.
2
+ //
3
+ // `statusCheckRollup` can retain an older cancelled run beside its newer
4
+ // replacement. Counting both makes a successful rerun look red forever. Keep
5
+ // only the newest observation for the same provider/workflow/check identity.
6
+
7
+ const FAILING_CONCLUSIONS = new Set([
8
+ 'FAILURE',
9
+ 'ERROR',
10
+ 'TIMED_OUT',
11
+ 'CANCELLED',
12
+ 'ACTION_REQUIRED',
13
+ 'STARTUP_FAILURE',
14
+ ]);
15
+
16
+ function checkName(check) {
17
+ return String(check?.name || check?.context || '').trim();
18
+ }
19
+
20
+ function stableDetailsUrl(value) {
21
+ try {
22
+ const url = new URL(String(value || ''));
23
+ const volatileSegment = /^(?:\d+|[0-9a-f]{7,64}|[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})$/i;
24
+ const volatileCollections = new Set([
25
+ 'run', 'runs', 'job', 'jobs', 'build', 'builds',
26
+ 'execution', 'executions', 'attempt', 'attempts',
27
+ ]);
28
+ const segments = url.pathname.split('/');
29
+ for (let index = 1; index < segments.length; index += 1) {
30
+ if (volatileCollections.has(segments[index - 1].toLowerCase()) && volatileSegment.test(segments[index])) {
31
+ segments[index] = ':id';
32
+ }
33
+ }
34
+ return `${url.origin}${segments.join('/')}${url.search}`;
35
+ } catch (_error) {
36
+ return '';
37
+ }
38
+ }
39
+
40
+ function checkIdentity(check, index) {
41
+ const name = String(check?.name || check?.context || '').trim();
42
+ if (!name) return `anonymous:${index}`;
43
+
44
+ const type = String(check?.__typename || (check?.context ? 'StatusContext' : 'CheckRun'));
45
+ const workflow = String(check?.workflowName || '').trim();
46
+ if (type === 'StatusContext') return `${type}\u0000${name}`;
47
+ if (workflow) return `${type}\u0000${workflow}\u0000${name}`;
48
+
49
+ const details = stableDetailsUrl(check?.detailsUrl);
50
+ return details ? `${type}\u0000${details}\u0000${name}` : `anonymous:${index}`;
51
+ }
52
+
53
+ function timestamp(value) {
54
+ const parsed = Date.parse(String(value || ''));
55
+ return Number.isFinite(parsed) ? parsed : Number.NEGATIVE_INFINITY;
56
+ }
57
+
58
+ function recency(check, index) {
59
+ return [
60
+ timestamp(check?.createdAt),
61
+ timestamp(check?.startedAt),
62
+ timestamp(check?.completedAt),
63
+ index,
64
+ ];
65
+ }
66
+
67
+ function isNewer(candidate, current) {
68
+ for (let index = 0; index < candidate.length; index += 1) {
69
+ if (candidate[index] !== current[index]) return candidate[index] > current[index];
70
+ }
71
+ return false;
72
+ }
73
+
74
+ function latestStatusChecks(value) {
75
+ const input = Array.isArray(value) ? value : [];
76
+ const latest = new Map();
77
+
78
+ input.forEach((check, index) => {
79
+ const identity = checkIdentity(check, index);
80
+ const previous = latest.get(identity);
81
+ const candidate = { check, index, firstIndex: previous?.firstIndex ?? index, recency: recency(check, index) };
82
+ if (!previous || isNewer(candidate.recency, previous.recency)) latest.set(identity, candidate);
83
+ });
84
+
85
+ const selected = [...latest.values()].sort((left, right) => left.firstIndex - right.firstIndex);
86
+ const selectedIndexes = new Set(selected.map((entry) => entry.index));
87
+ return {
88
+ checks: selected.map((entry) => entry.check),
89
+ superseded: input.filter((_check, index) => !selectedIndexes.has(index)),
90
+ };
91
+ }
92
+
93
+ function summarizeStatusCheckRollup(value) {
94
+ const { checks, superseded } = latestStatusChecks(value);
95
+ const failedNames = [];
96
+ const summary = checks.reduce(
97
+ (acc, check) => {
98
+ const state = String(check?.conclusion || check?.state || check?.status || '').toUpperCase();
99
+ if (state === 'SUCCESS') acc.success += 1;
100
+ else if (state === 'CANCELLED') acc.cancelled += 1;
101
+ else if (FAILING_CONCLUSIONS.has(state)) acc.failed += 1;
102
+ else if (state === 'PENDING' || state === 'IN_PROGRESS' || state === 'QUEUED') acc.pending += 1;
103
+ else acc.other += 1;
104
+
105
+ if (FAILING_CONCLUSIONS.has(state)) {
106
+ const name = checkName(check);
107
+ if (name) failedNames.push(name);
108
+ }
109
+ return acc;
110
+ },
111
+ { success: 0, failed: 0, pending: 0, cancelled: 0, other: 0, total: checks.length },
112
+ );
113
+
114
+ return { summary, failedNames, supersededCount: superseded.length };
115
+ }
116
+
117
+ module.exports = {
118
+ FAILING_CONCLUSIONS,
119
+ latestStatusChecks,
120
+ summarizeStatusCheckRollup,
121
+ };