@buildr-ai/buildr 0.1.0-rc.2 → 0.1.0-rc.21

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 (181) hide show
  1. package/README.md +47 -5
  2. package/application-payload.json +595 -0
  3. package/bin/buildr.mjs +14 -0
  4. package/installation-origin.json +13 -0
  5. package/package.json +16 -45
  6. package/payload/licenses/dependencies/yaml-LICENSE +13 -0
  7. package/payload/product/LICENSE +21 -0
  8. package/payload/product/README.md +59 -0
  9. package/payload/product/package/README.md +42 -0
  10. package/{package → payload/product/package}/bootstrap/contract.yml +26 -11
  11. package/{package → payload/product/package}/bootstrap/guide.md +11 -11
  12. package/payload/product/package/launchers/assets/Buildr.icns +0 -0
  13. package/payload/product/package/launchers/assets/Buildr.ico +0 -0
  14. package/payload/product/package/manifest.yml +547 -0
  15. package/payload/product/package/targets/runtime/skills/buildr/SKILL.md +174 -0
  16. package/{package → payload/product/package}/targets/workspace/commands/buildr/openspec/manifest.yml +2 -2
  17. package/payload/product/package/targets/workspace/components/buildr/openspec/component.yml +79 -0
  18. package/payload/product/package/targets/workspace/components/buildr/openspec/contributions/openspec-apply-sidebar.md +21 -0
  19. package/payload/product/package/targets/workspace/components/buildr/openspec/contributions/openspec-archive-converge.md +5 -0
  20. package/payload/product/package/targets/workspace/components/buildr/openspec/contributions/openspec-explore-terminology.md +5 -0
  21. package/payload/product/package/targets/workspace/components/buildr/openspec/contributions/openspec-propose-sidebar.md +21 -0
  22. package/payload/product/package/targets/workspace/components/buildr/openspec/contributions/openspec-sync-converge.md +5 -0
  23. package/payload/product/package/targets/workspace/components/buildr/openspec/contributions/openspec-update-sidebar.md +13 -0
  24. package/payload/product/package/targets/workspace/gitattributes +1 -0
  25. package/payload/product/package/targets/workspace/gitignore +31 -0
  26. package/{package → payload/product/package}/targets/workspace/projects/AGENTS.project.md +1 -1
  27. package/payload/product/package/targets/workspace/rules/buildr/core.md +62 -0
  28. package/payload/product/package/targets/workspace/skills/buildr/capability-adaptation/SKILL.md +56 -0
  29. package/payload/product/package/targets/workspace/skills/buildr/capability-adaptation/agents/openai.yaml +4 -0
  30. package/payload/product/package/targets/workspace/skills/buildr/current-knowledge-maintenance/SKILL.md +103 -0
  31. package/payload/product/package/targets/workspace/skills/buildr/declaration-intake/SKILL.md +65 -0
  32. package/payload/product/package/targets/workspace/skills/buildr/git-operations/SKILL.md +100 -0
  33. package/payload/product/package/targets/workspace/skills/buildr/openspec-contract-guard/SKILL.md +65 -0
  34. package/payload/product/package/targets/workspace/skills/buildr/project-daily-progress/SKILL.md +52 -0
  35. package/payload/product/package/targets/workspace/skills/buildr/project-testing/SKILL.md +84 -0
  36. package/payload/product/package/targets/workspace/skills/buildr/project-testing/references/testing-model-v1.md +116 -0
  37. package/payload/product/package/targets/workspace/skills/buildr/task-development/SKILL.md +108 -0
  38. package/payload/product/package/targets/workspace/skills/buildr/task-environment/SKILL.md +42 -0
  39. package/payload/product/package/targets/workspace/skills/buildr/task-environment/agents/openai.yaml +4 -0
  40. package/payload/product/package/targets/workspace/skills/buildr/task-environment/references/project-environment-preparation-v1.md +14 -0
  41. package/payload/product/package/targets/workspace/skills/buildr/task-environment/templates/project-preparation.yml +20 -0
  42. package/payload/product/package/targets/workspace/skills/buildr/task-environment/templates/task-environment-plan-request.json +17 -0
  43. package/payload/product/package/targets/workspace/skills/buildr/task-finish/SKILL.md +80 -0
  44. package/payload/product/package/targets/workspace/skills/buildr/task-manager/SKILL.md +47 -0
  45. package/payload/product/package/targets/workspace/skills/buildr/task-manager/agents/openai.yaml +4 -0
  46. package/payload/product/package/targets/workspace/skills/buildr/task-retrospective/SKILL.md +101 -0
  47. package/payload/product/package/targets/workspace/skills/buildr/task-retrospective/agents/openai.yaml +4 -0
  48. package/payload/product/package/targets/workspace/skills/buildr/task-review/SKILL.md +60 -0
  49. package/payload/product/package/targets/workspace/skills/buildr/task-review/agents/openai.yaml +4 -0
  50. package/payload/product/package/targets/workspace/skills/buildr/task-triage/SKILL.md +119 -0
  51. package/payload/product/package/targets/workspace/skills/buildr/task-verification/SKILL.md +142 -0
  52. package/payload/product/package/targets/workspace/skills/buildr/task-verification/references/project-verification-v2.md +51 -0
  53. package/payload/product/package/targets/workspace/skills/buildr/task-verification/templates/project-verification.yml +16 -0
  54. package/payload/product/package/targets/workspace/skills/buildr/task-worktree/SKILL.md +28 -0
  55. package/payload/product/package/targets/workspace/skills/buildr/terminology-governance/SKILL.md +60 -0
  56. package/payload/product/package/targets/workspace/skills/buildr/ui-preview/SKILL.md +74 -0
  57. package/payload/product/package/targets/workspace/skills/contracts/buildr/current-knowledge-maintenance/v1.md +36 -0
  58. package/payload/product/package/targets/workspace/skills/contracts/buildr/current-knowledge-maintenance/v2.md +45 -0
  59. package/payload/product/package/targets/workspace/skills/contracts/buildr/git-operations/v1.md +39 -0
  60. package/payload/product/package/targets/workspace/skills/contracts/buildr/git-worktree-provider/v1.md +35 -0
  61. package/payload/product/package/targets/workspace/skills/contracts/buildr/task-development/v2.md +61 -0
  62. package/payload/product/package/targets/workspace/skills/contracts/buildr/task-environment/v1.md +37 -0
  63. package/payload/product/package/targets/workspace/skills/contracts/buildr/task-finish/v1.md +59 -0
  64. package/payload/product/package/targets/workspace/skills/contracts/buildr/task-record/v2.md +35 -0
  65. package/payload/product/package/targets/workspace/skills/contracts/buildr/task-retrospective/v2.md +41 -0
  66. package/payload/product/package/targets/workspace/skills/contracts/buildr/task-review/v1.md +39 -0
  67. package/payload/product/package/targets/workspace/skills/contracts/buildr/task-verification/v3.md +63 -0
  68. package/payload/product/package/targets/workspace/skills/contracts/buildr/terminology-governance/v1.md +36 -0
  69. package/{package → payload/product/package}/targets/workspace/skills/openspec/openspec-apply-change/SKILL.md +4 -3
  70. package/{package → payload/product/package}/targets/workspace/skills/openspec/openspec-archive-change/SKILL.md +4 -3
  71. package/{package → payload/product/package}/targets/workspace/skills/openspec/openspec-explore/SKILL.md +4 -1
  72. package/{package → payload/product/package}/targets/workspace/skills/openspec/openspec-propose/SKILL.md +4 -1
  73. package/{package → payload/product/package}/targets/workspace/skills/openspec/openspec-sync-specs/SKILL.md +4 -3
  74. package/payload/product/package/targets/workspace/skills/openspec/openspec-update-change/SKILL.md +86 -0
  75. package/payload/product/package.json +33 -0
  76. package/payload/product/src/infrastructure/sqlite/migrations/0000_create_migration_ledger.sql +16 -0
  77. package/payload/product/src/infrastructure/sqlite/migrations/0001_create_task_store.sql +47 -0
  78. package/payload/product/src/infrastructure/sqlite/migrations/0002_create_parent_task_relations.sql +7 -0
  79. package/payload/product/src/infrastructure/sqlite/migrations/0003_inline_parent_task_column.sql +19 -0
  80. package/payload/product/src/infrastructure/sqlite/migrations/0004_create_task_current_records.sql +16 -0
  81. package/payload/product/src/infrastructure/sqlite/migrations/0005_create_task_retrospective_current.sql +4 -0
  82. package/payload/product/src/infrastructure/sqlite/migrations/0006_create_task_lifecycle_current.sql +4 -0
  83. package/payload/product/src/infrastructure/sqlite/migrations/0007_create_task_finish_current.sql +46 -0
  84. package/payload/product/src/infrastructure/sqlite/migrations/0008_create_task_environment_current.sql +8 -0
  85. package/payload/product/src/infrastructure/sqlite/migrations/0009_retire_task_lifecycle_current.sql +107 -0
  86. package/payload/product/src/infrastructure/sqlite/migrations/0010_add_task_retrospective_disposition.sql +19 -0
  87. package/payload/product/src/infrastructure/sqlite/migrations/0011_create_task_execution_records.sql +115 -0
  88. package/payload/product/src/infrastructure/sqlite/migrations/0012_compact_task_finish_current.sql +261 -0
  89. package/payload/product/src/infrastructure/sqlite/migrations/0013_add_todo_task_retrospective_sources.sql +56 -0
  90. package/payload/product/src/infrastructure/sqlite/migrations/0014_add_task_execution_invocation_identity.sql +14 -0
  91. package/payload/product/src/infrastructure/sqlite/migrations/0015_add_task_execution_unknown_outcome.sql +143 -0
  92. package/payload/product/src/infrastructure/sqlite/migrations/0016_allow_terminal_task_finish_target_lease.sql +83 -0
  93. package/payload/product/src/infrastructure/sqlite/migrations/0017_expand_task_finish_repository_set.sql +111 -0
  94. package/payload/product/src/interfaces/local-app/web-dist/assets/antd-NAtxFWmu.js +394 -0
  95. package/payload/product/src/interfaces/local-app/web-dist/assets/index-BqoyfMSY.css +1 -0
  96. package/payload/product/src/interfaces/local-app/web-dist/assets/index-DTqvE0TF.js +39 -0
  97. package/payload/product/src/interfaces/local-app/web-dist/assets/react-9kRp7SbA.js +28 -0
  98. package/payload/product/src/interfaces/local-app/web-dist/index.html +19 -0
  99. package/payload/runtime/read-worker.cjs +45071 -0
  100. package/runtime/buildr.cjs +51533 -0
  101. package/scripts/postinstall.mjs +15 -0
  102. package/docs/agent-runtime-adapters.md +0 -94
  103. package/docs/cli-architecture.md +0 -65
  104. package/docs/cli-reference.md +0 -67
  105. package/docs/known-limitations.md +0 -15
  106. package/examples/minimal-workspace/README.md +0 -24
  107. package/package/README.md +0 -28
  108. package/package/manifest.yml +0 -150
  109. package/package/targets/runtime/skills/buildr/SKILL.md +0 -154
  110. package/package/targets/workspace/.buildr/workspace.yml +0 -5
  111. package/package/targets/workspace/commands/manifest.yml +0 -2
  112. package/package/targets/workspace/components/buildr/openspec/component.yml +0 -16
  113. package/package/targets/workspace/components/buildr/openspec/contributions/openspec-apply-sidebar.md +0 -3
  114. package/package/targets/workspace/components/buildr/openspec/contributions/openspec-archive-sidebar.md +0 -3
  115. package/package/targets/workspace/components/buildr/openspec/contributions/openspec-explore-sidebar.md +0 -3
  116. package/package/targets/workspace/components/buildr/openspec/contributions/openspec-propose-sidebar.md +0 -3
  117. package/package/targets/workspace/components/buildr/openspec/contributions/openspec-sync-sidebar.md +0 -3
  118. package/package/targets/workspace/components/buildr/openspec/contributions/task-finish-post-sync.md +0 -1
  119. package/package/targets/workspace/components/buildr/openspec/contributions/task-finish-pre-sync.md +0 -1
  120. package/package/targets/workspace/components/buildr/openspec/contributions/task-triage-change-ready.md +0 -10
  121. package/package/targets/workspace/components/manifest.yml +0 -2
  122. package/package/targets/workspace/gitignore +0 -16
  123. package/package/targets/workspace/projects/manifest.yml +0 -2
  124. package/package/targets/workspace/projects/services/manifest.yml +0 -3
  125. package/package/targets/workspace/projects/skills/manifest.yml +0 -2
  126. package/package/targets/workspace/rules/buildr/core.md +0 -65
  127. package/package/targets/workspace/rules/manifest.yml +0 -9
  128. package/package/targets/workspace/skills/buildr/git-ops/SKILL.md +0 -73
  129. package/package/targets/workspace/skills/buildr/openspec-contract-guard/SKILL.md +0 -67
  130. package/package/targets/workspace/skills/buildr/task-finish/SKILL.md +0 -104
  131. package/package/targets/workspace/skills/buildr/task-triage/SKILL.md +0 -103
  132. package/package/targets/workspace/skills/buildr/task-worktree/SKILL.md +0 -104
  133. package/package/targets/workspace/skills/manifest.yml +0 -38
  134. package/tools/buildr +0 -11
  135. package/tools/cli/application/cli-update.mjs +0 -219
  136. package/tools/cli/application/compose-runtime.mjs +0 -38
  137. package/tools/cli/application/doctor/runtime-diagnostics.mjs +0 -227
  138. package/tools/cli/application/doctor/scope-diagnostics.mjs +0 -440
  139. package/tools/cli/application/doctor/service-diagnostics.mjs +0 -184
  140. package/tools/cli/application/doctor.mjs +0 -201
  141. package/tools/cli/application/package-maintenance/builtin-receipts.mjs +0 -73
  142. package/tools/cli/application/package-maintenance/output.mjs +0 -148
  143. package/tools/cli/application/package-maintenance/smoke-checks.mjs +0 -463
  144. package/tools/cli/application/package-maintenance/static-validation.mjs +0 -680
  145. package/tools/cli/application/package-maintenance.mjs +0 -540
  146. package/tools/cli/application/runtime.mjs +0 -118
  147. package/tools/cli/application/workspace-operations.mjs +0 -311
  148. package/tools/cli/bootstrap.mjs +0 -6
  149. package/tools/cli/command/help.mjs +0 -296
  150. package/tools/cli/command/registry.mjs +0 -97
  151. package/tools/cli/domains/commands.mjs +0 -661
  152. package/tools/cli/domains/components.mjs +0 -922
  153. package/tools/cli/domains/openspec.mjs +0 -603
  154. package/tools/cli/domains/package-assets.mjs +0 -652
  155. package/tools/cli/domains/rules.mjs +0 -380
  156. package/tools/cli/domains/runtime.mjs +0 -87
  157. package/tools/cli/domains/skills.mjs +0 -647
  158. package/tools/cli/domains/workspace.mjs +0 -571
  159. package/tools/cli/shared/infrastructure.mjs +0 -411
  160. package/tools/cli/shared/json-contracts.mjs +0 -22
  161. package/tools/cli/shared/platform.mjs +0 -52
  162. package/tools/runtime/adapter-contract.mjs +0 -655
  163. package/tools/runtime/check-claude-code.mjs +0 -23
  164. package/tools/runtime/check-codex.mjs +0 -23
  165. package/tools/runtime/check-runtime.mjs +0 -98
  166. package/tools/runtime/projection.mjs +0 -375
  167. package/tools/runtime/render-claude-code-rules.mjs +0 -459
  168. package/tools/runtime/render-claude-code.mjs +0 -59
  169. package/tools/runtime/skills/arguments.mjs +0 -51
  170. package/tools/runtime/skills/contributions.mjs +0 -171
  171. package/tools/runtime/skills/manifests.mjs +0 -167
  172. package/tools/runtime/skills/primitives.mjs +0 -86
  173. package/tools/runtime/skills/render-plan.mjs +0 -243
  174. package/tools/runtime/skills/sources.mjs +0 -276
  175. package/tools/shared/fetch-remote-text.mjs +0 -78
  176. package/tools/verification/integrity/managed-data-integrity.mjs +0 -107
  177. package/tools/verification/integrity/managed-mutations.mjs +0 -72
  178. package/tools/verification/openspec/contract.mjs +0 -212
  179. package/tools/verification/runtime/adapter-contract.mjs +0 -218
  180. package/tools/verification/runtime/adapter-parity.mjs +0 -173
  181. /package/{package → payload/product/package}/targets/workspace/AGENTS.md +0 -0
