geloforge 0.6.0 → 0.9.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/README.md +84 -87
- package/VERSION +1 -1
- package/adapters/n8n/staging-audit-error-workflow.json +132 -0
- package/core/audit-learning.mjs +68 -0
- package/core/audit-provider.mjs +157 -0
- package/core/autonomous-audit.mjs +214 -0
- package/core/checkpoint.mjs +20 -10
- package/core/coding-loop.mjs +500 -0
- package/core/compatibility.json +1 -1
- package/core/context-cache.mjs +114 -0
- package/core/context-compiler.mjs +77 -10
- package/core/doctor.mjs +319 -0
- package/core/evidence-capture.mjs +24 -3
- package/core/hooks-init.mjs +245 -0
- package/core/mcp-init.mjs +13 -9
- package/core/mcp-lock.mjs +488 -0
- package/core/mcp-server.mjs +70 -8
- package/core/operation-approval.mjs +102 -0
- package/core/project-lock.mjs +49 -17
- package/core/project-status.mjs +68 -0
- package/core/promotion.mjs +90 -0
- package/core/runtime-files.mjs +40 -0
- package/core/skills-advisor.mjs +944 -0
- package/core/staging-audit.mjs +454 -0
- package/core/staging-evidence.mjs +127 -0
- package/core/task-manager.mjs +3 -1
- package/core/text-utils.mjs +63 -5
- package/core/worktrees.mjs +64 -0
- package/package.json +6 -2
- package/policies/approval-boundaries.md +4 -4
- package/policies/token-efficiency.md +9 -9
- package/schemas/approval-record.schema.json +9 -0
- package/scripts/geloforge.mjs +648 -14
- package/templates/project-starter/AGENTS.md +4 -3
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** Owner authorization for bounded, explicitly scoped CLI operations. */
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createPrivateKey, createPublicKey, sign, verify } from "node:crypto";
|
|
5
|
+
import { assertSafeWithinRoot, atomicWriteFile, hasSecretContent, isSameOrInside, walkNonSymlinkFiles } from "./path-safety.mjs";
|
|
6
|
+
import { readRegularFile, sha256 } from "./runtime-files.mjs";
|
|
7
|
+
import { scanAndAllocateRecordId } from "./project-locator.mjs";
|
|
8
|
+
import { validateAgainstSchema } from "./json-schema-lite.mjs";
|
|
9
|
+
import { parseYaml, serializeYaml } from "./yaml-subset.mjs";
|
|
10
|
+
|
|
11
|
+
function readKey(project, keyPath) {
|
|
12
|
+
if (!keyPath) throw new Error("Supply the owner's key file explicitly.");
|
|
13
|
+
const resolved = fs.realpathSync(path.resolve(keyPath));
|
|
14
|
+
if (isSameOrInside(resolved, fs.realpathSync(project.projectDir))) {
|
|
15
|
+
throw new Error("Keep the pinned owner key outside the project.");
|
|
16
|
+
}
|
|
17
|
+
const bytes = readRegularFile(resolved, 16 * 1024);
|
|
18
|
+
if (!bytes) throw new Error("Owner key file is unavailable.");
|
|
19
|
+
return bytes;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function operationPayload(project, record, digest) {
|
|
23
|
+
return Buffer.from(JSON.stringify([
|
|
24
|
+
"geloforge-operation-v1", project.manifest.project_id, project.manifest.owner,
|
|
25
|
+
sha256(fs.realpathSync(project.projectDir)), record.id, record.decided_at,
|
|
26
|
+
record.expires_at, record.boundary_category, record.target_records, digest,
|
|
27
|
+
]));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function checkApprovalSchema(project, record) {
|
|
31
|
+
const schema = JSON.parse(fs.readFileSync(path.join(project.schemasDir, "approval-record.schema.json"), "utf8"));
|
|
32
|
+
const result = validateAgainstSchema(record, schema);
|
|
33
|
+
if (!result.valid) throw new Error(`Invalid approval record: ${result.errors.join("; ")}`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function signOperationApproval({ project, operation, privateKeyPath, expiresAt }) {
|
|
37
|
+
const timestamp = new Date().toISOString();
|
|
38
|
+
if (expiresAt != null && (!Number.isFinite(Date.parse(expiresAt)) || Date.parse(expiresAt) <= Date.parse(timestamp))) {
|
|
39
|
+
throw new Error("Approval expiry must be a future ISO timestamp.");
|
|
40
|
+
}
|
|
41
|
+
const privateKey = createPrivateKey(readKey(project, privateKeyPath));
|
|
42
|
+
if (privateKey.asymmetricKeyType !== "ed25519") throw new Error("Use an Ed25519 owner key.");
|
|
43
|
+
const { projectDir, projectPaths, manifest } = project;
|
|
44
|
+
const { id } = scanAndAllocateRecordId({
|
|
45
|
+
projectDir, prefix: "APPR", searchDirs: [projectPaths.proposals_dir, projectPaths.decisions_dir],
|
|
46
|
+
});
|
|
47
|
+
const record = {
|
|
48
|
+
schema_version: "1.1", id, title: operation.title, status: "approved",
|
|
49
|
+
memory_layer: "L2_OPERATIONAL", authority_level: "A4", boundary_category: operation.category,
|
|
50
|
+
requested_by: manifest.owner, requested_at: timestamp, decided_by: manifest.owner, decided_at: timestamp,
|
|
51
|
+
expires_at: expiresAt ?? null, target_records: operation.targets,
|
|
52
|
+
rationale: "Owner authorized this exact operation.",
|
|
53
|
+
risk_assessment: operation.risk, conditions: [],
|
|
54
|
+
operation_authorization: {
|
|
55
|
+
digest: operation.digest,
|
|
56
|
+
signature_base64: sign(null, operationPayload(project, {
|
|
57
|
+
id, decided_at: timestamp, expires_at: expiresAt ?? null,
|
|
58
|
+
boundary_category: operation.category, target_records: operation.targets,
|
|
59
|
+
}, operation.digest), privateKey).toString("base64"),
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
checkApprovalSchema(project, record);
|
|
63
|
+
const relativePath = `${projectPaths.proposals_dir}/${id}-operation.yaml`;
|
|
64
|
+
atomicWriteFile(assertSafeWithinRoot(projectDir, relativePath), serializeYaml(record), { allowOverwrite: false });
|
|
65
|
+
return { approvalId: id, relativePath };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function verifyOperationApproval({ project, operation, approvalId, publicKeyPath, remainingMs = 0 }) {
|
|
69
|
+
if (typeof approvalId !== "string" || !/^APPR-\d{4}$/.test(approvalId)) {
|
|
70
|
+
throw new Error("Supply a signed owner approval with --approval APPR-NNNN.");
|
|
71
|
+
}
|
|
72
|
+
const { projectDir, projectPaths } = project;
|
|
73
|
+
const approvalDir = assertSafeWithinRoot(projectDir, projectPaths.proposals_dir);
|
|
74
|
+
const filename = new RegExp(`^${approvalId}(?:-[^/]+)?\\.ya?ml$`, "i");
|
|
75
|
+
const files = walkNonSymlinkFiles(projectDir, approvalDir, (file) => filename.test(path.basename(file)));
|
|
76
|
+
if (files.length !== 1) throw new Error(`Expected one owner approval record for ${approvalId}.`);
|
|
77
|
+
const raw = readRegularFile(files[0]);
|
|
78
|
+
if (!raw || hasSecretContent(raw.toString())) throw new Error("Unsafe approval record.");
|
|
79
|
+
const record = parseYaml(raw.toString(), approvalId);
|
|
80
|
+
checkApprovalSchema(project, record);
|
|
81
|
+
const authorization = record.operation_authorization;
|
|
82
|
+
const now = Date.now();
|
|
83
|
+
if (record.id !== approvalId || record.is_example || record.status !== "approved" ||
|
|
84
|
+
record.decided_by !== project.manifest.owner || record.conditions.length !== 0 ||
|
|
85
|
+
!Number.isFinite(Date.parse(record.decided_at)) || Date.parse(record.decided_at) > now ||
|
|
86
|
+
(record.expires_at !== null && !(Date.parse(record.expires_at) > now + remainingMs)) ||
|
|
87
|
+
record.boundary_category !== operation.category ||
|
|
88
|
+
JSON.stringify(record.target_records) !== JSON.stringify(operation.targets) ||
|
|
89
|
+
authorization?.digest !== operation.digest) {
|
|
90
|
+
throw new Error(`Owner approval ${approvalId} does not authorize these inputs or has expired.`);
|
|
91
|
+
}
|
|
92
|
+
const keyBytes = readKey(project, publicKeyPath);
|
|
93
|
+
if (!keyBytes.toString("utf8").trimStart().startsWith("-----BEGIN PUBLIC KEY-----")) {
|
|
94
|
+
throw new Error("Pin the owner's public PEM, kept outside the project.");
|
|
95
|
+
}
|
|
96
|
+
const key = createPublicKey(keyBytes);
|
|
97
|
+
if (key.asymmetricKeyType !== "ed25519" || !verify(null, operationPayload(project, record, operation.digest), key,
|
|
98
|
+
Buffer.from(authorization.signature_base64, "base64"))) {
|
|
99
|
+
throw new Error(`Owner signature for ${approvalId} did not match the pinned public key.`);
|
|
100
|
+
}
|
|
101
|
+
return record;
|
|
102
|
+
}
|
package/core/project-lock.mjs
CHANGED
|
@@ -20,6 +20,11 @@ import { assertSafeWithinRoot, atomicWriteFile } from "./path-safety.mjs";
|
|
|
20
20
|
|
|
21
21
|
const ACTIVE_LOCKS = new Set();
|
|
22
22
|
const SLEEP_VIEW = new Int32Array(new SharedArrayBuffer(4));
|
|
23
|
+
const TRANSIENT_LOCK_FS_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
24
|
+
|
|
25
|
+
function isTransientLockFsError(err) {
|
|
26
|
+
return Boolean(err && TRANSIENT_LOCK_FS_CODES.has(err.code));
|
|
27
|
+
}
|
|
23
28
|
|
|
24
29
|
function sleepSyncMs(ms) {
|
|
25
30
|
if (!Number.isFinite(ms) || ms <= 0) return;
|
|
@@ -84,16 +89,24 @@ function isExpectedSameLock(currentMeta, expectedMeta) {
|
|
|
84
89
|
}
|
|
85
90
|
|
|
86
91
|
function releaseLockSafe(lockAbs, token) {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
92
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
93
|
+
try {
|
|
94
|
+
if (!fs.existsSync(lockAbs)) return;
|
|
95
|
+
const st = fs.lstatSync(lockAbs);
|
|
96
|
+
if (st.isSymbolicLink() || !st.isFile()) return;
|
|
97
|
+
const parsed = JSON.parse(fs.readFileSync(lockAbs, "utf8"));
|
|
98
|
+
if (parsed && parsed.token === token) {
|
|
99
|
+
fs.unlinkSync(lockAbs);
|
|
100
|
+
}
|
|
101
|
+
return;
|
|
102
|
+
} catch (err) {
|
|
103
|
+
if (isTransientLockFsError(err) && attempt < 4) {
|
|
104
|
+
sleepSyncMs(10);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
// Do not unlink lock owned by another process or already removed
|
|
108
|
+
return;
|
|
94
109
|
}
|
|
95
|
-
} catch {
|
|
96
|
-
// Do not unlink lock owned by another process or already removed
|
|
97
110
|
}
|
|
98
111
|
}
|
|
99
112
|
|
|
@@ -114,7 +127,7 @@ function acquireReclaimGuard(reclaimAbs, staleLockMs) {
|
|
|
114
127
|
}
|
|
115
128
|
return guardToken;
|
|
116
129
|
} catch (err) {
|
|
117
|
-
if (!err || (err.code !== "EEXIST" && err
|
|
130
|
+
if (!err || (err.code !== "EEXIST" && !isTransientLockFsError(err))) {
|
|
118
131
|
throw err;
|
|
119
132
|
}
|
|
120
133
|
// Check if an abandoned reclaim guard was left by a dead process
|
|
@@ -148,7 +161,7 @@ function tryReclaimStaleLock(lockAbs, expectedMeta, staleLockMs) {
|
|
|
148
161
|
try {
|
|
149
162
|
currentMeta = parseLockMeta(lockAbs);
|
|
150
163
|
} catch (err) {
|
|
151
|
-
if (err && err.code === "ENOENT") {
|
|
164
|
+
if (err && (err.code === "ENOENT" || isTransientLockFsError(err))) {
|
|
152
165
|
return false;
|
|
153
166
|
}
|
|
154
167
|
throw err;
|
|
@@ -163,7 +176,7 @@ function tryReclaimStaleLock(lockAbs, expectedMeta, staleLockMs) {
|
|
|
163
176
|
try {
|
|
164
177
|
fs.renameSync(lockAbs, staleTmp);
|
|
165
178
|
} catch (err) {
|
|
166
|
-
if (err && (err.code === "ENOENT" || err
|
|
179
|
+
if (err && (err.code === "ENOENT" || isTransientLockFsError(err))) {
|
|
167
180
|
return false;
|
|
168
181
|
}
|
|
169
182
|
throw err;
|
|
@@ -224,6 +237,20 @@ export function recoverPendingTransactionJournal(projectDir) {
|
|
|
224
237
|
return { recovered: true, restoredFiles };
|
|
225
238
|
}
|
|
226
239
|
|
|
240
|
+
function resolveSafeLockPath(resolvedDir, relPath, timeoutMs, delayMs, startMs) {
|
|
241
|
+
while (true) {
|
|
242
|
+
try {
|
|
243
|
+
return assertSafeWithinRoot(resolvedDir, relPath);
|
|
244
|
+
} catch (err) {
|
|
245
|
+
const elapsed = Date.now() - startMs;
|
|
246
|
+
if (!isTransientLockFsError(err) || elapsed >= timeoutMs) {
|
|
247
|
+
throw err;
|
|
248
|
+
}
|
|
249
|
+
sleepSyncMs(Math.min(delayMs, timeoutMs - elapsed));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
227
254
|
/**
|
|
228
255
|
* Executes `fn` while holding an exclusive atomic lockfile at `<projectDir>/.geloforge/.state.lock`.
|
|
229
256
|
*/
|
|
@@ -266,9 +293,9 @@ export function withProjectLock(
|
|
|
266
293
|
fs.mkdirSync(gfDirAbs, { recursive: true });
|
|
267
294
|
}
|
|
268
295
|
|
|
269
|
-
const lockAbs = assertSafeWithinRoot(resolvedDir, ".geloforge/.state.lock");
|
|
270
|
-
const token = crypto.randomBytes(12).toString("hex");
|
|
271
296
|
const startMs = Date.now();
|
|
297
|
+
const lockAbs = resolveSafeLockPath(resolvedDir, ".geloforge/.state.lock", timeout, delay, startMs);
|
|
298
|
+
const token = crypto.randomBytes(12).toString("hex");
|
|
272
299
|
|
|
273
300
|
let acquired = false;
|
|
274
301
|
while (!acquired) {
|
|
@@ -288,23 +315,28 @@ export function withProjectLock(
|
|
|
288
315
|
}
|
|
289
316
|
acquired = true;
|
|
290
317
|
} catch (err) {
|
|
291
|
-
if (!err || (err.code !== "EEXIST" && err
|
|
318
|
+
if (!err || (err.code !== "EEXIST" && !isTransientLockFsError(err))) {
|
|
292
319
|
throw err;
|
|
293
320
|
}
|
|
294
321
|
|
|
295
322
|
// Inspect existing lock (if present) for staleness or symlink violation
|
|
296
323
|
let metaInfo = null;
|
|
324
|
+
let transientInspectError = false;
|
|
297
325
|
try {
|
|
298
326
|
metaInfo = parseLockMeta(lockAbs);
|
|
299
327
|
} catch (inspectErr) {
|
|
300
328
|
if (inspectErr && inspectErr.code === "ENOENT") {
|
|
301
329
|
continue;
|
|
302
330
|
}
|
|
303
|
-
|
|
331
|
+
if (isTransientLockFsError(inspectErr)) {
|
|
332
|
+
transientInspectError = true;
|
|
333
|
+
} else {
|
|
334
|
+
throw inspectErr;
|
|
335
|
+
}
|
|
304
336
|
}
|
|
305
337
|
|
|
306
338
|
const nowMs = Date.now();
|
|
307
|
-
if (isLockStale(metaInfo, staleMs, nowMs)) {
|
|
339
|
+
if (!transientInspectError && isLockStale(metaInfo, staleMs, nowMs)) {
|
|
308
340
|
if (tryReclaimStaleLock(lockAbs, metaInfo, staleMs)) {
|
|
309
341
|
continue;
|
|
310
342
|
}
|
package/core/project-status.mjs
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import fs from "node:fs";
|
|
6
6
|
import path from "node:path";
|
|
7
|
+
import { findBlockedAudit, readAutonomousMode } from "./autonomous-audit.mjs";
|
|
7
8
|
import { parseYaml, extractFrontmatter } from "./yaml-subset.mjs";
|
|
8
9
|
import { validateProject } from "./project-validator.mjs";
|
|
9
10
|
import { getGitStatusScoped } from "./git-utils.mjs";
|
|
@@ -15,6 +16,7 @@ import {
|
|
|
15
16
|
walkNonSymlinkFiles,
|
|
16
17
|
} from "./path-safety.mjs";
|
|
17
18
|
import { listTaskLeases, listTasks, scopesOverlap } from "./task-manager.mjs";
|
|
19
|
+
import { suggestProjectSkills } from "./skills-advisor.mjs";
|
|
18
20
|
|
|
19
21
|
function inspectGitState(projectDir) {
|
|
20
22
|
const gs = getGitStatusScoped(projectDir);
|
|
@@ -68,6 +70,14 @@ export function getProjectStatus(rawProjectDir, options = {}) {
|
|
|
68
70
|
|
|
69
71
|
const vcs = inspectGitState(projectDir);
|
|
70
72
|
const advisoryWarnings = [...validation.warnings];
|
|
73
|
+
let autonomousMode = "off";
|
|
74
|
+
let blockedAudit = null;
|
|
75
|
+
try {
|
|
76
|
+
autonomousMode = readAutonomousMode(projectDir);
|
|
77
|
+
blockedAudit = findBlockedAudit(projectDir, state?.blocked_tasks ?? []);
|
|
78
|
+
} catch (err) {
|
|
79
|
+
advisoryWarnings.push(`Could not inspect autonomous audit state: ${err.message}`);
|
|
80
|
+
}
|
|
71
81
|
|
|
72
82
|
const pendingApprovalsInbox = manifest
|
|
73
83
|
? scanPendingApprovalsInbox({ projectDir, projectPaths, state, warnings: advisoryWarnings })
|
|
@@ -103,6 +113,7 @@ export function getProjectStatus(rawProjectDir, options = {}) {
|
|
|
103
113
|
pendingApprovalsInbox,
|
|
104
114
|
activeLeases,
|
|
105
115
|
leaseOverlaps,
|
|
116
|
+
blockedAudit,
|
|
106
117
|
});
|
|
107
118
|
|
|
108
119
|
const nextSteps = [];
|
|
@@ -141,6 +152,7 @@ export function getProjectStatus(rawProjectDir, options = {}) {
|
|
|
141
152
|
|
|
142
153
|
return {
|
|
143
154
|
projectDir,
|
|
155
|
+
autonomousMode,
|
|
144
156
|
valid: validation.valid,
|
|
145
157
|
compatibilityStatus: validation.compatibilityStatus,
|
|
146
158
|
project: manifest
|
|
@@ -195,6 +207,7 @@ export function getProjectRecommendations(projectDir) {
|
|
|
195
207
|
const status = getProjectStatus(projectDir);
|
|
196
208
|
return {
|
|
197
209
|
projectDir: status.projectDir,
|
|
210
|
+
autonomousMode: status.autonomousMode,
|
|
198
211
|
valid: status.valid,
|
|
199
212
|
project: status.project,
|
|
200
213
|
operationalState: status.operationalState,
|
|
@@ -416,6 +429,7 @@ function buildRecommendations({
|
|
|
416
429
|
pendingApprovalsInbox,
|
|
417
430
|
activeLeases,
|
|
418
431
|
leaseOverlaps,
|
|
432
|
+
blockedAudit,
|
|
419
433
|
}) {
|
|
420
434
|
const recs = [];
|
|
421
435
|
|
|
@@ -497,6 +511,19 @@ function buildRecommendations({
|
|
|
497
511
|
});
|
|
498
512
|
}
|
|
499
513
|
|
|
514
|
+
if (blockedAudit) {
|
|
515
|
+
recs.push({
|
|
516
|
+
rank: 81,
|
|
517
|
+
priority: "high",
|
|
518
|
+
category: "autonomous_audit",
|
|
519
|
+
title: `Review the blocked staging audit in ${blockedAudit.id}`,
|
|
520
|
+
reason: blockedAudit.resume_instructions,
|
|
521
|
+
options: ["Inspect the checkpoint and verify the missing or mismatched evidence"],
|
|
522
|
+
command: `geloforge checkpoint show --id ${blockedAudit.id}`,
|
|
523
|
+
requiresHumanApproval: false,
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
|
|
500
527
|
if (state) {
|
|
501
528
|
const activeIds = state.active_tasks || [];
|
|
502
529
|
if (activeIds.length === 0) {
|
|
@@ -600,6 +627,47 @@ function buildRecommendations({
|
|
|
600
627
|
});
|
|
601
628
|
}
|
|
602
629
|
|
|
630
|
+
try {
|
|
631
|
+
if (state && ((state.active_tasks || []).length > 0 || state.last_verified_evidence)) {
|
|
632
|
+
const advisor = suggestProjectSkills({
|
|
633
|
+
projectDir,
|
|
634
|
+
harnessDir,
|
|
635
|
+
taskId: (state.active_tasks || [])[0] || null,
|
|
636
|
+
limit: 3,
|
|
637
|
+
scaffoldDraft: false,
|
|
638
|
+
});
|
|
639
|
+
if (advisor.recommendedSkills.length > 0) {
|
|
640
|
+
const top = advisor.recommendedSkills[0];
|
|
641
|
+
recs.push({
|
|
642
|
+
rank: 56,
|
|
643
|
+
priority: "low",
|
|
644
|
+
category: "skills",
|
|
645
|
+
title: `Load matching skill "${top.name}" for current project/task context`,
|
|
646
|
+
reason: top.reasons.join("; ") || "Relevant active skill matched current project signals.",
|
|
647
|
+
options: [`Compile focused context with ${top.name}`],
|
|
648
|
+
command: `geloforge context ${advisor.taskId ? `--task ${advisor.taskId} ` : ""}--skills --skill ${top.name}`,
|
|
649
|
+
requiresHumanApproval: false,
|
|
650
|
+
});
|
|
651
|
+
} else {
|
|
652
|
+
const evGap = advisor.skillGaps.find((g) => g.kind === "evidence_backed_workflow" && !g.existingQuarantinedDraft);
|
|
653
|
+
if (evGap) {
|
|
654
|
+
recs.push({
|
|
655
|
+
rank: 54,
|
|
656
|
+
priority: "low",
|
|
657
|
+
category: "skills",
|
|
658
|
+
title: `Scaffold quarantined skill draft "${evGap.suggestedName}" from verified evidence`,
|
|
659
|
+
reason: evGap.reason,
|
|
660
|
+
options: ["Stage quarantined draft in proposals/skills/ for human review"],
|
|
661
|
+
command: `geloforge skills suggest --scaffold-draft`,
|
|
662
|
+
requiresHumanApproval: false,
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
} catch {
|
|
668
|
+
// Non-fatal advisory check
|
|
669
|
+
}
|
|
670
|
+
|
|
603
671
|
recs.sort((a, b) => {
|
|
604
672
|
if (b.rank !== a.rank) return b.rank - a.rank;
|
|
605
673
|
return String(a.title).localeCompare(String(b.title));
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { assertSafeWithinRoot, hasSecretContent, isForbiddenSecretPath } from "./path-safety.mjs";
|
|
4
|
+
import { loadProjectManifestAndState, scanAndAllocateRecordId } from "./project-locator.mjs";
|
|
5
|
+
import { runMultiFileTransaction, withProjectLock } from "./project-lock.mjs";
|
|
6
|
+
import { loadVerifiedSourceBundle } from "./skills-lifecycle.mjs";
|
|
7
|
+
import { readRegularFile, sha256 } from "./runtime-files.mjs";
|
|
8
|
+
import { signOperationApproval, verifyOperationApproval } from "./operation-approval.mjs";
|
|
9
|
+
import { validateAgainstSchema } from "./json-schema-lite.mjs";
|
|
10
|
+
import { extractFrontmatter, serializeYaml } from "./yaml-subset.mjs";
|
|
11
|
+
|
|
12
|
+
function projectMarkdownPath(projectDir, value) {
|
|
13
|
+
if (typeof value !== "string" || !value.endsWith(".md") || hasSecretContent(value) ||
|
|
14
|
+
isForbiddenSecretPath(value) || value.includes("\\") ||
|
|
15
|
+
value.split("/").some((part) => !part || part === "." || part === "..")) {
|
|
16
|
+
throw new Error("Use a safe project-relative Markdown path.");
|
|
17
|
+
}
|
|
18
|
+
return assertSafeWithinRoot(projectDir, value);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function promoteProjectProposal(options) {
|
|
22
|
+
const { projectDir, harnessDir, proposal, target, evidenceIds, approvalId, publicKeyPath, privateKeyPath,
|
|
23
|
+
expiresAt, action = "preview" } = options;
|
|
24
|
+
const execute = () => {
|
|
25
|
+
const project = loadProjectManifestAndState(projectDir, harnessDir);
|
|
26
|
+
const { manifest, projectPaths, schemasDir } = project;
|
|
27
|
+
const sourcePath = projectMarkdownPath(projectDir, proposal);
|
|
28
|
+
const targetPath = projectMarkdownPath(projectDir, target);
|
|
29
|
+
if (!proposal.startsWith(`${projectPaths.proposals_dir}/`) || sourcePath === targetPath) {
|
|
30
|
+
throw new Error("Choose a proposal from the project's proposals directory.");
|
|
31
|
+
}
|
|
32
|
+
const isRequirement = [projectPaths.prd, projectPaths.constraints].includes(target) &&
|
|
33
|
+
/^brain\/requirements\/[^/]+\.md$/.test(target);
|
|
34
|
+
const adrMatch = target.match(/^brain\/decisions\/(ADR-\d{4})-[a-z0-9-]+\.md$/);
|
|
35
|
+
const adrId = target.startsWith(`${projectPaths.decisions_dir}/`) ? adrMatch?.[1] : null;
|
|
36
|
+
if (!isRequirement && !adrId) throw new Error("Choose a canonical requirements document or ADR target.");
|
|
37
|
+
const raw = readRegularFile(sourcePath)?.toString("utf8");
|
|
38
|
+
if (!raw?.trim() || hasSecretContent(raw)) throw new Error("Proposal is missing, empty, or contains credential-like content.");
|
|
39
|
+
if (/^\s*is_example:\s*true\b/im.test(raw)) throw new Error("Example proposals cannot be promoted.");
|
|
40
|
+
const original = readRegularFile(targetPath);
|
|
41
|
+
if (original && hasSecretContent(original.toString("utf8"))) throw new Error("Canonical document contains credential-like content.");
|
|
42
|
+
let adr;
|
|
43
|
+
if (adrId) {
|
|
44
|
+
const frontmatter = extractFrontmatter(raw, proposal);
|
|
45
|
+
if (frontmatter.id !== adrId || frontmatter.status !== "proposed" ||
|
|
46
|
+
frontmatter.owner !== manifest.owner || frontmatter.is_example) {
|
|
47
|
+
throw new Error("Supply a proposed ADR with a matching ID and the current owner.");
|
|
48
|
+
}
|
|
49
|
+
scanAndAllocateRecordId({ projectDir, searchDirs: [projectPaths.decisions_dir], prefix: "ADR", explicitId: adrId });
|
|
50
|
+
const normalized = raw.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
|
|
51
|
+
adr = { frontmatter, body: normalized.slice(normalized.indexOf("\n---", 3) + 5) };
|
|
52
|
+
const check = validateAgainstSchema(frontmatter, JSON.parse(fs.readFileSync(path.join(schemasDir, "adr.schema.json"), "utf8")));
|
|
53
|
+
if (!check.valid) throw new Error(`Invalid proposed ADR: ${check.errors.join("; ")}`);
|
|
54
|
+
}
|
|
55
|
+
const bundle = loadVerifiedSourceBundle({ projectDir, harnessDir, evidenceIds });
|
|
56
|
+
const evidence = bundle.evidenceDigests;
|
|
57
|
+
const input = { proposal, target, content: sha256(raw), base: original ? sha256(original) : null, evidence };
|
|
58
|
+
const operation = {
|
|
59
|
+
title: `Promote proposal into ${target}`, category: isRequirement ? "requirements_change" : "architecture_change",
|
|
60
|
+
targets: [proposal, target, ...bundle.evidenceList.map(({ data }) => data.id)],
|
|
61
|
+
risk: "Updates one canonical document and binds it to verified evidence.", digest: sha256(JSON.stringify(input)),
|
|
62
|
+
};
|
|
63
|
+
const preview = { ...input, digest: operation.digest };
|
|
64
|
+
if (action === "preview") return preview;
|
|
65
|
+
if (action === "sign") return { ...preview, ...signOperationApproval({ project, operation, privateKeyPath, expiresAt }) };
|
|
66
|
+
const approval = verifyOperationApproval({ project, operation, approvalId, publicKeyPath });
|
|
67
|
+
const receipt = assertSafeWithinRoot(projectDir, `local-runtime/promotions/${approvalId}.json`);
|
|
68
|
+
if (fs.existsSync(receipt)) throw new Error(`Approval ${approvalId} was already used. Sign a fresh approval.`);
|
|
69
|
+
const content = adr ? `---\n${serializeYaml({
|
|
70
|
+
...adr.frontmatter, status: "accepted", approved_by: manifest.owner, decided_at: approval.decided_at,
|
|
71
|
+
updated_at: approval.decided_at, approval_ref: approvalId,
|
|
72
|
+
})}---\n${adr.body}` : raw;
|
|
73
|
+
const archivedProposal = adr ? `local-runtime/promotions/${approvalId}-source.md` : null;
|
|
74
|
+
const result = { ...preview, approvalId, archivedProposal, promoted: true };
|
|
75
|
+
const steps = [
|
|
76
|
+
{ filePath: targetPath, content, allowOverwrite: Boolean(original) },
|
|
77
|
+
{ filePath: receipt, content: `${JSON.stringify(result, null, 2)}\n`, allowOverwrite: false, mode: 0o600 },
|
|
78
|
+
];
|
|
79
|
+
if (archivedProposal) {
|
|
80
|
+
// A proposed ADR and its canonical successor cannot share a live record ID.
|
|
81
|
+
steps.push(
|
|
82
|
+
{ filePath: assertSafeWithinRoot(projectDir, archivedProposal), content: raw, allowOverwrite: false, mode: 0o600 },
|
|
83
|
+
{ filePath: sourcePath, deleteIfExists: true },
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
runMultiFileTransaction(steps, { projectDir });
|
|
87
|
+
return result;
|
|
88
|
+
};
|
|
89
|
+
return action === "preview" ? execute() : withProjectLock(projectDir, execute);
|
|
90
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { assertSafeWithinRoot, atomicWriteFile } from "./path-safety.mjs";
|
|
4
|
+
|
|
5
|
+
export function readRegularFile(file, maxBytes = 256 * 1024) {
|
|
6
|
+
let stat;
|
|
7
|
+
try {
|
|
8
|
+
stat = fs.lstatSync(file);
|
|
9
|
+
} catch (err) {
|
|
10
|
+
if (err.code === "ENOENT") return null;
|
|
11
|
+
throw err;
|
|
12
|
+
}
|
|
13
|
+
if (!stat.isFile() || stat.size > maxBytes) throw new Error("Expected a regular file within the size limit.");
|
|
14
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0));
|
|
15
|
+
try {
|
|
16
|
+
const opened = fs.fstatSync(fd);
|
|
17
|
+
if (!opened.isFile() || opened.size > maxBytes) throw new Error("Expected a regular file within the size limit.");
|
|
18
|
+
const bytes = Buffer.alloc(opened.size + 1);
|
|
19
|
+
const count = fs.readSync(fd, bytes, 0, bytes.length, 0);
|
|
20
|
+
if (count !== opened.size) throw new Error("File changed while being read. Retry with a stable copy.");
|
|
21
|
+
return bytes.subarray(0, count);
|
|
22
|
+
} finally {
|
|
23
|
+
fs.closeSync(fd);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function sha256(value) {
|
|
28
|
+
return createHash("sha256").update(value).digest("hex");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function readRuntimeJson(projectDir, relativePath, { maxBytes } = {}) {
|
|
32
|
+
const raw = readRegularFile(assertSafeWithinRoot(projectDir, relativePath), maxBytes);
|
|
33
|
+
return raw === null ? null : JSON.parse(raw.toString("utf8").replace(/^\uFEFF/, ""));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function writeRuntimeJson(projectDir, relativePath, value, { allowOverwrite = true } = {}) {
|
|
37
|
+
atomicWriteFile(assertSafeWithinRoot(projectDir, relativePath), `${JSON.stringify(value, null, 2)}\n`, {
|
|
38
|
+
mode: 0o600, allowOverwrite,
|
|
39
|
+
});
|
|
40
|
+
}
|