geloforge 0.0.0-stage → 0.6.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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +140 -2
  3. package/THIRD_PARTY_NOTICES.md +33 -0
  4. package/VERSION +1 -0
  5. package/core/adopt-project.mjs +458 -0
  6. package/core/checkpoint.mjs +438 -0
  7. package/core/codebase-map.mjs +886 -0
  8. package/core/compatibility.json +16 -0
  9. package/core/compatibility.mjs +123 -0
  10. package/core/context-compiler.mjs +1315 -0
  11. package/core/evidence-capture.mjs +326 -0
  12. package/core/git-utils.mjs +167 -0
  13. package/core/handoff.mjs +815 -0
  14. package/core/json-schema-lite.mjs +119 -0
  15. package/core/mcp-init.mjs +248 -0
  16. package/core/mcp-server.mjs +915 -0
  17. package/core/path-safety.mjs +508 -0
  18. package/core/project-locator.mjs +231 -0
  19. package/core/project-lock.mjs +438 -0
  20. package/core/project-status.mjs +609 -0
  21. package/core/project-validator.mjs +544 -0
  22. package/core/skills-history.mjs +572 -0
  23. package/core/skills-lifecycle.mjs +2225 -0
  24. package/core/skills-lint.mjs +365 -0
  25. package/core/skills.mjs +1449 -0
  26. package/core/task-manager.mjs +1042 -0
  27. package/core/template-utils.mjs +190 -0
  28. package/core/text-utils.mjs +48 -0
  29. package/core/verify-task.mjs +48 -0
  30. package/core/yaml-subset.mjs +572 -0
  31. package/package.json +47 -4
  32. package/policies/approval-boundaries.md +42 -0
  33. package/policies/memory-policy.md +53 -0
  34. package/policies/token-efficiency.md +30 -0
  35. package/schemas/README.md +43 -0
  36. package/schemas/adr.schema.json +64 -0
  37. package/schemas/agent-handoff.schema.json +139 -0
  38. package/schemas/approval-record.schema.json +101 -0
  39. package/schemas/conflict-record.schema.json +60 -0
  40. package/schemas/context-pack-manifest.schema.json +194 -0
  41. package/schemas/evidence-manifest.schema.json +83 -0
  42. package/schemas/incident-record.schema.json +53 -0
  43. package/schemas/project-manifest.schema.json +90 -0
  44. package/schemas/project-state.schema.json +64 -0
  45. package/schemas/recovery-checkpoint.schema.json +49 -0
  46. package/schemas/research-record.schema.json +76 -0
  47. package/schemas/task-contract.schema.json +95 -0
  48. package/scripts/bootstrap-project.mjs +357 -0
  49. package/scripts/geloforge.mjs +2291 -0
  50. package/templates/profiles/README.md +19 -0
  51. package/templates/profiles/ai-system/brain/profile.md +21 -0
  52. package/templates/profiles/ai-system/gitignore.append +5 -0
  53. package/templates/profiles/ai-system/profile.json +6 -0
  54. package/templates/profiles/automation/brain/profile.md +19 -0
  55. package/templates/profiles/automation/gitignore.append +5 -0
  56. package/templates/profiles/automation/profile.json +6 -0
  57. package/templates/profiles/desktop/brain/profile.md +21 -0
  58. package/templates/profiles/desktop/gitignore.append +7 -0
  59. package/templates/profiles/desktop/profile.json +6 -0
  60. package/templates/profiles/mobile/brain/profile.md +20 -0
  61. package/templates/profiles/mobile/gitignore.append +8 -0
  62. package/templates/profiles/mobile/profile.json +6 -0
  63. package/templates/profiles/web/brain/profile.md +21 -0
  64. package/templates/profiles/web/gitignore.append +6 -0
  65. package/templates/profiles/web/profile.json +6 -0
  66. package/templates/project-starter/AGENTS.md +26 -0
  67. package/templates/project-starter/GEMINI.md +16 -0
  68. package/templates/project-starter/README.md +26 -0
  69. package/templates/project-starter/brain/INDEX.md +40 -0
  70. package/templates/project-starter/brain/architecture/overview.md +30 -0
  71. package/templates/project-starter/brain/decisions/.gitkeep +0 -0
  72. package/templates/project-starter/brain/manifest.yaml +36 -0
  73. package/templates/project-starter/brain/requirements/constraints.md +29 -0
  74. package/templates/project-starter/brain/requirements/prd.md +37 -0
  75. package/templates/project-starter/brain/state/current.yaml +19 -0
  76. package/templates/project-starter/gitignore.template +25 -0
  77. package/templates/project-starter/src/.gitkeep +0 -0
  78. package/templates/project-starter/tasks/.gitkeep +0 -0
  79. package/templates/project-starter/tests/.gitkeep +0 -0
