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,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
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { AUDIT_CREATOR } from "./autonomous-audit.mjs";
|
|
3
|
+
import { assertSafeWithinRoot, validateSlug } from "./path-safety.mjs";
|
|
4
|
+
import { loadProjectManifestAndState } from "./project-locator.mjs";
|
|
5
|
+
import { withProjectLock } from "./project-lock.mjs";
|
|
6
|
+
import { readRuntimeJson, sha256 } from "./runtime-files.mjs";
|
|
7
|
+
import { draftSkillFromExperience, loadVerifiedSourceBundle, proposeSkillUpdate } from "./skills-lifecycle.mjs";
|
|
8
|
+
import { reportArtifactPath } from "./staging-audit.mjs";
|
|
9
|
+
import { verifyStagingReport } from "./staging-evidence.mjs";
|
|
10
|
+
import { getTask, listTasks } from "./task-manager.mjs";
|
|
11
|
+
|
|
12
|
+
export function learnFromStagingAudits({ projectDir, harnessDir, patternId, skillName, step }) {
|
|
13
|
+
const read = () => {
|
|
14
|
+
const project = loadProjectManifestAndState(projectDir, harnessDir);
|
|
15
|
+
const patterns = new Map();
|
|
16
|
+
const warnings = [];
|
|
17
|
+
for (const { id } of listTasks({ ...project, harnessDir, status: "completed" }).tasks) {
|
|
18
|
+
const { record } = getTask({ ...project, harnessDir, taskId: id });
|
|
19
|
+
if (record.created_by !== AUDIT_CREATOR) continue;
|
|
20
|
+
const artifact = reportArtifactPath(project.projectPaths, id);
|
|
21
|
+
try {
|
|
22
|
+
const source = readRuntimeJson(projectDir, artifact);
|
|
23
|
+
if (!source) continue;
|
|
24
|
+
const report = verifyStagingReport(source, id);
|
|
25
|
+
const { evidenceList } = loadVerifiedSourceBundle({ projectDir, harnessDir, evidenceIds: record.evidence_refs });
|
|
26
|
+
const evidence = evidenceList.find(({ data }) => data.task_id === id && data.verified_by === "geloforge-staging-report" &&
|
|
27
|
+
data.artifacts.some(({ path, sha256: digest }) => path === artifact && digest));
|
|
28
|
+
if (!evidence) throw new Error("Missing evidence binding.");
|
|
29
|
+
for (const { workflowId, node, pattern, reference } of report.findings) {
|
|
30
|
+
// A node definition gives useful context, but it does not show a recurring failure.
|
|
31
|
+
if (!node || reference !== "failed-at") continue;
|
|
32
|
+
const key = sha256(JSON.stringify([workflowId, node, pattern])).slice(0, 16);
|
|
33
|
+
if (!patterns.has(key)) patterns.set(key, { id: key, workflowId, node, pattern, executions: new Map() });
|
|
34
|
+
patterns.get(key).executions.set(report.executionId, {
|
|
35
|
+
executionId: report.executionId, evidenceId: evidence.data.id, revision: report.execution.revision,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
} catch {
|
|
39
|
+
warnings.push(`Excluded ${id} because its report or evidence could not be verified.`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const recurring = [...patterns.values()].filter((pattern) => pattern.executions.size >= 2)
|
|
43
|
+
.map(({ executions, ...pattern }) => ({ ...pattern, executions: [...executions.values()] }));
|
|
44
|
+
return { patterns: recurring, warnings };
|
|
45
|
+
};
|
|
46
|
+
if (!patternId) {
|
|
47
|
+
if (skillName || step) throw new Error("Use --pattern before drafting a skill.");
|
|
48
|
+
return read();
|
|
49
|
+
}
|
|
50
|
+
return withProjectLock(projectDir, () => {
|
|
51
|
+
validateSlug(skillName);
|
|
52
|
+
const result = read();
|
|
53
|
+
const pattern = result.patterns.find(({ id }) => id === patternId);
|
|
54
|
+
if (!pattern) throw new Error("Recurring pattern is missing or its evidence is no longer verified.");
|
|
55
|
+
const evidenceIds = pattern.executions.map(({ evidenceId }) => evidenceId);
|
|
56
|
+
const note = step ?? `For ${pattern.pattern} failures in workflow ${pattern.workflowId}, check whether ${pattern.node} is the failing node and confirm the saved execution and revision before recommending a fix.`;
|
|
57
|
+
const options = { projectDir, harnessDir, evidenceIds, skillName };
|
|
58
|
+
const active = assertSafeWithinRoot(projectDir, `.agents/skills/${skillName}/SKILL.md`);
|
|
59
|
+
const proposal = fs.existsSync(active)
|
|
60
|
+
? proposeSkillUpdate({ ...options, reason: "Review a recurring staging failure pattern.", appendNote: note })
|
|
61
|
+
: draftSkillFromExperience({
|
|
62
|
+
...options, title: "Investigate recurring n8n staging failures",
|
|
63
|
+
description: "Review the saved n8n staging execution and confirm recurring failures against linked evidence.",
|
|
64
|
+
steps: [note], tags: ["n8n", "staging", pattern.pattern], triggers: ["n8n", "audit", pattern.pattern],
|
|
65
|
+
});
|
|
66
|
+
return { pattern, proposalDir: proposal.proposalDir, nextAction: "Review the draft, then use the existing skill signing and promotion commands." };
|
|
67
|
+
});
|
|
68
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/** Headless audit adapters run outside the project and receive a bounded context packet. */
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { execFile } from "node:child_process";
|
|
6
|
+
import { hasSecretContent, isForbiddenSecretPath, isSameOrInside } from "./path-safety.mjs";
|
|
7
|
+
import { readRegularFile, sha256 } from "./runtime-files.mjs";
|
|
8
|
+
|
|
9
|
+
const ENV_KEYS = new Set([
|
|
10
|
+
"PATH", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "SYSTEMROOT", "WINDIR",
|
|
11
|
+
"TMP", "TEMP", "TMPDIR", "LANG", "LC_ALL",
|
|
12
|
+
]);
|
|
13
|
+
|
|
14
|
+
function executableIdentity(executable) {
|
|
15
|
+
const stat = fs.lstatSync(executable);
|
|
16
|
+
if (!stat.isFile()) throw new Error("Audit provider must be a regular executable file.");
|
|
17
|
+
return [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function resolveAuditProvider(spec, projectDir) {
|
|
21
|
+
if (!spec || !["codex", "gemini", "antigravity"].includes(spec.provider) ||
|
|
22
|
+
typeof spec.executable !== "string" || !path.isAbsolute(spec.executable) ||
|
|
23
|
+
hasSecretContent(spec.executable) || isForbiddenSecretPath(spec.executable)) {
|
|
24
|
+
throw new Error("Supply a provider and absolute CLI executable path.");
|
|
25
|
+
}
|
|
26
|
+
const executable = fs.realpathSync(spec.executable);
|
|
27
|
+
if (isSameOrInside(executable, fs.realpathSync(projectDir)) || /\.(cmd|bat|ps1)$/i.test(executable)) {
|
|
28
|
+
throw new Error("Use a native provider executable or Node.js entry point outside the project.");
|
|
29
|
+
}
|
|
30
|
+
const identity = executableIdentity(executable);
|
|
31
|
+
const bytes = readRegularFile(executable, 384 * 1024 * 1024);
|
|
32
|
+
if (!bytes || executableIdentity(executable) !== identity) {
|
|
33
|
+
throw new Error("Configured provider executable is unavailable or changed during authorization.");
|
|
34
|
+
}
|
|
35
|
+
const runner = { provider: spec.provider, executable, digest: sha256(bytes) };
|
|
36
|
+
return { runner, identity };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function startAuditProvider({ runner: { provider, executable }, identity }, prompt, { timeoutMs, signal } = {}) {
|
|
40
|
+
if (signal?.aborted) throw new Error("Audit worker is stopping.");
|
|
41
|
+
if (executableIdentity(executable) !== identity) throw new Error("Audit provider executable changed. Restart with the approved executable.");
|
|
42
|
+
if (hasSecretContent(prompt)) throw new Error("Audit inputs contain credential-like content.");
|
|
43
|
+
// Prompt text goes in a private file. No project directory or staging credentials are given to the CLI.
|
|
44
|
+
const cwd = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), "geloforge-audit-"));
|
|
45
|
+
const finalPath = path.join(cwd, "response.json");
|
|
46
|
+
let child;
|
|
47
|
+
const request = "Read audit-input.txt in the current directory. Follow its reporting format and return only the requested JSON. Use local file reads only.";
|
|
48
|
+
const args = {
|
|
49
|
+
codex: ["--ask-for-approval", "never", "exec", "--sandbox", "read-only", "--skip-git-repo-check",
|
|
50
|
+
"--ephemeral", "--ignore-user-config", "--output-last-message", finalPath, request],
|
|
51
|
+
gemini: ["--approval-mode=plan", "--output-format=json", "--prompt", request],
|
|
52
|
+
antigravity: ["--mode=plan", "--sandbox", "--output-format=json", "--print", request],
|
|
53
|
+
}[provider];
|
|
54
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => ENV_KEYS.has(key.toUpperCase())));
|
|
55
|
+
const stop = () => child?.kill("SIGKILL");
|
|
56
|
+
const promise = new Promise((resolve, reject) => {
|
|
57
|
+
try {
|
|
58
|
+
fs.writeFileSync(path.join(cwd, "audit-input.txt"), prompt, { mode: 0o600, flag: "wx" });
|
|
59
|
+
const isNodeEntry = /\.[cm]?js$/i.test(executable);
|
|
60
|
+
child = execFile(isNodeEntry ? process.execPath : executable, isNodeEntry ? [executable, ...args] : args, {
|
|
61
|
+
cwd, env, timeout: timeoutMs, maxBuffer: 256 * 1024, killSignal: "SIGKILL", windowsHide: true,
|
|
62
|
+
}, (err, stdout) => {
|
|
63
|
+
try {
|
|
64
|
+
if (err) {
|
|
65
|
+
throw new Error(err.killed ? "Audit provider stopped or exceeded its timeout." :
|
|
66
|
+
"Audit provider failed to start or returned an unsuccessful response.");
|
|
67
|
+
}
|
|
68
|
+
const text = provider === "codex" ? readRegularFile(finalPath)?.toString("utf8") : stdout;
|
|
69
|
+
const envelope = JSON.parse(text);
|
|
70
|
+
if (envelope?.error || (provider === "antigravity" && envelope?.status !== "SUCCESS")) {
|
|
71
|
+
throw new Error("Unsuccessful response envelope.");
|
|
72
|
+
}
|
|
73
|
+
const response = provider === "codex" ? envelope : JSON.parse(envelope.response);
|
|
74
|
+
resolve(response);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
reject(err ? error : new Error("Audit provider returned invalid JSON."));
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
80
|
+
} catch (err) {
|
|
81
|
+
reject(err);
|
|
82
|
+
}
|
|
83
|
+
}).finally(() => {
|
|
84
|
+
signal?.removeEventListener("abort", stop);
|
|
85
|
+
fs.rmSync(cwd, { recursive: true, force: true, maxRetries: 2 });
|
|
86
|
+
});
|
|
87
|
+
return { pid: child?.pid, promise, stop };
|
|
88
|
+
}
|