@imdeadpool/guardex 8.4.0 → 8.4.2

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 (97) hide show
  1. package/CONTRIBUTING.md +13 -4
  2. package/README.md +223 -1
  3. package/THIRD-PARTY-NOTICES.md +29 -0
  4. package/bin/multiagent-safety.js +9 -12
  5. package/package.json +4 -2
  6. package/skills/gitguardex/SKILL.md +28 -0
  7. package/skills/pr-lens/SKILL.md +87 -0
  8. package/src/abide.js +534 -0
  9. package/src/agents/activity.js +23 -4
  10. package/src/agents/inspect.js +15 -6
  11. package/src/agents/launch.js +6 -1
  12. package/src/agents/process-lease.js +84 -0
  13. package/src/agents/sessions.js +96 -16
  14. package/src/agents/start.js +18 -9
  15. package/src/agents/status.js +35 -14
  16. package/src/agents/supervise.js +87 -0
  17. package/src/budget/index.js +6 -1
  18. package/src/cli/args.js +71 -77
  19. package/src/cli/commands/agents.js +38 -10
  20. package/src/cli/commands/branch.js +116 -103
  21. package/src/cli/commands/claude.js +604 -50
  22. package/src/cli/commands/codex.js +359 -0
  23. package/src/cli/commands/context.js +52 -0
  24. package/src/cli/commands/mcp.js +5 -1
  25. package/src/cli/commands/pr.js +138 -3
  26. package/src/cli/commands/review.js +3 -1
  27. package/src/cli/commands/setup.js +25 -0
  28. package/src/cli/commands/status.js +128 -60
  29. package/src/cli/commands/storage.js +24 -0
  30. package/src/cli/commands/usage.js +48 -0
  31. package/src/cli/commands/watch.js +157 -47
  32. package/src/cli/commands/worktree-copy-ignored.js +38 -0
  33. package/src/cli/commands/worktree-estimate.js +69 -0
  34. package/src/cli/commands/worktree-hooks.js +62 -0
  35. package/src/cli/commands/worktree-navigation.js +71 -0
  36. package/src/cli/commands/worktree-provision.js +92 -0
  37. package/src/cli/main.js +229 -110
  38. package/src/cli/shared/gate-flags.js +131 -0
  39. package/src/cli/shared/scaffolding.js +31 -3
  40. package/src/cli/shared-locks.js +3 -1
  41. package/src/cockpit/pane-actions.js +43 -7
  42. package/src/context.js +373 -17
  43. package/src/doctor/index.js +29 -35
  44. package/src/finish/events.js +254 -0
  45. package/src/finish/index.js +322 -62
  46. package/src/finish/post-branch-finish-cleanup.js +316 -22
  47. package/src/finish/preflight.js +44 -1
  48. package/src/finish/progress.js +36 -0
  49. package/src/finish/review-gate.js +317 -127
  50. package/src/finish/review-receipt.js +156 -0
  51. package/src/finish/with-claims-lock.py +29 -0
  52. package/src/git/index.js +179 -42
  53. package/src/hooks/index.js +68 -3
  54. package/src/mcp/collect.js +61 -5
  55. package/src/mcp/server.js +4 -0
  56. package/src/output/index.js +167 -1
  57. package/src/pr-lens-publish.js +93 -0
  58. package/src/pr-lens.js +184 -0
  59. package/src/pr-respond.js +860 -0
  60. package/src/pr-review.js +519 -159
  61. package/src/pr.js +73 -14
  62. package/src/provider-binary.js +21 -0
  63. package/src/review-diff-context.js +90 -0
  64. package/src/review-fix.js +23 -17
  65. package/src/scaffold/agent-worktree-prep.js +14 -12
  66. package/src/scaffold/dependency-store.js +234 -0
  67. package/src/scaffold/index.js +13 -1
  68. package/src/scaffold/provision-approvals.js +83 -0
  69. package/src/scaffold/provision-config.js +169 -40
  70. package/src/shared-git-state.js +11 -1
  71. package/src/speckit/index.js +12 -1
  72. package/src/storage/run-artifacts.js +185 -0
  73. package/src/toolchain/index.js +322 -2
  74. package/src/worktree-copy-ignored.js +200 -0
  75. package/src/worktree-hook-worker.js +29 -0
  76. package/src/worktree-hooks.js +333 -0
  77. package/src/worktree-navigation.js +248 -0
  78. package/src/worktree-picker.js +89 -0
  79. package/src/worktree-quota.js +100 -0
  80. package/src/worktree-start.js +100 -0
  81. package/templates/AGENTS.multiagent-safety.md +8 -0
  82. package/templates/AGENTS.multiagent-safety.min.md +3 -1
  83. package/templates/codex/skills/gitguardex/SKILL.md +28 -0
  84. package/templates/codex/skills/opensrc/SKILL.md +24 -0
  85. package/templates/githooks/post-merge +16 -2
  86. package/templates/scripts/agent-autofinish-watch.sh +17 -18
  87. package/templates/scripts/agent-branch-finish.sh +180 -19
  88. package/templates/scripts/agent-branch-merge.sh +7 -32
  89. package/templates/scripts/agent-branch-start.sh +202 -43
  90. package/templates/scripts/agent-claude-stop-finish.sh +4 -27
  91. package/templates/scripts/agent-file-locks.py +257 -29
  92. package/templates/scripts/agent-preflight.sh +3 -0
  93. package/templates/scripts/agent-worktree-prune.sh +975 -63
  94. package/templates/scripts/codex-agent.sh +55 -5
  95. package/templates/scripts/lib/guardex-base-branch.sh +207 -0
  96. package/templates/scripts/openspec/init-change-workspace.sh +10 -18
  97. package/templates/scripts/review-bot-watch.sh +171 -4
