@sous-io/sous 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/README.md +115 -35
  2. package/bin/run.js +10 -1
  3. package/docs/markdown/README.md +27 -0
  4. package/docs/markdown/_sidebar.md +18 -0
  5. package/docs/markdown/commands.md +308 -0
  6. package/docs/markdown/config-discovery.md +74 -0
  7. package/docs/markdown/config-inspection.md +69 -0
  8. package/docs/markdown/config-layers.md +92 -0
  9. package/docs/markdown/config-variables.md +79 -0
  10. package/docs/markdown/configuration.md +71 -0
  11. package/docs/markdown/design-principles.md +59 -0
  12. package/docs/markdown/repositories-authoring.md +408 -0
  13. package/docs/markdown/repositories-consuming.md +580 -0
  14. package/docs/markdown/repositories-file-formats.md +1084 -0
  15. package/docs/markdown/repositories-variables.md +387 -0
  16. package/docs/markdown/repositories.md +303 -0
  17. package/docs/markdown/skill-categories.md +58 -0
  18. package/package.json +72 -8
  19. package/{shared-prompts/skills/sous-skills → recipes/core/sous-skills/skills}/about-agent-skills/SKILL.tpl.md +20 -20
  20. package/{shared-prompts/skills/sous-skills → recipes/core/sous-skills/skills}/about-agent-skills/examples/about-something.md +2 -2
  21. package/{shared-prompts/skills/sous-skills → recipes/core/sous-skills/skills}/about-agent-skills/examples/do-something.md +1 -1
  22. package/{shared-prompts/skills/sous-skills → recipes/core/sous-skills/skills}/about-agent-skills/references/advanced-patterns.md +6 -6
  23. package/{shared-prompts/skills/sous-skills → recipes/core/sous-skills/skills}/about-agent-skills/references/commands.md +5 -5
  24. package/{shared-prompts/skills/sous-skills → recipes/core/sous-skills/skills}/about-agent-skills/references/frontmatter.md +3 -3
  25. package/{shared-prompts/skills/sous-skills → recipes/core/sous-skills/skills}/about-liquid-templates/SKILL.tpl.md +40 -25
  26. package/recipes/core/sous-skills/skills/about-sous/SKILL.tpl.md +70 -0
  27. package/recipes/core/sous-skills/skills/about-sous-configuration/SKILL.tpl.md +75 -0
  28. package/{shared-prompts/skills/sous-skills → recipes/core/sous-skills/skills}/create-skill/SKILL.tpl.md +8 -9
  29. package/recipes/core/sous-skills/sous.recipe.yaml +45 -0
  30. package/sous.config.schema.json +337 -0
  31. package/src/base-command.ts +220 -67
  32. package/src/commands/build.ts +150 -73
  33. package/src/commands/clear.ts +23 -15
  34. package/src/commands/compile.ts +74 -16
  35. package/src/commands/config/get.ts +110 -0
  36. package/src/commands/config/show.ts +32 -0
  37. package/src/commands/config/validate.ts +53 -0
  38. package/src/commands/help.ts +46 -0
  39. package/src/commands/launch.ts +36 -14
  40. package/src/commands/lock/rebuild.ts +241 -0
  41. package/src/commands/lock/show.ts +115 -0
  42. package/src/commands/namespace/list.ts +117 -0
  43. package/src/commands/namespace/show.ts +110 -0
  44. package/src/commands/prune.ts +3 -11
  45. package/src/commands/recipe/list.ts +95 -0
  46. package/src/commands/recipe/show.ts +301 -0
  47. package/src/commands/repo/add.ts +145 -0
  48. package/src/commands/repo/gc.ts +172 -0
  49. package/src/commands/repo/init.ts +136 -0
  50. package/src/commands/repo/link.ts +500 -0
  51. package/src/commands/repo/list.ts +179 -0
  52. package/src/commands/repo/release.ts +619 -0
  53. package/src/commands/repo/remove.ts +193 -0
  54. package/src/commands/repo/search.ts +189 -0
  55. package/src/commands/repo/submit.ts +133 -0
  56. package/src/commands/repo/unlink.ts +147 -0
  57. package/src/commands/subscription/add.ts +285 -0
  58. package/src/commands/subscription/list.ts +129 -0
  59. package/src/commands/subscription/remove.ts +181 -0
  60. package/src/commands/vars/ask.ts +374 -0
  61. package/src/commands/vars/index.ts +79 -0
  62. package/src/commands/vars/list.ts +67 -0
  63. package/src/commands/vars/show.ts +77 -0
  64. package/src/config-command.ts +30 -0
  65. package/src/lib/build-service.ts +206 -54
  66. package/src/lib/config-discovery.ts +220 -27
  67. package/src/lib/config-inspect.ts +145 -0
  68. package/src/lib/config-kernel.mjs +377 -0
  69. package/src/lib/config-schema.ts +361 -0
  70. package/src/lib/env-file.ts +328 -0
  71. package/src/lib/env-local.ts +18 -1
  72. package/src/lib/errors.ts +32 -0
  73. package/src/lib/include-resolver.ts +108 -15
  74. package/src/lib/interactive.ts +165 -0
  75. package/src/lib/markdown-compiler.ts +118 -37
  76. package/src/lib/package-info.ts +25 -0
  77. package/src/lib/pid-service.ts +32 -21
  78. package/src/lib/refs/find.ts +589 -0
  79. package/src/lib/refs/index.ts +12 -0
  80. package/src/lib/refs/pick.ts +147 -0
  81. package/src/lib/refs/scopes.ts +61 -0
  82. package/src/lib/repos/catalog-display.ts +116 -0
  83. package/src/lib/repos/catalog-inputs.ts +160 -0
  84. package/src/lib/repos/catalog.ts +722 -0
  85. package/src/lib/repos/core-recipe.ts +105 -0
  86. package/src/lib/repos/defaults.ts +175 -0
  87. package/src/lib/repos/formats/common.ts +389 -0
  88. package/src/lib/repos/formats/index-file.ts +215 -0
  89. package/src/lib/repos/formats/links-map.ts +96 -0
  90. package/src/lib/repos/formats/lockfile.ts +167 -0
  91. package/src/lib/repos/formats/patterns.ts +57 -0
  92. package/src/lib/repos/formats/recipe-manifest.ts +395 -0
  93. package/src/lib/repos/formats/repo-manifest.ts +88 -0
  94. package/src/lib/repos/formats/store-entry.ts +84 -0
  95. package/src/lib/repos/freshness.ts +208 -0
  96. package/src/lib/repos/git-clone.ts +312 -0
  97. package/src/lib/repos/identity.ts +89 -0
  98. package/src/lib/repos/index.ts +58 -0
  99. package/src/lib/repos/links.ts +353 -0
  100. package/src/lib/repos/load-manifest.ts +236 -0
  101. package/src/lib/repos/lock-service.ts +453 -0
  102. package/src/lib/repos/locked-namespace-resolver.ts +90 -0
  103. package/src/lib/repos/locked-recipes.ts +254 -0
  104. package/src/lib/repos/managed-layer.ts +422 -0
  105. package/src/lib/repos/namespace-resolver.ts +370 -0
  106. package/src/lib/repos/providers/base.ts +206 -0
  107. package/src/lib/repos/providers/git.ts +233 -0
  108. package/src/lib/repos/providers/github.ts +294 -0
  109. package/src/lib/repos/providers/gitlab.ts +263 -0
  110. package/src/lib/repos/providers/http.ts +102 -0
  111. package/src/lib/repos/providers/index-cache.ts +382 -0
  112. package/src/lib/repos/providers/index.ts +106 -0
  113. package/src/lib/repos/providers/local.ts +391 -0
  114. package/src/lib/repos/providers/provider.ts +401 -0
  115. package/src/lib/repos/recipe-config-layers.ts +287 -0
  116. package/src/lib/repos/recipe-targets.ts +223 -0
  117. package/src/lib/repos/ref-search.ts +46 -0
  118. package/src/lib/repos/ref.ts +513 -0
  119. package/src/lib/repos/reference-report.ts +122 -0
  120. package/src/lib/repos/release/bump.ts +161 -0
  121. package/src/lib/repos/release/git-state.ts +305 -0
  122. package/src/lib/repos/release/index-builder.ts +635 -0
  123. package/src/lib/repos/release/index.ts +16 -0
  124. package/src/lib/repos/release/plan.ts +512 -0
  125. package/src/lib/repos/release/submit-service.ts +496 -0
  126. package/src/lib/repos/release/tags.ts +243 -0
  127. package/src/lib/repos/release/validate.ts +463 -0
  128. package/src/lib/repos/resolver.ts +789 -0
  129. package/src/lib/repos/scaffold/index.ts +238 -0
  130. package/src/lib/repos/scaffold/templates.ts +413 -0
  131. package/src/lib/repos/seed.ts +414 -0
  132. package/src/lib/repos/store/contract.ts +64 -0
  133. package/src/lib/repos/store/hash.ts +114 -0
  134. package/src/lib/repos/store/recipe-store.ts +599 -0
  135. package/src/lib/repos/store/settings.ts +58 -0
  136. package/src/lib/repos/subscription-service.ts +2678 -0
  137. package/src/lib/repos/trust.ts +447 -0
  138. package/src/lib/settings.ts +546 -189
  139. package/src/lib/sous-home.ts +104 -0
  140. package/src/lib/state.ts +52 -20
  141. package/src/lib/vars/ask.ts +1152 -0
  142. package/src/lib/vars/definition-source.ts +252 -0
  143. package/src/lib/vars/display.ts +233 -0
  144. package/src/lib/vars/index.ts +18 -0
  145. package/src/lib/vars/ladder.ts +282 -0
  146. package/src/lib/vars/mappings.ts +265 -0
  147. package/src/lib/vars/names.ts +94 -0
  148. package/src/lib/vars/preanswers.ts +395 -0
  149. package/src/lib/vars/question-plan.ts +218 -0
  150. package/src/lib/vars/report.ts +228 -0
  151. package/src/lib/vars/safe-regex.ts +235 -0
  152. package/src/lib/vars/validate.ts +312 -0
  153. package/src/lib/watch-loop.ts +148 -0
  154. package/src/templating/init-liquid-engine.ts +58 -16
  155. package/src/utils/choice-prompt.ts +143 -0
  156. package/src/utils/command-errors.ts +186 -0
  157. package/src/utils/command-help.ts +45 -0
  158. package/src/utils/confirm-prompt.ts +110 -0
  159. package/src/utils/flags.ts +153 -0
  160. package/src/utils/formatting.ts +540 -55
  161. package/src/utils/prompts.ts +35 -1
  162. package/src/utils/sous-directory.ts +245 -0
  163. package/src/utils/table.ts +603 -0
  164. package/src/utils/value-prompt.ts +119 -0
  165. package/shared-prompts/_partials/resume-task.md +0 -51
  166. package/shared-prompts/_partials/sub-agent-delegation.md +0 -32
  167. package/shared-prompts/_partials/update-task-file.md +0 -52
  168. package/shared-prompts/memories/automated-browser-tasks/INDEX.tpl.md +0 -52
  169. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/SKILL.tpl.md +0 -102
  170. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/examples/auth-failure-handling.mjs +0 -81
  171. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/examples/chained-workflow.mjs +0 -126
  172. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/examples/simple-fetch.mjs +0 -92
  173. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/references/architecture.md +0 -61
  174. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/references/auth-and-sessions.md +0 -65
  175. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/references/ctx-api.md +0 -96
  176. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/references/installation.md +0 -104
  177. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/references/script-conventions.md +0 -243
  178. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/chrome-state.mjs +0 -148
  179. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/debug.mjs +0 -383
  180. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/debug.spec.mjs +0 -267
  181. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/eslint.config.mjs +0 -56
  182. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/harness.mjs +0 -169
  183. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/keyring.mjs +0 -59
  184. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/logger.mjs +0 -25
  185. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/params.mjs +0 -140
  186. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/run.mjs +0 -140
  187. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/settings.tpl.mjs +0 -1
  188. package/shared-prompts/skills/automated-browser-tasks/about-automated-browser-tasks/scripts/utils.mjs +0 -185
  189. package/shared-prompts/skills/automated-browser-tasks/create-automated-browser-task/SKILL.tpl.md +0 -52
  190. package/shared-prompts/skills/automated-browser-tasks/running-automated-browser-tasks/SKILL.tpl.md +0 -59
  191. package/shared-prompts/skills/automated-browser-tasks/update-automated-browser-task/SKILL.tpl.md +0 -47
  192. package/shared-prompts/skills/control-flow/approve/SKILL.tpl.md +0 -26
  193. package/shared-prompts/skills/control-flow/opine/SKILL.tpl.md +0 -58
  194. package/shared-prompts/skills/control-flow/repeat/SKILL.tpl.md +0 -27
  195. package/shared-prompts/skills/control-flow/research/SKILL.tpl.md +0 -34
  196. package/shared-prompts/skills/sous-skills/about-sous/SKILL.tpl.md +0 -51
  197. package/shared-prompts/skills/task-files/about-task-files/SKILL.tpl.md +0 -122
  198. package/shared-prompts/skills/task-files/continue-task-in-new-branch/SKILL.tpl.md +0 -80
  199. package/shared-prompts/skills/task-files/go/SKILL.tpl.md +0 -14
  200. package/shared-prompts/skills/task-files/resume-task/SKILL.tpl.md +0 -13
  201. package/shared-prompts/skills/task-files/start-task/SKILL.tpl.md +0 -93
  202. package/shared-prompts/skills/task-files/update/SKILL.tpl.md +0 -14
  203. package/shared-prompts/skills/task-files/update-task-file/SKILL.tpl.md +0 -13
  204. /package/{shared-prompts/skills/sous-skills → recipes/core/sous-skills/skills}/about-agent-skills/references/substitutions.md +0 -0
  205. /package/{shared-prompts/skills/sous-skills → recipes/core/sous-skills/skills}/about-liquid-templates/references/liquid-filters.md +0 -0
