mandrel 2.83.0 → 2.85.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 (54) hide show
  1. package/.agents/README.md +65 -20
  2. package/.agents/docs/configuration.md +36 -0
  3. package/.agents/docs/runbooks/mods.md +98 -54
  4. package/.agents/docs/workflows.md +14 -0
  5. package/.agents/instructions.md +4 -1
  6. package/.agents/mods/mandrel-status/hooks/register.tsx +579 -204
  7. package/.agents/mods/mandrel-status/types/index.d.ts +58 -13
  8. package/.agents/schemas/story-deliver-terminal.schema.json +2 -2
  9. package/.agents/scripts/boot-sweep.js +42 -13
  10. package/.agents/scripts/coverage-capture.js +1 -0
  11. package/.agents/scripts/evidence-gate.js +1 -0
  12. package/.agents/scripts/generate-workflows-doc.js +14 -0
  13. package/.agents/scripts/lib/bootstrap/agents-md-fold.js +99 -16
  14. package/.agents/scripts/lib/bootstrap/manifest.js +4 -4
  15. package/.agents/scripts/lib/bootstrap/project-bootstrap.js +16 -1
  16. package/.agents/scripts/lib/close-lock-events.js +29 -9
  17. package/.agents/scripts/lib/codex/agents-projection.js +284 -0
  18. package/.agents/scripts/lib/codex/skills-projection.js +291 -0
  19. package/.agents/scripts/lib/config/agentrc-overlay.js +91 -0
  20. package/.agents/scripts/lib/config/sync-agentrc.js +39 -19
  21. package/.agents/scripts/lib/config-resolver.js +5 -42
  22. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  23. package/.agents/scripts/lib/full-suite-lock.js +2 -0
  24. package/.agents/scripts/lib/full-suite-queue.js +66 -26
  25. package/.agents/scripts/lib/observability/source-classifier.js +2 -0
  26. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +242 -0
  27. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +151 -111
  28. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +152 -0
  29. package/.agents/scripts/lib/orchestration/review-providers/codex.js +33 -105
  30. package/.agents/scripts/lib/orchestration/review-providers/provider-severity.js +30 -0
  31. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +3 -17
  32. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +12 -5
  33. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +30 -4
  34. package/.agents/scripts/lib/orchestration/story-handoff.js +84 -10
  35. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +89 -0
  36. package/.agents/scripts/single-story-init.js +20 -5
  37. package/.agents/scripts/sync-agentrc.js +5 -3
  38. package/.agents/scripts/sync-claude-agents.js +20 -0
  39. package/.agents/scripts/sync-claude-commands.js +64 -27
  40. package/.agents/scripts/sync-codex-agents.js +36 -0
  41. package/.agents/scripts/sync-codex-skills.js +36 -0
  42. package/.agents/workflows/helpers/deliver-story-reference.md +6 -0
  43. package/.agents/workflows/helpers/mandrel-sync-config.md +16 -9
  44. package/.agents/workflows/mandrel-update.md +2 -1
  45. package/docs/CHANGELOG.md +23 -0
  46. package/lib/cli/guarded-sync.js +3 -2
  47. package/lib/cli/registry.js +248 -0
  48. package/lib/cli/sync-agents.js +5 -2
  49. package/lib/cli/sync-commands.js +5 -2
  50. package/lib/cli/sync.js +45 -14
  51. package/lib/cli/uninstall.js +8 -1
  52. package/lib/migrations/index.js +2 -0
  53. package/lib/migrations/steps/2.84.0-hoist-system-prompt-block.js +64 -0
  54. package/package.json +3 -2
