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,753 @@
1
+ import { join } from 'node:path';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { parseDocument } from 'yaml';
4
+ import { AGENT_FILE_EXT, CLAUDE_AGENTS_DIR, isOpencodeTarget, OPENCODE_AGENTS_DIR, OPENCODE_COMMANDS_DIR, OPENCODE_CONFIG_FILE, OPENCODE_HOOKS_PLUGIN, OPENCODE_SKILLS_DIR, SKILL_FILE_NAME, } from '../core/constants.js';
5
+ import { declaredNotEmitted } from '../core/errors.js';
6
+ import { readUtf8File } from '../core/fs.js';
7
+ import { compareCodepoints } from '../core/json.js';
8
+ import { lstatOrUndefined } from '../core/paths.js';
9
+ import { emitsTools, personaBody, resourceBody } from '../materialise/source-tree.js';
10
+ export function expectedAgentPath(target, personaId) {
11
+ const directory = isOpencodeTarget(target) ? OPENCODE_AGENTS_DIR : CLAUDE_AGENTS_DIR;
12
+ return `${directory}/${personaId}${AGENT_FILE_EXT}`;
13
+ }
14
+ /**
15
+ * Split an emitted artefact. Unlike the source reader, an emitted file is not
16
+ * trusted: it must open with the frontmatter delimiter exactly, and the block
17
+ * must parse as one YAML mapping.
18
+ */
19
+ function parseEmittedAgent(text, subject) {
20
+ if (!text.startsWith('---\n')) {
21
+ throw declaredNotEmitted('emitted artefact does not start with a "---" frontmatter block', {
22
+ subject,
23
+ action: 'the renderer produced no usable frontmatter; nothing was written',
24
+ });
25
+ }
26
+ const close = text.indexOf('\n---', 4);
27
+ if (close === -1) {
28
+ throw declaredNotEmitted('emitted frontmatter block is not closed', { subject });
29
+ }
30
+ const document = parseDocument(text.slice(4, close), {
31
+ uniqueKeys: true,
32
+ schema: 'core',
33
+ logLevel: 'silent',
34
+ });
35
+ if (document.errors.length > 0) {
36
+ const [first] = document.errors;
37
+ throw declaredNotEmitted(`emitted frontmatter did not parse: ${first?.message ?? 'unknown'}`, {
38
+ subject,
39
+ });
40
+ }
41
+ const value = document.toJS();
42
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
43
+ throw declaredNotEmitted('emitted frontmatter is not a mapping', { subject });
44
+ }
45
+ const afterClose = text.indexOf('\n', close + 4);
46
+ const body = afterClose === -1 ? '' : text.slice(afterClose + 1);
47
+ return { frontmatter: value, body };
48
+ }
49
+ function stringArray(value) {
50
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string')) {
51
+ return undefined;
52
+ }
53
+ return [...value].sort(compareCodepoints);
54
+ }
55
+ function describe(value) {
56
+ return JSON.stringify(value);
57
+ }
58
+ /**
59
+ * Assert the emitted key set is exactly the declared one. A renderer that adds
60
+ * a harness directive the persona never declared (`permissionMode`, `hooks`,
61
+ * `maxTurns`, ...) is adding a capability, not just losing one, and must be
62
+ * refused in the same way.
63
+ */
64
+ function assertKeySet(expected, emitted, persona, subject) {
65
+ for (const key of Object.keys(emitted).sort(compareCodepoints)) {
66
+ if (!expected.has(key)) {
67
+ throw declaredNotEmitted(`emitted frontmatter carries undeclared key "${key}" for ${persona.id}`, {
68
+ subject,
69
+ action: 'the renderer may emit only the keys the persona declares; nothing was written',
70
+ });
71
+ }
72
+ }
73
+ }
74
+ /**
75
+ * Assert one frontmatter field against the resolved persona. An absent field
76
+ * must be absent, and a present field must equal the resolved value exactly.
77
+ */
78
+ function assertField(emitted, key, expected, subject, persona) {
79
+ const present = Object.hasOwn(emitted, key);
80
+ if (expected === undefined) {
81
+ if (present) {
82
+ throw declaredNotEmitted(`emitted frontmatter carries "${key}", which the persona does not declare`, {
83
+ subject,
84
+ action: `the renderer must not invent a ${key} for ${persona.id}; nothing was written`,
85
+ });
86
+ }
87
+ return;
88
+ }
89
+ if (!present) {
90
+ throw declaredNotEmitted(`emitted frontmatter is missing "${key}"`, {
91
+ subject,
92
+ action: `the renderer dropped the resolved ${key} for ${persona.id}; nothing was written`,
93
+ });
94
+ }
95
+ const actual = emitted[key];
96
+ if (typeof expected === 'string') {
97
+ if (actual !== expected) {
98
+ throw declaredNotEmitted(`emitted frontmatter "${key}" is ${describe(actual)} but the persona resolves to ${describe(expected)}`, { subject });
99
+ }
100
+ return;
101
+ }
102
+ const actualArray = stringArray(actual);
103
+ const expectedArray = [...expected].sort(compareCodepoints);
104
+ if (actualArray === undefined ||
105
+ actualArray.length !== expectedArray.length ||
106
+ actualArray.some((entry, index) => entry !== expectedArray[index])) {
107
+ throw declaredNotEmitted(`emitted frontmatter "${key}" is ${describe(actual)} but the persona resolves to ${describe(expectedArray)}`, { subject });
108
+ }
109
+ }
110
+ /**
111
+ * Compare bodies exactly, normalising only one trailing newline. A renderer
112
+ * that prepends an instruction, appends one, or reorders the body differs from
113
+ * the composed body and is refused; the presence of the right words somewhere
114
+ * is not containment.
115
+ */
116
+ function bodiesMatch(emitted, composed) {
117
+ const trimOne = (text) => (text.endsWith('\n') ? text.slice(0, -1) : text);
118
+ return trimOne(emitted) === trimOne(composed);
119
+ }
120
+ /**
121
+ * The body gate, shared by both targets. Every declared rule's text must be
122
+ * present; no other persona's composed body may appear; and the whole body must
123
+ * equal the composed body exactly.
124
+ */
125
+ function verifyBody(persona, source, emittedBody, managedPath) {
126
+ for (const rule of persona.rules) {
127
+ if (!emittedBody.includes(rule.body.trim())) {
128
+ throw declaredNotEmitted(`declared rule "${rule.id}" is absent from the artefact`, {
129
+ subject: `${managedPath} (persona ${persona.id})`,
130
+ action: 'the renderer dropped declared content; nothing was written',
131
+ });
132
+ }
133
+ }
134
+ const composed = personaBody(persona);
135
+ // Run the leak scan on the whole body, not only after a mismatch, and skip a
136
+ // body this persona legitimately contains through composition: a base
137
+ // persona's composed body is a prefix of the derived persona's body.
138
+ for (const other of source.personas) {
139
+ if (other.id === persona.id) {
140
+ continue;
141
+ }
142
+ const otherBody = personaBody(other);
143
+ if (otherBody === '' || otherBody === composed || composed.includes(otherBody)) {
144
+ continue;
145
+ }
146
+ if (emittedBody.includes(otherBody)) {
147
+ throw declaredNotEmitted(`persona ${other.id}'s content leaked into ${persona.id}`, {
148
+ subject: managedPath,
149
+ action: 'the renderer mixed persona content; nothing was written',
150
+ });
151
+ }
152
+ }
153
+ if (!bodiesMatch(emittedBody, composed)) {
154
+ throw declaredNotEmitted('emitted body does not match the composed persona body', {
155
+ subject: managedPath,
156
+ action: 'the renderer added or changed content the persona does not declare; nothing was written',
157
+ });
158
+ }
159
+ }
160
+ /** The exact Claude Code frontmatter keys this persona is allowed to emit. */
161
+ function claudeKeys(persona) {
162
+ const keys = new Set(['name', 'description']);
163
+ if (persona.model !== undefined) {
164
+ keys.add('model');
165
+ }
166
+ if (emitsTools(persona)) {
167
+ keys.add('tools');
168
+ }
169
+ if (persona.claude.deny.length > 0) {
170
+ keys.add('disallowedTools');
171
+ }
172
+ return keys;
173
+ }
174
+ function verifyClaudeAgent(persona, source, parsed, managedPath) {
175
+ assertKeySet(claudeKeys(persona), parsed.frontmatter, persona, managedPath);
176
+ assertField(parsed.frontmatter, 'name', persona.id, managedPath, persona);
177
+ assertField(parsed.frontmatter, 'description', persona.purpose, managedPath, persona);
178
+ assertField(parsed.frontmatter, 'model', persona.model, managedPath, persona);
179
+ assertField(parsed.frontmatter, 'tools', emitsTools(persona) ? persona.claude.allow : undefined, managedPath, persona);
180
+ assertField(parsed.frontmatter, 'disallowedTools', persona.claude.deny.length === 0 ? undefined : persona.claude.deny, managedPath, persona);
181
+ verifyBody(persona, source, parsed.body, managedPath);
182
+ }
183
+ function permissionRecords(value) {
184
+ if (!Array.isArray(value)) {
185
+ return undefined;
186
+ }
187
+ const records = [];
188
+ for (const entry of value) {
189
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
190
+ return undefined;
191
+ }
192
+ const record = entry;
193
+ const keys = Object.keys(record).sort(compareCodepoints);
194
+ if (keys.length !== 3 ||
195
+ keys[0] !== 'action' ||
196
+ keys[1] !== 'effect' ||
197
+ keys[2] !== 'resource') {
198
+ return undefined;
199
+ }
200
+ const { action, resource, effect } = record;
201
+ if (typeof action !== 'string' || typeof resource !== 'string' || typeof effect !== 'string') {
202
+ return undefined;
203
+ }
204
+ records.push({ action, resource, effect });
205
+ }
206
+ return records;
207
+ }
208
+ /**
209
+ * The V2 (`opencode`) per-agent file. Measured at rulesync 43.11.0: the
210
+ * frontmatter is `description`, `mode`, `model` (when declared) and
211
+ * `permissions` (when the persona declares one), with no `name` key — OpenCode
212
+ * 2.x names the agent from the file, and a stray V1 field would make the file
213
+ * be read as a V1 agent.
214
+ */
215
+ function verifyOpencodeV2Agent(persona, source, parsed, managedPath) {
216
+ const keys = new Set(['description', 'mode']);
217
+ if (persona.model !== undefined) {
218
+ keys.add('model');
219
+ }
220
+ if (persona.opencode.records.length > 0) {
221
+ keys.add('permissions');
222
+ }
223
+ assertKeySet(keys, parsed.frontmatter, persona, managedPath);
224
+ assertField(parsed.frontmatter, 'description', persona.purpose, managedPath, persona);
225
+ assertField(parsed.frontmatter, 'mode', 'subagent', managedPath, persona);
226
+ assertField(parsed.frontmatter, 'model', persona.model, managedPath, persona);
227
+ const expectedPermissions = persona.opencode.records;
228
+ if (expectedPermissions.length === 0) {
229
+ assertField(parsed.frontmatter, 'permissions', undefined, managedPath, persona);
230
+ }
231
+ else {
232
+ const actual = permissionRecords(parsed.frontmatter['permissions']);
233
+ if (actual === undefined || !isDeepStrictEqual(actual, expectedPermissions)) {
234
+ throw declaredNotEmitted(`emitted permissions are ${describe(parsed.frontmatter['permissions'])} but the persona resolves to ${describe(expectedPermissions)}`, {
235
+ subject: managedPath,
236
+ action: 'the renderer dropped, invented or reordered a permission record; nothing was written',
237
+ });
238
+ }
239
+ }
240
+ verifyBody(persona, source, parsed.body, managedPath);
241
+ }
242
+ /**
243
+ * The V1 (`opencodev1`) per-agent file. Measured at rulesync 43.11.0: the
244
+ * frontmatter is `name`, `description`, `mode`, `model` (when declared) and the
245
+ * per-tool `permission` map (when the persona declares one). `temperature` and
246
+ * `tools` are V1 keys this product does not author, so they must never appear;
247
+ * a renderer that invents one is adding a capability the persona did not
248
+ * declare. The V1 map is compared value for value, key order included by
249
+ * `isDeepStrictEqual` (order is not semantic in V1, but a reordered pattern set
250
+ * is still a different map and is refused rather than nodded through).
251
+ */
252
+ function verifyOpencodeV1Agent(persona, source, parsed, managedPath) {
253
+ const keys = new Set(['name', 'description', 'mode']);
254
+ if (persona.model !== undefined) {
255
+ keys.add('model');
256
+ }
257
+ if (persona.opencode.permission.length > 0) {
258
+ keys.add('permission');
259
+ }
260
+ assertKeySet(keys, parsed.frontmatter, persona, managedPath);
261
+ assertField(parsed.frontmatter, 'name', persona.id, managedPath, persona);
262
+ assertField(parsed.frontmatter, 'description', persona.purpose, managedPath, persona);
263
+ assertField(parsed.frontmatter, 'mode', 'subagent', managedPath, persona);
264
+ assertField(parsed.frontmatter, 'model', persona.model, managedPath, persona);
265
+ const expected = {};
266
+ for (const category of persona.opencode.permission) {
267
+ const patterns = {};
268
+ for (const [resource, effect] of category.patterns) {
269
+ patterns[resource] = effect;
270
+ }
271
+ expected[category.key] = patterns;
272
+ }
273
+ if (persona.opencode.permission.length === 0) {
274
+ assertField(parsed.frontmatter, 'permission', undefined, managedPath, persona);
275
+ }
276
+ else if (!isDeepStrictEqual(parsed.frontmatter['permission'], expected)) {
277
+ throw declaredNotEmitted(`emitted permission map is ${describe(parsed.frontmatter['permission'])} but the persona resolves to ${describe(expected)}`, {
278
+ subject: managedPath,
279
+ action: 'the renderer dropped, invented or rewrote a permission category; nothing was written',
280
+ });
281
+ }
282
+ verifyBody(persona, source, parsed.body, managedPath);
283
+ }
284
+ /** Dispatch the per-agent gate to the shape the configured target emits. */
285
+ function verifyOpencodeAgent(target, persona, source, parsed, managedPath) {
286
+ if (target === 'opencodev1') {
287
+ verifyOpencodeV1Agent(persona, source, parsed, managedPath);
288
+ return;
289
+ }
290
+ verifyOpencodeV2Agent(persona, source, parsed, managedPath);
291
+ }
292
+ function expectedEnvReference(values) {
293
+ const converted = {};
294
+ for (const [key, value] of Object.entries(values)) {
295
+ if (typeof value === 'string') {
296
+ // Unreachable from a validated source: the loader refuses a literal
297
+ // (F002). Failing loudly is safer than treating it as a reference.
298
+ throw declaredNotEmitted('an MCP credential value is not a reference', { subject: key });
299
+ }
300
+ converted[key] = `{env:${value.fromEnv}}`;
301
+ }
302
+ return converted;
303
+ }
304
+ /**
305
+ * The MCP server map rulesync emits from the materialised source. Both OpenCode
306
+ * targets use `type: local|remote`, a `command` array and the same
307
+ * `environment` / `headers` maps; OpenCode 1.x additionally writes an explicit
308
+ * `enabled: true` on every server, where 2.x omits an enabled server's toggle
309
+ * and writes only `disabled: true`. V2 nests the map under `mcp.servers`; V1
310
+ * keys it directly under `mcp`, so the same expected map is wrapped differently
311
+ * by the caller.
312
+ */
313
+ function expectedMcpServers(source, target) {
314
+ const servers = {};
315
+ for (const resource of source.mcp) {
316
+ if (resource.server.type === 'stdio') {
317
+ const env = resource.server.env === undefined ? undefined : expectedEnvReference(resource.server.env);
318
+ servers[resource.id] = {
319
+ type: 'local',
320
+ command: [resource.server.command, ...(resource.server.args ?? [])],
321
+ ...(target === 'opencodev1' ? { enabled: true } : {}),
322
+ ...(env === undefined ? {} : { environment: env }),
323
+ };
324
+ continue;
325
+ }
326
+ const headers = resource.server.headers === undefined
327
+ ? undefined
328
+ : expectedEnvReference(resource.server.headers);
329
+ servers[resource.id] = {
330
+ type: 'remote',
331
+ url: resource.server.url,
332
+ ...(target === 'opencodev1' ? { enabled: true } : {}),
333
+ ...(headers === undefined ? {} : { headers }),
334
+ };
335
+ }
336
+ return servers;
337
+ }
338
+ async function readManagedFile(absolute, subject) {
339
+ const stats = await lstatOrUndefined(absolute, subject);
340
+ if (stats === undefined) {
341
+ throw declaredNotEmitted('declared resource produced no artefact', {
342
+ subject,
343
+ action: 'the renderer did not emit this file; nothing was written',
344
+ });
345
+ }
346
+ if (!stats.isFile() || stats.isSymbolicLink()) {
347
+ throw declaredNotEmitted('rendered path is not a regular file', { subject });
348
+ }
349
+ return await readUtf8File(absolute, subject, {
350
+ action: 'the renderer must emit UTF-8; nothing was written',
351
+ });
352
+ }
353
+ async function verifySkill(skill, outputRoot) {
354
+ const verified = new Map();
355
+ const dir = `${OPENCODE_SKILLS_DIR}/${skill.id}`;
356
+ const skillPath = `${dir}/${SKILL_FILE_NAME}`;
357
+ const text = await readManagedFile(join(outputRoot, dir, SKILL_FILE_NAME), skillPath);
358
+ verified.set(skillPath, text);
359
+ const parsed = parseEmittedAgent(text, skillPath);
360
+ const keys = new Set(Object.keys(parsed.frontmatter).sort(compareCodepoints));
361
+ if (keys.size !== 2 || !keys.has('description') || !keys.has('name')) {
362
+ throw declaredNotEmitted(`skill "${skill.id}" frontmatter must carry exactly name and description`, { subject: skillPath });
363
+ }
364
+ if (parsed.frontmatter['name'] !== skill.id) {
365
+ throw declaredNotEmitted(`skill "${skill.id}" was emitted under name ${describe(parsed.frontmatter['name'])}`, { subject: skillPath });
366
+ }
367
+ if (parsed.frontmatter['description'] !== skill.description) {
368
+ throw declaredNotEmitted(`skill "${skill.id}" description differs from the declared description`, { subject: skillPath });
369
+ }
370
+ if (!bodiesMatch(parsed.body, `${resourceBody(skill.body)}\n`)) {
371
+ throw declaredNotEmitted(`skill "${skill.id}" body differs from the declared body`, {
372
+ subject: skillPath,
373
+ });
374
+ }
375
+ for (const file of skill.files) {
376
+ const path = `${dir}/${file.path}`;
377
+ const actual = await readManagedFile(join(outputRoot, dir, ...file.path.split('/')), path);
378
+ if (actual !== file.text) {
379
+ throw declaredNotEmitted(`skill file "${path}" differs from the declared bytes`, {
380
+ subject: path,
381
+ });
382
+ }
383
+ verified.set(path, actual);
384
+ }
385
+ return verified;
386
+ }
387
+ async function verifyCommand(command, outputRoot) {
388
+ const path = `${OPENCODE_COMMANDS_DIR}/${command.id}.md`;
389
+ const text = await readManagedFile(join(outputRoot, path), path);
390
+ const parsed = parseEmittedAgent(text, path);
391
+ const actualKeys = new Set(Object.keys(parsed.frontmatter));
392
+ if (actualKeys.size !== 1 || !actualKeys.has('description')) {
393
+ throw declaredNotEmitted(`command "${command.id}" frontmatter carries ${describe(Object.keys(parsed.frontmatter))}, but a command declares exactly description`, { subject: path });
394
+ }
395
+ if (parsed.frontmatter['description'] !== command.description) {
396
+ throw declaredNotEmitted(`command "${command.id}" description differs from the declared description`, {
397
+ subject: path,
398
+ });
399
+ }
400
+ if (!bodiesMatch(parsed.body, `${resourceBody(command.body)}\n`)) {
401
+ throw declaredNotEmitted(`command "${command.id}" body differs from the declared body`, {
402
+ subject: path,
403
+ });
404
+ }
405
+ return new Map([[path, text]]);
406
+ }
407
+ /**
408
+ * Undo rulesync's template-literal escaping, in the exact inverse of the order
409
+ * it applied (`escapeForTemplateLiteral`: double each backslash, prefix each
410
+ * backtick, then prefix each `${`):
411
+ *
412
+ * 1. `\${` -> `${`
413
+ * 2. `` \` `` -> `` ` ``
414
+ * 3. `\\` -> `\`
415
+ *
416
+ * The order is load-bearing. Undoing the backslash doubling first would turn a
417
+ * literal `\${` into `${` and make a command that only *looks* like a
418
+ * substitution compare equal to one that is.
419
+ */
420
+ function unescapeTemplateLiteral(value) {
421
+ return value.replaceAll('\\${', '${').replaceAll('\\`', '`').replaceAll('\\\\', '\\');
422
+ }
423
+ const HOOK_EVENT_BY_PHASE = {
424
+ 'before-tool': 'preToolUse',
425
+ 'after-tool': 'postToolUse',
426
+ 'session-start': 'sessionStart',
427
+ stop: 'stop',
428
+ };
429
+ /**
430
+ * The V2 (`opencode`) plugin's registration anchors, measured at rulesync
431
+ * 43.11.0: a tool hook (`ctx.tool.hook("execute.before"|"execute.after", ...)`)
432
+ * and an event hook whose `label: "<event>"` has no tool anchor.
433
+ */
434
+ const OPENCODE_V2_HOOK_ANCHORS = [
435
+ { pattern: /ctx\.tool\.hook\("execute\.before"/g, event: () => 'preToolUse', registration: true },
436
+ { pattern: /ctx\.tool\.hook\("execute\.after"/g, event: () => 'postToolUse', registration: true },
437
+ {
438
+ pattern: /label: "(preToolUse|postToolUse|sessionStart|stop)"/g,
439
+ event: (match) => match[1] ?? '',
440
+ registration: false,
441
+ },
442
+ ];
443
+ /**
444
+ * The V1 (`opencodev1`) `RulesyncHooksPlugin` registration anchors, measured at
445
+ * rulesync 43.11.0: the returned object keys `"tool.execute.before"` and
446
+ * `"tool.execute.after"`, and the event-loop branches
447
+ * `event.type === "session.created"` / `event.type === "session.idle"`. The
448
+ * V1 plugin also carries `label: "sessionStart"|"stop"|"postToolUse"` inside
449
+ * each run call; those are labels, not anchors, so they are deliberately absent
450
+ * from this list.
451
+ */
452
+ const OPENCODE_V1_HOOK_ANCHORS = [
453
+ { pattern: /"tool\.execute\.before":/g, event: () => 'preToolUse', registration: true },
454
+ { pattern: /"tool\.execute\.after":/g, event: () => 'postToolUse', registration: true },
455
+ {
456
+ pattern: /event\.type === "session\.created"/g,
457
+ event: () => 'sessionStart',
458
+ registration: true,
459
+ },
460
+ { pattern: /event\.type === "session\.idle"/g, event: () => 'stop', registration: true },
461
+ ];
462
+ /**
463
+ * The hooks plugin is generated JavaScript, so it is verified at the level that
464
+ * matters: exactly the declared commands, each bound to its declared event and
465
+ * matcher. A byte pin lives in the golden test; this gate is what fails when an
466
+ * undeclared command is injected, a declared one is dropped, or one is moved to
467
+ * another event.
468
+ *
469
+ * A command's event is the nearest preceding registration anchor; its matcher
470
+ * is the `new RegExp(...)` between the previous command and this one within that
471
+ * registration. The anchor set is the only thing that differs between the two
472
+ * OpenCode majors: V2 registers through `ctx.tool.hook(...)` and a label-only
473
+ * event loop, V1 through the returned `"tool.execute.*"` keys and
474
+ * `event.type === ...` branches.
475
+ *
476
+ * An `after-tool` command in V2 is emitted inside `ctx.tool.hook("execute.after",
477
+ * ...)` *and* carries `label: "postToolUse"` in the same `__rulesyncRunHook(...)`
478
+ * call. That label sits AFTER the matcher guard, so it must never start the
479
+ * matcher window: only the registration anchor may. The window runs from the
480
+ * previous command's end, so a matcher-less hook cannot inherit its neighbour's
481
+ * guard.
482
+ */
483
+ function verifyHookPlugin(source, text, subject, anchorPatterns) {
484
+ const anchors = [];
485
+ for (const { pattern, event, registration } of anchorPatterns) {
486
+ for (const match of text.matchAll(pattern)) {
487
+ anchors.push({ index: match.index ?? 0, event: event(match), registration });
488
+ }
489
+ }
490
+ const nearestAnchor = (index) => {
491
+ let found;
492
+ for (const anchor of anchors) {
493
+ if (anchor.index < index && (found === undefined || anchor.index > found.index)) {
494
+ found = anchor;
495
+ }
496
+ }
497
+ return found;
498
+ };
499
+ /** The start of the block that holds the command, never a label inside its run call. */
500
+ const registrationStartAt = (index) => {
501
+ let found;
502
+ for (const anchor of anchors) {
503
+ if (anchor.index >= index || !anchor.registration) {
504
+ continue;
505
+ }
506
+ if (found === undefined || anchor.index > found.index) {
507
+ found = anchor;
508
+ }
509
+ }
510
+ // An event-loop hook has no tool anchor; its `label:` is the block start.
511
+ return (found ?? nearestAnchor(index))?.index;
512
+ };
513
+ const registrations = [];
514
+ const commandPattern = /command: ("(?:[^"\\]|\\.)*")/g;
515
+ // rulesync lays a registration out as `matcher? command matcher? command ...`
516
+ // inside one callback, so a command's matcher is the `new RegExp(...)` between
517
+ // the PREVIOUS command and this one. Slicing from the event anchor instead
518
+ // let a second command inherit an earlier command's matcher (a matcher-less
519
+ // hook was refused, and a dropped matcher was accepted when both hooks named
520
+ // the same one).
521
+ let previousCommandEnd = -1;
522
+ for (const match of text.matchAll(commandPattern)) {
523
+ const index = match.index ?? 0;
524
+ const raw = match[1] ?? '""';
525
+ let command;
526
+ try {
527
+ // rulesync escapes the command for a template literal before embedding
528
+ // it, so the parsed string is the escaped form, not the source command.
529
+ // Undo that escaping before comparing: it is the renderer's
530
+ // representation of the same command, not an added or dropped instruction.
531
+ command = unescapeTemplateLiteral(JSON.parse(raw));
532
+ }
533
+ catch {
534
+ throw declaredNotEmitted('hooks plugin contains an unreadable command', { subject });
535
+ }
536
+ const registration = nearestAnchor(index);
537
+ if (registration === undefined) {
538
+ throw declaredNotEmitted(`hooks plugin declares command ${describe(command)} with no registration event`, { subject });
539
+ }
540
+ // The window starts after the previous command, never at the anchor: a hook
541
+ // without a matcher must not inherit its neighbour's guard, and a dropped
542
+ // matcher must not be replaced by an earlier identical one. With no previous
543
+ // command it starts at the enclosing registration, never at a `label:` that
544
+ // is an argument of this same call.
545
+ const windowStart = previousCommandEnd >= 0 ? previousCommandEnd : (registrationStartAt(index) ?? 0);
546
+ const block = text.slice(windowStart, index);
547
+ previousCommandEnd = index + match[0].length;
548
+ const matcherMatch = /new RegExp\("((?:[^"\\]|\\.)*)"\)/g;
549
+ let matcher;
550
+ for (const candidate of block.matchAll(matcherMatch)) {
551
+ try {
552
+ // A matcher is embedded directly in a quoted JS string with backslashes
553
+ // and quotes escaped, so JSON.parse is its whole inverse: applying the
554
+ // template-literal unescape here too would strip one level too many
555
+ // from a matcher that contains a literal backslash.
556
+ matcher = JSON.parse(`"${candidate[1] ?? ''}"`);
557
+ }
558
+ catch {
559
+ matcher = undefined;
560
+ }
561
+ }
562
+ registrations.push({
563
+ event: registration.event,
564
+ command,
565
+ ...(matcher === undefined ? {} : { matcher }),
566
+ });
567
+ }
568
+ const expected = source.hooks
569
+ .filter((hook) => hook.carried)
570
+ .map((hook) => ({
571
+ event: HOOK_EVENT_BY_PHASE[hook.phase] ?? '',
572
+ command: hook.command,
573
+ ...(hook.matcher === undefined ? {} : { matcher: hook.matcher }),
574
+ }))
575
+ .sort((a, b) => compareCodepoints(`${a.event}\0${a.command}`, `${b.event}\0${b.command}`));
576
+ registrations.sort((a, b) => compareCodepoints(`${a.event}\0${a.command}`, `${b.event}\0${b.command}`));
577
+ if (!isDeepStrictEqual(registrations, expected)) {
578
+ throw declaredNotEmitted(`hooks plugin registers ${describe(registrations)} but the source declares ${describe(expected)}`, {
579
+ subject,
580
+ action: 'the renderer dropped, invented or moved a hook; nothing was written',
581
+ });
582
+ }
583
+ }
584
+ async function verifyOpencodeWorkspace(source, outputRoot, target) {
585
+ const verified = new Map();
586
+ if (source.mcp.length > 0) {
587
+ const path = OPENCODE_CONFIG_FILE;
588
+ const text = await readManagedFile(join(outputRoot, path), path);
589
+ verified.set(path, text);
590
+ let parsed;
591
+ try {
592
+ parsed = JSON.parse(text);
593
+ }
594
+ catch {
595
+ throw declaredNotEmitted('opencode config is not valid JSON', { subject: path });
596
+ }
597
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
598
+ throw declaredNotEmitted('opencode config is not a JSON object', { subject: path });
599
+ }
600
+ const keys = Object.keys(parsed).sort(compareCodepoints);
601
+ if (keys.length !== 1 || keys[0] !== 'mcp') {
602
+ throw declaredNotEmitted(`opencode config carries top-level keys ${describe(keys)}, but this render declares only mcp`, {
603
+ subject: path,
604
+ action: 'the renderer must not add a shared permission or instruction block; nothing was written',
605
+ });
606
+ }
607
+ const mcp = parsed['mcp'];
608
+ if (mcp === null || typeof mcp !== 'object' || Array.isArray(mcp)) {
609
+ throw declaredNotEmitted('opencode config mcp is not an object', { subject: path });
610
+ }
611
+ const expected = expectedMcpServers(source, target);
612
+ let emitted;
613
+ if (source.target === 'opencodev1') {
614
+ // V1 is the flat map directly under `mcp`. An envelope here would be the
615
+ // V2 shape, which OpenCode 1.x does not read as servers.
616
+ emitted = mcp;
617
+ }
618
+ else {
619
+ const mcpKeys = Object.keys(mcp).sort(compareCodepoints);
620
+ if (mcpKeys.length !== 1 || mcpKeys[0] !== 'servers') {
621
+ throw declaredNotEmitted(`opencode config mcp carries keys ${describe(mcpKeys)}`, {
622
+ subject: path,
623
+ });
624
+ }
625
+ emitted = mcp['servers'];
626
+ }
627
+ if (!isDeepStrictEqual(emitted, expected)) {
628
+ throw declaredNotEmitted(`opencode mcp servers are ${describe(emitted)} but the source declares ${describe(expected)}`, {
629
+ subject: path,
630
+ action: 'the renderer dropped, invented or rewrote an MCP server; nothing was written',
631
+ });
632
+ }
633
+ }
634
+ for (const skill of source.skills) {
635
+ for (const [path, text] of await verifySkill(skill, outputRoot)) {
636
+ verified.set(path, text);
637
+ }
638
+ }
639
+ for (const command of source.commands) {
640
+ for (const [path, text] of await verifyCommand(command, outputRoot)) {
641
+ verified.set(path, text);
642
+ }
643
+ }
644
+ const carriedHooks = source.hooks.filter((hook) => hook.carried);
645
+ if (carriedHooks.length > 0) {
646
+ const text = await readManagedFile(join(outputRoot, OPENCODE_HOOKS_PLUGIN), OPENCODE_HOOKS_PLUGIN);
647
+ if (text.length === 0) {
648
+ throw declaredNotEmitted('hooks plugin is empty', { subject: OPENCODE_HOOKS_PLUGIN });
649
+ }
650
+ verifyHookPlugin(source, text, OPENCODE_HOOKS_PLUGIN, target === 'opencodev1' ? OPENCODE_V1_HOOK_ANCHORS : OPENCODE_V2_HOOK_ANCHORS);
651
+ verified.set(OPENCODE_HOOKS_PLUGIN, text);
652
+ }
653
+ return verified;
654
+ }
655
+ /**
656
+ * The exact set of managed paths a target renders. The set is derived from the
657
+ * plan, never from `RenderResult`: the renderer's own path list is what the
658
+ * gate is checking, so it cannot also define the expectation.
659
+ */
660
+ export function expectedPaths(source) {
661
+ const paths = source.personas.map((persona) => expectedAgentPath(source.target, persona.id));
662
+ if (isOpencodeTarget(source.target)) {
663
+ if (source.mcp.length > 0) {
664
+ paths.push(OPENCODE_CONFIG_FILE);
665
+ }
666
+ for (const skill of source.skills) {
667
+ paths.push(`${OPENCODE_SKILLS_DIR}/${skill.id}/${SKILL_FILE_NAME}`);
668
+ for (const file of skill.files) {
669
+ paths.push(`${OPENCODE_SKILLS_DIR}/${skill.id}/${file.path}`);
670
+ }
671
+ }
672
+ for (const command of source.commands) {
673
+ paths.push(`${OPENCODE_COMMANDS_DIR}/${command.id}.md`);
674
+ }
675
+ if (source.hooks.some((hook) => hook.carried)) {
676
+ paths.push(OPENCODE_HOOKS_PLUGIN);
677
+ }
678
+ }
679
+ return paths.sort(compareCodepoints);
680
+ }
681
+ /**
682
+ * The containment gate. Every expected artefact is a non-empty file whose
683
+ * frontmatter key set and values equal the resolved persona, and whose body is
684
+ * exactly the persona's composed body (one trailing newline normalised). On
685
+ * OpenCode the workspace files are verified against the resolved resources too.
686
+ *
687
+ * Returns the exact bytes it verified, keyed by managed path. The caller writes
688
+ * THESE bytes: re-reading the stage after verification would let a renderer (or
689
+ * a concurrent writer) change the file between the gate and the write, so the
690
+ * bytes that were checked would not be the bytes that landed.
691
+ */
692
+ export async function verifyRender(source, render, outputRoot) {
693
+ const expected = expectedPaths(source);
694
+ const emitted = [...render.files].sort(compareCodepoints);
695
+ const agentPaths = new Set(source.personas.map((persona) => expectedAgentPath(source.target, persona.id)));
696
+ for (const path of expected) {
697
+ if (!emitted.includes(path)) {
698
+ throw declaredNotEmitted(agentPaths.has(path)
699
+ ? 'declared persona produced no artefact'
700
+ : 'declared resource produced no artefact', {
701
+ subject: path,
702
+ action: 'the renderer did not emit this file; nothing was written',
703
+ });
704
+ }
705
+ }
706
+ for (const path of emitted) {
707
+ if (!expected.includes(path)) {
708
+ throw declaredNotEmitted('renderer emitted an unexpected path', {
709
+ subject: path,
710
+ action: 'the expected path set is one artefact per declaration',
711
+ });
712
+ }
713
+ }
714
+ const verified = new Map();
715
+ for (const persona of source.personas) {
716
+ const managedPath = expectedAgentPath(source.target, persona.id);
717
+ const absolute = join(outputRoot, managedPath);
718
+ // The renderer's own path list is not evidence that it wrote anything.
719
+ const stats = await lstatOrUndefined(absolute, managedPath);
720
+ if (stats === undefined) {
721
+ throw declaredNotEmitted('renderer listed a path it did not write', {
722
+ subject: managedPath,
723
+ action: 'the renderer reported a file that does not exist; nothing was written',
724
+ });
725
+ }
726
+ if (!stats.isFile() || stats.isSymbolicLink()) {
727
+ throw declaredNotEmitted('rendered path is not a regular file', { subject: managedPath });
728
+ }
729
+ const text = await readUtf8File(absolute, managedPath, {
730
+ action: 'the renderer must emit UTF-8; nothing was written',
731
+ });
732
+ if (text.length === 0) {
733
+ throw declaredNotEmitted('rendered artefact is empty', {
734
+ subject: managedPath,
735
+ action: 'an empty agent file declares no persona; nothing was written',
736
+ });
737
+ }
738
+ const parsed = parseEmittedAgent(text, managedPath);
739
+ if (isOpencodeTarget(source.target)) {
740
+ verifyOpencodeAgent(source.target, persona, source, parsed, managedPath);
741
+ }
742
+ else {
743
+ verifyClaudeAgent(persona, source, parsed, managedPath);
744
+ }
745
+ verified.set(managedPath, text);
746
+ }
747
+ if (isOpencodeTarget(source.target)) {
748
+ for (const [path, text] of await verifyOpencodeWorkspace(source, outputRoot, source.target)) {
749
+ verified.set(path, text);
750
+ }
751
+ }
752
+ return verified;
753
+ }