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.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +72 -2
  3. package/THIRD_PARTY_NOTICES.md +33 -0
  4. package/VERSION +1 -0
  5. package/adapters/n8n/staging-audit-error-workflow.json +132 -0
  6. package/core/adopt-project.mjs +458 -0
  7. package/core/audit-learning.mjs +68 -0
  8. package/core/audit-provider.mjs +88 -0
  9. package/core/autonomous-audit.mjs +214 -0
  10. package/core/checkpoint.mjs +448 -0
  11. package/core/codebase-map.mjs +886 -0
  12. package/core/compatibility.json +16 -0
  13. package/core/compatibility.mjs +123 -0
  14. package/core/context-cache.mjs +113 -0
  15. package/core/context-compiler.mjs +1315 -0
  16. package/core/evidence-capture.mjs +347 -0
  17. package/core/git-utils.mjs +167 -0
  18. package/core/handoff.mjs +815 -0
  19. package/core/json-schema-lite.mjs +119 -0
  20. package/core/mcp-init.mjs +251 -0
  21. package/core/mcp-server.mjs +915 -0
  22. package/core/operation-approval.mjs +102 -0
  23. package/core/path-safety.mjs +508 -0
  24. package/core/project-locator.mjs +231 -0
  25. package/core/project-lock.mjs +438 -0
  26. package/core/project-status.mjs +635 -0
  27. package/core/project-validator.mjs +544 -0
  28. package/core/promotion.mjs +90 -0
  29. package/core/runtime-files.mjs +40 -0
  30. package/core/skills-history.mjs +572 -0
  31. package/core/skills-lifecycle.mjs +2225 -0
  32. package/core/skills-lint.mjs +365 -0
  33. package/core/skills.mjs +1449 -0
  34. package/core/staging-audit.mjs +454 -0
  35. package/core/staging-evidence.mjs +127 -0
  36. package/core/task-manager.mjs +1044 -0
  37. package/core/template-utils.mjs +190 -0
  38. package/core/text-utils.mjs +48 -0
  39. package/core/verify-task.mjs +48 -0
  40. package/core/worktrees.mjs +64 -0
  41. package/core/yaml-subset.mjs +572 -0
  42. package/package.json +50 -4
  43. package/policies/approval-boundaries.md +42 -0
  44. package/policies/memory-policy.md +53 -0
  45. package/policies/token-efficiency.md +30 -0
  46. package/schemas/README.md +43 -0
  47. package/schemas/adr.schema.json +64 -0
  48. package/schemas/agent-handoff.schema.json +139 -0
  49. package/schemas/approval-record.schema.json +110 -0
  50. package/schemas/conflict-record.schema.json +60 -0
  51. package/schemas/context-pack-manifest.schema.json +194 -0
  52. package/schemas/evidence-manifest.schema.json +83 -0
  53. package/schemas/incident-record.schema.json +53 -0
  54. package/schemas/project-manifest.schema.json +90 -0
  55. package/schemas/project-state.schema.json +64 -0
  56. package/schemas/recovery-checkpoint.schema.json +49 -0
  57. package/schemas/research-record.schema.json +76 -0
  58. package/schemas/task-contract.schema.json +95 -0
  59. package/scripts/bootstrap-project.mjs +357 -0
  60. package/scripts/geloforge.mjs +2512 -0
  61. package/templates/profiles/README.md +19 -0
  62. package/templates/profiles/ai-system/brain/profile.md +21 -0
  63. package/templates/profiles/ai-system/gitignore.append +5 -0
  64. package/templates/profiles/ai-system/profile.json +6 -0
  65. package/templates/profiles/automation/brain/profile.md +19 -0
  66. package/templates/profiles/automation/gitignore.append +5 -0
  67. package/templates/profiles/automation/profile.json +6 -0
  68. package/templates/profiles/desktop/brain/profile.md +21 -0
  69. package/templates/profiles/desktop/gitignore.append +7 -0
  70. package/templates/profiles/desktop/profile.json +6 -0
  71. package/templates/profiles/mobile/brain/profile.md +20 -0
  72. package/templates/profiles/mobile/gitignore.append +8 -0
  73. package/templates/profiles/mobile/profile.json +6 -0
  74. package/templates/profiles/web/brain/profile.md +21 -0
  75. package/templates/profiles/web/gitignore.append +6 -0
  76. package/templates/profiles/web/profile.json +6 -0
  77. package/templates/project-starter/AGENTS.md +27 -0
  78. package/templates/project-starter/GEMINI.md +16 -0
  79. package/templates/project-starter/README.md +26 -0
  80. package/templates/project-starter/brain/INDEX.md +40 -0
  81. package/templates/project-starter/brain/architecture/overview.md +30 -0
  82. package/templates/project-starter/brain/decisions/.gitkeep +0 -0
  83. package/templates/project-starter/brain/manifest.yaml +36 -0
  84. package/templates/project-starter/brain/requirements/constraints.md +29 -0
  85. package/templates/project-starter/brain/requirements/prd.md +37 -0
  86. package/templates/project-starter/brain/state/current.yaml +19 -0
  87. package/templates/project-starter/gitignore.template +25 -0
  88. package/templates/project-starter/src/.gitkeep +0 -0
  89. package/templates/project-starter/tasks/.gitkeep +0 -0
  90. package/templates/project-starter/tests/.gitkeep +0 -0
