@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,201 @@
1
+ import {
2
+ fs,
3
+ path,
4
+ execFileSync,
5
+ SUPPORTED_AGENT_IDS,
6
+ UNSUPPORTED_AGENT_GUIDANCE,
7
+ getRuntimeAdapter,
8
+ isSupportedAgent,
9
+ RUNTIME_CHECKERS,
10
+ } from '../shared/platform.mjs';
11
+ import { createRuntimeDiagnostics } from './doctor/runtime-diagnostics.mjs';
12
+ import { createScopeDiagnostics } from './doctor/scope-diagnostics.mjs';
13
+ import { createServiceDiagnostics } from './doctor/service-diagnostics.mjs';
14
+
15
+ export function registerApplicationDoctor(runtime) {
16
+ const runCommandsCheck = (...args) => runtime.runCommandsCheck(...args);
17
+ const componentRegistryPath = (...args) => runtime.componentRegistryPath(...args);
18
+ const packageComponentsStatus = (...args) => runtime.packageComponentsStatus(...args);
19
+ const managedRuntimeSkillOrphans = (...args) => runtime.managedRuntimeSkillOrphans(...args);
20
+ const listManagedDirectories = (...args) => runtime.listManagedDirectories(...args);
21
+ const runtimeImplementation = (...args) => runtime.runtimeImplementation(...args);
22
+ const readSkillManifestSchemaVersion = (...args) => runtime.readSkillManifestSchemaVersion(...args);
23
+ const skillsManifestPath = (...args) => runtime.skillsManifestPath(...args);
24
+ const parseYamlValue = (...args) => runtime.parseYamlValue(...args);
25
+ const parseServicesManifestYaml = (...args) => runtime.parseServicesManifestYaml(...args);
26
+ const parseProjectsYaml = (...args) => runtime.parseProjectsYaml(...args);
27
+ const validateProjectsRegistry = (...args) => runtime.validateProjectsRegistry(...args);
28
+ const validateServicesManifest = (...args) => runtime.validateServicesManifest(...args);
29
+ const projectsManifestPath = (...args) => runtime.projectsManifestPath(...args);
30
+ const servicesManifestPath = (...args) => runtime.servicesManifestPath(...args);
31
+ const gitOutput = (...args) => runtime.gitOutput(...args);
32
+ const gitCurrentBranch = (...args) => runtime.gitCurrentBranch(...args);
33
+ const gitBoundaryFor = (...args) => runtime.gitBoundaryFor(...args);
34
+ const gitBoundaryIgnored = (...args) => runtime.gitBoundaryIgnored(...args);
35
+ const toPosixRelative = (...args) => runtime.toPosixRelative(...args);
36
+ const existsDirectory = (...args) => runtime.existsDirectory(...args);
37
+ const existsFile = (...args) => runtime.existsFile(...args);
38
+ const addDoctorFinding = (...args) => runtime.addDoctorFinding(...args);
39
+
40
+ const {
41
+ scopeParts,
42
+ workspaceName,
43
+ readProjectsRegistryIfExists,
44
+ discoverDoctorScopes,
45
+ resolveRepoPath,
46
+ readGitRemote,
47
+ gitignoreLines,
48
+ isIgnoredByWorkspace,
49
+ projectDoctorContextFor,
50
+ projectBaselineStatus,
51
+ missingProjectBaselineAssets,
52
+ diagnoseProjectRegistry,
53
+ diagnoseWorkspace,
54
+ diagnoseLegacyPractices,
55
+ diagnoseHierarchy,
56
+ } = createScopeDiagnostics({
57
+ addDoctorFinding,
58
+ execFileSync,
59
+ existsDirectory,
60
+ existsFile,
61
+ fs,
62
+ gitBoundaryFor,
63
+ gitBoundaryIgnored,
64
+ gitOutput,
65
+ parseProjectsYaml,
66
+ parseYamlValue,
67
+ path,
68
+ projectsManifestPath,
69
+ servicesManifestPath,
70
+ toPosixRelative,
71
+ validateProjectsRegistry,
72
+ });
73
+ const {
74
+ diagnoseServicesMetadata,
75
+ diagnoseServices,
76
+ } = createServiceDiagnostics({
77
+ addDoctorFinding,
78
+ existsDirectory,
79
+ existsFile,
80
+ fs,
81
+ gitBoundaryFor,
82
+ gitBoundaryIgnored,
83
+ gitCurrentBranch,
84
+ gitignoreLines,
85
+ listManagedDirectories,
86
+ parseServicesManifestYaml,
87
+ path,
88
+ projectDoctorContextFor,
89
+ readGitRemote,
90
+ toPosixRelative,
91
+ validateServicesManifest,
92
+ });
93
+ const {
94
+ runtimeFindingsForDoctor,
95
+ summarizeRuntimeFindings,
96
+ addUnsupportedAgentFinding,
97
+ diagnoseRuntime,
98
+ diagnoseCommands,
99
+ diagnoseComponents,
100
+ } = createRuntimeDiagnostics({
101
+ RUNTIME_CHECKERS,
102
+ SUPPORTED_AGENT_IDS,
103
+ UNSUPPORTED_AGENT_GUIDANCE,
104
+ addDoctorFinding,
105
+ componentRegistryPath,
106
+ existsFile,
107
+ getRuntimeAdapter,
108
+ isSupportedAgent,
109
+ managedRuntimeSkillOrphans,
110
+ packageComponentsStatus,
111
+ path,
112
+ runCommandsCheck,
113
+ runtimeImplementation,
114
+ toPosixRelative,
115
+ });
116
+
117
+ function diagnoseSkillsManifestSchemas(result, targetRoot, scopes) {
118
+ const checked = new Set();
119
+ const scopeRoots = [targetRoot];
120
+ for (const scope of scopes) {
121
+ if (scope.project) scopeRoots.push(path.join(targetRoot, 'projects', scope.project));
122
+ }
123
+ for (const scopeRoot of scopeRoots) {
124
+ const manifestPath = skillsManifestPath(scopeRoot);
125
+ const relative = toPosixRelative(targetRoot, manifestPath);
126
+ if (checked.has(relative) || !existsFile(manifestPath)) continue;
127
+ checked.add(relative);
128
+ const schemaVersion = readSkillManifestSchemaVersion(manifestPath);
129
+ if (schemaVersion !== 'buildr.skills/v1') {
130
+ addDoctorFinding(result, 'warning', 'skills.schema_version_invalid', `Skills manifest schemaVersion 缺失或不支持:${relative}`, {
131
+ path: relative,
132
+ suggestion: '运行 buildr update 或 buildr sync 补齐 schemaVersion: buildr.skills/v1。',
133
+ });
134
+ }
135
+ }
136
+ }
137
+
138
+ function finalizeDoctorResult(result) {
139
+ const counts = { ok: 0, info: 0, warning: 0, error: 0 };
140
+ for (const finding of result.findings) {
141
+ counts[finding.status] = (counts[finding.status] ?? 0) + 1;
142
+ }
143
+ result.summary = counts;
144
+ result.ok = counts.error === 0;
145
+ result.nextSteps = result.findings
146
+ .filter((finding) => finding.suggestion && finding.userActionRequired !== false)
147
+ .map((finding) => ({ code: finding.code, suggestion: finding.suggestion, command: finding.command, commands: finding.commands }))
148
+ .slice(0, 10);
149
+ }
150
+
151
+ function printDoctorReport(result) {
152
+ console.log(`Buildr doctor for ${result.targetRoot}`);
153
+ console.log(`Status: ok=${result.summary.ok} info=${result.summary.info} warning=${result.summary.warning} error=${result.summary.error}`);
154
+ console.log('');
155
+
156
+ if (result.findings.length === 0) {
157
+ console.log('[ok] 未发现问题。');
158
+ return;
159
+ }
160
+
161
+ for (const finding of result.findings) {
162
+ const location = finding.path ? ` (${finding.path})` : '';
163
+ console.log(`[${finding.status}] ${finding.code}${location} - ${finding.message}`);
164
+ if (finding.suggestion) console.log(` 建议:${finding.suggestion}`);
165
+ if (finding.command) console.log(` 命令:${finding.command}`);
166
+ if (finding.commands) {
167
+ for (const command of finding.commands) console.log(` 命令:${command}`);
168
+ }
169
+ }
170
+ }
171
+
172
+ Object.assign(runtime, {
173
+ scopeParts,
174
+ workspaceName,
175
+ readProjectsRegistryIfExists,
176
+ discoverDoctorScopes,
177
+ resolveRepoPath,
178
+ readGitRemote,
179
+ gitignoreLines,
180
+ isIgnoredByWorkspace,
181
+ projectDoctorContextFor,
182
+ projectBaselineStatus,
183
+ missingProjectBaselineAssets,
184
+ diagnoseProjectRegistry,
185
+ diagnoseWorkspace,
186
+ diagnoseLegacyPractices,
187
+ diagnoseHierarchy,
188
+ diagnoseServicesMetadata,
189
+ diagnoseServices,
190
+ runtimeFindingsForDoctor,
191
+ summarizeRuntimeFindings,
192
+ addUnsupportedAgentFinding,
193
+ diagnoseRuntime,
194
+ diagnoseCommands,
195
+ diagnoseComponents,
196
+ diagnoseSkillsManifestSchemas,
197
+ finalizeDoctorResult,
198
+ printDoctorReport,
199
+ });
200
+ return runtime;
201
+ }
@@ -0,0 +1,73 @@
1
+ export function createBuiltinReceipts(deps) {
2
+ const { atomicWriteJson, collectFiles, crypto, ensureDirectory, existsDirectory, existsFile, fs, isPlainObject, path, toPosixRelative } = deps;
3
+ const schemaVersion = 'buildr.builtin-receipts/v1';
4
+ const relativePath = '.buildr/builtin-receipts.json';
5
+ const sha256 = (value) => `sha256-${crypto.createHash('sha256').update(value).digest('hex')}`;
6
+
7
+ function assetInventory(assetPath, kind) {
8
+ if (kind === 'command') return [{ path: 'manifest-entry', integrity: sha256(JSON.stringify(assetPath)) }];
9
+ if (kind === 'rule') {
10
+ if (!existsFile(assetPath)) return null;
11
+ if (fs.lstatSync(assetPath).isSymbolicLink()) throw new Error(`Builtin asset must not be a symlink: ${assetPath}`);
12
+ return [{ path: path.basename(assetPath), integrity: sha256(fs.readFileSync(assetPath)) }];
13
+ }
14
+ if (!existsDirectory(assetPath)) return null;
15
+ const inventory = [];
16
+ for (const file of collectFiles(assetPath).sort()) {
17
+ if (fs.lstatSync(file).isSymbolicLink()) throw new Error(`Builtin asset must not contain symlinks: ${file}`);
18
+ const relative = toPosixRelative(assetPath, file);
19
+ if (!relative || relative.startsWith('../') || path.isAbsolute(relative)) throw new Error(`Builtin asset path escapes its root: ${file}`);
20
+ inventory.push({ path: relative, integrity: sha256(fs.readFileSync(file)) });
21
+ }
22
+ return inventory;
23
+ }
24
+
25
+ const inventoryIntegrity = (inventory) => inventory === null ? null : sha256(JSON.stringify(inventory));
26
+ function snapshot(assetPath, kind) {
27
+ const files = assetInventory(assetPath, kind);
28
+ return files === null ? null : { files, integrity: inventoryIntegrity(files) };
29
+ }
30
+ const key = (type, id) => `${type}:${id}`;
31
+
32
+ function read(targetRoot) {
33
+ const receiptPath = path.join(targetRoot, relativePath);
34
+ if (!existsFile(receiptPath)) return { schemaVersion, builtins: [] };
35
+ let value;
36
+ try { value = JSON.parse(fs.readFileSync(receiptPath, 'utf8')); } catch (error) { throw new Error(`Invalid Builtin receipt JSON: ${error.message}`); }
37
+ if (!isPlainObject(value) || value.schemaVersion !== schemaVersion || !Array.isArray(value.builtins)) throw new Error(`Invalid Builtin receipt schema: ${receiptPath}`);
38
+ const seen = new Set();
39
+ for (const item of value.builtins) {
40
+ if (!isPlainObject(item) || !['rule', 'skill', 'command'].includes(item.type) || typeof item.id !== 'string' || typeof item.target !== 'string' || !/^sha256-[a-f0-9]{64}$/.test(item.integrity || '') || !Array.isArray(item.files)) throw new Error(`Invalid Builtin receipt entry: ${JSON.stringify(item)}`);
41
+ const itemKey = key(item.type, item.id);
42
+ if (seen.has(itemKey)) throw new Error(`Duplicate Builtin receipt entry: ${itemKey}`);
43
+ seen.add(itemKey);
44
+ if (path.isAbsolute(item.target) || item.target.split('/').includes('..')) throw new Error(`Builtin receipt target escapes workspace: ${item.target}`);
45
+ const paths = new Set();
46
+ for (const file of item.files) {
47
+ if (!isPlainObject(file) || typeof file.path !== 'string' || !file.path || path.isAbsolute(file.path) || file.path.split('/').includes('..') || !/^sha256-[a-f0-9]{64}$/.test(file.integrity || '') || paths.has(file.path)) throw new Error(`Invalid Builtin receipt inventory for ${itemKey}`);
48
+ paths.add(file.path);
49
+ }
50
+ if (inventoryIntegrity(item.files) !== item.integrity) throw new Error(`Builtin receipt integrity mismatch: ${itemKey}`);
51
+ }
52
+ return value;
53
+ }
54
+
55
+ function write(targetRoot, receipts) {
56
+ receipts.builtins.sort((left, right) => key(left.type, left.id).localeCompare(key(right.type, right.id)));
57
+ ensureDirectory(path.dirname(path.join(targetRoot, relativePath)));
58
+ atomicWriteJson(path.join(targetRoot, relativePath), receipts);
59
+ return relativePath;
60
+ }
61
+
62
+ const fromSnapshot = (type, builtin, value) => ({ type, id: builtin.id, target: type === 'command' ? 'commands/manifest.yml' : builtin.target, integrity: value.integrity, files: value.files });
63
+
64
+ function resolveState({ builtin, liveSnapshot, newSnapshot, oldReceipt, isRestore, required }) {
65
+ if (liveSnapshot?.integrity === newSnapshot.integrity) return { status: 'installed', converge: false, adopt: true };
66
+ if (isRestore || required) return { status: liveSnapshot ? 'modified' : 'missing', converge: true, adopt: true };
67
+ if (oldReceipt && liveSnapshot?.integrity === oldReceipt.integrity) return { status: 'installed', converge: true, adopt: true };
68
+ if (!oldReceipt && liveSnapshot && (builtin.legacyIntegrities || []).includes(liveSnapshot.integrity)) return { status: 'installed', converge: true, adopt: true, legacy: true };
69
+ return { status: liveSnapshot ? 'modified' : 'missing', converge: false, adopt: false };
70
+ }
71
+
72
+ return { relativePath, key, snapshot, read, write, fromSnapshot, resolveState };
73
+ }
@@ -0,0 +1,148 @@
1
+ export function createPackageOutput(deps) {
2
+ const {
3
+ assertSafeAssetTarget,
4
+ atomicWriteJson,
5
+ collectFiles,
6
+ crypto,
7
+ ensureDirectory,
8
+ existsDirectory,
9
+ existsFile,
10
+ fs,
11
+ optionValue,
12
+ packageRoot,
13
+ parseManifestFileEntry,
14
+ path,
15
+ productRoot,
16
+ readPackageManifest,
17
+ toPosixRelative,
18
+ } = deps;
19
+
20
+ const PACKAGE_OUTPUT_RECEIPT = '.buildr-package-output.json';
21
+ const PACKAGE_OUTPUT_RECEIPT_SCHEMA = 'buildr.package-output/v1';
22
+
23
+ function packageOutputInventory(outputRoot) {
24
+ if (!existsDirectory(outputRoot)) return [];
25
+ return collectFiles(outputRoot)
26
+ .filter((file) => path.basename(file) !== PACKAGE_OUTPUT_RECEIPT)
27
+ .map((file) => ({
28
+ path: toPosixRelative(outputRoot, file),
29
+ integrity: `sha256-${crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')}`,
30
+ }))
31
+ .sort((left, right) => left.path.localeCompare(right.path));
32
+ }
33
+
34
+ function packageOutputIntegrity(inventory) {
35
+ return `sha256-${crypto.createHash('sha256').update(JSON.stringify(inventory)).digest('hex')}`;
36
+ }
37
+
38
+ function readPackageOutputReceipt(outDir) {
39
+ const file = path.join(outDir, PACKAGE_OUTPUT_RECEIPT);
40
+ if (!existsFile(file)) return null;
41
+ let receipt;
42
+ try { receipt = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (error) { throw new Error(`Package output receipt is invalid JSON: ${error.message}`); }
43
+ if (receipt?.schemaVersion !== PACKAGE_OUTPUT_RECEIPT_SCHEMA || !Array.isArray(receipt.files) || typeof receipt.integrity !== 'string') {
44
+ throw new Error('Package output receipt has an unsupported schema.');
45
+ }
46
+ return receipt;
47
+ }
48
+
49
+ function assertSafePackageOutput(outDir) {
50
+ const root = productRoot();
51
+ const candidate = path.resolve(outDir);
52
+ assertSafeAssetTarget(root, candidate, path.dirname(candidate), 'Package output');
53
+ if (fs.existsSync(candidate) && fs.lstatSync(candidate).isSymbolicLink()) throw new Error(`Package output is a symbolic link: ${candidate}`);
54
+ for (const collection of ['package', 'tools', 'openspec', 'docs', 'agents', 'skills', 'capabilities', 'services']) {
55
+ if (candidate === path.join(root, collection)) throw new Error(`Package output is a protected Product collection root: ${candidate}`);
56
+ }
57
+ return candidate;
58
+ }
59
+
60
+ function validateReplaceablePackageOutput(outDir) {
61
+ if (!fs.existsSync(outDir)) return;
62
+ if (!existsDirectory(outDir)) throw new Error(`Package output target is not a directory: ${outDir}`);
63
+ if (fs.readdirSync(outDir).length === 0) return;
64
+ const receipt = readPackageOutputReceipt(outDir);
65
+ if (!receipt) throw new Error(`Refusing to replace non-empty package output without ${PACKAGE_OUTPUT_RECEIPT}: ${outDir}`);
66
+ const liveFiles = packageOutputInventory(outDir);
67
+ const liveIntegrity = packageOutputIntegrity(liveFiles);
68
+ if (liveIntegrity !== receipt.integrity || JSON.stringify(liveFiles) !== JSON.stringify(receipt.files)) {
69
+ throw new Error(`Refusing to replace modified package output: ${outDir}`);
70
+ }
71
+ }
72
+
73
+ function buildPackageOutput(outDir, root, manifest) {
74
+ ensureDirectory(outDir);
75
+
76
+ const manifestSource = path.join(packageRoot(), 'manifest.yml');
77
+ const manifestTarget = path.join(outDir, 'package/manifest.yml');
78
+ ensureDirectory(path.dirname(manifestTarget));
79
+ fs.copyFileSync(manifestSource, manifestTarget);
80
+
81
+ for (const includePath of manifest.include) {
82
+ const source = path.resolve(root, includePath);
83
+ if (!fs.existsSync(source)) {
84
+ throw new Error(`Manifest include does not exist: ${includePath}`);
85
+ }
86
+ const target = path.join(outDir, includePath);
87
+ ensureDirectory(path.dirname(target));
88
+ fs.cpSync(source, target, { recursive: true });
89
+ }
90
+
91
+ for (const section of ['workspaceFiles', 'projectFiles']) {
92
+ for (const rawEntry of manifest[section]) {
93
+ const entry = parseManifestFileEntry(rawEntry, section);
94
+ const source = path.resolve(root, entry.source);
95
+ if (!fs.existsSync(source)) {
96
+ throw new Error(`Manifest source does not exist: ${entry.source}`);
97
+ }
98
+ const target = path.join(outDir, entry.source);
99
+ ensureDirectory(path.dirname(target));
100
+ fs.copyFileSync(source, target);
101
+ }
102
+ }
103
+
104
+ const files = packageOutputInventory(outDir);
105
+ atomicWriteJson(path.join(outDir, PACKAGE_OUTPUT_RECEIPT), {
106
+ schemaVersion: PACKAGE_OUTPUT_RECEIPT_SCHEMA,
107
+ generatedAt: new Date().toISOString(),
108
+ productVersion: (() => { try { return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version; } catch { return null; } })(),
109
+ files,
110
+ integrity: packageOutputIntegrity(files),
111
+ });
112
+ }
113
+
114
+ function packageBuild(args) {
115
+ const root = productRoot();
116
+ const manifest = readPackageManifest();
117
+ const outDir = assertSafePackageOutput(path.resolve(optionValue(args, '--out', path.join(root, 'dist', 'buildr-package'))));
118
+ validateReplaceablePackageOutput(outDir);
119
+ const staging = path.join(path.dirname(outDir), `.${path.basename(outDir)}.buildr-stage-${crypto.randomUUID()}`);
120
+ const backup = path.join(path.dirname(outDir), `.${path.basename(outDir)}.buildr-backup-${crypto.randomUUID()}`);
121
+ try {
122
+ buildPackageOutput(staging, root, manifest);
123
+ if (fs.existsSync(outDir)) fs.renameSync(outDir, backup);
124
+ fs.renameSync(staging, outDir);
125
+ if (fs.existsSync(backup)) fs.rmSync(backup, { recursive: true, force: true });
126
+ } catch (error) {
127
+ if (fs.existsSync(backup)) {
128
+ if (fs.existsSync(outDir)) fs.rmSync(outDir, { recursive: true, force: true });
129
+ fs.renameSync(backup, outDir);
130
+ }
131
+ throw error;
132
+ } finally {
133
+ if (fs.existsSync(staging)) fs.rmSync(staging, { recursive: true, force: true });
134
+ }
135
+
136
+ console.log(`Built Buildr package assets at ${outDir}`);
137
+ }
138
+
139
+ return {
140
+ packageOutputInventory,
141
+ packageOutputIntegrity,
142
+ readPackageOutputReceipt,
143
+ assertSafePackageOutput,
144
+ validateReplaceablePackageOutput,
145
+ buildPackageOutput,
146
+ packageBuild,
147
+ };
148
+ }