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,214 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { createCheckpoint, listCheckpoints } from "./checkpoint.mjs";
|
|
6
|
+
import { captureEvidence } from "./evidence-capture.mjs";
|
|
7
|
+
import { assertSafeWithinRoot, atomicWriteFile, hasSecretContent, isForbiddenSecretPath } from "./path-safety.mjs";
|
|
8
|
+
import { loadProjectManifestAndState } from "./project-locator.mjs";
|
|
9
|
+
import { withProjectLock } from "./project-lock.mjs";
|
|
10
|
+
import { normalizeN8nId as normalizeId } from "./staging-evidence.mjs";
|
|
11
|
+
import { completeTask, createTask, getTask, listTasks, updateTask } from "./task-manager.mjs";
|
|
12
|
+
|
|
13
|
+
const MODULE_PATH = fileURLToPath(import.meta.url);
|
|
14
|
+
const MODE_FILE = "local-runtime/autonomous-mode.json";
|
|
15
|
+
export const AUDIT_CREATOR = "geloforge-autonomous";
|
|
16
|
+
const MAX_JSON_BYTES = 256 * 1024;
|
|
17
|
+
const VERIFICATION_TIMEOUT_MS = 3000;
|
|
18
|
+
|
|
19
|
+
export function readAutonomousMode(projectDir) {
|
|
20
|
+
const file = assertSafeWithinRoot(projectDir, MODE_FILE);
|
|
21
|
+
const stat = fs.lstatSync(file, { throwIfNoEntry: false });
|
|
22
|
+
if (!stat) return "off";
|
|
23
|
+
if (!stat.isFile() || stat.size > MAX_JSON_BYTES) {
|
|
24
|
+
throw new Error("Invalid autonomous mode file. Run geloforge autonomous off to reset regular files.");
|
|
25
|
+
}
|
|
26
|
+
let config;
|
|
27
|
+
try {
|
|
28
|
+
config = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
29
|
+
} catch {
|
|
30
|
+
throw new Error("Cannot read autonomous mode. Run geloforge autonomous off to reset the file.");
|
|
31
|
+
}
|
|
32
|
+
if (typeof config?.enabled !== "boolean") {
|
|
33
|
+
throw new Error("Invalid autonomous mode setting. Run geloforge autonomous off to reset it.");
|
|
34
|
+
}
|
|
35
|
+
return config.enabled ? "on" : "off";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function setAutonomousMode({ projectDir, harnessDir, enabled }) {
|
|
39
|
+
return withProjectLock(projectDir, () => {
|
|
40
|
+
loadProjectManifestAndState(projectDir, harnessDir);
|
|
41
|
+
const file = assertSafeWithinRoot(projectDir, MODE_FILE);
|
|
42
|
+
const stat = fs.lstatSync(file, { throwIfNoEntry: false });
|
|
43
|
+
if (stat && !stat.isFile()) throw new Error("Autonomous mode requires a regular settings file.");
|
|
44
|
+
atomicWriteFile(file, `${JSON.stringify({ enabled }, null, 2)}\n`);
|
|
45
|
+
return enabled ? "on" : "off";
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function findBlockedAudit(projectDir, blockedTaskIds) {
|
|
50
|
+
if (blockedTaskIds.length === 0) return null;
|
|
51
|
+
const owners = new Set(blockedTaskIds.map((taskId) => `${AUDIT_CREATOR}/${taskId}`));
|
|
52
|
+
return listCheckpoints({ projectDir }).checkpoints.find((item) =>
|
|
53
|
+
owners.has(item.created_by) && item.verification_evidence_ref === null
|
|
54
|
+
) ?? null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function inputPath(rawPath, label) {
|
|
58
|
+
if (typeof rawPath !== "string" || !/\.json$/i.test(rawPath) ||
|
|
59
|
+
path.win32.isAbsolute(rawPath) || path.posix.isAbsolute(rawPath) ||
|
|
60
|
+
isForbiddenSecretPath(rawPath) || hasSecretContent(rawPath)) {
|
|
61
|
+
throw new Error(`${label} must be a project-relative JSON file path.`);
|
|
62
|
+
}
|
|
63
|
+
return rawPath.replace(/\\/g, "/");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function readJsonInput(projectDir, relativePath, label) {
|
|
67
|
+
let raw;
|
|
68
|
+
try {
|
|
69
|
+
const target = assertSafeWithinRoot(projectDir, relativePath);
|
|
70
|
+
const stat = fs.lstatSync(target);
|
|
71
|
+
if (!stat.isFile() || stat.size > MAX_JSON_BYTES) throw new Error("Invalid file");
|
|
72
|
+
raw = fs.readFileSync(target);
|
|
73
|
+
if (raw.length > MAX_JSON_BYTES) throw new Error("File too large");
|
|
74
|
+
} catch {
|
|
75
|
+
throw new Error(`${label} is missing, unreadable, unsafe, or larger than 256 KiB. Use a regular local JSON file inside this project.`);
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
return { data: JSON.parse(raw.toString("utf8").replace(/^\uFEFF/, "")), raw };
|
|
79
|
+
} catch {
|
|
80
|
+
throw new Error(`${label} is not valid JSON.`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function readFailureEvent(projectDir, eventFile) {
|
|
85
|
+
const { data } = readJsonInput(projectDir, inputPath(eventFile, "--event"), "n8n failure event");
|
|
86
|
+
if (Array.isArray(data) && data.length !== 1) {
|
|
87
|
+
throw new Error("Supply a single n8n Error Trigger event per call.");
|
|
88
|
+
}
|
|
89
|
+
const event = Array.isArray(data) ? data[0] : data;
|
|
90
|
+
const workflowId = normalizeId(event?.workflow?.id);
|
|
91
|
+
const executionId = normalizeId(event?.execution?.id);
|
|
92
|
+
if (!workflowId || !executionId || typeof event.execution.error?.message !== "string" ||
|
|
93
|
+
!event.execution.error.message.trim()) {
|
|
94
|
+
throw new Error("Expected a saved n8n failure with workflow.id, execution.id, and execution.error.message.");
|
|
95
|
+
}
|
|
96
|
+
return { workflowId, executionId };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function verifyExecutionRecord(projectDir, recordPath, workflowId, executionId) {
|
|
100
|
+
const { data, raw } = readJsonInput(projectDir, inputPath(recordPath, "--execution"), "Execution record");
|
|
101
|
+
if (normalizeId(data?.id) !== executionId || normalizeId(data?.workflowId) !== workflowId) {
|
|
102
|
+
throw new Error("Execution record does not match the failure's workflow and execution IDs.");
|
|
103
|
+
}
|
|
104
|
+
if (data.status !== "error") throw new Error('Execution record must have status "error".');
|
|
105
|
+
|
|
106
|
+
// Preserve a short node label only. Raw errors, inputs, and payload bodies stay in the source files.
|
|
107
|
+
const rawNode = data.lastNodeExecuted || data.data?.resultData?.lastNodeExecuted;
|
|
108
|
+
const node = typeof rawNode === "string" ? rawNode.trim() : "";
|
|
109
|
+
const nodeLabel = /^[\p{L}\p{N} _()./-]{1,100}$/u.test(node) && !hasSecretContent(node)
|
|
110
|
+
? `Last node: ${node}.`
|
|
111
|
+
: "Last node unavailable in the normalized evidence.";
|
|
112
|
+
const digest = createHash("sha256").update(raw).digest("hex");
|
|
113
|
+
return `Recorded failure matched workflow ${workflowId}, execution ${executionId}. ${nodeLabel} SHA-256: ${digest}.`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function stagingProgressPath(taskId) {
|
|
117
|
+
if (!/^TASK-\d{4}$/.test(taskId)) throw new Error("Invalid staging audit task ID.");
|
|
118
|
+
return `local-runtime/checkpoints/${taskId}-staging-audit.json`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// The caller holds the project lock across lookup and allocation.
|
|
122
|
+
export function getOrCreateStagingTask({ projectDir, harnessDir, workflowId, executionId }) {
|
|
123
|
+
const title = `Audit n8n staging failure ${workflowId}/${executionId}`;
|
|
124
|
+
const project = { projectDir, harnessDir };
|
|
125
|
+
const existing = listTasks(project).tasks
|
|
126
|
+
.filter((task) => task.title === title)
|
|
127
|
+
.map((task) => getTask({ ...project, taskId: task.id }))
|
|
128
|
+
.find((task) => task.record.created_by === AUDIT_CREATOR);
|
|
129
|
+
const task = existing ?? createTask({
|
|
130
|
+
...project, title, activate: true, createdBy: AUDIT_CREATOR,
|
|
131
|
+
assignedRole: "qa-security-reviewer", contextBudget: "quick",
|
|
132
|
+
objective: `Inspect saved staging execution ${executionId} for n8n workflow ${workflowId} and report evidence-based findings.`,
|
|
133
|
+
scopeIn: ["Inspect local staging execution evidence"],
|
|
134
|
+
scopeOut: ["Workflow changes", "Execution retries", "Customer messages"],
|
|
135
|
+
acceptanceCriteria: ["Verify the execution identity, recorded failure, and each cited finding reference."],
|
|
136
|
+
});
|
|
137
|
+
return { task, existing: Boolean(existing) };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Runs the first-pass audit of one delivered n8n staging failure using local files. */
|
|
141
|
+
export function auditStagingFailure({ projectDir, harnessDir, eventFile, executionFile }) {
|
|
142
|
+
return withProjectLock(projectDir, () => {
|
|
143
|
+
loadProjectManifestAndState(projectDir, harnessDir);
|
|
144
|
+
const mode = readAutonomousMode(projectDir);
|
|
145
|
+
const { workflowId, executionId } = readFailureEvent(projectDir, eventFile);
|
|
146
|
+
const result = { mode, workflowId, executionId, taskId: null, checkpointId: null, evidenceId: null, reused: false };
|
|
147
|
+
if (mode === "off") {
|
|
148
|
+
return {
|
|
149
|
+
...result, status: "skipped",
|
|
150
|
+
nextAction: `Review workflow ${workflowId}, execution ${executionId} manually. Use geloforge recommend for project guidance.`,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const recordPath = executionFile === undefined ? null : inputPath(executionFile, "--execution");
|
|
155
|
+
const project = { projectDir, harnessDir };
|
|
156
|
+
const { task, existing } = getOrCreateStagingTask({ ...project, workflowId, executionId });
|
|
157
|
+
if (fs.existsSync(assertSafeWithinRoot(projectDir, stagingProgressPath(task.id)))) {
|
|
158
|
+
throw new Error("This task is managed by the staging worker. Resume it through autonomous watch.");
|
|
159
|
+
}
|
|
160
|
+
const taskOptions = { ...project, taskId: task.id };
|
|
161
|
+
const checkpointOwner = `${AUDIT_CREATOR}/${task.id}`;
|
|
162
|
+
const prior = existing && listCheckpoints(project).checkpoints.find((item) => item.created_by === checkpointOwner);
|
|
163
|
+
if (existing && task.record.status !== "active") {
|
|
164
|
+
return {
|
|
165
|
+
...result, taskId: task.id, status: task.record.status, reused: true,
|
|
166
|
+
checkpointId: prior?.id ?? null, evidenceId: prior?.verification_evidence_ref ?? null,
|
|
167
|
+
nextAction: prior?.resume_instructions ?? `Inspect ${task.id} with geloforge task show --task ${task.id}.`,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
let checkpoint = prior;
|
|
172
|
+
if (!checkpoint) {
|
|
173
|
+
const evidence = recordPath && captureEvidence({
|
|
174
|
+
...taskOptions, name: "Verify saved n8n staging execution",
|
|
175
|
+
commandArgv: [process.execPath, MODULE_PATH, recordPath, workflowId, executionId],
|
|
176
|
+
displayCommand: `node "<geloforge-install>/core/autonomous-audit.mjs" ${JSON.stringify(recordPath)} ${workflowId} ${executionId}`,
|
|
177
|
+
timeoutMs: VERIFICATION_TIMEOUT_MS, linkVerifiedOnly: true,
|
|
178
|
+
});
|
|
179
|
+
const nextAction = evidence?.verified
|
|
180
|
+
? `${evidence.outputExcerpt} Review the recorded failure in staging to determine the cause.`
|
|
181
|
+
: `${evidence?.record.checks[0].summary ?? "No saved staging execution record was supplied."} Obtain the saved error record for workflow ${workflowId}, execution ${executionId}, and confirm it before closing ${task.id}.`;
|
|
182
|
+
const saved = createCheckpoint({
|
|
183
|
+
...project, createdBy: checkpointOwner,
|
|
184
|
+
evidenceRef: evidence?.verified ? evidence.id : null,
|
|
185
|
+
resumeInstructions: nextAction,
|
|
186
|
+
});
|
|
187
|
+
checkpoint = {
|
|
188
|
+
id: saved.checkpointId,
|
|
189
|
+
verification_evidence_ref: saved.record.verification_evidence_ref,
|
|
190
|
+
resume_instructions: saved.record.resume_instructions,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const evidenceId = checkpoint.verification_evidence_ref;
|
|
195
|
+
const updated = evidenceId
|
|
196
|
+
? completeTask({ ...taskOptions, evidenceRefs: [evidenceId], requireEvidence: true })
|
|
197
|
+
: updateTask({ ...taskOptions, status: "blocked" });
|
|
198
|
+
return {
|
|
199
|
+
...result, taskId: task.id, status: updated.status, reused: Boolean(existing),
|
|
200
|
+
checkpointId: checkpoint.id, evidenceId, nextAction: checkpoint.resume_instructions,
|
|
201
|
+
};
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// A fixed local verifier is executed by evidence capture. Event data never chooses an executable.
|
|
206
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === MODULE_PATH) {
|
|
207
|
+
const [recordPath, workflowId, executionId] = process.argv.slice(2);
|
|
208
|
+
try {
|
|
209
|
+
console.log(verifyExecutionRecord(process.cwd(), recordPath, workflowId, executionId));
|
|
210
|
+
} catch (err) {
|
|
211
|
+
console.error(err.message);
|
|
212
|
+
process.exitCode = 1;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mid-session recovery checkpoint manager for GeloForge (v0.5).
|
|
3
|
+
* Writes schema-valid CHKPT-NNNN records under brain/handoffs/ so agents and humans
|
|
4
|
+
* can restart fresh sessions cleanly without context rot or lost operational state.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import { parseYaml, serializeYaml } from "./yaml-subset.mjs";
|
|
11
|
+
import { validateAgainstSchema } from "./json-schema-lite.mjs";
|
|
12
|
+
import { checkRecordSchemaVersion } from "./compatibility.mjs";
|
|
13
|
+
import {
|
|
14
|
+
assertSafeWithinRoot,
|
|
15
|
+
atomicWriteFile,
|
|
16
|
+
hasSecretContent,
|
|
17
|
+
isForbiddenSecretPath,
|
|
18
|
+
walkNonSymlinkFiles,
|
|
19
|
+
} from "./path-safety.mjs";
|
|
20
|
+
import { getGitStatusScoped } from "./git-utils.mjs";
|
|
21
|
+
import { loadProjectManifestAndState, scanAndAllocateRecordId } from "./project-locator.mjs";
|
|
22
|
+
import { runMultiFileTransaction, withProjectLock } from "./project-lock.mjs";
|
|
23
|
+
import { listTaskLeases, verifyTaskEvidenceRefs } from "./task-manager.mjs";
|
|
24
|
+
|
|
25
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
26
|
+
const __dirname = path.dirname(__filename);
|
|
27
|
+
const DEFAULT_HARNESS_DIR = path.resolve(__dirname, "..");
|
|
28
|
+
|
|
29
|
+
const LOCAL_CHECKPOINTS = "local-runtime/checkpoints";
|
|
30
|
+
const ALLOWED_CHECKPOINT_STATUSES = new Set([
|
|
31
|
+
"created",
|
|
32
|
+
"verified",
|
|
33
|
+
"restored",
|
|
34
|
+
"expired",
|
|
35
|
+
"invalidated",
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
function loadCheckpointSchema(schemasDir) {
|
|
39
|
+
const schemaPath = path.join(schemasDir, "recovery-checkpoint.schema.json");
|
|
40
|
+
return JSON.parse(fs.readFileSync(schemaPath, "utf8"));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function buildAutoResumeInstructions({
|
|
44
|
+
summary,
|
|
45
|
+
activeTasks,
|
|
46
|
+
blockedTasks,
|
|
47
|
+
openConflicts,
|
|
48
|
+
pendingApprovals,
|
|
49
|
+
activeLeases,
|
|
50
|
+
gitStatus,
|
|
51
|
+
evidenceRef,
|
|
52
|
+
}) {
|
|
53
|
+
const parts = [];
|
|
54
|
+
if (typeof summary === "string" && summary.trim().length > 0) {
|
|
55
|
+
parts.push(`Summary: ${summary.trim()}`);
|
|
56
|
+
}
|
|
57
|
+
if (activeTasks.length > 0) {
|
|
58
|
+
parts.push(`Active task(s): ${activeTasks.join(", ")}.`);
|
|
59
|
+
} else {
|
|
60
|
+
parts.push("No active task currently set in state; inspect queued tasks or recommend next action.");
|
|
61
|
+
}
|
|
62
|
+
if (blockedTasks.length > 0) {
|
|
63
|
+
parts.push(`Blocked task(s): ${blockedTasks.join(", ")}.`);
|
|
64
|
+
}
|
|
65
|
+
if (openConflicts.length > 0) {
|
|
66
|
+
parts.push(`Open conflict(s): ${openConflicts.join(", ")}.`);
|
|
67
|
+
}
|
|
68
|
+
if (pendingApprovals.length > 0) {
|
|
69
|
+
parts.push(`Pending approval(s): ${pendingApprovals.join(", ")}.`);
|
|
70
|
+
}
|
|
71
|
+
if (activeLeases.length > 0) {
|
|
72
|
+
const leaseText = activeLeases
|
|
73
|
+
.map((l) => `${l.task_id} (${l.tool || "unknown"}/${l.role || "unassigned"})`)
|
|
74
|
+
.join(", ");
|
|
75
|
+
parts.push(`Active multi-IDE lease(s): ${leaseText}.`);
|
|
76
|
+
}
|
|
77
|
+
if (gitStatus.available) {
|
|
78
|
+
if (gitStatus.changedFiles.length > 0) {
|
|
79
|
+
const sample = gitStatus.changedFiles.slice(0, 8).join(", ");
|
|
80
|
+
const suffix = gitStatus.changedFiles.length > 8 ? ` (+${gitStatus.changedFiles.length - 8} more)` : "";
|
|
81
|
+
parts.push(`Modified files (${gitStatus.changedFiles.length}): ${sample}${suffix}.`);
|
|
82
|
+
} else {
|
|
83
|
+
parts.push("Git working tree is clean.");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (evidenceRef) {
|
|
87
|
+
parts.push(`Latest verified evidence: ${evidenceRef}.`);
|
|
88
|
+
}
|
|
89
|
+
if (activeTasks.length > 0) {
|
|
90
|
+
parts.push(
|
|
91
|
+
`Next session: run "geloforge context --task ${activeTasks[0]} --from-diff --map --profile quick" before editing.`
|
|
92
|
+
);
|
|
93
|
+
} else {
|
|
94
|
+
parts.push('Next session: run "geloforge recommend" to review priorities and pending human approvals.');
|
|
95
|
+
}
|
|
96
|
+
return parts.join(" ");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Creates a schema-valid CHKPT-NNNN recovery checkpoint and updates project state.
|
|
101
|
+
*/
|
|
102
|
+
export function createCheckpoint(options = {}) {
|
|
103
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
104
|
+
if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
|
|
105
|
+
throw new Error("Missing required project directory (--project <dir>).");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const execute = () => {
|
|
109
|
+
const { projectDir, schemasDir, compatConfig, manifest, state, stateSchema, projectPaths } =
|
|
110
|
+
loadProjectManifestAndState(options.projectDir, harnessDir);
|
|
111
|
+
|
|
112
|
+
if (!state) {
|
|
113
|
+
throw new Error(`Missing or invalid ${projectPaths.state} in ${projectDir}`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const createdAt = options.createdAt || new Date().toISOString();
|
|
117
|
+
const createdBy = String(options.createdBy || options.role || "geloforge-copilot").trim();
|
|
118
|
+
if (!createdBy) {
|
|
119
|
+
throw new Error("--created-by must not be empty.");
|
|
120
|
+
}
|
|
121
|
+
if (hasSecretContent(createdBy)) {
|
|
122
|
+
throw new Error("Refusing credential-like content in --created-by.");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const status = String(options.status || "created").trim();
|
|
126
|
+
if (!ALLOWED_CHECKPOINT_STATUSES.has(status)) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
`Invalid checkpoint status "${status}". Allowed: ${Array.from(ALLOWED_CHECKPOINT_STATUSES).join(", ")}`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
let evidenceRef = options.evidenceRef !== undefined ? options.evidenceRef : state.last_verified_evidence ?? null;
|
|
133
|
+
if (evidenceRef !== null && evidenceRef !== undefined && String(evidenceRef).trim() !== "") {
|
|
134
|
+
evidenceRef = String(evidenceRef).trim().toUpperCase();
|
|
135
|
+
if (!/^EVID-\d{4}$/.test(evidenceRef)) {
|
|
136
|
+
throw new Error(`Invalid --evidence ref "${evidenceRef}". Expected EVID-NNNN.`);
|
|
137
|
+
}
|
|
138
|
+
if (options.evidenceRef !== undefined) {
|
|
139
|
+
verifyTaskEvidenceRefs({
|
|
140
|
+
projectDir,
|
|
141
|
+
projectPaths,
|
|
142
|
+
schemasDir,
|
|
143
|
+
evidenceRefs: [evidenceRef],
|
|
144
|
+
strictExplicit: true,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
} else {
|
|
148
|
+
evidenceRef = null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const warnings = [];
|
|
152
|
+
const gitStatus = getGitStatusScoped(projectDir, warnings);
|
|
153
|
+
let activeLeases = [];
|
|
154
|
+
try {
|
|
155
|
+
activeLeases = listTaskLeases({ projectDir, nowIso: createdAt, harnessDir }).activeLeases || [];
|
|
156
|
+
} catch (err) {
|
|
157
|
+
warnings.push(`Could not inspect task leases: ${err.message}`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const activeTasks = Array.isArray(state.active_tasks) ? [...state.active_tasks] : [];
|
|
161
|
+
const resumeRaw =
|
|
162
|
+
typeof options.resumeInstructions === "string" && options.resumeInstructions.trim().length > 0
|
|
163
|
+
? options.resumeInstructions.trim()
|
|
164
|
+
: buildAutoResumeInstructions({
|
|
165
|
+
summary: options.summary || "",
|
|
166
|
+
activeTasks,
|
|
167
|
+
blockedTasks: state.blocked_tasks || [],
|
|
168
|
+
openConflicts: state.open_conflicts || [],
|
|
169
|
+
pendingApprovals: state.pending_approvals || [],
|
|
170
|
+
activeLeases,
|
|
171
|
+
gitStatus,
|
|
172
|
+
evidenceRef,
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
if (hasSecretContent(resumeRaw)) {
|
|
176
|
+
throw new Error("Refusing to write checkpoint containing credential-like content in resume_instructions.");
|
|
177
|
+
}
|
|
178
|
+
if (typeof options.summary === "string" && hasSecretContent(options.summary)) {
|
|
179
|
+
throw new Error("Refusing to write checkpoint containing credential-like content in summary.");
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const explicitId = options.id ? String(options.id).trim().toUpperCase() : null;
|
|
183
|
+
const searchDirs = Array.from(new Set([projectPaths.handoffs_dir, projectPaths.tasks_dir, LOCAL_CHECKPOINTS]));
|
|
184
|
+
const { id } = scanAndAllocateRecordId({
|
|
185
|
+
projectDir,
|
|
186
|
+
searchDirs,
|
|
187
|
+
prefix: "CHKPT",
|
|
188
|
+
explicitId,
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
const relPath = `${options.local ? LOCAL_CHECKPOINTS : projectPaths.handoffs_dir}/${id}-checkpoint.yaml`;
|
|
192
|
+
if (isForbiddenSecretPath(relPath)) {
|
|
193
|
+
throw new Error(`Refusing checkpoint destination path: ${relPath}`);
|
|
194
|
+
}
|
|
195
|
+
const targetAbs = assertSafeWithinRoot(projectDir, relPath);
|
|
196
|
+
if (fs.existsSync(targetAbs)) {
|
|
197
|
+
throw new Error(`Checkpoint file already exists: ${relPath}`);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const nextStateRevision = (state.state_revision ?? 0) + (options.local ? 0 : 1);
|
|
201
|
+
const stateRelPath = String(projectPaths.state || "brain/state/current.yaml").replace(/\\/g, "/");
|
|
202
|
+
|
|
203
|
+
const checkpointSchema = loadCheckpointSchema(schemasDir);
|
|
204
|
+
const record = {
|
|
205
|
+
schema_version: manifest.schema_version || compatConfig.default_schema_version || "1.1",
|
|
206
|
+
id,
|
|
207
|
+
project_id: manifest.project_id,
|
|
208
|
+
status,
|
|
209
|
+
memory_layer: "L2_OPERATIONAL",
|
|
210
|
+
authority_level: "A4",
|
|
211
|
+
created_at: createdAt,
|
|
212
|
+
created_by: createdBy,
|
|
213
|
+
git_branch: gitStatus.available && gitStatus.branch ? gitStatus.branch : "no-git-branch",
|
|
214
|
+
git_commit: gitStatus.available
|
|
215
|
+
? gitStatus.unborn
|
|
216
|
+
? "unborn-head"
|
|
217
|
+
: gitStatus.head || "unknown"
|
|
218
|
+
: "unavailable",
|
|
219
|
+
working_tree_clean: gitStatus.available ? !gitStatus.dirty : true,
|
|
220
|
+
active_tasks: activeTasks,
|
|
221
|
+
state_file_path: stateRelPath,
|
|
222
|
+
state_revision: nextStateRevision,
|
|
223
|
+
resume_instructions: resumeRaw,
|
|
224
|
+
verification_evidence_ref: evidenceRef,
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
const yamlText = serializeYaml(record, {
|
|
228
|
+
headerComment: `GeloForge recovery checkpoint ${id}`,
|
|
229
|
+
});
|
|
230
|
+
const roundTrip = parseYaml(yamlText, relPath);
|
|
231
|
+
const schemaCheck = validateAgainstSchema(roundTrip, checkpointSchema);
|
|
232
|
+
if (!schemaCheck.valid) {
|
|
233
|
+
throw new Error(`Checkpoint failed schema validation: ${schemaCheck.errors.join("; ")}`);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const nextState = {
|
|
237
|
+
...state,
|
|
238
|
+
updated_at: createdAt,
|
|
239
|
+
state_revision: nextStateRevision,
|
|
240
|
+
last_checkpoint: id,
|
|
241
|
+
};
|
|
242
|
+
const stateCheck = validateAgainstSchema(nextState, stateSchema);
|
|
243
|
+
if (!stateCheck.valid) {
|
|
244
|
+
throw new Error(`Updated state failed schema validation: ${stateCheck.errors.join("; ")}`);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
if (!options.dryRun && options.local) {
|
|
248
|
+
atomicWriteFile(targetAbs, yamlText, { allowOverwrite: false });
|
|
249
|
+
} else if (!options.dryRun) {
|
|
250
|
+
const stateAbs = assertSafeWithinRoot(projectDir, stateRelPath);
|
|
251
|
+
runMultiFileTransaction(
|
|
252
|
+
[
|
|
253
|
+
{ label: "checkpoint", filePath: targetAbs, content: yamlText, allowOverwrite: false },
|
|
254
|
+
{
|
|
255
|
+
label: "state",
|
|
256
|
+
filePath: stateAbs,
|
|
257
|
+
content: serializeYaml(nextState, { headerComment: "Current operational state of the project." }),
|
|
258
|
+
allowOverwrite: true,
|
|
259
|
+
},
|
|
260
|
+
],
|
|
261
|
+
{ projectDir, faultHook: options._faultHook }
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
return {
|
|
266
|
+
dryRun: Boolean(options.dryRun),
|
|
267
|
+
projectDir,
|
|
268
|
+
checkpointId: id,
|
|
269
|
+
recordPath: relPath,
|
|
270
|
+
record: roundTrip,
|
|
271
|
+
stateRevision: nextStateRevision,
|
|
272
|
+
changedFiles: gitStatus.changedFiles || [],
|
|
273
|
+
activeLeases,
|
|
274
|
+
warnings,
|
|
275
|
+
nextCommand:
|
|
276
|
+
activeTasks.length > 0
|
|
277
|
+
? `geloforge context --task ${activeTasks[0]} --from-diff --map --profile quick`
|
|
278
|
+
: "geloforge recommend",
|
|
279
|
+
};
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
if (options.dryRun) {
|
|
283
|
+
return execute();
|
|
284
|
+
}
|
|
285
|
+
return withProjectLock(options.projectDir, execute, {
|
|
286
|
+
lockTimeoutMs: options.lockTimeoutMs,
|
|
287
|
+
staleLockMs: options.staleLockMs,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function scanCheckpointsInternal({ projectDir, schemasDir, compatConfig, projectPaths, projectId }) {
|
|
292
|
+
const schema = loadCheckpointSchema(schemasDir);
|
|
293
|
+
const searchDirs = Array.from(new Set([projectPaths.handoffs_dir, projectPaths.tasks_dir, LOCAL_CHECKPOINTS]));
|
|
294
|
+
const warnings = [];
|
|
295
|
+
const checkpoints = [];
|
|
296
|
+
const seenFiles = new Set();
|
|
297
|
+
|
|
298
|
+
for (const relDir of searchDirs) {
|
|
299
|
+
const absDir = assertSafeWithinRoot(projectDir, relDir);
|
|
300
|
+
const files = walkNonSymlinkFiles(
|
|
301
|
+
projectDir,
|
|
302
|
+
absDir,
|
|
303
|
+
(p) => /^CHKPT-\d{4}.*\.ya?ml$/i.test(path.basename(p)),
|
|
304
|
+
warnings
|
|
305
|
+
);
|
|
306
|
+
for (const file of files) {
|
|
307
|
+
const rel = path.relative(projectDir, file).replace(/\\/g, "/");
|
|
308
|
+
if (seenFiles.has(rel) || isForbiddenSecretPath(rel)) {
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
seenFiles.add(rel);
|
|
312
|
+
const raw = fs.readFileSync(file, "utf8");
|
|
313
|
+
if (hasSecretContent(raw)) {
|
|
314
|
+
warnings.push(`Blocked checkpoint containing credential-like content: ${rel}`);
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
let data;
|
|
318
|
+
try {
|
|
319
|
+
data = parseYaml(raw, rel);
|
|
320
|
+
} catch (err) {
|
|
321
|
+
warnings.push(`Invalid YAML in checkpoint ${rel}: ${err.message}`);
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
const verCheck = checkRecordSchemaVersion(data, compatConfig);
|
|
325
|
+
if (!verCheck.compatible) {
|
|
326
|
+
warnings.push(`Incompatible checkpoint ${rel}: ${verCheck.error}`);
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
const res = validateAgainstSchema(data, schema);
|
|
330
|
+
if (!res.valid) {
|
|
331
|
+
warnings.push(`Checkpoint ${rel} failed schema check: ${res.errors.join("; ")}`);
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (data.project_id !== projectId) {
|
|
335
|
+
warnings.push(`Checkpoint ${rel} belongs to a different project.`);
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
checkpoints.push({ relPath: rel, record: data });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
checkpoints.sort((a, b) => {
|
|
343
|
+
const tA = Date.parse(a.record.created_at || "") || 0;
|
|
344
|
+
const tB = Date.parse(b.record.created_at || "") || 0;
|
|
345
|
+
if (tB !== tA) return tB - tA;
|
|
346
|
+
return String(b.record.id).localeCompare(String(a.record.id));
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
return { checkpoints, warnings };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Lists valid recovery checkpoints ordered newest first.
|
|
354
|
+
*/
|
|
355
|
+
export function listCheckpoints(options = {}) {
|
|
356
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
357
|
+
if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
|
|
358
|
+
throw new Error("Missing required project directory (--project <dir>).");
|
|
359
|
+
}
|
|
360
|
+
const { projectDir, schemasDir, compatConfig, manifest, state, projectPaths } = loadProjectManifestAndState(
|
|
361
|
+
options.projectDir,
|
|
362
|
+
harnessDir
|
|
363
|
+
);
|
|
364
|
+
const { checkpoints, warnings } = scanCheckpointsInternal({
|
|
365
|
+
projectDir,
|
|
366
|
+
schemasDir,
|
|
367
|
+
compatConfig,
|
|
368
|
+
projectPaths,
|
|
369
|
+
projectId: manifest.project_id,
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
const statusFilter = options.status ? String(options.status).trim() : null;
|
|
373
|
+
if (statusFilter && !ALLOWED_CHECKPOINT_STATUSES.has(statusFilter)) {
|
|
374
|
+
throw new Error(`Invalid status filter "${statusFilter}".`);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const filtered = statusFilter
|
|
378
|
+
? checkpoints.filter((c) => c.record.status === statusFilter)
|
|
379
|
+
: checkpoints;
|
|
380
|
+
|
|
381
|
+
return {
|
|
382
|
+
projectDir,
|
|
383
|
+
lastCheckpointId: state?.last_checkpoint ?? null,
|
|
384
|
+
count: filtered.length,
|
|
385
|
+
checkpoints: filtered.map((c) => ({
|
|
386
|
+
id: c.record.id,
|
|
387
|
+
status: c.record.status,
|
|
388
|
+
created_at: c.record.created_at,
|
|
389
|
+
created_by: c.record.created_by,
|
|
390
|
+
git_branch: c.record.git_branch,
|
|
391
|
+
git_commit: c.record.git_commit,
|
|
392
|
+
working_tree_clean: c.record.working_tree_clean,
|
|
393
|
+
active_tasks: c.record.active_tasks,
|
|
394
|
+
state_revision: c.record.state_revision,
|
|
395
|
+
verification_evidence_ref: c.record.verification_evidence_ref,
|
|
396
|
+
resume_instructions: c.record.resume_instructions,
|
|
397
|
+
recordPath: c.relPath,
|
|
398
|
+
})),
|
|
399
|
+
warnings,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Retrieves a single recovery checkpoint (or the latest if checkpointId is omitted).
|
|
405
|
+
*/
|
|
406
|
+
export function getCheckpoint(options = {}) {
|
|
407
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
408
|
+
if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
|
|
409
|
+
throw new Error("Missing required project directory (--project <dir>).");
|
|
410
|
+
}
|
|
411
|
+
const { projectDir, schemasDir, compatConfig, manifest, state, projectPaths } = loadProjectManifestAndState(
|
|
412
|
+
options.projectDir,
|
|
413
|
+
harnessDir
|
|
414
|
+
);
|
|
415
|
+
const { checkpoints, warnings } = scanCheckpointsInternal({
|
|
416
|
+
projectDir,
|
|
417
|
+
schemasDir,
|
|
418
|
+
compatConfig,
|
|
419
|
+
projectPaths,
|
|
420
|
+
projectId: manifest.project_id,
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
let found = null;
|
|
424
|
+
if (options.checkpointId) {
|
|
425
|
+
const targetId = String(options.checkpointId).trim().toUpperCase();
|
|
426
|
+
found = checkpoints.find((c) => c.record.id === targetId) || null;
|
|
427
|
+
if (!found) {
|
|
428
|
+
throw new Error(`Checkpoint "${targetId}" was not found or failed validation.`);
|
|
429
|
+
}
|
|
430
|
+
} else if (state?.last_checkpoint && !options.newest) {
|
|
431
|
+
found = checkpoints.find((c) => c.record.id === state.last_checkpoint) || checkpoints[0] || null;
|
|
432
|
+
} else {
|
|
433
|
+
found = checkpoints[0] || null;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
if (!found) {
|
|
437
|
+
throw new Error("No recovery checkpoints found in project.");
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
return {
|
|
441
|
+
projectDir,
|
|
442
|
+
checkpointId: found.record.id,
|
|
443
|
+
recordPath: found.relPath,
|
|
444
|
+
record: found.record,
|
|
445
|
+
isLastCheckpoint: state?.last_checkpoint === found.record.id,
|
|
446
|
+
warnings,
|
|
447
|
+
};
|
|
448
|
+
}
|