@buildr-ai/buildr 0.1.0-rc.1

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 +15 -0
  3. package/docs/cli-architecture.md +62 -0
  4. package/docs/cli-reference.md +67 -0
  5. package/docs/known-limitations.md +13 -0
  6. package/examples/minimal-workspace/README.md +24 -0
  7. package/package/README.md +28 -0
  8. package/package/bootstrap/contract.yml +122 -0
  9. package/package/bootstrap/guide.md +79 -0
  10. package/package/manifest.yml +144 -0
  11. package/package/targets/runtime/skills/buildr/SKILL.md +151 -0
  12. package/package/targets/workspace/.buildr/workspace.yml +5 -0
  13. package/package/targets/workspace/AGENTS.md +5 -0
  14. package/package/targets/workspace/commands/buildr/openspec/manifest.yml +15 -0
  15. package/package/targets/workspace/commands/manifest.yml +2 -0
  16. package/package/targets/workspace/components/buildr/openspec/component.yml +16 -0
  17. package/package/targets/workspace/components/buildr/openspec/contributions/openspec-apply-sidebar.md +3 -0
  18. package/package/targets/workspace/components/buildr/openspec/contributions/openspec-archive-sidebar.md +3 -0
  19. package/package/targets/workspace/components/buildr/openspec/contributions/openspec-explore-sidebar.md +3 -0
  20. package/package/targets/workspace/components/buildr/openspec/contributions/openspec-propose-sidebar.md +3 -0
  21. package/package/targets/workspace/components/buildr/openspec/contributions/openspec-sync-sidebar.md +3 -0
  22. package/package/targets/workspace/components/buildr/openspec/contributions/task-finish-post-sync.md +1 -0
  23. package/package/targets/workspace/components/buildr/openspec/contributions/task-finish-pre-sync.md +1 -0
  24. package/package/targets/workspace/components/buildr/openspec/contributions/task-triage-change-ready.md +10 -0
  25. package/package/targets/workspace/components/manifest.yml +2 -0
  26. package/package/targets/workspace/gitignore +13 -0
  27. package/package/targets/workspace/projects/AGENTS.project.md +25 -0
  28. package/package/targets/workspace/projects/manifest.yml +2 -0
  29. package/package/targets/workspace/projects/services/manifest.yml +3 -0
  30. package/package/targets/workspace/projects/skills/manifest.yml +2 -0
  31. package/package/targets/workspace/rules/buildr/core.md +63 -0
  32. package/package/targets/workspace/rules/manifest.yml +9 -0
  33. package/package/targets/workspace/skills/buildr/git-ops/SKILL.md +73 -0
  34. package/package/targets/workspace/skills/buildr/openspec-contract-guard/SKILL.md +67 -0
  35. package/package/targets/workspace/skills/buildr/task-finish/SKILL.md +104 -0
  36. package/package/targets/workspace/skills/buildr/task-triage/SKILL.md +103 -0
  37. package/package/targets/workspace/skills/buildr/task-worktree/SKILL.md +104 -0
  38. package/package/targets/workspace/skills/manifest.yml +38 -0
  39. package/package/targets/workspace/skills/openspec/openspec-apply-change/SKILL.md +159 -0
  40. package/package/targets/workspace/skills/openspec/openspec-archive-change/SKILL.md +117 -0
  41. package/package/targets/workspace/skills/openspec/openspec-explore/SKILL.md +287 -0
  42. package/package/targets/workspace/skills/openspec/openspec-propose/SKILL.md +111 -0
  43. package/package/targets/workspace/skills/openspec/openspec-sync-specs/SKILL.md +147 -0
  44. package/package.json +67 -0
  45. package/tools/buildr +11 -0
  46. package/tools/cli/application/cli-update.mjs +219 -0
  47. package/tools/cli/application/compose-runtime.mjs +38 -0
  48. package/tools/cli/application/doctor/runtime-diagnostics.mjs +226 -0
  49. package/tools/cli/application/doctor/scope-diagnostics.mjs +440 -0
  50. package/tools/cli/application/doctor/service-diagnostics.mjs +184 -0
  51. package/tools/cli/application/doctor.mjs +201 -0
  52. package/tools/cli/application/package-maintenance/builtin-receipts.mjs +73 -0
  53. package/tools/cli/application/package-maintenance/output.mjs +148 -0
  54. package/tools/cli/application/package-maintenance/smoke-checks.mjs +469 -0
  55. package/tools/cli/application/package-maintenance/static-validation.mjs +678 -0
  56. package/tools/cli/application/package-maintenance.mjs +538 -0
  57. package/tools/cli/application/runtime.mjs +118 -0
  58. package/tools/cli/application/workspace-operations.mjs +310 -0
  59. package/tools/cli/bootstrap.mjs +6 -0
  60. package/tools/cli/command/help.mjs +292 -0
  61. package/tools/cli/command/registry.mjs +97 -0
  62. package/tools/cli/domains/commands.mjs +661 -0
  63. package/tools/cli/domains/components.mjs +922 -0
  64. package/tools/cli/domains/openspec.mjs +603 -0
  65. package/tools/cli/domains/package-assets.mjs +652 -0
  66. package/tools/cli/domains/rules.mjs +380 -0
  67. package/tools/cli/domains/runtime.mjs +94 -0
  68. package/tools/cli/domains/skills.mjs +647 -0
  69. package/tools/cli/domains/workspace.mjs +571 -0
  70. package/tools/cli/shared/infrastructure.mjs +411 -0
  71. package/tools/cli/shared/json-contracts.mjs +22 -0
  72. package/tools/cli/shared/platform.mjs +52 -0
  73. package/tools/runtime/adapter-contract.mjs +330 -0
  74. package/tools/runtime/check-claude-code.mjs +26 -0
  75. package/tools/runtime/check-codex.mjs +26 -0
  76. package/tools/runtime/projection.mjs +163 -0
  77. package/tools/runtime/render-claude-code-rules.mjs +459 -0
  78. package/tools/runtime/render-claude-code.mjs +59 -0
  79. package/tools/runtime/skills/arguments.mjs +51 -0
  80. package/tools/runtime/skills/contributions.mjs +171 -0
  81. package/tools/runtime/skills/manifests.mjs +167 -0
  82. package/tools/runtime/skills/primitives.mjs +86 -0
  83. package/tools/runtime/skills/render-plan.mjs +244 -0
  84. package/tools/runtime/skills/sources.mjs +276 -0
  85. package/tools/shared/fetch-remote-text.mjs +78 -0
  86. package/tools/verification/integrity/managed-data-integrity.mjs +107 -0
  87. package/tools/verification/integrity/managed-mutations.mjs +72 -0
  88. package/tools/verification/openspec/contract.mjs +212 -0
  89. package/tools/verification/runtime/adapter-contract.mjs +102 -0
  90. package/tools/verification/runtime/adapter-parity.mjs +99 -0
