@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.
- package/README.md +123 -322
- package/package.json +23 -5
- package/skills/gitguardex/SKILL.md +83 -3
- package/src/agents/finish.js +15 -0
- package/src/ci-init/index.js +0 -1
- package/src/cli/args.js +142 -3
- package/src/cli/commands/branch.js +294 -14
- package/src/cli/commands/claude.js +15 -0
- package/src/cli/commands/doctor.js +26 -0
- package/src/cli/commands/onboard.js +293 -0
- package/src/cli/commands/prompt.js +15 -3
- package/src/cli/commands/review.js +18 -0
- package/src/cli/commands/setup.js +8 -6
- package/src/cli/commands/status.js +12 -0
- package/src/cli/main.js +2 -0
- package/src/cli/shared-locks.js +304 -0
- package/src/context.js +21 -3
- package/src/core/runtime.js +33 -1
- package/src/doctor/index.js +58 -6
- package/src/finish/heartbeat.js +169 -0
- package/src/finish/index.js +165 -18
- package/src/finish/progress.js +316 -0
- package/src/finish/review-gate.js +453 -32
- package/src/github-api.js +59 -0
- package/src/mcp/collect.js +155 -19
- package/src/mcp/server.js +35 -19
- package/src/output/index.js +210 -0
- package/src/pr-checks.js +121 -0
- package/src/pr-review.js +581 -51
- package/src/pr.js +143 -21
- package/src/provider-binary.js +101 -0
- package/src/review-diff.js +116 -0
- package/src/review-fix.js +229 -0
- package/src/sandbox/index.js +11 -5
- package/src/scaffold/index.js +4 -16
- package/src/shared-git-state.js +566 -0
- package/templates/AGENTS.multiagent-safety.md +63 -11
- package/templates/AGENTS.multiagent-safety.min.md +1 -0
- package/templates/codex/skills/gitguardex/SKILL.md +83 -3
- package/templates/githooks/post-checkout +4 -9
- package/templates/githooks/pre-commit +17 -1
- package/templates/github/workflows/README.md +30 -23
- package/templates/scripts/agent-autofinish-watch.sh +280 -0
- package/templates/scripts/agent-branch-finish.sh +354 -23
- package/templates/scripts/agent-branch-start.sh +49 -22
- package/templates/scripts/agent-claude-stop-finish.sh +194 -0
- package/templates/scripts/agent-file-locks.py +198 -29
- package/templates/scripts/agent-preflight.sh +14 -2
- package/templates/scripts/agent-stalled-report.sh +40 -0
- package/templates/scripts/codex-agent.sh +10 -63
- package/templates/github/workflows/cr.yml +0 -46
package/src/mcp/collect.js
CHANGED
|
@@ -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 —
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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 } = {}) {
|
|
@@ -305,28 +349,75 @@ function repoState(repoOrCwd, { includePrs = true } = {}) {
|
|
|
305
349
|
// Aggregate locks across ALL worktrees of the repo. Lock files are per-worktree
|
|
306
350
|
// on disk, so a single worktree's file only shows its own claims — the
|
|
307
351
|
// collision view requires the union.
|
|
308
|
-
function
|
|
309
|
-
|
|
352
|
+
function whoOwnsMany(files, { cwd = process.cwd(), repoPath } = {}) {
|
|
353
|
+
const requested = [...new Set(
|
|
354
|
+
(Array.isArray(files) ? files : [])
|
|
355
|
+
.filter((file) => typeof file === 'string' && file.trim())
|
|
356
|
+
.map((file) => file.trim()),
|
|
357
|
+
)].slice(0, 200);
|
|
358
|
+
if (requested.length === 0) return [];
|
|
310
359
|
const mainRoot = mainRepoRoot(repoPath || cwd);
|
|
311
|
-
if (!mainRoot)
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
const
|
|
360
|
+
if (!mainRoot) {
|
|
361
|
+
return requested.map((file) => ({ file, owner: null, error: 'not a git repo' }));
|
|
362
|
+
}
|
|
363
|
+
const targets = requested.map((file) => ({
|
|
364
|
+
file,
|
|
365
|
+
rel: path.isAbsolute(file) ? path.relative(mainRoot, file) : file,
|
|
366
|
+
owners: [],
|
|
367
|
+
seen: new Set(),
|
|
368
|
+
}));
|
|
369
|
+
const addOwner = (target, owner) => {
|
|
370
|
+
const key = `${owner.branch}\0${owner.agent || ''}`;
|
|
371
|
+
if (!owner.branch || target.seen.has(key)) return;
|
|
372
|
+
target.seen.add(key);
|
|
373
|
+
target.owners.push(owner);
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
// Read each worktree lock map once for the whole requested batch.
|
|
315
377
|
for (const wt of listWorktrees(mainRoot)) {
|
|
316
378
|
const map = readLockMap(wt.path);
|
|
317
|
-
const
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
379
|
+
for (const target of targets) {
|
|
380
|
+
const entry = map[target.rel] || map[target.file];
|
|
381
|
+
if (!entry) continue;
|
|
382
|
+
addOwner(target, {
|
|
321
383
|
branch: entry.branch,
|
|
322
|
-
agent: parseAgentName(entry.branch),
|
|
384
|
+
agent: entry.agent || parseAgentName(entry.branch),
|
|
323
385
|
claimed_at: entry.claimed_at || null,
|
|
324
386
|
worktree: wt.path,
|
|
325
387
|
});
|
|
326
388
|
}
|
|
327
389
|
}
|
|
328
|
-
if (
|
|
329
|
-
|
|
390
|
+
if (sharedGitState.settings(mainRoot).enabled) {
|
|
391
|
+
const sharedByFile = new Map(
|
|
392
|
+
sharedGitState.listLocks(mainRoot).map((entry) => [entry.file, entry]),
|
|
393
|
+
);
|
|
394
|
+
for (const target of targets) {
|
|
395
|
+
const entry = sharedByFile.get(target.rel) || sharedByFile.get(target.file);
|
|
396
|
+
if (!entry) continue;
|
|
397
|
+
addOwner(target, {
|
|
398
|
+
branch: entry.branch,
|
|
399
|
+
agent: entry.agent || parseAgentName(entry.branch),
|
|
400
|
+
claimed_at: entry.claimedAt,
|
|
401
|
+
worktree: null,
|
|
402
|
+
remote: true,
|
|
403
|
+
machine: entry.machine
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return targets.map(({ rel, owners }) => {
|
|
408
|
+
if (owners.length === 0) return { file: rel, owner: null };
|
|
409
|
+
return {
|
|
410
|
+
file: rel,
|
|
411
|
+
owner: owners.length === 1 ? owners[0] : null,
|
|
412
|
+
owners,
|
|
413
|
+
conflict: owners.length > 1,
|
|
414
|
+
};
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function whoOwns(file, options = {}) {
|
|
419
|
+
if (!file) return { file: null, owner: null, error: 'no file given' };
|
|
420
|
+
return whoOwnsMany([file], options)[0];
|
|
330
421
|
}
|
|
331
422
|
|
|
332
423
|
// Slim "radar" projection of a lane for list_agents — who-is-on-what at a
|
|
@@ -348,6 +439,7 @@ function radarRecord(a) {
|
|
|
348
439
|
if (a.ageDays != null) r.ageDays = a.ageDays; // age is the actionable bit for a prune candidate
|
|
349
440
|
}
|
|
350
441
|
if (a.warning) r.onPrimary = true; // lane editing the primary checkout (unsafe)
|
|
442
|
+
if (a.remote) r.remote = true;
|
|
351
443
|
if (a.pushed === false) r.unpushed = true;
|
|
352
444
|
return r;
|
|
353
445
|
}
|
|
@@ -359,6 +451,15 @@ function myContext({ cwd = process.cwd(), includePr = true } = {}) {
|
|
|
359
451
|
const branch = git(here, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
360
452
|
const self = listWorktrees(mainRoot).find((w) => path.resolve(w.path) === path.resolve(here));
|
|
361
453
|
const lc = branch ? lastCommit(mainRoot, branch) : null;
|
|
454
|
+
const localLocks = branch ? locksByBranch(here)[branch] || [] : [];
|
|
455
|
+
const shared = sharedGitState.settings(mainRoot);
|
|
456
|
+
const remoteLocks =
|
|
457
|
+
shared.enabled && branch
|
|
458
|
+
? sharedGitState
|
|
459
|
+
.listLocks(mainRoot)
|
|
460
|
+
.filter((entry) => entry.branch === branch)
|
|
461
|
+
.map((entry) => entry.file)
|
|
462
|
+
: [];
|
|
362
463
|
return {
|
|
363
464
|
repo: repoName(mainRoot),
|
|
364
465
|
repoPath: mainRoot,
|
|
@@ -368,11 +469,44 @@ function myContext({ cwd = process.cwd(), includePr = true } = {}) {
|
|
|
368
469
|
onPrimaryCheckout: self ? Boolean(self.isPrimary) : null,
|
|
369
470
|
protected: isProtectedBranch(branch),
|
|
370
471
|
dirty: dirtyFiles(here),
|
|
371
|
-
locks:
|
|
472
|
+
locks: [...new Set([...localLocks, ...remoteLocks])].sort(),
|
|
473
|
+
sharedGitState: shared.enabled ? { enabled: true, remote: shared.remote } : { enabled: false },
|
|
372
474
|
pr: includePr && branch ? safePr(mainRoot, branch) : null,
|
|
373
475
|
lastCommit: lc,
|
|
374
|
-
ageDays: lc ? daysSince(lc.date, Date.now()) : null
|
|
476
|
+
ageDays: lc ? daysSince(lc.date, Date.now()) : null
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function compactOwnership(result) {
|
|
481
|
+
const compactOwner = (owner) => {
|
|
482
|
+
if (!owner) return null;
|
|
483
|
+
const value = { branch: owner.branch, agent: owner.agent };
|
|
484
|
+
if (owner.remote) value.remote = true;
|
|
485
|
+
if (owner.machine) value.machine = owner.machine;
|
|
486
|
+
return value;
|
|
375
487
|
};
|
|
488
|
+
if (!result.owner && !result.conflict) return { file: result.file, owner: null };
|
|
489
|
+
if (result.conflict) {
|
|
490
|
+
return {
|
|
491
|
+
file: result.file,
|
|
492
|
+
owner: null,
|
|
493
|
+
owners: result.owners.map(compactOwner),
|
|
494
|
+
conflict: true,
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
return { file: result.file, owner: compactOwner(result.owner) };
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** One compact, repo-scoped snapshot for an agent about to edit files. */
|
|
501
|
+
function editContext({ cwd = process.cwd(), files = [], includePrs = false } = {}) {
|
|
502
|
+
const context = myContext({ cwd, includePr: includePrs });
|
|
503
|
+
if (context.error) return context;
|
|
504
|
+
const otherAgents = collectRepoAgents(context.repoPath, { includePrs })
|
|
505
|
+
.filter((agent) => agent.branch !== context.branch)
|
|
506
|
+
.map(radarRecord);
|
|
507
|
+
const ownership = whoOwnsMany(files, { repoPath: context.repoPath })
|
|
508
|
+
.map(compactOwnership);
|
|
509
|
+
return { ...context, otherAgents, ownership };
|
|
376
510
|
}
|
|
377
511
|
|
|
378
512
|
module.exports = {
|
|
@@ -380,7 +514,9 @@ module.exports = {
|
|
|
380
514
|
collectRepoAgents,
|
|
381
515
|
repoState,
|
|
382
516
|
whoOwns,
|
|
517
|
+
whoOwnsMany,
|
|
383
518
|
myContext,
|
|
519
|
+
editContext,
|
|
384
520
|
radarRecord,
|
|
385
521
|
indexPrsByBranch,
|
|
386
522
|
daysSince,
|
package/src/mcp/server.js
CHANGED
|
@@ -19,45 +19,45 @@ const TOOLS = [
|
|
|
19
19
|
{
|
|
20
20
|
name: 'list_agents',
|
|
21
21
|
description:
|
|
22
|
-
'
|
|
22
|
+
'Cross-repo agent radar. Compact by default; use detail only for paths and file lists.',
|
|
23
23
|
inputSchema: {
|
|
24
24
|
type: 'object',
|
|
25
25
|
properties: {
|
|
26
26
|
include_prs: {
|
|
27
27
|
type: 'boolean',
|
|
28
|
-
description: 'Fetch
|
|
28
|
+
description: 'Fetch PRs. Default false.',
|
|
29
29
|
},
|
|
30
30
|
roots: {
|
|
31
31
|
type: 'array',
|
|
32
32
|
items: { type: 'string' },
|
|
33
|
-
description: 'Override
|
|
33
|
+
description: 'Override search roots.',
|
|
34
34
|
},
|
|
35
|
-
limit: { type: 'number', description: '
|
|
36
|
-
detail: { type: 'boolean', description: 'Return full lane records
|
|
35
|
+
limit: { type: 'number', description: 'Repo scan cap.' },
|
|
36
|
+
detail: { type: 'boolean', description: 'Return full lane records. Default false.' },
|
|
37
37
|
},
|
|
38
38
|
},
|
|
39
39
|
},
|
|
40
40
|
{
|
|
41
41
|
name: 'repo_state',
|
|
42
42
|
description:
|
|
43
|
-
'Agent lanes for
|
|
43
|
+
'Agent lanes for one repo.',
|
|
44
44
|
inputSchema: {
|
|
45
45
|
type: 'object',
|
|
46
46
|
properties: {
|
|
47
|
-
repo: { type: 'string', description: '
|
|
48
|
-
include_prs: { type: 'boolean', description: 'Fetch
|
|
47
|
+
repo: { type: 'string', description: 'Repo path; default cwd.' },
|
|
48
|
+
include_prs: { type: 'boolean', description: 'Fetch PRs. Default false.' },
|
|
49
49
|
},
|
|
50
50
|
},
|
|
51
51
|
},
|
|
52
52
|
{
|
|
53
53
|
name: 'who_owns',
|
|
54
54
|
description:
|
|
55
|
-
'
|
|
55
|
+
'Find the lock owner for one file. owner=null means unclaimed.',
|
|
56
56
|
inputSchema: {
|
|
57
57
|
type: 'object',
|
|
58
58
|
properties: {
|
|
59
|
-
file: { type: 'string', description: '
|
|
60
|
-
repo: { type: 'string', description: '
|
|
59
|
+
file: { type: 'string', description: 'File path.' },
|
|
60
|
+
repo: { type: 'string', description: 'Repo path; default cwd.' },
|
|
61
61
|
},
|
|
62
62
|
required: ['file'],
|
|
63
63
|
},
|
|
@@ -65,19 +65,30 @@ const TOOLS = [
|
|
|
65
65
|
{
|
|
66
66
|
name: 'my_context',
|
|
67
67
|
description:
|
|
68
|
-
'
|
|
69
|
-
inputSchema: {
|
|
68
|
+
'Current lane. Pass files to also return compact same-repo radar and batch ownership in this one call.',
|
|
69
|
+
inputSchema: {
|
|
70
|
+
type: 'object',
|
|
71
|
+
properties: {
|
|
72
|
+
files: {
|
|
73
|
+
type: 'array',
|
|
74
|
+
items: { type: 'string' },
|
|
75
|
+
maxItems: 200,
|
|
76
|
+
description: 'Files intended for editing.',
|
|
77
|
+
},
|
|
78
|
+
include_prs: { type: 'boolean', description: 'Fetch PRs. Default false.' },
|
|
79
|
+
},
|
|
80
|
+
},
|
|
70
81
|
},
|
|
71
82
|
];
|
|
72
83
|
|
|
73
84
|
function callTool(name, args = {}) {
|
|
74
85
|
switch (name) {
|
|
75
86
|
case 'list_agents': {
|
|
76
|
-
//
|
|
77
|
-
//
|
|
87
|
+
// PR lookup is one batched gh call per repo with active lanes. Keep it
|
|
88
|
+
// opt-in so the default radar stays fast and compact.
|
|
78
89
|
const full = collect.collectAllAgents({
|
|
79
90
|
roots: args.roots,
|
|
80
|
-
includePrs: args.include_prs
|
|
91
|
+
includePrs: args.include_prs === true,
|
|
81
92
|
limit: args.limit,
|
|
82
93
|
});
|
|
83
94
|
// Compact radar by default (~80% fewer tokens); detail:true keeps the
|
|
@@ -86,11 +97,16 @@ function callTool(name, args = {}) {
|
|
|
86
97
|
return { ...full, agents: full.agents.map(collect.radarRecord) };
|
|
87
98
|
}
|
|
88
99
|
case 'repo_state':
|
|
89
|
-
return collect.repoState(args.repo || process.cwd(), { includePrs: args.include_prs
|
|
100
|
+
return collect.repoState(args.repo || process.cwd(), { includePrs: args.include_prs === true });
|
|
90
101
|
case 'who_owns':
|
|
91
102
|
return collect.whoOwns(args.file, { repoPath: args.repo });
|
|
92
|
-
case 'my_context':
|
|
93
|
-
|
|
103
|
+
case 'my_context': {
|
|
104
|
+
const includePrs = args.include_prs === true;
|
|
105
|
+
if (Array.isArray(args.files) && args.files.length > 0) {
|
|
106
|
+
return collect.editContext({ files: args.files, includePrs });
|
|
107
|
+
}
|
|
108
|
+
return collect.myContext({ includePr: includePrs });
|
|
109
|
+
}
|
|
94
110
|
default:
|
|
95
111
|
throw new Error(`Unknown tool: ${name}`);
|
|
96
112
|
}
|
package/src/output/index.js
CHANGED
|
@@ -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
|
};
|