geloforge 0.0.0-stage → 0.6.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.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +140 -2
  3. package/THIRD_PARTY_NOTICES.md +33 -0
  4. package/VERSION +1 -0
  5. package/core/adopt-project.mjs +458 -0
  6. package/core/checkpoint.mjs +438 -0
  7. package/core/codebase-map.mjs +886 -0
  8. package/core/compatibility.json +16 -0
  9. package/core/compatibility.mjs +123 -0
  10. package/core/context-compiler.mjs +1315 -0
  11. package/core/evidence-capture.mjs +326 -0
  12. package/core/git-utils.mjs +167 -0
  13. package/core/handoff.mjs +815 -0
  14. package/core/json-schema-lite.mjs +119 -0
  15. package/core/mcp-init.mjs +248 -0
  16. package/core/mcp-server.mjs +915 -0
  17. package/core/path-safety.mjs +508 -0
  18. package/core/project-locator.mjs +231 -0
  19. package/core/project-lock.mjs +438 -0
  20. package/core/project-status.mjs +609 -0
  21. package/core/project-validator.mjs +544 -0
  22. package/core/skills-history.mjs +572 -0
  23. package/core/skills-lifecycle.mjs +2225 -0
  24. package/core/skills-lint.mjs +365 -0
  25. package/core/skills.mjs +1449 -0
  26. package/core/task-manager.mjs +1042 -0
  27. package/core/template-utils.mjs +190 -0
  28. package/core/text-utils.mjs +48 -0
  29. package/core/verify-task.mjs +48 -0
  30. package/core/yaml-subset.mjs +572 -0
  31. package/package.json +47 -4
  32. package/policies/approval-boundaries.md +42 -0
  33. package/policies/memory-policy.md +53 -0
  34. package/policies/token-efficiency.md +30 -0
  35. package/schemas/README.md +43 -0
  36. package/schemas/adr.schema.json +64 -0
  37. package/schemas/agent-handoff.schema.json +139 -0
  38. package/schemas/approval-record.schema.json +101 -0
  39. package/schemas/conflict-record.schema.json +60 -0
  40. package/schemas/context-pack-manifest.schema.json +194 -0
  41. package/schemas/evidence-manifest.schema.json +83 -0
  42. package/schemas/incident-record.schema.json +53 -0
  43. package/schemas/project-manifest.schema.json +90 -0
  44. package/schemas/project-state.schema.json +64 -0
  45. package/schemas/recovery-checkpoint.schema.json +49 -0
  46. package/schemas/research-record.schema.json +76 -0
  47. package/schemas/task-contract.schema.json +95 -0
  48. package/scripts/bootstrap-project.mjs +357 -0
  49. package/scripts/geloforge.mjs +2291 -0
  50. package/templates/profiles/README.md +19 -0
  51. package/templates/profiles/ai-system/brain/profile.md +21 -0
  52. package/templates/profiles/ai-system/gitignore.append +5 -0
  53. package/templates/profiles/ai-system/profile.json +6 -0
  54. package/templates/profiles/automation/brain/profile.md +19 -0
  55. package/templates/profiles/automation/gitignore.append +5 -0
  56. package/templates/profiles/automation/profile.json +6 -0
  57. package/templates/profiles/desktop/brain/profile.md +21 -0
  58. package/templates/profiles/desktop/gitignore.append +7 -0
  59. package/templates/profiles/desktop/profile.json +6 -0
  60. package/templates/profiles/mobile/brain/profile.md +20 -0
  61. package/templates/profiles/mobile/gitignore.append +8 -0
  62. package/templates/profiles/mobile/profile.json +6 -0
  63. package/templates/profiles/web/brain/profile.md +21 -0
  64. package/templates/profiles/web/gitignore.append +6 -0
  65. package/templates/profiles/web/profile.json +6 -0
  66. package/templates/project-starter/AGENTS.md +26 -0
  67. package/templates/project-starter/GEMINI.md +16 -0
  68. package/templates/project-starter/README.md +26 -0
  69. package/templates/project-starter/brain/INDEX.md +40 -0
  70. package/templates/project-starter/brain/architecture/overview.md +30 -0
  71. package/templates/project-starter/brain/decisions/.gitkeep +0 -0
  72. package/templates/project-starter/brain/manifest.yaml +36 -0
  73. package/templates/project-starter/brain/requirements/constraints.md +29 -0
  74. package/templates/project-starter/brain/requirements/prd.md +37 -0
  75. package/templates/project-starter/brain/state/current.yaml +19 -0
  76. package/templates/project-starter/gitignore.template +25 -0
  77. package/templates/project-starter/src/.gitkeep +0 -0
  78. package/templates/project-starter/tasks/.gitkeep +0 -0
  79. package/templates/project-starter/tests/.gitkeep +0 -0
