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.
Files changed (60) hide show
  1. package/.agents/README.md +65 -20
  2. package/.agents/docs/configuration.md +40 -3
  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/agentrc.schema.json +1 -1
  9. package/.agents/scripts/boot-sweep.js +42 -13
  10. package/.agents/scripts/coverage-capture.js +55 -24
  11. package/.agents/scripts/evidence-gate.js +7 -1
  12. package/.agents/scripts/generate-workflows-doc.js +14 -0
  13. package/.agents/scripts/lib/baselines/duplication-scanner.js +26 -2
  14. package/.agents/scripts/lib/bootstrap/agents-md-fold.js +99 -16
  15. package/.agents/scripts/lib/bootstrap/manifest.js +4 -4
  16. package/.agents/scripts/lib/bootstrap/project-bootstrap.js +16 -1
  17. package/.agents/scripts/lib/close-lock-events.js +109 -0
  18. package/.agents/scripts/lib/close-validation/commands.js +12 -0
  19. package/.agents/scripts/lib/close-validation/gates.js +6 -0
  20. package/.agents/scripts/lib/close-validation/process.js +5 -2
  21. package/.agents/scripts/lib/close-validation/runner.js +14 -4
  22. package/.agents/scripts/lib/codex/agents-projection.js +284 -0
  23. package/.agents/scripts/lib/codex/skills-projection.js +291 -0
  24. package/.agents/scripts/lib/config/agentrc-overlay.js +91 -0
  25. package/.agents/scripts/lib/config/sync-agentrc.js +39 -19
  26. package/.agents/scripts/lib/config-resolver.js +5 -42
  27. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  28. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  29. package/.agents/scripts/lib/full-suite-lock.js +20 -0
  30. package/.agents/scripts/lib/full-suite-queue.js +24 -56
  31. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  32. package/.agents/scripts/lib/observability/source-classifier.js +2 -0
  33. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +152 -0
  34. package/.agents/scripts/lib/orchestration/review-providers/codex.js +33 -105
  35. package/.agents/scripts/lib/orchestration/review-providers/provider-severity.js +30 -0
  36. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +3 -17
  37. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +73 -63
  38. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +70 -0
  39. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +3 -0
  40. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +89 -0
  41. package/.agents/scripts/lib/supervised-suite.js +8 -28
  42. package/.agents/scripts/single-story-init.js +20 -5
  43. package/.agents/scripts/sync-agentrc.js +5 -3
  44. package/.agents/scripts/sync-claude-agents.js +20 -0
  45. package/.agents/scripts/sync-claude-commands.js +64 -27
  46. package/.agents/scripts/sync-codex-agents.js +36 -0
  47. package/.agents/scripts/sync-codex-skills.js +36 -0
  48. package/.agents/workflows/helpers/mandrel-sync-config.md +16 -9
  49. package/.agents/workflows/mandrel-update.md +2 -1
  50. package/README.md +167 -216
  51. package/docs/CHANGELOG.md +25 -0
  52. package/lib/cli/guarded-sync.js +3 -2
  53. package/lib/cli/registry.js +248 -0
  54. package/lib/cli/sync-agents.js +5 -2
  55. package/lib/cli/sync-commands.js +5 -2
  56. package/lib/cli/sync.js +45 -14
  57. package/lib/cli/uninstall.js +8 -1
  58. package/lib/migrations/index.js +2 -0
  59. package/lib/migrations/steps/2.84.0-hoist-system-prompt-block.js +64 -0
  60. package/package.json +3 -2
@@ -7,12 +7,21 @@ export type StageName =
7
7
  | 'close'
8
8
  | 'merge';
9
9
 
10
+ /**
11
+ * What the band says about a Story; it picks the glyph, the color and whether
12
+ * a second line shows. `needs-you` is a `blocked` result (the HITL pause);
13
+ * `failed` is a `failed` / `escalated` result or a PR whose checks are red.
14
+ */
15
+ export type Attention = 'working' | 'slow' | 'needs-you' | 'failed' | 'landed';
16
+
10
17
  /** One stage as the Details pane lists it; times in epoch milliseconds. */
11
18
  export type StageRow = {
12
19
  name: StageName;
13
20
  startedAt: number | null;
14
21
  /** The next stage's start, or null while this one is current or pending. */
15
22
  endedAt: number | null;
23
+ /** The learned median of the stage, once it has 3+ samples. */
24
+ usualMs: number | null;
16
25
  };
17
26
 
18
27
  /** One close phase: its recorded duration and the learned median, in seconds. */
