farna-bootstrapper 0.0.0-stage → 0.1.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 (80) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/LICENSE +30 -0
  3. package/NOTICE +42 -0
  4. package/README.md +1079 -2
  5. package/SECURITY.md +65 -0
  6. package/dist/cli/commands/check.d.ts +58 -0
  7. package/dist/cli/commands/check.js +198 -0
  8. package/dist/cli/commands/generate.d.ts +75 -0
  9. package/dist/cli/commands/generate.js +218 -0
  10. package/dist/cli/commands/init.d.ts +52 -0
  11. package/dist/cli/commands/init.js +271 -0
  12. package/dist/cli/main.d.ts +2 -0
  13. package/dist/cli/main.js +51 -0
  14. package/dist/cli/program.d.ts +23 -0
  15. package/dist/cli/program.js +183 -0
  16. package/dist/compose/resolve.d.ts +154 -0
  17. package/dist/compose/resolve.js +545 -0
  18. package/dist/config/load.d.ts +4 -0
  19. package/dist/config/load.js +45 -0
  20. package/dist/config/schema.d.ts +22 -0
  21. package/dist/config/schema.js +46 -0
  22. package/dist/core/constants.d.ts +268 -0
  23. package/dist/core/constants.js +336 -0
  24. package/dist/core/errors.d.ts +44 -0
  25. package/dist/core/errors.js +75 -0
  26. package/dist/core/fs.d.ts +31 -0
  27. package/dist/core/fs.js +169 -0
  28. package/dist/core/json.d.ts +22 -0
  29. package/dist/core/json.js +174 -0
  30. package/dist/core/paths.d.ts +45 -0
  31. package/dist/core/paths.js +110 -0
  32. package/dist/core/text.d.ts +10 -0
  33. package/dist/core/text.js +27 -0
  34. package/dist/index.d.ts +10 -0
  35. package/dist/index.js +1 -0
  36. package/dist/lock/lockfile.d.ts +229 -0
  37. package/dist/lock/lockfile.js +333 -0
  38. package/dist/materialise/source-tree.d.ts +77 -0
  39. package/dist/materialise/source-tree.js +264 -0
  40. package/dist/permissions/permissions.d.ts +128 -0
  41. package/dist/permissions/permissions.js +452 -0
  42. package/dist/render/commit.d.ts +59 -0
  43. package/dist/render/commit.js +279 -0
  44. package/dist/render/generate-lock.d.ts +9 -0
  45. package/dist/render/generate-lock.js +203 -0
  46. package/dist/render/identity.d.ts +23 -0
  47. package/dist/render/identity.js +396 -0
  48. package/dist/render/orphans.d.ts +59 -0
  49. package/dist/render/orphans.js +234 -0
  50. package/dist/render/port.d.ts +96 -0
  51. package/dist/render/port.js +1 -0
  52. package/dist/render/prepare.d.ts +33 -0
  53. package/dist/render/prepare.js +139 -0
  54. package/dist/render/root-cleanliness.d.ts +28 -0
  55. package/dist/render/root-cleanliness.js +76 -0
  56. package/dist/render/stage.d.ts +36 -0
  57. package/dist/render/stage.js +92 -0
  58. package/dist/render/staging.d.ts +16 -0
  59. package/dist/render/staging.js +94 -0
  60. package/dist/render/structured.d.ts +35 -0
  61. package/dist/render/structured.js +258 -0
  62. package/dist/render/upstream.d.ts +41 -0
  63. package/dist/render/upstream.js +179 -0
  64. package/dist/report/format.d.ts +7 -0
  65. package/dist/report/format.js +97 -0
  66. package/dist/report/warnings.d.ts +21 -0
  67. package/dist/report/warnings.js +24 -0
  68. package/dist/source/digest.d.ts +18 -0
  69. package/dist/source/digest.js +77 -0
  70. package/dist/source/frontmatter.d.ts +12 -0
  71. package/dist/source/frontmatter.js +29 -0
  72. package/dist/source/load.d.ts +103 -0
  73. package/dist/source/load.js +676 -0
  74. package/dist/source/schema.d.ts +149 -0
  75. package/dist/source/schema.js +283 -0
  76. package/dist/source/yaml.d.ts +10 -0
  77. package/dist/source/yaml.js +49 -0
  78. package/dist/verify/containment.d.ts +22 -0
  79. package/dist/verify/containment.js +753 -0
  80. package/package.json +79 -4
