@imdeadpool/guardex 8.4.12 → 8.4.14
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 +26 -0
- package/package.json +3 -2
- package/skills/gitguardex/SKILL.md +5 -0
- package/src/cli/commands/branch.js +45 -0
- package/src/cli/main.js +4 -1
- package/src/context.js +16 -0
- package/src/finish/preflight.js +11 -2
- package/src/heavy/index.js +113 -0
- package/src/heavy/run.py +394 -0
- package/src/worktree-start.js +21 -8
- package/src/worktree-tasks.js +144 -0
- package/templates/AGENTS.multiagent-safety.md +1 -0
- package/templates/AGENTS.multiagent-safety.min.md +1 -0
- package/templates/codex/skills/gitguardex/SKILL.md +5 -0
- package/templates/scripts/agent-branch-finish.sh +6 -2
package/README.md
CHANGED
|
@@ -45,6 +45,32 @@ gx onboard # optional 2-minute tour
|
|
|
45
45
|
Requires **Node.js 18+**, Git, and GitHub CLI (`gh`). Recommended on macOS or
|
|
46
46
|
Linux; use WSL on Windows.
|
|
47
47
|
|
|
48
|
+
### Adaptive local build queue
|
|
49
|
+
|
|
50
|
+
The npm install hook detects total RAM and reports the baseline. On Linux with
|
|
51
|
+
Python 3, Codex and Claude can share one foreground heavy-job queue across
|
|
52
|
+
worktrees:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
gx mem-doctor --json
|
|
56
|
+
gx run-heavy -- npm run build
|
|
57
|
+
gx run-heavy -- npm test
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
GitGuardex finish preflight uses the same queue. The ceiling is one job per
|
|
61
|
+
8 GiB of effective RAM (at least one, at most four); available RAM and active
|
|
62
|
+
slots are rechecked before every admission, so zero jobs may start under
|
|
63
|
+
pressure. On systemd systems with a user manager, jobs run in their own
|
|
64
|
+
worker scopes under the caller's user app or session slice, with a soft
|
|
65
|
+
`MemoryHigh` limit. It does not change earlyoom or systemd-oomd settings. Commands that do
|
|
66
|
+
not use GitGuardex are not queued, and background daemons are not supported.
|
|
67
|
+
|
|
68
|
+
Waiting defaults to 120 seconds (`GUARDEX_HEAVY_WAIT_SECONDS`); on expiry the
|
|
69
|
+
command is not run and GitGuardex returns 75. Set `GUARDEX_HEAVY_SCOPE=0` to
|
|
70
|
+
skip just the scope, or `GUARDEX_HEAVY_QUEUE=0` to run without the queue.
|
|
71
|
+
macOS and Linux without Python run commands directly. Ignoring npm install
|
|
72
|
+
scripts skips only the install report; the runtime still detects RAM.
|
|
73
|
+
|
|
48
74
|
> [!WARNING]
|
|
49
75
|
> GitGuardex is an independent project. It is not affiliated with OpenAI,
|
|
50
76
|
> Anthropic, or Codex.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imdeadpool/guardex",
|
|
3
|
-
"version": "8.4.
|
|
3
|
+
"version": "8.4.14",
|
|
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,
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"package:check": "node --check bin/multiagent-safety.js && bash scripts/check-script-symlinks.sh && npm pack --dry-run",
|
|
21
21
|
"verify": "npm run format:check:changed && npm run lint && npm test && npm run package:check",
|
|
22
22
|
"prepublishOnly": "node scripts/prepublish-bump-version.js",
|
|
23
|
+
"postinstall": "node -e \"require('./src/heavy').installReport()\"",
|
|
23
24
|
"agent:codex": "bash ./scripts/codex-agent.sh",
|
|
24
25
|
"agent:branch:start": "bash ./scripts/agent-branch-start.sh",
|
|
25
26
|
"agent:branch:finish": "bash ./scripts/agent-branch-finish.sh",
|
|
@@ -97,5 +98,5 @@
|
|
|
97
98
|
"jsonc-parser": "3.3.1",
|
|
98
99
|
"semver": "7.7.4"
|
|
99
100
|
},
|
|
100
|
-
"gitHead": "
|
|
101
|
+
"gitHead": "f748d7e02c853b29826bb1e1005127468de407e8"
|
|
101
102
|
}
|
|
@@ -10,6 +10,11 @@ Use when a GitGuardex-managed repository needs safe edits or multi-agent coordin
|
|
|
10
10
|
Bootstrap: `gx setup`
|
|
11
11
|
Ops: `gx branch start "<task>" "<agent>"`, `gx locks claim --branch "<agent-branch>" <file...>`, `gx branch finish --branch "<agent-branch>" --base <base> --via-pr --wait-for-merge --cleanup`, `gx finish --all`, `gx cleanup`
|
|
12
12
|
|
|
13
|
+
On Linux, use `gx run-heavy -- <command> [args...]` for foreground builds,
|
|
14
|
+
typechecks and full test suites. Codex and Claude share the same local RAM-based
|
|
15
|
+
queue; `gx mem-doctor` explains why a job would wait. Leave lightweight reads
|
|
16
|
+
and edits unwrapped.
|
|
17
|
+
|
|
13
18
|
## Choose the lane before editing
|
|
14
19
|
|
|
15
20
|
Worktree policy is strict `always` unless the repo opts into `adaptive` with
|
|
@@ -178,6 +178,21 @@ function isReadOnlyBranchStart(args) {
|
|
|
178
178
|
return args.some((arg) => ['--help', '-h', 'help', '--print-name-only', '--preview'].includes(arg));
|
|
179
179
|
}
|
|
180
180
|
|
|
181
|
+
// Identify options, not values that happen to look like one. Keep the shell
|
|
182
|
+
// asset as the authority for all branch-start arguments other than --json.
|
|
183
|
+
function branchStartOptionIndices(args, name) {
|
|
184
|
+
const takesValue = new Set([
|
|
185
|
+
'--task', '--task-id', '--agent', '--base', '--tier', '--provision-mode',
|
|
186
|
+
'--worktree-root', '--sparse-exclude', '--transfer-exclude'
|
|
187
|
+
]);
|
|
188
|
+
const indices = [];
|
|
189
|
+
for (let index = 0; index < args.length; index++) {
|
|
190
|
+
if (args[index] === name) indices.push(index);
|
|
191
|
+
if (takesValue.has(args[index])) index++;
|
|
192
|
+
}
|
|
193
|
+
return indices;
|
|
194
|
+
}
|
|
195
|
+
|
|
181
196
|
function recoverStaleManagedWorktrees(repoRoot) {
|
|
182
197
|
const idleMinutes = process.env.GUARDEX_BRANCH_START_CLEANUP_IDLE_MINUTES || '15';
|
|
183
198
|
const result = runPackageAsset(
|
|
@@ -216,10 +231,32 @@ function recoverStaleManagedWorktrees(repoRoot) {
|
|
|
216
231
|
function branch(rawArgs) {
|
|
217
232
|
const activeCwd = process.cwd();
|
|
218
233
|
const [subcommand, ...rest] = rawArgs;
|
|
234
|
+
if (subcommand === 'tasks') {
|
|
235
|
+
if (rest[0] === '--help' || rest[0] === '-h') {
|
|
236
|
+
process.stdout.write(
|
|
237
|
+
'Usage: gx branch tasks --json\n' +
|
|
238
|
+
'List ready linked worktrees in this repository and their occupancy (versioned JSON).\n' +
|
|
239
|
+
'Related: gx branch start --task-id <id> --json; gx branch run-task <id> <branch> <worktree> -- <command>\n'
|
|
240
|
+
);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (rest.length !== 1 || rest[0] !== '--json') throw new Error('Usage: gx branch tasks --json');
|
|
244
|
+
require('../../worktree-tasks').listTasks(resolveRepoRoot(activeCwd));
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (subcommand === 'run-task') {
|
|
248
|
+
require('../../worktree-tasks').runTask(resolveRepoRoot(activeCwd), rest);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
219
251
|
if (subcommand === 'start') {
|
|
220
252
|
const { target, passthrough } = extractTargetedArgs(rest);
|
|
221
253
|
const repoRoot = resolveRepoRoot(target);
|
|
222
254
|
const readOnly = isReadOnlyBranchStart(passthrough);
|
|
255
|
+
const jsonIndices = branchStartOptionIndices(passthrough, '--json');
|
|
256
|
+
const json = jsonIndices.length > 0;
|
|
257
|
+
if (json && (readOnly || jsonIndices.length !== 1 ||
|
|
258
|
+
branchStartOptionIndices(passthrough, '--task-id').length !== 1))
|
|
259
|
+
throw new Error('--json requires a normal branch start with --task-id');
|
|
223
260
|
const quota = readOnly ? {} : require('../../worktree-quota').readWorktreeQuota(repoRoot);
|
|
224
261
|
if (!readOnly) {
|
|
225
262
|
const modeIndex = passthrough.indexOf('--provision-mode');
|
|
@@ -235,6 +272,11 @@ function branch(rawArgs) {
|
|
|
235
272
|
passthrough[passthrough.indexOf('--task-id') + 1]
|
|
236
273
|
);
|
|
237
274
|
}
|
|
275
|
+
if (json) {
|
|
276
|
+
require('../../worktree-start').invokeTaskStart(repoRoot,
|
|
277
|
+
passthrough.filter((_, index) => index !== jsonIndices[0]), true);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
238
280
|
if (!isReadOnlyBranchStart(passthrough)) {
|
|
239
281
|
require('../../finish/post-branch-finish-cleanup').retryPendingFinishedCleanup(repoRoot, {
|
|
240
282
|
schedule: true
|
|
@@ -246,6 +288,9 @@ function branch(rawArgs) {
|
|
|
246
288
|
return;
|
|
247
289
|
}
|
|
248
290
|
invokePackageAsset('branchStart', passthrough, { cwd: repoRoot });
|
|
291
|
+
if (passthrough[0] === '--help' || passthrough[0] === '-h') {
|
|
292
|
+
process.stdout.write(' --json With --task-id, emit a versioned task result on stdout\n');
|
|
293
|
+
}
|
|
249
294
|
return;
|
|
250
295
|
}
|
|
251
296
|
if (subcommand === 'finish') {
|
package/src/cli/main.js
CHANGED
|
@@ -167,7 +167,8 @@ function hasRenderableHelp(command) {
|
|
|
167
167
|
function helpFlagIsTopLevel(rest) {
|
|
168
168
|
if (!rest.length) return false;
|
|
169
169
|
if (!String(rest[0]).startsWith('-')) return false;
|
|
170
|
-
|
|
170
|
+
const separator = rest.indexOf('--');
|
|
171
|
+
return (separator === -1 ? rest : rest.slice(0, separator)).some((arg) => HELP_FLAGS.has(arg));
|
|
171
172
|
}
|
|
172
173
|
|
|
173
174
|
function printCommandHelp(command) {
|
|
@@ -349,6 +350,8 @@ async function main() {
|
|
|
349
350
|
if (command === 'release') return require('./commands/release').release(rest);
|
|
350
351
|
if (command === 'watch') return require('./commands/watch').watch(rest);
|
|
351
352
|
if (command === 'budget') return require('../budget').runBudgetCommand(rest);
|
|
353
|
+
if (command === 'mem-doctor') return require('../heavy').memDoctor(rest);
|
|
354
|
+
if (command === 'run-heavy') return require('../heavy').runHeavy(rest);
|
|
352
355
|
if (command === 'ci-init') return require('../ci-init').runCiInitCommand(rest);
|
|
353
356
|
if (command === 'speckit') return require('../speckit').runSpeckitCommand(rest);
|
|
354
357
|
|
package/src/context.js
CHANGED
|
@@ -386,6 +386,8 @@ const SUGGESTIBLE_COMMANDS = [
|
|
|
386
386
|
'print-agents-snippet',
|
|
387
387
|
'release',
|
|
388
388
|
'budget',
|
|
389
|
+
'mem-doctor',
|
|
390
|
+
'run-heavy',
|
|
389
391
|
'ci-init',
|
|
390
392
|
'speckit',
|
|
391
393
|
];
|
|
@@ -403,6 +405,8 @@ const CLI_COMMAND_GROUPS = [
|
|
|
403
405
|
['setup', 'Install, repair, and verify guardrails (flags: --repair, --install-only, --target, --current)'],
|
|
404
406
|
['doctor', 'Repair drift + verify (flags: --target, --current; auto-sandboxes on protected main)'],
|
|
405
407
|
['status', 'Show GitGuardex CLI + service health without modifying files'],
|
|
408
|
+
['mem-doctor', 'Show live RAM, swap, and heavy-job queue capacity'],
|
|
409
|
+
['run-heavy', 'Run a local build or test through the adaptive memory queue'],
|
|
406
410
|
['migrate', 'Convert legacy repo-local installs to the zero-copy CLI-owned surface'],
|
|
407
411
|
],
|
|
408
412
|
},
|
|
@@ -488,6 +492,18 @@ const CLI_COMMAND_HELP = {
|
|
|
488
492
|
speckit: { nativeHelp: true },
|
|
489
493
|
prompt: { nativeHelp: true },
|
|
490
494
|
|
|
495
|
+
'mem-doctor': {
|
|
496
|
+
usage: 'gx mem-doctor [--json]',
|
|
497
|
+
summary: 'Read RAM, swap, memory pressure, and local heavy-job capacity without making changes.',
|
|
498
|
+
flags: [['--json', 'Machine-readable report']],
|
|
499
|
+
examples: ['gx mem-doctor', 'gx mem-doctor --json'],
|
|
500
|
+
},
|
|
501
|
+
'run-heavy': {
|
|
502
|
+
usage: 'gx run-heavy -- <command> [args...]',
|
|
503
|
+
summary: 'Wait for local RAM and a shared foreground job slot before running a command.',
|
|
504
|
+
examples: ['gx run-heavy -- npm run build', 'gx run-heavy -- pnpm test'],
|
|
505
|
+
},
|
|
506
|
+
|
|
491
507
|
setup: {
|
|
492
508
|
usage: 'gx setup [options]',
|
|
493
509
|
summary: 'Install, repair, and verify the guardrails in a repo. Idempotent — safe to re-run.',
|
package/src/finish/preflight.js
CHANGED
|
@@ -13,8 +13,10 @@ const fs = require('fs');
|
|
|
13
13
|
const path = require('path');
|
|
14
14
|
const { spawnSync } = require('child_process');
|
|
15
15
|
const { run, runPackageAsset } = require('../core/runtime');
|
|
16
|
+
const { heavyInvocation, needsPythonFallback } = require('../heavy');
|
|
16
17
|
|
|
17
18
|
const PREFLIGHT_SCRIPTS = ['typecheck', 'lint'];
|
|
19
|
+
const PREFLIGHT_SECONDS = 5 * 60;
|
|
18
20
|
|
|
19
21
|
function readJson(file) {
|
|
20
22
|
try {
|
|
@@ -128,11 +130,18 @@ function runPreflight(repoRoot, worktreePath, branch, baseBranch, options = {})
|
|
|
128
130
|
if (options.verbose) {
|
|
129
131
|
process.stdout.write(`[preflight] running ${label}…\n`);
|
|
130
132
|
}
|
|
131
|
-
const
|
|
133
|
+
const directOptions = {
|
|
132
134
|
cwd: repoRoot,
|
|
133
135
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
134
|
-
timeout:
|
|
136
|
+
timeout: PREFLIGHT_SECONDS * 1000,
|
|
137
|
+
};
|
|
138
|
+
const invocation = heavyInvocation(cmd, args, PREFLIGHT_SECONDS);
|
|
139
|
+
// The Linux runner starts its own execution clock only after admission.
|
|
140
|
+
let result = spawnSync(invocation.command, invocation.args, {
|
|
141
|
+
...directOptions,
|
|
142
|
+
timeout: invocation.queued ? undefined : directOptions.timeout,
|
|
135
143
|
});
|
|
144
|
+
if (needsPythonFallback(result, invocation)) result = spawnSync(cmd, args, directOptions);
|
|
136
145
|
const stdout = (result.stdout || '').toString();
|
|
137
146
|
const stderr = (result.stderr || '').toString();
|
|
138
147
|
const ok = !result.error && result.status === 0;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
const { spawn, spawnSync } = require('node:child_process');
|
|
2
|
+
const { totalmem, freemem, constants } = require('node:os');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
|
|
5
|
+
const runner = path.join(__dirname, 'run.py');
|
|
6
|
+
const GiB = 1024 ** 3;
|
|
7
|
+
const gib = (bytes) => `${(bytes / GiB).toFixed(1)} GiB`;
|
|
8
|
+
|
|
9
|
+
function inspect(profileOnly = false) {
|
|
10
|
+
if (process.platform === 'linux') {
|
|
11
|
+
const result = spawnSync('python3', [runner, profileOnly ? 'profile' : 'diagnose'], {
|
|
12
|
+
encoding: 'utf8',
|
|
13
|
+
timeout: profileOnly ? 1500 : 3500
|
|
14
|
+
});
|
|
15
|
+
if (result.status === 0) return JSON.parse(result.stdout);
|
|
16
|
+
if (!profileOnly && result.error?.code !== 'ENOENT') {
|
|
17
|
+
throw new Error(
|
|
18
|
+
result.stderr?.trim() || result.error?.message || 'Memory diagnostics failed'
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
supported: false,
|
|
24
|
+
hostTotalBytes: totalmem(),
|
|
25
|
+
availableBytes: freemem(),
|
|
26
|
+
reason: process.platform === 'linux' ? 'Linux queue needs python3' : 'Local queue is Linux-only'
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function installReport() {
|
|
31
|
+
const report = inspect(true);
|
|
32
|
+
const ram = gib(report.hostTotalBytes);
|
|
33
|
+
console.log(
|
|
34
|
+
report.supported
|
|
35
|
+
? `[gx] Detected ${ram} RAM; adaptive queue: up to ${report.maxJobs} heavy jobs (${gib(report.totalBytes)} effective RAM).`
|
|
36
|
+
: `[gx] Detected ${ram} RAM; ${report.reason}.`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function memDoctor(args) {
|
|
41
|
+
if (args.length && (args.length !== 1 || args[0] !== '--json')) {
|
|
42
|
+
throw new Error('Usage: gx mem-doctor [--json]');
|
|
43
|
+
}
|
|
44
|
+
const report = inspect();
|
|
45
|
+
if (args[0] === '--json') {
|
|
46
|
+
console.log(JSON.stringify(report, null, 2));
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
console.log(
|
|
50
|
+
`RAM: ${gib(report.availableBytes)} ${report.supported ? 'available' : 'free'} / ${gib(report.totalBytes ?? report.hostTotalBytes)} total`
|
|
51
|
+
);
|
|
52
|
+
if (!report.supported) {
|
|
53
|
+
console.log(report.reason);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
console.log(`Swap: ${gib(report.swapFreeBytes)} free / ${gib(report.swapTotalBytes)} total`);
|
|
57
|
+
console.log(
|
|
58
|
+
report.enabled
|
|
59
|
+
? `Heavy jobs: ${report.activeJobs}/${report.maxJobs} busy, ${report.admissibleJobs} can start now; ${gib(report.reserveBytes)} RAM reserved`
|
|
60
|
+
: 'Heavy-job queue disabled'
|
|
61
|
+
);
|
|
62
|
+
console.log(
|
|
63
|
+
`Memory pressure (10s): some ${report.pressureAvg10.some ?? 'n/a'}%, full ${report.pressureAvg10.full ?? 'n/a'}%`
|
|
64
|
+
);
|
|
65
|
+
console.log(
|
|
66
|
+
`systemd worker scope: ${report.scopeAvailable ? `available, MemoryHigh ${gib(report.memoryHighBytes)}/job` : 'unavailable'}`
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function heavyInvocation(command, args, executionSeconds) {
|
|
71
|
+
if (process.platform === 'linux' && process.env.GUARDEX_HEAVY_QUEUE !== '0') {
|
|
72
|
+
const budget = executionSeconds ? ['--run-timeout', String(executionSeconds)] : [];
|
|
73
|
+
return { command: 'python3', args: [runner, ...budget, '--', command, ...args], queued: true };
|
|
74
|
+
}
|
|
75
|
+
return { command, args };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function needsPythonFallback(result, invocation) {
|
|
79
|
+
return (
|
|
80
|
+
invocation.command === 'python3' &&
|
|
81
|
+
invocation.args[0] === runner &&
|
|
82
|
+
result.error?.code === 'ENOENT' &&
|
|
83
|
+
result.error.path === 'python3'
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function runHeavy(args) {
|
|
88
|
+
if (args[0] !== '--' || !args[1]) throw new Error('Usage: gx run-heavy -- <command> [args...]');
|
|
89
|
+
const [, command, ...commandArgs] = args;
|
|
90
|
+
const invocation = heavyInvocation(command, commandArgs);
|
|
91
|
+
function launch({ command, args }) {
|
|
92
|
+
return new Promise((resolve, reject) => {
|
|
93
|
+
const child = spawn(command, args, { stdio: 'inherit' });
|
|
94
|
+
const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
95
|
+
const forward = (signal) => child.kill(signal);
|
|
96
|
+
for (const signal of signals) process.on(signal, forward);
|
|
97
|
+
child.once('error', reject);
|
|
98
|
+
child.once('close', (code, signal) => {
|
|
99
|
+
for (const name of signals) process.off(name, forward);
|
|
100
|
+
resolve(code ?? (signal ? 128 + constants.signals[signal] : 1));
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
process.exitCode = await launch(invocation);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (!needsPythonFallback({ error }, invocation)) throw error;
|
|
108
|
+
console.error('[gx] python3 unavailable; running without the local memory queue.');
|
|
109
|
+
process.exitCode = await launch({ command, args: commandArgs });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
module.exports = { installReport, memDoctor, runHeavy, heavyInvocation, needsPythonFallback };
|
package/src/heavy/run.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
"""Per-user Linux admission control for foreground build and test commands."""
|
|
2
|
+
import contextlib
|
|
3
|
+
import fcntl
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import pwd
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
import signal
|
|
11
|
+
import stat
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
MIB = 1024 ** 2
|
|
17
|
+
GIB = 1024 * MIB
|
|
18
|
+
MAX_SLOTS = 4
|
|
19
|
+
CGROUP = Path("/sys/fs/cgroup")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def read(path):
|
|
23
|
+
try:
|
|
24
|
+
return Path(path).read_text()
|
|
25
|
+
except OSError:
|
|
26
|
+
return ""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def counters(path):
|
|
30
|
+
return {key.rstrip(":"): int(value) for key, value, *_ in
|
|
31
|
+
(line.split() for line in read(path).splitlines() if line.strip())
|
|
32
|
+
if value.isdecimal()}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def number(path):
|
|
36
|
+
value = read(path).strip()
|
|
37
|
+
return int(value) if value.isdecimal() else None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def current_group():
|
|
41
|
+
for line in read("/proc/self/cgroup").splitlines():
|
|
42
|
+
if line.startswith("0::/"):
|
|
43
|
+
group = (CGROUP / line[4:]).resolve()
|
|
44
|
+
if group == CGROUP or CGROUP in group.parents:
|
|
45
|
+
return group
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def v1_memory_group():
|
|
50
|
+
for line in read("/proc/self/cgroup").splitlines():
|
|
51
|
+
_, controllers, group = line.split(":", 2)
|
|
52
|
+
if "memory" in controllers.split(","):
|
|
53
|
+
break
|
|
54
|
+
else:
|
|
55
|
+
return None
|
|
56
|
+
for line in read("/proc/self/mountinfo").splitlines():
|
|
57
|
+
left, separator, right = line.partition(" - ")
|
|
58
|
+
if not separator:
|
|
59
|
+
continue
|
|
60
|
+
fs, _, options = right.split()
|
|
61
|
+
if fs != "cgroup" or "memory" not in options.split(","):
|
|
62
|
+
continue
|
|
63
|
+
root, mount = (Path(re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), field))
|
|
64
|
+
for field in left.split()[3:5])
|
|
65
|
+
try:
|
|
66
|
+
directory = (mount / Path(group).relative_to(root)).resolve()
|
|
67
|
+
except ValueError:
|
|
68
|
+
continue
|
|
69
|
+
if (directory == mount or mount in directory.parents) and (directory / "memory.limit_in_bytes").is_file():
|
|
70
|
+
return mount, directory
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def cgroup_headroom(total, available):
|
|
75
|
+
v1 = v1_memory_group()
|
|
76
|
+
root, group = v1 or (CGROUP, current_group())
|
|
77
|
+
if group is None:
|
|
78
|
+
return total, available
|
|
79
|
+
limit_file, usage_file = ("memory.limit_in_bytes", "memory.usage_in_bytes") if v1 else ("memory.max", "memory.current")
|
|
80
|
+
for parent in (group, *group.parents):
|
|
81
|
+
if not v1 or parent == group or read(parent / "memory.use_hierarchy").strip() != "0":
|
|
82
|
+
limit = number(parent / limit_file)
|
|
83
|
+
used = number(parent / usage_file)
|
|
84
|
+
if limit is not None:
|
|
85
|
+
total = min(total, limit)
|
|
86
|
+
available = min(available, max(0, limit - (used or 0)))
|
|
87
|
+
if parent == root:
|
|
88
|
+
break
|
|
89
|
+
return total, available
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def policy(total, available, active):
|
|
93
|
+
# ponytail: one conservative estimate per job; add job-specific weights only
|
|
94
|
+
# if measured workloads consistently need different admission thresholds.
|
|
95
|
+
max_jobs = min(MAX_SLOTS, max(1, total // (8 * GIB))) if total else 0
|
|
96
|
+
reserve = max(total // 8, min(512 * MIB, total // 4))
|
|
97
|
+
job = min(2 * GIB, total // 4)
|
|
98
|
+
additional = min(max_jobs - active, (available - reserve) // max(1, job) - active)
|
|
99
|
+
return {
|
|
100
|
+
"maxJobs": max_jobs,
|
|
101
|
+
"activeJobs": active,
|
|
102
|
+
"admissibleJobs": max(0, additional),
|
|
103
|
+
"reserveBytes": reserve,
|
|
104
|
+
"estimatedJobBytes": job,
|
|
105
|
+
"memoryHighBytes": min(4 * GIB, total // 2),
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def snapshot(active):
|
|
110
|
+
mem = counters("/proc/meminfo")
|
|
111
|
+
host_total = mem.get("MemTotal", 0) * 1024
|
|
112
|
+
host_available = mem.get("MemAvailable", 0) * 1024
|
|
113
|
+
total, available = cgroup_headroom(host_total, host_available)
|
|
114
|
+
return {
|
|
115
|
+
"supported": True,
|
|
116
|
+
"enabled": os.environ.get("GUARDEX_HEAVY_QUEUE") != "0",
|
|
117
|
+
"hostTotalBytes": host_total,
|
|
118
|
+
"hostAvailableBytes": host_available,
|
|
119
|
+
"totalBytes": total,
|
|
120
|
+
"availableBytes": available,
|
|
121
|
+
"swapTotalBytes": mem.get("SwapTotal", 0) * 1024,
|
|
122
|
+
"swapFreeBytes": mem.get("SwapFree", 0) * 1024,
|
|
123
|
+
**policy(total, available, active),
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def queue_dir():
|
|
128
|
+
uid = os.getuid()
|
|
129
|
+
runtime = Path(f"/run/user/{uid}")
|
|
130
|
+
if check_directory(runtime):
|
|
131
|
+
return runtime / "gitguardex-heavy"
|
|
132
|
+
# Use the account's home, not the caller's HOME. Prefer it over shared /tmp.
|
|
133
|
+
try:
|
|
134
|
+
home = Path(pwd.getpwuid(uid).pw_dir)
|
|
135
|
+
if home.is_absolute():
|
|
136
|
+
info = home.stat()
|
|
137
|
+
if stat.S_ISDIR(info.st_mode) and info.st_uid == uid and not info.st_mode & 0o022:
|
|
138
|
+
return home / ".cache" / "gitguardex-heavy"
|
|
139
|
+
except (KeyError, OSError):
|
|
140
|
+
pass
|
|
141
|
+
# Unmapped UIDs still share a queue; creation rejects foreign-owned paths.
|
|
142
|
+
return Path(f"/tmp/gitguardex-heavy-{uid}")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def check_directory(directory, create=False):
|
|
146
|
+
if create:
|
|
147
|
+
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
148
|
+
try:
|
|
149
|
+
info = directory.lstat()
|
|
150
|
+
except FileNotFoundError:
|
|
151
|
+
return False
|
|
152
|
+
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
|
|
153
|
+
raise RuntimeError(f"unsafe queue directory: {directory}")
|
|
154
|
+
return True
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def try_lock(path, create=False):
|
|
158
|
+
flags = (os.O_RDWR | os.O_CREAT) if create else os.O_RDONLY
|
|
159
|
+
try:
|
|
160
|
+
fd = os.open(path, flags | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
|
|
161
|
+
except FileNotFoundError:
|
|
162
|
+
if not create:
|
|
163
|
+
return None, False
|
|
164
|
+
raise
|
|
165
|
+
try:
|
|
166
|
+
info = os.fstat(fd)
|
|
167
|
+
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != os.getuid():
|
|
168
|
+
raise RuntimeError(f"unsafe queue lock: {path}")
|
|
169
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
170
|
+
return fd, False
|
|
171
|
+
except BlockingIOError:
|
|
172
|
+
os.close(fd)
|
|
173
|
+
return None, True
|
|
174
|
+
except BaseException:
|
|
175
|
+
os.close(fd)
|
|
176
|
+
raise
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@contextlib.contextmanager
|
|
180
|
+
def inspect_slots(directory, create=False):
|
|
181
|
+
with contextlib.ExitStack() as stack:
|
|
182
|
+
slots = []
|
|
183
|
+
for index in range(MAX_SLOTS):
|
|
184
|
+
fd, busy = try_lock(directory / f"slot-{index}", create)
|
|
185
|
+
if fd is not None:
|
|
186
|
+
if create:
|
|
187
|
+
stack.callback(os.close, fd)
|
|
188
|
+
else:
|
|
189
|
+
os.close(fd)
|
|
190
|
+
fd = None
|
|
191
|
+
slots.append((fd, busy))
|
|
192
|
+
yield slots
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def admit(directory):
|
|
196
|
+
guard, _ = try_lock(directory / "admission", create=True)
|
|
197
|
+
if guard is None:
|
|
198
|
+
return None
|
|
199
|
+
try:
|
|
200
|
+
with inspect_slots(directory, create=True) as slots:
|
|
201
|
+
plan = snapshot(sum(busy for _, busy in slots))
|
|
202
|
+
if plan["admissibleJobs"]:
|
|
203
|
+
# dup keeps the same kernel lock after the probe releases its fd.
|
|
204
|
+
fd = next(fd for fd, _ in slots if fd is not None)
|
|
205
|
+
return os.dup(fd), plan["memoryHighBytes"]
|
|
206
|
+
finally:
|
|
207
|
+
os.close(guard)
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def user_manager_group():
|
|
212
|
+
uid = os.getuid()
|
|
213
|
+
return CGROUP / f"user.slice/user-{uid}.slice/user@{uid}.service"
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def worker_slice():
|
|
217
|
+
if os.environ.get("GUARDEX_HEAVY_SCOPE") == "0" or not (CGROUP / "cgroup.controllers").is_file():
|
|
218
|
+
return None
|
|
219
|
+
# Only move out of ordinary user scopes. Stay under the same parent slice
|
|
220
|
+
# and don't escape memory limits on the caller's scope itself.
|
|
221
|
+
group = current_group()
|
|
222
|
+
if group is None or not group.name.endswith(".scope"):
|
|
223
|
+
return None
|
|
224
|
+
parent = group.parent
|
|
225
|
+
if parent.parent != user_manager_group() or parent.name not in ("app.slice", "session.slice"):
|
|
226
|
+
return None
|
|
227
|
+
if any(read(group / f"memory.{field}").strip() != "max" for field in ("max", "high")):
|
|
228
|
+
return None
|
|
229
|
+
if not shutil.which("systemd-run") or not shutil.which("systemctl"):
|
|
230
|
+
return None
|
|
231
|
+
try:
|
|
232
|
+
ready = subprocess.run(
|
|
233
|
+
["systemctl", "--user", "show", "--property=Version", "--value"], stdin=subprocess.DEVNULL,
|
|
234
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2,
|
|
235
|
+
).returncode == 0
|
|
236
|
+
return parent / parent.name.replace(".slice", "-gxheavy.slice") if ready else None
|
|
237
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
238
|
+
return None
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def supervise(command, seconds, pass_fds, *, new_session):
|
|
242
|
+
interrupted = False
|
|
243
|
+
with subprocess.Popen(command, start_new_session=new_session, pass_fds=pass_fds) as child:
|
|
244
|
+
def send(signum):
|
|
245
|
+
with contextlib.suppress(ProcessLookupError):
|
|
246
|
+
(os.killpg if new_session else os.kill)(child.pid, signum)
|
|
247
|
+
|
|
248
|
+
def forward(signum, _frame):
|
|
249
|
+
nonlocal interrupted
|
|
250
|
+
interrupted = True
|
|
251
|
+
send(signum)
|
|
252
|
+
|
|
253
|
+
previous = {signum: signal.signal(signum, forward)
|
|
254
|
+
for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)}
|
|
255
|
+
try:
|
|
256
|
+
status = child.wait(timeout=seconds)
|
|
257
|
+
return status, interrupted
|
|
258
|
+
except subprocess.TimeoutExpired:
|
|
259
|
+
send(signal.SIGKILL)
|
|
260
|
+
print(f"[gx] Heavy job timed out after {seconds}s of execution.", file=sys.stderr)
|
|
261
|
+
return 124, interrupted
|
|
262
|
+
finally:
|
|
263
|
+
for signum, handler in previous.items():
|
|
264
|
+
signal.signal(signum, handler)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def exit_status(status):
|
|
268
|
+
return status if status >= 0 else 128 - status
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def run_scope(command, seconds, scope, high, slot_fd):
|
|
272
|
+
# Scope setup and the command can fail with the same exit code. Only the
|
|
273
|
+
# in-scope wrapper can attest that it has taken responsibility for the job.
|
|
274
|
+
reader, writer = os.pipe2(os.O_CLOEXEC | os.O_NONBLOCK)
|
|
275
|
+
try:
|
|
276
|
+
scoped = ["systemd-run", "--user", "--scope", "--quiet", f"--slice={scope.name}",
|
|
277
|
+
"--description=GitGuardex heavy job", "-p", f"MemoryHigh={high}", "--",
|
|
278
|
+
sys.executable, os.path.abspath(__file__), "scoped", str(writer),
|
|
279
|
+
"" if seconds is None else str(seconds), str(slot_fd), *command]
|
|
280
|
+
try:
|
|
281
|
+
status, interrupted = supervise(scoped, None, (slot_fd, writer), new_session=False)
|
|
282
|
+
except (FileNotFoundError, PermissionError):
|
|
283
|
+
return None
|
|
284
|
+
if interrupted or status < 0:
|
|
285
|
+
return exit_status(status)
|
|
286
|
+
with contextlib.suppress(BlockingIOError):
|
|
287
|
+
if os.read(reader, 1):
|
|
288
|
+
return exit_status(status)
|
|
289
|
+
return None
|
|
290
|
+
finally:
|
|
291
|
+
os.close(reader)
|
|
292
|
+
os.close(writer)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def execute(command, seconds, scope=None, high=None, slot_fd=None):
|
|
296
|
+
if scope:
|
|
297
|
+
status = run_scope(command, seconds, scope, high, slot_fd)
|
|
298
|
+
if status is not None:
|
|
299
|
+
return status
|
|
300
|
+
if seconds is not None:
|
|
301
|
+
# Keep the slot locked if the supervisor dies while the child is running.
|
|
302
|
+
pass_fds = () if slot_fd is None else (slot_fd,)
|
|
303
|
+
status, _ = supervise(command, seconds, pass_fds, new_session=True)
|
|
304
|
+
return exit_status(status)
|
|
305
|
+
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
|
|
306
|
+
os.execvp(command[0], command)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def run(command, seconds=None):
|
|
310
|
+
if os.environ.get("GUARDEX_HEAVY_QUEUE") == "0" or os.environ.get("GUARDEX_HEAVY_ACTIVE") == "1":
|
|
311
|
+
return execute(command, seconds)
|
|
312
|
+
directory = queue_dir()
|
|
313
|
+
check_directory(directory, create=True)
|
|
314
|
+
timeout = int(os.environ.get("GUARDEX_HEAVY_WAIT_SECONDS", "120"))
|
|
315
|
+
if timeout < 0:
|
|
316
|
+
raise ValueError("GUARDEX_HEAVY_WAIT_SECONDS must be a non-negative integer")
|
|
317
|
+
deadline = time.monotonic() + timeout
|
|
318
|
+
warned = False
|
|
319
|
+
while True:
|
|
320
|
+
admission = admit(directory)
|
|
321
|
+
if admission is not None:
|
|
322
|
+
fd, high = admission
|
|
323
|
+
os.set_inheritable(fd, True)
|
|
324
|
+
os.environ["GUARDEX_HEAVY_ACTIVE"] = "1"
|
|
325
|
+
return execute(command, seconds, worker_slice(), high, fd)
|
|
326
|
+
remaining = deadline - time.monotonic()
|
|
327
|
+
if remaining <= 0:
|
|
328
|
+
with inspect_slots(directory) as slots:
|
|
329
|
+
plan = snapshot(sum(busy for _, busy in slots))
|
|
330
|
+
active = plan["activeJobs"]
|
|
331
|
+
needed = max(0, plan["reserveBytes"] + plan["estimatedJobBytes"] * (active + 1)
|
|
332
|
+
- plan["availableBytes"])
|
|
333
|
+
detail = f"{active}/{plan['maxJobs']} slots occupied"
|
|
334
|
+
if needed:
|
|
335
|
+
detail += f"; needs {needed / GIB:.1f} GiB more available RAM"
|
|
336
|
+
print(f"[gx] Heavy job not started before timeout ({detail}). Run gx mem-doctor.", file=sys.stderr)
|
|
337
|
+
return 75
|
|
338
|
+
if not warned:
|
|
339
|
+
print("[gx] Waiting for a heavy-job slot and available RAM…", file=sys.stderr)
|
|
340
|
+
warned = True
|
|
341
|
+
time.sleep(min(1, remaining))
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def diagnose():
|
|
345
|
+
directory = queue_dir()
|
|
346
|
+
with inspect_slots(directory) if check_directory(directory) else contextlib.nullcontext([]) as slots:
|
|
347
|
+
report = snapshot(sum(busy for _, busy in slots))
|
|
348
|
+
pressure = read("/proc/pressure/memory")
|
|
349
|
+
group = worker_slice()
|
|
350
|
+
report.update(
|
|
351
|
+
pressureAvg10={line.split()[0]: float(line.split()[1].split("=")[1])
|
|
352
|
+
for line in pressure.splitlines()},
|
|
353
|
+
scopeAvailable=group is not None,
|
|
354
|
+
scopeSlice=group.name if group else None,
|
|
355
|
+
scopeMemoryCurrentBytes=number(group / "memory.current") if group else None,
|
|
356
|
+
scopeMemoryPeakBytes=number(group / "memory.peak") if group else None,
|
|
357
|
+
scopeMemoryEvents=counters(group / "memory.events") if group else {},
|
|
358
|
+
)
|
|
359
|
+
print(json.dumps(report))
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def main(args):
|
|
363
|
+
if args == ["diagnose"]:
|
|
364
|
+
diagnose()
|
|
365
|
+
elif args == ["profile"]:
|
|
366
|
+
print(json.dumps(snapshot(0)))
|
|
367
|
+
elif len(args) >= 4 and args[0] == "--run-timeout" and args[2] == "--":
|
|
368
|
+
return run(args[3:], int(args[1]))
|
|
369
|
+
elif len(args) >= 5 and args[0] == "scoped":
|
|
370
|
+
ready, seconds, slot_fd = args[1:4]
|
|
371
|
+
os.write(int(ready), b"1")
|
|
372
|
+
os.close(int(ready))
|
|
373
|
+
return execute(args[4:], int(seconds) if seconds else None, slot_fd=int(slot_fd))
|
|
374
|
+
elif len(args) >= 2 and args[0] == "--":
|
|
375
|
+
return run(args[1:])
|
|
376
|
+
else:
|
|
377
|
+
raise ValueError("expected diagnose, profile or -- <command>")
|
|
378
|
+
return 0
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
if __name__ == "__main__":
|
|
382
|
+
try:
|
|
383
|
+
sys.exit(main(sys.argv[1:]))
|
|
384
|
+
except KeyboardInterrupt:
|
|
385
|
+
sys.exit(130)
|
|
386
|
+
except FileNotFoundError as error:
|
|
387
|
+
print(f"[gx] {error}", file=sys.stderr)
|
|
388
|
+
sys.exit(127)
|
|
389
|
+
except PermissionError as error:
|
|
390
|
+
print(f"[gx] {error}", file=sys.stderr)
|
|
391
|
+
sys.exit(126)
|
|
392
|
+
except (OSError, RuntimeError, ValueError) as error:
|
|
393
|
+
print(f"[gx] {error}", file=sys.stderr)
|
|
394
|
+
sys.exit(1)
|
package/src/worktree-start.js
CHANGED
|
@@ -65,19 +65,27 @@ function estimateCheckout(repoRoot, ref, exclusions) {
|
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
function commonGitDirectory(repoRoot) {
|
|
69
|
+
const common = run('git', ['-C', repoRoot, 'rev-parse', '--git-common-dir']);
|
|
70
|
+
if (common.status !== 0) throw new Error('Cannot resolve task lock directory');
|
|
71
|
+
return fs.realpathSync(path.resolve(repoRoot, common.stdout.trim()));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function taskLock(repoRoot, id, scope = 'task') {
|
|
75
|
+
const key = crypto.createHash('sha256').update(id).digest('hex');
|
|
76
|
+
return path.join(commonGitDirectory(repoRoot), `gitguardex-${scope}-${key}.lock`);
|
|
77
|
+
}
|
|
78
|
+
|
|
68
79
|
function runTaskStart(repoRoot, args) {
|
|
69
80
|
const taskFlags = args.filter((arg) => arg === '--task-id').length;
|
|
70
81
|
if (taskFlags > 1)
|
|
71
82
|
throw new Error('--task-id must appear once');
|
|
72
83
|
const id = taskFlags ? validateTaskId(args[args.indexOf('--task-id') + 1]) : '';
|
|
73
|
-
const common = run('git', ['-C', repoRoot, 'rev-parse', '--git-common-dir']);
|
|
74
|
-
if (common.status !== 0) throw new Error('Cannot resolve task lock directory');
|
|
75
|
-
const commonDir = fs.realpathSync(path.resolve(repoRoot, common.stdout.trim()));
|
|
76
84
|
const locks = [];
|
|
77
85
|
if (Object.keys(require('./worktree-quota').readWorktreeQuota(repoRoot)).length) {
|
|
78
|
-
locks.push(path.join(
|
|
86
|
+
locks.push(path.join(commonGitDirectory(repoRoot), 'gitguardex-worktree-quota.lock'));
|
|
79
87
|
}
|
|
80
|
-
if (id) locks.push(
|
|
88
|
+
if (id) locks.push(taskLock(repoRoot, id));
|
|
81
89
|
let command = ['bash', packageAssetPath('branchStart'), ...args];
|
|
82
90
|
for (const lock of locks.reverse()) {
|
|
83
91
|
command = ['python3', path.join(__dirname, 'finish/with-claims-lock.py'), lock, ...command];
|
|
@@ -89,12 +97,17 @@ function runTaskStart(repoRoot, args) {
|
|
|
89
97
|
);
|
|
90
98
|
}
|
|
91
99
|
|
|
92
|
-
function invokeTaskStart(repoRoot, args) {
|
|
100
|
+
function invokeTaskStart(repoRoot, args, json = false) {
|
|
93
101
|
const result = runTaskStart(repoRoot, args);
|
|
94
|
-
if (result.stdout) process.stdout.write(result.stdout);
|
|
102
|
+
if (result.stdout) (json ? process.stderr : process.stdout).write(result.stdout);
|
|
95
103
|
if (result.stderr) process.stderr.write(result.stderr);
|
|
96
104
|
if (result.status !== 0)
|
|
97
105
|
throw new Error(`Task start failed or is busy (status ${result.status})`);
|
|
106
|
+
if (json) {
|
|
107
|
+
const { findTask } = require('./worktree-tasks');
|
|
108
|
+
const task = findTask(repoRoot, args[args.indexOf('--task-id') + 1]);
|
|
109
|
+
process.stdout.write(JSON.stringify({ version: 1, ...task }) + '\n');
|
|
110
|
+
}
|
|
98
111
|
}
|
|
99
112
|
|
|
100
|
-
module.exports = { estimateCheckout, runTaskStart, invokeTaskStart, validateTaskId };
|
|
113
|
+
module.exports = { commonGitDirectory, estimateCheckout, runTaskStart, invokeTaskStart, taskLock, validateTaskId };
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
const fs = require('node:fs');
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
const { randomUUID } = require('node:crypto');
|
|
4
|
+
const { run } = require('./core/runtime');
|
|
5
|
+
const { listWorktrees } = require('./worktree-navigation');
|
|
6
|
+
const { commonGitDirectory, taskLock, validateTaskId } = require('./worktree-start');
|
|
7
|
+
|
|
8
|
+
function taskWorktrees(repoRoot, onlyId) {
|
|
9
|
+
const config = run('git', ['config', '--local', '--null', '--list'], { cwd: repoRoot });
|
|
10
|
+
if (config.status !== 0) throw new Error('Cannot read task identities');
|
|
11
|
+
const settings = new Map();
|
|
12
|
+
const branchesById = new Map();
|
|
13
|
+
for (const record of config.stdout.split('\0')) {
|
|
14
|
+
const end = record.indexOf('\n');
|
|
15
|
+
if (end < 0) continue;
|
|
16
|
+
const key = record.slice(0, end);
|
|
17
|
+
const value = record.slice(end + 1);
|
|
18
|
+
settings.set(key, value);
|
|
19
|
+
}
|
|
20
|
+
for (const [key, value] of settings) {
|
|
21
|
+
const match = key.match(/^branch\.(.+)\.guardextaskid$/);
|
|
22
|
+
if (!match || (onlyId && value !== onlyId)) continue;
|
|
23
|
+
try {
|
|
24
|
+
validateTaskId(value);
|
|
25
|
+
} catch {
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const branches = branchesById.get(value) || [];
|
|
29
|
+
branches.push(match[1]);
|
|
30
|
+
branchesById.set(value, branches);
|
|
31
|
+
}
|
|
32
|
+
if (!branchesById.size) return [];
|
|
33
|
+
const worktrees = new Map();
|
|
34
|
+
for (const entry of listWorktrees(repoRoot)) {
|
|
35
|
+
worktrees.set(entry.branch, worktrees.has(entry.branch) ? null : entry);
|
|
36
|
+
}
|
|
37
|
+
const tasks = [];
|
|
38
|
+
for (const [taskId, branches] of branchesById) {
|
|
39
|
+
if (branches.length !== 1) continue;
|
|
40
|
+
const [branch] = branches;
|
|
41
|
+
const agent = branch.match(/^agent\/([^/]+)\//)?.[1];
|
|
42
|
+
const entry = worktrees.get(branch);
|
|
43
|
+
if (
|
|
44
|
+
!agent ||
|
|
45
|
+
!entry ||
|
|
46
|
+
entry.locked ||
|
|
47
|
+
settings.get(`branch.${branch}.guardexstartready`) !== 'true'
|
|
48
|
+
)
|
|
49
|
+
continue;
|
|
50
|
+
const remote = settings.get(`branch.${branch}.remote`);
|
|
51
|
+
if (
|
|
52
|
+
remote &&
|
|
53
|
+
run('git', ['show-ref', '--verify', '--quiet', `refs/remotes/${remote}/${branch}`], {
|
|
54
|
+
cwd: repoRoot
|
|
55
|
+
}).status !== 0
|
|
56
|
+
)
|
|
57
|
+
continue;
|
|
58
|
+
let worktree;
|
|
59
|
+
try {
|
|
60
|
+
worktree = fs.realpathSync(entry.path);
|
|
61
|
+
if (!fs.lstatSync(path.join(worktree, '.git')).isFile()) continue;
|
|
62
|
+
} catch {
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
tasks.push({ taskId, agent, branch, worktree });
|
|
66
|
+
}
|
|
67
|
+
return tasks.sort((left, right) => left.taskId.localeCompare(right.taskId));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function worktreeBusy(worktree) {
|
|
71
|
+
const { active, supported } =
|
|
72
|
+
require('./finish/post-branch-finish-cleanup').probeWorktreeOwnership(worktree);
|
|
73
|
+
return active || !supported;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function listTasks(repoRoot) {
|
|
77
|
+
const tasks = taskWorktrees(repoRoot).map((task) => ({
|
|
78
|
+
...task,
|
|
79
|
+
busy: worktreeBusy(task.worktree)
|
|
80
|
+
}));
|
|
81
|
+
process.stdout.write(JSON.stringify({ version: 1, tasks }) + '\n');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function findTask(repoRoot, id) {
|
|
85
|
+
const task = taskWorktrees(repoRoot, validateTaskId(id))[0];
|
|
86
|
+
if (!task) throw new Error('Task has no unique, ready linked worktree');
|
|
87
|
+
return task;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function runTask(repoRoot, [id, branch, worktree, separator, ...command]) {
|
|
91
|
+
if (!branch || !worktree || separator !== '--' || !command[0])
|
|
92
|
+
throw new Error('Usage: gx branch run-task <id> <branch> <worktree> -- <command> [args...]');
|
|
93
|
+
if (
|
|
94
|
+
['GIT_DIR', 'GIT_COMMON_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE'].some(
|
|
95
|
+
(key) => key in process.env
|
|
96
|
+
)
|
|
97
|
+
)
|
|
98
|
+
throw new Error('Unset Git checkout overrides before running a task');
|
|
99
|
+
const result = run(
|
|
100
|
+
'python3',
|
|
101
|
+
[
|
|
102
|
+
path.join(__dirname, 'finish/with-claims-lock.py'),
|
|
103
|
+
'--try-lock',
|
|
104
|
+
taskLock(repoRoot, validateTaskId(id), 'task-run'),
|
|
105
|
+
process.execPath,
|
|
106
|
+
__filename,
|
|
107
|
+
id,
|
|
108
|
+
branch,
|
|
109
|
+
worktree,
|
|
110
|
+
...command
|
|
111
|
+
],
|
|
112
|
+
{ cwd: repoRoot, stdio: 'inherit' }
|
|
113
|
+
);
|
|
114
|
+
if (result.error) throw result.error;
|
|
115
|
+
if (result.status === 75)
|
|
116
|
+
console.error('GitGuardex: another launch holds the task lock (or the child exited 75).');
|
|
117
|
+
process.exitCode = result.status ?? (result.signal === 'SIGINT' ? 130 : 1);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (require.main === module) {
|
|
121
|
+
try {
|
|
122
|
+
const [id, branch, worktree, ...command] = process.argv.slice(2);
|
|
123
|
+
// Recheck under the lock: a listing is not authority to write, and a task
|
|
124
|
+
// disappearing between selection and launch must not create another lane.
|
|
125
|
+
const task = findTask(process.cwd(), id);
|
|
126
|
+
if (task.branch !== branch || task.worktree !== worktree)
|
|
127
|
+
throw new Error('Selected task worktree changed; select it again');
|
|
128
|
+
const head = run('git', ['symbolic-ref', 'HEAD'], { cwd: worktree });
|
|
129
|
+
if (
|
|
130
|
+
head.status !== 0 ||
|
|
131
|
+
head.stdout.trim() !== `refs/heads/${branch}` ||
|
|
132
|
+
commonGitDirectory(worktree) !== commonGitDirectory(process.cwd())
|
|
133
|
+
)
|
|
134
|
+
throw new Error('Selected path is not the expected linked worktree');
|
|
135
|
+
if (worktreeBusy(worktree))
|
|
136
|
+
throw new Error('Task worktree is in use or its occupancy cannot be verified');
|
|
137
|
+
require('./agents/supervise').supervise(worktree, randomUUID(), '--', ...command);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
console.error(`GitGuardex: ${error.message}`);
|
|
140
|
+
process.exitCode = 1;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
module.exports = { findTask, listTasks, runTask };
|
|
@@ -16,6 +16,7 @@ routing with `GUARDEX_WORKTREE_MODE=adaptive` in `.env` or
|
|
|
16
16
|
- Claim files before editing in isolated lanes. Confirm a path is in your claim before deleting it.
|
|
17
17
|
- Use CodeGraph first for repository symbol, relationship, architecture, and impact lookup. If the project is not initialized, run `codegraph init -i` once and retry.
|
|
18
18
|
- Use `opensrc path <package-or-owner/repo[@ref|#ref]>` before generic clone/download when inspecting dependency or external repository source.
|
|
19
|
+
- On Linux, run foreground builds, typechecks and full test suites with `gx run-heavy -- <command>`; inspect local capacity with `gx mem-doctor`.
|
|
19
20
|
- Commit, push, and open/update a PR for completed work unless the user says keep-local.
|
|
20
21
|
- Keep outputs and notes compact. Less word, same proof.
|
|
21
22
|
|
|
@@ -13,6 +13,7 @@ single-agent path may opt in with `GUARDEX_WORKTREE_MODE=adaptive` in `.env` (or
|
|
|
13
13
|
- In an isolated lane, claim files before editing: `gx locks claim --branch "<agent-branch>" <file...>`.
|
|
14
14
|
- Use CodeGraph first for repository symbol, relationship, architecture, and impact lookup. If the project is not initialized, run `codegraph init -i` once and retry.
|
|
15
15
|
- Use `opensrc path <package-or-owner/repo[@ref|#ref]>` before generic clone/download when inspecting dependency or external repository source.
|
|
16
|
+
- On Linux, run foreground builds, typechecks and full test suites with `gx run-heavy -- <command>`; inspect local capacity with `gx mem-doctor`.
|
|
16
17
|
- Finish isolated work via PR + cleanup: `gx branch finish --branch "<agent-branch>" --via-pr --wait-for-merge --cleanup` (or `gx finish --all`). Direct adaptive work uses the repository's ordinary commit/push flow.
|
|
17
18
|
- For isolated lanes, default to the self-repairing gated ship — add `--gate-review --gate-autofix` so blocking findings are fixed and re-verified before the merge instead of leaving the PR open. Add `--gate-baseline` only where the base branch CI is already red. CI waits until the review is clean by default; `--no-gate-serial-ci` opts into overlap. Codex code-assist defaults to bounded `medium` effort (override with `GUARDEX_REVIEW_CODEX_EFFORT`). Posting a review is not merging: `gx pr-review` posts and exits; only `gx branch finish` merges. Never ask the user whether to run the review or to merge: review automatically and merge when the gate is clean; stop only when it blocks or the user said keep-local.
|
|
18
19
|
|
|
@@ -10,6 +10,11 @@ Use when a GitGuardex-managed repository needs safe edits or multi-agent coordin
|
|
|
10
10
|
Bootstrap: `gx setup`
|
|
11
11
|
Ops: `gx branch start "<task>" "<agent>"`, `gx locks claim --branch "<agent-branch>" <file...>`, `gx branch finish --branch "<agent-branch>" --base <base> --via-pr --wait-for-merge --cleanup`, `gx finish --all`, `gx cleanup`
|
|
12
12
|
|
|
13
|
+
On Linux, use `gx run-heavy -- <command> [args...]` for foreground builds,
|
|
14
|
+
typechecks and full test suites. Codex and Claude share the same local RAM-based
|
|
15
|
+
queue; `gx mem-doctor` explains why a job would wait. Leave lightweight reads
|
|
16
|
+
and edits unwrapped.
|
|
17
|
+
|
|
13
18
|
## Choose the lane before editing
|
|
14
19
|
|
|
15
20
|
Worktree policy is strict `always` unless the repo opts into `adaptive` with
|
|
@@ -332,10 +332,14 @@ run_preflight() {
|
|
|
332
332
|
finish_progress running preflight "final verification before publish"
|
|
333
333
|
echo "[agent-branch-finish] Running pre-flight: ${script_path}" >&2
|
|
334
334
|
local preflight_status=0
|
|
335
|
+
local runner=()
|
|
336
|
+
if [[ -n "$CLI_ENTRY" ]]; then
|
|
337
|
+
runner=(run_guardex_cli run-heavy --)
|
|
338
|
+
fi
|
|
335
339
|
if [[ -n "$trusted_tree" ]]; then
|
|
336
|
-
( cd "$preflight_cwd" && "$script_path" --guardex-target-worktree "$worktree" ) || preflight_status=$?
|
|
340
|
+
( cd "$preflight_cwd" && "${runner[@]}" "$script_path" --guardex-target-worktree "$worktree" ) || preflight_status=$?
|
|
337
341
|
else
|
|
338
|
-
( cd "$preflight_cwd" && GUARDEX_PREFLIGHT_TARGET_WORKTREE="$worktree" "$script_path" ) || preflight_status=$?
|
|
342
|
+
( cd "$preflight_cwd" && GUARDEX_PREFLIGHT_TARGET_WORKTREE="$worktree" "${runner[@]}" "$script_path" ) || preflight_status=$?
|
|
339
343
|
fi
|
|
340
344
|
if [[ -n "$trusted_tree" ]]; then
|
|
341
345
|
rm -rf -- "$trusted_tree"
|