@@ -28,23 +37,32 @@ export type Focus = {
28
37
  title: string | null;
29
38
  /** `in-flight`, or the terminal envelope's `status`. */
30
39
  status: string;
40
+ attention: Attention;
31
41
  stage: StageName;
32
- /** The current stage's step detail, already worded. */
33
- detail: string;
42
+ /** The current stage's step, already worded: `check · round 2 · 5/6 met`. */
43
+ step: string;
44
+ /** The last commit subject, shown only in the Details pane. */
45
+ subject: string | null;
34
46
  stages: StageRow[];
35
- handoffSteps: { name: string; at: number }[];
36
47
  closePhases: PhaseRow[];
37
48
  prNumber: number | null;
49
+ /** The PR's web address: the envelope's `pr.url`, else built from `github`. */
50
+ prUrl: string | null;
38
51
  checksStatus: string | null;
39
52
  /** The envelope's `elapsedSeconds`, for a finished result. */
40
53
  elapsedSeconds: number | null;
41
54
  /** Milliseconds into the current phase, while in flight. */
42
55
  phaseElapsedMs: number | null;
43
- /** The learned median of the current phase, once it has 3+ samples. */
56
+ /** The learned median of the current phase or stage, once it has 3+ samples. */
44
57
  usualMs: number | null;
45
- isStalled: boolean;
46
- /** Minutes the gate log has been quiet, when the 10-minute rule fired. */
47
- idleMinutes: number | null;
58
+ /** The close phase being timed, when the stage has one. */
59
+ phase: string | null;
60
+ /** Minutes the close-gates log has been quiet, while in close. */
61
+ quietMinutes: number | null;
62
+ /** The gate named by the close-gates log's last line, while in close. */
63
+ lastGate: string | null;
64
+ /** 1-based ids of the newest verdict round's criteria not `met`. */
65
+ unmet: number[];
48
66
  /** `blocked.blockClass` or `failure.reason`. */
49
67
  problem: string | null;
50
68
  nextCommand: string | null;
@@ -52,12 +70,33 @@ export type Focus = {
52
70
  followUps: number | null;
53
71
  };
54
72
 
73
+ /** How one ledger Story reads as a run chip. */
74
+ export type ChipState =
75
+ | 'landed'
76
+ | 'needs-you'
77
+ | 'failed'
78
+ | 'focus'
79
+ | 'in-flight'
80
+ | 'undispatched';
81
+
82
+ /** A Story that ended without landing, named by the run roll-up. */
83
+ export type Straggler = {
84
+ storyId: number;
85
+ attention: 'needs-you' | 'failed';
86
+ /** The envelope's `phase`: where it stopped. */
87
+ phase: string | null;
88
+ };
89
+
55
90
  /** The newest live multi-Story run ledger. */
56
91
  export type RunLine = {
57
92
  landed: number;
58
93
  total: number;
59
- current: { storyId: number; stage: string } | null;
60
- queued: number;
94
+ chips: { storyId: number; state: ChipState }[];
95
+ /** True once every ledger Story has a terminal envelope. */
96
+ isDone: boolean;
97
+ /** From the earliest start to the newest result, once done. */
98
+ spanMs: number | null;
99
+ straggler: Straggler | null;
61
100
  };
62
101
 
63
102
  export type Snapshot = {
@@ -74,17 +113,23 @@ export type Learned = {
74
113
  phases: Record<string, { medianSeconds: number; samples: number }>;
75
114
  };
76
115
 
116
+ /** The followed Story and stage of the last scan, to see a stage finish. */
117
+ export type Tracked = { storyId: number; stage: StageName };
118
+
77
119
  declare module 'claude-code' {
78
120
  interface PluginState {
79
121
  'mandrel-status': {
80
122
  snapshot: Snapshot;
81
- /** `<storyId>:<mtimeMs>` of every envelope already seen. */
123
+ /** Envelope keys and `<storyId>:slow` of everything already toasted or recorded. */
82
124
  seen: string[];
83
- /** False until the first scan, which records envelopes without a toast. */
125
+ /** False until the first scan, which records without a toast. */
84
126
  isSeeded: boolean;
85
127
  learned: Learned;
86
- /** The focus Story the person hid the band for; it shows again on a new one. */
87
- hiddenFor: number | null;
128
+ /** Durations in seconds of finished stages this mod watched, newest 30 each. */
129
+ stageSamples: Partial<Record<StageName, number[]>>;
130
+ tracked: Tracked | null;
131
+ /** `<band key>:<attention>` the person hid; any change shows the band again. */
132
+ hiddenFor: string | null;
88
133
  };
89
134
  }
90
135
  }
@@ -91,7 +91,7 @@
91
91
  "type": "string",
92
92
  "pattern": "([;&|`]|\\$\\()"
93
93
  },
94
- "description": "Static type-check command. `null` disables the gate for projects with no type layer; the empty string is rejected so a typo cannot silently disable it.",
94
+ "description": "Static type-check command run as a close-validation gate. Left unset (the `null` default), it falls back to `npm run typecheck`. An explicit `null` disables the gate for projects with no type layer: close reports it as skipped (`typecheck-disabled`) and runs nothing. The empty string is rejected so a typo cannot silently disable it.",
95
95
  "default": null
96
96
  },