@@ -0,0 +1,545 @@
1
+ import { CONFIG_PATH, isOpencodeTarget, MAX_EXTENDS_DEPTH, MODE_AGENT, MODE_PROFILE, OPENCODE_WORKSPACE_KINDS, PROFILE_FORCING_KINDS, PROFILE_TARGETS, SUPPORTED_RESOURCE_KINDS, SUPPORTED_TARGETS, targetSupportsProfile, } from '../core/constants.js';
2
+ import { conflict, invalidConfig } from '../core/errors.js';
3
+ import { canonicalJson, compareCodepoints, sha256Hex } from '../core/json.js';
4
+ import { emptyResolvedPermissions, mapOpencodePermissions, mapPermissions, mergePermission, permissionDigest, permissionResourceDigest, } from '../permissions/permissions.js';
5
+ import { sortWarnings, warning } from '../report/warnings.js';
6
+ /** The persona field a source-derived warning carries when no persona declared it. */
7
+ const SOURCE_WARNING_SUBJECT = '<source>';
8
+ const KIND_ORDER = {
9
+ rule: 0,
10
+ permission: 1,
11
+ model: 2,
12
+ mcp: 3,
13
+ skill: 4,
14
+ command: 5,
15
+ hook: 6,
16
+ };
17
+ function splitRef(ref) {
18
+ const separator = ref.indexOf('/');
19
+ return { kind: ref.slice(0, separator), id: ref.slice(separator + 1) };
20
+ }
21
+ /** The one configured target. The config schema admits exactly one. */
22
+ export function configuredTarget(config) {
23
+ const [id] = Object.keys(config.targets);
24
+ if (id === undefined || !SUPPORTED_TARGETS.includes(id)) {
25
+ throw invalidConfig('no supported target is configured', {
26
+ subject: '.farna/config.jsonc',
27
+ action: `configure exactly one of: ${SUPPORTED_TARGETS.join(', ')}`,
28
+ });
29
+ }
30
+ return id;
31
+ }
32
+ /**
33
+ * Resolve `extends` to the full chain, base first. Cycles, a missing base and a
34
+ * depth over the limit are all F001; the cycle message names the whole path.
35
+ */
36
+ function resolveChain(persona, byId) {
37
+ const chain = [];
38
+ const visiting = [];
39
+ let current = persona;
40
+ while (current !== undefined) {
41
+ const cycleAt = visiting.indexOf(current.id);
42
+ if (cycleAt !== -1) {
43
+ const path = [...visiting.slice(cycleAt), current.id].join(' -> ');
44
+ throw invalidConfig(`extends cycle: ${path}`, {
45
+ subject: current.path,
46
+ action: 'remove one edge so the composition chain has a base',
47
+ });
48
+ }
49
+ if (visiting.length >= MAX_EXTENDS_DEPTH) {
50
+ throw invalidConfig(`extends chain is deeper than ${MAX_EXTENDS_DEPTH}`, {
51
+ subject: persona.path,
52
+ });
53
+ }
54
+ visiting.push(current.id);
55
+ chain.unshift(current);
56
+ if (current.extends === undefined) {
57
+ break;
58
+ }
59
+ const base = byId.get(current.extends);
60
+ if (base === undefined) {
61
+ throw invalidConfig(`extends "${current.extends}" names no persona`, {
62
+ subject: current.path,
63
+ action: 'add the base persona under .farna/personas/',
64
+ });
65
+ }
66
+ current = base;
67
+ }
68
+ return chain;
69
+ }
70
+ function resolveModelClass(modelClass, subject, config, target) {
71
+ const mapping = config.models?.[modelClass];
72
+ if (mapping === undefined) {
73
+ throw invalidConfig(`model class "${modelClass}" is not declared in config.models`, {
74
+ subject,
75
+ });
76
+ }
77
+ const modelId = mapping[target];
78
+ if (modelId === undefined) {
79
+ throw invalidConfig(`model class "${modelClass}" has no "${target}" mapping`, {
80
+ subject,
81
+ });
82
+ }
83
+ return modelId;
84
+ }
85
+ /**
86
+ * The model is inherited from the base or set on the persona. Two different
87
+ * concrete models in one composed set is F005: composition never silently
88
+ * changes the model. Two classes that resolve to the same model id are one
89
+ * model and do not conflict.
90
+ */
91
+ function resolveModel(chain, config, target) {
92
+ const declared = chain
93
+ .filter((persona) => persona.model !== undefined)
94
+ .map((persona) => ({
95
+ persona,
96
+ modelClass: persona.model,
97
+ modelId: resolveModelClass(persona.model, persona.path, config, target),
98
+ }));
99
+ const distinct = [...new Set(declared.map((entry) => entry.modelId))];
100
+ if (distinct.length > 1) {
101
+ const [first, second] = declared;
102
+ throw conflict(`composed persona declares two different models: "${first.modelClass}" -> "${first.modelId}" and "${second.modelClass}" -> "${second.modelId}"`, {
103
+ subject: second.persona.path,
104
+ action: `the same model must be inherited or set once; ${first.persona.path} sets "${first.modelClass}"`,
105
+ });
106
+ }
107
+ return distinct[0];
108
+ }
109
+ function assertSupportedRef(persona, ref, target, mode) {
110
+ const { kind } = splitRef(ref);
111
+ if (kind === 'model') {
112
+ throw invalidConfig('model resources are expressed with the persona "model" key', {
113
+ subject: persona.path,
114
+ });
115
+ }
116
+ if (!SUPPORTED_RESOURCE_KINDS.includes(kind)) {
117
+ throw invalidConfig(`unknown resource kind "${kind}"`, {
118
+ subject: persona.path,
119
+ action: `a resource reference names one of: ${SUPPORTED_RESOURCE_KINDS.join(', ')}`,
120
+ });
121
+ }
122
+ if (target === 'claudecode' && OPENCODE_WORKSPACE_KINDS.includes(kind)) {
123
+ throw invalidConfig(`the ${kind} resource kind is not carried by claudecode in this slice`, {
124
+ subject: persona.path,
125
+ action: `render this source for the opencode target, or remove the ${kind} reference`,
126
+ });
127
+ }
128
+ // A workspace kind in agent mode has no per-recipient record, no opt-out and
129
+ // no honest warning: a workspace emission would give every persona the
130
+ // declarer's resource. Profile mode is the only mode that carries it, and its
131
+ // absence is a refusal, never a silent workspace-wide emission.
132
+ if (mode === MODE_AGENT &&
133
+ isOpencodeTarget(target) &&
134
+ OPENCODE_WORKSPACE_KINDS.includes(kind)) {
135
+ const { id } = splitRef(ref);
136
+ throw invalidConfig(`${kind}/${id} is declared by persona ${persona.id} and requires profile mode`, {
137
+ subject: persona.path,
138
+ action: `set targets.${target}.active to this persona (or pass --persona <id>) to run profile mode, or remove the reference`,
139
+ });
140
+ }
141
+ }
142
+ function addResource(resources, resource) {
143
+ const key = `${resource.kind}/${resource.id}`;
144
+ const existing = resources.get(key);
145
+ if (existing === undefined) {
146
+ resources.set(key, resource);
147
+ return;
148
+ }
149
+ if (existing.sha256 !== resource.sha256) {
150
+ throw conflict(`two sources disagree on ${key}`, {
151
+ subject: existing.path,
152
+ action: `the same (kind, id) is also declared in ${resource.path}; their content differs`,
153
+ });
154
+ }
155
+ // Identical content is deduplicated and attributed to the most derived persona.
156
+ resources.set(key, resource);
157
+ }
158
+ /** Sorted canonically: resource-kind order, then codepoint id. */
159
+ function sortResources(resources) {
160
+ return [...resources].sort((a, b) => {
161
+ const byKind = (KIND_ORDER[a.kind] ?? 99) - (KIND_ORDER[b.kind] ?? 99);
162
+ return byKind === 0 ? compareCodepoints(a.id, b.id) : byKind;
163
+ });
164
+ }
165
+ /**
166
+ * Why OpenCode cannot carry this hook, or `undefined` when it can. Measured at
167
+ * rulesync 43.11.0: `session-end` has no OpenCode event, and a matcher is
168
+ * honoured only on the tool events (`preToolUse`/`postToolUse`).
169
+ */
170
+ function hookProblem(hook) {
171
+ if (hook.phase === 'session-end') {
172
+ return 'OpenCode has no session-end event';
173
+ }
174
+ if (hook.matcher !== undefined && hook.phase !== 'before-tool' && hook.phase !== 'after-tool') {
175
+ return `OpenCode honours a matcher on tool events only, not on ${hook.phase}`;
176
+ }
177
+ return undefined;
178
+ }
179
+ function resolveOne(persona, chain, byKind, config, target, mode) {
180
+ const model = resolveModel(chain, config, target);
181
+ const resources = new Map();
182
+ const permissions = emptyResolvedPermissions();
183
+ const warnings = [];
184
+ const seenRefs = new Set();
185
+ const missing = (kind, id, contributor) => {
186
+ const dirs = {
187
+ rule: 'rules',
188
+ permission: 'permissions',
189
+ mcp: 'mcp',
190
+ skill: 'skills',
191
+ command: 'commands',
192
+ hook: 'hooks',
193
+ };
194
+ throw invalidConfig(`unknown ${kind} "${id}"`, {
195
+ subject: contributor.path,
196
+ action: `add the resource under .farna/resources/${dirs[kind] ?? kind}/`,
197
+ });
198
+ };
199
+ for (const contributor of chain) {
200
+ for (const ref of contributor.resources) {
201
+ assertSupportedRef(contributor, ref, target, mode);
202
+ const { kind, id } = splitRef(ref);
203
+ const key = `${kind}/${id}`;
204
+ const repeated = seenRefs.has(key);
205
+ seenRefs.add(key);
206
+ if (kind === 'rule') {
207
+ const rule = byKind.rules.get(id) ?? missing('rule', id, contributor);
208
+ addResource(resources, {
209
+ kind: 'rule',
210
+ id: rule.id,
211
+ displayName: rule.displayName,
212
+ body: rule.body,
213
+ sha256: sha256Hex(rule.body),
214
+ path: rule.path,
215
+ fromPersona: contributor.id,
216
+ });
217
+ continue;
218
+ }
219
+ if (kind === 'permission') {
220
+ const permission = byKind.permissions.get(id) ?? missing('permission', id, contributor);
221
+ if (permission.allowlist === true && isOpencodeTarget(target)) {
222
+ throw invalidConfig('a permission resource opts into a tool allow-list, which OpenCode cannot express', {
223
+ subject: permission.path,
224
+ action: `remove "allowlist" or render this persona for claudecode; OpenCode's permission records are a deny-list`,
225
+ });
226
+ }
227
+ addResource(resources, {
228
+ kind: 'permission',
229
+ id: permission.id,
230
+ sha256: permissionResourceDigest(permission.tools, permission.patterns, permission.allowlist),
231
+ path: permission.path,
232
+ fromPersona: contributor.id,
233
+ });
234
+ if (!repeated) {
235
+ const contribution = {
236
+ id: permission.id,
237
+ tools: permission.tools,
238
+ patterns: permission.patterns ?? {},
239
+ allowlist: permission.allowlist,
240
+ };
241
+ mergePermission(permissions, contribution, {
242
+ persona: persona.id,
243
+ target,
244
+ warnings,
245
+ });
246
+ }
247
+ continue;
248
+ }
249
+ if (kind === 'mcp') {
250
+ const server = byKind.mcp.get(id) ?? missing('mcp', id, contributor);
251
+ addResource(resources, {
252
+ kind: 'mcp',
253
+ id: server.id,
254
+ server: server.server,
255
+ sha256: server.sha256,
256
+ path: server.path,
257
+ fromPersona: contributor.id,
258
+ });
259
+ continue;
260
+ }
261
+ if (kind === 'skill') {
262
+ const skill = byKind.skills.get(id) ?? missing('skill', id, contributor);
263
+ addResource(resources, {
264
+ kind: 'skill',
265
+ id: skill.id,
266
+ description: skill.description,
267
+ body: skill.body,
268
+ files: skill.files,
269
+ sha256: skill.sha256,
270
+ path: skill.path,
271
+ fromPersona: contributor.id,
272
+ });
273
+ continue;
274
+ }
275
+ if (kind === 'command') {
276
+ const command = byKind.commands.get(id) ?? missing('command', id, contributor);
277
+ addResource(resources, {
278
+ kind: 'command',
279
+ id: command.id,
280
+ ...(command.description === undefined ? {} : { description: command.description }),
281
+ body: command.body,
282
+ sha256: command.sha256,
283
+ path: command.path,
284
+ fromPersona: contributor.id,
285
+ });
286
+ continue;
287
+ }
288
+ const hook = byKind.hooks.get(id) ?? missing('hook', id, contributor);
289
+ addResource(resources, {
290
+ kind: 'hook',
291
+ id: hook.id,
292
+ phase: hook.phase,
293
+ ...(hook.matcher === undefined ? {} : { matcher: hook.matcher }),
294
+ command: hook.command,
295
+ sha256: hook.sha256,
296
+ path: hook.path,
297
+ fromPersona: contributor.id,
298
+ });
299
+ }
300
+ }
301
+ const sortedResources = sortResources([...resources.values()]);
302
+ const resolvedRules = sortedResources.filter((resource) => resource.kind === 'rule');
303
+ const resolvedMcp = sortedResources.filter((resource) => resource.kind === 'mcp');
304
+ const resolvedSkills = sortedResources.filter((resource) => resource.kind === 'skill');
305
+ const resolvedCommands = sortedResources.filter((resource) => resource.kind === 'command');
306
+ const resolvedHooks = sortedResources
307
+ .filter((resource) => resource.kind === 'hook')
308
+ .map((hook) => {
309
+ const reason = hookProblem(hook);
310
+ return reason === undefined
311
+ ? { ...hook, carried: true }
312
+ : { ...hook, carried: false, reason };
313
+ });
314
+ // A hook the target cannot represent is a real loss, never a silent omission.
315
+ // `hook` is a boundary capability, so the loss is HIGH. This is reachable only
316
+ // in profile mode: agent mode refuses a hook reference before attribution.
317
+ for (const hook of resolvedHooks) {
318
+ if (hook.carried) {
319
+ continue;
320
+ }
321
+ warnings.push(warning({
322
+ code: 'W101_CAPABILITY_DROPPED',
323
+ persona: persona.id,
324
+ target,
325
+ capability: 'hook',
326
+ severity: 'high',
327
+ message: `hook "${hook.id}" is not carried by ${target}: ${hook.reason ?? 'no matching event'}`,
328
+ }));
329
+ }
330
+ const mapped = target === 'claudecode'
331
+ ? mapPermissions(permissions, { persona: persona.id, target })
332
+ : undefined;
333
+ const mappedOpencode = isOpencodeTarget(target)
334
+ ? mapOpencodePermissions(permissions, { persona: persona.id, target })
335
+ : undefined;
336
+ if (mapped !== undefined) {
337
+ warnings.push(...mapped.warnings);
338
+ }
339
+ if (mappedOpencode !== undefined) {
340
+ warnings.push(...mappedOpencode.warnings);
341
+ }
342
+ const digest = sha256Hex(canonicalJson(sortedResources.map((resource) => ({
343
+ kind: resource.kind,
344
+ id: resource.id,
345
+ sha256: resource.sha256,
346
+ fromPersona: resource.fromPersona,
347
+ }))));
348
+ return {
349
+ id: persona.id,
350
+ displayName: persona.displayName,
351
+ purpose: persona.purpose,
352
+ ...(persona.extends === undefined ? {} : { extends: persona.extends }),
353
+ chain: chain.map((entry) => entry.id),
354
+ rules: resolvedRules,
355
+ mcp: resolvedMcp,
356
+ skills: resolvedSkills,
357
+ commands: resolvedCommands,
358
+ hooks: resolvedHooks,
359
+ resources: sortedResources,
360
+ permissions,
361
+ claude: {
362
+ allow: mapped?.entries.allow ?? [],
363
+ deny: mapped?.entries.deny ?? [],
364
+ allowlist: mapped?.allowlist ?? false,
365
+ },
366
+ opencode: {
367
+ permission: mappedOpencode?.source ?? [],
368
+ records: mappedOpencode?.records ?? [],
369
+ },
370
+ ...(model === undefined ? {} : { model }),
371
+ path: persona.path,
372
+ digest,
373
+ permissionDigest: permissionDigest(permissions, mapped?.allowlist ?? false),
374
+ warnings: sortWarnings(warnings),
375
+ };
376
+ }
377
+ function unionAcrossPersonas(kind, personas, select) {
378
+ const byId = new Map();
379
+ for (const persona of personas) {
380
+ for (const resource of select(persona)) {
381
+ const existing = byId.get(resource.id);
382
+ if (existing === undefined) {
383
+ byId.set(resource.id, resource);
384
+ continue;
385
+ }
386
+ if (existing.sha256 !== resource.sha256) {
387
+ throw conflict(`two personas disagree on ${kind}/${resource.id}`, {
388
+ subject: resource.id,
389
+ });
390
+ }
391
+ }
392
+ }
393
+ return [...byId.values()].sort((a, b) => compareCodepoints(a.id, b.id));
394
+ }
395
+ /**
396
+ * Resolve every persona's composition chain into its resource set. The base
397
+ * persona's rules, permissions and workspace resources are unioned in; the
398
+ * stricter permission value wins; two different models are a conflict, never a
399
+ * silent override.
400
+ *
401
+ * The target's mode is computed here, never chosen by a heuristic:
402
+ *
403
+ * - `targets.<target>.active` (or the `--persona` override) selects profile
404
+ * mode, makes exactly that persona live, and refuses F001 when the persona or
405
+ * the target's profile support is missing;
406
+ * - otherwise the target is in agent mode and every persona is live.
407
+ *
408
+ * In profile mode only the live persona's artefacts and workspace resources are
409
+ * returned, so `materialise` and the containment gate cannot emit or accept
410
+ * another persona's resources: the isolation is structural, not a filter applied
411
+ * later. Every persona is still resolved, so a broken declaration anywhere in
412
+ * the source is reported; only emission is scoped to the live persona.
413
+ */
414
+ export function resolveSource(source, config, selection = {}) {
415
+ const target = configuredTarget(config);
416
+ const configuredActive = config.targets[target]?.active;
417
+ const requested = selection.persona ?? configuredActive;
418
+ const mode = requested === undefined ? MODE_AGENT : MODE_PROFILE;
419
+ const active = requested ?? null;
420
+ // The subject names the thing the user must edit: the flag they passed, or
421
+ // the config field that selected the persona.
422
+ const selectionSubject = selection.persona !== undefined ? '--persona' : CONFIG_PATH;
423
+ const sourceWarnings = source.warnings.map((entry) => warning({
424
+ code: entry.code,
425
+ persona: SOURCE_WARNING_SUBJECT,
426
+ target,
427
+ ...(entry.capability === undefined ? {} : { capability: entry.capability }),
428
+ message: entry.message,
429
+ }));
430
+ const byId = new Map(source.personas.map((persona) => [persona.id, persona]));
431
+ // The committed selection is validated even when `--persona` overrides it: a
432
+ // `targets.<target>.active` that names no persona is a broken config, and the
433
+ // flag must not mask it. The user commits this value; a run that ignores it
434
+ // leaves the next run (without the flag) broken with no warning here.
435
+ if (configuredActive !== undefined && !byId.has(configuredActive)) {
436
+ throw invalidConfig(`targets.${target}.active "${configuredActive}" names no persona`, {
437
+ subject: CONFIG_PATH,
438
+ action: 'declare the persona under .farna/personas/, or remove the active key',
439
+ });
440
+ }
441
+ if (active !== null) {
442
+ if (!targetSupportsProfile(target)) {
443
+ throw invalidConfig(`the ${target} target does not support profile mode`, {
444
+ subject: selectionSubject,
445
+ action: `remove the active persona for ${target}; profile mode is supported for: ${PROFILE_TARGETS.join(', ')}`,
446
+ });
447
+ }
448
+ if (!byId.has(active)) {
449
+ throw invalidConfig(`active persona "${active}" names no persona`, {
450
+ subject: selectionSubject,
451
+ action: 'declare the persona under .farna/personas/, or choose one that exists',
452
+ });
453
+ }
454
+ }
455
+ const byKind = {
456
+ rules: new Map(source.rules.map((rule) => [rule.id, rule])),
457
+ permissions: new Map(source.permissions.map((permission) => [permission.id, permission])),
458
+ mcp: new Map(source.mcp.map((server) => [server.id, server])),
459
+ skills: new Map(source.skills.map((skill) => [skill.id, skill])),
460
+ commands: new Map(source.commands.map((command) => [command.id, command])),
461
+ hooks: new Map(source.hooks.map((hook) => [hook.id, hook])),
462
+ };
463
+ const resolved = source.personas.map((persona) => resolveOne(persona, resolveChain(persona, byId), byKind, config, target, mode));
464
+ const notLive = active === null
465
+ ? []
466
+ : resolved
467
+ .map((persona) => persona.id)
468
+ .filter((id) => id !== active)
469
+ .sort(compareCodepoints);
470
+ // Profile mode is forced only when the **live** persona declares a boundary
471
+ // capability the target carries at the workspace level and nowhere else.
472
+ // An inactive persona's `mcp` or `hook` does not force the mode: it is not
473
+ // emitted, so warning that the selection was forced would blame a declaration
474
+ // that is not in the profile. Otherwise the selection is a choice, and every
475
+ // other persona is silently not live unless the run says so: that is W109, at
476
+ // info severity.
477
+ const forcingScope = active === null ? resolved : resolved.filter((p) => p.id === active);
478
+ const forced = forcingScope.some((persona) => persona.resources.some((resource) => PROFILE_FORCING_KINDS.includes(resource.kind)));
479
+ // The message describes the resolved state, not the invocation: the same
480
+ // source and config must produce the same lockfile whether the persona came
481
+ // from `active` or from `--persona`, or `check` would report drift for an
482
+ // identical selection.
483
+ const profileWarnings = mode === MODE_PROFILE && !forced
484
+ ? [
485
+ warning({
486
+ code: 'W109_PROFILE_BY_CHOICE',
487
+ persona: active ?? SOURCE_WARNING_SUBJECT,
488
+ target,
489
+ message: `profile mode is active for ${target}${active === null ? '' : ` as ${active}`}, but ${active === null ? 'no persona' : 'the live persona'} declares no capability that requires it; agent mode is the default${notLive.length === 0
490
+ ? ''
491
+ : `, and ${notLive.join(', ')} ${notLive.length === 1 ? 'is' : 'are'} not live`}`,
492
+ }),
493
+ ]
494
+ : [];
495
+ const personas = active === null ? resolved : resolved.filter((persona) => persona.id === active);
496
+ if (active === null) {
497
+ return {
498
+ target,
499
+ mode,
500
+ active,
501
+ notLive,
502
+ personas,
503
+ mcp: unionAcrossPersonas('mcp', personas, (persona) => persona.mcp),
504
+ skills: unionAcrossPersonas('skill', personas, (persona) => persona.skills),
505
+ commands: unionAcrossPersonas('command', personas, (persona) => persona.commands),
506
+ hooks: unionAcrossPersonas('hook', personas, (persona) => persona.hooks),
507
+ warnings: sortWarnings([
508
+ ...sourceWarnings,
509
+ ...personas.flatMap((persona) => persona.warnings),
510
+ ]),
511
+ };
512
+ }
513
+ const live = personas[0];
514
+ if (personas.length !== 1 || live === undefined) {
515
+ // Defensive: `active` was proven to name a persona above. Reaching here
516
+ // means the source changed under the resolver, which must never be guessed.
517
+ throw invalidConfig(`active persona "${active}" did not resolve to exactly one live persona`, {
518
+ subject: selectionSubject,
519
+ });
520
+ }
521
+ return {
522
+ target,
523
+ mode,
524
+ active,
525
+ notLive,
526
+ personas,
527
+ // Profile mode: the live persona's own resources, never a union across the
528
+ // personas that are not live. Anything else would leak a resource the
529
+ // workspace owner never declared.
530
+ mcp: live.mcp,
531
+ skills: live.skills,
532
+ commands: live.commands,
533
+ hooks: live.hooks,
534
+ // Every resolved persona's source-derived warnings, not only the live
535
+ // persona's: a warning carries its own `persona` and describes a
536
+ // declaration that was validated, so dropping a non-live persona's W101 or
537
+ // W112 would hide a real loss from the run that resolved it. The lockfile
538
+ // records the same set, scoped by persona.
539
+ warnings: sortWarnings([
540
+ ...sourceWarnings,
541
+ ...resolved.flatMap((persona) => persona.warnings),
542
+ ...profileWarnings,
543
+ ]),
544
+ };
545
+ }
@@ -0,0 +1,4 @@
1
+ import { type Config } from './schema.js';
2
+ export declare function configPath(repoRoot: string): string;
3
+ /** Read and strictly validate `.farna/config.jsonc`. Never returns a partial config. */
4
+ export declare function loadConfig(repoRoot: string): Promise<Config>;
@@ -0,0 +1,45 @@
1
+ import { join } from 'node:path';
2
+ import { ZodError } from 'zod';
3
+ import { CONFIG_FILE, CONFIG_PATH, ROOT_DIR } from '../core/constants.js';
4
+ import { invalidConfig } from '../core/errors.js';
5
+ import { readUtf8File } from '../core/fs.js';
6
+ import { parseJsonc } from '../core/json.js';
7
+ import { assertRealDirectory, assertRealFile } from '../core/paths.js';
8
+ import { configSchema } from './schema.js';
9
+ export function configPath(repoRoot) {
10
+ return join(repoRoot, ROOT_DIR, CONFIG_FILE);
11
+ }
12
+ function describeZodError(error) {
13
+ const issue = error.issues[0];
14
+ if (issue === undefined) {
15
+ return { message: 'config did not validate' };
16
+ }
17
+ const pointer = issue.path.join('.');
18
+ return {
19
+ message: issue.message,
20
+ ...(pointer === '' ? {} : { pointer }),
21
+ };
22
+ }
23
+ /** Read and strictly validate `.farna/config.jsonc`. Never returns a partial config. */
24
+ export async function loadConfig(repoRoot) {
25
+ const path = configPath(repoRoot);
26
+ const relative = CONFIG_PATH;
27
+ await assertRealDirectory(join(repoRoot, ROOT_DIR), ROOT_DIR);
28
+ await assertRealFile(path, relative);
29
+ const text = await readUtf8File(path, relative, {
30
+ action: 'run "farna-bootstrapper init" first',
31
+ });
32
+ const parsed = parseJsonc(text, { subject: relative });
33
+ try {
34
+ return configSchema.parse(parsed);
35
+ }
36
+ catch (error) {
37
+ if (error instanceof ZodError) {
38
+ const described = describeZodError(error);
39
+ throw invalidConfig(described.message, {
40
+ subject: described.pointer === undefined ? relative : `${relative}:${described.pointer}`,
41
+ });
42
+ }
43
+ throw error;
44
+ }
45
+ }
@@ -0,0 +1,22 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * One configured target. `active` selects profile mode: exactly that persona is
4
+ * live and owns the workspace. Its existence is checked against the loaded
5
+ * source tree (F001) because the config loader does not read personas; the
6
+ * per-target filter field `exclude` is not implemented, so it is rejected rather
7
+ * than accepted and ignored.
8
+ */
9
+ declare const targetConfigSchema: z.ZodObject<{
10
+ active: z.ZodOptional<z.ZodString>;
11
+ }, z.core.$strict>;
12
+ export declare const configSchema: z.ZodObject<{
13
+ $schema: z.ZodOptional<z.ZodString>;
14
+ schemaVersion: z.ZodLiteral<1>;
15
+ targets: z.ZodRecord<z.ZodString, z.ZodObject<{
16
+ active: z.ZodOptional<z.ZodString>;
17
+ }, z.core.$strict>>;
18
+ models: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodString>>>;
19
+ }, z.core.$strict>;
20
+ export type Config = z.infer<typeof configSchema>;
21
+ export type TargetConfig = z.infer<typeof targetConfigSchema>;
22
+ export {};
@@ -0,0 +1,46 @@
1
+ import { z } from 'zod';
2
+ import { ID_RE, SCHEMA_VERSION, SUPPORTED_TARGETS } from '../core/constants.js';
3
+ /**
4
+ * One configured target. `active` selects profile mode: exactly that persona is
5
+ * live and owns the workspace. Its existence is checked against the loaded
6
+ * source tree (F001) because the config loader does not read personas; the
7
+ * per-target filter field `exclude` is not implemented, so it is rejected rather
8
+ * than accepted and ignored.
9
+ */
10
+ const targetConfigSchema = z.strictObject({
11
+ active: z.string().regex(ID_RE, 'a persona id uses lower-case kebab-case').optional(),
12
+ });
13
+ export const configSchema = z
14
+ .strictObject({
15
+ $schema: z.string().optional(),
16
+ schemaVersion: z.literal(SCHEMA_VERSION),
17
+ targets: z
18
+ .record(z.string(), targetConfigSchema)
19
+ .refine((targets) => Object.keys(targets).length >= 1, 'at least one target is required')
20
+ .refine((targets) => Object.keys(targets).length <= 8, 'at most eight targets are allowed')
21
+ .refine((targets) => Object.keys(targets).every((id) => SUPPORTED_TARGETS.includes(id)), `this slice supports only: ${SUPPORTED_TARGETS.join(', ')}`)
22
+ .refine((targets) => Object.keys(targets).length === 1, `this slice renders exactly one configured target per run; choose one of: ${SUPPORTED_TARGETS.join(', ')} — configuring both opencode and opencodev1 in one run is refused`),
23
+ models: z.record(z.string(), z.record(z.string(), z.string().min(1))).optional(),
24
+ })
25
+ .superRefine((config, ctx) => {
26
+ for (const modelClass of Object.keys(config.models ?? {})) {
27
+ if (!ID_RE.test(modelClass)) {
28
+ ctx.addIssue({
29
+ code: 'custom',
30
+ path: ['models', modelClass],
31
+ message: 'model class names use lower-case kebab-case',
32
+ });
33
+ }
34
+ }
35
+ for (const [modelClass, mapping] of Object.entries(config.models ?? {})) {
36
+ for (const target of Object.keys(mapping)) {
37
+ if (!(target in config.targets)) {
38
+ ctx.addIssue({
39
+ code: 'custom',
40
+ path: ['models', modelClass, target],
41
+ message: `target "${target}" is not configured`,
42
+ });
43
+ }
44
+ }
45
+ }
46
+ });