@@ -0,0 +1,544 @@
1
+ /**
2
+ * Reusable project Second Brain validator.
3
+ * Verifies core files, manifest/state schemas, version compatibility, record schemas,
4
+ * duplicate IDs, cross-record references, markdown links, and portability hygiene.
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { parseYaml, extractFrontmatter } from "./yaml-subset.mjs";
11
+ import { validateAgainstSchema } from "./json-schema-lite.mjs";
12
+ import { assertSafeWithinRoot, isForbiddenSecretPath, walkNonSymlinkFiles } from "./path-safety.mjs";
13
+ import { resolveProjectPaths } from "./project-locator.mjs";
14
+ import {
15
+ loadCompatibilityConfig,
16
+ checkManifestCompatibility,
17
+ checkRecordSchemaVersion,
18
+ } from "./compatibility.mjs";
19
+
20
+ const __filename = fileURLToPath(import.meta.url);
21
+ const __dirname = path.dirname(__filename);
22
+ const HARNESS_DIR = path.resolve(__dirname, "..");
23
+ const SCHEMAS_DIR = path.join(HARNESS_DIR, "schemas");
24
+
25
+ const RECORD_TYPES = [
26
+ { prefix: "ADR", regex: /^ADR-\d{4}.*\.md$/i, schema: "adr.schema.json", frontmatter: true },
27
+ { prefix: "RES", regex: /^RES-\d{4}.*\.md$/i, schema: "research-record.schema.json", frontmatter: true },
28
+ { prefix: "TASK", regex: /^TASK-\d{4}.*\.ya?ml$/i, schema: "task-contract.schema.json", frontmatter: false },
29
+ { prefix: "HANDOFF", regex: /^HANDOFF-\d{4}.*\.ya?ml$/i, schema: "agent-handoff.schema.json", frontmatter: false },
30
+ { prefix: "EVID", regex: /^EVID-\d{4}.*\.ya?ml$/i, schema: "evidence-manifest.schema.json", frontmatter: false },
31
+ { prefix: "APPR", regex: /^APPR-\d{4}.*\.ya?ml$/i, schema: "approval-record.schema.json", frontmatter: false },
32
+ { prefix: "CONF", regex: /^CONF-\d{4}.*\.ya?ml$/i, schema: "conflict-record.schema.json", frontmatter: false },
33
+ { prefix: "INC", regex: /^INC-\d{4}.*\.ya?ml$/i, schema: "incident-record.schema.json", frontmatter: false },
34
+ { prefix: "CHKPT", regex: /^CHKPT-\d{4}.*\.ya?ml$/i, schema: "recovery-checkpoint.schema.json", frontmatter: false },
35
+ { prefix: "CPACK", regex: /^CPACK-\d{4}.*\.ya?ml$/i, schema: "context-pack-manifest.schema.json", frontmatter: false },
36
+ ];
37
+
38
+ const SCHEMA_CACHE = new Map();
39
+
40
+ function loadSchema(schemaName) {
41
+ if (!SCHEMA_CACHE.has(schemaName)) {
42
+ const schemaPath = path.join(SCHEMAS_DIR, schemaName);
43
+ SCHEMA_CACHE.set(schemaName, JSON.parse(fs.readFileSync(schemaPath, "utf8")));
44
+ }
45
+ return SCHEMA_CACHE.get(schemaName);
46
+ }
47
+
48
+ function stripFencedAndInlineCode(markdown) {
49
+ const lines = markdown.replace(/\r\n/g, "\n").split("\n");
50
+ const out = [];
51
+ let inFence = false;
52
+ for (const line of lines) {
53
+ if (/^\s*```/.test(line)) {
54
+ inFence = !inFence;
55
+ continue;
56
+ }
57
+ if (!inFence) {
58
+ out.push(line.replace(/`[^`]*`/g, ""));
59
+ }
60
+ }
61
+ return out.join("\n");
62
+ }
63
+
64
+ const IGNORED_PROJECT_SCAN_DIRS = new Set([
65
+ ".git",
66
+ "node_modules",
67
+ ".venv",
68
+ "venv",
69
+ "__pycache__",
70
+ "dist",
71
+ "build",
72
+ "target",
73
+ ".next",
74
+ ".nuxt",
75
+ "vendor",
76
+ "obj",
77
+ "coverage",
78
+ ".cache",
79
+ ]);
80
+
81
+ function isSecondBrainOrGuideRelPath(relPath, projectPaths) {
82
+ const norm = relPath.replace(/\\/g, "/");
83
+ if (norm === "AGENTS.md" || norm === "GEMINI.md" || norm === "CLAUDE.md") {
84
+ return true;
85
+ }
86
+ const prefixes = [
87
+ "brain/",
88
+ `${projectPaths.tasks_dir}/`,
89
+ `${projectPaths.evidence_dir}/`,
90
+ `${projectPaths.proposals_dir}/`,
91
+ `${projectPaths.handoffs_dir}/`,
92
+ ];
93
+ return prefixes.some((p) => norm.startsWith(p) || norm === p.slice(0, -1));
94
+ }
95
+
96
+ function matchRecordType(fileName) {
97
+ for (const spec of RECORD_TYPES) {
98
+ if (spec.regex.test(fileName)) {
99
+ return spec;
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+
105
+ export function validateProject(rawProjectDir, options = {}) {
106
+ const errors = [];
107
+ const warnings = [];
108
+ const compatConfig = options.compatibilityConfig || loadCompatibilityConfig();
109
+ const referenceDate = options.referenceDate || new Date().toISOString().slice(0, 10);
110
+
111
+ if (typeof rawProjectDir !== "string" || rawProjectDir.trim().length === 0) {
112
+ return {
113
+ valid: false,
114
+ errors: ["Project path must be a non-empty string."],
115
+ warnings,
116
+ compatibilityStatus: "invalid",
117
+ recordCount: 0,
118
+ checkedMarkdownFiles: 0,
119
+ };
120
+ }
121
+
122
+ const projectDir = path.resolve(rawProjectDir);
123
+ if (!fs.existsSync(projectDir)) {
124
+ return {
125
+ valid: false,
126
+ errors: [`Project directory does not exist: ${projectDir}`],
127
+ warnings,
128
+ compatibilityStatus: "invalid",
129
+ recordCount: 0,
130
+ checkedMarkdownFiles: 0,
131
+ };
132
+ }
133
+ const projectStat = fs.lstatSync(projectDir);
134
+ if (projectStat.isSymbolicLink() || !projectStat.isDirectory()) {
135
+ return {
136
+ valid: false,
137
+ errors: [`Project root must be a real non-symlink directory: ${projectDir}`],
138
+ warnings,
139
+ compatibilityStatus: "invalid",
140
+ recordCount: 0,
141
+ checkedMarkdownFiles: 0,
142
+ };
143
+ }
144
+
145
+ let manifest = null;
146
+ let state = null;
147
+ let compatibilityStatus = "unknown";
148
+ let projectPaths = resolveProjectPaths(null);
149
+
150
+ // 1. Verify and parse brain/manifest.yaml first so custom paths can be resolved cleanly
151
+ const manifestRel = "brain/manifest.yaml";
152
+ try {
153
+ const manifestFull = assertSafeWithinRoot(projectDir, manifestRel);
154
+ if (!fs.existsSync(manifestFull)) {
155
+ errors.push(`Missing required project file: ${manifestRel}`);
156
+ } else if (!fs.lstatSync(manifestFull).isFile()) {
157
+ errors.push(`Required project path must be a regular file: ${manifestRel}`);
158
+ } else {
159
+ try {
160
+ manifest = parseYaml(fs.readFileSync(manifestFull, "utf8"), manifestRel);
161
+ const mRes = validateAgainstSchema(manifest, loadSchema("project-manifest.schema.json"));
162
+ if (!mRes.valid) {
163
+ errors.push(`brain/manifest.yaml schema error(s): ${mRes.errors.join("; ")}`);
164
+ }
165
+ const compat = checkManifestCompatibility(manifest, compatConfig);
166
+ compatibilityStatus = compat.status;
167
+ errors.push(...compat.errors);
168
+ warnings.push(...compat.warnings);
169
+ projectPaths = resolveProjectPaths(manifest);
170
+
171
+ if (manifest && manifest.paths && typeof manifest.paths === "object") {
172
+ const requiredPathKeys = [
173
+ "brain_index",
174
+ "prd",
175
+ "constraints",
176
+ "architecture",
177
+ "state",
178
+ "decisions_dir",
179
+ "tasks_dir",
180
+ ];
181
+ for (const [key, relVal] of Object.entries(manifest.paths)) {
182
+ try {
183
+ const resolved = assertSafeWithinRoot(projectDir, relVal);
184
+ if (requiredPathKeys.includes(key) && !fs.existsSync(resolved)) {
185
+ errors.push(`manifest.paths.${key} target does not exist: ${relVal}`);
186
+ }
187
+ } catch (err) {
188
+ errors.push(`manifest.paths.${key} unsafe: ${err.message}`);
189
+ }
190
+ }
191
+ }
192
+
193
+ if (manifest && manifest.profile) {
194
+ const profileGuide = path.join(projectDir, "brain", "profile.md");
195
+ if (!fs.existsSync(profileGuide)) {
196
+ errors.push(`Manifest declares profile "${manifest.profile}", but brain/profile.md is missing.`);
197
+ }
198
+ }
199
+ } catch (err) {
200
+ errors.push(`Failed to parse brain/manifest.yaml: ${err.message}`);
201
+ }
202
+ }
203
+ } catch (err) {
204
+ errors.push(`Core project file unsafe (${manifestRel}): ${err.message}`);
205
+ }
206
+
207
+ // 2. Verify remaining core required files using resolved paths
208
+ const requiredCoreFiles = Array.from(
209
+ new Set([
210
+ projectPaths.state,
211
+ projectPaths.brain_index,
212
+ projectPaths.prd,
213
+ projectPaths.constraints,
214
+ projectPaths.architecture,
215
+ ])
216
+ );
217
+ for (const rel of requiredCoreFiles) {
218
+ try {
219
+ const full = assertSafeWithinRoot(projectDir, rel);
220
+ if (!fs.existsSync(full)) {
221
+ errors.push(`Missing required project file: ${rel}`);
222
+ } else if (!fs.lstatSync(full).isFile()) {
223
+ errors.push(`Required project path must be a regular file: ${rel}`);
224
+ }
225
+ } catch (err) {
226
+ errors.push(`Core project file unsafe (${rel}): ${err.message}`);
227
+ }
228
+ }
229
+
230
+ // 3. Parse and validate operational state file
231
+ let statePath = null;
232
+ try {
233
+ statePath = assertSafeWithinRoot(projectDir, projectPaths.state);
234
+ } catch {
235
+ statePath = null;
236
+ }
237
+ if (statePath && fs.existsSync(statePath) && fs.lstatSync(statePath).isFile()) {
238
+ try {
239
+ state = parseYaml(fs.readFileSync(statePath, "utf8"), projectPaths.state);
240
+ const sVer = checkRecordSchemaVersion(state, compatConfig);
241
+ if (!sVer.compatible) {
242
+ errors.push(`${projectPaths.state}: ${sVer.error}`);
243
+ }
244
+ const sRes = validateAgainstSchema(state, loadSchema("project-state.schema.json"));
245
+ if (!sRes.valid) {
246
+ errors.push(`${projectPaths.state} schema error(s): ${sRes.errors.join("; ")}`);
247
+ }
248
+ if (manifest && state && manifest.project_id !== state.project_id) {
249
+ errors.push(
250
+ `Project ID mismatch: manifest.project_id="${manifest.project_id}" vs state.project_id="${state.project_id}"`
251
+ );
252
+ }
253
+ } catch (err) {
254
+ errors.push(`Failed to parse ${projectPaths.state}: ${err.message}`);
255
+ }
256
+ }
257
+
258
+ // 4. Scan structured records across resolved core & optional record folders
259
+ const recordDirs = Array.from(
260
+ new Set([
261
+ projectPaths.decisions_dir,
262
+ projectPaths.research_dir,
263
+ projectPaths.conflicts_dir,
264
+ projectPaths.incidents_dir,
265
+ projectPaths.tasks_dir,
266
+ projectPaths.evidence_dir,
267
+ projectPaths.proposals_dir,
268
+ projectPaths.handoffs_dir,
269
+ ])
270
+ );
271
+ const canonicalDirs = new Set(recordDirs.filter((d) => d !== projectPaths.proposals_dir));
272
+ const records = [];
273
+ const seenIds = new Map();
274
+
275
+ for (const relDir of recordDirs) {
276
+ const absDir = path.join(projectDir, relDir);
277
+ if (!fs.existsSync(absDir)) {
278
+ continue;
279
+ }
280
+ const files = walkNonSymlinkFiles(projectDir, absDir, (p) => /\.(md|ya?ml)$/i.test(p), null, {
281
+ onSymlink: (_rel, msg) => errors.push(msg),
282
+ });
283
+ for (const filePath of files) {
284
+ const fileName = path.basename(filePath);
285
+ const spec = matchRecordType(fileName);
286
+ if (!spec) {
287
+ const relUnrecognized = path.relative(projectDir, filePath).replace(/\\/g, "/");
288
+ const skillsDraftPrefix = `${projectPaths.proposals_dir.replace(/\\/g, "/")}/skills/`;
289
+ if (relDir === projectPaths.proposals_dir && relUnrecognized.startsWith(skillsDraftPrefix)) {
290
+ continue;
291
+ }
292
+ if (!/^(README|INDEX)\.md$/i.test(fileName)) {
293
+ warnings.push(`Unrecognized file in structured record directory ${relDir}: ${relUnrecognized}`);
294
+ }
295
+ continue;
296
+ }
297
+ const relFile = path.relative(projectDir, filePath).replace(/\\/g, "/");
298
+ try {
299
+ const raw = fs.readFileSync(filePath, "utf8");
300
+ const parsed = spec.frontmatter ? extractFrontmatter(raw, relFile) : parseYaml(raw, relFile);
301
+
302
+ const verCheck = checkRecordSchemaVersion(parsed, compatConfig);
303
+ if (!verCheck.compatible) {
304
+ errors.push(`${relFile}: ${verCheck.error}`);
305
+ }
306
+
307
+ const schemaRes = validateAgainstSchema(parsed, loadSchema(spec.schema));
308
+ if (!schemaRes.valid) {
309
+ errors.push(`${relFile} failed ${spec.schema}: ${schemaRes.errors.join("; ")}`);
310
+ }
311
+
312
+ if (parsed && typeof parsed.id === "string") {
313
+ if (seenIds.has(parsed.id)) {
314
+ errors.push(`Duplicate record ID "${parsed.id}" found in ${relFile} and ${seenIds.get(parsed.id)}`);
315
+ } else {
316
+ seenIds.set(parsed.id, relFile);
317
+ }
318
+ }
319
+
320
+ if (canonicalDirs.has(relDir) && parsed?.is_example === true) {
321
+ errors.push(`${relFile}: example record (is_example: true) is forbidden in canonical directory ${relDir}`);
322
+ }
323
+
324
+ if (spec.prefix === "ADR" && parsed?.status === "accepted") {
325
+ if (!parsed.approved_by || !parsed.decided_at) {
326
+ errors.push(`${relFile}: accepted ADR must specify non-null approved_by and decided_at`);
327
+ }
328
+ }
329
+
330
+ if (
331
+ spec.prefix === "RES" &&
332
+ typeof parsed?.valid_until === "string" &&
333
+ /^\d{4}-\d{2}-\d{2}$/.test(parsed.valid_until) &&
334
+ parsed.valid_until < referenceDate
335
+ ) {
336
+ warnings.push(`${relFile}: research record ${parsed.id} expired on ${parsed.valid_until} (< ${referenceDate})`);
337
+ }
338
+
339
+ records.push({ relFile, spec, data: parsed });
340
+ } catch (err) {
341
+ errors.push(`Failed to parse record ${relFile}: ${err.message}`);
342
+ }
343
+ }
344
+ }
345
+
346
+ // 5. Cross-record reference integrity checks
347
+ const ensureIdExists = (sourceLabel, refId) => {
348
+ if (typeof refId === "string" && !seenIds.has(refId)) {
349
+ errors.push(`${sourceLabel}: broken reference to unknown record ID "${refId}"`);
350
+ }
351
+ };
352
+
353
+ if (state && typeof state === "object") {
354
+ for (const id of state.active_tasks || []) ensureIdExists("brain/state/current.yaml#active_tasks", id);
355
+ for (const id of state.blocked_tasks || []) ensureIdExists("brain/state/current.yaml#blocked_tasks", id);
356
+ for (const id of state.pending_approvals || []) ensureIdExists("brain/state/current.yaml#pending_approvals", id);
357
+ for (const id of state.open_conflicts || []) ensureIdExists("brain/state/current.yaml#open_conflicts", id);
358
+ if (state.last_verified_evidence) ensureIdExists("brain/state/current.yaml#last_verified_evidence", state.last_verified_evidence);
359
+ if (state.last_completed_task) ensureIdExists("brain/state/current.yaml#last_completed_task", state.last_completed_task);
360
+ if (state.last_checkpoint) ensureIdExists("brain/state/current.yaml#last_checkpoint", state.last_checkpoint);
361
+
362
+ const activeSet = new Set(state.active_tasks || []);
363
+ const blockedSet = new Set(state.blocked_tasks || []);
364
+ for (const id of activeSet) {
365
+ if (blockedSet.has(id)) {
366
+ errors.push(`brain/state/current.yaml: task "${id}" cannot be in both active_tasks and blocked_tasks`);
367
+ }
368
+ }
369
+ if (state.last_completed_task) {
370
+ if (activeSet.has(state.last_completed_task)) {
371
+ errors.push(`brain/state/current.yaml: last_completed_task "${state.last_completed_task}" cannot also be in active_tasks`);
372
+ }
373
+ if (blockedSet.has(state.last_completed_task)) {
374
+ errors.push(`brain/state/current.yaml: last_completed_task "${state.last_completed_task}" cannot also be in blocked_tasks`);
375
+ }
376
+ }
377
+ }
378
+
379
+ const evidById = new Map(
380
+ records.filter((r) => r.spec.prefix === "EVID" && r.data && typeof r.data.id === "string").map((r) => [r.data.id, r])
381
+ );
382
+
383
+ for (const { relFile, spec, data } of records) {
384
+ if (!data || typeof data !== "object") continue;
385
+
386
+ if (spec.prefix === "TASK") {
387
+ for (const dep of data.dependencies || []) ensureIdExists(`${relFile}#dependencies`, dep);
388
+ for (const ev of data.evidence_refs || []) ensureIdExists(`${relFile}#evidence_refs`, ev);
389
+ if (data.approval_ref) ensureIdExists(`${relFile}#approval_ref`, data.approval_ref);
390
+ for (const inp of data.required_inputs || []) {
391
+ if (inp && typeof inp.path === "string") {
392
+ try {
393
+ const target = assertSafeWithinRoot(projectDir, inp.path);
394
+ if (!fs.existsSync(target)) {
395
+ errors.push(`${relFile}#required_inputs: referenced file does not exist: ${inp.path}`);
396
+ }
397
+ } catch (err) {
398
+ errors.push(`${relFile}#required_inputs: ${err.message}`);
399
+ }
400
+ }
401
+ }
402
+ } else if (spec.prefix === "ADR") {
403
+ for (const sup of data.supersedes || []) ensureIdExists(`${relFile}#supersedes`, sup);
404
+ if (data.superseded_by) ensureIdExists(`${relFile}#superseded_by`, data.superseded_by);
405
+ for (const resId of data.related_research || []) ensureIdExists(`${relFile}#related_research`, resId);
406
+ if (data.approval_ref) ensureIdExists(`${relFile}#approval_ref`, data.approval_ref);
407
+ } else if (spec.prefix === "HANDOFF") {
408
+ if (data.task_id) ensureIdExists(`${relFile}#task_id`, data.task_id);
409
+ for (const ev of data.evidence_refs || []) ensureIdExists(`${relFile}#evidence_refs`, ev);
410
+ for (const conf of data.conflicts_detected || []) ensureIdExists(`${relFile}#conflicts_detected`, conf);
411
+ for (const adr of data.relevant_decisions || []) ensureIdExists(`${relFile}#relevant_decisions`, adr);
412
+ for (const ve of data.verified_evidence || []) {
413
+ if (!ve || typeof ve.id !== "string") continue;
414
+ const evRec = evidById.get(ve.id);
415
+ if (!evRec) {
416
+ errors.push(`${relFile}#verified_evidence: forged or missing evidence ID "${ve.id}"`);
417
+ continue;
418
+ }
419
+ const checks = Array.isArray(evRec.data.checks) ? evRec.data.checks : [];
420
+ const passed = checks.filter((c) => c.result === "passed").length;
421
+ const bad = checks.filter((c) => c.result === "failed" || c.result === "blocked").length;
422
+ if (evRec.data.status !== "verified" || passed === 0 || bad > 0 || evRec.data.is_example === true) {
423
+ errors.push(
424
+ `${relFile}#verified_evidence: evidence "${ve.id}" is not verified with passing checks (${passed} passed, ${bad} failed/blocked, status=${evRec.data.status})`
425
+ );
426
+ }
427
+ if (ve.path && ve.path !== evRec.relFile) {
428
+ errors.push(`${relFile}#verified_evidence: path mismatch for "${ve.id}" ("${ve.path}" vs "${evRec.relFile}")`);
429
+ }
430
+ }
431
+ for (const art of data.artifacts_produced || []) {
432
+ if (art && typeof art.path === "string") {
433
+ if (isForbiddenSecretPath(art.path)) {
434
+ errors.push(`${relFile}#artifacts_produced: forbidden secret path "${art.path}"`);
435
+ continue;
436
+ }
437
+ try {
438
+ assertSafeWithinRoot(projectDir, art.path);
439
+ } catch (err) {
440
+ errors.push(`${relFile}#artifacts_produced: ${err.message}`);
441
+ }
442
+ }
443
+ }
444
+ } else if (spec.prefix === "EVID") {
445
+ if (data.task_id) ensureIdExists(`${relFile}#task_id`, data.task_id);
446
+ } else if (spec.prefix === "CONF") {
447
+ if (data.approval_ref) ensureIdExists(`${relFile}#approval_ref`, data.approval_ref);
448
+ for (const item of data.conflicting_records || []) {
449
+ if (item && typeof item.path === "string") {
450
+ try {
451
+ const target = assertSafeWithinRoot(projectDir, item.path);
452
+ if (!fs.existsSync(target)) {
453
+ errors.push(`${relFile}#conflicting_records: referenced file does not exist: ${item.path}`);
454
+ }
455
+ } catch (err) {
456
+ errors.push(`${relFile}#conflicting_records: ${err.message}`);
457
+ }
458
+ }
459
+ }
460
+ } else if (spec.prefix === "INC") {
461
+ for (const t of data.related_tasks || []) ensureIdExists(`${relFile}#related_tasks`, t);
462
+ for (const ev of data.evidence_refs || []) ensureIdExists(`${relFile}#evidence_refs`, ev);
463
+ } else if (spec.prefix === "CHKPT") {
464
+ for (const t of data.active_tasks || []) ensureIdExists(`${relFile}#active_tasks`, t);
465
+ if (data.verification_evidence_ref) {
466
+ ensureIdExists(`${relFile}#verification_evidence_ref`, data.verification_evidence_ref);
467
+ }
468
+ }
469
+ }
470
+
471
+ // 6. Markdown links, placeholder hygiene, and portability scan
472
+ const harnessTokenRegex =
473
+ /\{\{(PROJECT_NAME|PROJECT_SLUG|PROJECT_ID|PROJECT_DESCRIPTION|PROJECT_OWNER|CREATED_AT|CREATED_DATE|HARNESS_VERSION|TEMPLATE_VERSION|PROFILE_NAME|PROFILE_VERSION)\}\}/;
474
+ const isProjectMemoryFile = (rel) => rel === manifestRel || requiredCoreFiles.includes(rel) ||
475
+ isSecondBrainOrGuideRelPath(rel, projectPaths);
476
+ const mdFiles = walkNonSymlinkFiles(projectDir, projectDir, (p) => p.endsWith(".md"), null, {
477
+ ignoreDirs: IGNORED_PROJECT_SCAN_DIRS,
478
+ onSymlink: (_rel, msg) => errors.push(msg),
479
+ });
480
+ const linkRegex = /!?\[[^\]]*\]\(([^)]+)\)/g;
481
+ const projectBaseResolved = path.resolve(projectDir);
482
+
483
+ for (const mdFile of mdFiles) {
484
+ const relMd = path.relative(projectDir, mdFile).replace(/\\/g, "/");
485
+ const raw = fs.readFileSync(mdFile, "utf8");
486
+ if (isProjectMemoryFile(relMd) && harnessTokenRegex.test(raw)) {
487
+ errors.push(`${relMd}: contains unreplaced template placeholder`);
488
+ }
489
+ if (isSecondBrainOrGuideRelPath(relMd, projectPaths) && /(^|[^A-Za-z0-9_])([A-Za-z]:[\\/])/.test(raw)) {
490
+ errors.push(`${relMd}: contains hardcoded Windows drive path`);
491
+ }
492
+
493
+ const cleaned = stripFencedAndInlineCode(raw);
494
+ let match;
495
+ while ((match = linkRegex.exec(cleaned)) !== null) {
496
+ const rawTarget = match[1].trim().split(/\s+/)[0];
497
+ if (
498
+ !rawTarget ||
499
+ rawTarget.startsWith("#") ||
500
+ rawTarget.startsWith("http://") ||
501
+ rawTarget.startsWith("https://") ||
502
+ rawTarget.startsWith("mailto:")
503
+ ) {
504
+ continue;
505
+ }
506
+ if (rawTarget.startsWith("file://")) {
507
+ errors.push(`${relMd}: non-portable file:// link "${rawTarget}"`);
508
+ continue;
509
+ }
510
+ const targetNoHash = rawTarget.split("#")[0];
511
+ if (!targetNoHash) continue;
512
+ const resolved = path.resolve(path.dirname(mdFile), targetNoHash);
513
+ const relToRoot = path.relative(projectBaseResolved, resolved);
514
+ if (relToRoot.startsWith("..") || path.isAbsolute(relToRoot)) {
515
+ errors.push(`${relMd}: markdown link escapes project root "${rawTarget}"`);
516
+ continue;
517
+ }
518
+ if (!fs.existsSync(resolved)) {
519
+ errors.push(`${relMd}: broken relative markdown link "${rawTarget}"`);
520
+ }
521
+ }
522
+ }
523
+
524
+ // Existing application templates may intentionally contain these tokens.
525
+ const yamlFiles = walkNonSymlinkFiles(projectDir, projectDir, (p) => /\.ya?ml$/i.test(p), null, {
526
+ ignoreDirs: IGNORED_PROJECT_SCAN_DIRS,
527
+ onSymlink: (_rel, msg) => errors.push(msg),
528
+ });
529
+ for (const yf of yamlFiles) {
530
+ const relY = path.relative(projectDir, yf).replace(/\\/g, "/");
531
+ if (isProjectMemoryFile(relY) && harnessTokenRegex.test(fs.readFileSync(yf, "utf8"))) {
532
+ errors.push(`${relY}: contains unreplaced template placeholder`);
533
+ }
534
+ }
535
+
536
+ return {
537
+ valid: errors.length === 0,
538
+ errors,
539
+ warnings,
540
+ compatibilityStatus,
541
+ recordCount: records.length,
542
+ checkedMarkdownFiles: mdFiles.length,
543
+ };
544
+ }
@@ -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
+ }