97
97
  "lint": {
@@ -12,6 +12,9 @@
12
12
  * trees whose Story is closed or `agent::done` are removed; an open Story's
13
13
  * tree and the tree this process runs from are never touched.
14
14
  *
15
+ * Then it flips closed Stories stranded at `agent::closing` to
16
+ * `agent::done` (`closingReconcile`).
17
+ *
15
18
  * `content-merged` branches (merge-tree equivalence — no merge check ever
16
19
  * validated their exact diff) are never reaped here, only reported for
17
20
  * `/clean-git`.
@@ -26,6 +29,7 @@ import { Logger } from './lib/Logger.js';
26
29
  import { sweepStaleStoryWorktrees } from './lib/orchestration/plan-runner/worktree-sweep.js';
27
30
  import { createProvider } from './lib/provider-factory.js';
28
31
  import { buildProtectionCtx } from './lib/single-story-sweep/protection-ctx.js';
32
+ import { reconcileStrandedClosing } from './lib/single-story-sweep/reconcile-closing.js';
29
33
  import {
30
34
  acquireSweepLock,
31
35
  resolveSweepLockPath,
@@ -58,6 +62,9 @@ worktree, still-open parent Story), then fast-forwards the base branch.
58
62
  Then removes every .worktrees/story-<id> tree whose Story is closed or
59
63
  agent::done (never an open Story's, never the tree this process runs from);
60
64
  the outcome lands under "worktreeSweep".
65
+ Then flips closed Stories still labelled agent::closing whose story-<id> PR
66
+ is MERGED to agent::done (at most 10 per run); the outcome lands under
67
+ "closingReconcile".
61
68
  Branches detected only via the weaker content-equivalence signal
62
69
  (detectedBy: 'content-merged') are never reaped here — they are reported
63
70
  under "contentMerged" (and a routing hint in the summary line) for the
@@ -145,10 +152,11 @@ export async function runWorktreeSweep({
145
152
  * worktreeSweepFn?: Function,
146
153
  * acquireLockFn?: Function,
147
154
  * purgeFn?: Function,
155
+ * closingReconcileFn?: Function,
148
156
  * logger?: { info?: Function, warn?: Function },
149
157
  * }} [args]
150
158
  * @returns {Promise<object>} the {@link sweepMergedBranches} envelope plus
151
- * `worktreeSweep` and `tempPurge`.
159
+ * `worktreeSweep`, `closingReconcile` and `tempPurge`.
152
160
  */
153
161
  export async function runBootSweep({
154
162
  cwd,
@@ -163,6 +171,7 @@ export async function runBootSweep({
163
171
  worktreeSweepFn = sweepStaleStoryWorktrees,
164
172
  acquireLockFn = acquireSweepLock,
165
173
  purgeFn = sweepTempRetention,
174
+ closingReconcileFn = reconcileStrandedClosing,
166
175
  logger = Logger,
167
176
  } = {}) {
168
177
  const root = path.resolve(cwd ?? PROJECT_ROOT);
@@ -213,6 +222,16 @@ export async function runBootSweep({
213
222
  logger,
214
223
  });
215
224
 
225
+ const closingReconcile = await closingReconcileFn({
226
+ provider,
227
+ config,
228
+ cwd: root,
229
+ logger: {
230
+ info: (m) => logger.info?.(`[boot-sweep] ${m}`),
231
+ warn: (m) => logger.warn?.(`[boot-sweep] ${m}`),
232
+ },
233
+ });
234
+
216
235
  // Temp-retention catch-up: reaped branches are confirmed merges, so their
217
236
  // artifacts are spent; the age floor collects the rest.
218
237
  const purge = await purgeFn({
@@ -221,7 +240,7 @@ export async function runBootSweep({
221
240
  label: 'boot-sweep',
222
241
  logger,
223
242
  });
224
- return { ...result, worktreeSweep, tempPurge: purge };
243
+ return { ...result, worktreeSweep, closingReconcile, tempPurge: purge };
225
244
  } catch (err) {
226
245
  const msg = err?.message ?? String(err);
227
246
  logger.warn?.(`[boot-sweep] sweep threw (host continues): ${msg}`);
@@ -239,6 +258,12 @@ export async function runBootSweep({
239
258
  }
240
259
  }
241
260
 
261
+ /** `; <text>` for a nonzero count, else nothing. */
262
+ function countSuffix(list, render) {
263
+ const count = list?.length ?? 0;
264
+ return count > 0 ? `; ${render(count)}` : '';
265
+ }
266
+
242
267
  /**
243
268
  * One-line summary; a nonzero `contentMerged` count adds a `/clean-git` hint.
244
269
  *
@@ -247,17 +272,21 @@ export async function runBootSweep({
247
272
  */
248
273
  export function buildSummaryLine(result) {
249
274
  const protectedCount = result.protected?.length ?? 0;
250
- const contentMergedCount = result.contentMerged?.length ?? 0;
251
- const worktreesReaped = result.worktreeSweep?.reaped?.length ?? 0;
252
- const worktreeSuffix =
253
- worktreesReaped > 0
254
- ? `; removed ${worktreesReaped} closed-Story worktree(s)`
255
- : '';
256
- const contentMergedSuffix =
257
- contentMergedCount > 0
258
- ? `; ${contentMergedCount} content-merged branch(es) left for /clean-git`
259
- : '';
260
- return `[boot-sweep] reaped ${result.localDeleted} local + ${result.remoteDeleted} remote; protected ${protectedCount}${worktreeSuffix}${contentMergedSuffix}.`;
275
+ const suffixes = [
276
+ countSuffix(
277
+ result.worktreeSweep?.reaped,
278
+ (n) => `removed ${n} closed-Story worktree(s)`,
279
+ ),
280
+ countSuffix(
281
+ result.closingReconcile?.reconciled,
282
+ (n) => `flipped ${n} stranded agent::closing Story(ies) to agent::done`,
283
+ ),
284
+ countSuffix(
285
+ result.contentMerged,
286
+ (n) => `${n} content-merged branch(es) left for /clean-git`,
287
+ ),
288
+ ].join('');
289
+ return `[boot-sweep] reaped ${result.localDeleted} local + ${result.remoteDeleted} remote; protected ${protectedCount}${suffixes}.`;
261
290
  }
262
291
 
263
292
  /**
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { getChangedFiles } from './lib/changed-files.js';
16
16
  import { isDirectInvocation } from './lib/cli-utils.js';
17
+ import { claimLockEventSink, lockEventHooks } from './lib/close-lock-events.js';
17
18
  import { getQuality, resolveConfig } from './lib/config-resolver.js';
18
19
  import {
19
20
  computeContentDigest,
@@ -68,6 +69,7 @@ export function parseArgs(argv) {
68
69
  * filterFilesUnderTargetsImpl?: typeof filterFilesUnderTargets,
69
70
  * logger?: { info: Function, warn: Function, error: Function },
70
71
  * lockOptions?: object,
72
+ * env?: Record<string, string|undefined>,
71
73
  * }} [deps]
72
74
  * @returns {Promise<number>}
73
75
  */
@@ -85,30 +87,26 @@ export async function runCoverageCapture(argv = process.argv, deps = {}) {
85
87
  filterFilesUnderTargetsImpl = filterFilesUnderTargets,
86
88
  logger = Logger,
87
89
  lockOptions = {},
90
+ env = process.env,
88
91
  } = deps;
92
+ const lockHooks = lockEventHooks(claimLockEventSink(env));
89
93
  const args = parseArgs(argv);
90
94
  const config = resolveConfigImpl({ cwd: args.cwd });
91
95
  const { crap, coverage } = getQualityImpl(config);
92
-
93
- if (crap.enabled === false) {
94
- logger.info('[coverage-capture] CRAP gate disabled — skipping capture.');
95
- return 0;
96
- }
97
-
98
- // Name the fix rather than propagate npm's opaque "Missing script" exit.
99
- if (!hasNpmScriptImpl(readPackageScriptsImpl(args.cwd), 'test:coverage')) {
100
- logger.error(
101
- '[coverage-capture] ✖ No "test:coverage" script in package.json. ' +
102
- 'Add one (e.g. "test:coverage": "node --test --experimental-test-coverage") ' +
103
- 'or disable the CRAP gate via delivery.quality.gates.crap.enabled=false.',
104
- );
105
- return 1;
106
- }
96
+ const refused = refusal({
97
+ crap,
98
+ cwd: args.cwd,
99
+ readPackageScriptsImpl,
100
+ hasNpmScriptImpl,
101
+ logger,
102
+ });
103
+ if (refused !== null) return refused;
107
104
 
108
105
  // Outermost first: the credit probe announces or refuses the run, and only
109
106
  // a surviving run reaches the host-level full-suite lock.
110
- const locked = lockedCapture(runCaptureImpl, config, process.env, {
107
+ const locked = lockedCapture(runCaptureImpl, config, env, {
111
108
  rerunCommand: rerunCommandFor(argv),
109
+ onLockOutcome: lockHooks.onLockOutcome,
112
110
  ...lockOptions,
113
111
  });
114
112
  const credited = creditedCapture(locked, {
@@ -139,10 +137,39 @@ export async function runCoverageCapture(argv = process.argv, deps = {}) {
139
137
  logger,
140
138
  },
141
139
  });
142
- if (timings) logger.info(`[coverage-capture] ${formatSuiteTimings(timings)}`);
140
+ if (timings) reportTimings(timings, logger, lockHooks);
143
141
  return code;
144
142
  }
145
143
 
144
+ /** @returns {number|null} The exit code when no capture may run. */
145
+ function refusal({
146
+ crap,
147
+ cwd,
148
+ readPackageScriptsImpl,
149
+ hasNpmScriptImpl,
150
+ logger,
151
+ }) {
152
+ if (crap.enabled === false) {
153
+ logger.info('[coverage-capture] CRAP gate disabled — skipping capture.');
154
+ return 0;
155
+ }
156
+ if (hasNpmScriptImpl(readPackageScriptsImpl(cwd), 'test:coverage')) {
157
+ return null;
158
+ }
159
+ // Name the fix rather than propagate npm's opaque "Missing script" exit.
160
+ logger.error(
161
+ '[coverage-capture] ✖ No "test:coverage" script in package.json. ' +
162
+ 'Add one (e.g. "test:coverage": "node --test --experimental-test-coverage") ' +
163
+ 'or disable the CRAP gate via delivery.quality.gates.crap.enabled=false.',
164
+ );
165
+ return 1;
166
+ }
167
+
168
+ function reportTimings(timings, logger, lockHooks) {
169
+ logger.info(`[coverage-capture] ${formatSuiteTimings(timings)}`);
170
+ lockHooks.onTimings(timings);
171
+ }
172
+
146
173
  /** @param {string[]} argv */
147
174
  function rerunCommandFor(argv) {
148
175
  return ['node', ...argv.slice(1)].join(' ');
@@ -189,17 +216,21 @@ async function runCaptureScopes({ crap, coverage, args, capture, deps }) {
189
216
  return await runFullScopeCapture(shared);
190
217
  }
191
218
 
219
+ // Module-level so coverage sees them even when no test spawns the CLI.
220
+ function exitWith(code) {
221
+ process.exit(code);
222
+ }
223
+
224
+ function exitOnUnexpectedError(err) {
225
+ Logger.error('[coverage-capture] unexpected error:', err);
226
+ process.exit(1);
227
+ }
228
+
192
229
  // cli-opt-out: main resolves an exit code that is forwarded via process.exit(code); runAsCli's async-main signature does not preserve the result code.
193
230
  if (isDirectInvocation(import.meta.url)) {
194
231
  // `--help` must not reach the core, which would spawn the whole suite.
195
232
  (handleCoverageCaptureHelp(process.argv)
196
233
  ? Promise.resolve(0)
197
234
  : runCoverageCapture()
198
- ).then(
199
- (code) => process.exit(code),
200
- (err) => {
201
- Logger.error('[coverage-capture] unexpected error:', err);
202
- process.exit(1);
203
- },
204
- );
235
+ ).then(exitWith, exitOnUnexpectedError);
205
236
  }
@@ -11,6 +11,7 @@
11
11
  import { spawnSync } from 'node:child_process';
12
12
  import { parseArgs } from 'node:util';
13
13
  import { runAsCli } from './lib/cli-utils.js';
14
+ import { claimLockEventSink, lockEventHooks } from './lib/close-lock-events.js';
14
15
  import { getQuality, resolveConfig } from './lib/config-resolver.js';
15
16
  import {
16
17
  fullSuiteLockPolicy,
@@ -228,12 +229,14 @@ export function runLockedSuite(
228
229
  } = {},
229
230
  ) {
230
231
  const timeoutMs = getQuality(config).coverage?.timeoutMs;
232
+ const lockHooks = lockEventHooks(claimLockEventSink(env));
231
233
  return withFullSuiteLockAsync(
232
234
  {
233
235
  ...fullSuiteLockPolicy(config, env),
234
236
  cwd,
235
237
  log,
236
238
  rerunCommand: ['node', ...process.argv.slice(1)].join(' '),
239
+ onLockOutcome: lockHooks.onLockOutcome,
237
240
  ...lockOptions,
238
241
  },
239
242
  ({ lockWaitMs }) =>
@@ -243,7 +246,10 @@ export function runLockedSuite(
243
246
  cwd,
244
247
  timeoutMs,
245
248
  lockWaitMs,
246
- onTimings: (t) => log(`[evidence-gate] ${formatSuiteTimings(t)}`),
249
+ onTimings: (t) => {
250
+ log(`[evidence-gate] ${formatSuiteTimings(t)}`);
251
+ lockHooks.onTimings(t);
252
+ },
247
253
  onTimeout: () =>
248
254
  log(
249
255
  `[evidence-gate] ⏱ ${cmd} ${args.join(' ')} exceeded ${timeoutMs}ms — killed its process group.`,
@@ -77,6 +77,20 @@ export function renderWorkflowsDoc(catalog, loopCatalog = []) {
77
77
  'writes only `.claude/commands/<name>.md` — there is no plugin manifest and no',
78
78
  'marketplace listing. The commands load in every Claude Code environment.',
79
79
  '',
80
+ '**Codex.** The same sync also writes one Codex skill per command to',
81
+ '`.agents/skills/workflows/<name>/SKILL.md`, invoked as `$<name>` (e.g.',
82
+ '`$mandrel-plan`; loop units as `$loops-<name>`). Each skill points Codex at',
83
+ 'the workflow file and passes the text after `$<name>` as its arguments.',
84
+ '`npm run sync:agents` likewise writes the role agents a workflow dispatches',
85
+ '(`subagent_type: <role>`) as Codex custom agents',
86
+ '`.codex/agents/mandrel-<role>.toml`; Codex loads those only in a trusted',
87
+ 'project. `mandrel doctor` checks both projections',
88
+ '(`codex-skills-in-sync`, `codex-agents-in-sync`) and that Codex reads the',
89
+ 'Mandrel block of `AGENTS.md` (`codex-instructions`). To refresh only the',
90
+ 'Codex half, run `node .agents/scripts/sync-codex-skills.js` or',
91
+ '`node .agents/scripts/sync-codex-agents.js`. Setup: the',
92
+ '[`.agents/README.md`](../README.md#running-mandrel-from-codex) Codex section.',
93
+ '',
80
94
  'Loop units are the one namespaced exception: files under',
81
95
  '`.agents/workflows/loops/<name>.md` project to',
82
96
  '`.claude/commands/loops/<name>.md` and are invoked as the namespaced',
@@ -148,6 +148,30 @@ export function readLineCount(absPath) {
148
148
  return lines.length;
149
149
  }
150
150
 
151
+ /** fast-glob reads a backslash as an escape. */
152
+ function toGlobPath(p) {
153
+ return p.split(path.sep).join('/');
154
+ }
155
+
156
+ /**
157
+ * jscpd 4's finder globs with `cwd: process.cwd()` and ignores its `cwd`
158
+ * option, so a repo-relative ignore glob only ever matches the process tree.
159
+ * Anchor each one at `cwd`; absolute and `**\/`-prefixed globs pass through,
160
+ * as jscpd itself treats them.
161
+ *
162
+ * @param {unknown} ignoreGlobs
163
+ * @param {string} cwd
164
+ * @returns {string[]}
165
+ */
166
+ function anchorIgnoreGlobs(ignoreGlobs, cwd) {
167
+ if (!Array.isArray(ignoreGlobs)) return [];
168
+ return ignoreGlobs.map((glob) =>
169
+ path.isAbsolute(glob) || glob.startsWith('**/')
170
+ ? glob
171
+ : toGlobPath(path.resolve(cwd, glob)),
172
+ );
173
+ }
174
+
151
175
  /**
152
176
  * @param {{
153
177
  * targetDirs: string[],
@@ -174,14 +198,14 @@ export async function scanDuplication({
174
198
  }
175
199
  const dirs = Array.isArray(targetDirs) ? targetDirs : [];
176
200
  const clones = await detect({
177
- path: dirs,
201
+ path: dirs.map((dir) => toGlobPath(path.resolve(cwd, dir))),
178
202
  cwd,
179
203
  silent: true,
180
204
  gitignore: false,
181
205
  reporters: [],
182
206
  format: formats,
183
207
  minTokens,
184
- ignore: Array.isArray(ignoreGlobs) ? ignoreGlobs : [],
208
+ ignore: anchorIgnoreGlobs(ignoreGlobs, cwd),
185
209
  });
186
210
  const visited = collectVisitedFiles(clones, cwd);
187
211
  const fileLineCounts = new Map();
@@ -11,8 +11,24 @@ import path from 'node:path';
11
11
  /** Entry-doc wiring keys idempotence off this exact import path. */
12
12
  export const SYSTEM_PROMPT_IMPORT = '@.agents/instructions.md';
13
13
 
14
+ /**
15
+ * Prose twin of the import for hosts that load AGENTS.md but expand no `@`
16
+ * imports (Codex). The doctor's `codex-instructions` check locates the block
17
+ * by this exact line, so it stays one line.
18
+ */
19
+ export const SYSTEM_PROMPT_READ_DIRECTIVE =
20
+ 'Hosts that do not expand `@` imports (Codex): before any task, read `.agents/instructions.md`, `.agents/rules/security-baseline.md` and `.agents/rules/git-conventions.md` in full and follow them.';
21
+
14
22
  export const SYSTEM_PROMPT_BLOCK = `## System Prompt
15
23
 
24
+ ${SYSTEM_PROMPT_IMPORT}
25
+
26
+ ${SYSTEM_PROMPT_READ_DIRECTIVE}
27
+ `;
28
+
29
+ /** The pre-2.84.0 block, which carried the import alone. */
30
+ const LEGACY_SYSTEM_PROMPT_BLOCK = `## System Prompt
31
+
16
32
  ${SYSTEM_PROMPT_IMPORT}
17
33
  `;
18
34
 
@@ -69,14 +85,86 @@ function foldEntryDocs({ claude, agents = null }) {
69
85
  ? `${withTrailingNewline(agents)}\n${claudeBody}`
70
86
  : claudeBody;
71
87
  const lines = dedupeImport(combined.split('\n'));
72
- let result = withTrailingNewline(lines.join('\n'));
73
- if (!lines.some((line) => line.trim() === SYSTEM_PROMPT_IMPORT)) {
74
- result =
75
- result.trim().length === 0
76
- ? SYSTEM_PROMPT_ENTRY_DOC
77
- : `${result}\n${SYSTEM_PROMPT_BLOCK}`;
88
+ const result = withTrailingNewline(lines.join('\n'));
89
+ if (lines.some((line) => line.trim() === SYSTEM_PROMPT_IMPORT)) return result;
90
+ return result.trim().length === 0
91
+ ? SYSTEM_PROMPT_ENTRY_DOC
92
+ : insertSystemPromptBlock(result);
93
+ }
94
+
95
+ /**
96
+ * Place {@link SYSTEM_PROMPT_BLOCK} at the top of an entry doc — directly
97
+ * after a leading H1 when there is one. Codex stops reading AGENTS.md at
98
+ * `project_doc_max_bytes`, so an appended block in a long file never loads.
99
+ *
100
+ * @param {string} text - entry-doc content without the block.
101
+ * @returns {string}
102
+ */
103
+ function insertSystemPromptBlock(text) {
104
+ const h1 = /^(?:[ \t]*\r?\n)*# [^\n]*\n?/.exec(text);
105
+ const head = h1 ? withTrailingNewline(h1[0].replace(/^\s+/, '')) : '';
106
+ const rest = text.slice(h1 ? h1[0].length : 0).replace(/^\s*\n/, '');
107
+ const lead = head ? `${head}\n` : '';
108
+ const tail = rest.length > 0 ? `\n${withTrailingNewline(rest)}` : '';
109
+ return `${lead}${SYSTEM_PROMPT_BLOCK}${tail}`;
110
+ }
111
+
112
+ /**
113
+ * Byte offset just past a leading H1 and its blank lines — where the block
114
+ * belongs.
115
+ *
116
+ * @param {string} text
117
+ * @returns {number}
118
+ */
119
+ function topOffset(text) {
120
+ return /^(?:\s*\n)*(?:# [^\n]*\n(?:[ \t]*\n)*)?/.exec(text)[0].length;
121
+ }
122
+
123
+ /**
124
+ * Locate a recognizable Mandrel block (current or legacy shape).
125
+ *
126
+ * @param {string} text
127
+ * @returns {{ start: number, end: number, current: boolean } | null}
128
+ */
129
+ function findSystemPromptBlock(text) {
130
+ for (const [block, current] of [
131
+ [SYSTEM_PROMPT_BLOCK, true],
132
+ [LEGACY_SYSTEM_PROMPT_BLOCK, false],
133
+ ]) {
134
+ const start = text.indexOf(block);
135
+ if (start !== -1) return { start, end: start + block.length, current };
78
136
  }
79
- return result;
137
+ return null;
138
+ }
139
+
140
+ /**
141
+ * True when an entry doc carries a recognizable Mandrel block that is not
142
+ * the current block at the top — the migration's `detect`.
143
+ *
144
+ * @param {string} text
145
+ * @returns {boolean}
146
+ */
147
+ export function needsSystemPromptHoist(text) {
148
+ const found = findSystemPromptBlock(text);
149
+ if (!found) return false;
150
+ return !(found.current && found.start === topOffset(text));
151
+ }
152
+
153
+ /**
154
+ * Move a recognizable block to the top, upgrading a legacy one. Text with no
155
+ * recognizable block (a hand-edited import) is returned unchanged.
156
+ *
157
+ * @param {string} text
158
+ * @returns {string}
159
+ */
160
+ export function hoistSystemPromptBlock(text) {
161
+ if (!needsSystemPromptHoist(text)) return text;
162
+ const { start, end } = findSystemPromptBlock(text);
163
+ const without = `${text.slice(0, start)}${text.slice(end)}`.replace(
164
+ /\n{3,}/g,
165
+ '\n\n',
166
+ );
167
+ return insertSystemPromptBlock(without.replace(/\n+$/, '\n'));
80
168
  }
81
169
 
82
170
  /**
@@ -104,11 +192,11 @@ export function foldClaudeMdIntoAgentsMd(projectRoot, fsImpl = fs) {
104
192
 
105
193
  /**
106
194
  * Wire the system-prompt import into AGENTS.md, folding a CLAUDE.md in first.
107
- * Creates, folds, appends, or no-ops.
195
+ * Creates, folds, inserts the block at the top, or no-ops.
108
196
  *
109
197
  * @param {string} projectRoot
110
198
  * @param {typeof fs} [fsImpl]
111
- * @returns {{ action: 'created'|'folded'|'appended'|'already-present', path: string }}
199
+ * @returns {{ action: 'created'|'folded'|'inserted'|'already-present', path: string }}
112
200
  */
113
201
  export function wireEntryDoc(projectRoot, fsImpl = fs) {
114
202
  const folded = foldClaudeMdIntoAgentsMd(projectRoot, fsImpl);
@@ -122,13 +210,8 @@ export function wireEntryDoc(projectRoot, fsImpl = fs) {
122
210
  if (existing.includes(SYSTEM_PROMPT_IMPORT)) {
123
211
  return { action: 'already-present', path: target };
124
212
  }
125
- const separator = existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
126
- fsImpl.writeFileSync(
127
- target,
128
- `${existing}${separator}\n${SYSTEM_PROMPT_BLOCK}`,
129
- 'utf8',
130
- );
131
- return { action: 'appended', path: target };
213
+ fsImpl.writeFileSync(target, insertSystemPromptBlock(existing), 'utf8');
214
+ return { action: 'inserted', path: target };
132
215
  }
133
216
 
134
217
  /**
@@ -53,17 +53,17 @@ function ideWiringEntries() {
53
53
  e(
54
54
  rel('AGENTS.md'),
55
55
  'merge',
56
- 'Wire the @.agents/instructions.md system-prompt import into AGENTS.md (folding any CLAUDE.md into it) so Claude Code hydrates the framework on cold start.',
56
+ 'Wire the system-prompt block — the @.agents/instructions.md import plus a read directive for hosts without @-imports — at the top of AGENTS.md (folding any CLAUDE.md into it) so Claude Code and Codex both hydrate the framework on cold start.',
57
57
  ),
58
58
  e(
59
59
  rel('.claude', 'commands'),
60
60
  'run',
61
- 'Generate the flat command surface (/<name>) from .agents/workflows/.',
61
+ 'Generate the flat command surface (/<name>) and the Codex skills (.agents/skills/workflows/, invoked as $<name>) from .agents/workflows/.',
62
62
  ),
63
63
  e(
64
64
  rel('.gitignore'),
65
65
  'merge',
66
- 'Ignore the .claude/commands/ and .claude/agents/ projections (generated by prepare), .mcp.json + .env (carry secrets), and the per-clone install ledger.',
66
+ 'Ignore the .claude/commands/, .claude/agents/, .agents/skills/workflows/ and .codex/agents/mandrel-*.toml projections (generated by prepare), .mcp.json + .env (carry secrets), and the per-clone install ledger.',
67
67
  ),
68
68
  ];
69
69
  }
@@ -81,7 +81,7 @@ function repoConfigEntries() {
81
81
  e(
82
82
  rel('package.json'),
83
83
  'merge',
84
- 'Seed/merge the sync:commands, sync:agents, prepare, and bootstrap npm scripts. `prepare` is guarded: it exits 0 without writing when .agents/scripts/ is absent (a manifest-only container `npm ci`), and otherwise regenerates the .claude/commands/ and .claude/agents/ projections — both gitignored.',
84
+ 'Seed/merge the sync:commands, sync:agents, prepare, and bootstrap npm scripts. `prepare` is guarded: it exits 0 without writing when .agents/scripts/ is absent (a manifest-only container `npm ci`), and otherwise regenerates the Claude Code (.claude/commands/, .claude/agents/) and Codex (.agents/skills/workflows/, .codex/agents/mandrel-*.toml) projections — all gitignored.',
85
85
  ),
86
86
  e(
87
87
  rel('.agentrc.json'),