@@ -0,0 +1,234 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { createHash } = require('node:crypto');
6
+ const { spawnSync } = require('node:child_process');
7
+
8
+ const LOCKFILES = [
9
+ 'package-lock.json',
10
+ 'npm-shrinkwrap.json',
11
+ 'pnpm-lock.yaml',
12
+ 'yarn.lock',
13
+ 'bun.lock',
14
+ 'bun.lockb',
15
+ 'uv.lock',
16
+ 'poetry.lock',
17
+ 'requirements.txt'
18
+ ];
19
+
20
+ function dependencyKey(repoRoot, relativePath, options = {}) {
21
+ const hash = createHash('sha256');
22
+ hash.update(
23
+ JSON.stringify([
24
+ 1,
25
+ relativePath,
26
+ options.runtime || process.version,
27
+ process.versions.modules,
28
+ process.platform,
29
+ process.arch
30
+ ])
31
+ );
32
+ // Include root and package-local manifests: monorepos may use either layout.
33
+ for (const directory of new Set(['.', path.dirname(relativePath)])) {
34
+ for (const name of [
35
+ ...LOCKFILES,
36
+ 'package.json',
37
+ 'pyproject.toml',
38
+ '.python-version',
39
+ '.npmrc'
40
+ ]) {
41
+ const file = path.join(repoRoot, directory, name);
42
+ try {
43
+ hash.update(JSON.stringify([directory, name, fs.readFileSync(file).toString('base64')]));
44
+ } catch (error) {
45
+ if (error.code !== 'ENOENT') throw error;
46
+ }
47
+ }
48
+ }
49
+ return hash.digest('hex');
50
+ }
51
+
52
+ function walk(root, visit) {
53
+ for (const entry of fs
54
+ .readdirSync(root, { withFileTypes: true })
55
+ .sort((a, b) => a.name.localeCompare(b.name))) {
56
+ const file = path.join(root, entry.name);
57
+ visit(file, entry);
58
+ if (entry.isDirectory()) walk(file, visit);
59
+ }
60
+ }
61
+
62
+ function treeDigest(root) {
63
+ const hash = createHash('sha256');
64
+ walk(root, (file, entry) => {
65
+ hash.update(
66
+ JSON.stringify([
67
+ path.relative(root, file),
68
+ entry.isDirectory() ? 'dir' : entry.isSymbolicLink() ? 'link' : 'file'
69
+ ])
70
+ );
71
+ if (entry.isSymbolicLink()) {
72
+ const target = fs.realpathSync(file);
73
+ if (target !== root && !target.startsWith(root + path.sep))
74
+ throw new Error('dependency link escapes selected directory');
75
+ // Copies canonicalize internal links; hash their resolved in-tree target,
76
+ // not an absolute spelling or intermediate link that copying rewrites.
77
+ hash.update(path.relative(root, target));
78
+ } else if (entry.isFile()) {
79
+ hash.update(JSON.stringify(fs.statSync(file).mode & 0o111));
80
+ hash.update(fs.readFileSync(file));
81
+ } else if (!entry.isDirectory()) throw new Error('unsupported dependency entry');
82
+ });
83
+ return hash.digest('hex');
84
+ }
85
+
86
+ function setWritable(root, writable) {
87
+ fs.chmodSync(root, writable ? 0o755 : 0o555);
88
+ walk(root, (file, entry) => {
89
+ if (!entry.isSymbolicLink()) {
90
+ const mode = entry.isDirectory() ? 0o555 : 0o444 | (fs.statSync(file).mode & 0o111);
91
+ fs.chmodSync(file, mode | (writable ? 0o200 : 0));
92
+ }
93
+ });
94
+ }
95
+
96
+ function defaultStore(repoRoot) {
97
+ const result = spawnSync('git', ['-C', repoRoot, 'rev-parse', '--git-common-dir'], {
98
+ encoding: 'utf8'
99
+ });
100
+ if (result.status !== 0) return null;
101
+ return path.join(
102
+ fs.realpathSync(path.resolve(repoRoot, result.stdout.trim())),
103
+ 'gx-dependency-snapshots'
104
+ );
105
+ }
106
+
107
+ const SNAPSHOT_NAME = /^[0-9a-f]{64}-[0-9a-f]{64}$/;
108
+ const DAY_MS = 24 * 60 * 60 * 1000;
109
+
110
+ function retentionSetting(value, envName, fallback) {
111
+ const raw = value ?? process.env[envName];
112
+ const parsed = Number(raw);
113
+ return raw !== undefined && raw !== '' && Number.isInteger(parsed) && parsed >= 0
114
+ ? parsed
115
+ : fallback;
116
+ }
117
+
118
+ function removeSnapshotDir(dir) {
119
+ const tree = path.join(dir, 'tree');
120
+ try {
121
+ // Sealed read-only: make it writable again or the removal fails half-way.
122
+ if (fs.existsSync(tree) && !fs.lstatSync(tree).isSymbolicLink()) setWritable(tree, true);
123
+ } catch {
124
+ // best effort — rmSync below reports nothing either way
125
+ }
126
+ fs.rmSync(dir, { recursive: true, force: true });
127
+ }
128
+
129
+ // A snapshot is only a cache: every consumer copies out of it and nothing links
130
+ // into it, so an unused one can always be rebuilt. Without retention each
131
+ // lockfile or dependency change left another full copy behind for good (field
132
+ // 2026-11-18: 4 x 1.6 GB in one repo). Keeps the newest `keep` snapshots and any
133
+ // used within `maxAgeDays`; the snapshot just provisioned is never removed.
134
+ // Never throws: retention must not fail a provision.
135
+ function pruneSnapshots(store, currentContainer, options = {}) {
136
+ const removed = [];
137
+ try {
138
+ const keep = retentionSetting(options.snapshotKeep, 'GUARDEX_DEPENDENCY_SNAPSHOT_KEEP', 2);
139
+ const maxAgeMs =
140
+ retentionSetting(
141
+ options.snapshotMaxAgeDays,
142
+ 'GUARDEX_DEPENDENCY_SNAPSHOT_MAX_AGE_DAYS',
143
+ 14
144
+ ) * DAY_MS;
145
+ const now = options.now ?? Date.now();
146
+ const snapshots = [];
147
+ for (const entry of fs.readdirSync(store, { withFileTypes: true })) {
148
+ if (!entry.isDirectory()) continue;
149
+ const dir = path.join(store, entry.name);
150
+ const mtimeMs = fs.statSync(dir).mtimeMs;
151
+ if (entry.name.startsWith('.snapshot-')) {
152
+ // Staging directory of a provision that died; a live one is seconds old.
153
+ if (now - mtimeMs > DAY_MS) {
154
+ removeSnapshotDir(dir);
155
+ removed.push(dir);
156
+ }
157
+ } else if (SNAPSHOT_NAME.test(entry.name)) snapshots.push({ dir, mtimeMs });
158
+ }
159
+ snapshots.sort((a, b) => b.mtimeMs - a.mtimeMs);
160
+ snapshots.forEach((snapshot, index) => {
161
+ if (index < keep || snapshot.dir === currentContainer) return;
162
+ if (now - snapshot.mtimeMs < maxAgeMs) return;
163
+ removeSnapshotDir(snapshot.dir);
164
+ removed.push(snapshot.dir);
165
+ });
166
+ } catch {
167
+ // retention is best effort
168
+ }
169
+ return removed;
170
+ }
171
+
172
+ // Snapshots are never worktree symlink targets. Every consumer gets a reflink or
173
+ // ordinary copy with independent writable inodes; internal links stay internal.
174
+ function provisionDependency(repoRoot, relativePath, destination, options) {
175
+ if (path.isAbsolute(relativePath) || relativePath.split(/[\\/]/).includes('..'))
176
+ throw new Error('dependency path escapes repository');
177
+ const source = fs.realpathSync(path.join(repoRoot, relativePath));
178
+ const repo = fs.realpathSync(repoRoot);
179
+ if (!source.startsWith(repo + path.sep)) throw new Error('dependency path escapes repository');
180
+ if (relativePath.split(/[\\/]/).some((part) => ['.venv', 'venv'].includes(part)))
181
+ throw new Error(
182
+ 'Python environments are not relocatable; recreate with an approved postCreate command'
183
+ );
184
+ const store = options.storeDir || defaultStore(repoRoot);
185
+ if (!store) {
186
+ options.copyDirectory(source, destination, {});
187
+ return { reused: false, snapshot: null, key: null };
188
+ }
189
+ const content = treeDigest(source);
190
+ const key = `${dependencyKey(repoRoot, relativePath, options)}-${content}`;
191
+ fs.mkdirSync(store, { recursive: true, mode: 0o700 });
192
+ const container = path.join(store, key);
193
+ const snapshot = path.join(container, 'tree');
194
+ const reused = fs.existsSync(container);
195
+ if (reused) {
196
+ // The directory's mtime is "last used": retention goes by it.
197
+ try {
198
+ const now = new Date();
199
+ fs.utimesSync(container, now, now);
200
+ } catch {
201
+ // read-only store: retention then goes by creation time
202
+ }
203
+ }
204
+ if (!reused) {
205
+ const stage = fs.mkdtempSync(path.join(store, '.snapshot-'));
206
+ const tree = path.join(stage, 'tree');
207
+ try {
208
+ options.copyDirectory(source, tree, {});
209
+ if (treeDigest(tree) !== content)
210
+ throw new Error('dependencies changed during snapshot creation');
211
+ setWritable(tree, false);
212
+ try {
213
+ fs.renameSync(stage, container);
214
+ } catch (error) {
215
+ if (!['EEXIST', 'ENOTEMPTY'].includes(error.code)) throw error;
216
+ }
217
+ } finally {
218
+ if (fs.existsSync(tree)) setWritable(tree, true);
219
+ fs.rmSync(stage, { recursive: true, force: true });
220
+ }
221
+ }
222
+ if (
223
+ fs.lstatSync(container).isSymbolicLink() ||
224
+ fs.lstatSync(snapshot).isSymbolicLink() ||
225
+ treeDigest(snapshot) !== content
226
+ )
227
+ throw new Error('dependency snapshot integrity mismatch');
228
+ options.copyDirectory(snapshot, destination, {});
229
+ setWritable(destination, true);
230
+ pruneSnapshots(store, container, options);
231
+ return { key, snapshot, reused };
232
+ }
233
+
234
+ module.exports = { dependencyKey, provisionDependency, pruneSnapshots };
@@ -400,7 +400,19 @@ function writeLockState(repoRoot, payload, dryRun) {
400
400
  if (dryRun) return;
401
401
  const lockPath = lockFilePath(repoRoot);
402
402
  fs.mkdirSync(path.dirname(lockPath), { recursive: true });
403
- fs.writeFileSync(lockPath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
403
+ // Atomic write: temp sibling + rename so concurrent readers never see a
404
+ // partial file. Cross-worktree serialization (preventing two concurrent
405
+ // claim/release runs from racing on the read-modify-write cycle) is handled
406
+ // by the Python cross_worktree_lock in scripts/agent-file-locks.py, which
407
+ // acquires an fcntl.flock on <common-git-dir>/agent-file-locks.lock before
408
+ // calling into this write path. Node has no native fcntl binding without
409
+ // additional dependencies, so we provide atomicity only — not exclusion.
410
+ const tempPath = path.join(
411
+ path.dirname(lockPath),
412
+ `.${path.basename(lockPath)}.${process.pid}.${Date.now()}.tmp`,
413
+ );
414
+ fs.writeFileSync(tempPath, JSON.stringify(payload, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
415
+ fs.renameSync(tempPath, lockPath);
404
416
  }
405
417
 
406
418
  function removeLegacyPackageScripts(repoRoot, dryRun) {
@@ -0,0 +1,83 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { createHash, randomUUID } = require('node:crypto');
6
+ const { spawnSync } = require('node:child_process');
7
+ const { GUARDEX_HOME_DIR } = require('../context');
8
+
9
+ function digest(value) {
10
+ return createHash('sha256').update(JSON.stringify(value)).digest('hex');
11
+ }
12
+
13
+ function repositoryIdentity(repoRoot) {
14
+ const result = spawnSync('git', ['-C', repoRoot, 'rev-parse', '--git-common-dir'], {
15
+ encoding: 'utf8'
16
+ });
17
+ const commonDir = result.status === 0 ? result.stdout.trim() : '.';
18
+ return fs.realpathSync(path.resolve(repoRoot, commonDir));
19
+ }
20
+
21
+ function approvalFile(repoRoot, deps = {}) {
22
+ const directory =
23
+ deps.approvalDir || path.join(GUARDEX_HOME_DIR, '.config', 'gitguardex', 'provision-approvals');
24
+ return path.join(directory, `${digest(repositoryIdentity(repoRoot))}.json`);
25
+ }
26
+
27
+ function hasApproval(repoRoot, commands, deps = {}) {
28
+ try {
29
+ const record = JSON.parse(fs.readFileSync(approvalFile(repoRoot, deps), 'utf8'));
30
+ return (
31
+ record.version === 1 &&
32
+ record.digest === digest(['postCreate', repositoryIdentity(repoRoot), commands])
33
+ );
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ function saveApproval(repoRoot, commands, deps = {}) {
40
+ const file = approvalFile(repoRoot, deps);
41
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
42
+ const temporary = `${file}.${randomUUID()}.tmp`;
43
+ try {
44
+ const record = {
45
+ version: 1,
46
+ digest: digest(['postCreate', repositoryIdentity(repoRoot), commands])
47
+ };
48
+ fs.writeFileSync(temporary, `${JSON.stringify(record)}\n`, { mode: 0o600, flag: 'wx' });
49
+ fs.renameSync(temporary, file);
50
+ } finally {
51
+ fs.rmSync(temporary, { force: true });
52
+ }
53
+ }
54
+
55
+ function revokeApproval(repoRoot, deps = {}) {
56
+ fs.rmSync(approvalFile(repoRoot, deps), { force: true });
57
+ }
58
+
59
+ function promptApproval(question) {
60
+ process.stdout.write(`${question} [y/N] `);
61
+ const byte = Buffer.alloc(1);
62
+ let answer = '';
63
+ while (answer.length < 16 && fs.readSync(process.stdin.fd, byte, 0, 1, null) > 0) {
64
+ if (byte[0] === 10 || byte[0] === 13) break;
65
+ answer += byte.toString();
66
+ }
67
+ return /^(y|yes)$/i.test(answer.trim());
68
+ }
69
+
70
+ function requestApproval(repoRoot, commands, deps = {}) {
71
+ const interactive = deps.interactive ?? (process.stdin.isTTY && process.stdout.isTTY);
72
+ if (!interactive || commands.length === 0) return false;
73
+ // JSON quoting makes newlines and terminal control characters visible.
74
+ const question =
75
+ `Approve postCreate shell commands for ${JSON.stringify(fs.realpathSync(repoRoot))}?\n` +
76
+ commands.map((command) => ` ${JSON.stringify(command)}`).join('\n') +
77
+ '\nThese commands can run arbitrary code, including scripts they invoke. Approve';
78
+ if (!(deps.prompt || promptApproval)(question)) return false;
79
+ saveApproval(repoRoot, commands, deps);
80
+ return true;
81
+ }
82
+
83
+ module.exports = { repositoryIdentity, hasApproval, saveApproval, revokeApproval, requestApproval };
@@ -10,25 +10,38 @@
10
10
  // "provision": {
11
11
  // "files": {
12
12
  // "copy": [".env", "apps/*/.env"], // per-worktree copies
13
- // "symlink": ["node_modules", ".venv"] // shared via symlink
13
+ // "symlink": ["node_modules"] // dependencies are isolated copies, not links
14
14
  // },
15
15
  // "postCreate": ["pnpm install --offline"]
16
16
  // }
17
17
  // }
18
18
  //
19
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.
20
+ // are pure filesystem ops. postCreate requires separate local approval of the
21
+ // exact command list; a committed config alone is not consent to execute it.
22
+ // GUARDEX_PROVISION_HOOKS=0 disables even approved hooks. Provisioning is best-effort.
23
23
 
24
24
  const fs = require('fs');
25
25
  const path = require('path');
26
26
  const { spawnSync } = require('child_process');
27
27
  const jsonc = require('jsonc-parser');
28
+ const { hasApproval } = require('./provision-approvals');
29
+ const { provisionDependency } = require('./dependency-store');
28
30
 
29
31
  const CONFIG_BASENAME = '.guardex.json';
30
32
  const POST_CREATE_TIMEOUT_MS = 10 * 60 * 1000;
31
33
 
34
+ function provisioningMode(deps = {}) {
35
+ const mode = deps.mode || process.env.GUARDEX_PROVISION_MODE || 'full';
36
+ if (!['minimal', 'docs', 'full'].includes(mode))
37
+ throw new Error(`Invalid provisioning mode: ${mode}`);
38
+ return mode;
39
+ }
40
+
41
+ function isDependencyPath(rel) {
42
+ return rel.split(/[\\/]/).some((part) => ['node_modules', '.venv', 'venv'].includes(part));
43
+ }
44
+
32
45
  function toStringArray(value) {
33
46
  if (!Array.isArray(value)) return [];
34
47
  return value.filter((item) => typeof item === 'string' && item.trim() !== '');
@@ -65,9 +78,9 @@ function loadProvisionConfig(repoRoot, deps = {}) {
65
78
  source: configPath,
66
79
  files: {
67
80
  copy: toStringArray(files.copy),
68
- symlink: toStringArray(files.symlink),
81
+ symlink: toStringArray(files.symlink)
69
82
  },
70
- postCreate: toStringArray(provision.postCreate),
83
+ postCreate: toStringArray(provision.postCreate)
71
84
  };
72
85
  }
73
86
 
@@ -126,8 +139,14 @@ function expandGlob(rootDir, pattern, deps = {}) {
126
139
  return matches.filter((rel) => rel !== '');
127
140
  }
128
141
 
129
- function ensureParentDir(filePath) {
130
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
142
+ function ensureParentDir(filePath, worktreeReal) {
143
+ const parent = path.dirname(filePath);
144
+ // Validate before mkdir, which otherwise follows existing destination links.
145
+ let ancestor = parent;
146
+ while (!targetAlreadyPresent(ancestor)) ancestor = path.dirname(ancestor);
147
+ if (!withinReal(ancestor, worktreeReal)) throw new Error('destination escapes worktree');
148
+ fs.mkdirSync(parent, { recursive: true });
149
+ if (!withinReal(parent, worktreeReal)) throw new Error('destination escapes worktree');
131
150
  }
132
151
 
133
152
  function safeRealpath(target) {
@@ -158,12 +177,68 @@ function targetAlreadyPresent(destPath) {
158
177
  }
159
178
  }
160
179
 
180
+ function copyDirectory(source, destination, deps) {
181
+ const root = fs.realpathSync(source);
182
+ const staging = fs.mkdtempSync(path.join(path.dirname(destination), '.gx-copy-'));
183
+ const directories = [[root, staging]];
184
+ const links = [];
185
+ const flags = fs.constants.COPYFILE_FICLONE | fs.constants.COPYFILE_EXCL;
186
+ try {
187
+ for (let index = 0; index < directories.length; index++) {
188
+ const [from, to] = directories[index];
189
+ for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
190
+ const src = path.join(from, entry.name);
191
+ const dest = path.join(to, entry.name);
192
+ if (entry.isSymbolicLink()) {
193
+ const target = fs.realpathSync(src);
194
+ if (!withinReal(target, root)) throw new Error('copy link escapes selected directory');
195
+ links.push([
196
+ dest,
197
+ path.join(staging, path.relative(root, target)),
198
+ fs.statSync(target).isDirectory()
199
+ ]);
200
+ } else if (entry.isDirectory()) {
201
+ fs.mkdirSync(dest);
202
+ directories.push([src, dest]);
203
+ } else if (entry.isFile()) {
204
+ (deps.copyFile || fs.copyFileSync)(src, dest, flags);
205
+ } else {
206
+ throw new Error('copy supports only regular files, directories and internal symlinks');
207
+ }
208
+ }
209
+ }
210
+ for (const [dest, target, directory] of links) {
211
+ fs.symlinkSync(
212
+ path.relative(path.dirname(dest), target) || '.',
213
+ dest,
214
+ directory ? 'dir' : 'file'
215
+ );
216
+ }
217
+ for (const [from, to] of directories.reverse())
218
+ fs.chmodSync(to, fs.statSync(from).mode & 0o777);
219
+ if (targetAlreadyPresent(destination))
220
+ throw new Error('copy target appeared during provisioning');
221
+ fs.renameSync(staging, destination);
222
+ } finally {
223
+ // A read-only snapshot may have supplied directory modes before publication
224
+ // failed. Restore only our private staging tree so cleanup can remove it.
225
+ if (fs.existsSync(staging)) {
226
+ for (const [, directory] of directories) fs.chmodSync(directory, 0o700);
227
+ }
228
+ fs.rmSync(staging, { recursive: true, force: true });
229
+ }
230
+ }
231
+
161
232
  function applyCopy(repoRoot, worktreePath, patterns, deps = {}) {
162
233
  const operations = [];
163
234
  const repoReal = safeRealpath(repoRoot);
164
235
  const worktreeReal = safeRealpath(worktreePath);
165
236
  for (const pattern of patterns) {
166
- const rels = expandGlob(repoRoot, pattern, deps);
237
+ const rels = deps.literalPaths
238
+ ? isUnsafePattern(pattern)
239
+ ? []
240
+ : [pattern]
241
+ : expandGlob(repoRoot, pattern, deps);
167
242
  if (rels.length === 0) {
168
243
  operations.push({ status: 'skipped', file: pattern, note: 'no match in repo root' });
169
244
  continue;
@@ -177,22 +252,26 @@ function applyCopy(repoRoot, worktreePath, patterns, deps = {}) {
177
252
  operations.push({ status: 'skipped', file: rel, note: 'resolves outside repo root' });
178
253
  continue;
179
254
  }
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
255
  if (targetAlreadyPresent(dest)) {
185
256
  operations.push({ status: 'unchanged', file: rel, note: 'already present in worktree' });
186
257
  continue;
187
258
  }
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;
259
+ ensureParentDir(dest, worktreeReal);
260
+ if (fs.statSync(src).isDirectory()) {
261
+ const sourceReal = fs.realpathSync(src);
262
+ if (withinReal(worktreePath, sourceReal))
263
+ throw new Error('copy target is inside source directory');
264
+ if (isDependencyPath(rel))
265
+ provisionDependency(repoRoot, rel, dest, { ...deps, copyDirectory });
266
+ else copyDirectory(src, dest, deps);
267
+ } else {
268
+ if (!fs.statSync(src).isFile()) throw new Error('copy source is not a regular file');
269
+ (deps.copyFile || fs.copyFileSync)(
270
+ src,
271
+ dest,
272
+ fs.constants.COPYFILE_FICLONE | fs.constants.COPYFILE_EXCL
273
+ );
194
274
  }
195
- fs.copyFileSync(src, dest);
196
275
  operations.push({ status: 'copied', file: rel, note: 'copied from repo root' });
197
276
  } catch (error) {
198
277
  operations.push({ status: 'failed', file: rel, note: `copy failed: ${error.message}` });
@@ -225,13 +304,13 @@ function applySymlink(repoRoot, worktreePath, patterns, deps = {}) {
225
304
  operations.push({ status: 'unchanged', file: rel, note: 'already present in worktree' });
226
305
  continue;
227
306
  }
228
- ensureParentDir(dest);
229
- if (!withinReal(path.dirname(dest), worktreeReal)) {
230
- operations.push({ status: 'skipped', file: rel, note: 'destination escapes worktree' });
231
- continue;
232
- }
307
+ ensureParentDir(dest, worktreeReal);
233
308
  fs.symlinkSync(src, dest);
234
- operations.push({ status: 'linked', file: rel, note: `→ ${path.relative(worktreePath, src)}` });
309
+ operations.push({
310
+ status: 'linked',
311
+ file: rel,
312
+ note: `→ ${path.relative(worktreePath, src)}`
313
+ });
235
314
  } catch (error) {
236
315
  operations.push({ status: 'failed', file: rel, note: `symlink failed: ${error.message}` });
237
316
  }
@@ -241,21 +320,38 @@ function applySymlink(repoRoot, worktreePath, patterns, deps = {}) {
241
320
  }
242
321
 
243
322
  function hooksDisabled() {
244
- const flag = String(process.env.GUARDEX_PROVISION_HOOKS || '').trim().toLowerCase();
323
+ const flag = String(process.env.GUARDEX_PROVISION_HOOKS || '')
324
+ .trim()
325
+ .toLowerCase();
245
326
  return ['0', 'false', 'no', 'off'].includes(flag);
246
327
  }
247
328
 
248
329
  function applyPostCreate(repoRoot, worktreePath, commands, deps = {}) {
249
330
  if (commands.length === 0) return [];
250
331
  if (hooksDisabled()) {
251
- return commands.map((command) => ({ status: 'skipped', file: command, note: 'GUARDEX_PROVISION_HOOKS disabled' }));
332
+ return commands.map((command) => ({
333
+ status: 'skipped',
334
+ file: command,
335
+ note: 'GUARDEX_PROVISION_HOOKS disabled'
336
+ }));
252
337
  }
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
- }));
338
+ if (!(deps.hasApproval || hasApproval)(repoRoot, commands, deps)) {
339
+ return commands.map((command) => ({
340
+ status: 'skipped',
341
+ file: command,
342
+ code: 'HOOK_APPROVAL_REQUIRED',
343
+ note: 'postCreate requires local consent: run gx worktree approve-hooks --target <source-repo> in a terminal'
344
+ }));
345
+ }
346
+ const run =
347
+ deps.run ||
348
+ ((cmd, cwd, env) =>
349
+ spawnSync('sh', ['-lc', cmd], {
350
+ cwd,
351
+ env,
352
+ stdio: ['ignore', 'pipe', 'pipe'],
353
+ timeout: POST_CREATE_TIMEOUT_MS
354
+ }));
259
355
 
260
356
  const operations = [];
261
357
  const env = { ...process.env, GUARDEX_WORKTREE: worktreePath, GUARDEX_REPO_ROOT: repoRoot };
@@ -272,10 +368,10 @@ function applyPostCreate(repoRoot, worktreePath, commands, deps = {}) {
272
368
  ok
273
369
  ? { status: 'ran', file: command, note: 'post_create hook ok' }
274
370
  : {
275
- status: 'failed',
276
- file: command,
277
- note: `post_create exited ${result && result.status}${result && result.error ? `: ${result.error.message}` : ''}`,
278
- },
371
+ status: 'failed',
372
+ file: command,
373
+ note: `post_create exited ${result && result.status}${result && result.error ? `: ${result.error.message}` : ''}`
374
+ }
279
375
  );
280
376
  }
281
377
  return operations;
@@ -284,16 +380,47 @@ function applyPostCreate(repoRoot, worktreePath, commands, deps = {}) {
284
380
  // Apply a normalized provision config to a worktree. Order: copy, symlink, then
285
381
  // postCreate hooks (so hooks see the env/deps already in place). Best-effort.
286
382
  function applyProvisionConfig(repoRoot, worktreePath, config, deps = {}) {
383
+ const mode = provisioningMode(deps);
384
+ if (mode !== 'full')
385
+ return [
386
+ {
387
+ status: 'skipped',
388
+ code: 'PROVISION_MODE_SKIPPED',
389
+ file: mode,
390
+ note: 'dependencies, hooks, build and index provisioning skipped'
391
+ }
392
+ ];
287
393
  if (!config) return [];
288
394
  const operations = [];
289
395
  operations.push(...applyCopy(repoRoot, worktreePath, config.files.copy, deps));
290
- operations.push(...applySymlink(repoRoot, worktreePath, config.files.symlink, deps));
396
+ const copiedPaths = config.files.copy.flatMap((pattern) => expandGlob(repoRoot, pattern, deps));
397
+ const symlinkPaths = config.files.symlink
398
+ .flatMap((pattern) => expandGlob(repoRoot, pattern, deps))
399
+ .filter(
400
+ (rel) =>
401
+ !copiedPaths.some(
402
+ (copy) => rel === copy || rel.startsWith(`${copy}/`) || copy.startsWith(`${rel}/`)
403
+ )
404
+ );
405
+ // A failed explicit copy must never fall back to writable shared dependencies.
406
+ operations.push(
407
+ ...applyCopy(repoRoot, worktreePath, symlinkPaths.filter(isDependencyPath), deps)
408
+ );
409
+ operations.push(
410
+ ...applySymlink(
411
+ repoRoot,
412
+ worktreePath,
413
+ symlinkPaths.filter((rel) => !isDependencyPath(rel)),
414
+ deps
415
+ )
416
+ );
291
417
  operations.push(...applyPostCreate(repoRoot, worktreePath, config.postCreate, deps));
292
418
  return operations;
293
419
  }
294
420
 
295
421
  // Convenience: load + apply for a freshly created worktree.
296
422
  function provisionFromConfig(repoRoot, worktreePath, deps = {}) {
423
+ provisioningMode(deps);
297
424
  if (!repoRoot || !worktreePath || repoRoot === worktreePath) return [];
298
425
  if (!fs.existsSync(worktreePath)) return [];
299
426
  const config = loadProvisionConfig(repoRoot, deps);
@@ -302,6 +429,8 @@ function provisionFromConfig(repoRoot, worktreePath, deps = {}) {
302
429
  }
303
430
 
304
431
  module.exports = {
432
+ copyDirectory,
433
+ provisioningMode,
305
434
  CONFIG_BASENAME,
306
435
  loadProvisionConfig,
307
436
  expandGlob,
@@ -310,5 +439,5 @@ module.exports = {
310
439
  applySymlink,
311
440
  applyPostCreate,
312
441
  applyProvisionConfig,
313
- provisionFromConfig,
442
+ provisionFromConfig
314
443
  };