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,572 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Safe filesystem staging, atomic directory swap, content-addressed snapshot history,
|
|
3
|
+
* and rollback gate verification extracted from core/skills-lifecycle.mjs.
|
|
4
|
+
* Zero external dependencies, zero network calls.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import crypto from "node:crypto";
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { parseYaml, serializeYaml } from "./yaml-subset.mjs";
|
|
12
|
+
import {
|
|
13
|
+
WINDOWS_RESERVED_NAME_REGEX,
|
|
14
|
+
assertSafeWithinRoot,
|
|
15
|
+
atomicWriteFile,
|
|
16
|
+
deriveSlug,
|
|
17
|
+
hasSecretContent,
|
|
18
|
+
isForbiddenSecretPath,
|
|
19
|
+
isSameOrInside,
|
|
20
|
+
} from "./path-safety.mjs";
|
|
21
|
+
import { loadProjectManifestAndState } from "./project-locator.mjs";
|
|
22
|
+
import {
|
|
23
|
+
MAX_SKILL_BYTES,
|
|
24
|
+
MAX_SKILL_TEXT_RESOURCE_BYTES,
|
|
25
|
+
SKILL_NAME_REGEX,
|
|
26
|
+
computeSkillPackageDigest,
|
|
27
|
+
inspectSkillPackage,
|
|
28
|
+
isOversizedTextFile,
|
|
29
|
+
} from "./skills.mjs";
|
|
30
|
+
import { lintSkill } from "./skills-lint.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
|
+
export const SHA256_PREFIX_REGEX = /^sha256:[a-f0-9]{64}$/;
|
|
37
|
+
export const REVISION_REGEX = /^rev-\d{4}$/;
|
|
38
|
+
|
|
39
|
+
export function sha256Hex(input) {
|
|
40
|
+
return crypto.createHash("sha256").update(input).digest("hex");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function sha256Tag(input) {
|
|
44
|
+
return `sha256:${sha256Hex(input)}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function assertSafeDirNonSymlink(absDir, label) {
|
|
48
|
+
if (!fs.existsSync(absDir)) return false;
|
|
49
|
+
const st = fs.lstatSync(absDir);
|
|
50
|
+
if (st.isSymbolicLink() || !st.isDirectory()) {
|
|
51
|
+
throw new Error(`Refusing symbolic link or non-directory ${label}: ${absDir}`);
|
|
52
|
+
}
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function assertSafeAncestorChain(absTarget, stopAtRoot, label) {
|
|
57
|
+
const resolvedStop = path.resolve(stopAtRoot);
|
|
58
|
+
let cursor = path.dirname(path.resolve(absTarget));
|
|
59
|
+
while (cursor && isSameOrInside(cursor, resolvedStop)) {
|
|
60
|
+
if (fs.existsSync(cursor)) {
|
|
61
|
+
const st = fs.lstatSync(cursor);
|
|
62
|
+
if (st.isSymbolicLink()) {
|
|
63
|
+
throw new Error(`Refusing symbolic link/junction ancestor for ${label}: ${cursor}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (cursor === resolvedStop) break;
|
|
67
|
+
const parent = path.dirname(cursor);
|
|
68
|
+
if (parent === cursor) break;
|
|
69
|
+
cursor = parent;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function readSafeYamlWithinProject(projectDir, relPath) {
|
|
74
|
+
if (isForbiddenSecretPath(relPath)) {
|
|
75
|
+
throw new Error(`Forbidden secret path: ${relPath}`);
|
|
76
|
+
}
|
|
77
|
+
const full = assertSafeWithinRoot(projectDir, relPath);
|
|
78
|
+
if (!fs.existsSync(full)) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
const st = fs.lstatSync(full);
|
|
82
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
83
|
+
throw new Error(`Refusing symbolic link or non-regular file: ${relPath}`);
|
|
84
|
+
}
|
|
85
|
+
if (st.size > MAX_SKILL_BYTES) {
|
|
86
|
+
throw new Error(`File exceeds maximum safe record size (${MAX_SKILL_BYTES} bytes): ${relPath}`);
|
|
87
|
+
}
|
|
88
|
+
const raw = fs.readFileSync(full, "utf8");
|
|
89
|
+
if (hasSecretContent(raw)) {
|
|
90
|
+
throw new Error(`Blocked file containing credential-like pattern: ${relPath}`);
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
relPath: relPath.replace(/\\/g, "/"),
|
|
94
|
+
fullPath: full,
|
|
95
|
+
raw,
|
|
96
|
+
sha256: sha256Tag(raw),
|
|
97
|
+
data: parseYaml(raw, relPath),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function copyTreeSafe(srcDir, destDir, rootSrc = srcDir) {
|
|
102
|
+
const srcResolved = path.resolve(srcDir);
|
|
103
|
+
const rootResolved = path.resolve(rootSrc);
|
|
104
|
+
const srcStat = fs.lstatSync(srcResolved);
|
|
105
|
+
if (srcStat.isSymbolicLink() || !srcStat.isDirectory()) {
|
|
106
|
+
throw new Error(`Refusing symbolic link or non-directory source tree: ${srcDir}`);
|
|
107
|
+
}
|
|
108
|
+
fs.mkdirSync(destDir, { recursive: true });
|
|
109
|
+
const entries = fs.readdirSync(srcResolved, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
110
|
+
for (const entry of entries) {
|
|
111
|
+
if (entry.name === ".git" || entry.name === "node_modules") continue;
|
|
112
|
+
const srcEntry = path.join(srcResolved, entry.name);
|
|
113
|
+
const destEntry = path.join(destDir, entry.name);
|
|
114
|
+
const relFromRoot = path.relative(rootResolved, srcEntry).replace(/\\/g, "/");
|
|
115
|
+
const st = fs.lstatSync(srcEntry);
|
|
116
|
+
if (st.isSymbolicLink()) {
|
|
117
|
+
throw new Error(`Blocked symbolic link/junction during copy: ${srcEntry}`);
|
|
118
|
+
}
|
|
119
|
+
if (isForbiddenSecretPath(relFromRoot)) {
|
|
120
|
+
throw new Error(`Blocked forbidden secret path during copy: ${relFromRoot}`);
|
|
121
|
+
}
|
|
122
|
+
if (st.isDirectory()) {
|
|
123
|
+
copyTreeSafe(srcEntry, destEntry, rootResolved);
|
|
124
|
+
} else if (st.isFile()) {
|
|
125
|
+
if (st.size > MAX_SKILL_TEXT_RESOURCE_BYTES && isOversizedTextFile(srcEntry)) {
|
|
126
|
+
throw new Error(
|
|
127
|
+
`Text resource exceeds maximum safe scannable size (${MAX_SKILL_TEXT_RESOURCE_BYTES} bytes) during copy: ${relFromRoot}`
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
const buf = fs.readFileSync(srcEntry);
|
|
131
|
+
if (!buf.includes(0) && hasSecretContent(buf.toString("utf8"))) {
|
|
132
|
+
throw new Error(`Blocked secret literal in file during copy: ${entry.name}`);
|
|
133
|
+
}
|
|
134
|
+
fs.writeFileSync(destEntry, buf, { flag: "wx" });
|
|
135
|
+
} else {
|
|
136
|
+
throw new Error(`Blocked unsupported special file during copy: ${srcEntry}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function removeDirSafe(absDir) {
|
|
142
|
+
if (fs.existsSync(absDir)) {
|
|
143
|
+
fs.rmSync(absDir, { recursive: true, force: true, maxRetries: 4, retryDelay: 50 });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function renameSyncRetry(fromPath, toPath) {
|
|
148
|
+
let lastErr;
|
|
149
|
+
for (let i = 0; i < 4; i += 1) {
|
|
150
|
+
try {
|
|
151
|
+
fs.renameSync(fromPath, toPath);
|
|
152
|
+
return;
|
|
153
|
+
} catch (err) {
|
|
154
|
+
lastErr = err;
|
|
155
|
+
if (err.code !== "EPERM" && err.code !== "EBUSY") {
|
|
156
|
+
throw err;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
throw lastErr;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Stages an atomic directory replacement over `targetDir` with explicit commit/rollback handles.
|
|
165
|
+
* Uses lstatSync (not existsSync) so broken symlinks at `targetDir` fail closed immediately.
|
|
166
|
+
*/
|
|
167
|
+
export function stageAtomicSwap(stageDir, targetDir) {
|
|
168
|
+
const parent = path.dirname(targetDir);
|
|
169
|
+
fs.mkdirSync(parent, { recursive: true });
|
|
170
|
+
const backupDir = path.join(parent, `.geloforge-backup-${crypto.randomBytes(6).toString("hex")}`);
|
|
171
|
+
let hadExisting = false;
|
|
172
|
+
let targetStat = null;
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
targetStat = fs.lstatSync(targetDir);
|
|
176
|
+
hadExisting = true;
|
|
177
|
+
} catch (err) {
|
|
178
|
+
if (err.code !== "ENOENT") {
|
|
179
|
+
throw err;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (targetStat && (targetStat.isSymbolicLink() || !targetStat.isDirectory())) {
|
|
184
|
+
throw new Error(`Refusing symbolic link or non-directory at active destination: ${targetDir}`);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
try {
|
|
188
|
+
if (hadExisting) {
|
|
189
|
+
renameSyncRetry(targetDir, backupDir);
|
|
190
|
+
}
|
|
191
|
+
renameSyncRetry(stageDir, targetDir);
|
|
192
|
+
} catch (err) {
|
|
193
|
+
if (hadExisting && !fs.existsSync(targetDir) && fs.existsSync(backupDir)) {
|
|
194
|
+
try {
|
|
195
|
+
renameSyncRetry(backupDir, targetDir);
|
|
196
|
+
} catch {
|
|
197
|
+
// Best-effort restore
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
removeDirSafe(stageDir);
|
|
201
|
+
throw err;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
commit() {
|
|
206
|
+
if (hadExisting) {
|
|
207
|
+
removeDirSafe(backupDir);
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
rollback() {
|
|
211
|
+
try {
|
|
212
|
+
if (fs.existsSync(targetDir)) {
|
|
213
|
+
removeDirSafe(targetDir);
|
|
214
|
+
}
|
|
215
|
+
if (hadExisting && fs.existsSync(backupDir)) {
|
|
216
|
+
renameSyncRetry(backupDir, targetDir);
|
|
217
|
+
}
|
|
218
|
+
} catch {
|
|
219
|
+
// Best-effort restore
|
|
220
|
+
}
|
|
221
|
+
removeDirSafe(stageDir);
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function validateSkillSlugName(rawName, fallbackTitle = null) {
|
|
227
|
+
const candidate = rawName ? String(rawName).trim() : deriveSlug(fallbackTitle || "");
|
|
228
|
+
if (!candidate || !SKILL_NAME_REGEX.test(candidate) || candidate.includes("--")) {
|
|
229
|
+
throw new Error(
|
|
230
|
+
`Invalid skill name "${candidate}". Use lowercase kebab-case ASCII letters, digits, and single hyphens (e.g. "verify-webhook-tests").`
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
if (WINDOWS_RESERVED_NAME_REGEX.test(candidate)) {
|
|
234
|
+
throw new Error(`Skill name "${candidate}" conflicts with a reserved Windows device name.`);
|
|
235
|
+
}
|
|
236
|
+
return candidate;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export function validateAndLintSkillStaging({ stageDir, skillName, displayRoot }) {
|
|
240
|
+
const pkg = inspectSkillPackage({
|
|
241
|
+
skillDir: stageDir,
|
|
242
|
+
folderName: skillName,
|
|
243
|
+
source: "quarantined_draft",
|
|
244
|
+
trustTier: "quarantined_draft",
|
|
245
|
+
displayRoot,
|
|
246
|
+
});
|
|
247
|
+
const lint = lintSkill(pkg);
|
|
248
|
+
if (!pkg.valid || lint.counts.critical > 0 || lint.counts.error > 0 || lint.counts.high > 0 || lint.counts.warning > 0) {
|
|
249
|
+
const details = lint.findings.map((f) => `[${f.severity} ${f.ruleId}] ${f.message}`).join("; ");
|
|
250
|
+
throw new Error(`Candidate skill "${skillName}" failed strict validation/security lint: ${details}`);
|
|
251
|
+
}
|
|
252
|
+
const digestInfo = computeSkillPackageDigest(stageDir);
|
|
253
|
+
return { pkg, lint, digestInfo };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function validateSkillHistoryLedger(data, skillName, histRel) {
|
|
257
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
258
|
+
throw new Error(`${histRel}: history ledger must be a YAML object.`);
|
|
259
|
+
}
|
|
260
|
+
if (data.skill_name !== skillName) {
|
|
261
|
+
throw new Error(`${histRel}: history skill_name "${data.skill_name}" mismatches "${skillName}".`);
|
|
262
|
+
}
|
|
263
|
+
if (!Array.isArray(data.revisions)) {
|
|
264
|
+
throw new Error(`${histRel}: history ledger missing "revisions" list.`);
|
|
265
|
+
}
|
|
266
|
+
const seenRevs = new Set();
|
|
267
|
+
for (const entry of data.revisions) {
|
|
268
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
269
|
+
throw new Error(`${histRel}: invalid revision entry.`);
|
|
270
|
+
}
|
|
271
|
+
if (typeof entry.revision !== "string" || !REVISION_REGEX.test(entry.revision)) {
|
|
272
|
+
throw new Error(`${histRel}: invalid revision ID "${entry.revision}".`);
|
|
273
|
+
}
|
|
274
|
+
if (seenRevs.has(entry.revision)) {
|
|
275
|
+
throw new Error(`${histRel}: duplicate revision ID "${entry.revision}" in history ledger.`);
|
|
276
|
+
}
|
|
277
|
+
seenRevs.add(entry.revision);
|
|
278
|
+
if (typeof entry.package_sha256 !== "string" || !SHA256_PREFIX_REGEX.test(entry.package_sha256)) {
|
|
279
|
+
throw new Error(`${histRel}: invalid package_sha256 for ${entry.revision}.`);
|
|
280
|
+
}
|
|
281
|
+
const expectedSnapRel = `.geloforge/skill-history/${skillName}/snapshots/${entry.revision}`;
|
|
282
|
+
const normSnap =
|
|
283
|
+
typeof entry.snapshot_path === "string"
|
|
284
|
+
? entry.snapshot_path.replace(/\\/g, "/").replace(/^\.\//, "")
|
|
285
|
+
: "";
|
|
286
|
+
if (normSnap !== expectedSnapRel) {
|
|
287
|
+
throw new Error(
|
|
288
|
+
`${histRel}: forged or out-of-confinement snapshot_path "${entry.snapshot_path}" for ${entry.revision} (expected "${expectedSnapRel}").`
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export function readSkillHistoryData(projectDir, skillName) {
|
|
295
|
+
const histRel = `.geloforge/skill-history/${skillName}/history.yaml`;
|
|
296
|
+
const loaded = readSafeYamlWithinProject(projectDir, histRel);
|
|
297
|
+
if (!loaded || !loaded.data) {
|
|
298
|
+
return { histRel, exists: false, data: { schema_version: "1.0", skill_name: skillName, revisions: [] } };
|
|
299
|
+
}
|
|
300
|
+
validateSkillHistoryLedger(loaded.data, skillName, histRel);
|
|
301
|
+
return { histRel, exists: true, data: loaded.data };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function findConsumedApprovalInHistory(projectDir, approvalId) {
|
|
305
|
+
const histRootRel = ".geloforge/skill-history";
|
|
306
|
+
const histRootAbs = assertSafeWithinRoot(projectDir, histRootRel);
|
|
307
|
+
if (!assertSafeDirNonSymlink(histRootAbs, histRootRel)) {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
const entries = fs.readdirSync(histRootAbs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
311
|
+
for (const entry of entries) {
|
|
312
|
+
const childAbs = path.join(histRootAbs, entry.name);
|
|
313
|
+
const st = fs.lstatSync(childAbs);
|
|
314
|
+
if (st.isSymbolicLink()) {
|
|
315
|
+
throw new Error(`Refusing symbolic link/junction inside ${histRootRel}/${entry.name}`);
|
|
316
|
+
}
|
|
317
|
+
if (!st.isDirectory()) continue;
|
|
318
|
+
const histRel = `${histRootRel}/${entry.name}/history.yaml`;
|
|
319
|
+
const histAbs = assertSafeWithinRoot(projectDir, histRel);
|
|
320
|
+
if (!fs.existsSync(histAbs)) continue;
|
|
321
|
+
const loaded = readSafeYamlWithinProject(projectDir, histRel);
|
|
322
|
+
const revisions = Array.isArray(loaded?.data?.revisions) ? loaded.data.revisions : [];
|
|
323
|
+
for (const rev of revisions) {
|
|
324
|
+
if (typeof rev?.approval_ref === "string" && rev.approval_ref.toUpperCase() === approvalId) {
|
|
325
|
+
return { skillName: entry.name, revision: rev.revision, histRel };
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function inspectRollbackSnapshotForGate(projectDir, skillName, targetRevision) {
|
|
333
|
+
if (!REVISION_REGEX.test(String(targetRevision || "").trim())) {
|
|
334
|
+
throw new Error(`Invalid target revision "${targetRevision}". Expected rev-NNNN (e.g. rev-0001).`);
|
|
335
|
+
}
|
|
336
|
+
const histInfo = readSkillHistoryData(projectDir, skillName);
|
|
337
|
+
if (!histInfo.exists || !Array.isArray(histInfo.data.revisions)) {
|
|
338
|
+
throw new Error(`No history ledger found for skill "${skillName}" at ${histInfo.histRel}.`);
|
|
339
|
+
}
|
|
340
|
+
const entry = histInfo.data.revisions.find((r) => r.revision === targetRevision);
|
|
341
|
+
if (!entry) {
|
|
342
|
+
throw new Error(`Revision "${targetRevision}" not found in history for skill "${skillName}".`);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const snapshotRel = entry.snapshot_path;
|
|
346
|
+
const snapshotDir = assertSafeWithinRoot(projectDir, snapshotRel);
|
|
347
|
+
if (!fs.existsSync(snapshotDir)) {
|
|
348
|
+
throw new Error(`Snapshot directory missing on disk for ${targetRevision}: ${snapshotRel}`);
|
|
349
|
+
}
|
|
350
|
+
const verifiedSnap = validateAndLintSkillStaging({
|
|
351
|
+
stageDir: snapshotDir,
|
|
352
|
+
skillName,
|
|
353
|
+
displayRoot: `.geloforge/skill-history/${skillName}/snapshots`,
|
|
354
|
+
});
|
|
355
|
+
if (verifiedSnap.digestInfo.digest !== entry.package_sha256) {
|
|
356
|
+
throw new Error(
|
|
357
|
+
`Snapshot integrity failure for ${targetRevision} (disk=${verifiedSnap.digestInfo.digest} vs ledger=${entry.package_sha256}). Refusing rollback.`
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const activeRel = `.agents/skills/${skillName}`;
|
|
362
|
+
const activeDir = assertSafeWithinRoot(projectDir, activeRel);
|
|
363
|
+
if (!fs.existsSync(activeDir)) {
|
|
364
|
+
throw new Error(`Active skill "${skillName}" is not installed at ${activeRel}.`);
|
|
365
|
+
}
|
|
366
|
+
const currentBaseSha = computeSkillPackageDigest(activeDir).digest;
|
|
367
|
+
if (currentBaseSha === verifiedSnap.digestInfo.digest) {
|
|
368
|
+
throw new Error(`Active skill "${skillName}" already matches ${targetRevision} (${currentBaseSha}).`);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
return {
|
|
372
|
+
histInfo,
|
|
373
|
+
entry,
|
|
374
|
+
snapshotRel,
|
|
375
|
+
snapshotDir,
|
|
376
|
+
targetDigest: verifiedSnap.digestInfo.digest,
|
|
377
|
+
currentBaseSha,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export function stageSnapshotAtomic(srcDir, targetSnapAbs, expectedDigest, revLabel) {
|
|
382
|
+
let exists = false;
|
|
383
|
+
try {
|
|
384
|
+
fs.lstatSync(targetSnapAbs);
|
|
385
|
+
exists = true;
|
|
386
|
+
} catch (err) {
|
|
387
|
+
if (err.code !== "ENOENT") {
|
|
388
|
+
throw err;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (exists) {
|
|
392
|
+
throw new Error(`Snapshot target already exists (refusing overwrite): ${targetSnapAbs}`);
|
|
393
|
+
}
|
|
394
|
+
const snapParent = path.dirname(targetSnapAbs);
|
|
395
|
+
fs.mkdirSync(snapParent, { recursive: true });
|
|
396
|
+
const tempSnap = path.join(snapParent, `.geloforge-snap-tmp-${crypto.randomBytes(6).toString("hex")}`);
|
|
397
|
+
try {
|
|
398
|
+
copyTreeSafe(srcDir, tempSnap);
|
|
399
|
+
const writtenDigest = computeSkillPackageDigest(tempSnap).digest;
|
|
400
|
+
if (writtenDigest !== expectedDigest) {
|
|
401
|
+
throw new Error(`Snapshot verification failed after copy for ${revLabel}.`);
|
|
402
|
+
}
|
|
403
|
+
renameSyncRetry(tempSnap, targetSnapAbs);
|
|
404
|
+
} catch (err) {
|
|
405
|
+
removeDirSafe(tempSnap);
|
|
406
|
+
throw err;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export function recordHistoryRevision({
|
|
411
|
+
projectDir,
|
|
412
|
+
skillName,
|
|
413
|
+
action,
|
|
414
|
+
sourceDirToSnapshot,
|
|
415
|
+
packageSha256,
|
|
416
|
+
baseSha256,
|
|
417
|
+
approvalId,
|
|
418
|
+
authorizationTier,
|
|
419
|
+
approverId,
|
|
420
|
+
evidenceDigests,
|
|
421
|
+
createdAt,
|
|
422
|
+
restoredFromRevision = null,
|
|
423
|
+
reason = null,
|
|
424
|
+
}) {
|
|
425
|
+
const histBaseRel = `.geloforge/skill-history/${skillName}`;
|
|
426
|
+
const histBaseAbs = assertSafeWithinRoot(projectDir, histBaseRel);
|
|
427
|
+
assertSafeAncestorChain(histBaseAbs, projectDir, histBaseRel);
|
|
428
|
+
assertSafeDirNonSymlink(histBaseAbs, histBaseRel);
|
|
429
|
+
|
|
430
|
+
const histInfo = readSkillHistoryData(projectDir, skillName);
|
|
431
|
+
const histAbs = assertSafeWithinRoot(projectDir, histInfo.histRel);
|
|
432
|
+
const previousHistoryRaw = histInfo.exists ? fs.readFileSync(histAbs, "utf8") : null;
|
|
433
|
+
const revisions = [...(histInfo.data.revisions || [])];
|
|
434
|
+
const createdSnapshotDirs = [];
|
|
435
|
+
|
|
436
|
+
try {
|
|
437
|
+
// If upgrading a manually added active skill with no history yet, capture rev-0000 baseline first
|
|
438
|
+
if (revisions.length === 0 && action === "promote_update" && baseSha256) {
|
|
439
|
+
const activeAbs = assertSafeWithinRoot(projectDir, `.agents/skills/${skillName}`);
|
|
440
|
+
const snap0Rel = `${histBaseRel}/snapshots/rev-0000`;
|
|
441
|
+
const snap0Abs = assertSafeWithinRoot(projectDir, snap0Rel);
|
|
442
|
+
stageSnapshotAtomic(activeAbs, snap0Abs, baseSha256, "rev-0000");
|
|
443
|
+
createdSnapshotDirs.push(snap0Abs);
|
|
444
|
+
revisions.push({
|
|
445
|
+
revision: "rev-0000",
|
|
446
|
+
action: "baseline_snapshot",
|
|
447
|
+
package_sha256: baseSha256,
|
|
448
|
+
base_sha256: null,
|
|
449
|
+
snapshot_path: snap0Rel,
|
|
450
|
+
approval_ref: null,
|
|
451
|
+
authorization_tier: "preexisting_baseline",
|
|
452
|
+
approver_id: null,
|
|
453
|
+
evidence_digests: [],
|
|
454
|
+
restored_from_revision: null,
|
|
455
|
+
reason: "Captured preexisting .agents/skills baseline before first adaptive update.",
|
|
456
|
+
recorded_at: createdAt,
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const nextNum =
|
|
461
|
+
revisions.reduce((max, r) => {
|
|
462
|
+
const m = /^rev-(\d{4})$/.exec(r.revision || "");
|
|
463
|
+
return m ? Math.max(max, Number.parseInt(m[1], 10)) : max;
|
|
464
|
+
}, 0) + 1;
|
|
465
|
+
const revId = `rev-${String(nextNum).padStart(4, "0")}`;
|
|
466
|
+
const snapRel = `${histBaseRel}/snapshots/${revId}`;
|
|
467
|
+
const snapAbs = assertSafeWithinRoot(projectDir, snapRel);
|
|
468
|
+
|
|
469
|
+
stageSnapshotAtomic(sourceDirToSnapshot, snapAbs, packageSha256, revId);
|
|
470
|
+
createdSnapshotDirs.push(snapAbs);
|
|
471
|
+
|
|
472
|
+
const entry = {
|
|
473
|
+
revision: revId,
|
|
474
|
+
action,
|
|
475
|
+
package_sha256: packageSha256,
|
|
476
|
+
base_sha256: baseSha256 || null,
|
|
477
|
+
snapshot_path: snapRel,
|
|
478
|
+
approval_ref: approvalId || null,
|
|
479
|
+
authorization_tier: authorizationTier,
|
|
480
|
+
approver_id: approverId || null,
|
|
481
|
+
evidence_digests: [...(evidenceDigests || [])],
|
|
482
|
+
restored_from_revision: restoredFromRevision,
|
|
483
|
+
reason,
|
|
484
|
+
recorded_at: createdAt,
|
|
485
|
+
};
|
|
486
|
+
revisions.push(entry);
|
|
487
|
+
|
|
488
|
+
const ledger = {
|
|
489
|
+
schema_version: "1.0",
|
|
490
|
+
skill_name: skillName,
|
|
491
|
+
revisions,
|
|
492
|
+
};
|
|
493
|
+
atomicWriteFile(histAbs, serializeYaml(ledger, { headerComment: "Append-only GeloForge skill revision ledger" }), {
|
|
494
|
+
allowOverwrite: true,
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
return {
|
|
498
|
+
revision: revId,
|
|
499
|
+
snapshotRel: snapRel,
|
|
500
|
+
snapshotAbs: snapAbs,
|
|
501
|
+
historyRel: histInfo.histRel,
|
|
502
|
+
historyAbs: histAbs,
|
|
503
|
+
previousHistoryRaw,
|
|
504
|
+
createdSnapshotDirs,
|
|
505
|
+
entry,
|
|
506
|
+
};
|
|
507
|
+
} catch (err) {
|
|
508
|
+
try {
|
|
509
|
+
if (previousHistoryRaw !== null) {
|
|
510
|
+
atomicWriteFile(histAbs, previousHistoryRaw, { allowOverwrite: true });
|
|
511
|
+
} else if (fs.existsSync(histAbs)) {
|
|
512
|
+
fs.rmSync(histAbs, { force: true });
|
|
513
|
+
}
|
|
514
|
+
} catch {
|
|
515
|
+
// Best-effort restore
|
|
516
|
+
}
|
|
517
|
+
for (const sDir of createdSnapshotDirs) {
|
|
518
|
+
removeDirSafe(sDir);
|
|
519
|
+
}
|
|
520
|
+
throw err;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Inspects append-only revision history, snapshot integrity, and active skill drift.
|
|
526
|
+
*/
|
|
527
|
+
export function getSkillHistory({ projectDir, skillName, harnessDir = DEFAULT_HARNESS_DIR }) {
|
|
528
|
+
const loaded = loadProjectManifestAndState(projectDir, harnessDir);
|
|
529
|
+
const cleanName = validateSkillSlugName(skillName);
|
|
530
|
+
const histInfo = readSkillHistoryData(loaded.projectDir, cleanName);
|
|
531
|
+
|
|
532
|
+
const activeRel = `.agents/skills/${cleanName}`;
|
|
533
|
+
const activeAbs = assertSafeWithinRoot(loaded.projectDir, activeRel);
|
|
534
|
+
const activeExists = fs.existsSync(activeAbs);
|
|
535
|
+
const currentSha256 = activeExists ? computeSkillPackageDigest(activeAbs).digest : null;
|
|
536
|
+
|
|
537
|
+
const revisions = (histInfo.data.revisions || []).map((entry) => {
|
|
538
|
+
let snapshotValid = false;
|
|
539
|
+
let snapshotError = null;
|
|
540
|
+
try {
|
|
541
|
+
const snapAbs = assertSafeWithinRoot(loaded.projectDir, entry.snapshot_path);
|
|
542
|
+
if (fs.existsSync(snapAbs)) {
|
|
543
|
+
const snapSha = computeSkillPackageDigest(snapAbs).digest;
|
|
544
|
+
snapshotValid = snapSha === entry.package_sha256;
|
|
545
|
+
if (!snapshotValid) snapshotError = `Digest mismatch (${snapSha} vs ${entry.package_sha256})`;
|
|
546
|
+
} else {
|
|
547
|
+
snapshotError = "Snapshot missing";
|
|
548
|
+
}
|
|
549
|
+
} catch (err) {
|
|
550
|
+
snapshotError = err.message;
|
|
551
|
+
}
|
|
552
|
+
return {
|
|
553
|
+
...entry,
|
|
554
|
+
snapshotValid,
|
|
555
|
+
snapshotError,
|
|
556
|
+
};
|
|
557
|
+
});
|
|
558
|
+
|
|
559
|
+
const latest = revisions.length > 0 ? revisions[revisions.length - 1] : null;
|
|
560
|
+
const driftDetected = Boolean(activeExists && latest && currentSha256 !== latest.package_sha256);
|
|
561
|
+
|
|
562
|
+
return {
|
|
563
|
+
skillName: cleanName,
|
|
564
|
+
historyExists: histInfo.exists,
|
|
565
|
+
historyRel: histInfo.histRel,
|
|
566
|
+
activeExists,
|
|
567
|
+
currentSha256,
|
|
568
|
+
latestRecordedSha256: latest ? latest.package_sha256 : null,
|
|
569
|
+
driftDetected,
|
|
570
|
+
revisions,
|
|
571
|
+
};
|
|
572
|
+
}
|