@@ -0,0 +1,411 @@
1
+ import {
2
+ fs,
3
+ crypto,
4
+ os,
5
+ path,
6
+ process,
7
+ fileURLToPath,
8
+ YAML,
9
+ PACKAGE_WORKSPACE_TARGET,
10
+ PACKAGE_BOOTSTRAP_CONTRACT,
11
+ } from '../shared/platform.mjs';
12
+
13
+ export function registerSharedInfrastructure(runtime) {
14
+ const doctor = (...args) => runtime.doctor(...args);
15
+ const workspaceSymlinkSegment = (...args) => runtime.workspaceSymlinkSegment(...args);
16
+ const collectFiles = (...args) => runtime.collectFiles(...args);
17
+ const isGitUrl = (...args) => runtime.isGitUrl(...args);
18
+ const trackWrite = (...args) => runtime.trackWrite(...args);
19
+
20
+ function optionValue(args, name, fallback) {
21
+ const index = args.indexOf(name);
22
+ if (index === -1) return fallback;
23
+ const value = args[index + 1];
24
+ if (!value || value.startsWith('--')) {
25
+ throw new Error(`Missing value for ${name}`);
26
+ }
27
+ return value;
28
+ }
29
+
30
+ function optionValueRaw(args, name, fallback) {
31
+ const index = args.indexOf(name);
32
+ if (index === -1) return fallback;
33
+ const value = args[index + 1];
34
+ if (value === undefined) {
35
+ throw new Error(`Missing value for ${name}`);
36
+ }
37
+ return value;
38
+ }
39
+
40
+ function withResolvedTarget(args) {
41
+ const nextArgs = [...args];
42
+ const targetRoot = path.resolve(optionValue(nextArgs, '--target', process.cwd()));
43
+ const targetIndex = nextArgs.indexOf('--target');
44
+ if (targetIndex === -1) {
45
+ nextArgs.push('--target', targetRoot);
46
+ } else {
47
+ nextArgs[targetIndex + 1] = targetRoot;
48
+ }
49
+ return { args: nextArgs, targetRoot };
50
+ }
51
+
52
+ function withOption(args, name, value) {
53
+ const nextArgs = [...args];
54
+ const index = nextArgs.indexOf(name);
55
+ if (index === -1) nextArgs.push(name, value);
56
+ else nextArgs[index + 1] = value;
57
+ return nextArgs;
58
+ }
59
+
60
+ function skillScopeForRuleScope(scope) {
61
+ const parts = scope.split('/');
62
+ return parts[0] === 'projects' && parts[1] ? `projects/${parts[1]}` : '.';
63
+ }
64
+
65
+ function ensureDirectory(dir) {
66
+ fs.mkdirSync(dir, { recursive: true });
67
+ }
68
+
69
+ function atomicWriteFile(file, content, encoding = 'utf8') {
70
+ ensureDirectory(path.dirname(file));
71
+ const temporary = path.join(path.dirname(file), `.${path.basename(file)}.buildr-tmp-${process.pid}-${crypto.randomUUID()}`);
72
+ try {
73
+ fs.writeFileSync(temporary, content, encoding);
74
+ try {
75
+ const descriptor = fs.openSync(temporary, 'r');
76
+ try { fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); }
77
+ } catch {
78
+ // Some filesystems do not support fsync for these files; rename is still atomic.
79
+ }
80
+ fs.renameSync(temporary, file);
81
+ if (activeWorkspaceMutation && process.env.BUILDR_FAULT_AFTER_MUTATION_WRITE) {
82
+ activeWorkspaceMutation.writeCount = (activeWorkspaceMutation.writeCount || 0) + 1;
83
+ if (activeWorkspaceMutation.writeCount === Number(process.env.BUILDR_FAULT_AFTER_MUTATION_WRITE)) {
84
+ throw new Error(`Injected Buildr mutation failure after write ${activeWorkspaceMutation.writeCount}.`);
85
+ }
86
+ }
87
+ } finally {
88
+ if (fs.existsSync(temporary)) fs.rmSync(temporary, { force: true });
89
+ }
90
+ }
91
+
92
+ function atomicWriteJson(file, value) {
93
+ atomicWriteFile(file, `${JSON.stringify(value, null, 2)}\n`);
94
+ }
95
+
96
+ function parseYamlDocument(content, label = 'YAML document') {
97
+ let document;
98
+ try {
99
+ document = YAML.parseDocument(content, { uniqueKeys: true, prettyErrors: true });
100
+ } catch (error) {
101
+ throw new Error(`${label} is invalid YAML: ${error.message}`);
102
+ }
103
+ if (document.errors.length) throw new Error(`${label} is invalid YAML: ${document.errors.map((error) => error.message).join('; ')}`);
104
+ const value = document.toJS({ mapAsMap: false });
105
+ if (value === null || value === undefined) return {};
106
+ if (typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be a YAML mapping.`);
107
+ return value;
108
+ }
109
+
110
+ function mutationStateRoot(targetRoot) {
111
+ return path.join(targetRoot, '.buildr', 'mutations');
112
+ }
113
+
114
+ function mutationLockPath(targetRoot) {
115
+ return path.join(mutationStateRoot(targetRoot), 'lock.json');
116
+ }
117
+
118
+ function pathIsEqualOrInside(candidate, root) {
119
+ const relative = path.relative(root, candidate);
120
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
121
+ }
122
+
123
+ function assertSafeAssetTarget(targetRoot, target, containerRoot, label = 'Managed asset target') {
124
+ const resolvedTarget = path.resolve(target);
125
+ const resolvedContainer = path.resolve(containerRoot);
126
+ const relative = path.relative(resolvedContainer, resolvedTarget);
127
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
128
+ throw new Error(`${label} must be a strict descendant of ${resolvedContainer}: ${resolvedTarget}`);
129
+ }
130
+ const protectedRoots = [targetRoot, productRoot(), process.cwd(), os.homedir(), path.parse(resolvedTarget).root].map((item) => path.resolve(item));
131
+ for (const protectedRoot of protectedRoots) {
132
+ if (resolvedTarget === protectedRoot || pathIsEqualOrInside(protectedRoot, resolvedTarget)) {
133
+ throw new Error(`${label} is protected: ${resolvedTarget}`);
134
+ }
135
+ }
136
+ const targetRelative = path.relative(targetRoot, resolvedTarget);
137
+ if (!targetRelative.startsWith('..') && !path.isAbsolute(targetRelative)) {
138
+ const symlink = workspaceSymlinkSegment(targetRoot, targetRelative);
139
+ if (symlink) throw new Error(`${label} crosses a symbolic link: ${symlink}`);
140
+ }
141
+ return resolvedTarget;
142
+ }
143
+
144
+ function normalizedGitIdentity(value) {
145
+ if (!value) return null;
146
+ const trimmed = String(value).trim().replace(/\/$/, '').replace(/\.git$/, '');
147
+ if (trimmed.startsWith('file://')) {
148
+ try { return path.resolve(new URL(trimmed).pathname).replace(/\.git$/, ''); } catch {}
149
+ }
150
+ if (!isGitUrl(trimmed) && fs.existsSync(trimmed)) return path.resolve(trimmed).replace(/\.git$/, '');
151
+ return trimmed;
152
+ }
153
+
154
+ function sameGitIdentity(left, right) {
155
+ return normalizedGitIdentity(left) === normalizedGitIdentity(right);
156
+ }
157
+
158
+ function snapshotMutationPath(transactionRoot, targetRoot, target, index) {
159
+ const resolved = path.resolve(target);
160
+ const relative = toPosixRelative(targetRoot, resolved);
161
+ const backup = path.join(transactionRoot, 'backup', String(index));
162
+ const existed = fs.existsSync(resolved);
163
+ if (existed) {
164
+ ensureDirectory(path.dirname(backup));
165
+ fs.cpSync(resolved, backup, { recursive: true, preserveTimestamps: true });
166
+ }
167
+ return { target: resolved, relative, backup, existed };
168
+ }
169
+
170
+ function restoreMutationSnapshot(snapshot) {
171
+ if (fs.existsSync(snapshot.target)) fs.rmSync(snapshot.target, { recursive: true, force: true });
172
+ if (snapshot.existed) {
173
+ ensureDirectory(path.dirname(snapshot.target));
174
+ fs.cpSync(snapshot.backup, snapshot.target, { recursive: true, preserveTimestamps: true });
175
+ }
176
+ }
177
+
178
+ let activeWorkspaceMutation = null;
179
+
180
+ function withWorkspaceMutation(targetRoot, operation, affectedPaths, callback) {
181
+ const root = path.resolve(targetRoot);
182
+ if (activeWorkspaceMutation?.targetRoot === root) return callback(activeWorkspaceMutation);
183
+ for (const affectedPath of affectedPaths) {
184
+ const resolved = path.resolve(affectedPath);
185
+ const relative = path.relative(root, resolved);
186
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) throw new Error(`Mutation target must stay inside workspace and cannot be the workspace root: ${resolved}`);
187
+ const symlink = workspaceSymlinkSegment(root, relative);
188
+ if (symlink) throw new Error(`Mutation target crosses a symbolic link: ${symlink}`);
189
+ }
190
+ const lockFile = mutationLockPath(root);
191
+ if (existsFile(lockFile)) {
192
+ let existing = {};
193
+ try { existing = JSON.parse(fs.readFileSync(lockFile, 'utf8')); } catch {}
194
+ throw new Error(`Workspace source mutation is blocked by incomplete transaction ${existing.transactionId || '<unknown>'} (${existing.operation || 'unknown operation'}). Run buildr doctor --target ${root} --json.`);
195
+ }
196
+ const transactionId = `${Date.now()}-${process.pid}-${crypto.randomUUID()}`;
197
+ const transactionRoot = path.join(mutationStateRoot(root), transactionId);
198
+ ensureDirectory(transactionRoot);
199
+ const record = { schemaVersion: 'buildr.mutation/v1', transactionId, operation, phase: 'preflight', affectedPaths: [...new Set(affectedPaths.map((item) => toPosixRelative(root, path.resolve(item))))], startedAt: new Date().toISOString() };
200
+ try {
201
+ fs.writeFileSync(lockFile, `${JSON.stringify(record, null, 2)}\n`, { flag: 'wx' });
202
+ } catch (error) {
203
+ fs.rmSync(transactionRoot, { recursive: true, force: true });
204
+ throw new Error(`Cannot acquire workspace mutation lock: ${error.message}`);
205
+ }
206
+ let snapshots;
207
+ try {
208
+ snapshots = [...new Set(affectedPaths.map((item) => path.resolve(item)))].map((item, index) => snapshotMutationPath(transactionRoot, root, item, index));
209
+ } catch (error) {
210
+ fs.rmSync(transactionRoot, { recursive: true, force: true });
211
+ fs.rmSync(lockFile, { force: true });
212
+ throw error;
213
+ }
214
+ const journalSnapshots = snapshots.map(({ target, relative, existed }, index) => ({ index, target, relative, existed }));
215
+ record.phase = 'commit';
216
+ atomicWriteJson(path.join(transactionRoot, 'journal.json'), { ...record, snapshots: journalSnapshots });
217
+ activeWorkspaceMutation = { targetRoot: root, transactionId, transactionRoot, record };
218
+ try {
219
+ const result = callback(activeWorkspaceMutation);
220
+ record.phase = 'committed';
221
+ atomicWriteJson(path.join(transactionRoot, 'journal.json'), { ...record, snapshots: journalSnapshots });
222
+ fs.rmSync(transactionRoot, { recursive: true, force: true });
223
+ fs.rmSync(lockFile, { force: true });
224
+ return result;
225
+ } catch (error) {
226
+ record.phase = 'rollback';
227
+ try {
228
+ for (const snapshot of [...snapshots].reverse()) restoreMutationSnapshot(snapshot);
229
+ record.phase = 'rolled-back';
230
+ atomicWriteJson(path.join(transactionRoot, 'journal.json'), { ...record, snapshots: journalSnapshots });
231
+ fs.rmSync(transactionRoot, { recursive: true, force: true });
232
+ fs.rmSync(lockFile, { force: true });
233
+ } catch (rollbackError) {
234
+ record.phase = 'rollback-failed';
235
+ record.error = error.message;
236
+ record.rollbackError = rollbackError.message;
237
+ atomicWriteJson(path.join(transactionRoot, 'journal.json'), { ...record, snapshots: journalSnapshots });
238
+ throw new Error(`${error.message}\nRollback failed: ${rollbackError.message}. Run buildr doctor --target ${root} --json.`);
239
+ }
240
+ throw error;
241
+ } finally {
242
+ activeWorkspaceMutation = null;
243
+ }
244
+ }
245
+
246
+ function productRoot() {
247
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
248
+ }
249
+
250
+ function packageRoot() {
251
+ return path.join(productRoot(), 'package');
252
+ }
253
+
254
+ function packageWorkspaceTargetRoot() {
255
+ return path.join(productRoot(), PACKAGE_WORKSPACE_TARGET);
256
+ }
257
+
258
+ function packageBootstrapContractPath() {
259
+ return path.join(productRoot(), PACKAGE_BOOTSTRAP_CONTRACT);
260
+ }
261
+
262
+ function developmentWorkspaceRoot() {
263
+ const root = productRoot();
264
+ const parent = path.resolve(root, '..');
265
+ if (
266
+ path.basename(root) === 'product' &&
267
+ existsFile(path.join(parent, 'AGENTS.md')) &&
268
+ existsDirectory(path.join(parent, 'rules'))
269
+ ) {
270
+ return parent;
271
+ }
272
+ return null;
273
+ }
274
+
275
+ function renderTemplate(content, variables) {
276
+ return content.replace(/\{\{([A-Za-z0-9_]+)\}\}/g, (_, key) => {
277
+ if (variables[key] === undefined) {
278
+ throw new Error(`Missing template variable: ${key}`);
279
+ }
280
+ return variables[key];
281
+ });
282
+ }
283
+
284
+ function writeIfMissing(file, content) {
285
+ if (fs.existsSync(file)) return false;
286
+ atomicWriteFile(file, content);
287
+ return true;
288
+ }
289
+
290
+ function writeMappedFileIfMissing(targetRoot, outputRoot, entry, variables, created) {
291
+ const sourceFile = path.resolve(productRoot(), entry.source);
292
+ const targetFile = path.join(outputRoot, entry.target);
293
+ const sourceContent = fs.readFileSync(sourceFile, 'utf8');
294
+ const content = entry.mode === 'render' ? renderTemplate(sourceContent, variables) : sourceContent;
295
+ trackWrite(targetRoot, targetFile, content, created);
296
+ }
297
+
298
+ function appendGitignoreEntries(file, entries) {
299
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
300
+ const lines = new Set(existing.split(/\r?\n/).filter(Boolean));
301
+ const missing = entries.filter((entry) => !lines.has(entry));
302
+ if (missing.length === 0) return false;
303
+
304
+ const prefix = existing && !existing.endsWith('\n') ? '\n' : '';
305
+ atomicWriteFile(file, `${existing}${prefix}${missing.join('\n')}\n`);
306
+ return true;
307
+ }
308
+
309
+ function hasFlag(args, name) {
310
+ return args.includes(name);
311
+ }
312
+
313
+ function toPosixRelative(from, to) {
314
+ const relative = path.relative(from, to).split(path.sep).join('/');
315
+ return relative || '.';
316
+ }
317
+
318
+ function existsDirectory(dir) {
319
+ return fs.existsSync(dir) && fs.statSync(dir).isDirectory();
320
+ }
321
+
322
+ function existsFile(file) {
323
+ return fs.existsSync(file) && fs.statSync(file).isFile();
324
+ }
325
+
326
+ const BUILDR_REQUIRED_BLOCK_START = '<!-- buildr:required begin -->';
327
+ const BUILDR_REQUIRED_BLOCK_END = '<!-- buildr:required end -->';
328
+ const BUILDR_REQUIRED_BLOCK = [
329
+ BUILDR_REQUIRED_BLOCK_START,
330
+ '请读取并遵循 [Buildr Core](rules/buildr/core.md)。',
331
+ BUILDR_REQUIRED_BLOCK_END,
332
+ '',
333
+ ].join('\n');
334
+
335
+ function ensureRootRequiredBlock(targetRoot, changed = []) {
336
+ const agentsPath = path.join(targetRoot, 'AGENTS.md');
337
+ const existing = existsFile(agentsPath) ? fs.readFileSync(agentsPath, 'utf8') : '';
338
+ let next;
339
+ const start = existing.indexOf(BUILDR_REQUIRED_BLOCK_START);
340
+ const end = existing.indexOf(BUILDR_REQUIRED_BLOCK_END);
341
+ if (start !== -1 && end !== -1 && end > start) {
342
+ const afterEnd = end + BUILDR_REQUIRED_BLOCK_END.length;
343
+ next = `${existing.slice(0, start)}${BUILDR_REQUIRED_BLOCK.trimEnd()}${existing.slice(afterEnd)}`;
344
+ if (!next.endsWith('\n')) next += '\n';
345
+ } else {
346
+ const suffix = existing.trim() ? `\n${existing.replace(/^\s+/, '')}` : '';
347
+ next = `${BUILDR_REQUIRED_BLOCK}${suffix}`;
348
+ }
349
+ if (next !== existing) {
350
+ atomicWriteFile(agentsPath, next, 'utf8');
351
+ changed.push('AGENTS.md');
352
+ return true;
353
+ }
354
+ return false;
355
+ }
356
+
357
+ function rootRequiredBlockStatus(targetRoot) {
358
+ const agentsPath = path.join(targetRoot, 'AGENTS.md');
359
+ if (!existsFile(agentsPath)) return { exists: false, valid: false, path: 'AGENTS.md' };
360
+ const content = fs.readFileSync(agentsPath, 'utf8');
361
+ const start = content.indexOf(BUILDR_REQUIRED_BLOCK_START);
362
+ const end = content.indexOf(BUILDR_REQUIRED_BLOCK_END);
363
+ const block = start !== -1 && end !== -1 && end > start
364
+ ? content.slice(start, end + BUILDR_REQUIRED_BLOCK_END.length)
365
+ : '';
366
+ return {
367
+ exists: true,
368
+ valid: block.includes('rules/buildr/core.md'),
369
+ path: 'AGENTS.md',
370
+ };
371
+ }
372
+
373
+ function writeFileIfChanged(file, content) {
374
+ if (existsFile(file) && fs.readFileSync(file, 'utf8') === content) return false;
375
+ atomicWriteFile(file, content, 'utf8');
376
+ return true;
377
+ }
378
+
379
+ function copyFileIfChanged(sourceFile, targetFile) {
380
+ return writeFileIfChanged(targetFile, fs.readFileSync(sourceFile, 'utf8'));
381
+ }
382
+
383
+ function copyDirectoryIfChanged(sourceDir, targetDir) {
384
+ let changed = false;
385
+ for (const sourceFile of collectFiles(sourceDir)) {
386
+ const relative = path.relative(sourceDir, sourceFile);
387
+ const targetFile = path.join(targetDir, relative);
388
+ if (copyFileIfChanged(sourceFile, targetFile)) changed = true;
389
+ }
390
+ return changed;
391
+ }
392
+
393
+ function isInitializedBuildrWorkspace(targetRoot) {
394
+ return existsFile(path.join(targetRoot, 'AGENTS.md')) &&
395
+ existsFile(path.join(targetRoot, '.buildr', 'workspace.yml')) &&
396
+ existsDirectory(path.join(targetRoot, 'projects'));
397
+ }
398
+
399
+ function assertInitializedBuildrWorkspace(targetRoot) {
400
+ if (!isInitializedBuildrWorkspace(targetRoot)) {
401
+ throw new Error(`Target is not an initialized Buildr workspace: ${targetRoot}. 请先运行 buildr init。`);
402
+ }
403
+ }
404
+
405
+ function addDoctorFinding(result, status, code, message, extra = {}) {
406
+ result.findings.push({ status, code, message, ...extra });
407
+ }
408
+
409
+ Object.assign(runtime, { optionValue, optionValueRaw, withResolvedTarget, withOption, skillScopeForRuleScope, ensureDirectory, atomicWriteFile, atomicWriteJson, parseYamlDocument, mutationStateRoot, mutationLockPath, pathIsEqualOrInside, assertSafeAssetTarget, normalizedGitIdentity, sameGitIdentity, snapshotMutationPath, restoreMutationSnapshot, withWorkspaceMutation, productRoot, packageRoot, packageWorkspaceTargetRoot, packageBootstrapContractPath, developmentWorkspaceRoot, renderTemplate, writeIfMissing, writeMappedFileIfMissing, appendGitignoreEntries, hasFlag, toPosixRelative, existsDirectory, existsFile, ensureRootRequiredBlock, rootRequiredBlockStatus, writeFileIfChanged, copyFileIfChanged, copyDirectoryIfChanged, isInitializedBuildrWorkspace, assertInitializedBuildrWorkspace, addDoctorFinding });
410
+ return runtime;
411
+ }
@@ -0,0 +1,22 @@
1
+ export const PUBLIC_JSON_SCHEMAS = Object.freeze({
2
+ builtinList: 'buildr.builtin-list/v1',
3
+ commandsCheck: 'buildr.commands-check/v1',
4
+ componentCheck: 'buildr.component-check/v1',
5
+ componentList: 'buildr.component-list/v1',
6
+ doctor: 'buildr.doctor/v1',
7
+ openspecBaseline: 'buildr.openspec-baseline/v1',
8
+ openspecCheck: 'buildr.openspec-check/v1',
9
+ runtimeList: 'buildr.runtime-list/v1',
10
+ update: 'buildr.update/v1',
11
+ updateCheck: 'buildr.update-check/v1',
12
+ });
13
+
14
+ export function withJsonSchema(schemaVersion, payload) {
15
+ if (!Object.values(PUBLIC_JSON_SCHEMAS).includes(schemaVersion)) {
16
+ throw new Error(`Unknown public JSON schema: ${schemaVersion}`);
17
+ }
18
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
19
+ throw new Error(`Public JSON payload must be an object: ${schemaVersion}`);
20
+ }
21
+ return { schemaVersion, ...payload };
22
+ }
@@ -0,0 +1,52 @@
1
+ import fs from 'node:fs';
2
+ import crypto from 'node:crypto';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import process from 'node:process';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { execFileSync, spawnSync } from 'node:child_process';
8
+ import YAML from 'yaml';
9
+ import { checkClaudeCodeRuntime, printRuntimeCheckReport } from '../../runtime/check-claude-code.mjs';
10
+ import { hasManagedSkillMarker, parseInstallClaudeCodeBuildrSkillArgs } from '../../runtime/render-claude-code.mjs';
11
+ import { buildRuleDiscoveryPlan, hasManagedRulesMarker, renderClaudeCodeRules, resolveRuleScope } from '../../runtime/render-claude-code-rules.mjs';
12
+ import { checkCodexRuntime, printCodexRuntimeCheckReport } from '../../runtime/check-codex.mjs';
13
+ import { assembleRuntimeProjection } from '../../runtime/projection.mjs';
14
+ import {
15
+ RUNTIME_ADAPTERS,
16
+ SUPPORTED_AGENT_IDS,
17
+ UNSUPPORTED_AGENT_GUIDANCE,
18
+ getRuntimeAdapter,
19
+ isSupportedAgent,
20
+ reconcileRuntimePlan,
21
+ runtimeDiscoveryPayload,
22
+ } from '../../runtime/adapter-contract.mjs';
23
+
24
+ const PACKAGE_WORKSPACE_TARGET = 'package/targets/workspace';
25
+ const PACKAGE_RUNTIME_TARGET = 'package/targets/runtime';
26
+ const PACKAGE_BOOTSTRAP_CONTRACT = 'package/bootstrap/contract.yml';
27
+ const LEGACY_PACKAGE_PATHS = [
28
+ 'package/workspace',
29
+ 'package/agent-skills',
30
+ 'package/bootstrap/bootstrap.contract.yml',
31
+ ];
32
+ const OPENSPEC_CONTRACT_BASELINE_SCHEMA = 'buildr.openspec-contract-baseline/v1';
33
+ const OPENSPEC_CONTRACT_RECEIPT_SCHEMA = 'buildr.openspec-contract-receipt/v1';
34
+ const OPENSPEC_CONTRACT_SUPPORTED_UPSTREAM_VERSIONS = new Set(['1.4.1']);
35
+ const RUNTIME_CHECKERS = { 'claude-code': checkClaudeCodeRuntime, codex: checkCodexRuntime };
36
+ const RUNTIME_CHECK_PRINTERS = { 'claude-code': printRuntimeCheckReport, codex: printCodexRuntimeCheckReport };
37
+ const BUILDR_REQUIRED_BLOCK_START = '<!-- buildr:required begin -->';
38
+
39
+ export {
40
+ fs, crypto, os, path, process, fileURLToPath, execFileSync, spawnSync, YAML,
41
+ checkClaudeCodeRuntime, printRuntimeCheckReport,
42
+ hasManagedSkillMarker, parseInstallClaudeCodeBuildrSkillArgs,
43
+ buildRuleDiscoveryPlan, hasManagedRulesMarker, renderClaudeCodeRules, resolveRuleScope,
44
+ checkCodexRuntime, printCodexRuntimeCheckReport, assembleRuntimeProjection,
45
+ RUNTIME_ADAPTERS, SUPPORTED_AGENT_IDS, UNSUPPORTED_AGENT_GUIDANCE,
46
+ getRuntimeAdapter, isSupportedAgent, reconcileRuntimePlan, runtimeDiscoveryPayload,
47
+ PACKAGE_WORKSPACE_TARGET, PACKAGE_RUNTIME_TARGET, PACKAGE_BOOTSTRAP_CONTRACT,
48
+ LEGACY_PACKAGE_PATHS, OPENSPEC_CONTRACT_BASELINE_SCHEMA,
49
+ OPENSPEC_CONTRACT_RECEIPT_SCHEMA, OPENSPEC_CONTRACT_SUPPORTED_UPSTREAM_VERSIONS,
50
+ RUNTIME_CHECKERS, RUNTIME_CHECK_PRINTERS,
51
+ BUILDR_REQUIRED_BLOCK_START,
52
+ };