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,2225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Evidence-backed adaptive skills lifecycle for GeloForge (v0.4 PR 3):
|
|
3
|
+
* Verified Experience -> Quarantined Draft/Update Proposal -> Evaluation/Lint
|
|
4
|
+
* -> Genuine Human Authorization (Ed25519 / PR Branch / Explicit TTY)
|
|
5
|
+
* -> Atomic Promotion -> Content-Addressed History & Authorized Rollback
|
|
6
|
+
*
|
|
7
|
+
* Security invariants:
|
|
8
|
+
* - Zero third-party dependencies, zero network calls, zero automatic script execution.
|
|
9
|
+
* - Never treats self-reported `--approved-by` flags as human authorization.
|
|
10
|
+
* - Fails closed on missing/unverified/tampered evidence, contradictions, symlinks,
|
|
11
|
+
* secrets, digest mismatches, stale bases, or unauthorized promotion/rollback.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import crypto from "node:crypto";
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { execFileSync } from "node:child_process";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
import { parseYaml, serializeYaml } from "./yaml-subset.mjs";
|
|
20
|
+
import { validateAgainstSchema } from "./json-schema-lite.mjs";
|
|
21
|
+
import {
|
|
22
|
+
CONTROL_CHAR_REGEX,
|
|
23
|
+
WINDOWS_RESERVED_NAME_REGEX,
|
|
24
|
+
assertSafeWithinRoot,
|
|
25
|
+
atomicWriteFile,
|
|
26
|
+
deriveSlug,
|
|
27
|
+
hasSecretContent,
|
|
28
|
+
isForbiddenSecretPath,
|
|
29
|
+
isSameOrInside,
|
|
30
|
+
redactSecretContent,
|
|
31
|
+
validateScalarText,
|
|
32
|
+
walkNonSymlinkFiles,
|
|
33
|
+
} from "./path-safety.mjs";
|
|
34
|
+
import { getGitRepoInfo, getGitStatusScoped } from "./git-utils.mjs";
|
|
35
|
+
import { loadProjectManifestAndState, scanAndAllocateRecordId } from "./project-locator.mjs";
|
|
36
|
+
import { validateCreatedAt } from "./template-utils.mjs";
|
|
37
|
+
import {
|
|
38
|
+
MAX_SKILL_BYTES,
|
|
39
|
+
computeSkillPackageDigest,
|
|
40
|
+
inspectSkillPackage,
|
|
41
|
+
parseSkillMarkdown,
|
|
42
|
+
} from "./skills.mjs";
|
|
43
|
+
import {
|
|
44
|
+
assertSafeAncestorChain,
|
|
45
|
+
assertSafeDirNonSymlink,
|
|
46
|
+
copyTreeSafe,
|
|
47
|
+
findConsumedApprovalInHistory,
|
|
48
|
+
getSkillHistory,
|
|
49
|
+
inspectRollbackSnapshotForGate,
|
|
50
|
+
readSafeYamlWithinProject,
|
|
51
|
+
recordHistoryRevision,
|
|
52
|
+
removeDirSafe,
|
|
53
|
+
renameSyncRetry,
|
|
54
|
+
sha256Hex,
|
|
55
|
+
stageAtomicSwap,
|
|
56
|
+
validateAndLintSkillStaging,
|
|
57
|
+
validateSkillSlugName,
|
|
58
|
+
} from "./skills-history.mjs";
|
|
59
|
+
|
|
60
|
+
export { getSkillHistory };
|
|
61
|
+
|
|
62
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
63
|
+
const __dirname = path.dirname(__filename);
|
|
64
|
+
const DEFAULT_HARNESS_DIR = path.resolve(__dirname, "..");
|
|
65
|
+
|
|
66
|
+
const ALLOWED_AUTHORIZATION_MODES = new Set(["approval", "pr-branch", "interactive"]);
|
|
67
|
+
|
|
68
|
+
function loadSchema(schemasDir, schemaName) {
|
|
69
|
+
return JSON.parse(fs.readFileSync(path.join(schemasDir, schemaName), "utf8"));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function validateExternalKeyOutPath(
|
|
73
|
+
rawPath,
|
|
74
|
+
{ projectDir, harnessDir, workspaceRoot, label = "--out", allowInsideProject = false }
|
|
75
|
+
) {
|
|
76
|
+
if (typeof rawPath !== "string" || rawPath.trim().length === 0) {
|
|
77
|
+
throw new Error(`Missing required ${label} <file> path for Ed25519 key.`);
|
|
78
|
+
}
|
|
79
|
+
if (CONTROL_CHAR_REGEX.test(rawPath)) {
|
|
80
|
+
throw new Error("Key output path contains illegal control characters.");
|
|
81
|
+
}
|
|
82
|
+
if (/^(\\\\|\/\/)/.test(rawPath)) {
|
|
83
|
+
throw new Error(`Refusing UNC/network path for key output: "${rawPath}".`);
|
|
84
|
+
}
|
|
85
|
+
if (/(^|[\\/])\.\.([\\/]|$)/.test(rawPath)) {
|
|
86
|
+
throw new Error(`Refusing path traversal ".." in key path: "${rawPath}".`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const resolved = path.resolve(rawPath);
|
|
90
|
+
const baseName = path.basename(resolved);
|
|
91
|
+
if (WINDOWS_RESERVED_NAME_REGEX.test(baseName)) {
|
|
92
|
+
throw new Error(`Key filename "${baseName}" conflicts with reserved Windows device name.`);
|
|
93
|
+
}
|
|
94
|
+
const protectedDirs = [path.resolve(harnessDir)];
|
|
95
|
+
if (!allowInsideProject) {
|
|
96
|
+
protectedDirs.unshift(path.resolve(projectDir));
|
|
97
|
+
}
|
|
98
|
+
if (workspaceRoot && fs.existsSync(path.join(workspaceRoot, "worktrees"))) {
|
|
99
|
+
protectedDirs.push(path.resolve(workspaceRoot, "worktrees"));
|
|
100
|
+
}
|
|
101
|
+
if (workspaceRoot && fs.existsSync(path.join(workspaceRoot, "local-runtime"))) {
|
|
102
|
+
protectedDirs.push(path.resolve(workspaceRoot, "local-runtime"));
|
|
103
|
+
}
|
|
104
|
+
for (const dir of protectedDirs) {
|
|
105
|
+
if (isSameOrInside(resolved, dir)) {
|
|
106
|
+
throw new Error(`Refusing to write key inside repository or protected directory: ${dir}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Reject symlinks on target or ancestors (ignoring macOS /tmp, /var, /etc OS links)
|
|
111
|
+
let cursor = resolved;
|
|
112
|
+
const visited = new Set();
|
|
113
|
+
while (cursor && !visited.has(cursor)) {
|
|
114
|
+
visited.add(cursor);
|
|
115
|
+
const isDarwinSys =
|
|
116
|
+
process.platform === "darwin" && (cursor === "/tmp" || cursor === "/var" || cursor === "/etc");
|
|
117
|
+
try {
|
|
118
|
+
const st = fs.lstatSync(cursor);
|
|
119
|
+
if (st.isSymbolicLink() && !isDarwinSys) {
|
|
120
|
+
throw new Error(`Refusing symbolic link/junction in key path: ${cursor}`);
|
|
121
|
+
}
|
|
122
|
+
if (cursor === resolved) {
|
|
123
|
+
throw new Error(`Refusing to overwrite existing key file: ${resolved}`);
|
|
124
|
+
}
|
|
125
|
+
} catch (err) {
|
|
126
|
+
if (err.code !== "ENOENT") {
|
|
127
|
+
throw err;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const parent = path.dirname(cursor);
|
|
131
|
+
if (parent === cursor) break;
|
|
132
|
+
cursor = parent;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return resolved;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function validateExternalFileReadPath(rawPath, projectDir, label = "--key", { forbidInsideRepo = true } = {}) {
|
|
139
|
+
if (typeof rawPath !== "string" || rawPath.trim().length === 0) {
|
|
140
|
+
throw new Error(`Missing required ${label} file path.`);
|
|
141
|
+
}
|
|
142
|
+
if (CONTROL_CHAR_REGEX.test(rawPath) || /^(\\\\|\/\/)/.test(rawPath) || /(^|[\\/])\.\.([\\/]|$)/.test(rawPath)) {
|
|
143
|
+
throw new Error(`Unsafe ${label} file path: "${rawPath}".`);
|
|
144
|
+
}
|
|
145
|
+
const resolved = path.resolve(rawPath);
|
|
146
|
+
if (forbidInsideRepo && isSameOrInside(resolved, path.resolve(projectDir))) {
|
|
147
|
+
throw new Error(`Refusing private key stored inside project repository (${resolved}); keep signing keys outside version control.`);
|
|
148
|
+
}
|
|
149
|
+
let cursor = resolved;
|
|
150
|
+
const visited = new Set();
|
|
151
|
+
while (cursor && !visited.has(cursor)) {
|
|
152
|
+
visited.add(cursor);
|
|
153
|
+
const isDarwinSys =
|
|
154
|
+
process.platform === "darwin" && (cursor === "/tmp" || cursor === "/var" || cursor === "/etc");
|
|
155
|
+
const st = fs.lstatSync(cursor);
|
|
156
|
+
if (st.isSymbolicLink() && !isDarwinSys) {
|
|
157
|
+
throw new Error(`Refusing symbolic link/junction in ${label} path: ${cursor}`);
|
|
158
|
+
}
|
|
159
|
+
if (cursor === resolved && !st.isFile()) {
|
|
160
|
+
throw new Error(`${label} path is not a regular file: ${resolved}`);
|
|
161
|
+
}
|
|
162
|
+
const parent = path.dirname(cursor);
|
|
163
|
+
if (parent === cursor) break;
|
|
164
|
+
cursor = parent;
|
|
165
|
+
}
|
|
166
|
+
return resolved;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function findRecordYamlById(projectDir, relDir, prefix, rawId) {
|
|
170
|
+
const idClean = String(rawId || "").trim().toUpperCase();
|
|
171
|
+
const idRegex = new RegExp(`^${prefix}-\\d{4}$`);
|
|
172
|
+
if (!idRegex.test(idClean)) {
|
|
173
|
+
throw new Error(`Invalid ${prefix} ID "${rawId}". Expected ${prefix}-NNNN.`);
|
|
174
|
+
}
|
|
175
|
+
const absDir = assertSafeWithinRoot(projectDir, relDir);
|
|
176
|
+
if (!assertSafeDirNonSymlink(absDir, relDir)) {
|
|
177
|
+
throw new Error(`${relDir}/ directory does not exist; ${idClean} not found.`);
|
|
178
|
+
}
|
|
179
|
+
const matches = [];
|
|
180
|
+
const files = walkNonSymlinkFiles(projectDir, absDir, (p) => /\.ya?ml$/i.test(p), null, {
|
|
181
|
+
onSymlink: (_rel, msg) => {
|
|
182
|
+
throw new Error(msg);
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
for (const fullPath of files) {
|
|
186
|
+
const relPath = path.relative(projectDir, fullPath).replace(/\\/g, "/");
|
|
187
|
+
const loaded = readSafeYamlWithinProject(projectDir, relPath);
|
|
188
|
+
if (loaded?.data && typeof loaded.data.id === "string" && loaded.data.id.toUpperCase() === idClean) {
|
|
189
|
+
matches.push(loaded);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (matches.length === 0) {
|
|
193
|
+
throw new Error(`Record ${idClean} not found under ${relDir}/.`);
|
|
194
|
+
}
|
|
195
|
+
if (matches.length > 1) {
|
|
196
|
+
throw new Error(`Duplicate record ID ${idClean} found in ${matches.map((m) => m.relPath).join(" and ")}.`);
|
|
197
|
+
}
|
|
198
|
+
return matches[0];
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function verifySingleEvidenceRecord(loadedEvid, projectDir, schemasDir) {
|
|
202
|
+
const d = loadedEvid.data;
|
|
203
|
+
const res = validateAgainstSchema(d, loadSchema(schemasDir, "evidence-manifest.schema.json"));
|
|
204
|
+
if (!res.valid) {
|
|
205
|
+
throw new Error(`${loadedEvid.relPath} failed evidence-manifest schema: ${res.errors.join("; ")}`);
|
|
206
|
+
}
|
|
207
|
+
if (d.is_example === true) {
|
|
208
|
+
throw new Error(`${loadedEvid.relPath}: example evidence fixture (is_example: true) cannot back skills.`);
|
|
209
|
+
}
|
|
210
|
+
if (d.status !== "verified") {
|
|
211
|
+
throw new Error(`${loadedEvid.relPath}: evidence status is "${d.status}", expected "verified".`);
|
|
212
|
+
}
|
|
213
|
+
const checks = Array.isArray(d.checks) ? d.checks : [];
|
|
214
|
+
if (checks.length === 0) {
|
|
215
|
+
throw new Error(`${loadedEvid.relPath}: verified evidence must contain at least one check.`);
|
|
216
|
+
}
|
|
217
|
+
const bad = checks.filter((c) => c.result === "failed" || c.result === "blocked");
|
|
218
|
+
const passed = checks.filter((c) => c.result === "passed");
|
|
219
|
+
if (bad.length > 0 || passed.length === 0) {
|
|
220
|
+
throw new Error(
|
|
221
|
+
`${loadedEvid.relPath}: evidence requires >= 1 passed check and 0 failed/blocked checks (${passed.length} passed, ${bad.length} failed/blocked).`
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
for (const chk of checks) {
|
|
225
|
+
if (hasSecretContent(chk.command || "") || hasSecretContent(chk.summary || "")) {
|
|
226
|
+
throw new Error(`${loadedEvid.relPath}: evidence check contains unredacted credential pattern.`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
for (const art of d.artifacts || []) {
|
|
231
|
+
if (!art || typeof art.path !== "string") continue;
|
|
232
|
+
if (isForbiddenSecretPath(art.path)) {
|
|
233
|
+
throw new Error(`${loadedEvid.relPath}: forbidden secret artifact path "${art.path}".`);
|
|
234
|
+
}
|
|
235
|
+
const artFull = assertSafeWithinRoot(projectDir, art.path);
|
|
236
|
+
if (typeof art.sha256 === "string" && art.sha256.trim().length > 0) {
|
|
237
|
+
if (!fs.existsSync(artFull) || !fs.lstatSync(artFull).isFile()) {
|
|
238
|
+
throw new Error(`${loadedEvid.relPath}: hashed artifact missing or unsafe on disk: "${art.path}".`);
|
|
239
|
+
}
|
|
240
|
+
const actualHex = sha256Hex(fs.readFileSync(artFull));
|
|
241
|
+
const expectedHex = art.sha256.trim().replace(/^sha256:/i, "").toLowerCase();
|
|
242
|
+
if (actualHex !== expectedHex) {
|
|
243
|
+
throw new Error(`${loadedEvid.relPath}: artifact SHA-256 mismatch on "${art.path}" (tampered artifact).`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return loadedEvid;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Loads, schema-checks, cross-verifies, and contradiction-checks source EVID/HANDOFF records.
|
|
252
|
+
* Fails closed on invalid/unverified/tampered evidence or open CONF contradictions.
|
|
253
|
+
*/
|
|
254
|
+
export function loadVerifiedSourceBundle({
|
|
255
|
+
projectDir,
|
|
256
|
+
evidenceIds = [],
|
|
257
|
+
handoffIds = [],
|
|
258
|
+
harnessDir = DEFAULT_HARNESS_DIR,
|
|
259
|
+
} = {}) {
|
|
260
|
+
const loaded = loadProjectManifestAndState(projectDir, harnessDir);
|
|
261
|
+
const { schemasDir, projectPaths } = loaded;
|
|
262
|
+
const resolvedProj = loaded.projectDir;
|
|
263
|
+
|
|
264
|
+
const evIdList = Array.from(new Set((evidenceIds || []).map((s) => String(s).trim().toUpperCase()).filter(Boolean)));
|
|
265
|
+
const hoIdList = Array.from(new Set((handoffIds || []).map((s) => String(s).trim().toUpperCase()).filter(Boolean)));
|
|
266
|
+
if (evIdList.length === 0 && hoIdList.length === 0) {
|
|
267
|
+
throw new Error("Provide at least one source record (--from-evidence EVID-NNNN or --from-handoff HANDOFF-NNNN).");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const evidenceMap = new Map();
|
|
271
|
+
const handoffRecords = [];
|
|
272
|
+
const referencedIds = new Set([...evIdList, ...hoIdList]);
|
|
273
|
+
const referencedPaths = new Set();
|
|
274
|
+
|
|
275
|
+
for (const evId of evIdList) {
|
|
276
|
+
const rec = findRecordYamlById(resolvedProj, projectPaths.evidence_dir, "EVID", evId);
|
|
277
|
+
verifySingleEvidenceRecord(rec, resolvedProj, schemasDir);
|
|
278
|
+
evidenceMap.set(evId, rec);
|
|
279
|
+
referencedPaths.add(rec.relPath);
|
|
280
|
+
if (rec.data.task_id) referencedIds.add(rec.data.task_id);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const handoffSchema = loadSchema(schemasDir, "agent-handoff.schema.json");
|
|
284
|
+
for (const hoId of hoIdList) {
|
|
285
|
+
const hRec = findRecordYamlById(resolvedProj, projectPaths.handoffs_dir, "HANDOFF", hoId);
|
|
286
|
+
const hValid = validateAgainstSchema(hRec.data, handoffSchema);
|
|
287
|
+
if (!hValid.valid) {
|
|
288
|
+
throw new Error(`${hRec.relPath} failed agent-handoff schema: ${hValid.errors.join("; ")}`);
|
|
289
|
+
}
|
|
290
|
+
if (hRec.data.is_example === true) {
|
|
291
|
+
throw new Error(`${hRec.relPath}: example handoff (is_example: true) cannot back skills.`);
|
|
292
|
+
}
|
|
293
|
+
if (hRec.data.status === "rejected") {
|
|
294
|
+
throw new Error(`${hRec.relPath}: rejected handoff cannot back skills.`);
|
|
295
|
+
}
|
|
296
|
+
const verifiedRefs = Array.isArray(hRec.data.verified_evidence) ? hRec.data.verified_evidence : [];
|
|
297
|
+
if (verifiedRefs.length === 0) {
|
|
298
|
+
throw new Error(
|
|
299
|
+
`${hRec.relPath}: handoff has zero verified_evidence entries; unverified_claims alone cannot generate or update skills.`
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
for (const ve of verifiedRefs) {
|
|
303
|
+
const evRec = findRecordYamlById(resolvedProj, projectPaths.evidence_dir, "EVID", ve.id);
|
|
304
|
+
verifySingleEvidenceRecord(evRec, resolvedProj, schemasDir);
|
|
305
|
+
if (ve.path && ve.path !== evRec.relPath) {
|
|
306
|
+
throw new Error(`${hRec.relPath}: verified_evidence path mismatch for ${ve.id} ("${ve.path}" vs "${evRec.relPath}").`);
|
|
307
|
+
}
|
|
308
|
+
evidenceMap.set(evRec.data.id, evRec);
|
|
309
|
+
referencedIds.add(evRec.data.id);
|
|
310
|
+
referencedPaths.add(evRec.relPath);
|
|
311
|
+
if (evRec.data.task_id) referencedIds.add(evRec.data.task_id);
|
|
312
|
+
}
|
|
313
|
+
referencedPaths.add(hRec.relPath);
|
|
314
|
+
if (hRec.data.task_id) referencedIds.add(hRec.data.task_id);
|
|
315
|
+
handoffRecords.push(hRec);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Check brain/conflicts for open or under_review contradictions on source evidence/tasks/handoffs
|
|
319
|
+
const conflictsAbs = assertSafeWithinRoot(resolvedProj, projectPaths.conflicts_dir);
|
|
320
|
+
const openConflictIds = [];
|
|
321
|
+
if (assertSafeDirNonSymlink(conflictsAbs, projectPaths.conflicts_dir)) {
|
|
322
|
+
const confFiles = walkNonSymlinkFiles(resolvedProj, conflictsAbs, (p) => /\.ya?ml$/i.test(p), null, {
|
|
323
|
+
onSymlink: (_rel, msg) => {
|
|
324
|
+
throw new Error(msg);
|
|
325
|
+
},
|
|
326
|
+
});
|
|
327
|
+
for (const cf of confFiles) {
|
|
328
|
+
const rel = path.relative(resolvedProj, cf).replace(/\\/g, "/");
|
|
329
|
+
const confLoaded = readSafeYamlWithinProject(resolvedProj, rel);
|
|
330
|
+
const cData = confLoaded?.data;
|
|
331
|
+
if (!cData || (cData.status !== "open" && cData.status !== "under_review")) {
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
const hitsRef =
|
|
335
|
+
(cData.conflicting_records || []).some(
|
|
336
|
+
(cr) => referencedIds.has(cr.record_id) || referencedPaths.has(String(cr.path || "").replace(/\\/g, "/"))
|
|
337
|
+
) || handoffRecords.some((h) => (h.data.conflicts_detected || []).includes(cData.id));
|
|
338
|
+
if (hitsRef) {
|
|
339
|
+
openConflictIds.push(cData.id);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (openConflictIds.length > 0) {
|
|
344
|
+
throw new Error(
|
|
345
|
+
`Open contradiction conflict(s) (${openConflictIds.join(", ")}) affect the source evidence/task. Resolve conflicts before drafting or promoting skills.`
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Git revision staleness detection (informational warning — fails only if requested strict elsewhere)
|
|
350
|
+
const gitInfo = getGitRepoInfo(resolvedProj);
|
|
351
|
+
const stalenessWarnings = [];
|
|
352
|
+
const headCommit = gitInfo.available && !gitInfo.unborn ? gitInfo.head : null;
|
|
353
|
+
|
|
354
|
+
const evidenceList = Array.from(evidenceMap.values()).sort((a, b) => a.data.id.localeCompare(b.data.id));
|
|
355
|
+
for (const ev of evidenceList) {
|
|
356
|
+
const rev = String(ev.data.source_revision || "");
|
|
357
|
+
if (headCommit && /^[a-f0-9]{7,40}$/i.test(rev) && !headCommit.startsWith(rev) && !rev.startsWith(headCommit)) {
|
|
358
|
+
stalenessWarnings.push(
|
|
359
|
+
`Evidence ${ev.data.id} was captured at Git revision ${rev}, while current HEAD is ${headCommit.slice(0, 12)}.`
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Load primary task details if readable (non-fatal if archived)
|
|
365
|
+
const taskIds = Array.from(new Set(evidenceList.map((e) => e.data.task_id).filter(Boolean))).sort();
|
|
366
|
+
let primaryTask = null;
|
|
367
|
+
if (taskIds.length > 0) {
|
|
368
|
+
try {
|
|
369
|
+
primaryTask = findRecordYamlById(resolvedProj, projectPaths.tasks_dir, "TASK", taskIds[0]);
|
|
370
|
+
} catch {
|
|
371
|
+
primaryTask = null;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const evidenceDigests = [
|
|
376
|
+
...evidenceList.map((e) => `${e.data.id}@${e.sha256}`),
|
|
377
|
+
...handoffRecords.map((h) => `${h.data.id}@${h.sha256}`),
|
|
378
|
+
].sort();
|
|
379
|
+
|
|
380
|
+
return {
|
|
381
|
+
...loaded,
|
|
382
|
+
evidenceList,
|
|
383
|
+
handoffRecords,
|
|
384
|
+
taskIds,
|
|
385
|
+
primaryTask,
|
|
386
|
+
evidenceDigests,
|
|
387
|
+
stalenessWarnings,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function formatFactualObservationsLines(bundle) {
|
|
392
|
+
const lines = [];
|
|
393
|
+
for (const ev of bundle.evidenceList) {
|
|
394
|
+
const d = ev.data;
|
|
395
|
+
lines.push(`- **${d.id}** (\`${ev.relPath}\`, task \`${d.task_id}\`, revision \`${d.source_revision}\`, ${d.environment.os} / ${d.environment.runtime}):`);
|
|
396
|
+
for (const chk of d.checks) {
|
|
397
|
+
lines.push(` - Check \`${chk.name}\` — command: \`${chk.command}\` -> result: \`${chk.result}\` (${chk.summary})`);
|
|
398
|
+
}
|
|
399
|
+
if (Array.isArray(d.limitations) && d.limitations.length > 0) {
|
|
400
|
+
for (const lim of d.limitations) {
|
|
401
|
+
lines.push(` - Recorded limitation: ${lim}`);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
for (const h of bundle.handoffRecords) {
|
|
406
|
+
lines.push(`- **${h.data.id}** (\`${h.relPath}\`, role \`${h.data.from_role}\` -> \`${h.data.to_role}\`): ${h.data.summary}`);
|
|
407
|
+
}
|
|
408
|
+
return lines;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function buildDraftSkillMarkdown({ skillName, title, description, bundle, suggestedSteps = [], tags = [], triggers = [] }) {
|
|
412
|
+
const sourceIds = [...bundle.evidenceList.map((e) => e.data.id), ...bundle.handoffRecords.map((h) => h.data.id)];
|
|
413
|
+
const mergedTags = Array.from(new Set(["evidence-backed", ...tags])).join(", ");
|
|
414
|
+
const mergedTriggers = Array.from(
|
|
415
|
+
new Set(triggers.length > 0 ? triggers : [skillName.replace(/-/g, " "), bundle.taskIds[0] || "verification"])
|
|
416
|
+
).join(", ");
|
|
417
|
+
|
|
418
|
+
const frontmatterObj = {
|
|
419
|
+
name: skillName,
|
|
420
|
+
description,
|
|
421
|
+
license: "MIT",
|
|
422
|
+
metadata: {
|
|
423
|
+
geloforge_origin: "evidence_draft",
|
|
424
|
+
geloforge_source_records: sourceIds.join(", "),
|
|
425
|
+
...(bundle.taskIds.length > 0 ? { geloforge_source_task: bundle.taskIds.join(", ") } : {}),
|
|
426
|
+
geloforge_tags: mergedTags,
|
|
427
|
+
geloforge_triggers: mergedTriggers,
|
|
428
|
+
},
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
const yamlLines = serializeYaml(frontmatterObj).trimEnd();
|
|
432
|
+
const factualLines = formatFactualObservationsLines(bundle);
|
|
433
|
+
|
|
434
|
+
const procLines =
|
|
435
|
+
suggestedSteps.length > 0
|
|
436
|
+
? suggestedSteps.map((s, idx) => `${idx + 1}. ${s}`)
|
|
437
|
+
: [
|
|
438
|
+
...(bundle.primaryTask?.data?.objective
|
|
439
|
+
? [`1. Confirm task objective applies: ${bundle.primaryTask.data.objective}`]
|
|
440
|
+
: ["1. Review whether the target repository context matches the source task constraints."]),
|
|
441
|
+
...bundle.evidenceList.flatMap((ev, idx) =>
|
|
442
|
+
ev.data.checks.map(
|
|
443
|
+
(chk, cIdx) =>
|
|
444
|
+
`${bundle.primaryTask ? idx + cIdx + 2 : idx + cIdx + 1}. Re-run verification command \`${chk.command}\` explicitly with \`geloforge evidence capture\` (never treat historical \`exit 0\` as proof for new edits).`
|
|
445
|
+
)
|
|
446
|
+
),
|
|
447
|
+
];
|
|
448
|
+
|
|
449
|
+
const mdLines = [
|
|
450
|
+
"---",
|
|
451
|
+
yamlLines,
|
|
452
|
+
"---",
|
|
453
|
+
"",
|
|
454
|
+
`# ${title}`,
|
|
455
|
+
"",
|
|
456
|
+
"> **Draft Status (Quarantined):** Generated from local verified records below. Passing source evidence does **not** prove generalized procedure steps are valid; human review and authorization are required before promotion.",
|
|
457
|
+
"",
|
|
458
|
+
"## When to Use",
|
|
459
|
+
"",
|
|
460
|
+
`Use this skill when working on tasks related to ${title.toLowerCase()} where the recorded verification steps below apply.`,
|
|
461
|
+
"",
|
|
462
|
+
"## Verified Observations (Source Evidence — Factual Only)",
|
|
463
|
+
"",
|
|
464
|
+
...factualLines,
|
|
465
|
+
"",
|
|
466
|
+
"## Suggested Procedure (Agent/Draft Suggestion — Unverified Until Promoted)",
|
|
467
|
+
"",
|
|
468
|
+
...procLines,
|
|
469
|
+
"",
|
|
470
|
+
"## Provenance & Limitations",
|
|
471
|
+
"",
|
|
472
|
+
`- **Source Records & Digests:** ${bundle.evidenceDigests.map((d) => `\`${d}\``).join(", ")}`,
|
|
473
|
+
...(bundle.stalenessWarnings.length > 0
|
|
474
|
+
? bundle.stalenessWarnings.map((w) => `- **Staleness Notice:** ${w}`)
|
|
475
|
+
: ["- **Git Alignment:** Source evidence matches checked Git state or non-Git workspace."]),
|
|
476
|
+
"",
|
|
477
|
+
];
|
|
478
|
+
|
|
479
|
+
return mdLines.join("\n");
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function ensureProposalSlotAvailable(projectDir, proposalDir, metaRel, metaAbs) {
|
|
483
|
+
let allowMetaOverwrite = false;
|
|
484
|
+
if (fs.existsSync(metaAbs)) {
|
|
485
|
+
const existing = readSafeYamlWithinProject(projectDir, metaRel);
|
|
486
|
+
const st = existing?.data?.status;
|
|
487
|
+
if ((st === "promoted" || st === "pending_pr_review") && !fs.existsSync(proposalDir)) {
|
|
488
|
+
allowMetaOverwrite = true;
|
|
489
|
+
} else {
|
|
490
|
+
throw new Error(
|
|
491
|
+
`Proposal metadata "${metaRel}" already exists; resolve or remove pending proposal before creating a new one.`
|
|
492
|
+
);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
return allowMetaOverwrite;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Phase 3: Creates a quarantined portable SKILL.md draft under <proposalsDir>/skills/
|
|
500
|
+
* backed strictly by verified EVID-* / HANDOFF-* facts without auto-activating.
|
|
501
|
+
*/
|
|
502
|
+
export function draftSkillFromExperience(options = {}) {
|
|
503
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
504
|
+
const createdAt = validateCreatedAt(options.createdAt);
|
|
505
|
+
const bundle = loadVerifiedSourceBundle({
|
|
506
|
+
projectDir: options.projectDir,
|
|
507
|
+
evidenceIds: options.evidenceIds || [],
|
|
508
|
+
handoffIds: options.handoffIds || [],
|
|
509
|
+
harnessDir,
|
|
510
|
+
});
|
|
511
|
+
const { projectDir, projectPaths } = bundle;
|
|
512
|
+
|
|
513
|
+
const fallbackTitle =
|
|
514
|
+
bundle.primaryTask?.data?.title ||
|
|
515
|
+
bundle.evidenceList[0]?.data?.title ||
|
|
516
|
+
bundle.handoffRecords[0]?.data?.id ||
|
|
517
|
+
"verified-workflow";
|
|
518
|
+
const skillName = validateSkillSlugName(options.skillName, fallbackTitle);
|
|
519
|
+
|
|
520
|
+
if (options.title && CONTROL_CHAR_REGEX.test(options.title)) {
|
|
521
|
+
throw new Error("Title contains invalid control characters.");
|
|
522
|
+
}
|
|
523
|
+
const title = (options.title ? validateScalarText("--title", options.title) : null) ||
|
|
524
|
+
`${bundle.primaryTask?.data?.title || bundle.evidenceList[0].data.title}`;
|
|
525
|
+
|
|
526
|
+
const rawDesc =
|
|
527
|
+
options.description ||
|
|
528
|
+
`Apply verified checks for ${title} backed by ${bundle.evidenceList.map((e) => e.data.id).join(", ")}. Review draft guidance before use.`;
|
|
529
|
+
let description = redactSecretContent(validateScalarText("--description", rawDesc));
|
|
530
|
+
if (description.length < 20) {
|
|
531
|
+
description = `${description} — reviewed draft from verified project evidence.`;
|
|
532
|
+
}
|
|
533
|
+
if (description.length > 1024) {
|
|
534
|
+
description = `${description.slice(0, 1021)}...`;
|
|
535
|
+
}
|
|
536
|
+
if (hasSecretContent(title) || hasSecretContent(description)) {
|
|
537
|
+
throw new Error("Refusing draft metadata containing credential-like content.");
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
const suggestedSteps = Array.isArray(options.steps)
|
|
541
|
+
? options.steps.map((s) => validateScalarText("--step", s))
|
|
542
|
+
: [];
|
|
543
|
+
for (const s of suggestedSteps) {
|
|
544
|
+
if (hasSecretContent(s)) throw new Error("Refusing draft step containing credential-like content.");
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const activeDir = assertSafeWithinRoot(projectDir, `.agents/skills/${skillName}`);
|
|
548
|
+
if (fs.existsSync(activeDir)) {
|
|
549
|
+
throw new Error(
|
|
550
|
+
`Active skill "${skillName}" already exists at .agents/skills/${skillName}. Use "geloforge skills propose-update ${skillName}" instead.`
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
const skillsProposalsRoot = assertSafeWithinRoot(projectDir, `${projectPaths.proposals_dir}/skills`);
|
|
555
|
+
assertSafeAncestorChain(skillsProposalsRoot, projectDir, "proposals/skills");
|
|
556
|
+
assertSafeDirNonSymlink(skillsProposalsRoot, `${projectPaths.proposals_dir}/skills`);
|
|
557
|
+
|
|
558
|
+
const proposalSkillRel = `${projectPaths.proposals_dir}/skills/${skillName}`;
|
|
559
|
+
const proposalSkillDir = assertSafeWithinRoot(projectDir, proposalSkillRel);
|
|
560
|
+
const metaRel = `${projectPaths.proposals_dir}/skills/.proposals/${skillName}.yaml`;
|
|
561
|
+
const metaAbs = assertSafeWithinRoot(projectDir, metaRel);
|
|
562
|
+
|
|
563
|
+
if (fs.existsSync(proposalSkillDir)) {
|
|
564
|
+
throw new Error(`Proposal "${skillName}" already exists under ${proposalSkillRel}. Avoid duplicate proposals.`);
|
|
565
|
+
}
|
|
566
|
+
const allowMetaOverwrite = ensureProposalSlotAvailable(projectDir, proposalSkillDir, metaRel, metaAbs);
|
|
567
|
+
|
|
568
|
+
const markdown = buildDraftSkillMarkdown({
|
|
569
|
+
skillName,
|
|
570
|
+
title,
|
|
571
|
+
description,
|
|
572
|
+
bundle,
|
|
573
|
+
suggestedSteps,
|
|
574
|
+
tags: options.tags || [],
|
|
575
|
+
triggers: options.triggers || [],
|
|
576
|
+
});
|
|
577
|
+
if (hasSecretContent(markdown)) {
|
|
578
|
+
throw new Error("Refusing draft because generated SKILL.md triggered secret-content detection.");
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// Stage in isolated temp dir, validate + strict lint + compute digest
|
|
582
|
+
const stageDir = path.join(projectDir, projectPaths.proposals_dir, "skills", `.geloforge-stage-${crypto.randomBytes(6).toString("hex")}`);
|
|
583
|
+
let verified;
|
|
584
|
+
try {
|
|
585
|
+
fs.mkdirSync(stageDir, { recursive: true });
|
|
586
|
+
fs.writeFileSync(path.join(stageDir, "SKILL.md"), markdown, { encoding: "utf8", flag: "wx" });
|
|
587
|
+
verified = validateAndLintSkillStaging({
|
|
588
|
+
stageDir,
|
|
589
|
+
skillName,
|
|
590
|
+
displayRoot: `${projectPaths.proposals_dir}/skills`,
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
const proposalMeta = {
|
|
594
|
+
schema_version: "1.0",
|
|
595
|
+
proposal_id: `PROP-${skillName}`,
|
|
596
|
+
kind: "new_skill",
|
|
597
|
+
skill_name: skillName,
|
|
598
|
+
status: "draft",
|
|
599
|
+
created_at: createdAt,
|
|
600
|
+
base_skill_digest: null,
|
|
601
|
+
candidate_digest: verified.digestInfo.digest,
|
|
602
|
+
source_evidence: bundle.evidenceList.map((e) => ({
|
|
603
|
+
id: e.data.id,
|
|
604
|
+
path: e.relPath,
|
|
605
|
+
sha256: e.sha256,
|
|
606
|
+
})),
|
|
607
|
+
source_handoffs: bundle.handoffRecords.map((h) => ({
|
|
608
|
+
id: h.data.id,
|
|
609
|
+
path: h.relPath,
|
|
610
|
+
sha256: h.sha256,
|
|
611
|
+
})),
|
|
612
|
+
reason: `Evidence-backed draft generated from ${[...bundle.evidenceList, ...bundle.handoffRecords].map((r) => r.data.id).join(", ")}.`,
|
|
613
|
+
warnings: bundle.stalenessWarnings,
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
if (options.dryRun) {
|
|
617
|
+
return {
|
|
618
|
+
dryRun: true,
|
|
619
|
+
skillName,
|
|
620
|
+
proposalDir: proposalSkillRel,
|
|
621
|
+
proposalMetaPath: metaRel,
|
|
622
|
+
candidateDigest: verified.digestInfo.digest,
|
|
623
|
+
evidenceDigests: bundle.evidenceDigests,
|
|
624
|
+
stalenessWarnings: bundle.stalenessWarnings,
|
|
625
|
+
lintPassed: true,
|
|
626
|
+
markdown,
|
|
627
|
+
proposalMeta,
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
assertSafeAncestorChain(proposalSkillDir, projectDir, proposalSkillRel);
|
|
632
|
+
renameSyncRetry(stageDir, proposalSkillDir);
|
|
633
|
+
atomicWriteFile(metaAbs, serializeYaml(proposalMeta, { headerComment: "Quarantined GeloForge skill draft metadata" }), {
|
|
634
|
+
allowOverwrite: allowMetaOverwrite,
|
|
635
|
+
});
|
|
636
|
+
|
|
637
|
+
return {
|
|
638
|
+
dryRun: false,
|
|
639
|
+
skillName,
|
|
640
|
+
proposalDir: proposalSkillRel,
|
|
641
|
+
proposalMetaPath: metaRel,
|
|
642
|
+
candidateDigest: verified.digestInfo.digest,
|
|
643
|
+
evidenceDigests: bundle.evidenceDigests,
|
|
644
|
+
stalenessWarnings: bundle.stalenessWarnings,
|
|
645
|
+
lintPassed: true,
|
|
646
|
+
proposalMeta,
|
|
647
|
+
};
|
|
648
|
+
} finally {
|
|
649
|
+
removeDirSafe(stageDir);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* Deterministic line-based unified diff helper with zero external dependencies
|
|
655
|
+
* and bounded DP memory allocation.
|
|
656
|
+
*/
|
|
657
|
+
export function computeUnifiedDiff(oldText, newText, oldLabel = "a/SKILL.md", newLabel = "b/SKILL.md") {
|
|
658
|
+
const a = oldText.replace(/\r\n/g, "\n").split("\n");
|
|
659
|
+
const b = newText.replace(/\r\n/g, "\n").split("\n");
|
|
660
|
+
let start = 0;
|
|
661
|
+
while (start < a.length && start < b.length && a[start] === b[start]) {
|
|
662
|
+
start += 1;
|
|
663
|
+
}
|
|
664
|
+
let endA = a.length - 1;
|
|
665
|
+
let endB = b.length - 1;
|
|
666
|
+
while (endA >= start && endB >= start && a[endA] === b[endB]) {
|
|
667
|
+
endA -= 1;
|
|
668
|
+
endB -= 1;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
const aMid = a.slice(start, endA + 1);
|
|
672
|
+
const bMid = b.slice(start, endB + 1);
|
|
673
|
+
const m = aMid.length;
|
|
674
|
+
const n = bMid.length;
|
|
675
|
+
|
|
676
|
+
const lines = [`--- ${oldLabel}`, `+++ ${newLabel}`];
|
|
677
|
+
for (let k = 0; k < start; k += 1) {
|
|
678
|
+
lines.push(` ${a[k]}`);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
let added = 0;
|
|
682
|
+
let removed = 0;
|
|
683
|
+
if (m * n > 1_000_000) {
|
|
684
|
+
for (const line of aMid) {
|
|
685
|
+
lines.push(`-${line}`);
|
|
686
|
+
removed += 1;
|
|
687
|
+
}
|
|
688
|
+
for (const line of bMid) {
|
|
689
|
+
lines.push(`+${line}`);
|
|
690
|
+
added += 1;
|
|
691
|
+
}
|
|
692
|
+
} else {
|
|
693
|
+
const dp = Array.from({ length: m + 1 }, () => new Int32Array(n + 1));
|
|
694
|
+
for (let i = m - 1; i >= 0; i -= 1) {
|
|
695
|
+
for (let j = n - 1; j >= 0; j -= 1) {
|
|
696
|
+
if (aMid[i] === bMid[j]) dp[i][j] = dp[i + 1][j + 1] + 1;
|
|
697
|
+
else dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1]);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
let i = 0;
|
|
702
|
+
let j = 0;
|
|
703
|
+
while (i < m && j < n) {
|
|
704
|
+
if (aMid[i] === bMid[j]) {
|
|
705
|
+
lines.push(` ${aMid[i]}`);
|
|
706
|
+
i += 1;
|
|
707
|
+
j += 1;
|
|
708
|
+
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
|
|
709
|
+
lines.push(`-${aMid[i]}`);
|
|
710
|
+
removed += 1;
|
|
711
|
+
i += 1;
|
|
712
|
+
} else {
|
|
713
|
+
lines.push(`+${bMid[j]}`);
|
|
714
|
+
added += 1;
|
|
715
|
+
j += 1;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
while (i < m) {
|
|
719
|
+
lines.push(`-${aMid[i]}`);
|
|
720
|
+
removed += 1;
|
|
721
|
+
i += 1;
|
|
722
|
+
}
|
|
723
|
+
while (j < n) {
|
|
724
|
+
lines.push(`+${bMid[j]}`);
|
|
725
|
+
added += 1;
|
|
726
|
+
j += 1;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
for (let k = endA + 1; k < a.length; k += 1) {
|
|
731
|
+
lines.push(` ${a[k]}`);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
return {
|
|
735
|
+
diff: lines.join("\n"),
|
|
736
|
+
added,
|
|
737
|
+
removed,
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* Phase 4: Proposes an isolated candidate update to an existing trusted project skill
|
|
743
|
+
* without modifying `.agents/skills/<skillName>/`.
|
|
744
|
+
*/
|
|
745
|
+
export function proposeSkillUpdate(options = {}) {
|
|
746
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
747
|
+
const createdAt = validateCreatedAt(options.createdAt);
|
|
748
|
+
const skillName = validateSkillSlugName(options.skillName);
|
|
749
|
+
const reason = redactSecretContent(validateScalarText("--reason", options.reason || "Incorporate verified findings."));
|
|
750
|
+
if (hasSecretContent(reason)) {
|
|
751
|
+
throw new Error("Refusing update reason containing credential-like content.");
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
const bundle = loadVerifiedSourceBundle({
|
|
755
|
+
projectDir: options.projectDir,
|
|
756
|
+
evidenceIds: options.evidenceIds || [],
|
|
757
|
+
handoffIds: options.handoffIds || [],
|
|
758
|
+
harnessDir,
|
|
759
|
+
});
|
|
760
|
+
const { projectDir, projectPaths } = bundle;
|
|
761
|
+
|
|
762
|
+
const activeRel = `.agents/skills/${skillName}`;
|
|
763
|
+
const activeDir = assertSafeWithinRoot(projectDir, activeRel);
|
|
764
|
+
if (!fs.existsSync(activeDir)) {
|
|
765
|
+
throw new Error(`Trusted skill "${skillName}" does not exist at ${activeRel}. Use "geloforge skills draft" for new skills.`);
|
|
766
|
+
}
|
|
767
|
+
const activeDigestInfo = computeSkillPackageDigest(activeDir);
|
|
768
|
+
const activePkg = inspectSkillPackage({
|
|
769
|
+
skillDir: activeDir,
|
|
770
|
+
folderName: skillName,
|
|
771
|
+
source: "project",
|
|
772
|
+
trustTier: "project_trusted",
|
|
773
|
+
displayRoot: ".agents/skills",
|
|
774
|
+
});
|
|
775
|
+
if (!activePkg.valid) {
|
|
776
|
+
throw new Error(`Current active skill "${skillName}" is invalid and cannot be updated safely.`);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
const proposalRel = `${projectPaths.proposals_dir}/skills/${skillName}`;
|
|
780
|
+
const proposalDir = assertSafeWithinRoot(projectDir, proposalRel);
|
|
781
|
+
const metaRel = `${projectPaths.proposals_dir}/skills/.proposals/${skillName}.yaml`;
|
|
782
|
+
const metaAbs = assertSafeWithinRoot(projectDir, metaRel);
|
|
783
|
+
|
|
784
|
+
if (fs.existsSync(proposalDir)) {
|
|
785
|
+
let staleNote = "";
|
|
786
|
+
try {
|
|
787
|
+
const existingMeta = readSafeYamlWithinProject(projectDir, metaRel);
|
|
788
|
+
if (existingMeta?.data?.base_skill_digest && existingMeta.data.base_skill_digest !== activeDigestInfo.digest) {
|
|
789
|
+
staleNote = " Existing proposal appears stale against current active skill.";
|
|
790
|
+
}
|
|
791
|
+
} catch {
|
|
792
|
+
// Ignore unreadable meta
|
|
793
|
+
}
|
|
794
|
+
throw new Error(
|
|
795
|
+
`An update or draft proposal for "${skillName}" already exists at ${proposalRel}.${staleNote} Resolve or remove it before creating another proposal.`
|
|
796
|
+
);
|
|
797
|
+
}
|
|
798
|
+
const allowMetaOverwrite = ensureProposalSlotAvailable(projectDir, proposalDir, metaRel, metaAbs);
|
|
799
|
+
|
|
800
|
+
let candidateSkillMd = "";
|
|
801
|
+
if (options.patchFile) {
|
|
802
|
+
const patchAbs = validateExternalFileReadPath(options.patchFile, projectDir, "--patch-file", {
|
|
803
|
+
forbidInsideRepo: false,
|
|
804
|
+
});
|
|
805
|
+
if (isForbiddenSecretPath(path.basename(patchAbs))) {
|
|
806
|
+
throw new Error(`Blocked forbidden secret filename for --patch-file: ${path.basename(patchAbs)}`);
|
|
807
|
+
}
|
|
808
|
+
const pStat = fs.lstatSync(patchAbs);
|
|
809
|
+
if (pStat.size > MAX_SKILL_BYTES) {
|
|
810
|
+
throw new Error(`--patch-file exceeds max skill size (${MAX_SKILL_BYTES} bytes).`);
|
|
811
|
+
}
|
|
812
|
+
candidateSkillMd = fs.readFileSync(patchAbs, "utf8");
|
|
813
|
+
if (hasSecretContent(candidateSkillMd)) {
|
|
814
|
+
throw new Error("Blocked --patch-file containing credential-like pattern.");
|
|
815
|
+
}
|
|
816
|
+
const parsedCand = parseSkillMarkdown(candidateSkillMd, options.patchFile);
|
|
817
|
+
if (parsedCand.frontmatter?.name !== skillName) {
|
|
818
|
+
throw new Error(`Candidate SKILL.md frontmatter name "${parsedCand.frontmatter?.name}" must equal "${skillName}".`);
|
|
819
|
+
}
|
|
820
|
+
} else {
|
|
821
|
+
const note = options.appendNote ? validateScalarText("--append-note", options.appendNote) : null;
|
|
822
|
+
if (note && hasSecretContent(note)) {
|
|
823
|
+
throw new Error("Blocked --append-note containing credential-like pattern.");
|
|
824
|
+
}
|
|
825
|
+
const factualLines = formatFactualObservationsLines(bundle);
|
|
826
|
+
const updateLines = [
|
|
827
|
+
"",
|
|
828
|
+
`## Proposed Evidence-Backed Update (${createdAt.slice(0, 10)})`,
|
|
829
|
+
"",
|
|
830
|
+
`- **Reason:** ${reason}`,
|
|
831
|
+
`- **Provenance:** ${bundle.evidenceDigests.map((d) => `\`${d}\``).join(", ")}`,
|
|
832
|
+
...(note ? [`- **Proposed Improvement (Unverified Suggestion):** ${note}`] : []),
|
|
833
|
+
"",
|
|
834
|
+
"### Supporting Verified Observations",
|
|
835
|
+
"",
|
|
836
|
+
...factualLines,
|
|
837
|
+
"",
|
|
838
|
+
];
|
|
839
|
+
candidateSkillMd = `${activePkg.rawSkillText.trimEnd()}\n${updateLines.join("\n")}`;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const diffRes = computeUnifiedDiff(
|
|
843
|
+
activePkg.rawSkillText.replace(/\r\n/g, "\n").trimEnd(),
|
|
844
|
+
candidateSkillMd.replace(/\r\n/g, "\n").trimEnd(),
|
|
845
|
+
`.agents/skills/${skillName}/SKILL.md`,
|
|
846
|
+
`${proposalRel}/SKILL.md`
|
|
847
|
+
);
|
|
848
|
+
if (diffRes.added === 0 && diffRes.removed === 0) {
|
|
849
|
+
throw new Error("Proposed update introduces no changes to SKILL.md.");
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
const skillsProposalsRoot = assertSafeWithinRoot(projectDir, `${projectPaths.proposals_dir}/skills`);
|
|
853
|
+
assertSafeAncestorChain(skillsProposalsRoot, projectDir, "proposals/skills");
|
|
854
|
+
assertSafeDirNonSymlink(skillsProposalsRoot, `${projectPaths.proposals_dir}/skills`);
|
|
855
|
+
fs.mkdirSync(skillsProposalsRoot, { recursive: true });
|
|
856
|
+
|
|
857
|
+
const stageDir = path.join(skillsProposalsRoot, `.geloforge-stage-${crypto.randomBytes(6).toString("hex")}`);
|
|
858
|
+
try {
|
|
859
|
+
copyTreeSafe(activeDir, stageDir);
|
|
860
|
+
fs.writeFileSync(path.join(stageDir, "SKILL.md"), candidateSkillMd, "utf8");
|
|
861
|
+
|
|
862
|
+
const verified = validateAndLintSkillStaging({
|
|
863
|
+
stageDir,
|
|
864
|
+
skillName,
|
|
865
|
+
displayRoot: `${projectPaths.proposals_dir}/skills`,
|
|
866
|
+
});
|
|
867
|
+
if (verified.digestInfo.digest === activeDigestInfo.digest) {
|
|
868
|
+
throw new Error("Proposed candidate package SHA-256 is identical to the active skill.");
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
const proposalMeta = {
|
|
872
|
+
schema_version: "1.0",
|
|
873
|
+
proposal_id: `PROP-${skillName}`,
|
|
874
|
+
kind: "update_skill",
|
|
875
|
+
skill_name: skillName,
|
|
876
|
+
status: "draft",
|
|
877
|
+
created_at: createdAt,
|
|
878
|
+
base_skill_digest: activeDigestInfo.digest,
|
|
879
|
+
candidate_digest: verified.digestInfo.digest,
|
|
880
|
+
source_evidence: bundle.evidenceList.map((e) => ({
|
|
881
|
+
id: e.data.id,
|
|
882
|
+
path: e.relPath,
|
|
883
|
+
sha256: e.sha256,
|
|
884
|
+
})),
|
|
885
|
+
source_handoffs: bundle.handoffRecords.map((h) => ({
|
|
886
|
+
id: h.data.id,
|
|
887
|
+
path: h.relPath,
|
|
888
|
+
sha256: h.sha256,
|
|
889
|
+
})),
|
|
890
|
+
reason,
|
|
891
|
+
diff_summary: `+${diffRes.added}/-${diffRes.removed} lines in SKILL.md`,
|
|
892
|
+
warnings: bundle.stalenessWarnings,
|
|
893
|
+
};
|
|
894
|
+
|
|
895
|
+
if (options.dryRun) {
|
|
896
|
+
return {
|
|
897
|
+
dryRun: true,
|
|
898
|
+
skillName,
|
|
899
|
+
proposalDir: proposalRel,
|
|
900
|
+
proposalMetaPath: metaRel,
|
|
901
|
+
baseSkillDigest: activeDigestInfo.digest,
|
|
902
|
+
candidateDigest: verified.digestInfo.digest,
|
|
903
|
+
diff: diffRes.diff,
|
|
904
|
+
diffSummary: proposalMeta.diff_summary,
|
|
905
|
+
evidenceDigests: bundle.evidenceDigests,
|
|
906
|
+
stalenessWarnings: bundle.stalenessWarnings,
|
|
907
|
+
proposalMeta,
|
|
908
|
+
};
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
assertSafeAncestorChain(proposalDir, projectDir, proposalRel);
|
|
912
|
+
renameSyncRetry(stageDir, proposalDir);
|
|
913
|
+
atomicWriteFile(metaAbs, serializeYaml(proposalMeta, { headerComment: "Quarantined GeloForge skill update proposal metadata" }), {
|
|
914
|
+
allowOverwrite: allowMetaOverwrite,
|
|
915
|
+
});
|
|
916
|
+
|
|
917
|
+
return {
|
|
918
|
+
dryRun: false,
|
|
919
|
+
skillName,
|
|
920
|
+
proposalDir: proposalRel,
|
|
921
|
+
proposalMetaPath: metaRel,
|
|
922
|
+
baseSkillDigest: activeDigestInfo.digest,
|
|
923
|
+
candidateDigest: verified.digestInfo.digest,
|
|
924
|
+
diff: diffRes.diff,
|
|
925
|
+
diffSummary: proposalMeta.diff_summary,
|
|
926
|
+
evidenceDigests: bundle.evidenceDigests,
|
|
927
|
+
stalenessWarnings: bundle.stalenessWarnings,
|
|
928
|
+
proposalMeta,
|
|
929
|
+
};
|
|
930
|
+
} finally {
|
|
931
|
+
removeDirSafe(stageDir);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
function loadApproversRegistry(projectDir) {
|
|
936
|
+
const relPath = ".geloforge/approvers.yaml";
|
|
937
|
+
const loaded = readSafeYamlWithinProject(projectDir, relPath);
|
|
938
|
+
if (!loaded || !loaded.data) {
|
|
939
|
+
return { relPath, approvers: [] };
|
|
940
|
+
}
|
|
941
|
+
if (typeof loaded.data !== "object" || Array.isArray(loaded.data) || !Array.isArray(loaded.data.approvers)) {
|
|
942
|
+
throw new Error(`${relPath}: invalid approvers registry format (expected mapping with "approvers" list).`);
|
|
943
|
+
}
|
|
944
|
+
const seenIds = new Set();
|
|
945
|
+
const approvers = [];
|
|
946
|
+
for (const entry of loaded.data.approvers) {
|
|
947
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
948
|
+
throw new Error(`${relPath}: approver entry must be a YAML object.`);
|
|
949
|
+
}
|
|
950
|
+
if (typeof entry.approver_id !== "string" || entry.approver_id.trim().length === 0) {
|
|
951
|
+
throw new Error(`${relPath}: approver entry missing valid "approver_id".`);
|
|
952
|
+
}
|
|
953
|
+
if (seenIds.has(entry.approver_id)) {
|
|
954
|
+
throw new Error(`${relPath}: duplicate approver_id "${entry.approver_id}" in approvers registry.`);
|
|
955
|
+
}
|
|
956
|
+
seenIds.add(entry.approver_id);
|
|
957
|
+
if (entry.algorithm !== "ed25519") {
|
|
958
|
+
throw new Error(`${relPath}: unsupported algorithm "${entry.algorithm}" for approver "${entry.approver_id}".`);
|
|
959
|
+
}
|
|
960
|
+
if (typeof entry.public_key_pem !== "string" || !entry.public_key_pem.includes("BEGIN PUBLIC KEY")) {
|
|
961
|
+
throw new Error(`${relPath}: invalid public_key_pem for approver "${entry.approver_id}".`);
|
|
962
|
+
}
|
|
963
|
+
let pubObj;
|
|
964
|
+
try {
|
|
965
|
+
pubObj = crypto.createPublicKey(entry.public_key_pem);
|
|
966
|
+
} catch {
|
|
967
|
+
throw new Error(`${relPath}: unparseable public_key_pem for approver "${entry.approver_id}".`);
|
|
968
|
+
}
|
|
969
|
+
if (pubObj.asymmetricKeyType !== "ed25519") {
|
|
970
|
+
throw new Error(`${relPath}: public key for approver "${entry.approver_id}" must be Ed25519.`);
|
|
971
|
+
}
|
|
972
|
+
const canonicalPubPem = pubObj.export({ type: "spki", format: "pem" });
|
|
973
|
+
const canonicalFp = `ed25519:${sha256Hex(canonicalPubPem).slice(0, 16)}`;
|
|
974
|
+
const rawFp = `ed25519:${sha256Hex(entry.public_key_pem).slice(0, 16)}`;
|
|
975
|
+
if (entry.key_fingerprint !== canonicalFp && entry.key_fingerprint !== rawFp) {
|
|
976
|
+
throw new Error(`${relPath}: key_fingerprint mismatch for approver "${entry.approver_id}".`);
|
|
977
|
+
}
|
|
978
|
+
approvers.push(entry);
|
|
979
|
+
}
|
|
980
|
+
return { relPath, approvers };
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
/**
|
|
984
|
+
* Generates an Ed25519 keypair, storing ONLY the public key in `.geloforge/approvers.yaml`
|
|
985
|
+
* (plus optional pinned external `--pub-out`) and writing the private key outside project/harness trees (`mode 0o600`, no overwrite).
|
|
986
|
+
*/
|
|
987
|
+
export function generateApproverKeypair(options = {}) {
|
|
988
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
989
|
+
const loaded = loadProjectManifestAndState(options.projectDir, harnessDir);
|
|
990
|
+
const { projectDir } = loaded;
|
|
991
|
+
const createdAt = validateCreatedAt(options.createdAt);
|
|
992
|
+
const approverId = validateScalarText("--approver", options.approverId);
|
|
993
|
+
if (hasSecretContent(approverId)) {
|
|
994
|
+
throw new Error("Invalid --approver identifier.");
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
const workspaceRoot = options.workspaceRoot ? path.resolve(options.workspaceRoot) : path.resolve(harnessDir, "..");
|
|
998
|
+
const privOutAbs = validateExternalKeyOutPath(options.privateKeyOut, {
|
|
999
|
+
projectDir,
|
|
1000
|
+
harnessDir,
|
|
1001
|
+
workspaceRoot,
|
|
1002
|
+
label: "--out",
|
|
1003
|
+
allowInsideProject: false,
|
|
1004
|
+
});
|
|
1005
|
+
let pubOutAbs = null;
|
|
1006
|
+
if (options.publicKeyOut) {
|
|
1007
|
+
pubOutAbs = validateExternalKeyOutPath(options.publicKeyOut, {
|
|
1008
|
+
projectDir,
|
|
1009
|
+
harnessDir,
|
|
1010
|
+
workspaceRoot,
|
|
1011
|
+
label: "--pub-out",
|
|
1012
|
+
allowInsideProject: true,
|
|
1013
|
+
});
|
|
1014
|
+
if (pubOutAbs === privOutAbs) {
|
|
1015
|
+
throw new Error("--pub-out and --out must point to separate files.");
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
|
|
1020
|
+
const publicKeyPem = publicKey.export({ type: "spki", format: "pem" });
|
|
1021
|
+
const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" });
|
|
1022
|
+
const keyFingerprint = `ed25519:${sha256Hex(publicKeyPem).slice(0, 16)}`;
|
|
1023
|
+
|
|
1024
|
+
const registry = loadApproversRegistry(projectDir);
|
|
1025
|
+
if (registry.approvers.some((a) => a.approver_id === approverId)) {
|
|
1026
|
+
throw new Error(`Approver "${approverId}" is already registered in ${registry.relPath}. Use a unique --approver ID.`);
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
fs.mkdirSync(path.dirname(privOutAbs), { recursive: true });
|
|
1030
|
+
fs.writeFileSync(privOutAbs, privateKeyPem, { encoding: "utf8", mode: 0o600, flag: "wx" });
|
|
1031
|
+
if (pubOutAbs) {
|
|
1032
|
+
fs.mkdirSync(path.dirname(pubOutAbs), { recursive: true });
|
|
1033
|
+
fs.writeFileSync(pubOutAbs, publicKeyPem, { encoding: "utf8", mode: 0o644, flag: "wx" });
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
const regAbs = assertSafeWithinRoot(projectDir, registry.relPath);
|
|
1037
|
+
assertSafeAncestorChain(regAbs, projectDir, registry.relPath);
|
|
1038
|
+
const updated = {
|
|
1039
|
+
schema_version: "1.0",
|
|
1040
|
+
approvers: [
|
|
1041
|
+
...registry.approvers,
|
|
1042
|
+
{
|
|
1043
|
+
approver_id: approverId,
|
|
1044
|
+
algorithm: "ed25519",
|
|
1045
|
+
key_fingerprint: keyFingerprint,
|
|
1046
|
+
created_at: createdAt,
|
|
1047
|
+
public_key_pem: publicKeyPem,
|
|
1048
|
+
},
|
|
1049
|
+
],
|
|
1050
|
+
};
|
|
1051
|
+
atomicWriteFile(regAbs, serializeYaml(updated, { headerComment: "Registered Ed25519 public keys ONLY — never commit private keys" }), {
|
|
1052
|
+
allowOverwrite: true,
|
|
1053
|
+
});
|
|
1054
|
+
|
|
1055
|
+
return {
|
|
1056
|
+
approverId,
|
|
1057
|
+
keyFingerprint,
|
|
1058
|
+
publicKeyPem,
|
|
1059
|
+
registryPath: registry.relPath,
|
|
1060
|
+
privateKeyPath: privOutAbs,
|
|
1061
|
+
publicKeyPath: pubOutAbs,
|
|
1062
|
+
createdAt,
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
function buildApprovalSigningPayload({
|
|
1067
|
+
projectId,
|
|
1068
|
+
action,
|
|
1069
|
+
skillName,
|
|
1070
|
+
proposalId,
|
|
1071
|
+
targetRevision,
|
|
1072
|
+
contentSha256,
|
|
1073
|
+
baseSha256,
|
|
1074
|
+
evidenceDigests,
|
|
1075
|
+
approverId,
|
|
1076
|
+
decidedAt,
|
|
1077
|
+
expiresAt,
|
|
1078
|
+
}) {
|
|
1079
|
+
return JSON.stringify({
|
|
1080
|
+
version: 1,
|
|
1081
|
+
project_id: projectId,
|
|
1082
|
+
action,
|
|
1083
|
+
skill_name: skillName,
|
|
1084
|
+
proposal_id: proposalId || null,
|
|
1085
|
+
target_revision: targetRevision || null,
|
|
1086
|
+
content_sha256: contentSha256,
|
|
1087
|
+
base_sha256: baseSha256 || null,
|
|
1088
|
+
evidence_digests: [...(evidenceDigests || [])].sort(),
|
|
1089
|
+
approver_id: approverId,
|
|
1090
|
+
decided_at: decidedAt,
|
|
1091
|
+
expires_at: expiresAt || null,
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
/**
|
|
1096
|
+
* Resolves exact content SHA-256, base SHA-256, and verified evidence digests for a pending promotion proposal.
|
|
1097
|
+
*/
|
|
1098
|
+
function inspectProposalForGate(projectDir, projectPaths, skillName, harnessDir) {
|
|
1099
|
+
const proposalRel = `${projectPaths.proposals_dir}/skills/${skillName}`;
|
|
1100
|
+
const proposalDir = assertSafeWithinRoot(projectDir, proposalRel);
|
|
1101
|
+
if (!fs.existsSync(proposalDir)) {
|
|
1102
|
+
throw new Error(`Proposal directory not found: ${proposalRel}`);
|
|
1103
|
+
}
|
|
1104
|
+
const metaRel = `${projectPaths.proposals_dir}/skills/.proposals/${skillName}.yaml`;
|
|
1105
|
+
const loadedMeta = readSafeYamlWithinProject(projectDir, metaRel);
|
|
1106
|
+
if (!loadedMeta || !loadedMeta.data) {
|
|
1107
|
+
throw new Error(`Proposal metadata missing: ${metaRel}. Refusing untrusted proposal without provenance.`);
|
|
1108
|
+
}
|
|
1109
|
+
const meta = loadedMeta.data;
|
|
1110
|
+
if (meta.status !== "draft") {
|
|
1111
|
+
throw new Error(`Proposal "${skillName}" is not in "draft" status (got "${meta.status}").`);
|
|
1112
|
+
}
|
|
1113
|
+
if (meta.skill_name !== skillName) {
|
|
1114
|
+
throw new Error(`Proposal metadata skill_name "${meta.skill_name}" mismatches "${skillName}".`);
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
// Re-verify referenced evidence & handoffs fail-closed
|
|
1118
|
+
const sourceEvIds = (meta.source_evidence || []).map((e) => e.id).filter(Boolean);
|
|
1119
|
+
const sourceHoIds = (meta.source_handoffs || []).map((h) => h.id).filter(Boolean);
|
|
1120
|
+
const bundle = loadVerifiedSourceBundle({
|
|
1121
|
+
projectDir,
|
|
1122
|
+
evidenceIds: sourceEvIds,
|
|
1123
|
+
handoffIds: sourceHoIds,
|
|
1124
|
+
harnessDir,
|
|
1125
|
+
});
|
|
1126
|
+
|
|
1127
|
+
// Verify stored evidence SHA-256s match live evidence on disk
|
|
1128
|
+
for (const se of meta.source_evidence || []) {
|
|
1129
|
+
const live = bundle.evidenceList.find((e) => e.data.id === se.id);
|
|
1130
|
+
if (!live || live.sha256 !== se.sha256) {
|
|
1131
|
+
throw new Error(`Evidence ${se.id} changed or missing since proposal was created (fail-closed).`);
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
for (const sh of meta.source_handoffs || []) {
|
|
1135
|
+
const liveH = bundle.handoffRecords.find((h) => h.data.id === sh.id);
|
|
1136
|
+
if (!liveH || liveH.sha256 !== sh.sha256) {
|
|
1137
|
+
throw new Error(`Handoff ${sh.id} changed or missing since proposal was created (fail-closed).`);
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
const verified = validateAndLintSkillStaging({
|
|
1142
|
+
stageDir: proposalDir,
|
|
1143
|
+
skillName,
|
|
1144
|
+
displayRoot: `${projectPaths.proposals_dir}/skills`,
|
|
1145
|
+
});
|
|
1146
|
+
|
|
1147
|
+
if (verified.digestInfo.digest !== meta.candidate_digest) {
|
|
1148
|
+
throw new Error(
|
|
1149
|
+
`Proposal content digest mismatch for "${skillName}" (disk=${verified.digestInfo.digest} vs meta=${meta.candidate_digest}); refusing modified proposal.`
|
|
1150
|
+
);
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
const activeRel = `.agents/skills/${skillName}`;
|
|
1154
|
+
const activeDir = assertSafeWithinRoot(projectDir, activeRel);
|
|
1155
|
+
const activeExists = fs.existsSync(activeDir);
|
|
1156
|
+
let currentBaseSha = null;
|
|
1157
|
+
if (activeExists) {
|
|
1158
|
+
currentBaseSha = computeSkillPackageDigest(activeDir).digest;
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
if (meta.kind === "new_skill") {
|
|
1162
|
+
if (activeExists) {
|
|
1163
|
+
throw new Error(`Conflict: active skill "${skillName}" now exists at ${activeRel}; refusing new_skill promotion.`);
|
|
1164
|
+
}
|
|
1165
|
+
} else if (meta.kind === "update_skill") {
|
|
1166
|
+
if (!activeExists) {
|
|
1167
|
+
throw new Error(`Active skill "${skillName}" missing at ${activeRel}; update proposal cannot apply.`);
|
|
1168
|
+
}
|
|
1169
|
+
if (currentBaseSha !== meta.base_skill_digest) {
|
|
1170
|
+
throw new Error(
|
|
1171
|
+
`Stale/concurrent update conflict: active skill "${skillName}" digest (${currentBaseSha}) no longer matches proposal base (${meta.base_skill_digest}).`
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
} else {
|
|
1175
|
+
throw new Error(`Unsupported proposal kind "${meta.kind}".`);
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
return {
|
|
1179
|
+
proposalRel,
|
|
1180
|
+
proposalDir,
|
|
1181
|
+
metaRel,
|
|
1182
|
+
meta,
|
|
1183
|
+
bundle,
|
|
1184
|
+
candidateDigest: verified.digestInfo.digest,
|
|
1185
|
+
currentBaseSha,
|
|
1186
|
+
action: meta.kind === "new_skill" ? "promote_new" : "promote_update",
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
function createApprovalRecordFile({
|
|
1191
|
+
projectDir,
|
|
1192
|
+
schemasDir,
|
|
1193
|
+
projectPaths,
|
|
1194
|
+
title,
|
|
1195
|
+
status,
|
|
1196
|
+
boundaryCategory,
|
|
1197
|
+
requestedBy,
|
|
1198
|
+
decidedBy,
|
|
1199
|
+
timestamp,
|
|
1200
|
+
expiresAt,
|
|
1201
|
+
targetRecords,
|
|
1202
|
+
rationale,
|
|
1203
|
+
riskAssessment,
|
|
1204
|
+
conditions,
|
|
1205
|
+
skillAuthorization,
|
|
1206
|
+
slugHint,
|
|
1207
|
+
}) {
|
|
1208
|
+
const { id } = scanAndAllocateRecordId({
|
|
1209
|
+
projectDir,
|
|
1210
|
+
searchDirs: [projectPaths.proposals_dir, projectPaths.decisions_dir],
|
|
1211
|
+
prefix: "APPR",
|
|
1212
|
+
});
|
|
1213
|
+
const record = {
|
|
1214
|
+
schema_version: "1.1",
|
|
1215
|
+
id,
|
|
1216
|
+
title,
|
|
1217
|
+
status,
|
|
1218
|
+
memory_layer: "L2_OPERATIONAL",
|
|
1219
|
+
authority_level: "A4",
|
|
1220
|
+
boundary_category: boundaryCategory,
|
|
1221
|
+
requested_by: requestedBy,
|
|
1222
|
+
requested_at: timestamp,
|
|
1223
|
+
decided_by: decidedBy,
|
|
1224
|
+
decided_at: status === "approved" ? timestamp : null,
|
|
1225
|
+
expires_at: expiresAt || null,
|
|
1226
|
+
target_records: targetRecords,
|
|
1227
|
+
rationale,
|
|
1228
|
+
risk_assessment: riskAssessment,
|
|
1229
|
+
conditions,
|
|
1230
|
+
skill_authorization: skillAuthorization,
|
|
1231
|
+
};
|
|
1232
|
+
|
|
1233
|
+
const schema = loadSchema(schemasDir, "approval-record.schema.json");
|
|
1234
|
+
const valid = validateAgainstSchema(record, schema);
|
|
1235
|
+
if (!valid.valid) {
|
|
1236
|
+
throw new Error(`Internal APPR record failed schema validation: ${valid.errors.join("; ")}`);
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
const slug = deriveSlug(slugHint || title) || "skill-approval";
|
|
1240
|
+
const relPath = `${projectPaths.proposals_dir}/${id}-${slug}.yaml`;
|
|
1241
|
+
const absPath = assertSafeWithinRoot(projectDir, relPath);
|
|
1242
|
+
atomicWriteFile(absPath, serializeYaml(record, { headerComment: "GeloForge skill authorization record" }), {
|
|
1243
|
+
allowOverwrite: false,
|
|
1244
|
+
});
|
|
1245
|
+
return { id, relPath, absPath, record };
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
/**
|
|
1249
|
+
* Phase 5: Cryptographically signs an approval (APPR-NNNN) bound to exact content SHA-256,
|
|
1250
|
+
* base SHA-256, source evidence digests, action, and approver identity.
|
|
1251
|
+
*/
|
|
1252
|
+
export function signSkillApproval(options = {}) {
|
|
1253
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
1254
|
+
const loaded = loadProjectManifestAndState(options.projectDir, harnessDir);
|
|
1255
|
+
const { projectDir, schemasDir, manifest, projectPaths } = loaded;
|
|
1256
|
+
|
|
1257
|
+
const decidedAt = validateCreatedAt(options.decidedAt);
|
|
1258
|
+
let expiresAt = null;
|
|
1259
|
+
if (options.expiresAt) {
|
|
1260
|
+
expiresAt = validateCreatedAt(options.expiresAt);
|
|
1261
|
+
if (Date.parse(expiresAt) <= Date.parse(decidedAt)) {
|
|
1262
|
+
throw new Error(`--expires-at (${expiresAt}) must be after --decided-at (${decidedAt}).`);
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
const approverId = validateScalarText("--approver", options.approverId);
|
|
1267
|
+
const privKeyAbs = validateExternalFileReadPath(options.privateKeyPath, projectDir, "--key", { forbidInsideRepo: true });
|
|
1268
|
+
const privateKeyObj = crypto.createPrivateKey(fs.readFileSync(privKeyAbs, "utf8"));
|
|
1269
|
+
if (privateKeyObj.asymmetricKeyType !== "ed25519") {
|
|
1270
|
+
throw new Error(`Private key must be Ed25519 (got ${privateKeyObj.asymmetricKeyType}).`);
|
|
1271
|
+
}
|
|
1272
|
+
const derivedPubPem = crypto.createPublicKey(privateKeyObj).export({ type: "spki", format: "pem" });
|
|
1273
|
+
const keyFingerprint = `ed25519:${sha256Hex(derivedPubPem).slice(0, 16)}`;
|
|
1274
|
+
|
|
1275
|
+
const registry = loadApproversRegistry(projectDir);
|
|
1276
|
+
const regEntry = registry.approvers.find((a) => a.approver_id === approverId);
|
|
1277
|
+
if (!regEntry) {
|
|
1278
|
+
throw new Error(`Approver "${approverId}" is not registered in ${registry.relPath}. Run "geloforge skills keygen" first.`);
|
|
1279
|
+
}
|
|
1280
|
+
if (regEntry.key_fingerprint !== keyFingerprint) {
|
|
1281
|
+
throw new Error(`Private key fingerprint (${keyFingerprint}) does not match registered key (${regEntry.key_fingerprint}) for "${approverId}".`);
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
const reqAction = options.action || "promote";
|
|
1285
|
+
let boundAction;
|
|
1286
|
+
let skillName;
|
|
1287
|
+
let proposalId = null;
|
|
1288
|
+
let targetRevision = null;
|
|
1289
|
+
let contentSha256;
|
|
1290
|
+
let baseSha256 = null;
|
|
1291
|
+
let evidenceDigests = [];
|
|
1292
|
+
let targetRecords = [];
|
|
1293
|
+
|
|
1294
|
+
if (reqAction === "promote") {
|
|
1295
|
+
skillName = validateSkillSlugName(options.skillName || options.proposalName);
|
|
1296
|
+
const gate = inspectProposalForGate(projectDir, projectPaths, skillName, harnessDir);
|
|
1297
|
+
boundAction = gate.action;
|
|
1298
|
+
proposalId = gate.meta.proposal_id;
|
|
1299
|
+
contentSha256 = gate.candidateDigest;
|
|
1300
|
+
baseSha256 = gate.currentBaseSha;
|
|
1301
|
+
evidenceDigests = gate.bundle.evidenceDigests;
|
|
1302
|
+
targetRecords = [gate.proposalRel, ...gate.bundle.evidenceList.map((e) => e.relPath)];
|
|
1303
|
+
} else if (reqAction === "rollback") {
|
|
1304
|
+
skillName = validateSkillSlugName(options.skillName);
|
|
1305
|
+
targetRevision = String(options.targetRevision || "").trim();
|
|
1306
|
+
const gate = inspectRollbackSnapshotForGate(projectDir, skillName, targetRevision);
|
|
1307
|
+
boundAction = "rollback";
|
|
1308
|
+
contentSha256 = gate.targetDigest;
|
|
1309
|
+
baseSha256 = gate.currentBaseSha;
|
|
1310
|
+
evidenceDigests = Array.isArray(gate.entry.evidence_digests) ? gate.entry.evidence_digests : [];
|
|
1311
|
+
targetRecords = [gate.snapshotRel, gate.histInfo.histRel];
|
|
1312
|
+
} else {
|
|
1313
|
+
throw new Error(`Invalid --action "${reqAction}". Expected: promote or rollback.`);
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
const payloadStr = buildApprovalSigningPayload({
|
|
1317
|
+
projectId: manifest.project_id,
|
|
1318
|
+
action: boundAction,
|
|
1319
|
+
skillName,
|
|
1320
|
+
proposalId,
|
|
1321
|
+
targetRevision,
|
|
1322
|
+
contentSha256,
|
|
1323
|
+
baseSha256,
|
|
1324
|
+
evidenceDigests,
|
|
1325
|
+
approverId,
|
|
1326
|
+
decidedAt,
|
|
1327
|
+
expiresAt,
|
|
1328
|
+
});
|
|
1329
|
+
const signatureBase64 = crypto.sign(null, Buffer.from(payloadStr, "utf8"), privateKeyObj).toString("base64");
|
|
1330
|
+
|
|
1331
|
+
const rationale = validateScalarText(
|
|
1332
|
+
"--rationale",
|
|
1333
|
+
options.rationale || `Reviewed ${boundAction} for skill "${skillName}" at ${contentSha256.slice(0, 19)}.`
|
|
1334
|
+
);
|
|
1335
|
+
const riskAssessment = validateScalarText(
|
|
1336
|
+
"--risk-assessment",
|
|
1337
|
+
options.riskAssessment || "Static lint passed; skill remains A5 non-authoritative with zero auto-execution."
|
|
1338
|
+
);
|
|
1339
|
+
|
|
1340
|
+
const appr = createApprovalRecordFile({
|
|
1341
|
+
projectDir,
|
|
1342
|
+
schemasDir,
|
|
1343
|
+
projectPaths,
|
|
1344
|
+
title: `${boundAction} ${skillName}`.slice(0, 80),
|
|
1345
|
+
status: "approved",
|
|
1346
|
+
boundaryCategory: boundAction === "rollback" ? "destructive_action" : "security_boundary",
|
|
1347
|
+
requestedBy: options.requestedBy || approverId,
|
|
1348
|
+
decidedBy: approverId,
|
|
1349
|
+
timestamp: decidedAt,
|
|
1350
|
+
expiresAt,
|
|
1351
|
+
targetRecords,
|
|
1352
|
+
rationale,
|
|
1353
|
+
riskAssessment,
|
|
1354
|
+
conditions: ["Valid only while content_sha256, base_sha256, and source evidence digests remain unchanged."],
|
|
1355
|
+
skillAuthorization: {
|
|
1356
|
+
action: boundAction,
|
|
1357
|
+
skill_name: skillName,
|
|
1358
|
+
proposal_id: proposalId,
|
|
1359
|
+
target_revision: targetRevision,
|
|
1360
|
+
content_sha256: contentSha256,
|
|
1361
|
+
base_sha256: baseSha256,
|
|
1362
|
+
evidence_digests: evidenceDigests,
|
|
1363
|
+
authorization_tier: "cryptographic_ed25519",
|
|
1364
|
+
approver_id: approverId,
|
|
1365
|
+
key_fingerprint: keyFingerprint,
|
|
1366
|
+
signature_algorithm: "ed25519",
|
|
1367
|
+
signature_base64: signatureBase64,
|
|
1368
|
+
},
|
|
1369
|
+
slugHint: `${boundAction}-${skillName}`,
|
|
1370
|
+
});
|
|
1371
|
+
|
|
1372
|
+
return {
|
|
1373
|
+
approvalId: appr.id,
|
|
1374
|
+
relPath: appr.relPath,
|
|
1375
|
+
action: boundAction,
|
|
1376
|
+
skillName,
|
|
1377
|
+
targetRevision,
|
|
1378
|
+
contentSha256,
|
|
1379
|
+
baseSha256,
|
|
1380
|
+
approverId,
|
|
1381
|
+
keyFingerprint,
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
function assertValidIsoTimestamp(value, fieldLabel) {
|
|
1386
|
+
if (typeof value !== "string" || value.trim().length < 10) {
|
|
1387
|
+
throw new Error(`Invalid or missing ISO-8601 timestamp for ${fieldLabel}: "${value}".`);
|
|
1388
|
+
}
|
|
1389
|
+
const parsed = Date.parse(value.trim());
|
|
1390
|
+
if (!Number.isFinite(parsed)) {
|
|
1391
|
+
throw new Error(`Invalid ISO-8601 timestamp for ${fieldLabel}: "${value}".`);
|
|
1392
|
+
}
|
|
1393
|
+
return parsed;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
/**
|
|
1397
|
+
* Verifies a cryptographic Ed25519 APPR-NNNN approval record fail-closed.
|
|
1398
|
+
*/
|
|
1399
|
+
export function verifySignedSkillApproval({
|
|
1400
|
+
projectDir,
|
|
1401
|
+
projectPaths,
|
|
1402
|
+
schemasDir,
|
|
1403
|
+
projectId,
|
|
1404
|
+
approvalId,
|
|
1405
|
+
expectedAction,
|
|
1406
|
+
skillName,
|
|
1407
|
+
expectedProposalId = null,
|
|
1408
|
+
targetRevision = null,
|
|
1409
|
+
expectedContentSha256,
|
|
1410
|
+
expectedBaseSha256 = null,
|
|
1411
|
+
expectedEvidenceDigests = [],
|
|
1412
|
+
publicKeyPath = null,
|
|
1413
|
+
nowIso = new Date().toISOString(),
|
|
1414
|
+
}) {
|
|
1415
|
+
const loadedAppr = findRecordYamlById(projectDir, projectPaths.proposals_dir, "APPR", approvalId);
|
|
1416
|
+
const appr = loadedAppr.data;
|
|
1417
|
+
const schemaRes = validateAgainstSchema(appr, loadSchema(schemasDir, "approval-record.schema.json"));
|
|
1418
|
+
if (!schemaRes.valid) {
|
|
1419
|
+
throw new Error(`${loadedAppr.relPath}: invalid APPR schema: ${schemaRes.errors.join("; ")}`);
|
|
1420
|
+
}
|
|
1421
|
+
if (appr.is_example === true) {
|
|
1422
|
+
throw new Error(`${loadedAppr.relPath}: example approval cannot authorize skills.`);
|
|
1423
|
+
}
|
|
1424
|
+
if (appr.status !== "approved") {
|
|
1425
|
+
throw new Error(`${loadedAppr.relPath}: approval status is "${appr.status}", expected "approved".`);
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
const consumed = findConsumedApprovalInHistory(projectDir, loadedAppr.data.id);
|
|
1429
|
+
if (consumed) {
|
|
1430
|
+
throw new Error(
|
|
1431
|
+
`Approval replay refused (${loadedAppr.relPath}): ${loadedAppr.data.id} was already consumed by skill "${consumed.skillName}" (${consumed.revision} in ${consumed.histRel}). Sign a fresh approval.`
|
|
1432
|
+
);
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
assertValidIsoTimestamp(appr.decided_at, `${loadedAppr.relPath}: decided_at`);
|
|
1436
|
+
const nowMs = assertValidIsoTimestamp(nowIso, "nowIso");
|
|
1437
|
+
if (appr.expires_at !== null && appr.expires_at !== undefined) {
|
|
1438
|
+
const expiresMs = assertValidIsoTimestamp(appr.expires_at, `${loadedAppr.relPath}: expires_at`);
|
|
1439
|
+
if (expiresMs < nowMs) {
|
|
1440
|
+
throw new Error(`${loadedAppr.relPath}: approval expired at ${appr.expires_at}.`);
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
const sa = appr.skill_authorization;
|
|
1445
|
+
if (!sa || sa.authorization_tier !== "cryptographic_ed25519") {
|
|
1446
|
+
throw new Error(
|
|
1447
|
+
`${loadedAppr.relPath}: authorization_tier "${sa?.authorization_tier || "missing"}" is not cryptographic_ed25519; unsigned text approvals cannot bypass human authorization.`
|
|
1448
|
+
);
|
|
1449
|
+
}
|
|
1450
|
+
if (sa.signature_algorithm !== "ed25519" || !sa.signature_base64 || !sa.approver_id || !sa.key_fingerprint) {
|
|
1451
|
+
throw new Error(`${loadedAppr.relPath}: incomplete Ed25519 signature metadata.`);
|
|
1452
|
+
}
|
|
1453
|
+
if (appr.decided_by !== sa.approver_id) {
|
|
1454
|
+
throw new Error(
|
|
1455
|
+
`${loadedAppr.relPath}: decided_by "${appr.decided_by}" mismatches skill_authorization.approver_id "${sa.approver_id}".`
|
|
1456
|
+
);
|
|
1457
|
+
}
|
|
1458
|
+
if (sa.action !== expectedAction || sa.skill_name !== skillName) {
|
|
1459
|
+
throw new Error(
|
|
1460
|
+
`${loadedAppr.relPath}: bound to action="${sa.action}" skill="${sa.skill_name}", expected action="${expectedAction}" skill="${skillName}".`
|
|
1461
|
+
);
|
|
1462
|
+
}
|
|
1463
|
+
if (expectedProposalId !== null && sa.proposal_id !== expectedProposalId) {
|
|
1464
|
+
throw new Error(
|
|
1465
|
+
`${loadedAppr.relPath}: bound proposal_id "${sa.proposal_id}" mismatches "${expectedProposalId}".`
|
|
1466
|
+
);
|
|
1467
|
+
}
|
|
1468
|
+
if ((sa.target_revision || null) !== (targetRevision || null)) {
|
|
1469
|
+
throw new Error(`${loadedAppr.relPath}: bound target_revision "${sa.target_revision}" mismatches "${targetRevision}".`);
|
|
1470
|
+
}
|
|
1471
|
+
if (sa.content_sha256 !== expectedContentSha256) {
|
|
1472
|
+
throw new Error(
|
|
1473
|
+
`Approval digest mismatch (${loadedAppr.relPath}): signed ${sa.content_sha256}, current ${expectedContentSha256}. Re-review and re-sign.`
|
|
1474
|
+
);
|
|
1475
|
+
}
|
|
1476
|
+
if ((sa.base_sha256 || null) !== (expectedBaseSha256 || null)) {
|
|
1477
|
+
throw new Error(
|
|
1478
|
+
`Stale approval (${loadedAppr.relPath}): signed base_sha256=${sa.base_sha256 || "null"} does not match current active skill base=${expectedBaseSha256 || "null"}.`
|
|
1479
|
+
);
|
|
1480
|
+
}
|
|
1481
|
+
const signedEv = JSON.stringify([...(sa.evidence_digests || [])].sort());
|
|
1482
|
+
const curEv = JSON.stringify([...(expectedEvidenceDigests || [])].sort());
|
|
1483
|
+
if (signedEv !== curEv) {
|
|
1484
|
+
throw new Error(`Approval evidence binding mismatch (${loadedAppr.relPath}): source evidence changed after signing.`);
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
if (typeof sa.signature_base64 !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(sa.signature_base64)) {
|
|
1488
|
+
throw new Error(`Cryptographic Ed25519 signature verification failed for ${loadedAppr.relPath}: malformed base64 encoding.`);
|
|
1489
|
+
}
|
|
1490
|
+
const sigBuf = Buffer.from(sa.signature_base64, "base64");
|
|
1491
|
+
if (sigBuf.length !== 64) {
|
|
1492
|
+
throw new Error(
|
|
1493
|
+
`Cryptographic Ed25519 signature verification failed for ${loadedAppr.relPath}: invalid signature byte length (${sigBuf.length}, expected 64).`
|
|
1494
|
+
);
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
let trustedPubPem;
|
|
1498
|
+
let trustedFingerprint;
|
|
1499
|
+
let keyTrustSource;
|
|
1500
|
+
let inRepoRegistryDirty = false;
|
|
1501
|
+
if (publicKeyPath) {
|
|
1502
|
+
keyTrustSource = "external_pinned_public_key";
|
|
1503
|
+
const pubAbs = validateExternalFileReadPath(publicKeyPath, projectDir, "--public-key", { forbidInsideRepo: false });
|
|
1504
|
+
const rawPubPem = fs.readFileSync(pubAbs, "utf8");
|
|
1505
|
+
if (hasSecretContent(rawPubPem)) {
|
|
1506
|
+
throw new Error("--public-key file must contain only an SPKI public key, never private key material.");
|
|
1507
|
+
}
|
|
1508
|
+
let pubObj;
|
|
1509
|
+
try {
|
|
1510
|
+
pubObj = crypto.createPublicKey(rawPubPem);
|
|
1511
|
+
} catch {
|
|
1512
|
+
throw new Error(`Unparseable --public-key PEM file: ${pubAbs}`);
|
|
1513
|
+
}
|
|
1514
|
+
if (pubObj.asymmetricKeyType !== "ed25519") {
|
|
1515
|
+
throw new Error(`Pinned --public-key must be Ed25519 (got ${pubObj.asymmetricKeyType}).`);
|
|
1516
|
+
}
|
|
1517
|
+
trustedPubPem = pubObj.export({ type: "spki", format: "pem" });
|
|
1518
|
+
trustedFingerprint = `ed25519:${sha256Hex(trustedPubPem).slice(0, 16)}`;
|
|
1519
|
+
if (trustedFingerprint !== sa.key_fingerprint) {
|
|
1520
|
+
throw new Error(`Pinned --public-key fingerprint (${trustedFingerprint}) mismatches approval (${sa.key_fingerprint}).`);
|
|
1521
|
+
}
|
|
1522
|
+
} else {
|
|
1523
|
+
keyTrustSource = "in_repo_registry";
|
|
1524
|
+
const registry = loadApproversRegistry(projectDir);
|
|
1525
|
+
const regEntry = registry.approvers.find((a) => a.approver_id === sa.approver_id);
|
|
1526
|
+
if (!regEntry) {
|
|
1527
|
+
throw new Error(`Approver "${sa.approver_id}" not found in ${registry.relPath}.`);
|
|
1528
|
+
}
|
|
1529
|
+
let regPubObj;
|
|
1530
|
+
try {
|
|
1531
|
+
regPubObj = crypto.createPublicKey(regEntry.public_key_pem);
|
|
1532
|
+
} catch {
|
|
1533
|
+
throw new Error(`Unparseable public key for approver "${sa.approver_id}" in ${registry.relPath}.`);
|
|
1534
|
+
}
|
|
1535
|
+
if (regPubObj.asymmetricKeyType !== "ed25519") {
|
|
1536
|
+
throw new Error(`Registered key for approver "${sa.approver_id}" must be Ed25519.`);
|
|
1537
|
+
}
|
|
1538
|
+
trustedPubPem = regPubObj.export({ type: "spki", format: "pem" });
|
|
1539
|
+
trustedFingerprint = `ed25519:${sha256Hex(trustedPubPem).slice(0, 16)}`;
|
|
1540
|
+
const rawFp = `ed25519:${sha256Hex(regEntry.public_key_pem).slice(0, 16)}`;
|
|
1541
|
+
if (
|
|
1542
|
+
regEntry.key_fingerprint !== sa.key_fingerprint ||
|
|
1543
|
+
(trustedFingerprint !== sa.key_fingerprint && rawFp !== sa.key_fingerprint)
|
|
1544
|
+
) {
|
|
1545
|
+
throw new Error(`Public key fingerprint mismatch for approver "${sa.approver_id}".`);
|
|
1546
|
+
}
|
|
1547
|
+
const gitInfo = getGitRepoInfo(projectDir);
|
|
1548
|
+
if (gitInfo.available) {
|
|
1549
|
+
const gs = getGitStatusScoped(projectDir);
|
|
1550
|
+
inRepoRegistryDirty = gs.changedFiles.includes(registry.relPath);
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
const payloadStr = buildApprovalSigningPayload({
|
|
1555
|
+
projectId,
|
|
1556
|
+
action: sa.action,
|
|
1557
|
+
skillName: sa.skill_name,
|
|
1558
|
+
proposalId: sa.proposal_id,
|
|
1559
|
+
targetRevision: sa.target_revision,
|
|
1560
|
+
contentSha256: sa.content_sha256,
|
|
1561
|
+
baseSha256: sa.base_sha256,
|
|
1562
|
+
evidenceDigests: sa.evidence_digests,
|
|
1563
|
+
approverId: sa.approver_id,
|
|
1564
|
+
decidedAt: appr.decided_at,
|
|
1565
|
+
expiresAt: appr.expires_at,
|
|
1566
|
+
});
|
|
1567
|
+
let ok = false;
|
|
1568
|
+
try {
|
|
1569
|
+
ok = crypto.verify(
|
|
1570
|
+
null,
|
|
1571
|
+
Buffer.from(payloadStr, "utf8"),
|
|
1572
|
+
crypto.createPublicKey(trustedPubPem),
|
|
1573
|
+
sigBuf
|
|
1574
|
+
);
|
|
1575
|
+
} catch {
|
|
1576
|
+
ok = false;
|
|
1577
|
+
}
|
|
1578
|
+
if (!ok) {
|
|
1579
|
+
throw new Error(`Cryptographic Ed25519 signature verification failed for ${loadedAppr.relPath}.`);
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
return {
|
|
1583
|
+
approvalId: loadedAppr.data.id,
|
|
1584
|
+
relPath: loadedAppr.relPath,
|
|
1585
|
+
tier: "cryptographic_ed25519",
|
|
1586
|
+
approverId: sa.approver_id,
|
|
1587
|
+
keyFingerprint: sa.key_fingerprint,
|
|
1588
|
+
keyTrustSource,
|
|
1589
|
+
inRepoRegistryDirty,
|
|
1590
|
+
};
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
function assertAuthorizedOperation({
|
|
1594
|
+
projectDir,
|
|
1595
|
+
projectPaths,
|
|
1596
|
+
schemasDir,
|
|
1597
|
+
manifest,
|
|
1598
|
+
expectedAction,
|
|
1599
|
+
skillName,
|
|
1600
|
+
expectedProposalId = null,
|
|
1601
|
+
targetRevision = null,
|
|
1602
|
+
contentSha256,
|
|
1603
|
+
baseSha256,
|
|
1604
|
+
evidenceDigests,
|
|
1605
|
+
targetRecords,
|
|
1606
|
+
approvalId,
|
|
1607
|
+
publicKeyPath = null,
|
|
1608
|
+
mode,
|
|
1609
|
+
branch,
|
|
1610
|
+
approvedBy,
|
|
1611
|
+
interactiveConfirm,
|
|
1612
|
+
timestamp,
|
|
1613
|
+
slugHint,
|
|
1614
|
+
rationale,
|
|
1615
|
+
}) {
|
|
1616
|
+
if (approvedBy) {
|
|
1617
|
+
throw new Error(
|
|
1618
|
+
`Security refusal: self-reported --approved-by "${approvedBy}" cannot authorize "${expectedAction}". Use --approval <APPR-NNNN> (Ed25519), --mode pr-branch, or explicit --interactive TTY confirmation.`
|
|
1619
|
+
);
|
|
1620
|
+
}
|
|
1621
|
+
if (approvalId && mode) {
|
|
1622
|
+
throw new Error("Cannot combine --approval with --mode or --interactive; specify exactly one authorization mode.");
|
|
1623
|
+
}
|
|
1624
|
+
if (publicKeyPath && !approvalId) {
|
|
1625
|
+
throw new Error("--public-key requires --approval <APPR-NNNN>.");
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
const chosenMode = approvalId ? "approval" : mode || null;
|
|
1629
|
+
if (!chosenMode || !ALLOWED_AUTHORIZATION_MODES.has(chosenMode)) {
|
|
1630
|
+
throw new Error(
|
|
1631
|
+
`Authorization required for "${expectedAction}" on "${skillName}". Supply one of: --approval <APPR-NNNN>, --mode pr-branch, or --interactive (real TTY).`
|
|
1632
|
+
);
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
if (chosenMode === "approval") {
|
|
1636
|
+
const verified = verifySignedSkillApproval({
|
|
1637
|
+
projectDir,
|
|
1638
|
+
projectPaths,
|
|
1639
|
+
schemasDir,
|
|
1640
|
+
projectId: manifest.project_id,
|
|
1641
|
+
approvalId,
|
|
1642
|
+
expectedAction,
|
|
1643
|
+
skillName,
|
|
1644
|
+
expectedProposalId,
|
|
1645
|
+
targetRevision,
|
|
1646
|
+
expectedContentSha256: contentSha256,
|
|
1647
|
+
expectedBaseSha256: baseSha256,
|
|
1648
|
+
expectedEvidenceDigests: evidenceDigests,
|
|
1649
|
+
publicKeyPath,
|
|
1650
|
+
nowIso: timestamp,
|
|
1651
|
+
});
|
|
1652
|
+
return {
|
|
1653
|
+
tier: "cryptographic_ed25519",
|
|
1654
|
+
approvalId: verified.approvalId,
|
|
1655
|
+
approvalRelPath: verified.relPath,
|
|
1656
|
+
approverId: verified.approverId,
|
|
1657
|
+
keyFingerprint: verified.keyFingerprint,
|
|
1658
|
+
keyTrustSource: verified.keyTrustSource,
|
|
1659
|
+
inRepoRegistryDirty: verified.inRepoRegistryDirty,
|
|
1660
|
+
prBranch: null,
|
|
1661
|
+
};
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
if (chosenMode === "interactive") {
|
|
1665
|
+
if (typeof interactiveConfirm !== "function") {
|
|
1666
|
+
throw new Error("--interactive requires an interactive TTY confirmation handler.");
|
|
1667
|
+
}
|
|
1668
|
+
const token = `${expectedAction === "rollback" ? "rollback" : "promote"} ${skillName} ${contentSha256.slice(7, 15)}`;
|
|
1669
|
+
const confirmed = interactiveConfirm({
|
|
1670
|
+
action: expectedAction,
|
|
1671
|
+
skillName,
|
|
1672
|
+
targetRevision,
|
|
1673
|
+
contentSha256,
|
|
1674
|
+
baseSha256,
|
|
1675
|
+
expectedInput: token,
|
|
1676
|
+
});
|
|
1677
|
+
if (confirmed !== true) {
|
|
1678
|
+
throw new Error(`Interactive confirmation aborted or did not match "${token}".`);
|
|
1679
|
+
}
|
|
1680
|
+
const appr = createApprovalRecordFile({
|
|
1681
|
+
projectDir,
|
|
1682
|
+
schemasDir,
|
|
1683
|
+
projectPaths,
|
|
1684
|
+
title: `Interactive ${expectedAction} ${skillName}`.slice(0, 80),
|
|
1685
|
+
status: "approved",
|
|
1686
|
+
boundaryCategory: expectedAction === "rollback" ? "destructive_action" : "security_boundary",
|
|
1687
|
+
requestedBy: "local-operator",
|
|
1688
|
+
decidedBy: "local-interactive-tty",
|
|
1689
|
+
timestamp,
|
|
1690
|
+
expiresAt: null,
|
|
1691
|
+
targetRecords,
|
|
1692
|
+
rationale,
|
|
1693
|
+
riskAssessment:
|
|
1694
|
+
"LOCAL CONVENIENCE AUTHORIZATION ONLY: TTY confirmation is weaker than independent Ed25519 signatures or protected-branch PR reviews and relies on local operator integrity.",
|
|
1695
|
+
conditions: [
|
|
1696
|
+
"Not cryptographically signed.",
|
|
1697
|
+
`Confirmed interactive prompt digest ${contentSha256.slice(0, 19)}.`,
|
|
1698
|
+
],
|
|
1699
|
+
skillAuthorization: {
|
|
1700
|
+
action: expectedAction,
|
|
1701
|
+
skill_name: skillName,
|
|
1702
|
+
proposal_id: expectedAction === "rollback" ? null : `PROP-${skillName}`,
|
|
1703
|
+
target_revision: targetRevision,
|
|
1704
|
+
content_sha256: contentSha256,
|
|
1705
|
+
base_sha256: baseSha256,
|
|
1706
|
+
evidence_digests: evidenceDigests,
|
|
1707
|
+
authorization_tier: "local_interactive_tty",
|
|
1708
|
+
approver_id: "local-interactive-tty",
|
|
1709
|
+
key_fingerprint: null,
|
|
1710
|
+
signature_algorithm: null,
|
|
1711
|
+
signature_base64: null,
|
|
1712
|
+
},
|
|
1713
|
+
slugHint,
|
|
1714
|
+
});
|
|
1715
|
+
return {
|
|
1716
|
+
tier: "local_interactive_tty",
|
|
1717
|
+
approvalId: appr.id,
|
|
1718
|
+
approvalRelPath: appr.relPath,
|
|
1719
|
+
approverId: "local-interactive-tty",
|
|
1720
|
+
keyFingerprint: null,
|
|
1721
|
+
keyTrustSource: null,
|
|
1722
|
+
inRepoRegistryDirty: false,
|
|
1723
|
+
prBranch: null,
|
|
1724
|
+
};
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
// pr-branch mode: verify clean Git root (aside from proposals/skills/) and prepare dedicated branch + pending APPR
|
|
1728
|
+
const gitInfo = getGitRepoInfo(projectDir);
|
|
1729
|
+
if (!gitInfo.available || !gitInfo.isRepoRoot) {
|
|
1730
|
+
throw new Error("--mode pr-branch requires the project directory to be a Git repository root.");
|
|
1731
|
+
}
|
|
1732
|
+
if (gitInfo.unborn) {
|
|
1733
|
+
throw new Error("--mode pr-branch requires an existing base commit (HEAD is unborn). Commit initial files first.");
|
|
1734
|
+
}
|
|
1735
|
+
const gs = getGitStatusScoped(projectDir);
|
|
1736
|
+
const proposalsSkillsPrefix = `${projectPaths.proposals_dir.replace(/\\/g, "/")}/skills/`;
|
|
1737
|
+
const outsideDirty = gs.changedFiles.filter((f) => !f.startsWith(proposalsSkillsPrefix));
|
|
1738
|
+
if (outsideDirty.length > 0) {
|
|
1739
|
+
throw new Error(
|
|
1740
|
+
`--mode pr-branch requires a clean Git working tree outside ${proposalsSkillsPrefix}. Dirty files: ${outsideDirty.join(", ")}`
|
|
1741
|
+
);
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
const defaultBranch = `skill-${expectedAction === "rollback" ? "rollback" : "promote"}/${skillName}-${contentSha256.slice(7, 15)}`;
|
|
1745
|
+
const targetBranch = validateScalarText("--branch", branch || defaultBranch);
|
|
1746
|
+
if (/\s|\.\./.test(targetBranch)) {
|
|
1747
|
+
throw new Error(`Invalid Git branch name "${targetBranch}".`);
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
// Fail closed BEFORE mutating any skill files if targetBranch already exists
|
|
1751
|
+
try {
|
|
1752
|
+
execFileSync("git", ["-C", projectDir, "show-ref", "--verify", "--quiet", `refs/heads/${targetBranch}`], {
|
|
1753
|
+
windowsHide: true,
|
|
1754
|
+
stdio: "ignore",
|
|
1755
|
+
});
|
|
1756
|
+
throw new Error(`Git branch "${targetBranch}" already exists. Specify a different --branch.`);
|
|
1757
|
+
} catch (err) {
|
|
1758
|
+
if (err.message && err.message.startsWith("Git branch ")) {
|
|
1759
|
+
throw err;
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
return {
|
|
1764
|
+
tier: "git_pr_review_pending",
|
|
1765
|
+
approvalId: null,
|
|
1766
|
+
approvalRelPath: null,
|
|
1767
|
+
approverId: null,
|
|
1768
|
+
keyFingerprint: null,
|
|
1769
|
+
keyTrustSource: null,
|
|
1770
|
+
inRepoRegistryDirty: false,
|
|
1771
|
+
prBranch: targetBranch,
|
|
1772
|
+
};
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
function isTrackedInGitHead(projectDir, relPath) {
|
|
1776
|
+
try {
|
|
1777
|
+
execFileSync("git", ["-C", projectDir, "ls-files", "--error-unmatch", "--", relPath], {
|
|
1778
|
+
windowsHide: true,
|
|
1779
|
+
stdio: "ignore",
|
|
1780
|
+
});
|
|
1781
|
+
return true;
|
|
1782
|
+
} catch {
|
|
1783
|
+
return false;
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
/**
|
|
1788
|
+
* Shared transactional staging, history ledger update, atomic swap, proposal retirement,
|
|
1789
|
+
* and optional PR-branch commit helper with full failure rollback.
|
|
1790
|
+
*/
|
|
1791
|
+
function applyAuthorizedSkillPackageChange({
|
|
1792
|
+
projectDir,
|
|
1793
|
+
projectPaths,
|
|
1794
|
+
schemasDir,
|
|
1795
|
+
sourcePackageDir,
|
|
1796
|
+
expectedDigest,
|
|
1797
|
+
baseSha256,
|
|
1798
|
+
skillName,
|
|
1799
|
+
action,
|
|
1800
|
+
auth,
|
|
1801
|
+
evidenceDigests,
|
|
1802
|
+
timestamp,
|
|
1803
|
+
restoredFromRevision = null,
|
|
1804
|
+
reason,
|
|
1805
|
+
targetRecords,
|
|
1806
|
+
proposalMetaUpdate = null,
|
|
1807
|
+
extraStagePaths = [],
|
|
1808
|
+
}) {
|
|
1809
|
+
const activeRel = `.agents/skills/${skillName}`;
|
|
1810
|
+
const activeAbs = assertSafeWithinRoot(projectDir, activeRel);
|
|
1811
|
+
const skillsParentAbs = path.dirname(activeAbs);
|
|
1812
|
+
fs.mkdirSync(skillsParentAbs, { recursive: true });
|
|
1813
|
+
assertSafeDirNonSymlink(skillsParentAbs, ".agents/skills");
|
|
1814
|
+
|
|
1815
|
+
const stageDir = path.join(skillsParentAbs, `.geloforge-stage-${crypto.randomBytes(6).toString("hex")}`);
|
|
1816
|
+
let checkedOutPrBranch = false;
|
|
1817
|
+
let origHeadRef = null;
|
|
1818
|
+
let pendingAppr = null;
|
|
1819
|
+
let revInfo = null;
|
|
1820
|
+
let swapHandle = null;
|
|
1821
|
+
let proposalBackupDir = null;
|
|
1822
|
+
let origMetaRaw = null;
|
|
1823
|
+
let metaAbs = null;
|
|
1824
|
+
let prDetails = null;
|
|
1825
|
+
|
|
1826
|
+
try {
|
|
1827
|
+
if (auth.tier === "git_pr_review_pending") {
|
|
1828
|
+
const curBranch = execFileSync("git", ["-C", projectDir, "rev-parse", "--abbrev-ref", "HEAD"], {
|
|
1829
|
+
encoding: "utf8",
|
|
1830
|
+
windowsHide: true,
|
|
1831
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1832
|
+
}).trim();
|
|
1833
|
+
origHeadRef =
|
|
1834
|
+
curBranch === "HEAD"
|
|
1835
|
+
? execFileSync("git", ["-C", projectDir, "rev-parse", "HEAD"], {
|
|
1836
|
+
encoding: "utf8",
|
|
1837
|
+
windowsHide: true,
|
|
1838
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1839
|
+
}).trim()
|
|
1840
|
+
: curBranch;
|
|
1841
|
+
|
|
1842
|
+
execFileSync("git", ["-C", projectDir, "checkout", "-b", auth.prBranch], {
|
|
1843
|
+
encoding: "utf8",
|
|
1844
|
+
windowsHide: true,
|
|
1845
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1846
|
+
});
|
|
1847
|
+
checkedOutPrBranch = true;
|
|
1848
|
+
|
|
1849
|
+
pendingAppr = createApprovalRecordFile({
|
|
1850
|
+
projectDir,
|
|
1851
|
+
schemasDir,
|
|
1852
|
+
projectPaths,
|
|
1853
|
+
title: `PR Review Pending ${action} ${skillName}`.slice(0, 80),
|
|
1854
|
+
status: "pending",
|
|
1855
|
+
boundaryCategory: action === "rollback" ? "destructive_action" : "security_boundary",
|
|
1856
|
+
requestedBy: "geloforge-cli",
|
|
1857
|
+
decidedBy: null,
|
|
1858
|
+
timestamp,
|
|
1859
|
+
expiresAt: null,
|
|
1860
|
+
targetRecords,
|
|
1861
|
+
rationale: reason,
|
|
1862
|
+
riskAssessment:
|
|
1863
|
+
"STAGED ON REVIEW BRANCH ONLY: Requires repository branch protection and an independent human PR approval before merging to main. Without protected-branch enforcement, Git PR review is advisory only.",
|
|
1864
|
+
conditions: [
|
|
1865
|
+
`Must be merged to protected main after human review on branch ${auth.prBranch}.`,
|
|
1866
|
+
`Verify ${expectedDigest} matches reviewed .agents/skills/${skillName}.`,
|
|
1867
|
+
],
|
|
1868
|
+
skillAuthorization: {
|
|
1869
|
+
action,
|
|
1870
|
+
skill_name: skillName,
|
|
1871
|
+
proposal_id: action === "rollback" ? null : `PROP-${skillName}`,
|
|
1872
|
+
target_revision: restoredFromRevision,
|
|
1873
|
+
content_sha256: expectedDigest,
|
|
1874
|
+
base_sha256: baseSha256,
|
|
1875
|
+
evidence_digests: evidenceDigests,
|
|
1876
|
+
authorization_tier: "git_pr_review_pending",
|
|
1877
|
+
approver_id: null,
|
|
1878
|
+
key_fingerprint: null,
|
|
1879
|
+
signature_algorithm: null,
|
|
1880
|
+
signature_base64: null,
|
|
1881
|
+
},
|
|
1882
|
+
slugHint: `pr-${action}-${skillName}`,
|
|
1883
|
+
});
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
copyTreeSafe(sourcePackageDir, stageDir);
|
|
1887
|
+
if (computeSkillPackageDigest(stageDir).digest !== expectedDigest) {
|
|
1888
|
+
throw new Error(`Staged package digest mismatch; aborting ${action}.`);
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
const effectiveApprovalId = pendingAppr ? pendingAppr.id : auth.approvalId;
|
|
1892
|
+
revInfo = recordHistoryRevision({
|
|
1893
|
+
projectDir,
|
|
1894
|
+
skillName,
|
|
1895
|
+
action,
|
|
1896
|
+
sourceDirToSnapshot: stageDir,
|
|
1897
|
+
packageSha256: expectedDigest,
|
|
1898
|
+
baseSha256,
|
|
1899
|
+
approvalId: effectiveApprovalId,
|
|
1900
|
+
authorizationTier: auth.tier,
|
|
1901
|
+
approverId: auth.approverId,
|
|
1902
|
+
evidenceDigests,
|
|
1903
|
+
createdAt: timestamp,
|
|
1904
|
+
restoredFromRevision,
|
|
1905
|
+
reason,
|
|
1906
|
+
});
|
|
1907
|
+
|
|
1908
|
+
swapHandle = stageAtomicSwap(stageDir, activeAbs);
|
|
1909
|
+
|
|
1910
|
+
if (proposalMetaUpdate) {
|
|
1911
|
+
metaAbs = assertSafeWithinRoot(projectDir, proposalMetaUpdate.metaRel);
|
|
1912
|
+
origMetaRaw = fs.existsSync(metaAbs) ? fs.readFileSync(metaAbs, "utf8") : null;
|
|
1913
|
+
const updatedMeta = {
|
|
1914
|
+
...proposalMetaUpdate.meta,
|
|
1915
|
+
status: auth.tier === "git_pr_review_pending" ? "pending_pr_review" : "promoted",
|
|
1916
|
+
promoted_at: timestamp,
|
|
1917
|
+
promoted_revision: revInfo.revision,
|
|
1918
|
+
authorization_tier: auth.tier,
|
|
1919
|
+
approval_ref: effectiveApprovalId,
|
|
1920
|
+
};
|
|
1921
|
+
atomicWriteFile(metaAbs, serializeYaml(updatedMeta), { allowOverwrite: true });
|
|
1922
|
+
const propParent = path.dirname(proposalMetaUpdate.proposalDir);
|
|
1923
|
+
proposalBackupDir = path.join(propParent, `.geloforge-prop-backup-${crypto.randomBytes(6).toString("hex")}`);
|
|
1924
|
+
renameSyncRetry(proposalMetaUpdate.proposalDir, proposalBackupDir);
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
if (auth.tier === "git_pr_review_pending") {
|
|
1928
|
+
const startBranch = getGitRepoInfo(projectDir).branch || auth.prBranch;
|
|
1929
|
+
const snapRels = (revInfo.createdSnapshotDirs || []).map((abs) => path.relative(projectDir, abs).replace(/\\/g, "/"));
|
|
1930
|
+
const stageList = Array.from(
|
|
1931
|
+
new Set([activeRel, revInfo.historyRel, ...snapRels, ...extraStagePaths, pendingAppr.relPath])
|
|
1932
|
+
).filter((rel) => fs.existsSync(assertSafeWithinRoot(projectDir, rel)) || isTrackedInGitHead(projectDir, rel));
|
|
1933
|
+
|
|
1934
|
+
execFileSync("git", ["-C", projectDir, "add", "--all", "--", ...stageList], {
|
|
1935
|
+
encoding: "utf8",
|
|
1936
|
+
windowsHide: true,
|
|
1937
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1938
|
+
});
|
|
1939
|
+
execFileSync(
|
|
1940
|
+
"git",
|
|
1941
|
+
["-C", projectDir, "commit", "-m", `skills(${skillName}): ${action} (${expectedDigest.slice(0, 19)})`],
|
|
1942
|
+
{ encoding: "utf8", windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }
|
|
1943
|
+
);
|
|
1944
|
+
const commitSha = execFileSync("git", ["-C", projectDir, "rev-parse", "HEAD"], {
|
|
1945
|
+
encoding: "utf8",
|
|
1946
|
+
windowsHide: true,
|
|
1947
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1948
|
+
}).trim();
|
|
1949
|
+
prDetails = {
|
|
1950
|
+
approvalId: pendingAppr.id,
|
|
1951
|
+
approvalRelPath: pendingAppr.relPath,
|
|
1952
|
+
branch: startBranch,
|
|
1953
|
+
commitSha,
|
|
1954
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
swapHandle.commit();
|
|
1958
|
+
if (proposalBackupDir) {
|
|
1959
|
+
removeDirSafe(proposalBackupDir);
|
|
1960
|
+
}
|
|
1961
|
+
} catch (err) {
|
|
1962
|
+
try {
|
|
1963
|
+
if (swapHandle) swapHandle.rollback();
|
|
1964
|
+
} catch {
|
|
1965
|
+
// Best-effort restore
|
|
1966
|
+
}
|
|
1967
|
+
try {
|
|
1968
|
+
if (proposalBackupDir && fs.existsSync(proposalBackupDir) && proposalMetaUpdate && !fs.existsSync(proposalMetaUpdate.proposalDir)) {
|
|
1969
|
+
renameSyncRetry(proposalBackupDir, proposalMetaUpdate.proposalDir);
|
|
1970
|
+
}
|
|
1971
|
+
} catch {
|
|
1972
|
+
// Best-effort restore
|
|
1973
|
+
}
|
|
1974
|
+
try {
|
|
1975
|
+
if (metaAbs) {
|
|
1976
|
+
if (origMetaRaw !== null) {
|
|
1977
|
+
atomicWriteFile(metaAbs, origMetaRaw, { allowOverwrite: true });
|
|
1978
|
+
} else if (fs.existsSync(metaAbs)) {
|
|
1979
|
+
fs.rmSync(metaAbs, { force: true });
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
} catch {
|
|
1983
|
+
// Best-effort restore
|
|
1984
|
+
}
|
|
1985
|
+
try {
|
|
1986
|
+
if (revInfo) {
|
|
1987
|
+
if (revInfo.previousHistoryRaw !== null) {
|
|
1988
|
+
atomicWriteFile(revInfo.historyAbs, revInfo.previousHistoryRaw, { allowOverwrite: true });
|
|
1989
|
+
} else if (fs.existsSync(revInfo.historyAbs)) {
|
|
1990
|
+
fs.rmSync(revInfo.historyAbs, { force: true });
|
|
1991
|
+
}
|
|
1992
|
+
for (const sDir of revInfo.createdSnapshotDirs || []) {
|
|
1993
|
+
removeDirSafe(sDir);
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
} catch {
|
|
1997
|
+
// Best-effort restore
|
|
1998
|
+
}
|
|
1999
|
+
try {
|
|
2000
|
+
if (pendingAppr && fs.existsSync(pendingAppr.absPath)) {
|
|
2001
|
+
fs.rmSync(pendingAppr.absPath, { force: true });
|
|
2002
|
+
}
|
|
2003
|
+
} catch {
|
|
2004
|
+
// Best-effort restore
|
|
2005
|
+
}
|
|
2006
|
+
removeDirSafe(stageDir);
|
|
2007
|
+
if (checkedOutPrBranch && origHeadRef) {
|
|
2008
|
+
try {
|
|
2009
|
+
execFileSync("git", ["-C", projectDir, "reset", "--mixed"], {
|
|
2010
|
+
windowsHide: true,
|
|
2011
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
2012
|
+
});
|
|
2013
|
+
execFileSync("git", ["-C", projectDir, "checkout", origHeadRef], {
|
|
2014
|
+
windowsHide: true,
|
|
2015
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
2016
|
+
});
|
|
2017
|
+
execFileSync("git", ["-C", projectDir, "branch", "-D", auth.prBranch], {
|
|
2018
|
+
windowsHide: true,
|
|
2019
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
2020
|
+
});
|
|
2021
|
+
} catch {
|
|
2022
|
+
// Best-effort Git branch cleanup
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
throw err;
|
|
2026
|
+
}
|
|
2027
|
+
|
|
2028
|
+
let authorizationWarning = null;
|
|
2029
|
+
if (auth.tier === "local_interactive_tty") {
|
|
2030
|
+
authorizationWarning =
|
|
2031
|
+
"Authorized via local TTY confirmation (weaker than independent Ed25519 signature or protected-branch PR review).";
|
|
2032
|
+
} else if (auth.tier === "git_pr_review_pending") {
|
|
2033
|
+
authorizationWarning = `Committed on branch "${prDetails.branch}" ONLY (not pushed). Security depends on Git branch protection & required human PR reviews before merging.`;
|
|
2034
|
+
} else if (auth.tier === "cryptographic_ed25519" && auth.keyTrustSource === "in_repo_registry") {
|
|
2035
|
+
authorizationWarning =
|
|
2036
|
+
`Verified against mutable in-repo .geloforge/approvers.yaml${auth.inRepoRegistryDirty ? " (uncommitted in Git)" : ""}. ` +
|
|
2037
|
+
"Local processes/agents with workspace write access can run keygen or edit this file; pin external --public-key <file> or enforce protected-branch PR reviews + CODEOWNERS for independent human authorization.";
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
return {
|
|
2041
|
+
activeRel,
|
|
2042
|
+
revInfo,
|
|
2043
|
+
prDetails,
|
|
2044
|
+
authorizationWarning,
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
/**
|
|
2049
|
+
* Phase 5: Promotes a quarantined proposal into `.agents/skills/<name>/` after verifying
|
|
2050
|
+
* proposal integrity, evidence hashes, strict lint, base digest, and human authorization.
|
|
2051
|
+
*/
|
|
2052
|
+
export function promoteSkillProposal(options = {}) {
|
|
2053
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
2054
|
+
const loaded = loadProjectManifestAndState(options.projectDir, harnessDir);
|
|
2055
|
+
const { projectDir, schemasDir, manifest, projectPaths } = loaded;
|
|
2056
|
+
const skillName = validateSkillSlugName(options.proposalName || options.skillName);
|
|
2057
|
+
const timestamp = validateCreatedAt(options.createdAt);
|
|
2058
|
+
|
|
2059
|
+
const gate = inspectProposalForGate(projectDir, projectPaths, skillName, harnessDir);
|
|
2060
|
+
|
|
2061
|
+
if (options.dryRun) {
|
|
2062
|
+
return {
|
|
2063
|
+
dryRun: true,
|
|
2064
|
+
action: gate.action,
|
|
2065
|
+
skillName,
|
|
2066
|
+
candidateDigest: gate.candidateDigest,
|
|
2067
|
+
baseSha256: gate.currentBaseSha,
|
|
2068
|
+
evidenceDigests: gate.bundle.evidenceDigests,
|
|
2069
|
+
proposalDir: gate.proposalRel,
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
const auth = assertAuthorizedOperation({
|
|
2074
|
+
projectDir,
|
|
2075
|
+
projectPaths,
|
|
2076
|
+
schemasDir,
|
|
2077
|
+
manifest,
|
|
2078
|
+
expectedAction: gate.action,
|
|
2079
|
+
skillName,
|
|
2080
|
+
expectedProposalId: gate.meta.proposal_id,
|
|
2081
|
+
targetRevision: null,
|
|
2082
|
+
contentSha256: gate.candidateDigest,
|
|
2083
|
+
baseSha256: gate.currentBaseSha,
|
|
2084
|
+
evidenceDigests: gate.bundle.evidenceDigests,
|
|
2085
|
+
targetRecords: [gate.proposalRel, ...gate.bundle.evidenceList.map((e) => e.relPath)],
|
|
2086
|
+
approvalId: options.approvalId,
|
|
2087
|
+
publicKeyPath: options.publicKeyPath,
|
|
2088
|
+
mode: options.mode,
|
|
2089
|
+
branch: options.branch,
|
|
2090
|
+
approvedBy: options.approvedBy,
|
|
2091
|
+
interactiveConfirm: options.interactiveConfirm,
|
|
2092
|
+
timestamp,
|
|
2093
|
+
slugHint: `${gate.action}-${skillName}`,
|
|
2094
|
+
rationale: gate.meta.reason || `Promote ${skillName} backed by ${gate.bundle.evidenceDigests.join(", ")}.`,
|
|
2095
|
+
});
|
|
2096
|
+
|
|
2097
|
+
const activeRel = `.agents/skills/${skillName}`;
|
|
2098
|
+
const applied = applyAuthorizedSkillPackageChange({
|
|
2099
|
+
projectDir,
|
|
2100
|
+
projectPaths,
|
|
2101
|
+
schemasDir,
|
|
2102
|
+
sourcePackageDir: gate.proposalDir,
|
|
2103
|
+
expectedDigest: gate.candidateDigest,
|
|
2104
|
+
baseSha256: gate.currentBaseSha,
|
|
2105
|
+
skillName,
|
|
2106
|
+
action: gate.action,
|
|
2107
|
+
auth,
|
|
2108
|
+
evidenceDigests: gate.bundle.evidenceDigests,
|
|
2109
|
+
timestamp,
|
|
2110
|
+
restoredFromRevision: null,
|
|
2111
|
+
reason: gate.meta.reason,
|
|
2112
|
+
targetRecords: [activeRel, ...gate.bundle.evidenceList.map((e) => e.relPath)],
|
|
2113
|
+
extraStagePaths: [gate.metaRel, gate.proposalRel],
|
|
2114
|
+
proposalMetaUpdate: {
|
|
2115
|
+
metaRel: gate.metaRel,
|
|
2116
|
+
meta: gate.meta,
|
|
2117
|
+
proposalDir: gate.proposalDir,
|
|
2118
|
+
},
|
|
2119
|
+
});
|
|
2120
|
+
|
|
2121
|
+
return {
|
|
2122
|
+
dryRun: false,
|
|
2123
|
+
action: gate.action,
|
|
2124
|
+
skillName,
|
|
2125
|
+
activeRel: applied.activeRel,
|
|
2126
|
+
revision: applied.revInfo.revision,
|
|
2127
|
+
snapshotRel: applied.revInfo.snapshotRel,
|
|
2128
|
+
historyRel: applied.revInfo.historyRel,
|
|
2129
|
+
candidateDigest: gate.candidateDigest,
|
|
2130
|
+
authorizationTier: auth.tier,
|
|
2131
|
+
keyTrustSource: auth.keyTrustSource || null,
|
|
2132
|
+
approvalId: applied.prDetails ? applied.prDetails.approvalId : auth.approvalId,
|
|
2133
|
+
approvalRelPath: applied.prDetails ? applied.prDetails.approvalRelPath : auth.approvalRelPath,
|
|
2134
|
+
prBranch: applied.prDetails ? applied.prDetails.branch : null,
|
|
2135
|
+
prCommitSha: applied.prDetails ? applied.prDetails.commitSha : null,
|
|
2136
|
+
authorizationWarning: applied.authorizationWarning,
|
|
2137
|
+
};
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
/**
|
|
2141
|
+
* Phase 6: Restores a skill deterministically from a verified historical snapshot after
|
|
2142
|
+
* enforcing content integrity AND explicit human authorization (never an unsigned escape hatch).
|
|
2143
|
+
*/
|
|
2144
|
+
export function rollbackSkill(options = {}) {
|
|
2145
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
2146
|
+
const loaded = loadProjectManifestAndState(options.projectDir, harnessDir);
|
|
2147
|
+
const { projectDir, schemasDir, manifest, projectPaths } = loaded;
|
|
2148
|
+
const skillName = validateSkillSlugName(options.skillName);
|
|
2149
|
+
const targetRevision = String(options.targetRevision || "").trim();
|
|
2150
|
+
const timestamp = validateCreatedAt(options.createdAt);
|
|
2151
|
+
|
|
2152
|
+
const gate = inspectRollbackSnapshotForGate(projectDir, skillName, targetRevision);
|
|
2153
|
+
|
|
2154
|
+
if (options.dryRun) {
|
|
2155
|
+
return {
|
|
2156
|
+
dryRun: true,
|
|
2157
|
+
skillName,
|
|
2158
|
+
targetRevision,
|
|
2159
|
+
restoredDigest: gate.targetDigest,
|
|
2160
|
+
currentBaseSha256: gate.currentBaseSha,
|
|
2161
|
+
snapshotRel: gate.snapshotRel,
|
|
2162
|
+
};
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
const evidenceDigests = Array.isArray(gate.entry.evidence_digests) ? gate.entry.evidence_digests : [];
|
|
2166
|
+
const auth = assertAuthorizedOperation({
|
|
2167
|
+
projectDir,
|
|
2168
|
+
projectPaths,
|
|
2169
|
+
schemasDir,
|
|
2170
|
+
manifest,
|
|
2171
|
+
expectedAction: "rollback",
|
|
2172
|
+
skillName,
|
|
2173
|
+
targetRevision,
|
|
2174
|
+
contentSha256: gate.targetDigest,
|
|
2175
|
+
baseSha256: gate.currentBaseSha,
|
|
2176
|
+
evidenceDigests,
|
|
2177
|
+
targetRecords: [gate.snapshotRel, gate.histInfo.histRel],
|
|
2178
|
+
approvalId: options.approvalId,
|
|
2179
|
+
publicKeyPath: options.publicKeyPath,
|
|
2180
|
+
mode: options.mode,
|
|
2181
|
+
branch: options.branch,
|
|
2182
|
+
approvedBy: options.approvedBy,
|
|
2183
|
+
interactiveConfirm: options.interactiveConfirm,
|
|
2184
|
+
timestamp,
|
|
2185
|
+
slugHint: `rollback-${skillName}-${targetRevision}`,
|
|
2186
|
+
rationale: `Authorized rollback of skill "${skillName}" from ${gate.currentBaseSha.slice(0, 19)} to ${targetRevision} (${gate.targetDigest.slice(0, 19)}).`,
|
|
2187
|
+
});
|
|
2188
|
+
|
|
2189
|
+
const activeRel = `.agents/skills/${skillName}`;
|
|
2190
|
+
const applied = applyAuthorizedSkillPackageChange({
|
|
2191
|
+
projectDir,
|
|
2192
|
+
projectPaths,
|
|
2193
|
+
schemasDir,
|
|
2194
|
+
sourcePackageDir: gate.snapshotDir,
|
|
2195
|
+
expectedDigest: gate.targetDigest,
|
|
2196
|
+
baseSha256: gate.currentBaseSha,
|
|
2197
|
+
skillName,
|
|
2198
|
+
action: "rollback",
|
|
2199
|
+
auth,
|
|
2200
|
+
evidenceDigests,
|
|
2201
|
+
timestamp,
|
|
2202
|
+
restoredFromRevision: targetRevision,
|
|
2203
|
+
reason: `Rolled back to verified snapshot ${targetRevision}.`,
|
|
2204
|
+
targetRecords: [activeRel, gate.histInfo.histRel, gate.snapshotRel],
|
|
2205
|
+
});
|
|
2206
|
+
|
|
2207
|
+
return {
|
|
2208
|
+
dryRun: false,
|
|
2209
|
+
skillName,
|
|
2210
|
+
activeRel: applied.activeRel,
|
|
2211
|
+
restoredFromRevision: targetRevision,
|
|
2212
|
+
newRevision: applied.revInfo.revision,
|
|
2213
|
+
restoredDigest: gate.targetDigest,
|
|
2214
|
+
previousBaseDigest: gate.currentBaseSha,
|
|
2215
|
+
historyRel: applied.revInfo.historyRel,
|
|
2216
|
+
snapshotRel: applied.revInfo.snapshotRel,
|
|
2217
|
+
authorizationTier: auth.tier,
|
|
2218
|
+
keyTrustSource: auth.keyTrustSource || null,
|
|
2219
|
+
approvalId: applied.prDetails ? applied.prDetails.approvalId : auth.approvalId,
|
|
2220
|
+
approvalRelPath: applied.prDetails ? applied.prDetails.approvalRelPath : auth.approvalRelPath,
|
|
2221
|
+
prBranch: applied.prDetails ? applied.prDetails.branch : null,
|
|
2222
|
+
prCommitSha: applied.prDetails ? applied.prDetails.commitSha : null,
|
|
2223
|
+
authorizationWarning: applied.authorizationWarning,
|
|
2224
|
+
};
|
|
2225
|
+
}
|