@@ -0,0 +1,377 @@
1
+ /**
2
+ * The sous "config kernel": a single loader subprocess that turns an ordered
3
+ * list of config layer files into ONE merged, plain-JSON config.
4
+ *
5
+ * Spawned by loadSettings (src/lib/settings.ts). Plain JavaScript ESM, no
6
+ * TypeScript syntax — it must run under bare Node AND under the tsx loader
7
+ * (the tsx attempt exists so user configs may use TypeScript syntax). It ships
8
+ * to npm via the package.json "files": "src" allowlist.
9
+ *
10
+ * Protocol
11
+ * --------
12
+ * stdin (one JSON document):
13
+ * {
14
+ * sources: (string | { path, config })[], // ordered layers, primary first.
15
+ * // A string is an absolute layer path the
16
+ * // kernel reads itself. An object is a layer
17
+ * // the parent already read and filtered (a
18
+ * // subscribed recipe's config layer); the
19
+ * // kernel merges `config` as-is and never
20
+ * // opens `path`.
21
+ * context: { sousDir, confDir, sousRootPath, sousVersion, configPath },
22
+ * trace: boolean
23
+ * }
24
+ *
25
+ * stdout (one JSON document):
26
+ * { config, layers }
27
+ * `layers` is [] unless trace; when tracing it holds one { path, config }
28
+ * snapshot of the CUMULATIVE config after each top-level source. Builder
29
+ * sub-loads (loadConfig/loadConfigs) fold into the enclosing layer's snapshot.
30
+ *
31
+ * Any layer failure (parse error, import error, configure() throw, cycle,
32
+ * old multi-project schema) writes a message NAMING THE LAYER FILE to stderr
33
+ * and exits 1; the parent wraps stderr in a ConfigError.
34
+ *
35
+ * Layer contract
36
+ * --------------
37
+ * - .json → JSON.parse of the file text.
38
+ * - .jsonc → JSON with comments: line comments, block comments and trailing
39
+ * commas are allowed. The layers sous manages are written this way.
40
+ * - .yaml → parsed with the 'yaml' package.
41
+ * - .js/.mjs → dynamic import. The module may export:
42
+ * * an object: `config`, else `default` when it is a non-function object;
43
+ * * a function: `configure`, else `default` when it is a function;
44
+ * * both: the object merges FIRST, then the function runs.
45
+ * The function is awaited: `await fn(currentConfig, builder)`. It may mutate
46
+ * `currentConfig` by reference freely; a returned object (if any) is merged
47
+ * after it resolves — UNLESS it is `currentConfig` itself (mutate-and-return
48
+ * for chaining), which is skipped so self-merge does not duplicate arrays.
49
+ *
50
+ * Every layer object is forced through a JSON round-trip BEFORE merging, so
51
+ * functions, RegExp, Date and undefined values drop at the layer boundary.
52
+ * The final cumulative config is JSON round-tripped again on the way out.
53
+ *
54
+ * Merge semantics (deepMerge): plain object + plain object → recurse;
55
+ * array + array → concatenate (target then source); anything else → the
56
+ * source value replaces. No dedupe.
57
+ */
58
+
59
+ import fs from "node:fs";
60
+ import path from "node:path";
61
+ import { pathToFileURL } from "node:url";
62
+ import { parse as parseYaml } from "yaml";
63
+ import { globSync } from "glob";
64
+ import { parse as parseJsonc, printParseErrorCode } from "jsonc-parser";
65
+
66
+ // --- small utilities -----------------------------------------------------------------------------
67
+
68
+ /** True for a plain object (not null, not an array). */
69
+ function isPlainObject(value) {
70
+ return value !== null && typeof value === "object" && !Array.isArray(value);
71
+ }
72
+
73
+ /**
74
+ * Parses a `.jsonc` layer: JSON plus line comments, block comments and trailing
75
+ * commas. The error names the layer file and the line the parser stopped on.
76
+ */
77
+ function parseJsoncLayer(text, filePath) {
78
+ const errors = [];
79
+ const value = parseJsonc(text, errors, { allowTrailingComma: true, disallowComments: false });
80
+
81
+ if (errors.length > 0) {
82
+ const first = errors[0];
83
+ const before = text.slice(0, first.offset);
84
+ const line = before.split("\n").length;
85
+ const column = first.offset - before.lastIndexOf("\n");
86
+ throw new Error(
87
+ `Config layer ${filePath} is not valid JSON with comments: ` +
88
+ `${printParseErrorCode(first.error)} at line ${line}, column ${column}.\n` +
89
+ ` Comments and trailing commas are allowed; anything else must be valid JSON.`
90
+ );
91
+ }
92
+
93
+ return value;
94
+ }
95
+
96
+ /** Forces a value through a JSON round-trip. */
97
+ function jsonRoundTrip(value) {
98
+ return JSON.parse(JSON.stringify(value));
99
+ }
100
+
101
+ /**
102
+ * Bytewise string comparison (plain `<` on the string), locale-independent so
103
+ * layer order is identical on every machine. NOT numeric: '10-' sorts before '2-'.
104
+ */
105
+ function bytewiseCompare(a, b) {
106
+ return a < b ? -1 : a > b ? 1 : 0;
107
+ }
108
+
109
+ /**
110
+ * Deep-merges `source` INTO `target` (the live cumulative config).
111
+ * plain object + plain object → recurse; array + array → concatenate
112
+ * (target then source, no dedupe); anything else → source replaces.
113
+ */
114
+ function deepMerge(target, source) {
115
+ for (const [key, sourceValue] of Object.entries(source)) {
116
+ // Guard against prototype pollution: a JSON layer can carry an OWN
117
+ // enumerable "__proto__" (or "constructor"/"prototype") key through the
118
+ // round-trip; merging it would mutate Object.prototype and corrupt every
119
+ // later object (including tripping the old-schema guard on innocent layers).
120
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
121
+ continue;
122
+ }
123
+ const targetValue = target[key];
124
+ if (isPlainObject(targetValue) && isPlainObject(sourceValue)) {
125
+ deepMerge(targetValue, sourceValue);
126
+ } else if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
127
+ target[key] = [...targetValue, ...sourceValue];
128
+ } else {
129
+ target[key] = sourceValue;
130
+ }
131
+ }
132
+ return target;
133
+ }
134
+
135
+ // --- kernel --------------------------------------------------------------------------------------
136
+
137
+ async function readStdin() {
138
+ const chunks = [];
139
+ for await (const chunk of process.stdin) chunks.push(chunk);
140
+ return Buffer.concat(chunks).toString("utf8");
141
+ }
142
+
143
+ async function main() {
144
+ const { sources, context, trace } = JSON.parse(await readStdin());
145
+
146
+ /** The live cumulative config every layer merges into. */
147
+ const currentConfig = {};
148
+
149
+ /** Trace-mode snapshots: one per TOP-LEVEL source, taken after it finishes. */
150
+ const layers = [];
151
+
152
+ /** Absolute paths currently mid-load, for cycle detection. */
153
+ const loadingSet = new Set();
154
+
155
+ /** The layer file whose code is currently executing (for builder.currentFile). */
156
+ let currentFile = null;
157
+
158
+ /**
159
+ * The only variables usable in builder loadConfig/loadConfigs paths. Builder
160
+ * paths resolve BEFORE variable resolution, so user _vars do not exist yet.
161
+ */
162
+ const autoVars = {
163
+ sousDir: context.sousDir,
164
+ sousConfDir: context.confDir,
165
+ sousRootPath: context.sousRootPath,
166
+ sousVersion: context.sousVersion,
167
+ };
168
+
169
+ /** Substitutes ${autoVar} references in a builder path; any other var is fatal. */
170
+ function substituteAutoVars(rawPath, where) {
171
+ return rawPath.replace(/\$\{([^}]+)\}/g, (_match, name) => {
172
+ if (name in autoVars) return autoVars[name];
173
+ throw new Error(
174
+ `${where}: \${${name}} cannot be used in a builder path.\n` +
175
+ ` Builder paths (loadConfig/loadConfigs) resolve BEFORE variable resolution, so user\n` +
176
+ ` _vars are not available yet. Only these auto-vars are allowed:\n` +
177
+ ` ${Object.keys(autoVars)
178
+ .map((n) => "${" + n + "}")
179
+ .join(", ")}`
180
+ );
181
+ });
182
+ }
183
+
184
+ /** Resolves a builder path: auto-vars, then relative-to-the-current-layer-file. */
185
+ function resolveBuilderPath(rawPath, where) {
186
+ const substituted = substituteAutoVars(String(rawPath), where);
187
+ if (path.isAbsolute(substituted)) return path.normalize(substituted);
188
+ return path.resolve(path.dirname(currentFile), substituted);
189
+ }
190
+
191
+ /**
192
+ * Guards against the removed multi-project schema, per layer, so the error
193
+ * names the exact file that still uses it.
194
+ */
195
+ function assertNotOldSchema(layerObject, filePath) {
196
+ if (isPlainObject(layerObject) && ("projects" in layerObject || "defaultProject" in layerObject)) {
197
+ throw new Error(
198
+ `Config layer ${filePath} uses the removed multi-project schema ` +
199
+ `('projects' / 'defaultProject').\n` +
200
+ ` A sous config now describes exactly one project. To migrate:\n` +
201
+ ` 1. Move your single project's fields (name, _vars, _aliases, compilation,\n` +
202
+ ` runtimeContext, tools) to the top level of the config.\n` +
203
+ ` 2. Delete the 'projects' and 'defaultProject' keys.\n` +
204
+ ` A config with several projects must be split into one config per project.`
205
+ );
206
+ }
207
+ }
208
+
209
+ /**
210
+ * JSON-forces a layer's object and deep-merges it into the live config.
211
+ * Runs the old-schema guard on the layer's OWN object, pre-merge.
212
+ */
213
+ function mergeLayerObject(layerObject, filePath) {
214
+ if (!isPlainObject(layerObject)) {
215
+ throw new Error(
216
+ `Config layer ${filePath} did not produce a plain object (got ${
217
+ Array.isArray(layerObject) ? "an array" : typeof layerObject
218
+ }).`
219
+ );
220
+ }
221
+ assertNotOldSchema(layerObject, filePath);
222
+ deepMerge(currentConfig, jsonRoundTrip(layerObject));
223
+ }
224
+
225
+ /**
226
+ * The builder singleton passed to every configure(currentConfig, builder).
227
+ * One instance per kernel run; `currentFile` tracks whichever layer is executing.
228
+ */
229
+ const builder = {
230
+ get config() {
231
+ return currentConfig;
232
+ },
233
+ sousDir: context.sousDir,
234
+ confDir: context.confDir,
235
+ get currentFile() {
236
+ return currentFile;
237
+ },
238
+ env(name, fallback) {
239
+ return process.env[name] ?? fallback;
240
+ },
241
+ merge(obj) {
242
+ mergeLayerObject(obj, currentFile ?? "<builder.merge>");
243
+ },
244
+ async loadConfig(p) {
245
+ await loadLayer(resolveBuilderPath(p, `loadConfig(${JSON.stringify(p)}) in ${currentFile}`));
246
+ },
247
+ async loadConfigs(globPattern) {
248
+ const where = `loadConfigs(${JSON.stringify(globPattern)}) in ${currentFile}`;
249
+ const pattern = resolveBuilderPath(globPattern, where);
250
+ const matches = globSync(pattern, { absolute: true })
251
+ .filter((p) => fs.statSync(p).isFile())
252
+ .sort(bytewiseCompare);
253
+ for (const match of matches) {
254
+ await loadLayer(match);
255
+ }
256
+ },
257
+ };
258
+
259
+ /**
260
+ * Loads ONE layer file (any extension) and merges it into the cumulative
261
+ * config. Builder sub-loads recurse here too, under the full layer contract
262
+ * (including nested configure), guarded by the loading-set cycle check.
263
+ */
264
+ async function loadLayer(filePath) {
265
+ const resolved = path.resolve(filePath);
266
+
267
+ if (loadingSet.has(resolved)) {
268
+ throw new Error(
269
+ `Config layer cycle detected: ${resolved} is already being loaded.\n` +
270
+ ` Load chain: ${[...loadingSet].join(" -> ")} -> ${resolved}`
271
+ );
272
+ }
273
+ if (!fs.existsSync(resolved)) {
274
+ throw new Error(`Config layer not found: ${resolved}`);
275
+ }
276
+
277
+ loadingSet.add(resolved);
278
+ const previousFile = currentFile;
279
+ currentFile = resolved;
280
+
281
+ try {
282
+ const ext = path.extname(resolved).toLowerCase();
283
+
284
+ if (ext === ".json") {
285
+ mergeLayerObject(JSON.parse(fs.readFileSync(resolved, "utf8")), resolved);
286
+ } else if (ext === ".jsonc") {
287
+ mergeLayerObject(parseJsoncLayer(fs.readFileSync(resolved, "utf8"), resolved), resolved);
288
+ } else if (ext === ".yaml") {
289
+ mergeLayerObject(parseYaml(fs.readFileSync(resolved, "utf8")), resolved);
290
+ } else if (ext === ".js" || ext === ".mjs") {
291
+ const mod = await import(pathToFileURL(resolved).href);
292
+
293
+ let configObject;
294
+ if (mod.config !== undefined) {
295
+ configObject = mod.config;
296
+ } else if (mod.default !== undefined && typeof mod.default !== "function") {
297
+ configObject = mod.default;
298
+ }
299
+
300
+ let configureFn;
301
+ if (typeof mod.configure === "function") {
302
+ configureFn = mod.configure;
303
+ } else if (typeof mod.default === "function") {
304
+ configureFn = mod.default;
305
+ }
306
+
307
+ if (configObject === undefined && configureFn === undefined) {
308
+ throw new Error(
309
+ `Config layer ${resolved} exports neither a config object ` +
310
+ `(\`config\` or a default object) nor a configure function ` +
311
+ `(\`configure\` or a default function).`
312
+ );
313
+ }
314
+
315
+ // When both exist, the object merges FIRST, then the function runs.
316
+ if (configObject !== undefined) {
317
+ mergeLayerObject(configObject, resolved);
318
+ }
319
+ if (configureFn !== undefined) {
320
+ const returned = await configureFn(currentConfig, builder);
321
+ // A configure() may mutate currentConfig by reference AND return it for
322
+ // chaining (`cfg.x = ...; return cfg;`, or `return builder.config`).
323
+ // Merging currentConfig back onto itself would deepMerge it with itself,
324
+ // concatenating (and so duplicating) every array. Only merge a returned
325
+ // value when it is a DISTINCT object.
326
+ if (returned !== undefined && returned !== null && returned !== currentConfig) {
327
+ mergeLayerObject(returned, resolved);
328
+ }
329
+ }
330
+ } else {
331
+ throw new Error(
332
+ `Config layer ${resolved} has an unsupported extension '${ext}'. ` +
333
+ `Supported: .js, .mjs, .json, .jsonc, .yaml`
334
+ );
335
+ }
336
+ } catch (error) {
337
+ // Make sure every failure names a layer file.
338
+ const message = error instanceof Error ? error.message : String(error);
339
+ if (message.includes(resolved)) throw error;
340
+ throw new Error(`Config layer ${resolved} failed to load: ${message}`);
341
+ } finally {
342
+ loadingSet.delete(resolved);
343
+ currentFile = previousFile;
344
+ }
345
+ }
346
+
347
+ for (const source of sources) {
348
+ // An inline source is a layer the PARENT already read and already filtered
349
+ // (a subscribed recipe's config layer; see repos/recipe-config-layers.ts).
350
+ // The kernel merges the content it was handed and never opens the file, so
351
+ // the filtering cannot be sidestepped by re-reading it here.
352
+ if (isPlainObject(source)) {
353
+ const previousFile = currentFile;
354
+ currentFile = source.path;
355
+ try {
356
+ mergeLayerObject(source.config, source.path);
357
+ } finally {
358
+ currentFile = previousFile;
359
+ }
360
+ } else {
361
+ await loadLayer(source);
362
+ }
363
+ if (trace) {
364
+ layers.push({
365
+ path: isPlainObject(source) ? source.path : source,
366
+ config: jsonRoundTrip(currentConfig),
367
+ });
368
+ }
369
+ }
370
+
371
+ process.stdout.write(JSON.stringify({ config: jsonRoundTrip(currentConfig), layers }));
372
+ }
373
+
374
+ main().catch((error) => {
375
+ process.stderr.write(error instanceof Error ? error.message : String(error));
376
+ process.exit(1);
377
+ });