geloforge 0.0.0-stage → 0.7.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 (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +72 -2
  3. package/THIRD_PARTY_NOTICES.md +33 -0
  4. package/VERSION +1 -0
  5. package/adapters/n8n/staging-audit-error-workflow.json +132 -0
  6. package/core/adopt-project.mjs +458 -0
  7. package/core/audit-learning.mjs +68 -0
  8. package/core/audit-provider.mjs +88 -0
  9. package/core/autonomous-audit.mjs +214 -0
  10. package/core/checkpoint.mjs +448 -0
  11. package/core/codebase-map.mjs +886 -0
  12. package/core/compatibility.json +16 -0
  13. package/core/compatibility.mjs +123 -0
  14. package/core/context-cache.mjs +113 -0
  15. package/core/context-compiler.mjs +1315 -0
  16. package/core/evidence-capture.mjs +347 -0
  17. package/core/git-utils.mjs +167 -0
  18. package/core/handoff.mjs +815 -0
  19. package/core/json-schema-lite.mjs +119 -0
  20. package/core/mcp-init.mjs +251 -0
  21. package/core/mcp-server.mjs +915 -0
  22. package/core/operation-approval.mjs +102 -0
  23. package/core/path-safety.mjs +508 -0
  24. package/core/project-locator.mjs +231 -0
  25. package/core/project-lock.mjs +438 -0
  26. package/core/project-status.mjs +635 -0
  27. package/core/project-validator.mjs +544 -0
  28. package/core/promotion.mjs +90 -0
  29. package/core/runtime-files.mjs +40 -0
  30. package/core/skills-history.mjs +572 -0
  31. package/core/skills-lifecycle.mjs +2225 -0
  32. package/core/skills-lint.mjs +365 -0
  33. package/core/skills.mjs +1449 -0
  34. package/core/staging-audit.mjs +454 -0
  35. package/core/staging-evidence.mjs +127 -0
  36. package/core/task-manager.mjs +1044 -0
  37. package/core/template-utils.mjs +190 -0
  38. package/core/text-utils.mjs +48 -0
  39. package/core/verify-task.mjs +48 -0
  40. package/core/worktrees.mjs +64 -0
  41. package/core/yaml-subset.mjs +572 -0
  42. package/package.json +50 -4
  43. package/policies/approval-boundaries.md +42 -0
  44. package/policies/memory-policy.md +53 -0
  45. package/policies/token-efficiency.md +30 -0
  46. package/schemas/README.md +43 -0
  47. package/schemas/adr.schema.json +64 -0
  48. package/schemas/agent-handoff.schema.json +139 -0
  49. package/schemas/approval-record.schema.json +110 -0
  50. package/schemas/conflict-record.schema.json +60 -0
  51. package/schemas/context-pack-manifest.schema.json +194 -0
  52. package/schemas/evidence-manifest.schema.json +83 -0
  53. package/schemas/incident-record.schema.json +53 -0
  54. package/schemas/project-manifest.schema.json +90 -0
  55. package/schemas/project-state.schema.json +64 -0
  56. package/schemas/recovery-checkpoint.schema.json +49 -0
  57. package/schemas/research-record.schema.json +76 -0
  58. package/schemas/task-contract.schema.json +95 -0
  59. package/scripts/bootstrap-project.mjs +357 -0
  60. package/scripts/geloforge.mjs +2512 -0
  61. package/templates/profiles/README.md +19 -0
  62. package/templates/profiles/ai-system/brain/profile.md +21 -0
  63. package/templates/profiles/ai-system/gitignore.append +5 -0
  64. package/templates/profiles/ai-system/profile.json +6 -0
  65. package/templates/profiles/automation/brain/profile.md +19 -0
  66. package/templates/profiles/automation/gitignore.append +5 -0
  67. package/templates/profiles/automation/profile.json +6 -0
  68. package/templates/profiles/desktop/brain/profile.md +21 -0
  69. package/templates/profiles/desktop/gitignore.append +7 -0
  70. package/templates/profiles/desktop/profile.json +6 -0
  71. package/templates/profiles/mobile/brain/profile.md +20 -0
  72. package/templates/profiles/mobile/gitignore.append +8 -0
  73. package/templates/profiles/mobile/profile.json +6 -0
  74. package/templates/profiles/web/brain/profile.md +21 -0
  75. package/templates/profiles/web/gitignore.append +6 -0
  76. package/templates/profiles/web/profile.json +6 -0
  77. package/templates/project-starter/AGENTS.md +27 -0
  78. package/templates/project-starter/GEMINI.md +16 -0
  79. package/templates/project-starter/README.md +26 -0
  80. package/templates/project-starter/brain/INDEX.md +40 -0
  81. package/templates/project-starter/brain/architecture/overview.md +30 -0
  82. package/templates/project-starter/brain/decisions/.gitkeep +0 -0
  83. package/templates/project-starter/brain/manifest.yaml +36 -0
  84. package/templates/project-starter/brain/requirements/constraints.md +29 -0
  85. package/templates/project-starter/brain/requirements/prd.md +37 -0
  86. package/templates/project-starter/brain/state/current.yaml +19 -0
  87. package/templates/project-starter/gitignore.template +25 -0
  88. package/templates/project-starter/src/.gitkeep +0 -0
  89. package/templates/project-starter/tasks/.gitkeep +0 -0
  90. package/templates/project-starter/tests/.gitkeep +0 -0
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Project root discovery (CWD upward search) and canonical manifest path resolution.
3
+ * Zero external dependencies.
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { isSameOrInside, assertSafeWithinRoot, walkNonSymlinkFiles } from "./path-safety.mjs";
10
+ import { parseYaml } from "./yaml-subset.mjs";
11
+ import { validateAgainstSchema } from "./json-schema-lite.mjs";
12
+ import { loadCompatibilityConfig, checkManifestCompatibility, checkRecordSchemaVersion } from "./compatibility.mjs";
13
+
14
+ const __filename = fileURLToPath(import.meta.url);
15
+ const __dirname = path.dirname(__filename);
16
+ const DEFAULT_HARNESS_DIR = path.resolve(__dirname, "..");
17
+
18
+ export const DEFAULT_PROJECT_PATHS = Object.freeze({
19
+ brain_index: "brain/INDEX.md",
20
+ prd: "brain/requirements/prd.md",
21
+ constraints: "brain/requirements/constraints.md",
22
+ architecture: "brain/architecture/overview.md",
23
+ state: "brain/state/current.yaml",
24
+ decisions_dir: "brain/decisions",
25
+ research_dir: "brain/research",
26
+ tasks_dir: "tasks",
27
+ evidence_dir: "evidence",
28
+ proposals_dir: "proposals",
29
+ conflicts_dir: "brain/conflicts",
30
+ incidents_dir: "brain/incidents",
31
+ handoffs_dir: "handoffs",
32
+ });
33
+
34
+ function normalizeRelPath(raw, fallback) {
35
+ if (typeof raw !== "string" || raw.trim().length === 0) {
36
+ return fallback;
37
+ }
38
+ const cleaned = raw.trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
39
+ return cleaned.length > 0 ? cleaned : fallback;
40
+ }
41
+
42
+ /**
43
+ * Resolves configured relative Second Brain paths from a parsed project manifest.
44
+ */
45
+ export function resolveProjectPaths(manifest = null) {
46
+ const configured = manifest && manifest.paths && typeof manifest.paths === "object" ? manifest.paths : {};
47
+ return {
48
+ brain_index: normalizeRelPath(configured.brain_index, DEFAULT_PROJECT_PATHS.brain_index),
49
+ prd: normalizeRelPath(configured.prd, DEFAULT_PROJECT_PATHS.prd),
50
+ constraints: normalizeRelPath(configured.constraints, DEFAULT_PROJECT_PATHS.constraints),
51
+ architecture: normalizeRelPath(configured.architecture, DEFAULT_PROJECT_PATHS.architecture),
52
+ state: normalizeRelPath(configured.state, DEFAULT_PROJECT_PATHS.state),
53
+ decisions_dir: normalizeRelPath(configured.decisions_dir, DEFAULT_PROJECT_PATHS.decisions_dir),
54
+ research_dir: normalizeRelPath(configured.research_dir, DEFAULT_PROJECT_PATHS.research_dir),
55
+ tasks_dir: normalizeRelPath(configured.tasks_dir, DEFAULT_PROJECT_PATHS.tasks_dir),
56
+ evidence_dir: normalizeRelPath(configured.evidence_dir, DEFAULT_PROJECT_PATHS.evidence_dir),
57
+ proposals_dir: normalizeRelPath(configured.proposals_dir, DEFAULT_PROJECT_PATHS.proposals_dir),
58
+ conflicts_dir: DEFAULT_PROJECT_PATHS.conflicts_dir,
59
+ incidents_dir: DEFAULT_PROJECT_PATHS.incidents_dir,
60
+ handoffs_dir: DEFAULT_PROJECT_PATHS.handoffs_dir,
61
+ };
62
+ }
63
+
64
+ /**
65
+ * Resolves a project root from an explicit `--project` argument or by walking upward
66
+ * from `cwd` to the nearest non-symlink `brain/manifest.yaml`, stopping at Git root or FS root.
67
+ */
68
+ export function resolveProjectDir({ project = null, cwd = process.cwd(), harnessDir = DEFAULT_HARNESS_DIR } = {}) {
69
+ if (typeof project === "string" && project.trim().length > 0) {
70
+ return {
71
+ projectDir: path.resolve(project),
72
+ discoveredFromCwd: false,
73
+ };
74
+ }
75
+
76
+ const resolvedHarness = path.resolve(harnessDir);
77
+ let cursor = path.resolve(cwd);
78
+ const visited = new Set();
79
+
80
+ while (cursor && !visited.has(cursor)) {
81
+ visited.add(cursor);
82
+ if (!fs.existsSync(cursor)) {
83
+ throw new Error(`Current working directory does not exist: ${cursor}`);
84
+ }
85
+ const dirStat = fs.lstatSync(cursor);
86
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) {
87
+ throw new Error(`Refusing symbolic link directory during project discovery: ${cursor}`);
88
+ }
89
+
90
+ if (!isSameOrInside(cursor, resolvedHarness)) {
91
+ const brainDir = path.join(cursor, "brain");
92
+ const manifestFile = path.join(brainDir, "manifest.yaml");
93
+ if (fs.existsSync(manifestFile)) {
94
+ if (fs.lstatSync(brainDir).isSymbolicLink() || fs.lstatSync(manifestFile).isSymbolicLink()) {
95
+ throw new Error(`Refusing symbolic link Second Brain manifest during discovery: ${manifestFile}`);
96
+ }
97
+ return {
98
+ projectDir: cursor,
99
+ discoveredFromCwd: true,
100
+ };
101
+ }
102
+ }
103
+
104
+ if (fs.existsSync(path.join(cursor, ".git"))) {
105
+ break;
106
+ }
107
+ const parent = path.dirname(cursor);
108
+ if (parent === cursor) {
109
+ break;
110
+ }
111
+ cursor = parent;
112
+ }
113
+
114
+ throw new Error(
115
+ `No GeloForge project found from "${path.resolve(cwd)}" (searched upward to Git root). Run "geloforge adopt" to add GeloForge to this repository, or pass "--project <path>".`
116
+ );
117
+ }
118
+
119
+ /**
120
+ * Loads and schema-validates brain/manifest.yaml and state YAML safely inside projectDir.
121
+ */
122
+ export function loadProjectManifestAndState(rawProjectDir, harnessDir = DEFAULT_HARNESS_DIR) {
123
+ const projectDir = path.resolve(rawProjectDir);
124
+ if (!fs.existsSync(projectDir)) {
125
+ throw new Error(`Project directory does not exist: ${projectDir}`);
126
+ }
127
+ const rootStat = fs.lstatSync(projectDir);
128
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
129
+ throw new Error(`Project root must be a real non-symlink directory: ${projectDir}`);
130
+ }
131
+
132
+ const schemasDir = path.join(path.resolve(harnessDir), "schemas");
133
+ const compatConfig = loadCompatibilityConfig();
134
+
135
+ const manifestPath = assertSafeWithinRoot(projectDir, "brain/manifest.yaml");
136
+ if (!fs.existsSync(manifestPath) || !fs.lstatSync(manifestPath).isFile()) {
137
+ throw new Error(`Missing or unsafe brain/manifest.yaml in ${projectDir}`);
138
+ }
139
+ const manifest = parseYaml(fs.readFileSync(manifestPath, "utf8"), "brain/manifest.yaml");
140
+ const manifestSchema = JSON.parse(fs.readFileSync(path.join(schemasDir, "project-manifest.schema.json"), "utf8"));
141
+ const mValid = validateAgainstSchema(manifest, manifestSchema);
142
+ if (!mValid.valid) {
143
+ throw new Error(`Invalid brain/manifest.yaml: ${mValid.errors.join("; ")}`);
144
+ }
145
+ const compat = checkManifestCompatibility(manifest, compatConfig);
146
+ if (!compat.compatible) {
147
+ throw new Error(`Incompatible brain/manifest.yaml: ${compat.errors.join("; ")}`);
148
+ }
149
+
150
+ const projectPaths = resolveProjectPaths(manifest);
151
+ const statePath = assertSafeWithinRoot(projectDir, projectPaths.state);
152
+ if (!fs.existsSync(statePath) || !fs.lstatSync(statePath).isFile()) {
153
+ throw new Error(`Missing or unsafe ${projectPaths.state} in ${projectDir}`);
154
+ }
155
+ const state = parseYaml(fs.readFileSync(statePath, "utf8"), projectPaths.state);
156
+ const sVer = checkRecordSchemaVersion(state, compatConfig);
157
+ if (!sVer.compatible) {
158
+ throw new Error(`${projectPaths.state}: ${sVer.error}`);
159
+ }
160
+ const stateSchema = JSON.parse(fs.readFileSync(path.join(schemasDir, "project-state.schema.json"), "utf8"));
161
+ const sValid = validateAgainstSchema(state, stateSchema);
162
+ if (!sValid.valid) {
163
+ throw new Error(`Invalid ${projectPaths.state}: ${sValid.errors.join("; ")}`);
164
+ }
165
+
166
+ return {
167
+ projectDir,
168
+ schemasDir,
169
+ compatConfig,
170
+ manifest,
171
+ state,
172
+ stateSchema,
173
+ stateFilePath: statePath,
174
+ projectPaths,
175
+ };
176
+ }
177
+
178
+ /**
179
+ * Scans record folders to discover existing IDs and allocate the next sequential ID (PREFIX-NNNN).
180
+ */
181
+ export function scanAndAllocateRecordId({ projectDir, searchDirs, prefix, explicitId = null }) {
182
+ const idRegex = new RegExp(`^(${prefix})-(\\d{4})$`, "i");
183
+ const filePrefixRegex = new RegExp(`^(${prefix}-\\d{4})(?=[^0-9]|$)`, "i");
184
+ const existingIds = new Set();
185
+ let maxNum = 0;
186
+
187
+ for (const relDir of Array.from(new Set(searchDirs))) {
188
+ const absDir = assertSafeWithinRoot(projectDir, relDir);
189
+ if (!fs.existsSync(absDir)) continue;
190
+ const files = walkNonSymlinkFiles(projectDir, absDir, (p) => /\.(md|ya?ml)$/i.test(p));
191
+ for (const f of files) {
192
+ const base = path.basename(f);
193
+ const fnameMatch = base.match(filePrefixRegex);
194
+ if (fnameMatch) {
195
+ const up = fnameMatch[1].toUpperCase();
196
+ existingIds.add(up);
197
+ const n = Number.parseInt(up.split("-")[1], 10);
198
+ if (n > maxNum) maxNum = n;
199
+ }
200
+ try {
201
+ const raw = fs.readFileSync(f, "utf8");
202
+ const parsedIdMatch = raw.match(new RegExp(`^id:\\s*["']?(${prefix}-\\d{4})["']?\\s*$`, "im"));
203
+ if (parsedIdMatch) {
204
+ const up = parsedIdMatch[1].toUpperCase();
205
+ existingIds.add(up);
206
+ const n = Number.parseInt(up.split("-")[1], 10);
207
+ if (n > maxNum) maxNum = n;
208
+ }
209
+ } catch {
210
+ // Ignore unreadable file during ID scan
211
+ }
212
+ }
213
+ }
214
+
215
+ if (explicitId !== null && explicitId !== undefined) {
216
+ const clean = String(explicitId).trim().toUpperCase();
217
+ if (!idRegex.test(clean)) {
218
+ throw new Error(`Invalid record ID "${explicitId}". Expected format ${prefix}-NNNN.`);
219
+ }
220
+ if (existingIds.has(clean)) {
221
+ throw new Error(`Duplicate record ID "${clean}" already exists.`);
222
+ }
223
+ return { id: clean, existingIds };
224
+ }
225
+
226
+ return {
227
+ id: `${prefix}-${String(maxNum + 1).padStart(4, "0")}`,
228
+ existingIds,
229
+ };
230
+ }
231
+
@@ -0,0 +1,438 @@
1
+ /**
2
+ * Cross-platform local filesystem lock (.geloforge/.state.lock), concurrent-safe stale-lock
3
+ * reclamation, pre-image rollback journal (.geloforge/.tx-journal.json), and multi-file
4
+ * transaction helper.
5
+ *
6
+ * Security & durability boundary:
7
+ * - `.geloforge/.state.lock` serializes cooperative local GeloForge processes only (it is NOT
8
+ * an OS mandatory file lock preventing external editors from touching files).
9
+ * - A lock owned by a living OS PID (`process.kill(pid, 0)`) is NEVER stolen regardless of TTL.
10
+ * - `runMultiFileTransaction` performs caught-exception rollback immediately in-process and writes
11
+ * a pre-image journal (`.geloforge/.tx-journal.json`) so subsequent locked GeloForge operations
12
+ * roll back interrupted partial writes after a process crash/kill. It is NOT a kernel-level
13
+ * or fsync-backed ACID database across power loss or unsynchronized external readers.
14
+ */
15
+
16
+ import crypto from "node:crypto";
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import { assertSafeWithinRoot, atomicWriteFile } from "./path-safety.mjs";
20
+
21
+ const ACTIVE_LOCKS = new Set();
22
+ const SLEEP_VIEW = new Int32Array(new SharedArrayBuffer(4));
23
+
24
+ function sleepSyncMs(ms) {
25
+ if (!Number.isFinite(ms) || ms <= 0) return;
26
+ Atomics.wait(SLEEP_VIEW, 0, 0, Math.ceil(ms));
27
+ }
28
+
29
+ function isPidAlive(pid) {
30
+ if (!Number.isInteger(pid) || pid <= 0) return false;
31
+ try {
32
+ process.kill(pid, 0);
33
+ return true;
34
+ } catch (err) {
35
+ if (err && err.code === "EPERM") return true;
36
+ return false;
37
+ }
38
+ }
39
+
40
+ function parseLockMeta(lockAbs) {
41
+ const st = fs.lstatSync(lockAbs);
42
+ if (st.isSymbolicLink() || !st.isFile()) {
43
+ throw new Error(`Refusing symbolic link or non-regular project lock file: ${lockAbs}`);
44
+ }
45
+ const raw = fs.readFileSync(lockAbs, "utf8");
46
+ let parsed = null;
47
+ try {
48
+ parsed = JSON.parse(raw);
49
+ } catch {
50
+ parsed = null;
51
+ }
52
+ return { st, parsed };
53
+ }
54
+
55
+ function isLockStale({ st, parsed }, staleLockMs, nowMs) {
56
+ if (!parsed || typeof parsed !== "object") {
57
+ // Allow brief grace window for another process still flushing JSON after openSync("wx")
58
+ return nowMs - st.mtimeMs >= Math.min(250, staleLockMs);
59
+ }
60
+ // Never expire or steal a lock while its owning OS PID remains alive.
61
+ if (Number.isInteger(parsed.pid) && parsed.pid > 0) {
62
+ if (parsed.pid === process.pid || isPidAlive(parsed.pid)) {
63
+ return false;
64
+ }
65
+ return true;
66
+ }
67
+ // Fallback only when lock metadata lacks a valid positive integer pid
68
+ const expMs = Date.parse(String(parsed.expires_at || ""));
69
+ if (Number.isFinite(expMs) && nowMs > expMs) {
70
+ return true;
71
+ }
72
+ if (nowMs - st.mtimeMs > staleLockMs) {
73
+ return true;
74
+ }
75
+ return false;
76
+ }
77
+
78
+ function isExpectedSameLock(currentMeta, expectedMeta) {
79
+ const expToken = expectedMeta?.parsed?.token;
80
+ if (typeof expToken === "string" && expToken.length > 0) {
81
+ return currentMeta?.parsed?.token === expToken;
82
+ }
83
+ return !currentMeta?.parsed && currentMeta?.st?.mtimeMs === expectedMeta?.st?.mtimeMs;
84
+ }
85
+
86
+ function releaseLockSafe(lockAbs, token) {
87
+ try {
88
+ if (!fs.existsSync(lockAbs)) return;
89
+ const st = fs.lstatSync(lockAbs);
90
+ if (st.isSymbolicLink() || !st.isFile()) return;
91
+ const parsed = JSON.parse(fs.readFileSync(lockAbs, "utf8"));
92
+ if (parsed && parsed.token === token) {
93
+ fs.unlinkSync(lockAbs);
94
+ }
95
+ } catch {
96
+ // Do not unlink lock owned by another process or already removed
97
+ }
98
+ }
99
+
100
+ function acquireReclaimGuard(reclaimAbs, staleLockMs) {
101
+ const guardToken = crypto.randomBytes(8).toString("hex");
102
+ const guardTtlMs = Math.max(1000, staleLockMs);
103
+ try {
104
+ const fd = fs.openSync(reclaimAbs, "wx", 0o600);
105
+ try {
106
+ const now = Date.now();
107
+ fs.writeFileSync(
108
+ fd,
109
+ `${JSON.stringify({ pid: process.pid, token: guardToken, created_at: new Date(now).toISOString() })}\n`,
110
+ "utf8"
111
+ );
112
+ } finally {
113
+ fs.closeSync(fd);
114
+ }
115
+ return guardToken;
116
+ } catch (err) {
117
+ if (!err || (err.code !== "EEXIST" && err.code !== "EPERM")) {
118
+ throw err;
119
+ }
120
+ // Check if an abandoned reclaim guard was left by a dead process
121
+ try {
122
+ const meta = parseLockMeta(reclaimAbs);
123
+ if (isLockStale(meta, guardTtlMs, Date.now())) {
124
+ const tmp = `${reclaimAbs}.dead-${crypto.randomBytes(4).toString("hex")}`;
125
+ try {
126
+ fs.renameSync(reclaimAbs, tmp);
127
+ if (fs.existsSync(tmp)) fs.unlinkSync(tmp);
128
+ } catch {
129
+ // Another process cleared or replaced it
130
+ }
131
+ }
132
+ } catch {
133
+ // Ignore transient ENOENT / busy races on guard check
134
+ }
135
+ return null;
136
+ }
137
+ }
138
+
139
+ function tryReclaimStaleLock(lockAbs, expectedMeta, staleLockMs) {
140
+ const reclaimAbs = `${lockAbs}.reclaim`;
141
+ const guardToken = acquireReclaimGuard(reclaimAbs, staleLockMs);
142
+ if (!guardToken) {
143
+ return false;
144
+ }
145
+
146
+ try {
147
+ let currentMeta;
148
+ try {
149
+ currentMeta = parseLockMeta(lockAbs);
150
+ } catch (err) {
151
+ if (err && err.code === "ENOENT") {
152
+ return false;
153
+ }
154
+ throw err;
155
+ }
156
+
157
+ // Re-verify identity and staleness so concurrent reclaimers never delete a winner's fresh live lock
158
+ if (!isExpectedSameLock(currentMeta, expectedMeta) || !isLockStale(currentMeta, staleLockMs, Date.now())) {
159
+ return false;
160
+ }
161
+
162
+ const staleTmp = `${lockAbs}.stale-${crypto.randomBytes(6).toString("hex")}`;
163
+ try {
164
+ fs.renameSync(lockAbs, staleTmp);
165
+ } catch (err) {
166
+ if (err && (err.code === "ENOENT" || err.code === "EPERM" || err.code === "EACCES" || err.code === "EBUSY")) {
167
+ return false;
168
+ }
169
+ throw err;
170
+ }
171
+ try {
172
+ if (fs.existsSync(staleTmp)) {
173
+ fs.unlinkSync(staleTmp);
174
+ }
175
+ } catch {
176
+ // Ignore cleanup error on reclaimed stale lock temp file
177
+ }
178
+ return true;
179
+ } finally {
180
+ releaseLockSafe(reclaimAbs, guardToken);
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Replays and clears any pending rollback journal (`.geloforge/.tx-journal.json`) left by an
186
+ * interrupted process before executing new locked work. Caller must hold `.geloforge/.state.lock`.
187
+ */
188
+ export function recoverPendingTransactionJournal(projectDir) {
189
+ const resolvedDir = path.resolve(projectDir);
190
+ const journalAbs = assertSafeWithinRoot(resolvedDir, ".geloforge/.tx-journal.json");
191
+ if (!fs.existsSync(journalAbs)) {
192
+ return { recovered: false, restoredFiles: 0 };
193
+ }
194
+ const st = fs.lstatSync(journalAbs);
195
+ if (st.isSymbolicLink() || !st.isFile()) {
196
+ throw new Error(`Refusing symbolic link or non-regular transaction journal: ${journalAbs}`);
197
+ }
198
+
199
+ const parsed = JSON.parse(fs.readFileSync(journalAbs, "utf8"));
200
+ const entries = Array.isArray(parsed?.entries) ? parsed.entries : [];
201
+ let restoredFiles = 0;
202
+
203
+ for (const entry of [...entries].reverse()) {
204
+ if (!entry || typeof entry.relPath !== "string") continue;
205
+ const targetAbs = assertSafeWithinRoot(resolvedDir, entry.relPath);
206
+ if (fs.existsSync(targetAbs)) {
207
+ const targetSt = fs.lstatSync(targetAbs);
208
+ if (targetSt.isSymbolicLink() || !targetSt.isFile()) {
209
+ throw new Error(`Refusing journal recovery onto symlink or non-regular path: ${entry.relPath}`);
210
+ }
211
+ }
212
+ if (entry.existed) {
213
+ atomicWriteFile(targetAbs, String(entry.previousContent ?? ""), { allowOverwrite: true });
214
+ } else if (fs.existsSync(targetAbs)) {
215
+ fs.unlinkSync(targetAbs);
216
+ }
217
+ restoredFiles += 1;
218
+ }
219
+
220
+ if (fs.existsSync(journalAbs)) {
221
+ fs.unlinkSync(journalAbs);
222
+ }
223
+
224
+ return { recovered: true, restoredFiles };
225
+ }
226
+
227
+ /**
228
+ * Executes `fn` while holding an exclusive atomic lockfile at `<projectDir>/.geloforge/.state.lock`.
229
+ */
230
+ export function withProjectLock(
231
+ projectDir,
232
+ fn,
233
+ { lockTimeoutMs = 5000, staleLockMs = 30000, retryDelayMs = 15 } = {}
234
+ ) {
235
+ if (typeof projectDir !== "string" || projectDir.trim().length === 0) {
236
+ throw new Error("Missing required project directory (--project <path>).");
237
+ }
238
+ const resolvedDir = path.resolve(projectDir);
239
+ if (!fs.existsSync(resolvedDir)) {
240
+ throw new Error(`Project directory does not exist: ${resolvedDir}`);
241
+ }
242
+ const rootStat = fs.lstatSync(resolvedDir);
243
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
244
+ throw new Error(`Project root must be a real non-symlink directory: ${resolvedDir}`);
245
+ }
246
+ const manifestAbs = assertSafeWithinRoot(resolvedDir, "brain/manifest.yaml");
247
+ if (!fs.existsSync(manifestAbs) || fs.lstatSync(manifestAbs).isSymbolicLink()) {
248
+ throw new Error(`Missing or unsafe brain/manifest.yaml in ${resolvedDir}`);
249
+ }
250
+ const canonicalDir = fs.realpathSync(resolvedDir);
251
+ if (ACTIVE_LOCKS.has(canonicalDir)) {
252
+ return fn();
253
+ }
254
+
255
+ const timeout = Number.isFinite(Number(lockTimeoutMs)) && Number(lockTimeoutMs) > 0 ? Number(lockTimeoutMs) : 5000;
256
+ const staleMs = Number.isFinite(Number(staleLockMs)) && Number(staleLockMs) > 0 ? Number(staleLockMs) : 30000;
257
+ const delay = Number.isFinite(Number(retryDelayMs)) && Number(retryDelayMs) > 0 ? Number(retryDelayMs) : 15;
258
+
259
+ const gfDirAbs = assertSafeWithinRoot(resolvedDir, ".geloforge");
260
+ if (fs.existsSync(gfDirAbs)) {
261
+ const dirSt = fs.lstatSync(gfDirAbs);
262
+ if (dirSt.isSymbolicLink() || !dirSt.isDirectory()) {
263
+ throw new Error(`Refusing symbolic link or non-directory .geloforge path: ${gfDirAbs}`);
264
+ }
265
+ } else {
266
+ fs.mkdirSync(gfDirAbs, { recursive: true });
267
+ }
268
+
269
+ const lockAbs = assertSafeWithinRoot(resolvedDir, ".geloforge/.state.lock");
270
+ const token = crypto.randomBytes(12).toString("hex");
271
+ const startMs = Date.now();
272
+
273
+ let acquired = false;
274
+ while (!acquired) {
275
+ try {
276
+ const fd = fs.openSync(lockAbs, "wx", 0o600);
277
+ try {
278
+ const now = Date.now();
279
+ const meta = {
280
+ pid: process.pid,
281
+ token,
282
+ created_at: new Date(now).toISOString(),
283
+ expires_at: new Date(now + staleMs).toISOString(),
284
+ };
285
+ fs.writeFileSync(fd, `${JSON.stringify(meta)}\n`, "utf8");
286
+ } finally {
287
+ fs.closeSync(fd);
288
+ }
289
+ acquired = true;
290
+ } catch (err) {
291
+ if (!err || (err.code !== "EEXIST" && err.code !== "EPERM")) {
292
+ throw err;
293
+ }
294
+
295
+ // Inspect existing lock (if present) for staleness or symlink violation
296
+ let metaInfo = null;
297
+ try {
298
+ metaInfo = parseLockMeta(lockAbs);
299
+ } catch (inspectErr) {
300
+ if (inspectErr && inspectErr.code === "ENOENT") {
301
+ continue;
302
+ }
303
+ throw inspectErr;
304
+ }
305
+
306
+ const nowMs = Date.now();
307
+ if (isLockStale(metaInfo, staleMs, nowMs)) {
308
+ if (tryReclaimStaleLock(lockAbs, metaInfo, staleMs)) {
309
+ continue;
310
+ }
311
+ }
312
+
313
+ const elapsed = nowMs - startMs;
314
+ if (elapsed >= timeout) {
315
+ throw new Error(
316
+ `Timed out waiting for project state lock (.geloforge/.state.lock) after ${timeout}ms.`
317
+ );
318
+ }
319
+ sleepSyncMs(Math.min(delay, timeout - elapsed));
320
+ }
321
+ }
322
+
323
+ ACTIVE_LOCKS.add(canonicalDir);
324
+ try {
325
+ recoverPendingTransactionJournal(resolvedDir);
326
+ return fn();
327
+ } finally {
328
+ ACTIVE_LOCKS.delete(canonicalDir);
329
+ releaseLockSafe(lockAbs, token);
330
+ }
331
+ }
332
+
333
+ /**
334
+ * Executes a sequence of file mutations atomically per file with a pre-image rollback journal
335
+ * (when `projectDir` is supplied). Restores pre-transaction state immediately on caught
336
+ * exceptions and allows future locked processes to recover from interrupted runs via `.tx-journal.json`.
337
+ */
338
+ export function runMultiFileTransaction(steps, { projectDir = null, faultHook = null } = {}) {
339
+ if (!Array.isArray(steps) || steps.length === 0) {
340
+ return;
341
+ }
342
+
343
+ const snapshots = new Map();
344
+ for (const step of steps) {
345
+ if (!step || typeof step.filePath !== "string") {
346
+ throw new Error("Invalid transaction step: missing filePath.");
347
+ }
348
+ if (snapshots.has(step.filePath)) continue;
349
+ if (fs.existsSync(step.filePath)) {
350
+ const st = fs.lstatSync(step.filePath);
351
+ if (st.isSymbolicLink() || !st.isFile()) {
352
+ throw new Error(`Refusing transaction target symlink or non-regular file: ${step.filePath}`);
353
+ }
354
+ snapshots.set(step.filePath, {
355
+ filePath: step.filePath,
356
+ existed: true,
357
+ previousContent: fs.readFileSync(step.filePath, "utf8"),
358
+ mode: step.mode,
359
+ });
360
+ } else {
361
+ snapshots.set(step.filePath, {
362
+ filePath: step.filePath,
363
+ existed: false,
364
+ previousContent: null,
365
+ });
366
+ }
367
+ }
368
+
369
+ let journalAbs = null;
370
+ if (typeof projectDir === "string" && projectDir.trim().length > 0) {
371
+ const resolvedProject = path.resolve(projectDir);
372
+ journalAbs = assertSafeWithinRoot(resolvedProject, ".geloforge/.tx-journal.json");
373
+ const entries = Array.from(snapshots.values()).map((snap) => {
374
+ const relPath = path.relative(resolvedProject, path.resolve(snap.filePath)).replace(/\\/g, "/");
375
+ if (!relPath || relPath.startsWith("..") || path.isAbsolute(relPath)) {
376
+ throw new Error(`Refusing transaction journal entry outside project root: ${snap.filePath}`);
377
+ }
378
+ return {
379
+ relPath,
380
+ existed: snap.existed,
381
+ previousContent: snap.previousContent,
382
+ };
383
+ });
384
+ atomicWriteFile(
385
+ journalAbs,
386
+ `${JSON.stringify({ pid: process.pid, created_at: new Date().toISOString(), entries }, null, 2)}\n`,
387
+ { allowOverwrite: true }
388
+ );
389
+ }
390
+
391
+ try {
392
+ for (let i = 0; i < steps.length; i += 1) {
393
+ const step = steps[i];
394
+ if (typeof faultHook === "function") {
395
+ faultHook(step.label, i);
396
+ }
397
+ if (step.deleteIfExists) {
398
+ if (fs.existsSync(step.filePath)) {
399
+ fs.unlinkSync(step.filePath);
400
+ }
401
+ } else {
402
+ atomicWriteFile(step.filePath, step.content, { allowOverwrite: step.allowOverwrite !== false, mode: step.mode });
403
+ }
404
+ if (typeof faultHook === "function") {
405
+ faultHook(`after:${step.label}`, i);
406
+ }
407
+ }
408
+ if (journalAbs && fs.existsSync(journalAbs)) {
409
+ fs.unlinkSync(journalAbs);
410
+ }
411
+ } catch (err) {
412
+ const rollbackErrors = [];
413
+ for (const snap of Array.from(snapshots.values()).reverse()) {
414
+ try {
415
+ if (snap.existed) {
416
+ atomicWriteFile(snap.filePath, snap.previousContent, { allowOverwrite: true, mode: snap.mode });
417
+ } else if (fs.existsSync(snap.filePath)) {
418
+ fs.unlinkSync(snap.filePath);
419
+ }
420
+ } catch (rbErr) {
421
+ rollbackErrors.push(`${snap.filePath}: ${rbErr.message}`);
422
+ }
423
+ }
424
+ if (rollbackErrors.length === 0 && journalAbs && fs.existsSync(journalAbs)) {
425
+ try {
426
+ fs.unlinkSync(journalAbs);
427
+ } catch {
428
+ // Leave journal for next lock acquisition if cleanup failed
429
+ }
430
+ }
431
+ if (rollbackErrors.length > 0) {
432
+ err.message = `${err.message} (rollback warnings: ${rollbackErrors.join("; ")})`;
433
+ }
434
+ throw err;
435
+ }
436
+ }
437
+
438
+ export { sleepSyncMs };