mandrel 2.82.0 → 2.84.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.
- package/.agents/README.md +65 -20
- package/.agents/docs/configuration.md +40 -3
- package/.agents/docs/runbooks/mods.md +98 -54
- package/.agents/docs/workflows.md +14 -0
- package/.agents/instructions.md +4 -1
- package/.agents/mods/mandrel-status/hooks/register.tsx +579 -204
- package/.agents/mods/mandrel-status/types/index.d.ts +58 -13
- package/.agents/schemas/agentrc.schema.json +1 -1
- package/.agents/scripts/boot-sweep.js +42 -13
- package/.agents/scripts/coverage-capture.js +55 -24
- package/.agents/scripts/evidence-gate.js +7 -1
- package/.agents/scripts/generate-workflows-doc.js +14 -0
- package/.agents/scripts/lib/baselines/duplication-scanner.js +26 -2
- package/.agents/scripts/lib/bootstrap/agents-md-fold.js +99 -16
- package/.agents/scripts/lib/bootstrap/manifest.js +4 -4
- package/.agents/scripts/lib/bootstrap/project-bootstrap.js +16 -1
- package/.agents/scripts/lib/close-lock-events.js +109 -0
- package/.agents/scripts/lib/close-validation/commands.js +12 -0
- package/.agents/scripts/lib/close-validation/gates.js +6 -0
- package/.agents/scripts/lib/close-validation/process.js +5 -2
- package/.agents/scripts/lib/close-validation/runner.js +14 -4
- package/.agents/scripts/lib/codex/agents-projection.js +284 -0
- package/.agents/scripts/lib/codex/skills-projection.js +291 -0
- package/.agents/scripts/lib/config/agentrc-overlay.js +91 -0
- package/.agents/scripts/lib/config/sync-agentrc.js +39 -19
- package/.agents/scripts/lib/config-resolver.js +5 -42
- package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
- package/.agents/scripts/lib/config-settings-schema.js +1 -1
- package/.agents/scripts/lib/full-suite-lock.js +20 -0
- package/.agents/scripts/lib/full-suite-queue.js +24 -56
- package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
- package/.agents/scripts/lib/observability/source-classifier.js +2 -0
- package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +152 -0
- package/.agents/scripts/lib/orchestration/review-providers/codex.js +33 -105
- package/.agents/scripts/lib/orchestration/review-providers/provider-severity.js +30 -0
- package/.agents/scripts/lib/orchestration/review-providers/security-review.js +3 -17
- package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +73 -63
- package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +70 -0
- package/.agents/scripts/lib/orchestration/single-story-close/runner.js +3 -0
- package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +89 -0
- package/.agents/scripts/lib/supervised-suite.js +8 -28
- package/.agents/scripts/single-story-init.js +20 -5
- package/.agents/scripts/sync-agentrc.js +5 -3
- package/.agents/scripts/sync-claude-agents.js +20 -0
- package/.agents/scripts/sync-claude-commands.js +64 -27
- package/.agents/scripts/sync-codex-agents.js +36 -0
- package/.agents/scripts/sync-codex-skills.js +36 -0
- package/.agents/workflows/helpers/mandrel-sync-config.md +16 -9
- package/.agents/workflows/mandrel-update.md +2 -1
- package/README.md +167 -216
- package/docs/CHANGELOG.md +25 -0
- package/lib/cli/guarded-sync.js +3 -2
- package/lib/cli/registry.js +248 -0
- package/lib/cli/sync-agents.js +5 -2
- package/lib/cli/sync-commands.js +5 -2
- package/lib/cli/sync.js +45 -14
- package/lib/cli/uninstall.js +8 -1
- package/lib/migrations/index.js +2 -0
- package/lib/migrations/steps/2.84.0-hoist-system-prompt-block.js +64 -0
- package/package.json +3 -2
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
SYSTEM_PROMPT_BLOCK,
|
|
16
16
|
SYSTEM_PROMPT_ENTRY_DOC,
|
|
17
17
|
SYSTEM_PROMPT_IMPORT,
|
|
18
|
+
SYSTEM_PROMPT_READ_DIRECTIVE,
|
|
18
19
|
wireEntryDoc,
|
|
19
20
|
} from './agents-md-fold.js';
|
|
20
21
|
import { LEDGER_RELATIVE_PATH } from './install-ledger.js';
|
|
@@ -42,7 +43,11 @@ const PREPARE_GUARD = `node -e "process.exit(require('fs').existsSync('.agents/s
|
|
|
42
43
|
/** The `prepare` script bootstrap writes: guarded, then both projections. */
|
|
43
44
|
export const PREPARE_COMMAND = `${PREPARE_GUARD} || (${LEGACY_PREPARE_COMMAND})`;
|
|
44
45
|
|
|
45
|
-
export {
|
|
46
|
+
export {
|
|
47
|
+
SYSTEM_PROMPT_BLOCK,
|
|
48
|
+
SYSTEM_PROMPT_IMPORT,
|
|
49
|
+
SYSTEM_PROMPT_READ_DIRECTIVE,
|
|
50
|
+
};
|
|
46
51
|
|
|
47
52
|
/** Install template for a fresh AGENTS.md (also the legacy CLAUDE.md one). */
|
|
48
53
|
export const SYSTEM_PROMPT_AGENTS_MD = SYSTEM_PROMPT_ENTRY_DOC;
|
|
@@ -58,6 +63,16 @@ export const GITIGNORE_BLOCKS = Object.freeze({
|
|
|
58
63
|
block:
|
|
59
64
|
'\n# Claude Code agent projection is generated from .agents/agents/ by `prepare` — do not commit.\n.claude/agents/\n',
|
|
60
65
|
},
|
|
66
|
+
codexSkills: {
|
|
67
|
+
pattern: /^\s*\/?\.agents\/skills\/workflows\/?\s*$/m,
|
|
68
|
+
block:
|
|
69
|
+
'\n# Codex skill projection is generated from .agents/workflows/ — do not commit.\n.agents/skills/workflows/\n',
|
|
70
|
+
},
|
|
71
|
+
codexAgents: {
|
|
72
|
+
pattern: /^\s*\/?\.codex\/agents\/mandrel-\*\.toml\s*$/m,
|
|
73
|
+
block:
|
|
74
|
+
'\n# Codex agent projection is generated from .agents/agents/ — do not commit.\n.codex/agents/mandrel-*.toml\n',
|
|
75
|
+
},
|
|
61
76
|
mcp: {
|
|
62
77
|
pattern: /^\s*\.mcp\.json\s*$/m,
|
|
63
78
|
block:
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Close's lock-wait and suite-timing figures, as NDJSON in a per-close file
|
|
3
|
+
* (never gate output, which tests can forge). A child claims the env var
|
|
4
|
+
* before spawning, so no suite process can write to it.
|
|
5
|
+
*/
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
|
|
11
|
+
const CLOSE_LOCK_EVENTS_FILE_ENV = 'MANDREL_CLOSE_LOCK_EVENTS_FILE';
|
|
12
|
+
|
|
13
|
+
const EVENT_KINDS = new Set(['lock-wait', 'suite-timings']);
|
|
14
|
+
|
|
15
|
+
function appendEvent(file, event, fsImpl) {
|
|
16
|
+
try {
|
|
17
|
+
fsImpl.appendFileSync(file, `${JSON.stringify(event)}\n`);
|
|
18
|
+
} catch {}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function parseEventLine(line) {
|
|
22
|
+
try {
|
|
23
|
+
const event = JSON.parse(line);
|
|
24
|
+
return EVENT_KINDS.has(event?.kind) ? event : null;
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** @param {{ dir?: string, fsImpl?: object }} [opts] */
|
|
31
|
+
export function createLockEventChannel({
|
|
32
|
+
dir = os.tmpdir(),
|
|
33
|
+
fsImpl = fs,
|
|
34
|
+
} = {}) {
|
|
35
|
+
const name = `mandrel-lock-events-${process.pid}-${crypto.randomBytes(6).toString('hex')}.ndjson`;
|
|
36
|
+
const file = path.join(dir, name);
|
|
37
|
+
return {
|
|
38
|
+
file,
|
|
39
|
+
env: { [CLOSE_LOCK_EVENTS_FILE_ENV]: file },
|
|
40
|
+
emit: (event) => appendEvent(file, event, fsImpl),
|
|
41
|
+
read: () => readEvents(file, fsImpl),
|
|
42
|
+
dispose() {
|
|
43
|
+
try {
|
|
44
|
+
fsImpl.rmSync(file, { force: true });
|
|
45
|
+
} catch {}
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readEvents(file, fsImpl) {
|
|
51
|
+
let text;
|
|
52
|
+
try {
|
|
53
|
+
text = fsImpl.readFileSync(file, 'utf8');
|
|
54
|
+
} catch {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
return text.split('\n').filter(Boolean).map(parseEventLine).filter(Boolean);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Remove the channel from `env` and return its emitter (a no-op without one).
|
|
62
|
+
*
|
|
63
|
+
* @param {Record<string, string|undefined>} [env]
|
|
64
|
+
* @param {{ fsImpl?: object }} [opts]
|
|
65
|
+
* @returns {(event: object) => void}
|
|
66
|
+
*/
|
|
67
|
+
export function claimLockEventSink(env = process.env, { fsImpl = fs } = {}) {
|
|
68
|
+
const file = env[CLOSE_LOCK_EVENTS_FILE_ENV];
|
|
69
|
+
delete env[CLOSE_LOCK_EVENTS_FILE_ENV];
|
|
70
|
+
if (!file) return () => {};
|
|
71
|
+
return (event) => appendEvent(file, event, fsImpl);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Waits sum, an expiry sticks, the last holder wins; timings are the last.
|
|
76
|
+
*
|
|
77
|
+
* @param {object[]} events
|
|
78
|
+
* @returns {{ lockWait: object|null, suiteTimings: object|null }}
|
|
79
|
+
*/
|
|
80
|
+
export function summarizeLockEvents(events) {
|
|
81
|
+
let lockWait = null;
|
|
82
|
+
let suiteTimings = null;
|
|
83
|
+
for (const event of events) {
|
|
84
|
+
if (event.kind === 'lock-wait') lockWait = mergeLockWait(lockWait, event);
|
|
85
|
+
else suiteTimings = timingsOf(event);
|
|
86
|
+
}
|
|
87
|
+
return { lockWait, suiteTimings };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function mergeLockWait(tally, event) {
|
|
91
|
+
const holder = event.holder ?? tally?.holder;
|
|
92
|
+
return {
|
|
93
|
+
waitedSeconds: (tally?.waitedSeconds ?? 0) + Number(event.waitedSeconds),
|
|
94
|
+
expired: Boolean(tally?.expired) || event.expired === true,
|
|
95
|
+
...(holder ? { holder } : {}),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function timingsOf({ lockWaitMs, hostWaitMs, testRunMs }) {
|
|
100
|
+
return { lockWaitMs, hostWaitMs: hostWaitMs ?? null, testRunMs };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** @param {(event: object) => void} emit */
|
|
104
|
+
export function lockEventHooks(emit) {
|
|
105
|
+
return {
|
|
106
|
+
onLockOutcome: (outcome) => emit({ kind: 'lock-wait', ...outcome }),
|
|
107
|
+
onTimings: (timings) => emit({ kind: 'suite-timings', ...timings }),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
@@ -60,6 +60,18 @@ export function resolveTypecheckCommand(config) {
|
|
|
60
60
|
return resolveCommandWithFallback(config, 'typecheck', TYPECHECK_FALLBACK);
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
/**
|
|
64
|
+
* Own-present explicit `null` only: `getCommands` collapses absent and `null`.
|
|
65
|
+
*
|
|
66
|
+
* @param {{ project?: { commands?: object } } | null | undefined} config
|
|
67
|
+
* @returns {boolean}
|
|
68
|
+
*/
|
|
69
|
+
export function isTypecheckDisabled(config) {
|
|
70
|
+
const commands = config?.project?.commands;
|
|
71
|
+
if (commands === null || typeof commands !== 'object') return false;
|
|
72
|
+
return Object.hasOwn(commands, 'typecheck') && commands.typecheck === null;
|
|
73
|
+
}
|
|
74
|
+
|
|
63
75
|
/**
|
|
64
76
|
* A consumer may point this at its hooks' scoped lint; CI keeps whole-repo drift.
|
|
65
77
|
*
|
|
@@ -12,6 +12,7 @@ import { predictsTestEvidenceCredit } from '../test-run-credit.js';
|
|
|
12
12
|
import {
|
|
13
13
|
buildFormatHint,
|
|
14
14
|
FORMAT_CHECK_FALLBACK,
|
|
15
|
+
isTypecheckDisabled,
|
|
15
16
|
resolveFormatCheckCommand,
|
|
16
17
|
resolveFormatWriteCommand,
|
|
17
18
|
resolveLintCommand,
|
|
@@ -28,6 +29,7 @@ import {
|
|
|
28
29
|
* @property {{ baseRef: string }} [changedFileScope]
|
|
29
30
|
* @property {{ reason: string }} [skip] - Pre-decided skip: recorded, never spawned.
|
|
30
31
|
* @property {Record<string, string>} [env] - Overlay merged over `process.env` for this gate's child only.
|
|
32
|
+
* @property {boolean} [lockEventChannel] - The child reports on close's lock-event channel.
|
|
31
33
|
* @property {(cmd: string, args: string[], opts: { cwd: string, gateName?: string, log?: (m: string) => void, signal?: AbortSignal, env?: Record<string, string> }) => Promise<{ status: number }> | { status: number }} [run]
|
|
32
34
|
* - In-process runner used instead of spawning `cmd`/`args`.
|
|
33
35
|
*/
|
|
@@ -487,6 +489,9 @@ export function buildDefaultGates({
|
|
|
487
489
|
cmd: typecheck.cmd,
|
|
488
490
|
args: typecheck.args,
|
|
489
491
|
hint: TYPECHECK_HINT,
|
|
492
|
+
...(isTypecheckDisabled(config)
|
|
493
|
+
? { skip: { reason: 'typecheck-disabled' } }
|
|
494
|
+
: {}),
|
|
490
495
|
},
|
|
491
496
|
// Gate names stay generic though commands resolve from config, so the
|
|
492
497
|
// log line, evidence keyspace and partition membership never shift.
|
|
@@ -516,6 +521,7 @@ export function buildDefaultGates({
|
|
|
516
521
|
cmd: 'node',
|
|
517
522
|
args: [...COVERAGE_CAPTURE_ARGS],
|
|
518
523
|
hint: COVERAGE_CAPTURE_HINT,
|
|
524
|
+
lockEventChannel: true,
|
|
519
525
|
...(captureSkipPredicted
|
|
520
526
|
? { skip: { reason: 'incremental-no-crap-changes' } }
|
|
521
527
|
: {}),
|
|
@@ -81,12 +81,12 @@ function isBiomeNoFilesProcessed(output) {
|
|
|
81
81
|
* nothing and returns `LOCK_WAIT_EXPIRED_EXIT_CODE`, so close ends
|
|
82
82
|
* `pending`. A full-suite gate's timeout is armed at spawn, re-armed on the
|
|
83
83
|
* suite-ready handshake, and its lock wait, host wait and test run are logged
|
|
84
|
-
* as three figures. Each child leads its own process group so a timeout,
|
|
84
|
+
* as three figures, and both reach `onLockEvent` as structured events. Each child leads its own process group so a timeout,
|
|
85
85
|
* abort or parent signal kills its workers too.
|
|
86
86
|
*
|
|
87
87
|
* @param {string} cmd
|
|
88
88
|
* @param {string[]} args
|
|
89
|
-
* @param {{ cwd: string, signal?: AbortSignal, gateName?: string, log?: (m: string) => void, env?: Record<string, string>, tolerateNoFilesProcessed?: boolean, fullSuiteLock?: boolean, timeoutMs?: number, lockOptions?: object, skipIfSatisfied?: () => {status: number}|undefined }} opts
|
|
89
|
+
* @param {{ cwd: string, signal?: AbortSignal, gateName?: string, log?: (m: string) => void, env?: Record<string, string>, tolerateNoFilesProcessed?: boolean, fullSuiteLock?: boolean, timeoutMs?: number, lockOptions?: object, onLockEvent?: (event: object) => void, skipIfSatisfied?: () => {status: number}|undefined }} opts
|
|
90
90
|
* @returns {Promise<{ status: number }>}
|
|
91
91
|
*/
|
|
92
92
|
export function defaultGateRunner(cmd, args, opts = {}) {
|
|
@@ -106,6 +106,9 @@ function gateLockOptions(opts) {
|
|
|
106
106
|
log: opts.log,
|
|
107
107
|
skipIfSatisfied: opts.skipIfSatisfied,
|
|
108
108
|
onWaitExpired: deferredGateStatus,
|
|
109
|
+
onLockOutcome: opts.onLockEvent
|
|
110
|
+
? (outcome) => opts.onLockEvent({ kind: 'lock-wait', ...outcome })
|
|
111
|
+
: undefined,
|
|
109
112
|
...opts.lockOptions, // `rerunCommand`, plus test seams
|
|
110
113
|
};
|
|
111
114
|
}
|
|
@@ -123,6 +123,7 @@ function applyChangedFileScope({ gate, spawnCwd, log }) {
|
|
|
123
123
|
* runProjections?: typeof defaultRunProjections,
|
|
124
124
|
* runner?: (cmd: string, args: string[], opts: { cwd: string, signal?: AbortSignal, gateName?: string, log?: (m: string) => void }) => Promise<{ status: number }> | { status: number },
|
|
125
125
|
* log?: (m: string) => void,
|
|
126
|
+
* lockEvents?: object|null,
|
|
126
127
|
* onGateStart?: (gate: Gate) => void,
|
|
127
128
|
* storyId?: number|null,
|
|
128
129
|
* standalone?: boolean,
|
|
@@ -143,6 +144,7 @@ export async function runCloseValidation({
|
|
|
143
144
|
gates = DEFAULT_GATES,
|
|
144
145
|
runner = defaultGateRunner,
|
|
145
146
|
log = () => {},
|
|
147
|
+
lockEvents = null,
|
|
146
148
|
onGateStart,
|
|
147
149
|
baseBranch = null,
|
|
148
150
|
storyBranch = null,
|
|
@@ -159,7 +161,7 @@ export async function runCloseValidation({
|
|
|
159
161
|
shouldSkip = defaultShouldSkip,
|
|
160
162
|
} = {}) {
|
|
161
163
|
const failed = [];
|
|
162
|
-
const lockOpts = fullSuiteLockOptions({ config });
|
|
164
|
+
const lockOpts = fullSuiteLockOptions({ config, lockEvents });
|
|
163
165
|
const skipped = [];
|
|
164
166
|
const evidenceActive = useEvidence && storyId != null && standalone;
|
|
165
167
|
const evidenceStoreOpts = { cwd, standalone };
|
|
@@ -359,21 +361,29 @@ export async function runCloseValidation({
|
|
|
359
361
|
* (`coverage.timeoutMs`) so a hung suite fails instead of holding the host
|
|
360
362
|
* lock; the same figure bounds its lock wait (`resolveFullSuiteLockBudget`).
|
|
361
363
|
*
|
|
362
|
-
* @param {{ config: object|null }} args
|
|
364
|
+
* @param {{ config: object|null, lockEvents: object|null }} args
|
|
363
365
|
* @returns {{ forGate: (gate: object) => object }}
|
|
364
366
|
*/
|
|
365
|
-
function fullSuiteLockOptions({ config }) {
|
|
367
|
+
function fullSuiteLockOptions({ config, lockEvents }) {
|
|
366
368
|
const timeoutMs = getQuality(config).coverage?.timeoutMs;
|
|
367
369
|
return {
|
|
368
370
|
forGate(gate) {
|
|
371
|
+
const env = gateEnv(gate, lockEvents);
|
|
369
372
|
return {
|
|
370
|
-
...(
|
|
373
|
+
...(env ? { env } : {}),
|
|
374
|
+
...(lockEvents ? { onLockEvent: lockEvents.emit } : {}),
|
|
371
375
|
...(gate.fullSuiteLock ? fullSuiteGateOptions(gate, timeoutMs) : {}),
|
|
372
376
|
};
|
|
373
377
|
},
|
|
374
378
|
};
|
|
375
379
|
}
|
|
376
380
|
|
|
381
|
+
/** Any child but a `lockEventChannel` one would leak the channel to tests. */
|
|
382
|
+
function gateEnv(gate, lockEvents) {
|
|
383
|
+
if (!(gate.lockEventChannel && lockEvents)) return gate.env;
|
|
384
|
+
return { ...lockEvents.env, ...gate.env };
|
|
385
|
+
}
|
|
386
|
+
|
|
377
387
|
/**
|
|
378
388
|
* A full-suite gate's kill bound, and the command its lock-expiry line names.
|
|
379
389
|
*
|
|
@@ -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
|
+
}
|