@imdeadpool/guardex 7.0.43 → 7.1.1

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 (68) hide show
  1. package/README.md +35 -0
  2. package/package.json +4 -1
  3. package/scripts/prepublish-bump-version.js +191 -0
  4. package/skills/gx-act/SKILL.md +82 -0
  5. package/src/agents/activity.js +279 -0
  6. package/src/agents/inspect.js +17 -4
  7. package/src/agents/launch.js +10 -1
  8. package/src/agents/status.js +9 -6
  9. package/src/budget/index.js +2 -1
  10. package/src/cli/args.js +118 -5
  11. package/src/cli/commands/agents.js +381 -0
  12. package/src/cli/commands/bootstrap.js +92 -0
  13. package/src/cli/commands/branch.js +127 -0
  14. package/src/cli/commands/claude.js +674 -0
  15. package/src/cli/commands/doctor.js +268 -0
  16. package/src/cli/commands/finish.js +26 -0
  17. package/src/cli/commands/mcp.js +122 -0
  18. package/src/cli/commands/misc.js +304 -0
  19. package/src/cli/commands/pr.js +439 -0
  20. package/src/cli/commands/prompt.js +92 -0
  21. package/src/cli/commands/release.js +305 -0
  22. package/src/cli/commands/report.js +244 -0
  23. package/src/cli/commands/review.js +32 -0
  24. package/src/cli/commands/setup.js +242 -0
  25. package/src/cli/commands/status.js +338 -0
  26. package/src/cli/commands/watch.js +234 -0
  27. package/src/cli/main.js +68 -3726
  28. package/src/cli/shared/repo-env.js +161 -0
  29. package/src/cli/shared/sandbox.js +417 -0
  30. package/src/cli/shared/scaffolding.js +535 -0
  31. package/src/cli/shared/toolchain-shims.js +420 -0
  32. package/src/context.js +229 -11
  33. package/src/core/runtime.js +6 -1
  34. package/src/doctor/index.js +42 -13
  35. package/src/finish/index.js +147 -5
  36. package/src/finish/preflight.js +177 -0
  37. package/src/finish/review-gate.js +182 -0
  38. package/src/git/index.js +446 -4
  39. package/src/hooks/index.js +0 -64
  40. package/src/mcp/collect.js +394 -0
  41. package/src/mcp/server.js +163 -0
  42. package/src/output/index.js +67 -1
  43. package/src/pr-review.js +23 -0
  44. package/src/pr.js +381 -0
  45. package/src/sandbox/index.js +13 -2
  46. package/src/scaffold/agent-worktree-prep.js +220 -0
  47. package/src/scaffold/index.js +108 -10
  48. package/src/scaffold/provision-config.js +314 -0
  49. package/src/speckit/index.js +226 -0
  50. package/src/terminal/index.js +1 -76
  51. package/src/terminal/kitty.js +20 -0
  52. package/src/terminal/tmux.js +9 -1
  53. package/src/toolchain/index.js +20 -0
  54. package/templates/AGENTS.monorepo-apps.md +26 -0
  55. package/templates/AGENTS.multiagent-safety.md +68 -344
  56. package/templates/AGENTS.multiagent-safety.min.md +11 -0
  57. package/templates/codex/skills/gx-act/SKILL.md +82 -0
  58. package/templates/githooks/pre-commit +22 -19
  59. package/templates/scripts/agent-branch-finish.sh +17 -33
  60. package/templates/scripts/agent-branch-merge.sh +4 -1
  61. package/templates/scripts/agent-branch-start.sh +115 -6
  62. package/templates/scripts/agent-file-locks.py +245 -50
  63. package/templates/scripts/agent-preflight.sh +31 -5
  64. package/templates/scripts/agent-worktree-prune.sh +1 -1
  65. package/templates/scripts/codex-agent.sh +0 -91
  66. package/src/agents/detect.js +0 -160
  67. package/src/cockpit/keybindings.js +0 -224
  68. package/src/cockpit/layout.js +0 -224
