@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
@@ -20,6 +20,7 @@
20
20
  const fs = require('fs');
21
21
  const path = require('path');
22
22
  const { spawnSync } = require('child_process');
23
+ const { provisionFromConfig } = require('./provision-config');
23
24
 
24
25
  const ENV_FILE_CANDIDATES = [
25
26
  '.env',
@@ -190,10 +191,16 @@ function prepareAgentWorktree(repoRoot, worktreePath) {
190
191
  if (!repoRoot || !worktreePath) return [];
191
192
  if (repoRoot === worktreePath) return [];
192
193
  if (!fs.existsSync(worktreePath)) return [];
193
- const apps = detectAppPackages(repoRoot);
194
- if (apps.length === 0) return [];
195
194
 
196
195
  const operations = [];
196
+
197
+ // Declarative `.guardex.json` provisioning runs for ANY repo (monorepo or
198
+ // not) — copy/symlink gitignored files and run post_create hooks.
199
+ operations.push(...provisionFromConfig(repoRoot, worktreePath));
200
+
201
+ // Built-in apps/* monorepo convenience: env-file symlinks + a free dev port
202
+ // per app. Stays as the zero-config default for monorepos.
203
+ const apps = detectAppPackages(repoRoot);
197
204
  const takenPorts = new Set();
198
205
  for (const appName of apps) {
199
206
  operations.push(...symlinkAppEnvFiles(repoRoot, worktreePath, appName));
@@ -502,19 +502,9 @@ function removeLegacyManagedRepoFile(repoRoot, relativePath, options = {}) {
502
502
  return { status: dryRun ? 'would-remove' : 'removed', file: relativePath };
503
503
  }
504
504
 
505
- // A managed block longer than this many non-blank lines is treated as the full
506
- // contract. The minimal block is ~8 lines and the full contract is ~171, so any
507
- // threshold between the two is safe; 40 leaves a wide margin on both sides.
508
- const FULL_BLOCK_LINE_THRESHOLD = 40;
509
-
510
- function countNonBlankLines(text) {
511
- return text.split('\n').filter((line) => line.trim().length > 0).length;
512
- }
513
-
514
- // Default install ships the minimal block; the full 171-line contract is opt-in
515
- // via `options.contract` (--contract / --full). Once a repo has the full block,
516
- // it is never silently downgraded: an existing managed block over the line
517
- // threshold keeps refreshing from the full template even without the flag.
505
+ // The full contract is deliberately non-sticky: normal setup refreshes return
506
+ // to the token-light minimal block. Repositories that need the expanded policy
507
+ // must opt in explicitly with --contract on that refresh.
518
508
  function ensureAgentsSnippet(repoRoot, dryRun, options = {}) {
519
509
  const agentsPath = path.join(repoRoot, 'AGENTS.md');
520
510
  const managedRegex = new RegExp(
@@ -524,9 +514,7 @@ function ensureAgentsSnippet(repoRoot, dryRun, options = {}) {
524
514
 
525
515
  const existing = fs.existsSync(agentsPath) ? fs.readFileSync(agentsPath, 'utf8') : null;
526
516
  const existingBlock = existing ? existing.match(managedRegex) : null;
527
- const existingIsFull = Boolean(existingBlock)
528
- && countNonBlankLines(existingBlock[0]) > FULL_BLOCK_LINE_THRESHOLD;
529
- const wantFull = Boolean(options.contract) || existingIsFull;
517
+ const wantFull = Boolean(options.contract);
530
518
 
531
519
  const templateFile = wantFull
532
520
  ? 'AGENTS.multiagent-safety.md'
@@ -0,0 +1,314 @@
1
+ 'use strict';
2
+
3
+ // Declarative per-repo worktree provisioning (workmux W2).
4
+ //
5
+ // A repo may commit a `.guardex.json` at its root describing how to make a
6
+ // fresh agent worktree usable — which gitignored files to copy or symlink in,
7
+ // and which setup commands to run after creation:
8
+ //
9
+ // {
10
+ // "provision": {
11
+ // "files": {
12
+ // "copy": [".env", "apps/*/.env"], // per-worktree copies
13
+ // "symlink": ["node_modules", ".venv"] // shared via symlink
14
+ // },
15
+ // "postCreate": ["pnpm install --offline"]
16
+ // }
17
+ // }
18
+ //
19
+ // Parsed with jsonc-parser (comments allowed) — no new dependency. copy/symlink
20
+ // are pure filesystem ops. postCreate runs shell commands from the repo owner's
21
+ // committed config (same trust as package.json scripts); disable with
22
+ // GUARDEX_PROVISION_HOOKS=0. Everything is best-effort and never throws fatally.
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const { spawnSync } = require('child_process');
27
+ const jsonc = require('jsonc-parser');
28
+
29
+ const CONFIG_BASENAME = '.guardex.json';
30
+ const POST_CREATE_TIMEOUT_MS = 10 * 60 * 1000;
31
+
32
+ function toStringArray(value) {
33
+ if (!Array.isArray(value)) return [];
34
+ return value.filter((item) => typeof item === 'string' && item.trim() !== '');
35
+ }
36
+
37
+ // Read + normalize <repoRoot>/.guardex.json's `provision` block. Returns null
38
+ // when there is no config or no provision block; tolerant of malformed JSON.
39
+ function loadProvisionConfig(repoRoot, deps = {}) {
40
+ if (!repoRoot) return null;
41
+ const readFile = deps.readFile || ((p) => fs.readFileSync(p, 'utf8'));
42
+ const configPath = path.join(repoRoot, CONFIG_BASENAME);
43
+
44
+ let text;
45
+ try {
46
+ text = readFile(configPath);
47
+ } catch (error) {
48
+ if (error && error.code === 'ENOENT') return null;
49
+ return null;
50
+ }
51
+
52
+ const errors = [];
53
+ const parsed = jsonc.parse(text, errors, { allowTrailingComma: true });
54
+ if (errors.length > 0 || !parsed || typeof parsed !== 'object') {
55
+ return null;
56
+ }
57
+
58
+ const provision = parsed.provision;
59
+ if (!provision || typeof provision !== 'object' || Array.isArray(provision)) {
60
+ return null;
61
+ }
62
+
63
+ const files = provision.files && typeof provision.files === 'object' ? provision.files : {};
64
+ return {
65
+ source: configPath,
66
+ files: {
67
+ copy: toStringArray(files.copy),
68
+ symlink: toStringArray(files.symlink),
69
+ },
70
+ postCreate: toStringArray(provision.postCreate),
71
+ };
72
+ }
73
+
74
+ // A provisioning pattern must stay inside the repo: no absolute paths, no `..`.
75
+ function isUnsafePattern(pattern) {
76
+ if (typeof pattern !== 'string' || pattern.trim() === '') return true;
77
+ if (path.isAbsolute(pattern)) return true;
78
+ return pattern.split(/[\\/]/).some((segment) => segment === '..');
79
+ }
80
+
81
+ function segmentToRegExp(segment) {
82
+ // Only `*` is special (matches within a single path segment). Everything else
83
+ // is literal.
84
+ const escaped = segment.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*');
85
+ return new RegExp(`^${escaped}$`);
86
+ }
87
+
88
+ // Minimal, dependency-free glob: literal segments plus a `*` wildcard within a
89
+ // single path segment (covers `.env`, `apps/*/.env`, `packages/*/.env`,
90
+ // `node_modules`). Returns repo-relative paths that exist.
91
+ function expandGlob(rootDir, pattern, deps = {}) {
92
+ if (isUnsafePattern(pattern)) return [];
93
+ const readdir = deps.readdir || ((p) => fs.readdirSync(p, { withFileTypes: true }));
94
+ const exists = deps.exists || ((p) => fs.existsSync(p));
95
+
96
+ const segments = pattern.split('/').filter((segment) => segment !== '' && segment !== '.');
97
+ let matches = [''];
98
+
99
+ for (const segment of segments) {
100
+ const next = [];
101
+ const hasWildcard = segment.includes('*');
102
+ for (const rel of matches) {
103
+ const absDir = path.join(rootDir, rel);
104
+ if (!hasWildcard) {
105
+ const candidate = rel ? `${rel}/${segment}` : segment;
106
+ if (exists(path.join(rootDir, candidate))) next.push(candidate);
107
+ continue;
108
+ }
109
+ let entries;
110
+ try {
111
+ entries = readdir(absDir);
112
+ } catch {
113
+ continue;
114
+ }
115
+ const re = segmentToRegExp(segment);
116
+ for (const entry of entries) {
117
+ const name = entry && entry.name ? entry.name : entry;
118
+ if (typeof name === 'string' && re.test(name)) {
119
+ next.push(rel ? `${rel}/${name}` : name);
120
+ }
121
+ }
122
+ }
123
+ matches = next;
124
+ }
125
+
126
+ return matches.filter((rel) => rel !== '');
127
+ }
128
+
129
+ function ensureParentDir(filePath) {
130
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
131
+ }
132
+
133
+ function safeRealpath(target) {
134
+ try {
135
+ return fs.realpathSync(target);
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
140
+
141
+ // True only when `target` (after resolving symlinks) stays inside `baseReal`.
142
+ // isUnsafePattern fences the pattern STRING; this fences the real filesystem so
143
+ // an in-repo symlink (e.g. `link -> /etc`) can't escape on read or write.
144
+ function withinReal(target, baseReal) {
145
+ if (!baseReal) return false;
146
+ const real = safeRealpath(target);
147
+ if (!real) return false;
148
+ return real === baseReal || real.startsWith(baseReal + path.sep);
149
+ }
150
+
151
+ function targetAlreadyPresent(destPath) {
152
+ try {
153
+ fs.lstatSync(destPath);
154
+ return true;
155
+ } catch (error) {
156
+ if (error && error.code !== 'ENOENT') throw error;
157
+ return false;
158
+ }
159
+ }
160
+
161
+ function applyCopy(repoRoot, worktreePath, patterns, deps = {}) {
162
+ const operations = [];
163
+ const repoReal = safeRealpath(repoRoot);
164
+ const worktreeReal = safeRealpath(worktreePath);
165
+ for (const pattern of patterns) {
166
+ const rels = expandGlob(repoRoot, pattern, deps);
167
+ if (rels.length === 0) {
168
+ operations.push({ status: 'skipped', file: pattern, note: 'no match in repo root' });
169
+ continue;
170
+ }
171
+ for (const rel of rels) {
172
+ const src = path.join(repoRoot, rel);
173
+ const dest = path.join(worktreePath, rel);
174
+ try {
175
+ // Source must resolve inside the repo (block in-repo symlink escapes).
176
+ if (!withinReal(src, repoReal)) {
177
+ operations.push({ status: 'skipped', file: rel, note: 'resolves outside repo root' });
178
+ continue;
179
+ }
180
+ if (fs.statSync(src).isDirectory()) {
181
+ operations.push({ status: 'skipped', file: rel, note: 'copy of a directory unsupported; use symlink' });
182
+ continue;
183
+ }
184
+ if (targetAlreadyPresent(dest)) {
185
+ operations.push({ status: 'unchanged', file: rel, note: 'already present in worktree' });
186
+ continue;
187
+ }
188
+ ensureParentDir(dest);
189
+ // Destination parent must resolve inside the worktree (block writes that
190
+ // tunnel through a symlink the worktree may already contain).
191
+ if (!withinReal(path.dirname(dest), worktreeReal)) {
192
+ operations.push({ status: 'skipped', file: rel, note: 'destination escapes worktree' });
193
+ continue;
194
+ }
195
+ fs.copyFileSync(src, dest);
196
+ operations.push({ status: 'copied', file: rel, note: 'copied from repo root' });
197
+ } catch (error) {
198
+ operations.push({ status: 'failed', file: rel, note: `copy failed: ${error.message}` });
199
+ }
200
+ }
201
+ }
202
+ return operations;
203
+ }
204
+
205
+ function applySymlink(repoRoot, worktreePath, patterns, deps = {}) {
206
+ const operations = [];
207
+ const repoReal = safeRealpath(repoRoot);
208
+ const worktreeReal = safeRealpath(worktreePath);
209
+ for (const pattern of patterns) {
210
+ const rels = expandGlob(repoRoot, pattern, deps);
211
+ if (rels.length === 0) {
212
+ operations.push({ status: 'skipped', file: pattern, note: 'no match in repo root' });
213
+ continue;
214
+ }
215
+ for (const rel of rels) {
216
+ const src = path.join(repoRoot, rel);
217
+ const dest = path.join(worktreePath, rel);
218
+ try {
219
+ // The symlink target must resolve inside the repo.
220
+ if (!withinReal(src, repoReal)) {
221
+ operations.push({ status: 'skipped', file: rel, note: 'resolves outside repo root' });
222
+ continue;
223
+ }
224
+ if (targetAlreadyPresent(dest)) {
225
+ operations.push({ status: 'unchanged', file: rel, note: 'already present in worktree' });
226
+ continue;
227
+ }
228
+ ensureParentDir(dest);
229
+ if (!withinReal(path.dirname(dest), worktreeReal)) {
230
+ operations.push({ status: 'skipped', file: rel, note: 'destination escapes worktree' });
231
+ continue;
232
+ }
233
+ fs.symlinkSync(src, dest);
234
+ operations.push({ status: 'linked', file: rel, note: `→ ${path.relative(worktreePath, src)}` });
235
+ } catch (error) {
236
+ operations.push({ status: 'failed', file: rel, note: `symlink failed: ${error.message}` });
237
+ }
238
+ }
239
+ }
240
+ return operations;
241
+ }
242
+
243
+ function hooksDisabled() {
244
+ const flag = String(process.env.GUARDEX_PROVISION_HOOKS || '').trim().toLowerCase();
245
+ return ['0', 'false', 'no', 'off'].includes(flag);
246
+ }
247
+
248
+ function applyPostCreate(repoRoot, worktreePath, commands, deps = {}) {
249
+ if (commands.length === 0) return [];
250
+ if (hooksDisabled()) {
251
+ return commands.map((command) => ({ status: 'skipped', file: command, note: 'GUARDEX_PROVISION_HOOKS disabled' }));
252
+ }
253
+ const run = deps.run || ((cmd, cwd, env) => spawnSync('sh', ['-lc', cmd], {
254
+ cwd,
255
+ env,
256
+ stdio: ['ignore', 'pipe', 'pipe'],
257
+ timeout: POST_CREATE_TIMEOUT_MS,
258
+ }));
259
+
260
+ const operations = [];
261
+ const env = { ...process.env, GUARDEX_WORKTREE: worktreePath, GUARDEX_REPO_ROOT: repoRoot };
262
+ for (const command of commands) {
263
+ let result;
264
+ try {
265
+ result = run(command, worktreePath, env);
266
+ } catch (error) {
267
+ operations.push({ status: 'failed', file: command, note: `hook error: ${error.message}` });
268
+ continue;
269
+ }
270
+ const ok = result && (result.status === 0 || result.status === undefined) && !result.error;
271
+ operations.push(
272
+ ok
273
+ ? { status: 'ran', file: command, note: 'post_create hook ok' }
274
+ : {
275
+ status: 'failed',
276
+ file: command,
277
+ note: `post_create exited ${result && result.status}${result && result.error ? `: ${result.error.message}` : ''}`,
278
+ },
279
+ );
280
+ }
281
+ return operations;
282
+ }
283
+
284
+ // Apply a normalized provision config to a worktree. Order: copy, symlink, then
285
+ // postCreate hooks (so hooks see the env/deps already in place). Best-effort.
286
+ function applyProvisionConfig(repoRoot, worktreePath, config, deps = {}) {
287
+ if (!config) return [];
288
+ const operations = [];
289
+ operations.push(...applyCopy(repoRoot, worktreePath, config.files.copy, deps));
290
+ operations.push(...applySymlink(repoRoot, worktreePath, config.files.symlink, deps));
291
+ operations.push(...applyPostCreate(repoRoot, worktreePath, config.postCreate, deps));
292
+ return operations;
293
+ }
294
+
295
+ // Convenience: load + apply for a freshly created worktree.
296
+ function provisionFromConfig(repoRoot, worktreePath, deps = {}) {
297
+ if (!repoRoot || !worktreePath || repoRoot === worktreePath) return [];
298
+ if (!fs.existsSync(worktreePath)) return [];
299
+ const config = loadProvisionConfig(repoRoot, deps);
300
+ if (!config) return [];
301
+ return applyProvisionConfig(repoRoot, worktreePath, config, deps);
302
+ }
303
+
304
+ module.exports = {
305
+ CONFIG_BASENAME,
306
+ loadProvisionConfig,
307
+ expandGlob,
308
+ isUnsafePattern,
309
+ applyCopy,
310
+ applySymlink,
311
+ applyPostCreate,
312
+ applyProvisionConfig,
313
+ provisionFromConfig,
314
+ };