@@ -0,0 +1,508 @@
1
+ /**
2
+ * Portable path, naming, symlink/junction, and boundary safety helpers.
3
+ * Zero external dependencies and zero hardcoded drive letters or usernames.
4
+ */
5
+
6
+ import crypto from "node:crypto";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+
10
+ export const SLUG_REGEX = /^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$/;
11
+ export const WINDOWS_RESERVED_NAME_REGEX = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;
12
+ export const CONTROL_CHAR_REGEX = /[\x00-\x1f\x7f]/;
13
+ export const INVALID_SEGMENT_CHARS_REGEX = /[<>:"/\\|?*]/;
14
+
15
+ export function isWindowsPlatform() {
16
+ return process.platform === "win32";
17
+ }
18
+
19
+ function normalizeForCompare(targetPath) {
20
+ const resolved = path.resolve(targetPath);
21
+ return isWindowsPlatform() ? resolved.toLowerCase() : resolved;
22
+ }
23
+
24
+ export function isSameOrInside(candidatePath, parentPath) {
25
+ const normCandidate = normalizeForCompare(candidatePath);
26
+ const normParent = normalizeForCompare(parentPath);
27
+ if (normCandidate === normParent) {
28
+ return true;
29
+ }
30
+ const prefix = normParent.endsWith(path.sep) ? normParent : normParent + path.sep;
31
+ return normCandidate.startsWith(prefix);
32
+ }
33
+
34
+ export function validateProjectName(rawName) {
35
+ if (typeof rawName !== "string" || rawName.trim().length === 0) {
36
+ throw new Error("Missing required project name (--name).");
37
+ }
38
+ const name = rawName.trim();
39
+ if (name.length < 3 || name.length > 80) {
40
+ throw new Error("--name must be between 3 and 80 characters after trimming.");
41
+ }
42
+ if (CONTROL_CHAR_REGEX.test(name)) {
43
+ throw new Error("--name must not contain control characters or newlines.");
44
+ }
45
+ if (INVALID_SEGMENT_CHARS_REGEX.test(name) || name.includes("..")) {
46
+ throw new Error('--name must not contain path separators, "..", colons, or reserved characters (< > : " / \\ | ? *).');
47
+ }
48
+ if (name.endsWith(".")) {
49
+ throw new Error("--name must not end with a trailing dot.");
50
+ }
51
+ if (WINDOWS_RESERVED_NAME_REGEX.test(name)) {
52
+ throw new Error(`--name "${name}" conflicts with a reserved Windows device name.`);
53
+ }
54
+ return name;
55
+ }
56
+
57
+ export function deriveSlug(name) {
58
+ return name
59
+ .normalize("NFKD")
60
+ .replace(/[\u0300-\u036f]/g, "")
61
+ .toLowerCase()
62
+ .replace(/[^a-z0-9]+/g, "-")
63
+ .replace(/^-+|-+$/g, "")
64
+ .replace(/-{2,}/g, "-");
65
+ }
66
+
67
+ export function validateSlug(slug) {
68
+ if (typeof slug !== "string" || !SLUG_REGEX.test(slug)) {
69
+ throw new Error(
70
+ `Invalid slug "${slug}". Must match ${SLUG_REGEX} (3-50 chars, lowercase ASCII letters, digits, hyphens).`
71
+ );
72
+ }
73
+ if (WINDOWS_RESERVED_NAME_REGEX.test(slug)) {
74
+ throw new Error(`Slug "${slug}" is a reserved Windows device name.`);
75
+ }
76
+ return slug;
77
+ }
78
+
79
+ export function validateScalarText(label, value) {
80
+ if (typeof value !== "string") {
81
+ throw new Error(`${label} must be a string.`);
82
+ }
83
+ const trimmed = value.trim();
84
+ if (trimmed.length === 0) {
85
+ throw new Error(`${label} must not be empty.`);
86
+ }
87
+ if (CONTROL_CHAR_REGEX.test(trimmed)) {
88
+ throw new Error(`${label} must not contain control characters or newlines.`);
89
+ }
90
+ return trimmed;
91
+ }
92
+
93
+ function validateWindowsCompatibleSegments(resolvedPath) {
94
+ const parsed = path.parse(resolvedPath);
95
+ const remainder = resolvedPath.slice(parsed.root.length);
96
+ const segments = remainder.split(/[\\/]+/).filter(Boolean);
97
+ if (segments.length === 0) {
98
+ throw new Error(`Invalid destination path "${resolvedPath}".`);
99
+ }
100
+ for (const segment of segments) {
101
+ if (segment === "." || segment === "..") {
102
+ throw new Error(`Destination path "${resolvedPath}" contains invalid relative segment "${segment}".`);
103
+ }
104
+ if (INVALID_SEGMENT_CHARS_REGEX.test(segment)) {
105
+ throw new Error(`Destination path segment "${segment}" contains illegal filename characters.`);
106
+ }
107
+ if (WINDOWS_RESERVED_NAME_REGEX.test(segment)) {
108
+ throw new Error(`Destination path segment "${segment}" is a reserved Windows device name.`);
109
+ }
110
+ if (segment.endsWith(".") || segment.endsWith(" ")) {
111
+ throw new Error(`Destination path segment "${segment}" must not end with a dot or trailing space.`);
112
+ }
113
+ }
114
+ }
115
+
116
+ function isOsManagedDarwinSymlink(cursorPath) {
117
+ return process.platform === "darwin" && (cursorPath === "/tmp" || cursorPath === "/var" || cursorPath === "/etc");
118
+ }
119
+
120
+ function assertSafeAncestors(resolvedTarget, protectedDirs, kindLabel) {
121
+ let cursor = path.dirname(resolvedTarget);
122
+ const visited = new Set();
123
+ while (cursor && !visited.has(cursor)) {
124
+ visited.add(cursor);
125
+ try {
126
+ const stat = fs.lstatSync(cursor);
127
+ if (stat.isSymbolicLink() && !isOsManagedDarwinSymlink(cursor)) {
128
+ throw new Error(`Refusing ${kindLabel} with symbolic link or junction ancestor: ${cursor}`);
129
+ }
130
+ const realAnc = fs.realpathSync(cursor);
131
+ const relTail = path.relative(cursor, resolvedTarget);
132
+ const effectiveTarget = path.resolve(realAnc, relTail);
133
+ for (const dir of protectedDirs) {
134
+ const realProtected = fs.existsSync(dir) ? fs.realpathSync(dir) : dir;
135
+ if (isSameOrInside(realAnc, realProtected) || isSameOrInside(effectiveTarget, realProtected)) {
136
+ throw new Error(`Refusing ${kindLabel} resolving inside protected directory via ${cursor} -> ${realAnc}`);
137
+ }
138
+ }
139
+ } catch (err) {
140
+ if (err.code !== "ENOENT") {
141
+ throw err;
142
+ }
143
+ }
144
+ const parent = path.dirname(cursor);
145
+ if (parent === cursor) {
146
+ break;
147
+ }
148
+ cursor = parent;
149
+ }
150
+ }
151
+
152
+ export function validateDestinationPath(rawDest, { harnessDir, workspaceRoot }) {
153
+ if (typeof rawDest !== "string" || rawDest.trim().length === 0) {
154
+ throw new Error("Destination path must not be empty.");
155
+ }
156
+ if (CONTROL_CHAR_REGEX.test(rawDest)) {
157
+ throw new Error("Destination path contains illegal control characters.");
158
+ }
159
+ if (/^(\\\\|\/\/)/.test(rawDest)) {
160
+ throw new Error(`Refusing UNC or device network path as destination: "${rawDest}".`);
161
+ }
162
+ if (/(^|[\\/])\.\.([\\/]|$)/.test(rawDest)) {
163
+ throw new Error(`Refusing destination path containing traversal segment "..": "${rawDest}".`);
164
+ }
165
+
166
+ const resolved = path.resolve(rawDest);
167
+ const parsed = path.parse(resolved);
168
+ if (resolved === parsed.root) {
169
+ throw new Error(`Refusing to initialize project at filesystem root "${resolved}".`);
170
+ }
171
+
172
+ validateWindowsCompatibleSegments(resolved);
173
+
174
+ const protectedDirs = [
175
+ path.resolve(harnessDir),
176
+ path.resolve(workspaceRoot, "local-runtime"),
177
+ path.resolve(workspaceRoot, "worktrees"),
178
+ ];
179
+ const exactForbidden = [
180
+ path.resolve(workspaceRoot),
181
+ path.resolve(workspaceRoot, "projects"),
182
+ ];
183
+
184
+ for (const dir of protectedDirs) {
185
+ if (isSameOrInside(resolved, dir)) {
186
+ throw new Error(`Refusing to write inside protected workspace directory: ${dir}`);
187
+ }
188
+ }
189
+ for (const dir of exactForbidden) {
190
+ if (normalizeForCompare(resolved) === normalizeForCompare(dir)) {
191
+ throw new Error(`Refusing to initialize project directly at container directory: ${dir}`);
192
+ }
193
+ }
194
+
195
+ // Reject if destination already exists (including broken symlinks).
196
+ if (fs.existsSync(resolved)) {
197
+ throw new Error(`Refusing to overwrite existing destination: ${resolved}`);
198
+ }
199
+ try {
200
+ fs.lstatSync(resolved);
201
+ throw new Error(`Refusing to overwrite existing destination entry: ${resolved}`);
202
+ } catch (err) {
203
+ if (err.code !== "ENOENT") {
204
+ throw err;
205
+ }
206
+ }
207
+
208
+ assertSafeAncestors(resolved, protectedDirs, "destination");
209
+
210
+ return resolved;
211
+ }
212
+
213
+ /**
214
+ * Validates an existing non-symlink directory target (e.g. brownfield adoption).
215
+ */
216
+ export function validateExistingProjectDir(rawDest, { harnessDir, workspaceRoot }) {
217
+ if (typeof rawDest !== "string" || rawDest.trim().length === 0) {
218
+ throw new Error("Project path must not be empty.");
219
+ }
220
+ if (CONTROL_CHAR_REGEX.test(rawDest)) {
221
+ throw new Error("Project path contains illegal control characters.");
222
+ }
223
+ if (/^(\\\\|\/\/)/.test(rawDest)) {
224
+ throw new Error(`Refusing UNC or device network path as project directory: "${rawDest}".`);
225
+ }
226
+ if (/(^|[\\/])\.\.([\\/]|$)/.test(rawDest)) {
227
+ throw new Error(`Refusing project path containing traversal segment "..": "${rawDest}".`);
228
+ }
229
+
230
+ const resolved = path.resolve(rawDest);
231
+ const parsed = path.parse(resolved);
232
+ if (resolved === parsed.root) {
233
+ throw new Error(`Refusing to operate directly at filesystem root "${resolved}".`);
234
+ }
235
+
236
+ validateWindowsCompatibleSegments(resolved);
237
+
238
+ const protectedDirs = [path.resolve(harnessDir)];
239
+ if (workspaceRoot && fs.existsSync(path.join(workspaceRoot, "local-runtime"))) {
240
+ protectedDirs.push(path.resolve(workspaceRoot, "local-runtime"));
241
+ }
242
+ if (workspaceRoot && fs.existsSync(path.join(workspaceRoot, "worktrees"))) {
243
+ protectedDirs.push(path.resolve(workspaceRoot, "worktrees"));
244
+ }
245
+ const exactForbidden = workspaceRoot
246
+ ? [path.resolve(workspaceRoot), path.resolve(workspaceRoot, "projects")]
247
+ : [];
248
+
249
+ for (const dir of protectedDirs) {
250
+ if (isSameOrInside(resolved, dir)) {
251
+ throw new Error(`Refusing protected workspace directory as target project: ${dir}`);
252
+ }
253
+ }
254
+ for (const dir of exactForbidden) {
255
+ if (normalizeForCompare(resolved) === normalizeForCompare(dir)) {
256
+ throw new Error(`Refusing container directory as target project: ${dir}`);
257
+ }
258
+ }
259
+
260
+ if (!fs.existsSync(resolved)) {
261
+ throw new Error(`Target project directory does not exist: ${resolved}`);
262
+ }
263
+ const stat = fs.lstatSync(resolved);
264
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
265
+ throw new Error(`Target project path must be a real non-symlink directory: ${resolved}`);
266
+ }
267
+
268
+ assertSafeAncestors(resolved, protectedDirs, "project directory");
269
+
270
+ return resolved;
271
+ }
272
+
273
+ export function assertSafeWithinRoot(baseDir, relativeOrTargetPath) {
274
+ if (typeof relativeOrTargetPath !== "string" || relativeOrTargetPath.trim().length === 0) {
275
+ throw new Error("Path must be a non-empty string.");
276
+ }
277
+ if (CONTROL_CHAR_REGEX.test(relativeOrTargetPath)) {
278
+ throw new Error(`Path contains illegal control characters: ${relativeOrTargetPath}`);
279
+ }
280
+ if (path.isAbsolute(relativeOrTargetPath)) {
281
+ throw new Error(`Absolute path is not allowed inside project metadata: ${relativeOrTargetPath}`);
282
+ }
283
+ const baseResolved = path.resolve(baseDir);
284
+ const resolved = path.resolve(baseResolved, relativeOrTargetPath);
285
+ const rel = path.relative(baseResolved, resolved);
286
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
287
+ throw new Error(`Path escapes project root: ${relativeOrTargetPath}`);
288
+ }
289
+
290
+ // Check every existing path component between baseResolved and resolved for symlinks/junctions.
291
+ const segments = rel.split(/[\\/]+/).filter(Boolean);
292
+ let cursor = baseResolved;
293
+ for (const seg of segments) {
294
+ cursor = path.join(cursor, seg);
295
+ const stat = fs.lstatSync(cursor, { throwIfNoEntry: false });
296
+ if (!stat) break;
297
+ if (stat.isSymbolicLink()) {
298
+ throw new Error(`Symbolic links are not allowed inside project paths: ${relativeOrTargetPath}`);
299
+ }
300
+ }
301
+ return resolved;
302
+ }
303
+
304
+ export function isForbiddenSecretPath(relativePath) {
305
+ const normalized = relativePath.replace(/\\/g, "/").replace(/^\.\//, "").toLowerCase();
306
+ const segments = normalized.split("/").filter(Boolean);
307
+ if (segments.length === 0) {
308
+ return false;
309
+ }
310
+ if (segments.includes(".git") || segments.includes("secrets") || segments.includes(".aws") || segments.includes(".ssh")) {
311
+ return true;
312
+ }
313
+ const base = segments[segments.length - 1];
314
+ if (
315
+ base === ".env" ||
316
+ base.startsWith(".env.") ||
317
+ base === ".npmrc" ||
318
+ base === ".pypirc" ||
319
+ base === ".netrc" ||
320
+ base === "credentials.json" ||
321
+ /^id_(?:rsa|dsa|ecdsa|ed25519)(?:\..+)?$/.test(base)
322
+ ) {
323
+ return true;
324
+ }
325
+ return /\.(pem|key|p12|pfx|jks|keystore|mobileprovision|kdbx)$/i.test(base);
326
+ }
327
+
328
+ export const SECRET_CONTENT_PATTERNS = [
329
+ /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----/,
330
+ /\bAKIA[0-9A-Z]{16}\b/,
331
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/,
332
+ /\bgithub_pat_[A-Za-z0-9_]{20,}\b/,
333
+ /\bAIza[0-9A-Za-z_-]{35}\b/,
334
+ /\bsk-[A-Za-z0-9_-]{20,}\b/,
335
+ ];
336
+
337
+ export function hasSecretContent(text) {
338
+ if (typeof text !== "string" || text.length === 0) {
339
+ return false;
340
+ }
341
+ return SECRET_CONTENT_PATTERNS.some((pat) => pat.test(text));
342
+ }
343
+
344
+ /**
345
+ * Redacts common credential/token/private-key patterns from captured logs and diagnostics.
346
+ */
347
+ export function redactSecretContent(text) {
348
+ if (typeof text !== "string" || text.length === 0) {
349
+ return "";
350
+ }
351
+ let out = text;
352
+ out = out.replace(
353
+ /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?(?:-----END (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----|$)/g,
354
+ "[REDACTED_SECRET]"
355
+ );
356
+ for (const pat of SECRET_CONTENT_PATTERNS) {
357
+ const flags = pat.flags.includes("g") ? pat.flags : `${pat.flags}g`;
358
+ out = out.replace(new RegExp(pat.source, flags), "[REDACTED_SECRET]");
359
+ }
360
+ out = out.replace(/(Authorization\s*:\s*Bearer\s+)[^\s"']+/gi, "$1[REDACTED_SECRET]");
361
+ out = out.replace(/\bBearer\s+[A-Za-z0-9._-]{16,}\b/g, "Bearer [REDACTED_SECRET]");
362
+ out = out.replace(
363
+ /\b([A-Z0-9_]*(?:(?<!TOKENS?_)TOKEN(?!S\b)|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|ACCESS_KEY)(?:_[A-Z0-9_]+)?)\s*([=:])\s*("[^"]*"|'[^']*'|[^\s"',;]+)/gi,
364
+ "$1$2[REDACTED_SECRET]"
365
+ );
366
+ return out;
367
+ }
368
+
369
+ export function atomicWriteFile(resolvedOutPath, content, { allowOverwrite = true, onBeforeCommit = null, mode } = {}) {
370
+ const parent = path.dirname(resolvedOutPath);
371
+ fs.mkdirSync(parent, { recursive: true });
372
+ if (!allowOverwrite && fs.existsSync(resolvedOutPath)) {
373
+ throw new Error(`Refusing to overwrite existing file: ${resolvedOutPath}`);
374
+ }
375
+ const tempPath = path.join(parent, `.geloforge-tmp-${crypto.randomBytes(6).toString("hex")}`);
376
+ try {
377
+ fs.writeFileSync(tempPath, content, { encoding: "utf8", flag: "wx", mode });
378
+ if (typeof onBeforeCommit === "function") {
379
+ onBeforeCommit(tempPath);
380
+ }
381
+ if (!allowOverwrite && fs.existsSync(resolvedOutPath)) {
382
+ throw new Error(`Refusing to overwrite existing file: ${resolvedOutPath}`);
383
+ }
384
+ fs.renameSync(tempPath, resolvedOutPath);
385
+ } catch (err) {
386
+ try {
387
+ if (fs.existsSync(tempPath)) {
388
+ fs.unlinkSync(tempPath);
389
+ }
390
+ } catch {
391
+ // Ignore cleanup failure
392
+ }
393
+ throw err;
394
+ }
395
+ }
396
+
397
+ export function validateOutputFilePath(rawOutPath, { harnessDir, workspaceRoot }) {
398
+ if (typeof rawOutPath !== "string" || rawOutPath.trim().length === 0) {
399
+ throw new Error("Output path must not be empty.");
400
+ }
401
+ if (CONTROL_CHAR_REGEX.test(rawOutPath)) {
402
+ throw new Error("Output path contains illegal control characters.");
403
+ }
404
+ if (/^(\\\\|\/\/)/.test(rawOutPath)) {
405
+ throw new Error(`Refusing UNC or device network path as output target: "${rawOutPath}".`);
406
+ }
407
+ if (/(^|[\\/])\.\.([\\/]|$)/.test(rawOutPath)) {
408
+ throw new Error(`Refusing output path containing traversal segment "..": "${rawOutPath}".`);
409
+ }
410
+
411
+ const resolved = path.resolve(rawOutPath);
412
+ const parsed = path.parse(resolved);
413
+ if (resolved === parsed.root) {
414
+ throw new Error(`Refusing to write output file at filesystem root "${resolved}".`);
415
+ }
416
+ validateWindowsCompatibleSegments(resolved);
417
+
418
+ const relFromRoot = resolved.slice(parsed.root.length);
419
+ if (isForbiddenSecretPath(relFromRoot)) {
420
+ throw new Error(`Refusing to write output to sensitive secret/credential path: "${rawOutPath}".`);
421
+ }
422
+
423
+ const protectedDirs = [path.resolve(harnessDir)];
424
+ if (workspaceRoot && fs.existsSync(path.join(workspaceRoot, "worktrees"))) {
425
+ protectedDirs.push(path.resolve(workspaceRoot, "worktrees"));
426
+ }
427
+ for (const dir of protectedDirs) {
428
+ if (isSameOrInside(resolved, dir)) {
429
+ throw new Error(`Refusing to write output inside protected directory: ${dir}`);
430
+ }
431
+ }
432
+
433
+ try {
434
+ const targetStat = fs.lstatSync(resolved);
435
+ if (targetStat.isSymbolicLink()) {
436
+ throw new Error(`Refusing to write output to a symbolic link: ${resolved}`);
437
+ }
438
+ if (targetStat.isDirectory()) {
439
+ throw new Error(`Output file path points to an existing directory: ${resolved}`);
440
+ }
441
+ } catch (err) {
442
+ if (err.code !== "ENOENT") {
443
+ throw err;
444
+ }
445
+ }
446
+
447
+ assertSafeAncestors(resolved, protectedDirs, "output path");
448
+
449
+ return resolved;
450
+ }
451
+
452
+ export function walkNonSymlinkFiles(rootDir, absDir, predicate = () => true, warnings = null, options = {}) {
453
+ if (!fs.existsSync(absDir)) {
454
+ return [];
455
+ }
456
+ const onSymlink = typeof options.onSymlink === "function" ? options.onSymlink : null;
457
+ const dirStat = fs.lstatSync(absDir);
458
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) {
459
+ const relDir = path.relative(rootDir, absDir).replace(/\\/g, "/") || ".";
460
+ const msg = `Blocked symbolic link directory inside project: ${relDir}`;
461
+ if (onSymlink) onSymlink(relDir, msg);
462
+ else if (Array.isArray(warnings)) warnings.push(msg);
463
+ return [];
464
+ }
465
+ const results = [];
466
+ const ignoreDirs = options.ignoreDirs instanceof Set ? options.ignoreDirs : new Set([".git", "node_modules"]);
467
+ const entries = fs.readdirSync(absDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
468
+ for (const entry of entries) {
469
+ if (ignoreDirs.has(entry.name)) {
470
+ continue;
471
+ }
472
+ const full = path.join(absDir, entry.name);
473
+ const stat = fs.lstatSync(full);
474
+ if (stat.isSymbolicLink()) {
475
+ const rel = path.relative(rootDir, full).replace(/\\/g, "/");
476
+ const msg = `Blocked symbolic link inside project: ${rel}`;
477
+ if (onSymlink) onSymlink(rel, msg);
478
+ else if (Array.isArray(warnings)) warnings.push(msg);
479
+ continue;
480
+ }
481
+ if (stat.isDirectory()) {
482
+ results.push(...walkNonSymlinkFiles(rootDir, full, predicate, warnings, options));
483
+ } else if (stat.isFile() && predicate(full)) {
484
+ results.push(full);
485
+ }
486
+ }
487
+ return results;
488
+ }
489
+
490
+ export function assertNoSymlinkInTree(rootDir) {
491
+ const rootStat = fs.lstatSync(rootDir);
492
+ if (rootStat.isSymbolicLink()) {
493
+ throw new Error(`Refusing symbolic link / junction template root: ${rootDir}`);
494
+ }
495
+ if (!rootStat.isDirectory()) {
496
+ return;
497
+ }
498
+ for (const entry of fs.readdirSync(rootDir, { withFileTypes: true })) {
499
+ const fullPath = path.join(rootDir, entry.name);
500
+ const stat = fs.lstatSync(fullPath);
501
+ if (stat.isSymbolicLink()) {
502
+ throw new Error(`Refusing symbolic link / junction inside template tree: ${fullPath}`);
503
+ }
504
+ if (stat.isDirectory()) {
505
+ assertNoSymlinkInTree(fullPath);
506
+ }
507
+ }
508
+ }