farna-bootstrapper 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/LICENSE +30 -0
  3. package/NOTICE +42 -0
  4. package/README.md +1102 -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 +161 -0
  17. package/dist/compose/resolve.js +576 -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 +279 -0
  23. package/dist/core/constants.js +351 -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 +230 -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 +267 -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 +154 -0
  75. package/dist/source/schema.js +292 -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,576 @@
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
+ /**
110
+ * The mode a composed persona declares. A mode is inherited from the base and
111
+ * overridden by the most derived persona that declares one; a chain with no
112
+ * declaration returns `undefined`, which is the target's default. Unlike the
113
+ * model there is no conflict: the child is the more specific declaration, so
114
+ * overriding is the intended composition.
115
+ */
116
+ function resolveMode(chain) {
117
+ for (let index = chain.length - 1; index >= 0; index -= 1) {
118
+ const declared = chain[index]?.mode;
119
+ if (declared !== undefined) {
120
+ return declared;
121
+ }
122
+ }
123
+ return undefined;
124
+ }
125
+ function assertSupportedRef(persona, ref, target, mode) {
126
+ const { kind } = splitRef(ref);
127
+ if (kind === 'model') {
128
+ throw invalidConfig('model resources are expressed with the persona "model" key', {
129
+ subject: persona.path,
130
+ });
131
+ }
132
+ if (!SUPPORTED_RESOURCE_KINDS.includes(kind)) {
133
+ throw invalidConfig(`unknown resource kind "${kind}"`, {
134
+ subject: persona.path,
135
+ action: `a resource reference names one of: ${SUPPORTED_RESOURCE_KINDS.join(', ')}`,
136
+ });
137
+ }
138
+ if (target === 'claudecode' && OPENCODE_WORKSPACE_KINDS.includes(kind)) {
139
+ throw invalidConfig(`the ${kind} resource kind is not carried by claudecode in this slice`, {
140
+ subject: persona.path,
141
+ action: `render this source for the opencode target, or remove the ${kind} reference`,
142
+ });
143
+ }
144
+ // A workspace kind in agent mode has no per-recipient record, no opt-out and
145
+ // no honest warning: a workspace emission would give every persona the
146
+ // declarer's resource. Profile mode is the only mode that carries it, and its
147
+ // absence is a refusal, never a silent workspace-wide emission.
148
+ if (mode === MODE_AGENT &&
149
+ isOpencodeTarget(target) &&
150
+ OPENCODE_WORKSPACE_KINDS.includes(kind)) {
151
+ const { id } = splitRef(ref);
152
+ throw invalidConfig(`${kind}/${id} is declared by persona ${persona.id} and requires profile mode`, {
153
+ subject: persona.path,
154
+ action: `set targets.${target}.active to this persona (or pass --persona <id>) to run profile mode, or remove the reference`,
155
+ });
156
+ }
157
+ }
158
+ function addResource(resources, resource) {
159
+ const key = `${resource.kind}/${resource.id}`;
160
+ const existing = resources.get(key);
161
+ if (existing === undefined) {
162
+ resources.set(key, resource);
163
+ return;
164
+ }
165
+ if (existing.sha256 !== resource.sha256) {
166
+ throw conflict(`two sources disagree on ${key}`, {
167
+ subject: existing.path,
168
+ action: `the same (kind, id) is also declared in ${resource.path}; their content differs`,
169
+ });
170
+ }
171
+ // Identical content is deduplicated and attributed to the most derived persona.
172
+ resources.set(key, resource);
173
+ }
174
+ /** Sorted canonically: resource-kind order, then codepoint id. */
175
+ function sortResources(resources) {
176
+ return [...resources].sort((a, b) => {
177
+ const byKind = (KIND_ORDER[a.kind] ?? 99) - (KIND_ORDER[b.kind] ?? 99);
178
+ return byKind === 0 ? compareCodepoints(a.id, b.id) : byKind;
179
+ });
180
+ }
181
+ /**
182
+ * Why OpenCode cannot carry this hook, or `undefined` when it can. Measured at
183
+ * rulesync 43.11.0: `session-end` has no OpenCode event, and a matcher is
184
+ * honoured only on the tool events (`preToolUse`/`postToolUse`).
185
+ */
186
+ function hookProblem(hook) {
187
+ if (hook.phase === 'session-end') {
188
+ return 'OpenCode has no session-end event';
189
+ }
190
+ if (hook.matcher !== undefined && hook.phase !== 'before-tool' && hook.phase !== 'after-tool') {
191
+ return `OpenCode honours a matcher on tool events only, not on ${hook.phase}`;
192
+ }
193
+ return undefined;
194
+ }
195
+ function resolveOne(persona, chain, byKind, config, target, mode) {
196
+ const model = resolveModel(chain, config, target);
197
+ const personaMode = resolveMode(chain);
198
+ const resources = new Map();
199
+ const permissions = emptyResolvedPermissions();
200
+ const warnings = [];
201
+ const seenRefs = new Set();
202
+ // Claude Code models one agent per file and has no primary/subagent axis, so
203
+ // a declared mode has no representation there. The declaration is still
204
+ // valid; dropping it silently would hide that the source asked for something
205
+ // the target cannot do. The warning names both the persona and the target,
206
+ // and the emitted file carries no `mode` key at all.
207
+ if (target === 'claudecode' && personaMode !== undefined) {
208
+ warnings.push(warning({
209
+ code: 'W117_PERSONA_MODE_IGNORED',
210
+ persona: persona.id,
211
+ target,
212
+ message: `persona "${persona.id}" declares mode "${personaMode}", which claudecode cannot carry: Claude Code has no primary/subagent mode, so no mode key is written`,
213
+ }));
214
+ }
215
+ const missing = (kind, id, contributor) => {
216
+ const dirs = {
217
+ rule: 'rules',
218
+ permission: 'permissions',
219
+ mcp: 'mcp',
220
+ skill: 'skills',
221
+ command: 'commands',
222
+ hook: 'hooks',
223
+ };
224
+ throw invalidConfig(`unknown ${kind} "${id}"`, {
225
+ subject: contributor.path,
226
+ action: `add the resource under .farna/resources/${dirs[kind] ?? kind}/`,
227
+ });
228
+ };
229
+ for (const contributor of chain) {
230
+ for (const ref of contributor.resources) {
231
+ assertSupportedRef(contributor, ref, target, mode);
232
+ const { kind, id } = splitRef(ref);
233
+ const key = `${kind}/${id}`;
234
+ const repeated = seenRefs.has(key);
235
+ seenRefs.add(key);
236
+ if (kind === 'rule') {
237
+ const rule = byKind.rules.get(id) ?? missing('rule', id, contributor);
238
+ addResource(resources, {
239
+ kind: 'rule',
240
+ id: rule.id,
241
+ displayName: rule.displayName,
242
+ body: rule.body,
243
+ sha256: sha256Hex(rule.body),
244
+ path: rule.path,
245
+ fromPersona: contributor.id,
246
+ });
247
+ continue;
248
+ }
249
+ if (kind === 'permission') {
250
+ const permission = byKind.permissions.get(id) ?? missing('permission', id, contributor);
251
+ if (permission.allowlist === true && isOpencodeTarget(target)) {
252
+ throw invalidConfig('a permission resource opts into a tool allow-list, which OpenCode cannot express', {
253
+ subject: permission.path,
254
+ action: `remove "allowlist" or render this persona for claudecode; OpenCode's permission records are a deny-list`,
255
+ });
256
+ }
257
+ addResource(resources, {
258
+ kind: 'permission',
259
+ id: permission.id,
260
+ sha256: permissionResourceDigest(permission.tools, permission.patterns, permission.allowlist),
261
+ path: permission.path,
262
+ fromPersona: contributor.id,
263
+ });
264
+ if (!repeated) {
265
+ const contribution = {
266
+ id: permission.id,
267
+ tools: permission.tools,
268
+ patterns: permission.patterns ?? {},
269
+ allowlist: permission.allowlist,
270
+ };
271
+ mergePermission(permissions, contribution, {
272
+ persona: persona.id,
273
+ target,
274
+ warnings,
275
+ });
276
+ }
277
+ continue;
278
+ }
279
+ if (kind === 'mcp') {
280
+ const server = byKind.mcp.get(id) ?? missing('mcp', id, contributor);
281
+ addResource(resources, {
282
+ kind: 'mcp',
283
+ id: server.id,
284
+ server: server.server,
285
+ sha256: server.sha256,
286
+ path: server.path,
287
+ fromPersona: contributor.id,
288
+ });
289
+ continue;
290
+ }
291
+ if (kind === 'skill') {
292
+ const skill = byKind.skills.get(id) ?? missing('skill', id, contributor);
293
+ addResource(resources, {
294
+ kind: 'skill',
295
+ id: skill.id,
296
+ description: skill.description,
297
+ body: skill.body,
298
+ files: skill.files,
299
+ sha256: skill.sha256,
300
+ path: skill.path,
301
+ fromPersona: contributor.id,
302
+ });
303
+ continue;
304
+ }
305
+ if (kind === 'command') {
306
+ const command = byKind.commands.get(id) ?? missing('command', id, contributor);
307
+ addResource(resources, {
308
+ kind: 'command',
309
+ id: command.id,
310
+ ...(command.description === undefined ? {} : { description: command.description }),
311
+ body: command.body,
312
+ sha256: command.sha256,
313
+ path: command.path,
314
+ fromPersona: contributor.id,
315
+ });
316
+ continue;
317
+ }
318
+ const hook = byKind.hooks.get(id) ?? missing('hook', id, contributor);
319
+ addResource(resources, {
320
+ kind: 'hook',
321
+ id: hook.id,
322
+ phase: hook.phase,
323
+ ...(hook.matcher === undefined ? {} : { matcher: hook.matcher }),
324
+ command: hook.command,
325
+ sha256: hook.sha256,
326
+ path: hook.path,
327
+ fromPersona: contributor.id,
328
+ });
329
+ }
330
+ }
331
+ const sortedResources = sortResources([...resources.values()]);
332
+ const resolvedRules = sortedResources.filter((resource) => resource.kind === 'rule');
333
+ const resolvedMcp = sortedResources.filter((resource) => resource.kind === 'mcp');
334
+ const resolvedSkills = sortedResources.filter((resource) => resource.kind === 'skill');
335
+ const resolvedCommands = sortedResources.filter((resource) => resource.kind === 'command');
336
+ const resolvedHooks = sortedResources
337
+ .filter((resource) => resource.kind === 'hook')
338
+ .map((hook) => {
339
+ const reason = hookProblem(hook);
340
+ return reason === undefined
341
+ ? { ...hook, carried: true }
342
+ : { ...hook, carried: false, reason };
343
+ });
344
+ // A hook the target cannot represent is a real loss, never a silent omission.
345
+ // `hook` is a boundary capability, so the loss is HIGH. This is reachable only
346
+ // in profile mode: agent mode refuses a hook reference before attribution.
347
+ for (const hook of resolvedHooks) {
348
+ if (hook.carried) {
349
+ continue;
350
+ }
351
+ warnings.push(warning({
352
+ code: 'W101_CAPABILITY_DROPPED',
353
+ persona: persona.id,
354
+ target,
355
+ capability: 'hook',
356
+ severity: 'high',
357
+ message: `hook "${hook.id}" is not carried by ${target}: ${hook.reason ?? 'no matching event'}`,
358
+ }));
359
+ }
360
+ const mapped = target === 'claudecode'
361
+ ? mapPermissions(permissions, { persona: persona.id, target })
362
+ : undefined;
363
+ const mappedOpencode = isOpencodeTarget(target)
364
+ ? mapOpencodePermissions(permissions, { persona: persona.id, target })
365
+ : undefined;
366
+ if (mapped !== undefined) {
367
+ warnings.push(...mapped.warnings);
368
+ }
369
+ if (mappedOpencode !== undefined) {
370
+ warnings.push(...mappedOpencode.warnings);
371
+ }
372
+ const digest = sha256Hex(canonicalJson(sortedResources.map((resource) => ({
373
+ kind: resource.kind,
374
+ id: resource.id,
375
+ sha256: resource.sha256,
376
+ fromPersona: resource.fromPersona,
377
+ }))));
378
+ return {
379
+ id: persona.id,
380
+ displayName: persona.displayName,
381
+ purpose: persona.purpose,
382
+ ...(persona.extends === undefined ? {} : { extends: persona.extends }),
383
+ chain: chain.map((entry) => entry.id),
384
+ ...(personaMode === undefined ? {} : { mode: personaMode }),
385
+ rules: resolvedRules,
386
+ mcp: resolvedMcp,
387
+ skills: resolvedSkills,
388
+ commands: resolvedCommands,
389
+ hooks: resolvedHooks,
390
+ resources: sortedResources,
391
+ permissions,
392
+ claude: {
393
+ allow: mapped?.entries.allow ?? [],
394
+ deny: mapped?.entries.deny ?? [],
395
+ allowlist: mapped?.allowlist ?? false,
396
+ },
397
+ opencode: {
398
+ permission: mappedOpencode?.source ?? [],
399
+ records: mappedOpencode?.records ?? [],
400
+ },
401
+ ...(model === undefined ? {} : { model }),
402
+ path: persona.path,
403
+ digest,
404
+ permissionDigest: permissionDigest(permissions, mapped?.allowlist ?? false),
405
+ warnings: sortWarnings(warnings),
406
+ };
407
+ }
408
+ function unionAcrossPersonas(kind, personas, select) {
409
+ const byId = new Map();
410
+ for (const persona of personas) {
411
+ for (const resource of select(persona)) {
412
+ const existing = byId.get(resource.id);
413
+ if (existing === undefined) {
414
+ byId.set(resource.id, resource);
415
+ continue;
416
+ }
417
+ if (existing.sha256 !== resource.sha256) {
418
+ throw conflict(`two personas disagree on ${kind}/${resource.id}`, {
419
+ subject: resource.id,
420
+ });
421
+ }
422
+ }
423
+ }
424
+ return [...byId.values()].sort((a, b) => compareCodepoints(a.id, b.id));
425
+ }
426
+ /**
427
+ * Resolve every persona's composition chain into its resource set. The base
428
+ * persona's rules, permissions and workspace resources are unioned in; the
429
+ * stricter permission value wins; two different models are a conflict, never a
430
+ * silent override.
431
+ *
432
+ * The target's mode is computed here, never chosen by a heuristic:
433
+ *
434
+ * - `targets.<target>.active` (or the `--persona` override) selects profile
435
+ * mode, makes exactly that persona live, and refuses F001 when the persona or
436
+ * the target's profile support is missing;
437
+ * - otherwise the target is in agent mode and every persona is live.
438
+ *
439
+ * In profile mode only the live persona's artefacts and workspace resources are
440
+ * returned, so `materialise` and the containment gate cannot emit or accept
441
+ * another persona's resources: the isolation is structural, not a filter applied
442
+ * later. Every persona is still resolved, so a broken declaration anywhere in
443
+ * the source is reported; only emission is scoped to the live persona.
444
+ */
445
+ export function resolveSource(source, config, selection = {}) {
446
+ const target = configuredTarget(config);
447
+ const configuredActive = config.targets[target]?.active;
448
+ const requested = selection.persona ?? configuredActive;
449
+ const mode = requested === undefined ? MODE_AGENT : MODE_PROFILE;
450
+ const active = requested ?? null;
451
+ // The subject names the thing the user must edit: the flag they passed, or
452
+ // the config field that selected the persona.
453
+ const selectionSubject = selection.persona !== undefined ? '--persona' : CONFIG_PATH;
454
+ const sourceWarnings = source.warnings.map((entry) => warning({
455
+ code: entry.code,
456
+ persona: SOURCE_WARNING_SUBJECT,
457
+ target,
458
+ ...(entry.capability === undefined ? {} : { capability: entry.capability }),
459
+ message: entry.message,
460
+ }));
461
+ const byId = new Map(source.personas.map((persona) => [persona.id, persona]));
462
+ // The committed selection is validated even when `--persona` overrides it: a
463
+ // `targets.<target>.active` that names no persona is a broken config, and the
464
+ // flag must not mask it. The user commits this value; a run that ignores it
465
+ // leaves the next run (without the flag) broken with no warning here.
466
+ if (configuredActive !== undefined && !byId.has(configuredActive)) {
467
+ throw invalidConfig(`targets.${target}.active "${configuredActive}" names no persona`, {
468
+ subject: CONFIG_PATH,
469
+ action: 'declare the persona under .farna/personas/, or remove the active key',
470
+ });
471
+ }
472
+ if (active !== null) {
473
+ if (!targetSupportsProfile(target)) {
474
+ throw invalidConfig(`the ${target} target does not support profile mode`, {
475
+ subject: selectionSubject,
476
+ action: `remove the active persona for ${target}; profile mode is supported for: ${PROFILE_TARGETS.join(', ')}`,
477
+ });
478
+ }
479
+ if (!byId.has(active)) {
480
+ throw invalidConfig(`active persona "${active}" names no persona`, {
481
+ subject: selectionSubject,
482
+ action: 'declare the persona under .farna/personas/, or choose one that exists',
483
+ });
484
+ }
485
+ }
486
+ const byKind = {
487
+ rules: new Map(source.rules.map((rule) => [rule.id, rule])),
488
+ permissions: new Map(source.permissions.map((permission) => [permission.id, permission])),
489
+ mcp: new Map(source.mcp.map((server) => [server.id, server])),
490
+ skills: new Map(source.skills.map((skill) => [skill.id, skill])),
491
+ commands: new Map(source.commands.map((command) => [command.id, command])),
492
+ hooks: new Map(source.hooks.map((hook) => [hook.id, hook])),
493
+ };
494
+ const resolved = source.personas.map((persona) => resolveOne(persona, resolveChain(persona, byId), byKind, config, target, mode));
495
+ const notLive = active === null
496
+ ? []
497
+ : resolved
498
+ .map((persona) => persona.id)
499
+ .filter((id) => id !== active)
500
+ .sort(compareCodepoints);
501
+ // Profile mode is forced only when the **live** persona declares a boundary
502
+ // capability the target carries at the workspace level and nowhere else.
503
+ // An inactive persona's `mcp` or `hook` does not force the mode: it is not
504
+ // emitted, so warning that the selection was forced would blame a declaration
505
+ // that is not in the profile. Otherwise the selection is a choice, and every
506
+ // other persona is silently not live unless the run says so: that is W109, at
507
+ // info severity.
508
+ const forcingScope = active === null ? resolved : resolved.filter((p) => p.id === active);
509
+ const forced = forcingScope.some((persona) => persona.resources.some((resource) => PROFILE_FORCING_KINDS.includes(resource.kind)));
510
+ // The message describes the resolved state, not the invocation: the same
511
+ // source and config must produce the same lockfile whether the persona came
512
+ // from `active` or from `--persona`, or `check` would report drift for an
513
+ // identical selection.
514
+ const profileWarnings = mode === MODE_PROFILE && !forced
515
+ ? [
516
+ warning({
517
+ code: 'W109_PROFILE_BY_CHOICE',
518
+ persona: active ?? SOURCE_WARNING_SUBJECT,
519
+ target,
520
+ 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
521
+ ? ''
522
+ : `, and ${notLive.join(', ')} ${notLive.length === 1 ? 'is' : 'are'} not live`}`,
523
+ }),
524
+ ]
525
+ : [];
526
+ const personas = active === null ? resolved : resolved.filter((persona) => persona.id === active);
527
+ if (active === null) {
528
+ return {
529
+ target,
530
+ mode,
531
+ active,
532
+ notLive,
533
+ personas,
534
+ mcp: unionAcrossPersonas('mcp', personas, (persona) => persona.mcp),
535
+ skills: unionAcrossPersonas('skill', personas, (persona) => persona.skills),
536
+ commands: unionAcrossPersonas('command', personas, (persona) => persona.commands),
537
+ hooks: unionAcrossPersonas('hook', personas, (persona) => persona.hooks),
538
+ warnings: sortWarnings([
539
+ ...sourceWarnings,
540
+ ...personas.flatMap((persona) => persona.warnings),
541
+ ]),
542
+ };
543
+ }
544
+ const live = personas[0];
545
+ if (personas.length !== 1 || live === undefined) {
546
+ // Defensive: `active` was proven to name a persona above. Reaching here
547
+ // means the source changed under the resolver, which must never be guessed.
548
+ throw invalidConfig(`active persona "${active}" did not resolve to exactly one live persona`, {
549
+ subject: selectionSubject,
550
+ });
551
+ }
552
+ return {
553
+ target,
554
+ mode,
555
+ active,
556
+ notLive,
557
+ personas,
558
+ // Profile mode: the live persona's own resources, never a union across the
559
+ // personas that are not live. Anything else would leak a resource the
560
+ // workspace owner never declared.
561
+ mcp: live.mcp,
562
+ skills: live.skills,
563
+ commands: live.commands,
564
+ hooks: live.hooks,
565
+ // Every resolved persona's source-derived warnings, not only the live
566
+ // persona's: a warning carries its own `persona` and describes a
567
+ // declaration that was validated, so dropping a non-live persona's W101 or
568
+ // W112 would hide a real loss from the run that resolved it. The lockfile
569
+ // records the same set, scoped by persona.
570
+ warnings: sortWarnings([
571
+ ...sourceWarnings,
572
+ ...resolved.flatMap((persona) => persona.warnings),
573
+ ...profileWarnings,
574
+ ]),
575
+ };
576
+ }
@@ -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 {};