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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 63L0
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,141 @@
1
- # Temporary Holding Version
1
+ # GeloForge
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Keep your AI coding work understandable, portable, and verifiable.**
4
+
5
+ [![CI](https://github.com/63L0/GeloForge/actions/workflows/ci.yml/badge.svg)](https://github.com/63L0/GeloForge/actions/workflows/ci.yml)
6
+ [![Latest release](https://img.shields.io/github/v/release/63L0/GeloForge?label=release)](https://github.com/63L0/GeloForge/releases/latest)
7
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)
8
+
9
+ ![15-second GeloForge terminal replay showing MCP setup, an overlapping lease blocked, verified evidence, and a signed skill approval](./docs/media/geloforge-v06-demo.gif)
10
+
11
+ [Read and replay the GeloForge worktree case study](./docs/dogfooding-v06.md).
12
+
13
+ When an AI coding session ends, important decisions, unfinished work, and test results are easy to lose. **GeloForge keeps that knowledge in your repository**, not trapped inside one assistant's chat.
14
+
15
+ It's a small, open-source **command-line toolkit** for project memory, task tracking, verified command results, reusable agent skills, and handoffs between coding assistants. Built with Node.js, with **no paid API, hosted service, or third-party runtime dependencies**.
16
+
17
+ **[Get started](#quick-start)** · **[See a workflow](#see-it-in-action)** · **[Read the docs](#documentation)** · **[Contribute](#contributing)**
18
+
19
+ > **What GeloForge is not:** An AI model, autonomous coding agent, or automatic connection to your IDE. It prepares and validates files that you and your preferred AI coding tools can use.
20
+
21
+ ## Why GeloForge?
22
+
23
+ | Without a shared record | With GeloForge |
24
+ | --- | --- |
25
+ | A new chat has to relearn the project. | Build a focused context packet from project files. |
26
+ | "Tests passed" is just something an agent said. | Capture the actual command, exit status, and evidence. |
27
+ | Switching coding assistants loses the thread. | Hand over the task, verified results, and next actions. |
28
+ | Useful fixes stay buried in old conversations. | Draft portable `SKILL.md` workflows, review them, and reuse them. |
29
+
30
+ You stay in control of changes and approvals. GeloForge helps organize the work; it does **not** silently run or authorize AI-generated instructions.
31
+
32
+ ## Quick start
33
+
34
+ **Requires:** Node.js **20+** and Git. Works on Windows, macOS, and Linux.
35
+
36
+ Once v0.6 is available on npm, run these commands inside your existing project:
37
+
38
+ ```bash
39
+ npx geloforge adopt --dry-run
40
+ npx geloforge adopt
41
+ npx geloforge status
42
+ ```
43
+
44
+ For the current GitHub release, clone GeloForge and link the CLI:
45
+
46
+ ```bash
47
+ git clone https://github.com/63L0/GeloForge.git
48
+ cd GeloForge
49
+ npm link
50
+ geloforge --version
51
+ ```
52
+
53
+ Then go to **your existing project**:
54
+
55
+ ```bash
56
+ cd /path/to/your-project
57
+ geloforge adopt --dry-run # Preview changes first
58
+ geloforge adopt # Add project memory without overwriting your code
59
+ geloforge status
60
+ ```
61
+
62
+ That's it. Your project now has its own file-based starting point. GeloForge's CLI works from the project root or a nested directory.
63
+
64
+ You can also run `node scripts/geloforge.mjs --help` from the GeloForge checkout, or invoke the script by its full path from any directory.
65
+
66
+ [Follow the 5-minute walkthrough →](./docs/quickstart-5min.md)
67
+
68
+ ## See it in action
69
+
70
+ Here's a typical workflow after adopting a project:
71
+
72
+ ```bash
73
+ # 1. Give the next coding session a clear task.
74
+ geloforge task new --title "Fix login validation" --activate
75
+
76
+ # 2. Build a focused packet with relevant files and reusable skills.
77
+ geloforge context --task TASK-0001 --map --skills
78
+
79
+ # 3. Run your check, save a checkpoint, and complete the task if it passes.
80
+ geloforge verify -- node --test
81
+ ```
82
+
83
+ Replace `node --test` with your project's test command. To record a check while keeping a task open, run `geloforge evidence capture --task TASK-0001 -- node --test`.
84
+
85
+ When you're done, use `geloforge handoff` to record what changed, what was verified, and what the next developer or assistant should do. [See the handoff examples →](./docs/advanced-usage.md)
86
+
87
+ ## What you can do
88
+
89
+ | Capability | What it means for you |
90
+ | --- | --- |
91
+ | **Project memory** | Keep decisions, requirements, and current state in Markdown/YAML inside your repository. |
92
+ | **Safe onboarding** | Add GeloForge to an existing codebase with `adopt` or scaffold a new one with `init`. |
93
+ | **Tasks + evidence** | Create scoped tasks and capture real command results instead of relying on AI claims. |
94
+ | **Context + code map** | Send a smaller, more relevant project summary to your chosen AI assistant. |
95
+ | **Cross-agent handoff** | Pass structured, checkable work between sessions or tools. |
96
+ | **Portable Agent Skills** | Use open-format `SKILL.md` packages, with validation and progressive loading. |
97
+ | **Reviewed skill improvements** | Draft improvements from evidence, require explicit authorization, track versions, and roll back. |
98
+ | **Co-Pilot & checkpoints** | Get ranked next steps, human approval reminders, and resumable session notes. |
99
+ | **Cooperative multi-IDE work** | Claim tasks and scopes, see peer collision warnings, and avoid accidental overlapping work. |
100
+ | **Local MCP interface** | Run `geloforge mcp init` to set up Cursor, VS Code, Claude Code, or Gemini CLI with project-scoped tools. |
101
+
102
+ **Compatible workflow:** Codex, Claude Code, Gemini CLI, Antigravity, or any assistant that can read text you provide. GeloForge does not automatically operate or connect to those tools.
103
+
104
+ ## How it fits your project
105
+
106
+ GeloForge stores its records **alongside your code**, so you can inspect, version, and share them through Git:
107
+
108
+ ```text
109
+ your-project/
110
+ ├── brain/ # Decisions, constraints, and project state
111
+ ├── tasks/ # What needs to be done
112
+ ├── evidence/ # Recorded checks (created when needed)
113
+ ├── handoffs/ # Session/agent transfers (created when needed)
114
+ └── .agents/skills/ # Optional reusable SKILL.md packages
115
+ ```
116
+
117
+ You can use one AI assistant or switch between several. **No new backend, database, or model subscription is required.**
118
+
119
+ ## Documentation
120
+
121
+ | Start here | For |
122
+ | --- | --- |
123
+ | [5-minute quickstart](./docs/quickstart-5min.md) | Your first working project |
124
+ | [Detailed CLI & technical guide](./docs/advanced-usage.md) | Every major workflow and command |
125
+ | [Portable Skills guide](./docs/portable-skills.md) | `SKILL.md`, validation, approvals, and rollback |
126
+ | [Creating a new project](./docs/new-projects.md) | Profiles and project scaffolding |
127
+ | [Known limitations](./docs/known-limitations.md) | What is and is not guaranteed |
128
+ | [Security policy](./SECURITY.md) | Risks, trust boundaries, and reporting |
129
+ | [Changelog](./CHANGELOG.md) | What's changed in each release |
130
+
131
+ **Security note:** A local AI agent with unrestricted filesystem access can still bypass local file-level controls. Signing a skill does not prove an *independent human* approved it unless keys and enforcement are outside that agent's control. Skills linting is not a sandbox.
132
+
133
+ ## Contributing
134
+
135
+ GeloForge is **MIT-licensed** and built to be useful beyond one person's workflow.
136
+
137
+ Have an idea, find a confusing command, or hit a bug? [Open an issue](https://github.com/63L0/GeloForge/issues) or read [CONTRIBUTING.md](./CONTRIBUTING.md) to submit a pull request.
138
+
139
+ If this helps your AI-assisted development workflow, consider **[starring the repository](https://github.com/63L0/GeloForge)** so you can find it again.
140
+
141
+ **Latest published release:** [GitHub Releases](https://github.com/63L0/GeloForge/releases/latest) · [MIT License](./LICENSE)
@@ -0,0 +1,33 @@
1
+ # Third-Party Notices & Pattern Attribution
2
+
3
+ GeloForge is original software released under the [MIT License](./LICENSE) (`Copyright (c) 2026 63L0`) with zero third-party npm runtime dependencies.
4
+
5
+ Several design patterns in GeloForge were informed by studying public open-source agent ecosystems. Where upstream design ideas were adapted into original Node.js code, the corresponding project, commit/version, and license notices are preserved below.
6
+
7
+ ---
8
+
9
+ ## 1. NousResearch Hermes Agent (v0.4 Portable Skills Inspiration)
10
+
11
+ - **Upstream Repository:** https://github.com/NousResearch/hermes-agent
12
+ - **Inspected Reference Commit:** `15a495d672bee0ae6361ea523eb0854067e8d024`
13
+ - **License:** MIT License (`Copyright (c) 2025 Nous Research`)
14
+ - **Patterns Adapted in Original Node.js (`core/skills.mjs`, `core/skills-lint.mjs`, `core/skills-lifecycle.mjs`):**
15
+ - Separating support subdirectories (`references/`, `templates/`, `assets/`, `scripts/`) so nested documentation is never misread as standalone skills.
16
+ - Three-tier progressive disclosure (compact index -> relevant `SKILL.md` -> on-demand reference paths).
17
+ - Anti-rot skill linting heuristics (body size thresholds, trigger guidance, reference sprawl, extraneous scaffolding files, POSIX-only script portability warnings).
18
+ - Static security scanner categories for prompt-injection overrides, encoded shell execution, remote pipe installers, credential exfiltration, and hidden Unicode overrides (extended in GeloForge with fail-closed symlink/junction refusal, `.env*`/secret blacklists, and `A0`/quarantine isolation).
19
+ - Skill provenance tracking, experience-to-draft capture, isolated update diffs, and reversible revision snapshots (implemented in GeloForge with explicit verified-vs-suggested separation, Ed25519/PR-branch/TTY promotion gates, and SHA-256-verified rollback).
20
+ - **Attribution Note:** All code in GeloForge's skills modules was implemented from scratch in zero-dependency Node.js; no Python source files from Hermes Agent were copied verbatim.
21
+
22
+ ---
23
+
24
+ ## 2. Agent Skills Specification (`agentskills.io`)
25
+
26
+ - **Specification:** https://agentskills.io
27
+ - **Usage in GeloForge:** GeloForge's portable `SKILL.md` package layout, required `name`/`description` frontmatter rules, optional `license`/`compatibility`/`metadata`/`allowed-tools` fields, and `references/` / `templates/` / `assets/` / `scripts/` conventions follow the open Agent Skills format so skills remain portable across Codex, Gemini CLI, Claude Code, and Hermes-compatible workflows.
28
+
29
+ ---
30
+
31
+ ## 3. v0.3 Architecture & Repo-Map Research References
32
+
33
+ See [docs/research/upstream-patterns-v0.3.md](./docs/research/upstream-patterns-v0.3.md) for v0.3 design inspirations from GitHub Spec Kit (`MIT`), BMad Method (`MIT`), OpenHands (`MIT`), and Aider (`Apache-2.0` repo-map concept re-implemented cleanly in original Node.js without copying Apache-2.0 source code).
package/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.6.0
@@ -0,0 +1,458 @@
1
+ /**
2
+ * Safe, non-destructive brownfield adoption for existing repositories.
3
+ * Never overwrites existing files or mutates Git history; validates staged changes
4
+ * and rolls back only files and directories created by the current invocation.
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import {
11
+ assertNoSymlinkInTree,
12
+ assertSafeWithinRoot,
13
+ deriveSlug,
14
+ isForbiddenSecretPath,
15
+ validateExistingProjectDir,
16
+ validateProjectName,
17
+ validateScalarText,
18
+ validateSlug,
19
+ } from "./path-safety.mjs";
20
+ import { loadCompatibilityConfig } from "./compatibility.mjs";
21
+ import { getGitRepoInfo } from "./git-utils.mjs";
22
+ import { serializeYaml } from "./yaml-subset.mjs";
23
+ import { validateProject } from "./project-validator.mjs";
24
+ import {
25
+ detectStackHints,
26
+ inferProjectName,
27
+ renderSinglePass,
28
+ resolveProfile,
29
+ validateCreatedAt,
30
+ } from "./template-utils.mjs";
31
+
32
+ const __filename = fileURLToPath(import.meta.url);
33
+ const __dirname = path.dirname(__filename);
34
+ const DEFAULT_HARNESS_DIR = path.resolve(__dirname, "..");
35
+
36
+ function normalizeSubdirOption(rawVal, label, destDir) {
37
+ const clean = validateScalarText(label, rawVal).replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
38
+ if (clean.length === 0 || clean === "." || isForbiddenSecretPath(clean)) {
39
+ throw new Error(`Invalid ${label} path "${rawVal}".`);
40
+ }
41
+ assertSafeWithinRoot(destDir, clean);
42
+ return clean;
43
+ }
44
+
45
+ function pathExistsOrSymlink(absPath) {
46
+ if (fs.existsSync(absPath)) {
47
+ return true;
48
+ }
49
+ try {
50
+ fs.lstatSync(absPath);
51
+ return true;
52
+ } catch (err) {
53
+ if (err.code === "ENOENT") {
54
+ return false;
55
+ }
56
+ throw err;
57
+ }
58
+ }
59
+
60
+ function createDirsTracked(baseDir, relDir, createdDirs) {
61
+ const parts = relDir.split("/").filter(Boolean);
62
+ let cursor = baseDir;
63
+ for (const part of parts) {
64
+ cursor = path.join(cursor, part);
65
+ if (pathExistsOrSymlink(cursor)) {
66
+ const stat = fs.lstatSync(cursor);
67
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
68
+ throw new Error(`Refusing non-directory or symlink path collision: ${cursor}`);
69
+ }
70
+ } else {
71
+ fs.mkdirSync(cursor);
72
+ createdDirs.push(cursor);
73
+ }
74
+ }
75
+ }
76
+
77
+ function buildAdoptedIndexMarkdown({ tokens, destDir, tasksDir, evidenceDir }) {
78
+ const candidateCodeDirs = [
79
+ "src",
80
+ "app",
81
+ "lib",
82
+ "packages",
83
+ "cmd",
84
+ "pkg",
85
+ "internal",
86
+ "tests",
87
+ "test",
88
+ "__tests__",
89
+ "spec",
90
+ "docs",
91
+ ];
92
+ const existingDirs = candidateCodeDirs.filter((rel) => {
93
+ const abs = path.join(destDir, rel);
94
+ if (!fs.existsSync(abs)) return false;
95
+ try {
96
+ const st = fs.lstatSync(abs);
97
+ return !st.isSymbolicLink() && st.isDirectory();
98
+ } catch {
99
+ return false;
100
+ }
101
+ });
102
+
103
+ const codeLines =
104
+ existingDirs.length > 0
105
+ ? existingDirs.map((d) => `- [${d}/](../${d}/) — Existing project directory`)
106
+ : ["- *(No standard `src/` or `tests/` top-level directory detected; customize links as needed.)*"];
107
+
108
+ return [
109
+ `# Second Brain Index — ${tokens.PROJECT_NAME}`,
110
+ "",
111
+ `**Project ID:** \`${tokens.PROJECT_ID}\` `,
112
+ `**Owner:** ${tokens.PROJECT_OWNER}`,
113
+ "",
114
+ "This index maps this repository's provider-independent Second Brain added by `geloforge adopt`.",
115
+ "",
116
+ "## Layer 1 — Authoritative Knowledge (`L1_AUTHORITATIVE`)",
117
+ "",
118
+ "- [Project Manifest](./manifest.yaml) — Canonical metadata, version compatibility, and configured path map.",
119
+ "- [Product Requirements Document](./requirements/prd.md) — Goals, scope, and functional requirements (`A1` once owner-approved).",
120
+ "- [Project Constraints](./requirements/constraints.md) — Technical, security, and operational boundaries (`A1` once owner-approved).",
121
+ "- [Architecture Overview](./architecture/overview.md) — Topology overview and unverified (`A6`) stack hints for review.",
122
+ "- [Architecture Decision Records](./decisions/) — Immutable `ADR-NNNN-*.md` history.",
123
+ "",
124
+ "## Layer 2 — Operational Memory (`L2_OPERATIONAL`)",
125
+ "",
126
+ "- [Current Project State](./state/current.yaml) — Active tasks, blockers, pending approvals, and conflicts (`A4`).",
127
+ `- [Tasks](../${tasksDir}/) — Scoped \`TASK-NNNN\` contracts created with \`geloforge task new\`.`,
128
+ "",
129
+ "## Layer 3 — Research and Evidence (`L3_RESEARCH_EVIDENCE`)",
130
+ "",
131
+ `- Evidence records (\`EVID-NNNN-*.yaml\`) are written on demand into \`${evidenceDir}/\` via \`geloforge evidence capture\`.`,
132
+ "- Cross-agent handoffs live under `handoffs/` via `geloforge handoff`.",
133
+ "- Pending proposals live under `proposals/` when needed.",
134
+ "",
135
+ "## Existing Project Directories",
136
+ "",
137
+ ...codeLines,
138
+ "",
139
+ ].join("\n");
140
+ }
141
+
142
+ function buildAdoptedArchitectureMarkdown({ rawTemplate, tokens, hints }) {
143
+ const base = renderSinglePass(rawTemplate, tokens, false, "brain/architecture/overview.md").trimEnd();
144
+ const hintLines =
145
+ hints.length > 0
146
+ ? hints.map((h) => `- Detected marker: ${h.label}`)
147
+ : ["- No standard language manifest detected in repository root."];
148
+ return [
149
+ base,
150
+ "",
151
+ "## 4. Auto-Detected Stack Hints (A6 Draft — Requires Human Confirmation)",
152
+ "",
153
+ "> **Unverified Draft Notice:** GeloForge detected these markers by filename inspection only during `geloforge adopt`. Review and confirm before treating them as `A2` authoritative architecture facts.",
154
+ "",
155
+ ...hintLines,
156
+ "",
157
+ ].join("\n");
158
+ }
159
+
160
+ /**
161
+ * Safely adopts GeloForge into an existing project directory without overwriting any files.
162
+ */
163
+ export function adoptProject(options = {}) {
164
+ const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
165
+ const workspaceRoot = path.resolve(options.workspaceRoot || path.resolve(harnessDir, ".."));
166
+ const templateDir = path.join(harnessDir, "templates", "project-starter");
167
+ const profilesDir = path.join(harnessDir, "templates", "profiles");
168
+ const versionFile = path.join(harnessDir, "VERSION");
169
+
170
+ if (!fs.existsSync(templateDir) || !fs.existsSync(versionFile)) {
171
+ throw new Error(`Harness template or VERSION missing under ${harnessDir}`);
172
+ }
173
+ assertNoSymlinkInTree(templateDir);
174
+
175
+ const compatConfig = options.compatibilityConfig || loadCompatibilityConfig();
176
+ const destDir = validateExistingProjectDir(options.dest ?? process.cwd(), {
177
+ harnessDir,
178
+ workspaceRoot,
179
+ });
180
+
181
+ // Never allow duplicate adoption.
182
+ const existingManifest = path.join(destDir, "brain", "manifest.yaml");
183
+ if (pathExistsOrSymlink(existingManifest) || pathExistsOrSymlink(path.join(destDir, "brain", "manifest.yml"))) {
184
+ throw new Error(`Refusing to adopt: "${destDir}" already contains a GeloForge Second Brain (brain/manifest.yaml).`);
185
+ }
186
+
187
+ const projectName = options.name ? validateProjectName(options.name) : inferProjectName(destDir);
188
+ const derivedOrExplicitSlug = options.slug ? options.slug.trim() : deriveSlug(projectName);
189
+ const slug = validateSlug(derivedOrExplicitSlug);
190
+ const projectId = `proj-${slug}`;
191
+ const owner = validateScalarText("--owner", options.owner ?? "Project Owner");
192
+ const description = validateScalarText(
193
+ "--description",
194
+ options.description ?? "Existing project adopted into GeloForge Second Brain."
195
+ );
196
+
197
+ const tasksDir = normalizeSubdirOption(options.tasksDir ?? "tasks", "--tasks-dir", destDir);
198
+ const evidenceDir = normalizeSubdirOption(options.evidenceDir ?? "evidence", "--evidence-dir", destDir);
199
+ if (tasksDir === evidenceDir) {
200
+ throw new Error(`--tasks-dir and --evidence-dir must resolve to different folders ("${tasksDir}").`);
201
+ }
202
+
203
+ const resolvedProfile = resolveProfile(options.profile, compatConfig, profilesDir);
204
+ const profileMeta = resolvedProfile ? resolvedProfile.meta : null;
205
+
206
+ const gitInfo = getGitRepoInfo(destDir);
207
+ const defaultBranch = gitInfo.available && gitInfo.branch ? gitInfo.branch : "main";
208
+ const harnessVersion = fs.readFileSync(versionFile, "utf8").trim();
209
+ const createdAt = validateCreatedAt(options.createdAt);
210
+ const createdDate = createdAt.slice(0, 10);
211
+
212
+ const tokens = {
213
+ PROJECT_NAME: projectName,
214
+ PROJECT_SLUG: slug,
215
+ PROJECT_ID: projectId,
216
+ PROJECT_DESCRIPTION: description,
217
+ PROJECT_OWNER: owner,
218
+ CREATED_AT: createdAt,
219
+ CREATED_DATE: createdDate,
220
+ HARNESS_VERSION: harnessVersion,
221
+ TEMPLATE_VERSION: compatConfig.template_version,
222
+ PROFILE_NAME: profileMeta ? profileMeta.name : "none",
223
+ PROFILE_VERSION: profileMeta ? profileMeta.version : "0.0.0",
224
+ };
225
+
226
+ const detectedStack = detectStackHints(destDir);
227
+ const warnings = [];
228
+
229
+ const manifestObj = {
230
+ schema_version: "1.1",
231
+ template_version: compatConfig.template_version,
232
+ profile: profileMeta ? profileMeta.name : null,
233
+ profile_version: profileMeta ? profileMeta.version : null,
234
+ project_id: projectId,
235
+ slug,
236
+ name: projectName,
237
+ description,
238
+ status: "initialized",
239
+ owner,
240
+ memory_layer: "L1_AUTHORITATIVE",
241
+ authority_level: "A1",
242
+ harness_version: harnessVersion,
243
+ created_at: createdAt,
244
+ updated_at: createdAt,
245
+ repository: {
246
+ vcs: "git",
247
+ initialized: Boolean(gitInfo.available),
248
+ default_branch: defaultBranch,
249
+ },
250
+ paths: {
251
+ brain_index: "brain/INDEX.md",
252
+ prd: "brain/requirements/prd.md",
253
+ constraints: "brain/requirements/constraints.md",
254
+ architecture: "brain/architecture/overview.md",
255
+ state: "brain/state/current.yaml",
256
+ decisions_dir: "brain/decisions",
257
+ research_dir: "brain/research",
258
+ tasks_dir: tasksDir,
259
+ evidence_dir: evidenceDir,
260
+ proposals_dir: "proposals",
261
+ },
262
+ policies: [
263
+ "policies/approval-boundaries.md",
264
+ "policies/memory-policy.md",
265
+ "policies/token-efficiency.md",
266
+ ],
267
+ };
268
+
269
+ const stateObj = {
270
+ schema_version: "1.1",
271
+ project_id: projectId,
272
+ state_revision: 0,
273
+ status: "initialized",
274
+ memory_layer: "L2_OPERATIONAL",
275
+ authority_level: "A4",
276
+ updated_at: createdAt,
277
+ updated_by: owner,
278
+ current_phase: "adoption",
279
+ active_tasks: [],
280
+ blocked_tasks: [],
281
+ pending_approvals: [],
282
+ open_conflicts: [],
283
+ last_verified_evidence: null,
284
+ last_checkpoint: null,
285
+ last_completed_task: null,
286
+ known_dependencies: [],
287
+ summary: `Existing repository adopted into GeloForge Second Brain (tasks=${tasksDir}, evidence=${evidenceDir}); no application verification run captured yet.`,
288
+ };
289
+
290
+ const plannedMap = new Map();
291
+ plannedMap.set("brain/manifest.yaml", serializeYaml(manifestObj, { headerComment: "Project Manifest (adopted)" }));
292
+ plannedMap.set(
293
+ "brain/state/current.yaml",
294
+ serializeYaml(stateObj, { headerComment: "Current Operational Project State" })
295
+ );
296
+ plannedMap.set(
297
+ "brain/INDEX.md",
298
+ buildAdoptedIndexMarkdown({ tokens, destDir, tasksDir, evidenceDir })
299
+ );
300
+ plannedMap.set(
301
+ "brain/requirements/prd.md",
302
+ renderSinglePass(
303
+ fs.readFileSync(path.join(templateDir, "brain", "requirements", "prd.md"), "utf8"),
304
+ tokens,
305
+ false,
306
+ "brain/requirements/prd.md"
307
+ )
308
+ );
309
+ plannedMap.set(
310
+ "brain/requirements/constraints.md",
311
+ renderSinglePass(
312
+ fs.readFileSync(path.join(templateDir, "brain", "requirements", "constraints.md"), "utf8"),
313
+ tokens,
314
+ false,
315
+ "brain/requirements/constraints.md"
316
+ )
317
+ );
318
+ plannedMap.set(
319
+ "brain/architecture/overview.md",
320
+ buildAdoptedArchitectureMarkdown({
321
+ rawTemplate: fs.readFileSync(path.join(templateDir, "brain", "architecture", "overview.md"), "utf8"),
322
+ tokens,
323
+ hints: detectedStack,
324
+ })
325
+ );
326
+
327
+ if (!pathExistsOrSymlink(path.join(destDir, "brain", "decisions"))) {
328
+ plannedMap.set("brain/decisions/.gitkeep", "");
329
+ }
330
+
331
+ const absTasksDir = path.join(destDir, tasksDir);
332
+ if (!pathExistsOrSymlink(absTasksDir)) {
333
+ plannedMap.set(`${tasksDir}/.gitkeep`, "");
334
+ } else {
335
+ const tasksStat = fs.lstatSync(absTasksDir);
336
+ if (tasksStat.isSymbolicLink() || !tasksStat.isDirectory()) {
337
+ throw new Error(`Existing tasks directory "${tasksDir}" is not a real non-symlink directory.`);
338
+ }
339
+ const preExistingTaskFiles = fs.readdirSync(absTasksDir).filter((f) => /\.(md|ya?ml)$/i.test(f));
340
+ if (preExistingTaskFiles.length > 0) {
341
+ warnings.push(
342
+ `Existing directory "${tasksDir}" already contains ${preExistingTaskFiles.length} Markdown/YAML file(s); left untouched.`
343
+ );
344
+ }
345
+ }
346
+
347
+ if (resolvedProfile) {
348
+ const profileGuideSrc = path.join(resolvedProfile.profileDir, "brain", "profile.md");
349
+ if (fs.existsSync(profileGuideSrc)) {
350
+ const rawGuide = fs.readFileSync(profileGuideSrc, "utf8");
351
+ plannedMap.set("brain/profile.md", renderSinglePass(rawGuide, tokens, false, "brain/profile.md"));
352
+ }
353
+ }
354
+
355
+ if (options.withAgentGuides) {
356
+ for (const guideName of ["AGENTS.md", "GEMINI.md"]) {
357
+ const rawGuide = fs.readFileSync(path.join(templateDir, guideName), "utf8");
358
+ plannedMap.set(guideName, renderSinglePass(rawGuide, tokens, false, guideName));
359
+ }
360
+ }
361
+
362
+ const orderedFiles = Array.from(plannedMap.entries())
363
+ .sort(([a], [b]) => a.localeCompare(b))
364
+ .map(([relPath, content]) => ({ relPath, content }));
365
+
366
+ // Pre-flight check: verify zero collisions and zero symlink escapes BEFORE creating any directory or file.
367
+ for (const file of orderedFiles) {
368
+ const absTarget = assertSafeWithinRoot(destDir, file.relPath);
369
+ if (pathExistsOrSymlink(absTarget)) {
370
+ throw new Error(`Refusing to overwrite existing file during adoption: ${file.relPath}`);
371
+ }
372
+ }
373
+
374
+ if (options.dryRun) {
375
+ return {
376
+ dryRun: true,
377
+ projectName,
378
+ projectId,
379
+ slug,
380
+ owner,
381
+ destDir,
382
+ profile: profileMeta ? profileMeta.name : null,
383
+ profileVersion: profileMeta ? profileMeta.version : null,
384
+ gitDetected: Boolean(gitInfo.available),
385
+ defaultBranch,
386
+ tasksDir,
387
+ evidenceDir,
388
+ detectedStack,
389
+ files: orderedFiles.map((f) => f.relPath),
390
+ warnings,
391
+ validation: null,
392
+ };
393
+ }
394
+
395
+ const createdFiles = [];
396
+ const createdDirs = [];
397
+
398
+ try {
399
+ for (const file of orderedFiles) {
400
+ const parentRel = path.posix.dirname(file.relPath);
401
+ if (parentRel && parentRel !== ".") {
402
+ createDirsTracked(destDir, parentRel, createdDirs);
403
+ }
404
+ const absTarget = assertSafeWithinRoot(destDir, file.relPath);
405
+ fs.writeFileSync(absTarget, file.content, { encoding: "utf8", flag: "wx" });
406
+ createdFiles.push(absTarget);
407
+ }
408
+
409
+ const validation = validateProject(destDir, { compatibilityConfig: compatConfig });
410
+ if (!validation.valid) {
411
+ throw new Error(`Adopted project failed validation: ${validation.errors.join("; ")}`);
412
+ }
413
+
414
+ if (typeof options.onBeforeCommit === "function") {
415
+ options.onBeforeCommit({
416
+ destDir,
417
+ createdFiles: [...createdFiles],
418
+ createdDirs: [...createdDirs],
419
+ });
420
+ }
421
+
422
+ return {
423
+ dryRun: false,
424
+ projectName,
425
+ projectId,
426
+ slug,
427
+ owner,
428
+ destDir,
429
+ profile: profileMeta ? profileMeta.name : null,
430
+ profileVersion: profileMeta ? profileMeta.version : null,
431
+ gitDetected: Boolean(gitInfo.available),
432
+ defaultBranch,
433
+ tasksDir,
434
+ evidenceDir,
435
+ detectedStack,
436
+ files: orderedFiles.map((f) => f.relPath),
437
+ warnings,
438
+ validation,
439
+ };
440
+ } catch (err) {
441
+ // Strictly unlink/rmdir ONLY the files and empty directories created during this invocation.
442
+ for (let i = createdFiles.length - 1; i >= 0; i -= 1) {
443
+ try {
444
+ fs.unlinkSync(createdFiles[i]);
445
+ } catch {
446
+ // Best-effort rollback
447
+ }
448
+ }
449
+ for (let i = createdDirs.length - 1; i >= 0; i -= 1) {
450
+ try {
451
+ fs.rmdirSync(createdDirs[i]);
452
+ } catch {
453
+ // Leave non-empty or pre-existing directories untouched
454
+ }
455
+ }
456
+ throw err;
457
+ }
458
+ }