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.
- package/LICENSE +21 -0
- package/README.md +72 -2
- package/THIRD_PARTY_NOTICES.md +33 -0
- package/VERSION +1 -0
- package/adapters/n8n/staging-audit-error-workflow.json +132 -0
- package/core/adopt-project.mjs +458 -0
- package/core/audit-learning.mjs +68 -0
- package/core/audit-provider.mjs +88 -0
- package/core/autonomous-audit.mjs +214 -0
- package/core/checkpoint.mjs +448 -0
- package/core/codebase-map.mjs +886 -0
- package/core/compatibility.json +16 -0
- package/core/compatibility.mjs +123 -0
- package/core/context-cache.mjs +113 -0
- package/core/context-compiler.mjs +1315 -0
- package/core/evidence-capture.mjs +347 -0
- package/core/git-utils.mjs +167 -0
- package/core/handoff.mjs +815 -0
- package/core/json-schema-lite.mjs +119 -0
- package/core/mcp-init.mjs +251 -0
- package/core/mcp-server.mjs +915 -0
- package/core/operation-approval.mjs +102 -0
- package/core/path-safety.mjs +508 -0
- package/core/project-locator.mjs +231 -0
- package/core/project-lock.mjs +438 -0
- package/core/project-status.mjs +635 -0
- package/core/project-validator.mjs +544 -0
- package/core/promotion.mjs +90 -0
- package/core/runtime-files.mjs +40 -0
- package/core/skills-history.mjs +572 -0
- package/core/skills-lifecycle.mjs +2225 -0
- package/core/skills-lint.mjs +365 -0
- package/core/skills.mjs +1449 -0
- package/core/staging-audit.mjs +454 -0
- package/core/staging-evidence.mjs +127 -0
- package/core/task-manager.mjs +1044 -0
- package/core/template-utils.mjs +190 -0
- package/core/text-utils.mjs +48 -0
- package/core/verify-task.mjs +48 -0
- package/core/worktrees.mjs +64 -0
- package/core/yaml-subset.mjs +572 -0
- package/package.json +50 -4
- package/policies/approval-boundaries.md +42 -0
- package/policies/memory-policy.md +53 -0
- package/policies/token-efficiency.md +30 -0
- package/schemas/README.md +43 -0
- package/schemas/adr.schema.json +64 -0
- package/schemas/agent-handoff.schema.json +139 -0
- package/schemas/approval-record.schema.json +110 -0
- package/schemas/conflict-record.schema.json +60 -0
- package/schemas/context-pack-manifest.schema.json +194 -0
- package/schemas/evidence-manifest.schema.json +83 -0
- package/schemas/incident-record.schema.json +53 -0
- package/schemas/project-manifest.schema.json +90 -0
- package/schemas/project-state.schema.json +64 -0
- package/schemas/recovery-checkpoint.schema.json +49 -0
- package/schemas/research-record.schema.json +76 -0
- package/schemas/task-contract.schema.json +95 -0
- package/scripts/bootstrap-project.mjs +357 -0
- package/scripts/geloforge.mjs +2512 -0
- package/templates/profiles/README.md +19 -0
- package/templates/profiles/ai-system/brain/profile.md +21 -0
- package/templates/profiles/ai-system/gitignore.append +5 -0
- package/templates/profiles/ai-system/profile.json +6 -0
- package/templates/profiles/automation/brain/profile.md +19 -0
- package/templates/profiles/automation/gitignore.append +5 -0
- package/templates/profiles/automation/profile.json +6 -0
- package/templates/profiles/desktop/brain/profile.md +21 -0
- package/templates/profiles/desktop/gitignore.append +7 -0
- package/templates/profiles/desktop/profile.json +6 -0
- package/templates/profiles/mobile/brain/profile.md +20 -0
- package/templates/profiles/mobile/gitignore.append +8 -0
- package/templates/profiles/mobile/profile.json +6 -0
- package/templates/profiles/web/brain/profile.md +21 -0
- package/templates/profiles/web/gitignore.append +6 -0
- package/templates/profiles/web/profile.json +6 -0
- package/templates/project-starter/AGENTS.md +27 -0
- package/templates/project-starter/GEMINI.md +16 -0
- package/templates/project-starter/README.md +26 -0
- package/templates/project-starter/brain/INDEX.md +40 -0
- package/templates/project-starter/brain/architecture/overview.md +30 -0
- package/templates/project-starter/brain/decisions/.gitkeep +0 -0
- package/templates/project-starter/brain/manifest.yaml +36 -0
- package/templates/project-starter/brain/requirements/constraints.md +29 -0
- package/templates/project-starter/brain/requirements/prd.md +37 -0
- package/templates/project-starter/brain/state/current.yaml +19 -0
- package/templates/project-starter/gitignore.template +25 -0
- package/templates/project-starter/src/.gitkeep +0 -0
- package/templates/project-starter/tasks/.gitkeep +0 -0
- package/templates/project-starter/tests/.gitkeep +0 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared template rendering, compatibility profile loading, timestamp validation,
|
|
3
|
+
* and lightweight read-only project discovery helpers.
|
|
4
|
+
* Zero external dependencies.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { parseSemver } from "./compatibility.mjs";
|
|
10
|
+
import { assertNoSymlinkInTree, validateProjectName } from "./path-safety.mjs";
|
|
11
|
+
|
|
12
|
+
const PROFILE_NAME_REGEX = /^[a-z0-9][a-z0-9-]*$/;
|
|
13
|
+
|
|
14
|
+
export function escapeYamlScalarText(value) {
|
|
15
|
+
return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function renderSinglePass(rawContent, tokens, isYaml, sourceLabel) {
|
|
19
|
+
return rawContent.replace(/\{\{([A-Z0-9_]+)\}\}/g, (_match, key) => {
|
|
20
|
+
if (!Object.hasOwn(tokens, key)) {
|
|
21
|
+
throw new Error(`Unsupported template placeholder "{{${key}}}" in ${sourceLabel}`);
|
|
22
|
+
}
|
|
23
|
+
const val = tokens[key];
|
|
24
|
+
return isYaml ? escapeYamlScalarText(val) : val;
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function validateCreatedAt(rawCreatedAt) {
|
|
29
|
+
if (rawCreatedAt === undefined || rawCreatedAt === null) {
|
|
30
|
+
return new Date().toISOString();
|
|
31
|
+
}
|
|
32
|
+
const trimmed = String(rawCreatedAt).trim();
|
|
33
|
+
const parsed = Date.parse(trimmed);
|
|
34
|
+
if (Number.isNaN(parsed) || trimmed.length < 10) {
|
|
35
|
+
throw new Error(`Invalid --created-at ISO timestamp "${rawCreatedAt}".`);
|
|
36
|
+
}
|
|
37
|
+
return trimmed;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function resolveProfile(profileName, compatConfig, profilesDir) {
|
|
41
|
+
if (!profileName) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
const clean = profileName.trim();
|
|
45
|
+
if (!PROFILE_NAME_REGEX.test(clean)) {
|
|
46
|
+
throw new Error(`Invalid profile name "${profileName}".`);
|
|
47
|
+
}
|
|
48
|
+
if (!Object.hasOwn(compatConfig.profiles, clean)) {
|
|
49
|
+
const allowed = Object.keys(compatConfig.profiles).join(", ");
|
|
50
|
+
throw new Error(`Unknown project profile "${clean}". Available profiles: ${allowed}`);
|
|
51
|
+
}
|
|
52
|
+
const profileDir = path.join(profilesDir, clean);
|
|
53
|
+
if (!fs.existsSync(profileDir) || !fs.statSync(profileDir).isDirectory()) {
|
|
54
|
+
throw new Error(`Profile directory missing for "${clean}": ${profileDir}`);
|
|
55
|
+
}
|
|
56
|
+
assertNoSymlinkInTree(profileDir);
|
|
57
|
+
|
|
58
|
+
const metaPath = path.join(profileDir, "profile.json");
|
|
59
|
+
if (!fs.existsSync(metaPath)) {
|
|
60
|
+
throw new Error(`Profile metadata missing: ${metaPath}`);
|
|
61
|
+
}
|
|
62
|
+
const meta = JSON.parse(fs.readFileSync(metaPath, "utf8"));
|
|
63
|
+
if (meta.name !== clean) {
|
|
64
|
+
throw new Error(`Profile metadata mismatch in ${metaPath}: expected "${clean}", got "${meta.name}".`);
|
|
65
|
+
}
|
|
66
|
+
if (meta.compatible_template_major !== compatConfig.supported_template_major) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
`Profile "${clean}" requires template major ${meta.compatible_template_major}, harness uses ${compatConfig.supported_template_major}.`
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
const parsedProfVer = parseSemver(meta.version);
|
|
72
|
+
if (!parsedProfVer || parsedProfVer.major !== compatConfig.supported_profile_major) {
|
|
73
|
+
throw new Error(`Profile "${clean}" has incompatible version "${meta.version}".`);
|
|
74
|
+
}
|
|
75
|
+
return { meta, profileDir };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function sanitizeInferredName(candidate) {
|
|
79
|
+
if (typeof candidate !== "string") return null;
|
|
80
|
+
let cleaned = candidate.trim();
|
|
81
|
+
if (cleaned.startsWith("@") && cleaned.includes("/")) {
|
|
82
|
+
cleaned = cleaned.split("/").slice(1).join("-");
|
|
83
|
+
}
|
|
84
|
+
cleaned = cleaned
|
|
85
|
+
.replace(/[<>:"/\\|?*\x00-\x1f\x7f]+/g, " ")
|
|
86
|
+
.replace(/\.\.+/g, " ")
|
|
87
|
+
.replace(/\.+$/g, "")
|
|
88
|
+
.replace(/\s+/g, " ")
|
|
89
|
+
.trim()
|
|
90
|
+
.slice(0, 80);
|
|
91
|
+
if (cleaned.length < 3) {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
return validateProjectName(cleaned);
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Infers a display name read-only from common project manifests or directory basename.
|
|
103
|
+
*/
|
|
104
|
+
export function inferProjectName(destDir) {
|
|
105
|
+
const tryReadSafe = (fileName) => {
|
|
106
|
+
const full = path.join(destDir, fileName);
|
|
107
|
+
if (!fs.existsSync(full)) return null;
|
|
108
|
+
try {
|
|
109
|
+
const st = fs.lstatSync(full);
|
|
110
|
+
if (st.isSymbolicLink() || !st.isFile() || st.size > 256 * 1024) return null;
|
|
111
|
+
return fs.readFileSync(full, "utf8");
|
|
112
|
+
} catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const pkgRaw = tryReadSafe("package.json");
|
|
118
|
+
if (pkgRaw) {
|
|
119
|
+
try {
|
|
120
|
+
const pkg = JSON.parse(pkgRaw);
|
|
121
|
+
const inferred = sanitizeInferredName(pkg?.name);
|
|
122
|
+
if (inferred) return inferred;
|
|
123
|
+
} catch {
|
|
124
|
+
// Ignore malformed package.json
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const pyRaw = tryReadSafe("pyproject.toml");
|
|
129
|
+
if (pyRaw) {
|
|
130
|
+
const match = pyRaw.match(/^\s*name\s*=\s*["']([^"'\r\n]+)["']/m);
|
|
131
|
+
const inferred = sanitizeInferredName(match?.[1]);
|
|
132
|
+
if (inferred) return inferred;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const cargoRaw = tryReadSafe("Cargo.toml");
|
|
136
|
+
if (cargoRaw) {
|
|
137
|
+
const match = cargoRaw.match(/^\s*name\s*=\s*["']([^"'\r\n]+)["']/m);
|
|
138
|
+
const inferred = sanitizeInferredName(match?.[1]);
|
|
139
|
+
if (inferred) return inferred;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const goModRaw = tryReadSafe("go.mod");
|
|
143
|
+
if (goModRaw) {
|
|
144
|
+
const match = goModRaw.match(/^\s*module\s+([^\s\r\n]+)/m);
|
|
145
|
+
if (match?.[1]) {
|
|
146
|
+
const tail = match[1].split("/").filter(Boolean).pop();
|
|
147
|
+
const inferred = sanitizeInferredName(tail);
|
|
148
|
+
if (inferred) return inferred;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return sanitizeInferredName(path.basename(destDir)) || "Adopted Project";
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Performs read-only filename-based stack detection (marked as unverified draft hints).
|
|
157
|
+
*/
|
|
158
|
+
export function detectStackHints(destDir) {
|
|
159
|
+
const hints = [];
|
|
160
|
+
let rootEntries = [];
|
|
161
|
+
try {
|
|
162
|
+
rootEntries = fs.readdirSync(destDir, { withFileTypes: true }).map((e) => e.name);
|
|
163
|
+
} catch {
|
|
164
|
+
return hints;
|
|
165
|
+
}
|
|
166
|
+
const entrySet = new Set(rootEntries);
|
|
167
|
+
const addIfPresent = (file, label) => {
|
|
168
|
+
if (entrySet.has(file)) {
|
|
169
|
+
hints.push({ marker: file, label });
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
addIfPresent("package.json", "Node.js / JavaScript (`package.json`)");
|
|
174
|
+
addIfPresent("tsconfig.json", "TypeScript (`tsconfig.json`)");
|
|
175
|
+
addIfPresent("pyproject.toml", "Python (`pyproject.toml`)");
|
|
176
|
+
addIfPresent("requirements.txt", "Python dependencies (`requirements.txt`)");
|
|
177
|
+
addIfPresent("go.mod", "Go module (`go.mod`)");
|
|
178
|
+
addIfPresent("Cargo.toml", "Rust crate (`Cargo.toml`)");
|
|
179
|
+
addIfPresent("pom.xml", "Java Maven (`pom.xml`)");
|
|
180
|
+
addIfPresent("build.gradle", "Gradle (`build.gradle`)");
|
|
181
|
+
addIfPresent("build.gradle.kts", "Gradle Kotlin (`build.gradle.kts`)");
|
|
182
|
+
addIfPresent("Makefile", "Make (`Makefile`)");
|
|
183
|
+
addIfPresent("Dockerfile", "Docker (`Dockerfile`)");
|
|
184
|
+
|
|
185
|
+
const csproj = rootEntries.find((name) => name.endsWith(".csproj") || name.endsWith(".sln"));
|
|
186
|
+
if (csproj) {
|
|
187
|
+
hints.push({ marker: csproj, label: `.NET / C# (\`${csproj}\`)` });
|
|
188
|
+
}
|
|
189
|
+
return hints;
|
|
190
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared deterministic text, token-estimation, keywording, and fence-escaping helpers
|
|
3
|
+
* reused across GeloForge Context Compiler and Portable Skills modules.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export const TOKEN_ESTIMATE_METHOD = "heuristic:ceil(utf8_bytes/4)";
|
|
7
|
+
|
|
8
|
+
export const STOP_WORDS = new Set([
|
|
9
|
+
"the", "and", "for", "with", "that", "this", "from", "into", "when", "what", "where",
|
|
10
|
+
"which", "will", "should", "must", "have", "has", "been", "being", "they", "their",
|
|
11
|
+
"them", "then", "than", "only", "also", "more", "most", "some", "such", "each",
|
|
12
|
+
"other", "about", "after", "before", "between", "through", "under", "over", "using",
|
|
13
|
+
"use", "used", "task", "project", "brain", "file", "files", "all", "not", "are", "but",
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Estimates prompt token count conservatively from UTF-8 byte length.
|
|
18
|
+
*/
|
|
19
|
+
export function estimateTokens(text) {
|
|
20
|
+
if (!text) {
|
|
21
|
+
return 0;
|
|
22
|
+
}
|
|
23
|
+
return Math.ceil(Buffer.byteLength(text, "utf8") / 4);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Extracts normalized search keywords (>= 3 chars, excluding stop words).
|
|
28
|
+
*/
|
|
29
|
+
export function tokenizeKeywords(text) {
|
|
30
|
+
if (!text || typeof text !== "string") {
|
|
31
|
+
return new Set();
|
|
32
|
+
}
|
|
33
|
+
const tokens = text
|
|
34
|
+
.toLowerCase()
|
|
35
|
+
.split(/[^a-z0-9_-]+/)
|
|
36
|
+
.filter((t) => t.length >= 3 && !STOP_WORDS.has(t));
|
|
37
|
+
return new Set(tokens);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Escapes spoofed GELOFORGE_DOC delimiters inside included text.
|
|
42
|
+
* Marker escaping alone does NOT mitigate semantic prompt injection.
|
|
43
|
+
*/
|
|
44
|
+
export function sanitizeFenceContent(text) {
|
|
45
|
+
return String(text || "")
|
|
46
|
+
.replace(/<<<END_GELOFORGE_DOC>>>/g, "<<<ESCAPED_END_GELOFORGE_DOC>>>")
|
|
47
|
+
.replace(/<<<GELOFORGE_DOC/g, "<<<ESCAPED_GELOFORGE_DOC");
|
|
48
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { createCheckpoint } from "./checkpoint.mjs";
|
|
2
|
+
import { captureEvidence } from "./evidence-capture.mjs";
|
|
3
|
+
import { redactSecretContent } from "./path-safety.mjs";
|
|
4
|
+
import { loadProjectManifestAndState } from "./project-locator.mjs";
|
|
5
|
+
import { withProjectLock } from "./project-lock.mjs";
|
|
6
|
+
import { completeTask, getTask } from "./task-manager.mjs";
|
|
7
|
+
|
|
8
|
+
export function verifyTask({ projectDir, harnessDir, taskId, commandArgv, name, timeoutMs, tool, sessionId, dryRun }) {
|
|
9
|
+
if (!taskId) {
|
|
10
|
+
const { state } = loadProjectManifestAndState(projectDir, harnessDir);
|
|
11
|
+
const active = state.active_tasks ?? [];
|
|
12
|
+
if (active.length !== 1) throw new Error("Pass --task TASK-NNNN when there is no single active task.");
|
|
13
|
+
[taskId] = active;
|
|
14
|
+
}
|
|
15
|
+
const task = getTask({ projectDir, harnessDir, taskId });
|
|
16
|
+
taskId = task.id;
|
|
17
|
+
const taskOptions = { projectDir, harnessDir, taskId, tool, sessionId };
|
|
18
|
+
const assertOpen = ({ record }) => {
|
|
19
|
+
if (["completed", "cancelled", "superseded"].includes(record.status)) {
|
|
20
|
+
throw new Error(`${taskId} is ${record.status}. Run evidence capture to check a closed task.`);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
assertOpen(task);
|
|
24
|
+
completeTask({ ...taskOptions, dryRun: true });
|
|
25
|
+
|
|
26
|
+
const evidence = captureEvidence({
|
|
27
|
+
projectDir, harnessDir, taskId, commandArgv, name, timeoutMs, dryRun, linkVerifiedOnly: true,
|
|
28
|
+
});
|
|
29
|
+
const result = { taskId, evidence, checkpoint: null, completion: null };
|
|
30
|
+
if (dryRun) return { ...result, status: "dry_run" };
|
|
31
|
+
if (!evidence.verified) return { ...result, status: "check_failed" };
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
return withProjectLock(projectDir, () => {
|
|
35
|
+
assertOpen(getTask(taskOptions));
|
|
36
|
+
const completionOptions = { ...taskOptions, requireEvidence: true, evidenceRefs: [evidence.id] };
|
|
37
|
+
completeTask({ ...completionOptions, dryRun: true });
|
|
38
|
+
result.checkpoint = createCheckpoint({
|
|
39
|
+
projectDir, harnessDir, evidenceRef: evidence.id,
|
|
40
|
+
summary: `Verification command passed for ${taskId} (${evidence.id}).`,
|
|
41
|
+
});
|
|
42
|
+
result.completion = completeTask(completionOptions);
|
|
43
|
+
return { ...result, status: "completed" };
|
|
44
|
+
});
|
|
45
|
+
} catch (err) {
|
|
46
|
+
return { ...result, status: "completion_blocked", error: redactSecretContent(err.message) };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { getGitRepoInfo } from "./git-utils.mjs";
|
|
5
|
+
import { assertSafeWithinRoot, isSameOrInside, validateSlug } from "./path-safety.mjs";
|
|
6
|
+
import { withProjectLock } from "./project-lock.mjs";
|
|
7
|
+
|
|
8
|
+
function git(projectDir, ...args) {
|
|
9
|
+
return execFileSync("git", ["-C", projectDir, ...args], {
|
|
10
|
+
encoding: "utf8", windowsHide: true, timeout: 30_000, stdio: ["ignore", "pipe", "pipe"],
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function manageWorktrees({ projectDir, workspace = path.dirname(projectDir), action, name, ref = "HEAD" }) {
|
|
15
|
+
const root = fs.realpathSync(path.resolve(workspace));
|
|
16
|
+
const worktreesDir = assertSafeWithinRoot(root, "worktrees");
|
|
17
|
+
if (isSameOrInside(worktreesDir, projectDir)) throw new Error("Worktrees must be outside the project's main checkout.");
|
|
18
|
+
const info = getGitRepoInfo(projectDir);
|
|
19
|
+
if (!info.isRepoRoot || info.unborn) throw new Error("Use an initialized Git project root with at least one commit.");
|
|
20
|
+
|
|
21
|
+
const list = () => {
|
|
22
|
+
if (!fs.existsSync(worktreesDir)) return [];
|
|
23
|
+
const canonicalDir = fs.realpathSync.native(worktreesDir);
|
|
24
|
+
const entries = git(projectDir, "worktree", "list", "--porcelain", "-z").split("\0\0");
|
|
25
|
+
return entries.flatMap((block) => {
|
|
26
|
+
const [entry, head, branch, ...flags] = block.split("\0");
|
|
27
|
+
if (!entry.startsWith("worktree ") || !head?.startsWith("HEAD ") || !branch?.startsWith("branch refs/heads/geloforge/")) return [];
|
|
28
|
+
const target = path.resolve(entry.slice(9));
|
|
29
|
+
try {
|
|
30
|
+
// Git for Windows may report a long path even when the workspace uses a short alias.
|
|
31
|
+
const canonicalParent = fs.realpathSync.native(path.dirname(target));
|
|
32
|
+
if (path.relative(canonicalDir, canonicalParent) !== "" || isSameOrInside(projectDir, target)) return [];
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (error.code === "ENOENT") return [];
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
const name = path.basename(target);
|
|
38
|
+
return [{ path: path.join(worktreesDir, name), name, commit: head.slice(5), branch: branch.slice(18), locked: flags.some((flag) => flag.startsWith("locked")) }];
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
if (action === "list") return { worktrees: list() };
|
|
42
|
+
|
|
43
|
+
validateSlug(name);
|
|
44
|
+
const target = assertSafeWithinRoot(root, `worktrees/${name}`);
|
|
45
|
+
return withProjectLock(projectDir, () => {
|
|
46
|
+
if (action === "add") {
|
|
47
|
+
const commit = git(projectDir, "rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`).trim();
|
|
48
|
+
if (!/^[a-f0-9]{40,64}$/.test(commit) || fs.existsSync(target)) {
|
|
49
|
+
throw new Error("Worktree target must be unused and the ref must resolve to a commit.");
|
|
50
|
+
}
|
|
51
|
+
fs.mkdirSync(worktreesDir, { recursive: true });
|
|
52
|
+
git(projectDir, "worktree", "add", "-b", `geloforge/${name}`, "--", target, commit);
|
|
53
|
+
return { path: target, branch: `geloforge/${name}`, commit };
|
|
54
|
+
}
|
|
55
|
+
const existing = list().find((item) => item.path === target && item.branch === `geloforge/${name}`);
|
|
56
|
+
if (!existing) throw new Error("Managed worktree not found.");
|
|
57
|
+
// Git's default removal can discard ignored files, including local runtime state.
|
|
58
|
+
if (git(target, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching")) {
|
|
59
|
+
throw new Error("Worktree contains uncommitted, untracked, or ignored files. Preserve them before removal.");
|
|
60
|
+
}
|
|
61
|
+
git(projectDir, "worktree", "remove", "--", target);
|
|
62
|
+
return { ...existing, removed: true };
|
|
63
|
+
});
|
|
64
|
+
}
|