@@ -1,655 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- export const REQUIRED_RENDER_CAPABILITIES = Object.freeze([
5
- 'rules-entry',
6
- 'product-buildr-skill',
7
- 'workspace-project-skills',
8
- 'skill-install-plans',
9
- 'runtime-check',
10
- ]);
11
-
12
- export const ADAPTER_VERIFICATION_LEVELS = Object.freeze(['documented', 'verified']);
13
-
14
- export const ADAPTER_TRAIT_CATALOG = Object.freeze({
15
- rules: Object.freeze(['native-recursive', 'native-root', 'reference-bridge', 'vendor-rule-files']),
16
- skills: Object.freeze(['agents-compatible', 'vendor-root']),
17
- surfaces: Object.freeze(['ide', 'cli', 'desktop', 'cloud']),
18
- activation: Object.freeze(['immediate', 'path-read', 'session-start', 'explicit-reload']),
19
- checker: Object.freeze(['projection']),
20
- environmentProbe: Object.freeze(['none', 'command', 'manual']),
21
- });
22
-
23
- export const BUILTIN_ADAPTER_IMPLEMENTATIONS = Object.freeze({
24
- rules: Object.freeze(['native-recursive', 'reference-bridge', 'vendor-rule-files']),
25
- skills: Object.freeze(['filesystem-skills']),
26
- checker: Object.freeze(['projection']),
27
- });
28
-
29
- export const UNSUPPORTED_AGENT_GUIDANCE = Object.freeze({
30
- message: 'Buildr 暂不支持当前 Agent runtime 的自动渲染。',
31
- nextStep: '请联系 Buildr 作者反馈该 Agent。',
32
- mustNotUseFallbackAdapter: true,
33
- });
34
-
35
- const AGENT_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
36
-
37
- function freeze(value) {
38
- if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
39
- for (const child of Object.values(value)) freeze(child);
40
- return Object.freeze(value);
41
- }
42
-
43
- function planFromTraits(context, traits) {
44
- const rules = traits.rules.kind === 'native-recursive'
45
- ? {
46
- writes: [],
47
- removals: [],
48
- nativeAssets: context.rules.nativeAssets,
49
- actions: [],
50
- }
51
- : context.rules;
52
- return createRuntimePlan({
53
- adapterId: context.adapterId,
54
- targetRoot: context.targetRoot,
55
- scope: context.scope,
56
- writes: [...rules.writes, ...context.skills.writes],
57
- nativeAssets: rules.nativeAssets,
58
- removals: [...rules.removals, ...context.skills.removals],
59
- capabilityEvidence: REQUIRED_RENDER_CAPABILITIES.map((capability) => ({
60
- capability,
61
- supported: true,
62
- adapterId: context.adapterId,
63
- })),
64
- findings: [...context.findings],
65
- repairs: [...context.repairs],
66
- warnings: [...context.warnings],
67
- ruleActions: rules.actions,
68
- });
69
- }
70
-
71
- function isSafeRuntimeRoot(value) {
72
- if (typeof value !== 'string' || value.length === 0 || path.isAbsolute(value)) return false;
73
- const normalized = path.posix.normalize(value.replaceAll('\\', '/'));
74
- return normalized !== '.' && normalized !== '..' && !normalized.startsWith('../') && normalized === value.replaceAll('\\', '/').replace(/\/$/, '');
75
- }
76
-
77
- function normalizeImplementationCatalog(value = {}) {
78
- return {
79
- rules: new Set(value.rules || BUILTIN_ADAPTER_IMPLEMENTATIONS.rules),
80
- skills: new Set(value.skills || BUILTIN_ADAPTER_IMPLEMENTATIONS.skills),
81
- checker: new Set(value.checker || BUILTIN_ADAPTER_IMPLEMENTATIONS.checker),
82
- };
83
- }
84
-
85
- function validateEnvironmentProbe(probe, label, errors) {
86
- if (!probe || !ADAPTER_TRAIT_CATALOG.environmentProbe.includes(probe.kind)) {
87
- errors.push(`${label} kind is invalid: ${probe?.kind || '<missing>'}`);
88
- return;
89
- }
90
- if (probe.kind === 'command') {
91
- if (typeof probe.executable !== 'string' || !AGENT_ID_PATTERN.test(probe.executable)) errors.push(`${label} command executable must be a static command name`);
92
- if (!Array.isArray(probe.args) || probe.args.some((item) => typeof item !== 'string')) errors.push(`${label} command args must be an array of strings`);
93
- if (!Number.isInteger(probe.timeoutMs) || probe.timeoutMs < 100 || probe.timeoutMs > 10000) errors.push(`${label} command timeoutMs must be between 100 and 10000`);
94
- }
95
- if (probe.kind === 'manual' && !probe.guidance) errors.push(`${label} manual guidance is required`);
96
- }
97
-
98
- function validateAdapterTraits(descriptor, options = {}) {
99
- const errors = [];
100
- const traits = descriptor?.traits;
101
- const implementations = normalizeImplementationCatalog(options.implementations);
102
- if (!traits || typeof traits !== 'object') return [`adapter ${descriptor?.id || '<missing>'} traits are required`];
103
-
104
- const rules = traits.rules;
105
- if (!rules || !ADAPTER_TRAIT_CATALOG.rules.includes(rules.kind)) errors.push(`adapter ${descriptor.id} rules trait is invalid: ${rules?.kind || '<missing>'}`);
106
- if (!rules?.implementation || !implementations.rules.has(rules.implementation)) errors.push(`adapter ${descriptor.id} has no registered rules implementation: ${rules?.implementation || '<missing>'}`);
107
- if (rules?.kind === 'native-recursive' && rules.implementation !== 'native-recursive') errors.push(`adapter ${descriptor.id} native-recursive rules must use native-recursive implementation`);
108
- if (rules?.kind === 'native-root' && rules.scopeCoverage !== 'recursive') errors.push(`adapter ${descriptor.id} native-root rules do not cover recursive scope`);
109
- if (['reference-bridge', 'vendor-rule-files'].includes(rules?.kind) && !rules.targetPattern) errors.push(`adapter ${descriptor.id} rendered rules targetPattern is required`);
110
- if (rules?.kind === 'reference-bridge' && !['per-source', 'root-index'].includes(rules.placement || 'per-source')) errors.push(`adapter ${descriptor.id} reference bridge placement is invalid: ${rules?.placement}`);
111
- if (rules?.kind === 'vendor-rule-files' && !['cursor-mdc', 'qoder-markdown', 'trae-markdown'].includes(rules.format)) errors.push(`adapter ${descriptor.id} vendor rules format is invalid: ${rules?.format || '<missing>'}`);
112
- if (rules?.maxChars !== undefined && (!Number.isInteger(rules.maxChars) || rules.maxChars < 256)) errors.push(`adapter ${descriptor.id} rules maxChars must be an integer of at least 256`);
113
-
114
- const skills = traits.skills;
115
- if (!skills || !ADAPTER_TRAIT_CATALOG.skills.includes(skills.kind)) errors.push(`adapter ${descriptor.id} skills trait is invalid: ${skills?.kind || '<missing>'}`);
116
- if (!skills?.implementation || !implementations.skills.has(skills.implementation)) errors.push(`adapter ${descriptor.id} has no registered skills implementation: ${skills?.implementation || '<missing>'}`);
117
- if (!isSafeRuntimeRoot(skills?.root)) errors.push(`adapter ${descriptor.id} skills root is unsafe: ${skills?.root || '<missing>'}`);
118
- if (skills?.kind === 'agents-compatible' && skills.root !== '.agents') errors.push(`adapter ${descriptor.id} agents-compatible skills root must be .agents`);
119
-
120
- if (!Array.isArray(traits.surfaces) || traits.surfaces.length === 0) errors.push(`adapter ${descriptor.id} surfaces are required`);
121
- for (const surface of traits.surfaces || []) {
122
- if (!surface || !ADAPTER_TRAIT_CATALOG.surfaces.includes(surface.kind)) errors.push(`adapter ${descriptor.id} surface is invalid: ${surface?.kind || '<missing>'}`);
123
- }
124
-
125
- const activation = traits.activation;
126
- for (const asset of ['rules', 'skills']) {
127
- if (!ADAPTER_TRAIT_CATALOG.activation.includes(activation?.[asset])) errors.push(`adapter ${descriptor.id} ${asset} activation is invalid: ${activation?.[asset] || '<missing>'}`);
128
- }
129
- if ([activation?.rules, activation?.skills].includes('explicit-reload') && !activation.reloadGuidance) errors.push(`adapter ${descriptor.id} explicit-reload guidance is required`);
130
-
131
- const checker = traits.checker;
132
- if (!checker || !ADAPTER_TRAIT_CATALOG.checker.includes(checker.kind)) errors.push(`adapter ${descriptor.id} checker trait is invalid: ${checker?.kind || '<missing>'}`);
133
- if (!checker?.implementation || !implementations.checker.has(checker.implementation)) errors.push(`adapter ${descriptor.id} has no registered checker implementation: ${checker?.implementation || '<missing>'}`);
134
- validateEnvironmentProbe(checker?.installationProbe, `adapter ${descriptor.id} installation probe`, errors);
135
- validateEnvironmentProbe(checker?.versionProbe, `adapter ${descriptor.id} version probe`, errors);
136
- if (checker?.prerequisites !== undefined && !Array.isArray(checker.prerequisites)) errors.push(`adapter ${descriptor.id} checker prerequisites must be an array`);
137
- for (const prerequisite of checker?.prerequisites || []) {
138
- if (!prerequisite?.code || !prerequisite?.message || !prerequisite?.guidance) errors.push(`adapter ${descriptor.id} checker prerequisite must declare code, message, and guidance`);
139
- }
140
- return errors;
141
- }
142
-
143
- function ruleCapability(traits) {
144
- const rules = traits.rules;
145
- const native = rules.kind === 'native-recursive';
146
- return {
147
- supported: true,
148
- mode: native ? 'native' : 'rendered',
149
- scopeSyntax: 'workspace-relative-path',
150
- sourceDiscovery: { pattern: '**/AGENTS.md', mode: 'recursive-scope', includesAncestors: true },
151
- projection: native ? { mode: 'native' } : { mode: 'rendered', targetPattern: rules.targetPattern },
152
- writesFiles: !native,
153
- ...(native ? { sourceAssets: ['**/AGENTS.md'] } : { targets: [rules.targetPattern] }),
154
- };
155
- }
156
-
157
- function renderCapabilities(traits) {
158
- const root = traits.skills.root;
159
- return {
160
- 'rules-entry': ruleCapability(traits),
161
- 'product-buildr-skill': { supported: true, mode: 'install', writesFiles: true, targets: [`${root}/skills/buildr/SKILL.md`] },
162
- 'workspace-project-skills': { supported: true, mode: 'rendered', writesFiles: true, targets: [`${root}/skills/<skill>/SKILL.md`] },
163
- 'skill-install-plans': { supported: true, mode: 'plan', writesFiles: true, targets: [`${root}/buildr/skill-install-plans/<skill>.md`] },
164
- 'runtime-check': {
165
- supported: true,
166
- mode: 'diagnostic',
167
- writesFiles: false,
168
- projection: traits.checker.kind,
169
- installationProbe: traits.checker.installationProbe.kind,
170
- versionProbe: traits.checker.versionProbe.kind,
171
- },
172
- };
173
- }
174
-
175
- function runtimeTargets(traits) {
176
- const rules = traits.rules.kind === 'native-recursive'
177
- ? ['AGENTS.md']
178
- : [traits.rules.targetPattern.replace('<source-dir>/', '').replace('<workspace-root>/', '')];
179
- return [...rules, `${traits.skills.root}/skills/`, `${traits.skills.root}/buildr/skill-install-plans/`];
180
- }
181
-
182
- export function createRuntimeAdapterDescriptor(value, options = {}) {
183
- const traitErrors = validateAdapterTraits(value, options);
184
- if (traitErrors.length > 0) throw new Error(`Invalid runtime adapter descriptor ${value.id || '<missing>'}:\n- ${traitErrors.join('\n- ')}`);
185
- const traits = freeze(structuredClone(value.traits));
186
- const descriptor = {
187
- id: value.id,
188
- displayName: value.displayName,
189
- traits,
190
- implementation: {
191
- rules: traits.rules.implementation,
192
- skills: traits.skills.implementation,
193
- checker: traits.checker.implementation,
194
- },
195
- runtimeTargets: runtimeTargets(traits),
196
- renderCapabilities: renderCapabilities(traits),
197
- recommendedCommands: value.recommendedCommands,
198
- evidence: value.evidence || {},
199
- planRuntime(context) { return planFromTraits(context, traits); },
200
- };
201
- const errors = validateAdapterDescriptor(descriptor, options);
202
- if (errors.length > 0) throw new Error(`Invalid runtime adapter descriptor ${value.id || '<missing>'}:\n- ${errors.join('\n- ')}`);
203
- return freeze(descriptor);
204
- }
205
-
206
- function recommendedCommands(id) {
207
- return {
208
- doctor: `buildr doctor --agent ${id} --target <dir> --json`,
209
- syncWorkspaceEntry: `buildr sync ${id} --target <dir>`,
210
- renderScope: `buildr render ${id} --scope <workspace-relative-path> --target <dir>`,
211
- renderSkillsScope: `buildr skills render ${id} --scope <scope> --target <dir>`,
212
- renderRulesScope: `buildr rules render ${id} --scope <scope> --target <dir>`,
213
- runtimeCheckScope: `buildr runtime check ${id} --scope <workspace-relative-path> --target <dir>`,
214
- installProductSkill: `buildr skill install ${id} --target <dir>`,
215
- };
216
- }
217
-
218
- function renderedRulesDiagnostics(label, codeId) {
219
- return {
220
- missingStatus: 'missing',
221
- missingPath: 'AGENTS.md',
222
- missingCode: `runtime.${codeId}_rules_missing`,
223
- label,
224
- codes: {
225
- ok: `runtime.${codeId}_rules_ok`,
226
- missing: `runtime.${codeId}_rules_missing`,
227
- stale: `runtime.${codeId}_rules_stale`,
228
- conflict: `runtime.${codeId}_rules_conflict`,
229
- orphan: `runtime.${codeId}_rules_orphan`,
230
- },
231
- };
232
- }
233
-
234
- const DESCRIPTORS = [
235
- createRuntimeAdapterDescriptor({
236
- id: 'claude-code',
237
- displayName: 'Claude Code',
238
- traits: {
239
- rules: {
240
- kind: 'reference-bridge',
241
- implementation: 'reference-bridge',
242
- placement: 'per-source',
243
- targetPattern: '<source-dir>/CLAUDE.md',
244
- diagnostics: {
245
- missingStatus: 'conflict',
246
- missingPath: 'CLAUDE.md',
247
- missingCode: 'runtime.rules_bridge_missing',
248
- label: 'Claude Code rules bridge',
249
- codes: { ok: 'runtime.reference_bridge_ok', missing: 'runtime.rules_bridge_missing', stale: 'runtime.rules_bridge_stale', conflict: 'runtime.rules_bridge_conflict', orphan: 'runtime.rules_bridge_orphan' },
250
- },
251
- },
252
- skills: { kind: 'vendor-root', implementation: 'filesystem-skills', root: '.claude' },
253
- surfaces: [{ kind: 'cli' }],
254
- activation: { rules: 'session-start', skills: 'session-start' },
255
- checker: { kind: 'projection', implementation: 'projection', resultKey: 'claudeCode', skillsManifestAbsentCode: 'runtime.skills_manifest_absent', installationProbe: { kind: 'none' }, versionProbe: { kind: 'none' } },
256
- },
257
- recommendedCommands: {
258
- doctor: 'buildr doctor --agent claude-code --target <dir> --json',
259
- syncWorkspaceEntry: 'buildr sync claude-code --target <dir>',
260
- renderScope: 'buildr render claude-code --scope <workspace-relative-path> --target <dir>',
261
- renderSkillsScope: 'buildr skills render claude-code --scope <scope> --target <dir>',
262
- renderRulesScope: 'buildr rules render claude-code --scope <scope> --target <dir>',
263
- runtimeCheckScope: 'buildr runtime check claude-code --scope <workspace-relative-path> --target <dir>',
264
- installProductSkill: 'buildr skill install claude-code --target <dir>',
265
- },
266
- }),
267
- createRuntimeAdapterDescriptor({
268
- id: 'codex',
269
- displayName: 'Codex',
270
- traits: {
271
- rules: {
272
- kind: 'native-recursive',
273
- implementation: 'native-recursive',
274
- diagnostics: { missingStatus: 'missing', missingPath: 'AGENTS.md', missingCode: 'runtime.codex_rules_missing', label: 'Codex native AGENTS.md rule asset', okCode: 'runtime.codex_rules_ok' },
275
- },
276
- skills: { kind: 'agents-compatible', implementation: 'filesystem-skills', root: '.agents' },
277
- surfaces: [{ kind: 'cli' }, { kind: 'desktop' }],
278
- activation: { rules: 'path-read', skills: 'session-start' },
279
- checker: { kind: 'projection', implementation: 'projection', resultKey: 'codex', installationProbe: { kind: 'none' }, versionProbe: { kind: 'none' } },
280
- },
281
- recommendedCommands: {
282
- doctor: 'buildr doctor --agent codex --target <dir> --json',
283
- syncWorkspaceEntry: 'buildr sync codex --target <dir>',
284
- renderScope: 'buildr render codex --scope <workspace-relative-path> --target <dir>',
285
- renderSkillsScope: 'buildr skills render codex --scope <scope> --target <dir>',
286
- runtimeCheckScope: 'buildr runtime check codex --scope <workspace-relative-path> --target <dir>',
287
- installProductSkill: 'buildr skill install codex --target <dir>',
288
- },
289
- }),
290
- createRuntimeAdapterDescriptor({
291
- id: 'cursor',
292
- displayName: 'Cursor',
293
- traits: {
294
- rules: {
295
- kind: 'vendor-rule-files', implementation: 'vendor-rule-files', format: 'cursor-mdc',
296
- targetPattern: '<source-dir>/.cursor/rules/buildr.mdc',
297
- diagnostics: renderedRulesDiagnostics('Cursor scoped project rule', 'cursor'),
298
- },
299
- skills: { kind: 'agents-compatible', implementation: 'filesystem-skills', root: '.agents' },
300
- surfaces: [{ kind: 'ide' }, { kind: 'cli' }],
301
- activation: { rules: 'path-read', skills: 'session-start', reloadGuidance: 'Start a new Cursor chat after adding or changing project Skills; reopen the chat if project-rule discovery is stale.' },
302
- checker: {
303
- kind: 'projection', implementation: 'projection', resultKey: 'cursor',
304
- installationProbe: { kind: 'manual', guidance: 'Confirm Cursor IDE or Cursor Agent CLI is installed for the surface you are using.' },
305
- versionProbe: { kind: 'manual', guidance: 'Record the Cursor IDE About version or run agent --version when the CLI is installed.' },
306
- },
307
- },
308
- recommendedCommands: recommendedCommands('cursor'),
309
- evidence: { verificationLevel: 'documented', rules: 'official-documentation-with-version-drift-mitigation', skills: 'official-documentation', smokeStatus: 'pending' },
310
- }),
311
- createRuntimeAdapterDescriptor({
312
- id: 'qoder',
313
- displayName: 'Qoder',
314
- traits: {
315
- rules: {
316
- kind: 'vendor-rule-files', implementation: 'vendor-rule-files', format: 'qoder-markdown',
317
- targetPattern: '<workspace-root>/.qoder/rules/buildr/<source-id>.md', maxChars: 100000,
318
- diagnostics: renderedRulesDiagnostics('Qoder vendor rule file', 'qoder'),
319
- },
320
- skills: { kind: 'vendor-root', implementation: 'filesystem-skills', root: '.qoder' },
321
- surfaces: [{ kind: 'ide' }],
322
- activation: { rules: 'path-read', skills: 'explicit-reload', reloadGuidance: 'Run /skills reload when available, or start a new Qoder session.' },
323
- checker: {
324
- kind: 'projection', implementation: 'projection', resultKey: 'qoder',
325
- installationProbe: { kind: 'command', executable: 'qoder', args: ['--version'], timeoutMs: 3000 },
326
- versionProbe: { kind: 'command', executable: 'qoder', args: ['--version'], timeoutMs: 3000 },
327
- },
328
- },
329
- recommendedCommands: recommendedCommands('qoder'),
330
- evidence: { verificationLevel: 'documented', rules: 'official-documentation-and-local-intake', skills: 'official-documentation-and-local-intake', smokeStatus: 'pending' },
331
- }),
332
- createRuntimeAdapterDescriptor({
333
- id: 'trae',
334
- displayName: 'TRAE',
335
- traits: {
336
- rules: {
337
- kind: 'vendor-rule-files', implementation: 'vendor-rule-files', format: 'trae-markdown',
338
- targetPattern: '<source-dir>/.trae/rules/buildr.md',
339
- diagnostics: renderedRulesDiagnostics('TRAE vendor rule file', 'trae'),
340
- },
341
- skills: { kind: 'agents-compatible', implementation: 'filesystem-skills', root: '.agents' },
342
- surfaces: [{ kind: 'ide' }],
343
- activation: { rules: 'path-read', skills: 'session-start', reloadGuidance: 'Start a new TRAE conversation after adding or changing Rules or Skills.' },
344
- checker: {
345
- kind: 'projection', implementation: 'projection', resultKey: 'trae',
346
- installationProbe: { kind: 'command', executable: 'trae', args: ['--version'], timeoutMs: 3000 },
347
- versionProbe: { kind: 'manual', guidance: 'Record the TRAE product version from About; trae --version may report the embedded editor build instead.' },
348
- },
349
- },
350
- recommendedCommands: recommendedCommands('trae'),
351
- evidence: { verificationLevel: 'documented', rules: 'installed-product-and-local-intake', skills: 'installed-product-and-local-intake', smokeStatus: 'pending' },
352
- }),
353
- createRuntimeAdapterDescriptor({
354
- id: 'trae-work',
355
- displayName: 'TRAE Work',
356
- traits: {
357
- rules: {
358
- kind: 'reference-bridge', implementation: 'reference-bridge', placement: 'root-index', template: 'buildr-root-index',
359
- targetPattern: '<workspace-root>/CLAUDE.local.md',
360
- diagnostics: renderedRulesDiagnostics('TRAE Work root rules bridge', 'trae_work'),
361
- },
362
- skills: { kind: 'vendor-root', implementation: 'filesystem-skills', root: '.trae' },
363
- surfaces: [{ kind: 'desktop' }],
364
- activation: { rules: 'session-start', skills: 'immediate', reloadGuidance: 'Start a new TRAE Work conversation after adding or changing imported Rules.' },
365
- checker: {
366
- kind: 'projection', implementation: 'projection', resultKey: 'traeWork',
367
- installationProbe: { kind: 'command', executable: 'defaults', args: ['read', '/Applications/TRAE SOLO.app/Contents/Info', 'CFBundleIdentifier'], timeoutMs: 3000 },
368
- versionProbe: { kind: 'command', executable: 'defaults', args: ['read', '/Applications/TRAE SOLO.app/Contents/Info', 'CFBundleShortVersionString'], timeoutMs: 3000 },
369
- prerequisites: [
370
- { code: 'runtime.trae_work_rules_import_unverified', message: 'TRAE Work Rules import and reference traversal cannot be proven from projection state.', guidance: 'Enable the desktop Rules import toggle for CLAUDE.local.md, start a new conversation, and run the documented reference-bridge smoke.' },
371
- ],
372
- },
373
- },
374
- recommendedCommands: recommendedCommands('trae-work'),
375
- evidence: { verificationLevel: 'documented', rules: 'official-documentation-and-local-intake', skills: 'official-documentation-and-local-intake', smokeStatus: 'pending' },
376
- }),
377
- createRuntimeAdapterDescriptor({
378
- id: 'workbuddy',
379
- displayName: 'WorkBuddy',
380
- traits: {
381
- rules: {
382
- kind: 'reference-bridge', implementation: 'reference-bridge', placement: 'root-index', template: 'buildr-root-index',
383
- targetPattern: '<workspace-root>/CODEBUDDY.md', maxChars: 8000,
384
- diagnostics: renderedRulesDiagnostics('WorkBuddy CODEBUDDY.md rules bridge', 'workbuddy'),
385
- },
386
- skills: { kind: 'vendor-root', implementation: 'filesystem-skills', root: '.codebuddy' },
387
- surfaces: [{ kind: 'desktop' }, { kind: 'cli', variant: 'desktop-bundled' }],
388
- activation: { rules: 'session-start', skills: 'session-start', reloadGuidance: 'Start a new WorkBuddy task after adding or changing Rules or Skills.' },
389
- checker: {
390
- kind: 'projection', implementation: 'projection', resultKey: 'workbuddy',
391
- installationProbe: { kind: 'command', executable: 'defaults', args: ['read', '/Applications/WorkBuddy.app/Contents/Info', 'CFBundleIdentifier'], timeoutMs: 3000 },
392
- versionProbe: { kind: 'command', executable: 'defaults', args: ['read', '/Applications/WorkBuddy.app/Contents/Info', 'CFBundleShortVersionString'], timeoutMs: 3000 },
393
- },
394
- },
395
- recommendedCommands: recommendedCommands('workbuddy'),
396
- evidence: {
397
- verificationLevel: 'verified',
398
- rules: 'installed-source-code-5.2.5',
399
- skills: 'installed-product-docs-and-source',
400
- smokeStatus: 'passed',
401
- smoke: {
402
- observedAt: '2026-07-13',
403
- productVersion: '5.2.5',
404
- runtimeVersion: '2.106.4',
405
- surface: 'desktop-bundled-cli',
406
- rules: { root: 'pass', project: 'pass', active: 'pass', siblingIsolated: 'pass' },
407
- skill: { status: 'pass', result: 'SMOKE_SKILL_DISCOVERED_19AF' },
408
- activation: { rules: 'session-start', skills: 'session-start' },
409
- evidence: 'Headless task from the WorkBuddy desktop bundle plus an audited tool transcript; no sibling Rule file was read.',
410
- },
411
- },
412
- }),
413
- ];
414
-
415
- export function validateAdapterDescriptor(descriptor, options = {}) {
416
- const errors = [];
417
- if (!descriptor || typeof descriptor !== 'object') return ['adapter descriptor must be an object'];
418
- errors.push(...validateAdapterTraits(descriptor, options));
419
- if (!AGENT_ID_PATTERN.test(descriptor.id || '')) errors.push(`adapter id is invalid: ${descriptor.id || '<missing>'}`);
420
- if (!descriptor.displayName) errors.push(`adapter ${descriptor.id || '<missing>'} displayName is required`);
421
- if (!Array.isArray(descriptor.runtimeTargets) || descriptor.runtimeTargets.length === 0) errors.push(`adapter ${descriptor.id} runtimeTargets are required`);
422
- if (new Set(descriptor.runtimeTargets || []).size !== (descriptor.runtimeTargets || []).length) errors.push(`adapter ${descriptor.id} runtimeTargets must be unique`);
423
- for (const capability of REQUIRED_RENDER_CAPABILITIES) {
424
- if (descriptor.renderCapabilities?.[capability]?.supported !== true) errors.push(`adapter ${descriptor.id} is missing required capability ${capability}`);
425
- }
426
- for (const capability of Object.keys(descriptor.renderCapabilities || {})) {
427
- if (!REQUIRED_RENDER_CAPABILITIES.includes(capability)) errors.push(`adapter ${descriptor.id} declares unknown capability ${capability}`);
428
- }
429
- if (typeof descriptor.planRuntime !== 'function') errors.push(`adapter ${descriptor.id} planRuntime is required`);
430
- if (!descriptor.implementation || !['string', 'object'].includes(typeof descriptor.implementation)) errors.push(`adapter ${descriptor.id} implementation entry is required`);
431
- if (!descriptor.recommendedCommands || typeof descriptor.recommendedCommands !== 'object') errors.push(`adapter ${descriptor.id} recommendedCommands are required`);
432
- const evidence = descriptor.evidence || {};
433
- if (Object.keys(evidence).length > 0) {
434
- if (!ADAPTER_VERIFICATION_LEVELS.includes(evidence.verificationLevel)) errors.push(`adapter ${descriptor.id} evidence verificationLevel is invalid: ${evidence.verificationLevel || '<missing>'}`);
435
- if (!['pending', 'passed'].includes(evidence.smokeStatus)) errors.push(`adapter ${descriptor.id} evidence smokeStatus is invalid: ${evidence.smokeStatus || '<missing>'}`);
436
- if (evidence.verificationLevel === 'verified' && evidence.smokeStatus !== 'passed') errors.push(`adapter ${descriptor.id} verified evidence requires a passed smoke`);
437
- if (evidence.smokeStatus === 'passed' && evidence.verificationLevel !== 'verified') errors.push(`adapter ${descriptor.id} passed smoke requires verified evidence`);
438
- }
439
- return errors;
440
- }
441
-
442
- export function createRuntimeAdapterRegistry(descriptors, options = {}) {
443
- const registry = {};
444
- const errors = [];
445
- for (const descriptor of descriptors) {
446
- errors.push(...validateAdapterDescriptor(descriptor, options));
447
- if (registry[descriptor?.id]) errors.push(`duplicate adapter id: ${descriptor.id}`);
448
- if (descriptor?.id) registry[descriptor.id] = descriptor;
449
- }
450
- if (errors.length > 0) throw new Error(`Invalid runtime adapter registry:\n- ${errors.join('\n- ')}`);
451
- const result = freeze({ ...registry });
452
- if (options.testOnly === true) return result;
453
- return result;
454
- }
455
-
456
- export const RUNTIME_ADAPTERS = createRuntimeAdapterRegistry(DESCRIPTORS);
457
- export const SUPPORTED_AGENT_IDS = Object.freeze(Object.keys(RUNTIME_ADAPTERS));
458
-
459
- export function isSupportedAgent(agent) {
460
- return Object.hasOwn(RUNTIME_ADAPTERS, agent);
461
- }
462
-
463
- export function getRuntimeAdapter(agent) {
464
- const adapter = RUNTIME_ADAPTERS[agent];
465
- if (!adapter) throw new Error(`Unsupported Agent runtime: ${agent}`);
466
- return adapter;
467
- }
468
-
469
- export function selectAdapterImplementation(adapter, kind, implementations) {
470
- const implementation = adapter.implementation?.[kind];
471
- const selected = implementations[implementation];
472
- if (!selected) throw new Error(`Runtime adapter ${adapter.id} has no registered ${kind} implementation: ${implementation || '<missing>'}`);
473
- return selected;
474
- }
475
-
476
- export function runtimeDiscoveryPayload() {
477
- return {
478
- supportedAgents: [...SUPPORTED_AGENT_IDS],
479
- requiredRenderCapabilities: [...REQUIRED_RENDER_CAPABILITIES],
480
- adapterTraitCatalog: ADAPTER_TRAIT_CATALOG,
481
- agents: RUNTIME_ADAPTERS,
482
- unsupportedAgentGuidance: UNSUPPORTED_AGENT_GUIDANCE,
483
- };
484
- }
485
-
486
- export function createRuntimeContext(value) {
487
- const context = {
488
- adapterId: value.adapterId,
489
- targetRoot: path.resolve(value.targetRoot),
490
- scope: value.scope,
491
- rules: value.rules || { writes: [], nativeAssets: [], removals: [], actions: [] },
492
- skills: value.skills || { writes: [], removals: [] },
493
- findings: value.findings || [],
494
- repairs: value.repairs || [],
495
- warnings: value.warnings || [],
496
- };
497
- return freeze(context);
498
- }
499
-
500
- export function createRuntimePlan(value) {
501
- return freeze({
502
- schemaVersion: 'buildr.runtime-plan/v1',
503
- adapterId: value.adapterId,
504
- targetRoot: path.resolve(value.targetRoot),
505
- scope: value.scope,
506
- writes: value.writes || [],
507
- nativeAssets: value.nativeAssets || [],
508
- removals: value.removals || [],
509
- capabilityEvidence: value.capabilityEvidence || [],
510
- findings: value.findings || [],
511
- repairs: value.repairs || [],
512
- warnings: value.warnings || [],
513
- ruleActions: value.ruleActions || [],
514
- });
515
- }
516
-
517
- function safeTarget(targetRoot, targetFile) {
518
- const root = path.resolve(targetRoot);
519
- const target = path.resolve(targetFile);
520
- return target !== root && target.startsWith(`${root}${path.sep}`);
521
- }
522
-
523
- function firstSymbolicLinkSegment(targetRoot, targetFile) {
524
- const root = path.resolve(targetRoot);
525
- const target = path.resolve(targetFile);
526
- const relative = path.relative(root, target);
527
- if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
528
- let current = root;
529
- for (const segment of ['.', ...relative.split(path.sep)]) {
530
- if (segment !== '.') current = path.join(current, segment);
531
- try {
532
- if (fs.lstatSync(current).isSymbolicLink()) return current;
533
- } catch (error) {
534
- if (error?.code === 'ENOENT') break;
535
- throw error;
536
- }
537
- }
538
- return null;
539
- }
540
-
541
- export function assertRuntimeTargetPath(targetRoot, targetFile, label = 'Runtime target') {
542
- if (!safeTarget(targetRoot, targetFile)) {
543
- throw new Error(`${label} is outside target root: ${targetFile}`);
544
- }
545
- const symbolicLink = firstSymbolicLinkSegment(targetRoot, targetFile);
546
- if (symbolicLink) {
547
- throw new Error(`${label} crosses a symbolic link: ${symbolicLink}`);
548
- }
549
- return path.resolve(targetFile);
550
- }
551
-
552
- export function validateRuntimePlan(plan, adapter = getRuntimeAdapter(plan?.adapterId)) {
553
- const errors = [];
554
- if (plan?.schemaVersion !== 'buildr.runtime-plan/v1') errors.push('runtime plan schemaVersion is invalid');
555
- if (plan?.adapterId !== adapter.id) errors.push(`runtime plan adapterId does not match descriptor: ${plan?.adapterId}`);
556
- const writes = new Map();
557
- for (const item of plan?.writes || []) {
558
- try { assertRuntimeTargetPath(plan.targetRoot, item.targetFile, 'runtime write target'); }
559
- catch (error) { errors.push(error.message); }
560
- if (typeof item.content !== 'string') errors.push(`runtime write content must be text: ${item.targetFile}`);
561
- const existing = writes.get(path.resolve(item.targetFile));
562
- if (existing && existing.content !== item.content) errors.push(`runtime writes contain conflicting target: ${item.targetFile}`);
563
- else writes.set(path.resolve(item.targetFile), item);
564
- }
565
- const removals = new Set();
566
- for (const item of plan?.removals || []) {
567
- const targetFile = typeof item === 'string' ? item : item.targetFile;
568
- try { assertRuntimeTargetPath(plan.targetRoot, targetFile, 'runtime removal target'); }
569
- catch (error) { errors.push(error.message); }
570
- if (writes.has(path.resolve(targetFile))) errors.push(`runtime target cannot be written and removed: ${targetFile}`);
571
- if (removals.has(path.resolve(targetFile))) errors.push(`runtime removals contain duplicate target: ${targetFile}`);
572
- removals.add(path.resolve(targetFile));
573
- }
574
- const evidence = new Map((plan?.capabilityEvidence || []).map((item) => [item.capability, item]));
575
- for (const capability of REQUIRED_RENDER_CAPABILITIES) {
576
- if (evidence.get(capability)?.supported !== true) errors.push(`runtime plan is missing capability evidence: ${capability}`);
577
- }
578
- for (const capability of evidence.keys()) {
579
- if (!REQUIRED_RENDER_CAPABILITIES.includes(capability)) errors.push(`runtime plan has unknown capability evidence: ${capability}`);
580
- }
581
- if (errors.length > 0) throw new Error(`Invalid runtime plan for ${adapter.id}:\n- ${errors.join('\n- ')}`);
582
- return plan;
583
- }
584
-
585
- function runtimePath(targetRoot, targetFile) {
586
- return path.relative(targetRoot, targetFile).split(path.sep).join('/');
587
- }
588
-
589
- function diagnosticFinding(item, observedStatus, plan) {
590
- const diagnostic = item.diagnostic || {};
591
- const status = observedStatus === 'ok' && diagnostic.currentStatus
592
- ? diagnostic.currentStatus
593
- : observedStatus === 'ok' && diagnostic.actionRequiredWhenCurrent ? 'stale' : observedStatus;
594
- const code = diagnostic.codes?.[status] || diagnostic.code;
595
- const message = diagnostic.messages?.[status]
596
- || (status === 'ok' ? `${diagnostic.label || item.source || 'runtime target'} is up to date.` : `${diagnostic.label || item.source || 'runtime target'} is ${status}.`);
597
- const repair = status === 'ok' ? undefined : diagnostic.repairs?.[status] || diagnostic.repair;
598
- return {
599
- status,
600
- path: runtimePath(plan.targetRoot, item.targetFile),
601
- adapter: plan.adapterId,
602
- source: item.source,
603
- message,
604
- ...(code ? { code } : {}),
605
- ...(repair ? { repair } : {}),
606
- userActionRequired: status !== 'ok' && status !== 'info' && status !== 'warning',
607
- };
608
- }
609
-
610
- export function reconcileRuntimePlan(plan, options = {}) {
611
- validateRuntimePlan(plan);
612
- const compareOnly = options.compareOnly === true;
613
- const conflicts = [];
614
- const changed = [];
615
- const removed = [];
616
- for (const item of plan.writes) {
617
- if (!fs.existsSync(item.targetFile)) continue;
618
- const current = fs.readFileSync(item.targetFile, 'utf8');
619
- const matches = current === item.content || item.matchesCurrent?.(current) === true;
620
- if (!matches && current !== item.sourceContent && item.isManaged && !item.isManaged(current)) conflicts.push(item);
621
- }
622
- const findings = [...plan.findings];
623
- for (const item of conflicts) findings.push(diagnosticFinding(item, 'conflict', plan));
624
- const plannedConflicts = findings.filter((finding) => finding.status === 'conflict');
625
- if (!compareOnly && plannedConflicts.length > 0) {
626
- throw new Error(`Runtime reconcile found conflict(s); no files were changed:\n- ${plannedConflicts.map((finding) => finding.message || finding.path).sort().join('\n- ')}`);
627
- }
628
- for (const item of plan.writes) {
629
- if (conflicts.includes(item)) continue;
630
- const current = fs.existsSync(item.targetFile) ? fs.readFileSync(item.targetFile, 'utf8') : null;
631
- const status = current === null ? 'missing' : current === item.content || item.matchesCurrent?.(current) === true ? 'ok' : 'stale';
632
- findings.push(diagnosticFinding(item, status, plan));
633
- if (!compareOnly && status !== 'ok') {
634
- fs.mkdirSync(path.dirname(item.targetFile), { recursive: true });
635
- fs.writeFileSync(item.targetFile, item.content, 'utf8');
636
- changed.push(item.targetFile);
637
- }
638
- }
639
- for (const nativeAsset of plan.nativeAssets) {
640
- const item = typeof nativeAsset === 'string' ? { targetFile: nativeAsset, source: nativeAsset } : nativeAsset;
641
- const status = fs.existsSync(item.targetFile) ? 'ok' : 'missing';
642
- findings.push(diagnosticFinding(item, status, plan));
643
- }
644
- for (const removal of plan.removals) {
645
- const item = typeof removal === 'string' ? { targetFile: removal } : removal;
646
- if (!fs.existsSync(item.targetFile)) continue;
647
- if (item.isManaged && !item.isManaged(item.type === 'directory' ? null : fs.readFileSync(item.targetFile, 'utf8'))) continue;
648
- findings.push(diagnosticFinding(item, 'orphan', plan));
649
- if (!compareOnly) {
650
- fs.rmSync(item.targetFile, { recursive: item.type === 'directory', force: true });
651
- removed.push(item.targetFile);
652
- }
653
- }
654
- return { targetRoot: plan.targetRoot, adapterId: plan.adapterId, scope: plan.scope, changed, removed, findings, repairs: plan.repairs, warnings: plan.warnings, ruleActions: plan.ruleActions };
655
- }