@@ -0,0 +1,220 @@
1
+ 'use strict';
2
+
3
+ // Prepares a freshly-created agent worktree for monorepos that have `apps/*`
4
+ // packages. Two jobs:
5
+ //
6
+ // 1. Symlink the root's `apps/<pkg>/.env` (and friends) into the worktree
7
+ // so backend / storefront / etc. can boot with the same secrets without
8
+ // asking the user to copy gitignored env files manually.
9
+ //
10
+ // 2. Pick a free port per app and write it into the worktree's
11
+ // `apps/<pkg>/.env.local` (which both Vite and Medusa's loadEnv read with
12
+ // higher precedence than `.env`). This stops agent dev servers from
13
+ // colliding with whatever's running in the root worktree on the default
14
+ // port.
15
+ //
16
+ // Both jobs are best-effort: if `apps/` doesn't exist, or there are no env
17
+ // files / no package.json in a subfolder, we silently skip — non-monorepo
18
+ // repos see no change.
19
+
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+ const { spawnSync } = require('child_process');
23
+ const { provisionFromConfig } = require('./provision-config');
24
+
25
+ const ENV_FILE_CANDIDATES = [
26
+ '.env',
27
+ '.env.local',
28
+ '.env.development',
29
+ '.env.development.local',
30
+ '.env.production',
31
+ '.env.production.local',
32
+ ];
33
+
34
+ // Port pool by detected app role. Storefronts get the Vite/Next range,
35
+ // backends get the Medusa range, everything else gets a generic mid-range.
36
+ const PORT_POOLS = {
37
+ storefront: 5174,
38
+ backend: 9101,
39
+ default: 8100,
40
+ };
41
+
42
+ function detectAppPackages(repoRoot) {
43
+ const appsRoot = path.join(repoRoot, 'apps');
44
+ let stat;
45
+ try {
46
+ stat = fs.statSync(appsRoot);
47
+ } catch {
48
+ return [];
49
+ }
50
+ if (!stat.isDirectory()) return [];
51
+ let entries;
52
+ try {
53
+ entries = fs.readdirSync(appsRoot, { withFileTypes: true });
54
+ } catch {
55
+ return [];
56
+ }
57
+ return entries
58
+ .filter((e) => e.isDirectory())
59
+ .map((e) => e.name)
60
+ .filter((name) => fs.existsSync(path.join(appsRoot, name, 'package.json')));
61
+ }
62
+
63
+ function inferAppRole(appName) {
64
+ const n = appName.toLowerCase();
65
+ if (n.includes('storefront') || n.includes('frontend') || n.includes('web')) {
66
+ return 'storefront';
67
+ }
68
+ if (n.includes('backend') || n.includes('api') || n.includes('server')) {
69
+ return 'backend';
70
+ }
71
+ return 'default';
72
+ }
73
+
74
+ function isPortFree(port) {
75
+ // Use `lsof` if available — it's on macOS and most Linux distros. Fall
76
+ // back to assuming free when lsof isn't installed (e.g. minimal Alpine
77
+ // CI image); the dev server will fail loudly if it isn't.
78
+ const probe = spawnSync('lsof', ['-iTCP:' + port, '-sTCP:LISTEN', '-t'], {
79
+ stdio: ['ignore', 'pipe', 'pipe'],
80
+ timeout: 2000,
81
+ });
82
+ if (probe.error) return true;
83
+ const out = (probe.stdout && probe.stdout.toString().trim()) || '';
84
+ return out === '';
85
+ }
86
+
87
+ function pickFreePort(start) {
88
+ for (let p = start; p < start + 200; p++) {
89
+ if (isPortFree(p)) return p;
90
+ }
91
+ return null;
92
+ }
93
+
94
+ function symlinkAppEnvFiles(repoRoot, worktreePath, appName) {
95
+ const operations = [];
96
+ const rootAppDir = path.join(repoRoot, 'apps', appName);
97
+ const wtAppDir = path.join(worktreePath, 'apps', appName);
98
+ if (!fs.existsSync(wtAppDir)) {
99
+ return operations;
100
+ }
101
+ for (const candidate of ENV_FILE_CANDIDATES) {
102
+ const rootEnv = path.join(rootAppDir, candidate);
103
+ const wtEnv = path.join(wtAppDir, candidate);
104
+ if (!fs.existsSync(rootEnv)) continue;
105
+ // Don't overwrite an existing file/symlink in the worktree.
106
+ let alreadyExists = false;
107
+ try {
108
+ fs.lstatSync(wtEnv);
109
+ alreadyExists = true;
110
+ } catch (err) {
111
+ if (err.code !== 'ENOENT') throw err;
112
+ }
113
+ if (alreadyExists) {
114
+ operations.push({
115
+ status: 'unchanged',
116
+ file: `apps/${appName}/${candidate}`,
117
+ note: 'already present in worktree',
118
+ });
119
+ continue;
120
+ }
121
+ try {
122
+ fs.symlinkSync(rootEnv, wtEnv);
123
+ operations.push({
124
+ status: 'linked',
125
+ file: `apps/${appName}/${candidate}`,
126
+ note: `→ ${path.relative(worktreePath, rootEnv)}`,
127
+ });
128
+ } catch (err) {
129
+ operations.push({
130
+ status: 'failed',
131
+ file: `apps/${appName}/${candidate}`,
132
+ note: `symlink failed: ${err.message}`,
133
+ });
134
+ }
135
+ }
136
+ return operations;
137
+ }
138
+
139
+ function assignAgentPort(repoRoot, worktreePath, appName, takenPorts) {
140
+ const wtAppDir = path.join(worktreePath, 'apps', appName);
141
+ if (!fs.existsSync(wtAppDir)) {
142
+ return { status: 'skipped', file: `apps/${appName}`, note: 'no app dir in worktree' };
143
+ }
144
+ const role = inferAppRole(appName);
145
+ const base = PORT_POOLS[role] || PORT_POOLS.default;
146
+ let port = pickFreePort(base);
147
+ // Bump past anything we've already assigned this run.
148
+ while (port !== null && takenPorts.has(port)) {
149
+ port = pickFreePort(port + 1);
150
+ }
151
+ if (port === null) {
152
+ return {
153
+ status: 'failed',
154
+ file: `apps/${appName}/.env.local`,
155
+ note: 'no free port found in pool',
156
+ };
157
+ }
158
+ takenPorts.add(port);
159
+
160
+ const envLocalPath = path.join(wtAppDir, '.env.local');
161
+ let existing = '';
162
+ try {
163
+ existing = fs.readFileSync(envLocalPath, 'utf8');
164
+ } catch (err) {
165
+ if (err.code !== 'ENOENT') throw err;
166
+ }
167
+
168
+ // If a .env.local already exists, replace the PORT= line if present,
169
+ // otherwise append. Keep everything else the user might have added.
170
+ const portLine = `PORT=${port}`;
171
+ let next;
172
+ if (/^PORT=/m.test(existing)) {
173
+ next = existing.replace(/^PORT=.*$/m, portLine);
174
+ } else {
175
+ const sep = existing.length === 0 || existing.endsWith('\n') ? '' : '\n';
176
+ next = `${existing}${sep}${portLine}\n`;
177
+ // Header on fresh files so the user knows what wrote this.
178
+ if (existing.length === 0) {
179
+ next = `# Written by gitguardex on worktree creation — agent dev server port.\n${portLine}\n`;
180
+ }
181
+ }
182
+ fs.writeFileSync(envLocalPath, next, 'utf8');
183
+ return {
184
+ status: 'wrote',
185
+ file: `apps/${appName}/.env.local`,
186
+ note: `PORT=${port} (${role} pool)`,
187
+ };
188
+ }
189
+
190
+ function prepareAgentWorktree(repoRoot, worktreePath) {
191
+ if (!repoRoot || !worktreePath) return [];
192
+ if (repoRoot === worktreePath) return [];
193
+ if (!fs.existsSync(worktreePath)) return [];
194
+
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);
204
+ const takenPorts = new Set();
205
+ for (const appName of apps) {
206
+ operations.push(...symlinkAppEnvFiles(repoRoot, worktreePath, appName));
207
+ operations.push(assignAgentPort(repoRoot, worktreePath, appName, takenPorts));
208
+ }
209
+ return operations;
210
+ }
211
+
212
+ module.exports = {
213
+ detectAppPackages,
214
+ inferAppRole,
215
+ isPortFree,
216
+ pickFreePort,
217
+ symlinkAppEnvFiles,
218
+ assignAgentPort,
219
+ prepareAgentWorktree,
220
+ };
@@ -14,6 +14,8 @@ const {
14
14
  USER_LEVEL_SKILL_ASSETS,
15
15
  AGENTS_MARKER_START,
16
16
  AGENTS_MARKER_END,
17
+ MONOREPO_MARKER_START,
18
+ MONOREPO_MARKER_END,
17
19
  GITIGNORE_MARKER_START,
18
20
  GITIGNORE_MARKER_END,
19
21
  SHARED_VSCODE_SETTINGS_RELATIVE,
@@ -500,31 +502,54 @@ function removeLegacyManagedRepoFile(repoRoot, relativePath, options = {}) {
500
502
  return { status: dryRun ? 'would-remove' : 'removed', file: relativePath };
501
503
  }
502
504
 
503
- function ensureAgentsSnippet(repoRoot, dryRun) {
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.
518
+ function ensureAgentsSnippet(repoRoot, dryRun, options = {}) {
504
519
  const agentsPath = path.join(repoRoot, 'AGENTS.md');
505
- const snippet = fs.readFileSync(path.join(TEMPLATE_ROOT, 'AGENTS.multiagent-safety.md'), 'utf8').trimEnd();
506
520
  const managedRegex = new RegExp(
507
521
  `${AGENTS_MARKER_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[\\s\\S]*?${AGENTS_MARKER_END.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`,
508
522
  'm',
509
523
  );
510
524
 
511
- if (!fs.existsSync(agentsPath)) {
525
+ const existing = fs.existsSync(agentsPath) ? fs.readFileSync(agentsPath, 'utf8') : null;
526
+ 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;
530
+
531
+ const templateFile = wantFull
532
+ ? 'AGENTS.multiagent-safety.md'
533
+ : 'AGENTS.multiagent-safety.min.md';
534
+ const snippet = fs.readFileSync(path.join(TEMPLATE_ROOT, templateFile), 'utf8').trimEnd();
535
+ const variant = wantFull ? 'full contract block' : 'minimal block';
536
+
537
+ if (existing == null) {
512
538
  if (!dryRun) {
513
539
  fs.writeFileSync(agentsPath, `# AGENTS\n\n${snippet}\n`, 'utf8');
514
540
  }
515
- return { status: 'created', file: 'AGENTS.md' };
541
+ return { status: 'created', file: 'AGENTS.md', note: variant };
516
542
  }
517
543
 
518
- const existing = fs.readFileSync(agentsPath, 'utf8');
519
- if (managedRegex.test(existing)) {
520
- const next = existing.replace(managedRegex, snippet);
544
+ if (existingBlock) {
545
+ const next = existing.replace(managedRegex, () => snippet);
521
546
  if (next === existing) {
522
- return { status: 'unchanged', file: 'AGENTS.md' };
547
+ return { status: 'unchanged', file: 'AGENTS.md', note: variant };
523
548
  }
524
549
  if (!dryRun) {
525
550
  fs.writeFileSync(agentsPath, next, 'utf8');
526
551
  }
527
- return { status: 'updated', file: 'AGENTS.md', note: 'refreshed gitguardex-managed block' };
552
+ return { status: 'updated', file: 'AGENTS.md', note: `refreshed gitguardex-managed block (${variant})` };
528
553
  }
529
554
 
530
555
  if (existing.includes(AGENTS_MARKER_START)) {
@@ -536,7 +561,7 @@ function ensureAgentsSnippet(repoRoot, dryRun) {
536
561
  fs.writeFileSync(agentsPath, `${existing}${separator}${snippet}\n`, 'utf8');
537
562
  }
538
563
 
539
- return { status: 'updated', file: 'AGENTS.md' };
564
+ return { status: 'updated', file: 'AGENTS.md', note: variant };
540
565
  }
541
566
 
542
567
  function ensureClaudeAgentsLink(repoRoot, dryRun) {
@@ -557,6 +582,77 @@ function ensureClaudeAgentsLink(repoRoot, dryRun) {
557
582
  return { status: dryRun ? 'would-create' : 'created', file: 'CLAUDE.md', note: 'symlink to AGENTS.md' };
558
583
  }
559
584
 
585
+ function detectMonorepoApps(repoRoot) {
586
+ const appsDir = path.join(repoRoot, 'apps');
587
+ let stat;
588
+ try {
589
+ stat = fs.statSync(appsDir);
590
+ } catch {
591
+ return false;
592
+ }
593
+ if (!stat.isDirectory()) return false;
594
+ let entries;
595
+ try {
596
+ entries = fs.readdirSync(appsDir, { withFileTypes: true });
597
+ } catch {
598
+ return false;
599
+ }
600
+ return entries.some(
601
+ (entry) =>
602
+ entry.isDirectory() &&
603
+ fs.existsSync(path.join(appsDir, entry.name, 'package.json')),
604
+ );
605
+ }
606
+
607
+ function ensureMonorepoAppsSnippet(repoRoot, dryRun) {
608
+ const agentsPath = path.join(repoRoot, 'AGENTS.md');
609
+ if (!detectMonorepoApps(repoRoot)) {
610
+ return {
611
+ status: 'skipped',
612
+ file: 'AGENTS.md',
613
+ note: 'no apps/<pkg>/package.json detected — monorepo block not needed',
614
+ };
615
+ }
616
+ const snippet = fs
617
+ .readFileSync(path.join(TEMPLATE_ROOT, 'AGENTS.monorepo-apps.md'), 'utf8')
618
+ .trimEnd();
619
+ const managedRegex = new RegExp(
620
+ `${MONOREPO_MARKER_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[\\s\\S]*?${MONOREPO_MARKER_END.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`,
621
+ 'm',
622
+ );
623
+
624
+ // Ensure AGENTS.md exists first (created by ensureAgentsSnippet upstream).
625
+ if (!fs.existsSync(agentsPath)) {
626
+ if (!dryRun) {
627
+ fs.writeFileSync(agentsPath, `# AGENTS\n\n${snippet}\n`, 'utf8');
628
+ }
629
+ return { status: 'created', file: 'AGENTS.md', note: 'monorepo-apps block' };
630
+ }
631
+
632
+ const existing = fs.readFileSync(agentsPath, 'utf8');
633
+ if (managedRegex.test(existing)) {
634
+ const next = existing.replace(managedRegex, snippet);
635
+ if (next === existing) {
636
+ return { status: 'unchanged', file: 'AGENTS.md', note: 'monorepo-apps block' };
637
+ }
638
+ if (!dryRun) {
639
+ fs.writeFileSync(agentsPath, next, 'utf8');
640
+ }
641
+ return {
642
+ status: 'updated',
643
+ file: 'AGENTS.md',
644
+ note: 'refreshed monorepo-apps block',
645
+ };
646
+ }
647
+
648
+ const separator = existing.endsWith('\n') ? '\n' : '\n\n';
649
+ if (!dryRun) {
650
+ fs.writeFileSync(agentsPath, `${existing}${separator}${snippet}\n`, 'utf8');
651
+ }
652
+
653
+ return { status: 'updated', file: 'AGENTS.md', note: 'appended monorepo-apps block' };
654
+ }
655
+
560
656
  function ensureManagedGitignore(repoRoot, dryRun) {
561
657
  const gitignorePath = path.join(repoRoot, '.gitignore');
562
658
  const managedBlock = [
@@ -782,6 +878,8 @@ module.exports = {
782
878
  removeLegacyManagedRepoFile,
783
879
  ensureAgentsSnippet,
784
880
  ensureClaudeAgentsLink,
881
+ ensureMonorepoAppsSnippet,
882
+ detectMonorepoApps,
785
883
  ensureManagedGitignore,
786
884
  parseJsonObjectLikeFile,
787
885
  buildRepoVscodeSettings,
@@ -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
+ };