@@ -0,0 +1,438 @@
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
+ hasSecretContent,
16
+ isForbiddenSecretPath,
17
+ walkNonSymlinkFiles,
18
+ } from "./path-safety.mjs";
19
+ import { getGitStatusScoped } from "./git-utils.mjs";
20
+ import { loadProjectManifestAndState, scanAndAllocateRecordId } from "./project-locator.mjs";
21
+ import { runMultiFileTransaction, withProjectLock } from "./project-lock.mjs";
22
+ import { listTaskLeases, verifyTaskEvidenceRefs } from "./task-manager.mjs";
23
+
24
+ const __filename = fileURLToPath(import.meta.url);
25
+ const __dirname = path.dirname(__filename);
26
+ const DEFAULT_HARNESS_DIR = path.resolve(__dirname, "..");
27
+
28
+ const ALLOWED_CHECKPOINT_STATUSES = new Set([
29
+ "created",
30
+ "verified",
31
+ "restored",
32
+ "expired",
33
+ "invalidated",
34
+ ]);
35
+
36
+ function loadCheckpointSchema(schemasDir) {
37
+ const schemaPath = path.join(schemasDir, "recovery-checkpoint.schema.json");
38
+ return JSON.parse(fs.readFileSync(schemaPath, "utf8"));
39
+ }
40
+
41
+ function buildAutoResumeInstructions({
42
+ summary,
43
+ activeTasks,
44
+ blockedTasks,
45
+ openConflicts,
46
+ pendingApprovals,
47
+ activeLeases,
48
+ gitStatus,
49
+ evidenceRef,
50
+ }) {
51
+ const parts = [];
52
+ if (typeof summary === "string" && summary.trim().length > 0) {
53
+ parts.push(`Summary: ${summary.trim()}`);
54
+ }
55
+ if (activeTasks.length > 0) {
56
+ parts.push(`Active task(s): ${activeTasks.join(", ")}.`);
57
+ } else {
58
+ parts.push("No active task currently set in state; inspect queued tasks or recommend next action.");
59
+ }
60
+ if (blockedTasks.length > 0) {
61
+ parts.push(`Blocked task(s): ${blockedTasks.join(", ")}.`);
62
+ }
63
+ if (openConflicts.length > 0) {
64
+ parts.push(`Open conflict(s): ${openConflicts.join(", ")}.`);
65
+ }
66
+ if (pendingApprovals.length > 0) {
67
+ parts.push(`Pending approval(s): ${pendingApprovals.join(", ")}.`);
68
+ }
69
+ if (activeLeases.length > 0) {
70
+ const leaseText = activeLeases
71
+ .map((l) => `${l.task_id} (${l.tool || "unknown"}/${l.role || "unassigned"})`)
72
+ .join(", ");
73
+ parts.push(`Active multi-IDE lease(s): ${leaseText}.`);
74
+ }
75
+ if (gitStatus.available) {
76
+ if (gitStatus.changedFiles.length > 0) {
77
+ const sample = gitStatus.changedFiles.slice(0, 8).join(", ");
78
+ const suffix = gitStatus.changedFiles.length > 8 ? ` (+${gitStatus.changedFiles.length - 8} more)` : "";
79
+ parts.push(`Modified files (${gitStatus.changedFiles.length}): ${sample}${suffix}.`);
80
+ } else {
81
+ parts.push("Git working tree is clean.");
82
+ }
83
+ }
84
+ if (evidenceRef) {
85
+ parts.push(`Latest verified evidence: ${evidenceRef}.`);
86
+ }
87
+ if (activeTasks.length > 0) {
88
+ parts.push(
89
+ `Next session: run "geloforge context --task ${activeTasks[0]} --from-diff --map --profile quick" before editing.`
90
+ );
91
+ } else {
92
+ parts.push('Next session: run "geloforge recommend" to review priorities and pending human approvals.');
93
+ }
94
+ return parts.join(" ");
95
+ }
96
+
97
+ /**
98
+ * Creates a schema-valid CHKPT-NNNN recovery checkpoint and updates project state.
99
+ */
100
+ export function createCheckpoint(options = {}) {
101
+ const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
102
+ if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
103
+ throw new Error("Missing required project directory (--project <dir>).");
104
+ }
105
+
106
+ const execute = () => {
107
+ const { projectDir, schemasDir, compatConfig, manifest, state, stateSchema, projectPaths } =
108
+ loadProjectManifestAndState(options.projectDir, harnessDir);
109
+
110
+ if (!state) {
111
+ throw new Error(`Missing or invalid ${projectPaths.state} in ${projectDir}`);
112
+ }
113
+
114
+ const createdAt = options.createdAt || new Date().toISOString();
115
+ const createdBy = String(options.createdBy || options.role || "geloforge-copilot").trim();
116
+ if (!createdBy) {
117
+ throw new Error("--created-by must not be empty.");
118
+ }
119
+ if (hasSecretContent(createdBy)) {
120
+ throw new Error("Refusing credential-like content in --created-by.");
121
+ }
122
+
123
+ const status = String(options.status || "created").trim();
124
+ if (!ALLOWED_CHECKPOINT_STATUSES.has(status)) {
125
+ throw new Error(
126
+ `Invalid checkpoint status "${status}". Allowed: ${Array.from(ALLOWED_CHECKPOINT_STATUSES).join(", ")}`
127
+ );
128
+ }
129
+
130
+ let evidenceRef = options.evidenceRef !== undefined ? options.evidenceRef : state.last_verified_evidence ?? null;
131
+ if (evidenceRef !== null && evidenceRef !== undefined && String(evidenceRef).trim() !== "") {
132
+ evidenceRef = String(evidenceRef).trim().toUpperCase();
133
+ if (!/^EVID-\d{4}$/.test(evidenceRef)) {
134
+ throw new Error(`Invalid --evidence ref "${evidenceRef}". Expected EVID-NNNN.`);
135
+ }
136
+ if (options.evidenceRef !== undefined) {
137
+ verifyTaskEvidenceRefs({
138
+ projectDir,
139
+ projectPaths,
140
+ schemasDir,
141
+ evidenceRefs: [evidenceRef],
142
+ strictExplicit: true,
143
+ });
144
+ }
145
+ } else {
146
+ evidenceRef = null;
147
+ }
148
+
149
+ const warnings = [];
150
+ const gitStatus = getGitStatusScoped(projectDir, warnings);
151
+ let activeLeases = [];
152
+ try {
153
+ activeLeases = listTaskLeases({ projectDir, nowIso: createdAt, harnessDir }).activeLeases || [];
154
+ } catch (err) {
155
+ warnings.push(`Could not inspect task leases: ${err.message}`);
156
+ }
157
+
158
+ const activeTasks = Array.isArray(state.active_tasks) ? [...state.active_tasks] : [];
159
+ const resumeRaw =
160
+ typeof options.resumeInstructions === "string" && options.resumeInstructions.trim().length > 0
161
+ ? options.resumeInstructions.trim()
162
+ : buildAutoResumeInstructions({
163
+ summary: options.summary || "",
164
+ activeTasks,
165
+ blockedTasks: state.blocked_tasks || [],
166
+ openConflicts: state.open_conflicts || [],
167
+ pendingApprovals: state.pending_approvals || [],
168
+ activeLeases,
169
+ gitStatus,
170
+ evidenceRef,
171
+ });
172
+
173
+ if (hasSecretContent(resumeRaw)) {
174
+ throw new Error("Refusing to write checkpoint containing credential-like content in resume_instructions.");
175
+ }
176
+ if (typeof options.summary === "string" && hasSecretContent(options.summary)) {
177
+ throw new Error("Refusing to write checkpoint containing credential-like content in summary.");
178
+ }
179
+
180
+ const explicitId = options.id ? String(options.id).trim().toUpperCase() : null;
181
+ const searchDirs = Array.from(new Set([projectPaths.handoffs_dir, projectPaths.tasks_dir]));
182
+ const { id } = scanAndAllocateRecordId({
183
+ projectDir,
184
+ searchDirs,
185
+ prefix: "CHKPT",
186
+ explicitId,
187
+ });
188
+
189
+ const relPath = `${projectPaths.handoffs_dir}/${id}-checkpoint.yaml`;
190
+ if (isForbiddenSecretPath(relPath)) {
191
+ throw new Error(`Refusing checkpoint destination path: ${relPath}`);
192
+ }
193
+ const targetAbs = assertSafeWithinRoot(projectDir, relPath);
194
+ if (fs.existsSync(targetAbs)) {
195
+ throw new Error(`Checkpoint file already exists: ${relPath}`);
196
+ }
197
+
198
+ const nextStateRevision = (typeof state.state_revision === "number" ? state.state_revision : 0) + 1;
199
+ const stateRelPath = String(projectPaths.state || "brain/state/current.yaml").replace(/\\/g, "/");
200
+
201
+ const checkpointSchema = loadCheckpointSchema(schemasDir);
202
+ const record = {
203
+ schema_version: manifest.schema_version || compatConfig.default_schema_version || "1.1",
204
+ id,
205
+ project_id: manifest.project_id,
206
+ status,
207
+ memory_layer: "L2_OPERATIONAL",
208
+ authority_level: "A4",
209
+ created_at: createdAt,
210
+ created_by: createdBy,
211
+ git_branch: gitStatus.available && gitStatus.branch ? gitStatus.branch : "no-git-branch",
212
+ git_commit: gitStatus.available
213
+ ? gitStatus.unborn
214
+ ? "unborn-head"
215
+ : gitStatus.head || "unknown"
216
+ : "unavailable",
217
+ working_tree_clean: gitStatus.available ? !gitStatus.dirty : true,
218
+ active_tasks: activeTasks,
219
+ state_file_path: stateRelPath,
220
+ state_revision: nextStateRevision,
221
+ resume_instructions: resumeRaw,
222
+ verification_evidence_ref: evidenceRef,
223
+ };
224
+
225
+ const yamlText = serializeYaml(record, {
226
+ headerComment: `GeloForge recovery checkpoint ${id}`,
227
+ });
228
+ const roundTrip = parseYaml(yamlText, relPath);
229
+ const schemaCheck = validateAgainstSchema(roundTrip, checkpointSchema);
230
+ if (!schemaCheck.valid) {
231
+ throw new Error(`Checkpoint failed schema validation: ${schemaCheck.errors.join("; ")}`);
232
+ }
233
+
234
+ const nextState = {
235
+ ...state,
236
+ updated_at: createdAt,
237
+ state_revision: nextStateRevision,
238
+ last_checkpoint: id,
239
+ };
240
+ const stateCheck = validateAgainstSchema(nextState, stateSchema);
241
+ if (!stateCheck.valid) {
242
+ throw new Error(`Updated state failed schema validation: ${stateCheck.errors.join("; ")}`);
243
+ }
244
+
245
+ if (!options.dryRun) {
246
+ const stateAbs = assertSafeWithinRoot(projectDir, stateRelPath);
247
+ runMultiFileTransaction(
248
+ [
249
+ { label: "checkpoint", filePath: targetAbs, content: yamlText, allowOverwrite: false },
250
+ {
251
+ label: "state",
252
+ filePath: stateAbs,
253
+ content: serializeYaml(nextState, { headerComment: "Current operational state of the project." }),
254
+ allowOverwrite: true,
255
+ },
256
+ ],
257
+ { projectDir, faultHook: options._faultHook }
258
+ );
259
+ }
260
+
261
+ return {
262
+ dryRun: Boolean(options.dryRun),
263
+ projectDir,
264
+ checkpointId: id,
265
+ recordPath: relPath,
266
+ record: roundTrip,
267
+ stateRevision: nextStateRevision,
268
+ changedFiles: gitStatus.changedFiles || [],
269
+ activeLeases,
270
+ warnings,
271
+ nextCommand:
272
+ activeTasks.length > 0
273
+ ? `geloforge context --task ${activeTasks[0]} --from-diff --map --profile quick`
274
+ : "geloforge recommend",
275
+ };
276
+ };
277
+
278
+ if (options.dryRun) {
279
+ return execute();
280
+ }
281
+ return withProjectLock(options.projectDir, execute, {
282
+ lockTimeoutMs: options.lockTimeoutMs,
283
+ staleLockMs: options.staleLockMs,
284
+ });
285
+ }
286
+
287
+ function scanCheckpointsInternal({ projectDir, schemasDir, compatConfig, projectPaths }) {
288
+ const schema = loadCheckpointSchema(schemasDir);
289
+ const searchDirs = Array.from(new Set([projectPaths.handoffs_dir, projectPaths.tasks_dir]));
290
+ const warnings = [];
291
+ const checkpoints = [];
292
+ const seenFiles = new Set();
293
+
294
+ for (const relDir of searchDirs) {
295
+ const absDir = path.join(projectDir, relDir);
296
+ const files = walkNonSymlinkFiles(
297
+ projectDir,
298
+ absDir,
299
+ (p) => /^CHKPT-\d{4}.*\.ya?ml$/i.test(path.basename(p)),
300
+ warnings
301
+ );
302
+ for (const file of files) {
303
+ const rel = path.relative(projectDir, file).replace(/\\/g, "/");
304
+ if (seenFiles.has(rel) || isForbiddenSecretPath(rel)) {
305
+ continue;
306
+ }
307
+ seenFiles.add(rel);
308
+ const raw = fs.readFileSync(file, "utf8");
309
+ if (hasSecretContent(raw)) {
310
+ warnings.push(`Blocked checkpoint containing credential-like content: ${rel}`);
311
+ continue;
312
+ }
313
+ let data;
314
+ try {
315
+ data = parseYaml(raw, rel);
316
+ } catch (err) {
317
+ warnings.push(`Invalid YAML in checkpoint ${rel}: ${err.message}`);
318
+ continue;
319
+ }
320
+ const verCheck = checkRecordSchemaVersion(data, compatConfig);
321
+ if (!verCheck.compatible) {
322
+ warnings.push(`Incompatible checkpoint ${rel}: ${verCheck.error}`);
323
+ continue;
324
+ }
325
+ const res = validateAgainstSchema(data, schema);
326
+ if (!res.valid) {
327
+ warnings.push(`Checkpoint ${rel} failed schema check: ${res.errors.join("; ")}`);
328
+ continue;
329
+ }
330
+ checkpoints.push({ relPath: rel, record: data });
331
+ }
332
+ }
333
+
334
+ checkpoints.sort((a, b) => {
335
+ const tA = Date.parse(a.record.created_at || "") || 0;
336
+ const tB = Date.parse(b.record.created_at || "") || 0;
337
+ if (tB !== tA) return tB - tA;
338
+ return String(b.record.id).localeCompare(String(a.record.id));
339
+ });
340
+
341
+ return { checkpoints, warnings };
342
+ }
343
+
344
+ /**
345
+ * Lists valid recovery checkpoints ordered newest first.
346
+ */
347
+ export function listCheckpoints(options = {}) {
348
+ const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
349
+ if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
350
+ throw new Error("Missing required project directory (--project <dir>).");
351
+ }
352
+ const { projectDir, schemasDir, compatConfig, state, projectPaths } = loadProjectManifestAndState(
353
+ options.projectDir,
354
+ harnessDir
355
+ );
356
+ const { checkpoints, warnings } = scanCheckpointsInternal({
357
+ projectDir,
358
+ schemasDir,
359
+ compatConfig,
360
+ projectPaths,
361
+ });
362
+
363
+ const statusFilter = options.status ? String(options.status).trim() : null;
364
+ if (statusFilter && !ALLOWED_CHECKPOINT_STATUSES.has(statusFilter)) {
365
+ throw new Error(`Invalid status filter "${statusFilter}".`);
366
+ }
367
+
368
+ const filtered = statusFilter
369
+ ? checkpoints.filter((c) => c.record.status === statusFilter)
370
+ : checkpoints;
371
+
372
+ return {
373
+ projectDir,
374
+ lastCheckpointId: state?.last_checkpoint ?? null,
375
+ count: filtered.length,
376
+ checkpoints: filtered.map((c) => ({
377
+ id: c.record.id,
378
+ status: c.record.status,
379
+ created_at: c.record.created_at,
380
+ created_by: c.record.created_by,
381
+ git_branch: c.record.git_branch,
382
+ git_commit: c.record.git_commit,
383
+ working_tree_clean: c.record.working_tree_clean,
384
+ active_tasks: c.record.active_tasks,
385
+ state_revision: c.record.state_revision,
386
+ verification_evidence_ref: c.record.verification_evidence_ref,
387
+ resume_instructions: c.record.resume_instructions,
388
+ recordPath: c.relPath,
389
+ })),
390
+ warnings,
391
+ };
392
+ }
393
+
394
+ /**
395
+ * Retrieves a single recovery checkpoint (or the latest if checkpointId is omitted).
396
+ */
397
+ export function getCheckpoint(options = {}) {
398
+ const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
399
+ if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
400
+ throw new Error("Missing required project directory (--project <dir>).");
401
+ }
402
+ const { projectDir, schemasDir, compatConfig, state, projectPaths } = loadProjectManifestAndState(
403
+ options.projectDir,
404
+ harnessDir
405
+ );
406
+ const { checkpoints, warnings } = scanCheckpointsInternal({
407
+ projectDir,
408
+ schemasDir,
409
+ compatConfig,
410
+ projectPaths,
411
+ });
412
+
413
+ let found = null;
414
+ if (options.checkpointId) {
415
+ const targetId = String(options.checkpointId).trim().toUpperCase();
416
+ found = checkpoints.find((c) => c.record.id === targetId) || null;
417
+ if (!found) {
418
+ throw new Error(`Checkpoint "${targetId}" was not found or failed validation.`);
419
+ }
420
+ } else if (state?.last_checkpoint) {
421
+ found = checkpoints.find((c) => c.record.id === state.last_checkpoint) || checkpoints[0] || null;
422
+ } else {
423
+ found = checkpoints[0] || null;
424
+ }
425
+
426
+ if (!found) {
427
+ throw new Error("No recovery checkpoints found in project.");
428
+ }
429
+
430
+ return {
431
+ projectDir,
432
+ checkpointId: found.record.id,
433
+ recordPath: found.relPath,
434
+ record: found.record,
435
+ isLastCheckpoint: state?.last_checkpoint === found.record.id,
436
+ warnings,
437
+ };
438
+ }