@@ -0,0 +1,284 @@
1
+ /**
2
+ * Codex custom-agent projection of the role set: each `.agents/agents/<role>.md`
3
+ * (payload, then `.agents/local/agents/`) becomes
4
+ * `.codex/agents/mandrel-<role>.toml`. Codex resolves no `@` imports, so an
5
+ * import line is inlined here; no `model` is ever emitted, because
6
+ * `delivery.routing.agentModels` values are Claude-only. Node built-ins only,
7
+ * so the doctor registry can import it.
8
+ *
9
+ * @module codex/agents-projection
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+
15
+ import { extractDescription } from '../mandrel-catalog.js';
16
+
17
+ /** Project-relative POSIX home of the projection. */
18
+ export const CODEX_AGENTS_DIR = '.codex/agents';
19
+
20
+ /** Generated files are `mandrel-<role>.toml`; consumer agents are never named so. */
21
+ const CODEX_AGENT_PREFIX = 'mandrel-';
22
+
23
+ /** First line of every generated file; the reap touches nothing without it. */
24
+ const CODEX_AGENT_HEADER = '# AUTO-GENERATED by mandrel';
25
+
26
+ const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
27
+ const IMPORT_LINE_RE = /^@(\S+)\s*$/;
28
+
29
+ /**
30
+ * @param {string} dir
31
+ * @returns {string[]}
32
+ */
33
+ function roleFilesIn(dir) {
34
+ try {
35
+ return fs
36
+ .readdirSync(dir, { withFileTypes: true })
37
+ .filter((e) => e.isFile() && e.name.endsWith('.md'))
38
+ .map((e) => e.name)
39
+ .sort();
40
+ } catch {
41
+ return [];
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Role files from both sources; the payload wins a collision.
47
+ *
48
+ * @param {{ payloadSrc: string, localSrc: string }} sources
49
+ * @returns {Array<{ role: string, sourcePath: string }>}
50
+ */
51
+ function listRoleSources({ payloadSrc, localSrc }) {
52
+ const byRole = new Map();
53
+ for (const dir of [payloadSrc, localSrc]) {
54
+ for (const file of roleFilesIn(dir)) {
55
+ const role = file.replace(/\.md$/, '');
56
+ if (!byRole.has(role)) {
57
+ byRole.set(role, { role, sourcePath: path.join(dir, file) });
58
+ }
59
+ }
60
+ }
61
+ return [...byRole.values()].sort((a, b) => a.role.localeCompare(b.role));
62
+ }
63
+
64
+ /** Short escapes TOML basic strings accept. */
65
+ const TOML_SHORT_ESCAPES = Object.freeze({
66
+ '\\': '\\\\',
67
+ '"': '\\"',
68
+ '\n': '\\n',
69
+ '\t': '\\t',
70
+ '\r': '\\r',
71
+ });
72
+
73
+ /**
74
+ * Control characters (U+0000–U+001F, U+007F), which TOML forbids raw.
75
+ *
76
+ * @param {string} ch
77
+ * @returns {boolean}
78
+ */
79
+ function isControl(ch) {
80
+ const code = ch.charCodeAt(0);
81
+ return code < 0x20 || code === 0x7f;
82
+ }
83
+
84
+ /**
85
+ * @param {string} ch
86
+ * @returns {string}
87
+ */
88
+ function unicodeEscape(ch) {
89
+ return `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`;
90
+ }
91
+
92
+ /**
93
+ * A TOML basic string (single line), escaping what the spec forbids raw.
94
+ *
95
+ * @param {string} value
96
+ * @returns {string}
97
+ */
98
+ function tomlString(value) {
99
+ let out = '';
100
+ for (const ch of String(value)) {
101
+ if (TOML_SHORT_ESCAPES[ch]) out += TOML_SHORT_ESCAPES[ch];
102
+ else out += isControl(ch) ? unicodeEscape(ch) : ch;
103
+ }
104
+ return `"${out}"`;
105
+ }
106
+
107
+ /**
108
+ * A TOML multi-line basic string. Newlines and tabs stay raw; a `"""` run is
109
+ * broken so it cannot close the string early.
110
+ *
111
+ * @param {string} value
112
+ * @returns {string}
113
+ */
114
+ function tomlMultiline(value) {
115
+ let body = '';
116
+ for (const ch of String(value).replace(/\r\n/g, '\n')) {
117
+ if (ch === '\\') body += '\\\\';
118
+ else if (ch === '\n' || ch === '\t' || !isControl(ch)) body += ch;
119
+ else body += unicodeEscape(ch);
120
+ }
121
+ body = body.replace(/"""/g, '""\\"');
122
+ return `"""\n${body.endsWith('\n') ? body : `${body}\n`}"""`;
123
+ }
124
+
125
+ /**
126
+ * Replace each whole-line `@<path>` import with the imported file's text,
127
+ * resolved against the role file's directory. A missing target throws.
128
+ *
129
+ * @param {string} body
130
+ * @param {string} baseDir
131
+ * @returns {string}
132
+ */
133
+ function inlineImports(body, baseDir) {
134
+ return body
135
+ .split('\n')
136
+ .map((line) => {
137
+ const match = IMPORT_LINE_RE.exec(line);
138
+ if (!match) return line;
139
+ const target = path.resolve(baseDir, match[1]);
140
+ try {
141
+ return fs.readFileSync(target, 'utf8').replace(/\n+$/, '');
142
+ } catch {
143
+ throw new Error(
144
+ `codex agent projection: cannot inline '${line.trim()}' from ${baseDir} — ${target} is unreadable.`,
145
+ );
146
+ }
147
+ })
148
+ .join('\n');
149
+ }
150
+
151
+ /**
152
+ * The `.toml` for one role.
153
+ *
154
+ * @param {{ role: string, source: string, baseDir: string, sourceLabel: string }} input
155
+ * @returns {string}
156
+ */
157
+ function renderCodexAgent({ role, source, baseDir, sourceLabel }) {
158
+ const fm = FRONTMATTER_RE.exec(source);
159
+ const body = fm ? source.slice(fm[0].length) : source;
160
+ const description =
161
+ extractDescription(source) ?? `Mandrel ${role} role agent.`;
162
+ const effort = fm?.[1].match(/^effort:\s*["']?([\w-]+)/m)?.[1] ?? null;
163
+ const lines = [
164
+ `${CODEX_AGENT_HEADER} from ${sourceLabel} — do not edit. Re-run: npm run sync:agents`,
165
+ `name = ${tomlString(role)}`,
166
+ `description = ${tomlString(description)}`,
167
+ ];
168
+ if (effort) lines.push(`model_reasoning_effort = ${tomlString(effort)}`);
169
+ lines.push(
170
+ `developer_instructions = ${tomlMultiline(inlineImports(body.replace(/^\n+/, ''), baseDir))}`,
171
+ );
172
+ return `${lines.join('\n')}\n`;
173
+ }
174
+
175
+ /**
176
+ * Every projected agent keyed by its `.toml` file name.
177
+ *
178
+ * @param {{ projectRoot: string, payloadSrc?: string, localSrc?: string }} opts
179
+ * @returns {Map<string, string>}
180
+ */
181
+ export function expectedCodexAgents({
182
+ projectRoot,
183
+ payloadSrc = path.join(projectRoot, '.agents', 'agents'),
184
+ localSrc = path.join(projectRoot, '.agents', 'local', 'agents'),
185
+ }) {
186
+ const expected = new Map();
187
+ for (const { role, sourcePath } of listRoleSources({
188
+ payloadSrc,
189
+ localSrc,
190
+ })) {
191
+ expected.set(
192
+ `${CODEX_AGENT_PREFIX}${role}.toml`,
193
+ renderCodexAgent({
194
+ role,
195
+ source: fs.readFileSync(sourcePath, 'utf8'),
196
+ baseDir: path.dirname(sourcePath),
197
+ sourceLabel: path
198
+ .relative(projectRoot, sourcePath)
199
+ .split(path.sep)
200
+ .join('/'),
201
+ }),
202
+ );
203
+ }
204
+ return expected;
205
+ }
206
+
207
+ /**
208
+ * Generated agent files on disk: `mandrel-*.toml` opening with the header.
209
+ *
210
+ * @param {string} destDir
211
+ * @returns {string[]}
212
+ */
213
+ export function listGeneratedCodexAgents(destDir) {
214
+ let names;
215
+ try {
216
+ names = fs.readdirSync(destDir);
217
+ } catch {
218
+ return [];
219
+ }
220
+ return names
221
+ .filter((f) => f.startsWith(CODEX_AGENT_PREFIX) && f.endsWith('.toml'))
222
+ .filter((f) => {
223
+ try {
224
+ return fs
225
+ .readFileSync(path.join(destDir, f), 'utf8')
226
+ .startsWith(CODEX_AGENT_HEADER);
227
+ } catch {
228
+ return false;
229
+ }
230
+ })
231
+ .sort();
232
+ }
233
+
234
+ /**
235
+ * Write the projection, reap header-bearing orphans, skip unchanged files.
236
+ *
237
+ * @param {{
238
+ * projectRoot: string,
239
+ * payloadSrc?: string,
240
+ * localSrc?: string,
241
+ * destDir?: string,
242
+ * log?: (line: string) => void,
243
+ * }} opts
244
+ * @returns {{ written: string[], removed: string[], total: number }}
245
+ */
246
+ export function syncCodexAgents({
247
+ projectRoot,
248
+ payloadSrc,
249
+ localSrc,
250
+ destDir = path.join(projectRoot, ...CODEX_AGENTS_DIR.split('/')),
251
+ log = () => {},
252
+ }) {
253
+ const expected = expectedCodexAgents({ projectRoot, payloadSrc, localSrc });
254
+
255
+ const removed = [];
256
+ for (const file of listGeneratedCodexAgents(destDir)) {
257
+ if (expected.has(file)) continue;
258
+ fs.rmSync(path.join(destDir, file), { force: true });
259
+ removed.push(file);
260
+ log(` removed ${CODEX_AGENTS_DIR}/${file} (no longer in .agents/agents)`);
261
+ }
262
+
263
+ const written = [];
264
+ for (const [file, body] of expected) {
265
+ const target = path.join(destDir, file);
266
+ let current = null;
267
+ try {
268
+ current = fs.readFileSync(target, 'utf8');
269
+ } catch {
270
+ // absent — written below
271
+ }
272
+ if (current === body) continue;
273
+ if (current !== null && !current.startsWith(CODEX_AGENT_HEADER)) {
274
+ throw new Error(
275
+ `codex agent projection: ${CODEX_AGENTS_DIR}/${file} is hand-authored — rename it; the mandrel- prefix is reserved.`,
276
+ );
277
+ }
278
+ fs.mkdirSync(destDir, { recursive: true });
279
+ fs.writeFileSync(target, body, 'utf8');
280
+ written.push(file);
281
+ log(` synced ${CODEX_AGENTS_DIR}/${file}`);
282
+ }
283
+ return { written, removed, total: expected.size };
284
+ }
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Codex skill projection of the workflow set: one
3
+ * `.agents/skills/workflows/<name>/SKILL.md` per projectable workflow, from the
4
+ * same source set and exclusions as the Claude command projection. Each skill
5
+ * is a pointer to its workflow file, never a copy. Node built-ins only, so
6
+ * the doctor registry can import it before third-party packages exist.
7
+ *
8
+ * @module codex/skills-projection
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+
14
+ import { isCommandExcluded } from '../command-header.js';
15
+ import { extractDescription } from '../mandrel-catalog.js';
16
+ import {
17
+ collectLocalSkillFiles,
18
+ collectSkillFiles,
19
+ } from '../skills/walk-skill-files.js';
20
+
21
+ /**
22
+ * Project-relative POSIX home of the projection. Outside the `core`/`stack`
23
+ * tiers, so the skills index never walks it; not dot-prefixed, because Codex
24
+ * skips hidden directories when it scans `.agents/skills/`.
25
+ */
26
+ export const CODEX_SKILLS_DIR = '.agents/skills/workflows';
27
+
28
+ /** Codex's skill-metadata limits. */
29
+ const CODEX_SKILL_NAME_MAX = 64;
30
+ const CODEX_SKILL_DESCRIPTION_MAX = 1024;
31
+
32
+ /** Every generated SKILL.md carries this; the reap touches nothing without it. */
33
+ const CODEX_SKILL_MARKER = '<!-- AUTO-GENERATED by mandrel';
34
+
35
+ const LOOPS_NS = 'loops';
36
+
37
+ /**
38
+ * @param {string} dir
39
+ * @returns {boolean}
40
+ */
41
+ function dirExists(dir) {
42
+ try {
43
+ return fs.statSync(dir).isDirectory();
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * @param {string} dir
51
+ * @param {(entry: import('node:fs').Dirent) => boolean} keep
52
+ * @returns {string[]}
53
+ */
54
+ function mdFilesIn(dir, keep) {
55
+ if (!dirExists(dir)) return [];
56
+ return fs
57
+ .readdirSync(dir, { withFileTypes: true })
58
+ .filter((e) => e.isFile() && e.name.endsWith('.md') && keep(e))
59
+ .map((e) => e.name)
60
+ .sort();
61
+ }
62
+
63
+ /**
64
+ * The workflows both projections expose: top-level `*.md` plus `loops/*.md`
65
+ * (minus its README) from the payload, then the local zone. The payload wins
66
+ * a collision; a `command: false` workflow is skipped.
67
+ *
68
+ * @param {{ payloadSrc: string, localSrc: string }} sources
69
+ * @returns {Array<{ name: string, sourcePath: string, content: string }>}
70
+ */
71
+ function listProjectableWorkflows({ payloadSrc, localSrc }) {
72
+ const byName = new Map();
73
+ for (const dir of [payloadSrc, localSrc]) {
74
+ const candidates = [
75
+ ...mdFilesIn(dir, () => true).map((f) => ({
76
+ name: f.replace(/\.md$/, ''),
77
+ sourcePath: path.join(dir, f),
78
+ })),
79
+ ...mdFilesIn(
80
+ path.join(dir, LOOPS_NS),
81
+ (e) => e.name.toLowerCase() !== 'readme.md',
82
+ ).map((f) => ({
83
+ name: `${LOOPS_NS}-${f.replace(/\.md$/, '')}`,
84
+ sourcePath: path.join(dir, LOOPS_NS, f),
85
+ })),
86
+ ];
87
+ for (const candidate of candidates) {
88
+ if (byName.has(candidate.name)) continue;
89
+ const content = fs.readFileSync(candidate.sourcePath, 'utf8');
90
+ if (isCommandExcluded(content)) continue;
91
+ byName.set(candidate.name, { ...candidate, content });
92
+ }
93
+ }
94
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
95
+ }
96
+
97
+ /**
98
+ * @param {string} projectRoot
99
+ * @param {string} absPath
100
+ * @returns {string}
101
+ */
102
+ function toPosixRelative(projectRoot, absPath) {
103
+ return path.relative(projectRoot, absPath).split(path.sep).join('/');
104
+ }
105
+
106
+ /**
107
+ * @param {string | null} description
108
+ * @param {string} name
109
+ * @returns {string}
110
+ */
111
+ function skillDescription(description, name) {
112
+ const text = description ?? `Run the Mandrel ${name} workflow.`;
113
+ return text.length > CODEX_SKILL_DESCRIPTION_MAX
114
+ ? `${text.slice(0, CODEX_SKILL_DESCRIPTION_MAX - 1)}…`
115
+ : text;
116
+ }
117
+
118
+ /**
119
+ * The SKILL.md for one workflow. `description` is a JSON string, which is
120
+ * also a valid YAML double-quoted scalar whatever the workflow text holds.
121
+ *
122
+ * @param {{ name: string, description: string | null, workflowPath: string }} input
123
+ * `workflowPath` is project-relative POSIX.
124
+ * @returns {string}
125
+ */
126
+ function renderCodexSkill({ name, description, workflowPath }) {
127
+ return [
128
+ '---',
129
+ `name: ${name}`,
130
+ `description: ${JSON.stringify(skillDescription(description, name))}`,
131
+ '---',
132
+ '',
133
+ `${CODEX_SKILL_MARKER} from ${workflowPath} — do not edit. Re-run: npm run sync:commands -->`,
134
+ '',
135
+ `# $${name}`,
136
+ '',
137
+ `Read \`${workflowPath}\` in full and execute it as the workflow for this`,
138
+ `request. Treat the text that follows \`$${name}\` in the request as the`,
139
+ "workflow's ARGUMENTS.",
140
+ '',
141
+ ].join('\n');
142
+ }
143
+
144
+ /**
145
+ * Every projected skill keyed by name, with the exact SKILL.md it should hold.
146
+ * Throws on a name Codex cannot load or that collides with an authored skill.
147
+ *
148
+ * @param {{ projectRoot: string, payloadSrc?: string, localSrc?: string }} opts
149
+ * @returns {Map<string, string>}
150
+ */
151
+ export function expectedCodexSkills({
152
+ projectRoot,
153
+ payloadSrc = path.join(projectRoot, '.agents', 'workflows'),
154
+ localSrc = path.join(projectRoot, '.agents', 'local', 'workflows'),
155
+ }) {
156
+ const expected = new Map();
157
+ for (const wf of listProjectableWorkflows({ payloadSrc, localSrc })) {
158
+ expected.set(
159
+ wf.name,
160
+ renderCodexSkill({
161
+ name: wf.name,
162
+ description: extractDescription(wf.content),
163
+ workflowPath: toPosixRelative(projectRoot, wf.sourcePath),
164
+ }),
165
+ );
166
+ }
167
+ assertProjectableNames(projectRoot, expected.keys());
168
+ return expected;
169
+ }
170
+
171
+ /**
172
+ * `name:` of a SKILL.md's front-matter, or null.
173
+ *
174
+ * @param {string} file
175
+ * @returns {string | null}
176
+ */
177
+ function skillNameOf(file) {
178
+ try {
179
+ const source = fs.readFileSync(file, 'utf8');
180
+ const fm = source.match(/^---\r?\n([\s\S]*?)\r?\n---/);
181
+ return fm?.[1].match(/^name:\s*["']?([^"'\s]+)/m)?.[1] ?? null;
182
+ } catch {
183
+ return null;
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Fails loudly on a projected name Codex cannot load or that would collide
189
+ * with a hand-authored payload or local skill.
190
+ *
191
+ * @param {string} projectRoot
192
+ * @param {Iterable<string>} names
193
+ */
194
+ function assertProjectableNames(projectRoot, names) {
195
+ const taken = new Map();
196
+ for (const file of [
197
+ ...collectSkillFiles(projectRoot),
198
+ ...collectLocalSkillFiles(projectRoot),
199
+ ]) {
200
+ const skillName = skillNameOf(file);
201
+ if (skillName) taken.set(skillName, toPosixRelative(projectRoot, file));
202
+ }
203
+ for (const name of names) {
204
+ if (name.length > CODEX_SKILL_NAME_MAX) {
205
+ throw new Error(
206
+ `codex skill projection: workflow name '${name}' exceeds Codex's ${CODEX_SKILL_NAME_MAX}-character skill-name limit.`,
207
+ );
208
+ }
209
+ if (taken.has(name)) {
210
+ throw new Error(
211
+ `codex skill projection: workflow '${name}' collides with the skill of the same name at ${taken.get(name)} — rename one of them.`,
212
+ );
213
+ }
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Generated skill directories currently on disk (marker-bearing only).
219
+ *
220
+ * @param {string} destDir
221
+ * @returns {string[]}
222
+ */
223
+ export function listGeneratedCodexSkills(destDir) {
224
+ if (!dirExists(destDir)) return [];
225
+ return fs
226
+ .readdirSync(destDir, { withFileTypes: true })
227
+ .filter((e) => e.isDirectory())
228
+ .map((e) => e.name)
229
+ .filter((name) => {
230
+ try {
231
+ return fs
232
+ .readFileSync(path.join(destDir, name, 'SKILL.md'), 'utf8')
233
+ .includes(CODEX_SKILL_MARKER);
234
+ } catch {
235
+ return false;
236
+ }
237
+ })
238
+ .sort();
239
+ }
240
+
241
+ /**
242
+ * Write the projection, reap marker-bearing orphans, skip unchanged files.
243
+ *
244
+ * @param {{
245
+ * projectRoot: string,
246
+ * payloadSrc?: string,
247
+ * localSrc?: string,
248
+ * destDir?: string,
249
+ * log?: (line: string) => void,
250
+ * }} opts
251
+ * @returns {{ written: string[], removed: string[], total: number }}
252
+ */
253
+ export function syncCodexSkills({
254
+ projectRoot,
255
+ payloadSrc,
256
+ localSrc,
257
+ destDir = path.join(projectRoot, ...CODEX_SKILLS_DIR.split('/')),
258
+ log = () => {},
259
+ }) {
260
+ const expected = expectedCodexSkills({ projectRoot, payloadSrc, localSrc });
261
+
262
+ const removed = [];
263
+ for (const name of listGeneratedCodexSkills(destDir)) {
264
+ if (expected.has(name)) continue;
265
+ fs.rmSync(path.join(destDir, name), { recursive: true, force: true });
266
+ removed.push(name);
267
+ log(` removed ${CODEX_SKILLS_DIR}/${name} (no longer in workflows)`);
268
+ }
269
+
270
+ const written = [];
271
+ for (const [name, body] of expected) {
272
+ const file = path.join(destDir, name, 'SKILL.md');
273
+ let current = null;
274
+ try {
275
+ current = fs.readFileSync(file, 'utf8');
276
+ } catch {
277
+ // absent — written below
278
+ }
279
+ if (current === body) continue;
280
+ if (current !== null && !current.includes(CODEX_SKILL_MARKER)) {
281
+ throw new Error(
282
+ `codex skill projection: ${CODEX_SKILLS_DIR}/${name}/SKILL.md is hand-authored — move it out of the generated directory.`,
283
+ );
284
+ }
285
+ fs.mkdirSync(path.dirname(file), { recursive: true });
286
+ fs.writeFileSync(file, body, 'utf8');
287
+ written.push(name);
288
+ log(` synced ${CODEX_SKILLS_DIR}/${name}`);
289
+ }
290
+ return { written, removed, total: expected.size };
291
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The `.agentrc.local.json` overlay, shared by the runtime resolver and the
3
+ * read-only `sync-agentrc` check so both validate the same effective config.
4
+ */
5
+
6
+ import path from 'node:path';
7
+
8
+ const LOCAL_AGENTRC = '.agentrc.local.json';
9
+
10
+ function isPlainObject(value) {
11
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
12
+ }
13
+
14
+ /**
15
+ * Deep-merge plain objects for the overlay. Arrays and scalars from
16
+ * `override` replace the base value at that key.
17
+ *
18
+ * @param {unknown} base
19
+ * @param {unknown} override
20
+ * @returns {unknown}
21
+ */
22
+ export function deepMergeObjects(base, override) {
23
+ if (!isPlainObject(override)) return override;
24
+ if (!isPlainObject(base)) return { ...override };
25
+ const out = { ...base };
26
+ for (const key of Object.keys(override)) {
27
+ out[key] = mergeValue(base[key], override[key]);
28
+ }
29
+ return out;
30
+ }
31
+
32
+ function mergeValue(baseVal, overrideVal) {
33
+ if (isPlainObject(overrideVal) && isPlainObject(baseVal)) {
34
+ return deepMergeObjects(baseVal, overrideVal);
35
+ }
36
+ return overrideVal;
37
+ }
38
+
39
+ /**
40
+ * Merge the project's overlay, when present, over the committed config.
41
+ * Throws a parse error naming `.agentrc.local.json`.
42
+ *
43
+ * @param {{ fsImpl: typeof import('node:fs'), projectRoot: string, committed: object }} opts
44
+ * @returns {{ effective: object, localPath: string|null }}
45
+ */
46
+ export function applyLocalOverlay({ fsImpl, projectRoot, committed }) {
47
+ const localPath = path.join(projectRoot, LOCAL_AGENTRC);
48
+ if (!fsImpl.existsSync(localPath)) {
49
+ return { effective: committed, localPath: null };
50
+ }
51
+ const local = parseOverlay(fsImpl, localPath);
52
+ return { effective: deepMergeObjects(committed, local), localPath };
53
+ }
54
+
55
+ function parseOverlay(fsImpl, localPath) {
56
+ try {
57
+ return JSON.parse(fsImpl.readFileSync(localPath, 'utf8'));
58
+ } catch (err) {
59
+ const wrapped = new Error(
60
+ `Failed to parse ${LOCAL_AGENTRC}: ${err.message}`,
61
+ );
62
+ wrapped.localPath = localPath;
63
+ throw wrapped;
64
+ }
65
+ }
66
+
67
+ const OPERATOR_HANDLE_REMEDY = `set github.operatorHandle in the gitignored ${LOCAL_AGENTRC} (per-operator), or keep the "@[USERNAME]" placeholder committed in .agentrc.json`;
68
+
69
+ function isMissingOperatorHandle(e) {
70
+ return (
71
+ e.keyword === 'required' &&
72
+ e.instancePath === '/github' &&
73
+ e.params?.missingProperty === 'operatorHandle'
74
+ );
75
+ }
76
+
77
+ /**
78
+ * Render AJV errors for an `.agentrc` validation failure, one string per
79
+ * error. A missing `github.operatorHandle` carries where to put it.
80
+ *
81
+ * @param {Array<{ instancePath?: string, message?: string, keyword?: string, params?: object }>|null|undefined} errors
82
+ * @returns {string[]}
83
+ */
84
+ export function formatAgentrcErrors(errors) {
85
+ return (errors || []).map((e) => {
86
+ const line = `${e.instancePath || '(root)'} ${e.message}`;
87
+ return isMissingOperatorHandle(e)
88
+ ? `${line} — ${OPERATOR_HANDLE_REMEDY}`
89
+ : line;
90
+ });
91
+ }