mancode 0.3.12 → 0.3.14

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.
@@ -417,7 +417,7 @@ async function inspectV3Adapter(projectRoot, platform) {
417
417
  installed,
418
418
  ready: installed,
419
419
  target,
420
- detail: installed ? "V3 bootstrap and original mode entries are present; session identity is explicit-required." : "V3 bootstrap or one of its original mode entries is not installed.",
420
+ detail: installed ? "mancode bootstrap and original mode entries are present; session identity is explicit-required." : "mancode bootstrap or one of its original mode entries is not installed.",
421
421
  capabilities: capabilitiesFor(platform)
422
422
  };
423
423
  }
@@ -493,25 +493,27 @@ async function removeV3Adapter(projectRoot, platform) {
493
493
  }
494
494
  function renderV3Bootstrap(platform) {
495
495
  const platformLabel = platformLabelFor(platform);
496
+ const sessionArguments = sessionArgumentsFor(platform);
496
497
  const sessionCreationGuidance = platform === "codex" || platform === "zcode" ? "When status has no `currentSession`, first reuse any explicit session ID already returned in this conversation. Only when neither exists, create one once with `mancode context session new --client codex` in Codex or `mancode context session new --client zcode` in ZCode." : `When status has no \`currentSession\`, first reuse any explicit session ID already returned in this conversation. Only when neither exists, create one once with \`mancode context session new --client ${platform}\`.`;
497
498
  const spikePlatform = platform === "codex" || platform === "zcode" ? "the active Codex or ZCode host" : platform;
498
- const modeEntry = capabilitiesFor(platform).nativeModeEntry ? "Use the platform mode entry only as a shortcut; resolve a Context Pack first." : "This platform has no native V3 mode entry; use the CLI commands explicitly.";
499
+ const modeEntry = capabilitiesFor(platform).nativeModeEntry ? "Use the platform mode entry only as a shortcut; resolve a Context Pack first." : "This platform has no native mancode mode entry; use the CLI commands explicitly.";
499
500
  return [
500
- "# mancode V3 bootstrap",
501
+ "# mancode bootstrap",
501
502
  "",
502
503
  V3_ADAPTER_MANAGED_MARKER,
503
504
  "",
504
505
  `- Platform: ${platformLabel}. This file is a non-authoritative bootstrap.`,
505
506
  "- Locate the project root before running mancode commands.",
506
507
  "- First run `mancode status --json` from the project root.",
508
+ '- Treat status values such as `authority: "v3"` and `v3_active` as internal machine fields. In operator-facing narration, say `mancode`; never prefix a mode or action with a version label.',
507
509
  "- An explicitly invoked original `man`, `manba`, `manteam`, `manps`, or `mansolo` entry supplies its authorized action. Its mode-specific steps override conflicting generic no-task or mutation guidance below.",
508
510
  "- In particular, `manps` may run local health scans without an actor, session, or TaskRef. `mansolo` needs them only for an explicit governed handoff.",
509
511
  '- If status has no `localIdentity.actorId`, ask for a display name and run `mancode team identity create --name "<display name>"` before creating a session.',
510
512
  "- If status reports `currentSession`, reuse it. `currentTask: null` and `MANCODE_TASK_REQUIRED` do not make a session stale.",
511
- `- ${sessionCreationGuidance} Pass its returned \`sessionId\` as \`--session <id>\` to later commands; an \`export\` inside one command tool does not persist to later command tools.`,
513
+ `- ${sessionCreationGuidance} Pass its returned \`sessionId\` and matching client as \`${sessionArguments}\` to every later session command; an \`export\` inside one command tool does not persist to later command tools.`,
512
514
  '- Outside an invoked original mode entry, if no current task and no task is explicitly supplied, report "no task bound" and stop. Do not probe workflow subcommands to work around `MANCODE_TASK_REQUIRED`.',
513
515
  "- Bootstrap discovery is read-only: before the operator explicitly requests task work, do not run `mancode init`, `mancode migrate`, `mancode workflow`, or inspect mancode installed package/source.",
514
- "- With an existing or supplied task, read its Context Pack with `mancode context show --purpose orient --session <id>`; for anonymous diagnosis, include an explicit `--task <namespace:id>`.",
516
+ `- With an existing or supplied task, read its Context Pack with \`mancode context show --purpose orient ${sessionArguments}\`; for anonymous diagnosis, include an explicit \`--task <namespace:id>\`.`,
515
517
  "- After an operator explicitly requests task work, perform mutations only through `mancode workflow`, `mancode team`, and `mancode context` commands with their required revision and session arguments.",
516
518
  "- For a mode entry, request the matching Context Pack purpose: `plan`, `implement`, `review`, `verify`, or `handoff`.",
517
519
  "- Do not persist task, mode, or session state in this adapter file or any legacy state file.",
@@ -521,23 +523,41 @@ function renderV3Bootstrap(platform) {
521
523
  }
522
524
  function renderV3ModeEntry(mode, platform) {
523
525
  const definition = V3_MODE_DEFINITIONS[mode];
526
+ const sessionArguments = sessionArgumentsFor(platform);
527
+ const sessionClientGuidance = sessionClientGuidanceFor(platform);
524
528
  const sessionCreationGuidance = platform === "codex" || platform === "zcode" ? "If status has no current session, reuse an explicit session ID already retained in this conversation. Only if neither exists, run `mancode context session new --client codex` in Codex or `mancode context session new --client zcode` in ZCode exactly once, then retain the returned session ID." : `If status has no current session, reuse an explicit session ID already retained in this conversation. Only if neither exists, run \`mancode context session new --client ${platform}\` exactly once and retain the returned session ID.`;
525
- const authoritySteps = mode === "manps" ? [
526
- "1. Run `mancode status --json` from the project root and require active V3 authority.",
527
- "2. Run the health action below directly. A local scan needs no TaskRef, actor identity, or explicit session.",
528
- "3. Never read or write legacy mode authority before or after the scan."
529
- ] : mode === "mansolo" ? [
530
- "1. Run `mancode status --json` from the project root. Never read or write legacy mode authority.",
531
- "2. If no governed task is being handed off, continue with focused solo work without creating a persistent mode, actor, session, or TaskRef.",
532
- "3. For an explicit governed handoff, ensure `localIdentity.actorId`, reuse or create the current session, and bind the existing TaskRef before running the handoff action below.",
533
- "4. For that governed task only, read `mancode context show --purpose implement --session <id>` using the bound or explicit TaskRef."
534
- ] : [
535
- "1. Run `mancode status --json` from the project root. Never read or write the legacy authority file.",
536
- '2. If `localIdentity.actorId` is absent, ask for a display name and run `mancode team identity create --name "<display name>"`.',
537
- `3. Reuse \`currentSession.sessionId\` when present. ${sessionCreationGuidance}`,
538
- "4. Reuse the current TaskRef. To bind a supplied existing task, run `mancode context resume <namespace:ULID> --session <id>`.",
539
- `5. For an existing task, read only the needed Context Pack with \`mancode context show --purpose ${definition.contextPurpose} --session <id>\`; include \`--task <namespace:ULID>\` when it is not yet bound. For a new task, create it through the mode action first, then read the returned TaskRef's Context Pack.`
540
- ];
529
+ let authoritySteps;
530
+ if (mode === "manps") {
531
+ authoritySteps = [
532
+ "1. Run `mancode status --json` from the project root and require active mancode authority.",
533
+ "2. Run the health action below directly. A local scan needs no TaskRef, actor identity, or explicit session.",
534
+ "3. Never read or write legacy mode authority before or after the scan."
535
+ ];
536
+ } else if (mode === "mansolo") {
537
+ authoritySteps = [
538
+ "1. Run `mancode status --json` from the project root. Never read or write legacy mode authority.",
539
+ "2. If no governed task is being handed off, continue with focused solo work without creating a persistent mode, actor, session, or TaskRef.",
540
+ `3. For an explicit governed handoff, ensure \`localIdentity.actorId\`, reuse or create the current session, and bind the existing TaskRef. ${sessionCreationGuidance} ${sessionClientGuidance}`,
541
+ `4. For that governed task only, read \`mancode context show --purpose implement ${sessionArguments}\` using the bound or explicit TaskRef.`
542
+ ];
543
+ } else if (mode === "man") {
544
+ authoritySteps = [
545
+ "1. Run `mancode status --json` from the project root. Never read or write the legacy authority file.",
546
+ "2. If the request is only a read-only project orientation, introduction, explanation, or summary, inspect the repository and answer directly without creating an actor, session, TaskRef, or workflow. Do not turn an orientation request into a `plan_only` workflow.",
547
+ '3. Only for requested governed task work, if `localIdentity.actorId` is absent, ask for a display name and run `mancode team identity create --name "<display name>"`.',
548
+ `4. Reuse \`currentSession.sessionId\` when present. ${sessionCreationGuidance} ${sessionClientGuidance}`,
549
+ `5. Reuse the current TaskRef. To bind a supplied existing task, run \`mancode context resume <namespace:ULID> ${sessionArguments}\`.`,
550
+ `6. For an existing task, read only the needed Context Pack with \`mancode context show --purpose ${definition.contextPurpose} ${sessionArguments}\`; include \`--task <namespace:ULID>\` when it is not yet bound. For a new task, create it through the mode action first, then read the returned TaskRef's Context Pack.`
551
+ ];
552
+ } else {
553
+ authoritySteps = [
554
+ "1. Run `mancode status --json` from the project root. Never read or write the legacy authority file.",
555
+ '2. If `localIdentity.actorId` is absent, ask for a display name and run `mancode team identity create --name "<display name>"`.',
556
+ `3. Reuse \`currentSession.sessionId\` when present. ${sessionCreationGuidance} ${sessionClientGuidance}`,
557
+ `4. Reuse the current TaskRef. To bind a supplied existing task, run \`mancode context resume <namespace:ULID> ${sessionArguments}\`.`,
558
+ `5. For an existing task, read only the needed Context Pack with \`mancode context show --purpose ${definition.contextPurpose} ${sessionArguments}\`; include \`--task <namespace:ULID>\` when it is not yet bound. For a new task, create it through the mode action first, then read the returned TaskRef's Context Pack.`
559
+ ];
560
+ }
541
561
  const frontmatter = [
542
562
  "---",
543
563
  ...platform === "claude-code" || platform === "codex" || platform === "zcode" ? [`name: ${mode}`] : [],
@@ -545,63 +565,77 @@ function renderV3ModeEntry(mode, platform) {
545
565
  `description: ${JSON.stringify(definition.description)}`,
546
566
  "---"
547
567
  ];
548
- const mutationGuidance = mode === "manps" ? "The local scan and an explicitly requested remediation do not require a TaskRef, workflow revision, actor, or session. Never turn their report files into workflow authority." : mode === "mansolo" ? "Only an explicit governed handoff mutation requires the bound TaskRef, explicit session, and latest expected revision. Ordinary focused solo work persists no mode state." : "For every mutation, use the TaskRef, explicit session, and latest expected revision reported by V3. Do not emulate the legacy `--step` protocol or persist mode state in an adapter file.";
568
+ const mutationGuidance = mode === "manps" ? "The local scan and an explicitly requested remediation do not require a TaskRef, workflow revision, actor, or session. Never turn their report files into workflow authority." : mode === "mansolo" ? "Only an explicit governed handoff mutation requires the bound TaskRef, explicit session, and latest expected revision. Ordinary focused solo work persists no mode state." : "For every mutation, use the TaskRef, explicit session, matching client, and latest expected revision reported by mancode. Do not emulate the legacy `--step` protocol or persist mode state in an adapter file.";
569
+ const actions = definition.actions.map(
570
+ (action) => action.replaceAll("--session <id>", sessionArguments)
571
+ );
549
572
  return [
550
573
  ...frontmatter,
551
574
  "",
552
575
  V3_MODE_ENTRY_MANAGED_MARKER,
553
576
  "",
554
- `# mancode V3 mode: ${mode}`,
577
+ `# mancode mode: ${mode}`,
555
578
  "",
556
579
  `Purpose: ${definition.purpose}.`,
557
580
  "",
558
- "## Enter through V3 authority",
581
+ "## Enter through mancode",
559
582
  "",
560
583
  ...authoritySteps,
561
584
  "",
562
585
  "## Mode action",
563
586
  "",
564
- ...definition.actions,
587
+ ...actions,
588
+ "",
589
+ 'Treat status values such as `authority: "v3"` and `v3_active` as internal machine fields. In operator-facing narration, say `mancode`; never prefix this mode or its actions with a version label.',
565
590
  "",
566
591
  mutationGuidance,
567
592
  ""
568
593
  ].join("\n");
569
594
  }
595
+ function sessionArgumentsFor(platform) {
596
+ const client = platform === "codex" || platform === "zcode" ? "<active-client>" : platform;
597
+ return `--session <id> --client ${client}`;
598
+ }
599
+ function sessionClientGuidanceFor(platform) {
600
+ return platform === "codex" || platform === "zcode" ? "Use `--client codex` in Codex or `--client zcode` in ZCode on every command that uses this session." : `Use \`--client ${platform}\` on every command that uses this session.`;
601
+ }
570
602
  var V3_MODE_DEFINITIONS = {
571
603
  man: {
572
- description: "Plan and execute governed work through mancode V3.",
604
+ description: "Plan and execute governed work through mancode.",
573
605
  purpose: "clarify, plan, implement, verify, and review governed work",
574
606
  contextPurpose: "plan",
575
607
  actions: [
608
+ "- For a read-only project orientation, inspect and answer directly; do not create governance records.",
576
609
  '- For a new task, run `mancode workflow create man "<task>" --session <id>`.',
610
+ "- Write requirements as semantic JSON with `version: 1`, `goal`, `confirmedScope`, `excludedScope`, `technicalDecisions`, `defaults`, `blockingUnknowns`, all seven `coverage` dimensions, and `acceptanceCriteria`; mancode generates canonical internal IDs and digests.",
577
611
  "- Finalize requirements with `mancode workflow requirements <namespace:ULID> finalize --file <requirements.json> --expected-revision <n> --session <id>`.",
578
612
  "- Revise or confirm the plan with `mancode workflow plan <namespace:ULID> revise|confirm --expected-revision <n> ... --session <id>`.",
579
- "- Apply verification and review ledgers with their V3 `apply --file` commands, then use `mancode workflow complete <namespace:ULID> --expected-revision <n> --session <id>`."
613
+ "- Apply verification and review ledgers with their mancode `apply --file` commands, then use `mancode workflow complete <namespace:ULID> --expected-revision <n> --session <id>`."
580
614
  ]
581
615
  },
582
616
  manba: {
583
- description: "Diagnose and verify a bug through mancode V3.",
617
+ description: "Diagnose and verify a bug through mancode.",
584
618
  purpose: "reproduce, diagnose, fix, and verify a regression",
585
619
  contextPurpose: "implement",
586
620
  actions: [
587
621
  '- For a new diagnostic task, run `mancode workflow create manba "<task>" --session <id>`.',
588
- "- When this is a child investigation, add `--parent <namespace:ULID>`; report and merge the typed outcome through the V3 child commands.",
622
+ "- When this is a child investigation, add `--parent <namespace:ULID>`; report and merge the typed outcome through the mancode child commands.",
589
623
  "- Change lifecycle only with `mancode workflow update <namespace:ULID> --status <status> --expected-revision <n> --session <id>` and finish with `workflow complete` plus the typed `--outcome`."
590
624
  ]
591
625
  },
592
626
  manteam: {
593
- description: "Coordinate shared governed work through mancode V3.",
627
+ description: "Coordinate shared governed work through mancode.",
594
628
  purpose: "plan and execute work with explicit team ownership and handoff",
595
629
  contextPurpose: "plan",
596
630
  actions: [
597
631
  "- Confirm team membership with `mancode team status`; join invited participants before assigning shared work.",
598
632
  '- For a new shared task, run `mancode workflow create manteam "<task>" --visibility shared --coordination team --confirm-shared --session <id>`.',
599
633
  "- Use claims, checkpoints, sync, and handoffs through `mancode team`; never infer ownership from an adapter prompt.",
600
- "- Use the same V3 requirements, plan, verification, review, and completion commands as `man`, adding `--sync` whenever the active transport requires it."
634
+ "- Use the same mancode requirements, plan, verification, review, and completion commands as `man`, adding `--sync` whenever the active transport requires it."
601
635
  ]
602
636
  },
603
637
  manps: {
604
- description: "Inspect project health through the existing manps command.",
638
+ description: "Inspect project health through mancode.",
605
639
  purpose: "scan project health and review bounded remediation",
606
640
  contextPurpose: "review",
607
641
  actions: [
@@ -610,7 +644,7 @@ var V3_MODE_DEFINITIONS = {
610
644
  ]
611
645
  },
612
646
  mansolo: {
613
- description: "Return to focused solo execution under V3 authority.",
647
+ description: "Return to focused solo execution through mancode.",
614
648
  purpose: "perform a small focused task or accept an explicit solo handoff",
615
649
  contextPurpose: "implement",
616
650
  actions: [
@@ -670,7 +704,7 @@ function renderClaudeSkill(content) {
670
704
  return [
671
705
  "---",
672
706
  "name: mancode-v3",
673
- 'description: "Internal bootstrap for original mancode mode entries under V3 authority."',
707
+ 'description: "Internal bootstrap for the original mancode mode entries."',
674
708
  "user-invocable: false",
675
709
  "---",
676
710
  "",
@@ -681,7 +715,7 @@ function renderClaudeSkill(content) {
681
715
  function renderCursorRule(content) {
682
716
  return [
683
717
  "---",
684
- 'description: "Stable bootstrap for mancode V3 context and workflow commands."',
718
+ 'description: "Stable bootstrap for mancode context and workflow commands."',
685
719
  "alwaysApply: true",
686
720
  'globs: "**/*"',
687
721
  "---",
@@ -999,32 +1033,32 @@ function renderRetiredClaudeSoloEntry() {
999
1033
  return [
1000
1034
  "---",
1001
1035
  "name: solo",
1002
- 'description: "Compatibility alias for the mancode V3 mansolo entry."',
1036
+ 'description: "Compatibility alias for the mancode mansolo entry."',
1003
1037
  "user-invocable: false",
1004
1038
  "---",
1005
1039
  "",
1006
1040
  V3_MODE_ENTRY_MANAGED_MARKER,
1007
1041
  "",
1008
- "# mancode V3 mode compatibility alias",
1042
+ "# mancode mode compatibility alias",
1009
1043
  "",
1010
- "Use the `mansolo` mode entry. Resolve V3 status, identity, session, TaskRef, and Context Pack there; do not use legacy mode persistence.",
1044
+ "Use the `mansolo` mode entry. Resolve mancode status, identity, session, TaskRef, and Context Pack there; do not use legacy mode persistence.",
1011
1045
  ""
1012
1046
  ].join("\n");
1013
1047
  }
1014
1048
  function renderRetiredCursorRule(target) {
1015
1049
  const legacyName = target.replace("cursor-legacy-", "");
1016
1050
  const mode = legacyName === "solo" ? "mansolo" : legacyName === "mamba" ? "manba" : legacyName === "man8" ? "man" : legacyName;
1017
- const guidance = mode === "context" || mode === "practice" ? "Run `mancode status --json`, then use the matching V3 mode command." : `Use the \`/${mode}\` V3 mode command.`;
1051
+ const guidance = mode === "context" || mode === "practice" ? "Run `mancode status --json`, then use the matching mancode mode command." : `Use the \`/${mode}\` mancode mode command.`;
1018
1052
  return [
1019
1053
  "---",
1020
- 'description: "Retired legacy mancode rule; V3 mode entries are authoritative."',
1054
+ 'description: "Retired legacy mancode rule; current mancode mode entries are authoritative."',
1021
1055
  "alwaysApply: false",
1022
1056
  'globs: "__mancode_v3_retired_rule__"',
1023
1057
  "---",
1024
1058
  "",
1025
1059
  V3_ADAPTER_MANAGED_MARKER,
1026
1060
  "",
1027
- "# mancode V3 compatibility redirect",
1061
+ "# mancode compatibility redirect",
1028
1062
  "",
1029
1063
  guidance,
1030
1064
  "Do not use legacy mode persistence or legacy workflow paths.",
@@ -1042,7 +1076,7 @@ function renderRetiredModeAlias(target) {
1042
1076
  ...parsed.family === "claude" || parsed.family === "agents" ? [`name: ${parsed.alias}`] : [],
1043
1077
  ...parsed.family === "copilot" ? ["agent: 'agent'"] : [],
1044
1078
  ...parsed.family === "claude" ? ["user-invocable: false"] : [],
1045
- `description: ${JSON.stringify(`Compatibility alias for the mancode V3 ${publicMode} entry.`)}`,
1079
+ `description: ${JSON.stringify(`Compatibility alias for the mancode ${publicMode} entry.`)}`,
1046
1080
  "---"
1047
1081
  ];
1048
1082
  return [
@@ -1050,11 +1084,11 @@ function renderRetiredModeAlias(target) {
1050
1084
  "",
1051
1085
  V3_MODE_ENTRY_MANAGED_MARKER,
1052
1086
  "",
1053
- "# mancode V3 mode compatibility alias",
1087
+ "# mancode mode compatibility alias",
1054
1088
  "",
1055
- `The legacy name \`${parsed.alias}\` maps to the public V3 mode \`${publicMode}\`. Use that original V3 mode entry instead.`,
1089
+ `The legacy name \`${parsed.alias}\` maps to the public mancode mode \`${publicMode}\`. Use that original mancode mode entry instead.`,
1056
1090
  "",
1057
- "Resolve status, identity, session, TaskRef, and Context Pack through V3 authority there. Do not use legacy mode persistence or the legacy workflow protocol.",
1091
+ "Resolve status, identity, session, TaskRef, and Context Pack through mancode there. Do not use legacy mode persistence or the legacy workflow protocol.",
1058
1092
  ""
1059
1093
  ].join("\n");
1060
1094
  }
@@ -1287,4 +1321,4 @@ export {
1287
1321
  renderV3Bootstrap,
1288
1322
  renderV3ModeEntry
1289
1323
  };
1290
- //# sourceMappingURL=chunk-CFC3HBNA.js.map
1324
+ //# sourceMappingURL=chunk-L3TKSX6R.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/installers/v3-adapter.ts","../src/installers/managed-block.ts"],"sourcesContent":["import {\n lstat,\n mkdir,\n readFile,\n rename,\n rm,\n rmdir,\n writeFile,\n} from 'node:fs/promises';\nimport path from 'node:path';\nimport {\n hasManagedBlock,\n removeManagedBlock,\n replaceManagedBlock,\n} from './managed-block.js';\nimport type { PlatformName } from './registry.js';\n\n/**\n * This is the schema of the generated bootstrap, not a product version. The\n * schema manifest records the expected renderer schema while physical status\n * is derived from the managed files below.\n */\nexport const V3_ADAPTER_VERSION = '3';\n\nexport const V3_ADAPTER_MANAGED_MARKER =\n '<!-- Managed by mancode:v3-adapter. Do not edit this marker. -->';\n\nexport const V3_MODE_ENTRY_MANAGED_MARKER =\n '<!-- Managed by mancode:v3-mode-entry. Do not edit this marker. -->';\n\nexport const V3_MODE_NAMES = [\n 'manba',\n 'man',\n 'manteam',\n 'manps',\n 'mansolo',\n] as const;\n\nexport type V3ModeName = (typeof V3_MODE_NAMES)[number];\n\nconst LEGACY_MODE_ENTRY_MANAGED_MARKERS = [\n '<!-- Managed by mancode:claude-skill. Do not edit this marker. -->',\n '<!-- Managed by mancode:codex-skill. Do not edit this file manually. -->',\n '<!-- Managed by mancode:zcode-skill. Do not edit this file manually. -->',\n '<!-- Managed by mancode:mode-file. Do not edit this file manually. -->',\n] as const;\n\nconst GENERATED_CLAUDE_HOOK_COMMANDS = new Set([\n 'node \".mancode/hooks/session-start.mjs\"',\n 'node \".mancode/hooks/user-prompt-submit.mjs\"',\n 'bash .mancode/hooks/session-start.sh',\n 'bash .mancode/hooks/user-prompt-submit.sh',\n]);\n\nconst LEGACY_CLAUDE_SKILL_PATHS = new Set([\n '.claude/skills/mancode-solo.md',\n '.claude/skills/mancode-man8.md',\n '.claude/skills/mancode-man.md',\n '.claude/skills/mancode-mansolo.md',\n]);\n\nconst LEGACY_CLAUDE_SETTINGS_RAW_HINTS = [\n '.mancode/hooks/session-start.',\n '.mancode/hooks/user-prompt-submit.',\n ...LEGACY_CLAUDE_SKILL_PATHS,\n] as const;\n\nconst V3_CODEX_START_MARKER = '<!-- mancode:v3:codex:start -->';\nconst V3_CODEX_END_MARKER = '<!-- mancode:v3:codex:end -->';\nconst V3_ZCODE_START_MARKER = '<!-- mancode:v3:zcode:start -->';\nconst V3_ZCODE_END_MARKER = '<!-- mancode:v3:zcode:end -->';\nconst V3_COPILOT_START_MARKER = '<!-- mancode:v3:copilot:start -->';\nconst V3_COPILOT_END_MARKER = '<!-- mancode:v3:copilot:end -->';\nconst LEGACY_CODEX_START_MARKER = '<!-- mancode:start -->';\nconst LEGACY_CODEX_END_MARKER = '<!-- mancode:end -->';\nconst LEGACY_ZCODE_START_MARKER = '<!-- mancode:zcode:start -->';\nconst LEGACY_ZCODE_END_MARKER = '<!-- mancode:zcode:end -->';\nconst RETRIABLE_ADAPTER_READ_CODES = new Set(['EACCES', 'EBUSY', 'EPERM']);\nconst ADAPTER_READ_MAX_ATTEMPTS = 4;\nconst ADAPTER_READ_RETRY_DELAY_MS = 25;\n\nexport interface V3AdapterCapabilities {\n nativeModeEntry: boolean;\n sessionHook: false;\n promptHook: false;\n sessionIdentity: 'explicit-required';\n}\n\nexport interface V3PlatformAdapterStatus {\n version: string;\n installed: boolean;\n ready: boolean;\n target: string;\n detail: string;\n capabilities: V3AdapterCapabilities;\n}\n\n/**\n * A physical file touched by the V3 bootstrap renderer. Codex and ZCode\n * deliberately share the AGENTS target, so activation journals these files\n * rather than individual platform installs.\n */\nexport type V3ModeEntryFileTarget =\n | `claude-mode-${V3ModeName}`\n | `agents-mode-${V3ModeName}`\n | `cursor-mode-${V3ModeName}`\n | `copilot-mode-${V3ModeName}`;\n\nexport type V3LegacyAdapterFileTarget =\n | 'claude-settings'\n | 'claude-legacy-solo'\n | 'cursor-legacy-context'\n | 'cursor-legacy-practice'\n | 'cursor-legacy-solo'\n | 'cursor-legacy-manba'\n | 'cursor-legacy-man'\n | 'cursor-legacy-manteam'\n | 'cursor-legacy-manps'\n | 'cursor-legacy-mamba'\n | 'cursor-legacy-man8'\n | V3LegacyModeAliasTarget;\n\ntype V3LegacyModeAliasTarget =\n | `claude-alias-${LegacyModeAlias}`\n | `agents-alias-${LegacyModeAlias}`\n | `cursor-alias-${LegacyModeAlias}`\n | `copilot-alias-${LegacyModeAlias}`;\n\ntype LegacyModeAlias = 'mamba' | 'man8';\n\nexport type V3AdapterFileTarget =\n | 'claude-skill'\n | 'cursor-rule'\n | 'agents'\n | 'copilot-instructions'\n | V3ModeEntryFileTarget\n | V3LegacyAdapterFileTarget;\n\nexport interface V3AdapterFilePlan {\n target: V3AdapterFileTarget;\n beforeContent: string | null;\n targetContent: string;\n}\n\nexport interface V3StagedAdapter {\n platform: PlatformName;\n /** The corresponding live target, relative to the project root. */\n target: string;\n /** The generated candidate, kept under V3 staging rather than the live target. */\n stagingTarget: string;\n /** Original public mode entries staged beside the bootstrap candidate. */\n modeEntries: Array<{\n mode: V3ModeName;\n target: string;\n stagingTarget: string;\n }>;\n}\n\nconst V3_MODE_ENTRY_FILE_TARGETS = V3_MODE_NAMES.flatMap((mode) => [\n `claude-mode-${mode}` as const,\n `agents-mode-${mode}` as const,\n `cursor-mode-${mode}` as const,\n `copilot-mode-${mode}` as const,\n]);\n\nconst V3_LEGACY_ADAPTER_FILE_TARGETS: readonly V3LegacyAdapterFileTarget[] = [\n 'claude-settings',\n 'claude-legacy-solo',\n 'cursor-legacy-context',\n 'cursor-legacy-practice',\n 'cursor-legacy-solo',\n 'cursor-legacy-manba',\n 'cursor-legacy-man',\n 'cursor-legacy-manteam',\n 'cursor-legacy-manps',\n 'cursor-legacy-mamba',\n 'cursor-legacy-man8',\n ...(['mamba', 'man8'] as const).flatMap((mode) => [\n `claude-alias-${mode}` as const,\n `agents-alias-${mode}` as const,\n `cursor-alias-${mode}` as const,\n `copilot-alias-${mode}` as const,\n ]),\n];\n\nexport const V3_ADAPTER_FILE_TARGETS: readonly V3AdapterFileTarget[] = [\n 'claude-skill',\n 'cursor-rule',\n 'agents',\n 'copilot-instructions',\n ...V3_MODE_ENTRY_FILE_TARGETS,\n ...V3_LEGACY_ADAPTER_FILE_TARGETS,\n];\n\n/**\n * Calculates exact file replacements without publishing them. This lets a\n * migration journal bind the combined AGENTS.md result before its first\n * visible write and preserves all user-authored content outside our blocks.\n */\nexport async function planV3AdapterFiles(\n projectRoot: string,\n): Promise<V3AdapterFilePlan[]> {\n const root = path.resolve(projectRoot);\n const existing = new Map<V3AdapterFileTarget, string | null>();\n for (const target of V3_ADAPTER_FILE_TARGETS) {\n existing.set(target, await readAdapterTarget(root, target));\n }\n const agents = removeLegacyAgentsBlocks(existing.get('agents') ?? '');\n const nextAgents = replaceManagedV3BlockText(\n replaceManagedV3BlockText(\n agents,\n V3_CODEX_START_MARKER,\n V3_CODEX_END_MARKER,\n renderV3Bootstrap('codex'),\n ),\n V3_ZCODE_START_MARKER,\n V3_ZCODE_END_MARKER,\n renderV3Bootstrap('zcode'),\n );\n const legacyAdapterPlans = planLegacyAdapterRetirement(existing);\n const plans: V3AdapterFilePlan[] = [\n managedFilePlan(\n 'claude-skill',\n existing.get('claude-skill') ?? null,\n renderClaudeSkill(renderV3Bootstrap('claude-code')),\n ),\n managedFilePlan(\n 'cursor-rule',\n existing.get('cursor-rule') ?? null,\n renderCursorRule(renderV3Bootstrap('cursor')),\n ),\n {\n target: 'agents',\n beforeContent: existing.get('agents') ?? null,\n targetContent: nextAgents,\n },\n {\n target: 'copilot-instructions',\n beforeContent: existing.get('copilot-instructions') ?? null,\n targetContent: replaceManagedV3BlockText(\n removeManagedBlock(existing.get('copilot-instructions') ?? ''),\n V3_COPILOT_START_MARKER,\n V3_COPILOT_END_MARKER,\n renderV3Bootstrap('copilot'),\n ),\n },\n ...V3_MODE_ENTRY_FILE_TARGETS.map((target) =>\n managedModeEntryPlan(\n target,\n existing.get(target) ?? null,\n renderModeEntryForFileTarget(target),\n ),\n ),\n ...legacyAdapterPlans,\n ];\n return plans;\n}\n\n/** Publishes one precomputed fixed-target replacement with atomic rename. */\nexport async function applyV3AdapterFilePlan(\n projectRoot: string,\n plan: V3AdapterFilePlan,\n): Promise<void> {\n const root = path.resolve(projectRoot);\n if (!V3_ADAPTER_FILE_TARGETS.includes(plan.target)) {\n throw new Error('MANCODE_V3_ADAPTER_TARGET_INVALID');\n }\n if (typeof plan.targetContent !== 'string' || !plan.targetContent.trim()) {\n throw new Error('MANCODE_V3_ADAPTER_TARGET_INVALID');\n }\n const target = v3AdapterTargetPath(root, plan.target);\n await assertAdapterPathSafe(root, target);\n await mkdir(path.dirname(target), { recursive: true });\n await atomicWrite(target, plan.targetContent);\n}\n\n/**\n * Renders a complete adapter candidate under V3 staging. Shadow integration\n * may inspect this exact replacement without changing a live managed file.\n */\nexport async function stageV3Adapter(\n projectRoot: string,\n platform: PlatformName,\n): Promise<V3StagedAdapter> {\n const root = path.resolve(projectRoot);\n await assertPlatformAdapterPathsSafe(root, platform);\n const target = targetFor(platform);\n const content = await renderV3AdapterCandidate(root, platform);\n const stagingTarget = path.join(\n '.mancode',\n 'staging',\n 'adapters',\n 'v3',\n platform,\n target,\n );\n const destination = path.join(root, stagingTarget);\n await assertAdapterPathSafe(root, destination);\n await mkdir(path.dirname(destination), { recursive: true });\n await atomicWrite(destination, content);\n const modeEntries = [] as V3StagedAdapter['modeEntries'];\n for (const mode of V3_MODE_NAMES) {\n const modeTarget = path.relative(\n root,\n v3ModeEntryPath(root, platform, mode),\n );\n const modeStagingTarget = path.join(\n '.mancode',\n 'staging',\n 'adapters',\n 'v3',\n platform,\n modeTarget,\n );\n const modeDestination = path.join(root, modeStagingTarget);\n await assertAdapterPathSafe(root, modeDestination);\n await mkdir(path.dirname(modeDestination), { recursive: true });\n await atomicWrite(modeDestination, renderV3ModeEntry(mode, platform));\n modeEntries.push({\n mode,\n target: modeTarget,\n stagingTarget: modeStagingTarget,\n });\n }\n return { platform, target, stagingTarget, modeEntries };\n}\n\nexport function v3AdapterTargetPath(\n projectRoot: string,\n target: V3AdapterFileTarget,\n): string {\n const root = path.resolve(projectRoot);\n const modeTarget = parseModeEntryFileTarget(target);\n if (modeTarget !== null) {\n return v3ModeEntryPath(root, modeTarget.platform, modeTarget.mode);\n }\n const legacyTarget = legacyAdapterRelativePath(target);\n if (legacyTarget !== null) return path.join(root, legacyTarget);\n switch (target) {\n case 'claude-skill':\n return path.join(root, '.claude', 'skills', 'mancode-v3', 'SKILL.md');\n case 'cursor-rule':\n return path.join(root, '.cursor', 'rules', 'mancode-v3.mdc');\n case 'agents':\n return path.join(root, 'AGENTS.md');\n case 'copilot-instructions':\n return path.join(root, '.github', 'copilot-instructions.md');\n }\n throw new Error('MANCODE_V3_ADAPTER_TARGET_INVALID');\n}\n\n/** Validates every existing segment before a recovery read or removal. */\nexport async function assertV3AdapterTargetSafe(\n projectRoot: string,\n target: V3AdapterFileTarget,\n): Promise<void> {\n const root = path.resolve(projectRoot);\n await assertAdapterPathSafe(root, v3AdapterTargetPath(root, target));\n}\n\n/** The original public mode name, rendered at the host's native entry path. */\nexport function v3ModeEntryPath(\n projectRoot: string,\n platform: PlatformName,\n mode: V3ModeName,\n): string {\n const root = path.resolve(projectRoot);\n switch (platform) {\n case 'claude-code':\n return path.join(root, '.claude', 'skills', mode, 'SKILL.md');\n case 'codex':\n case 'zcode':\n return path.join(root, '.agents', 'skills', mode, 'SKILL.md');\n case 'cursor':\n return path.join(root, '.cursor', 'commands', `${mode}.md`);\n case 'copilot':\n return path.join(root, '.github', 'prompts', `${mode}.prompt.md`);\n }\n}\n\n/**\n * Writes only stable V3 bootstrap instructions. In particular, this never\n * creates legacy authority or copies task state into an adapter file.\n */\nexport async function installV3Adapter(\n projectRoot: string,\n platform: PlatformName,\n): Promise<V3PlatformAdapterStatus> {\n const root = path.resolve(projectRoot);\n await assertV3AdapterInstallable(root, platform);\n const content = renderV3Bootstrap(platform);\n switch (platform) {\n case 'claude-code':\n await writeManagedFile(\n path.join(root, '.claude', 'skills', 'mancode-v3', 'SKILL.md'),\n renderClaudeSkill(content),\n );\n break;\n case 'cursor':\n await writeManagedFile(\n path.join(root, '.cursor', 'rules', 'mancode-v3.mdc'),\n renderCursorRule(content),\n );\n break;\n case 'codex':\n await replaceManagedV3Block(\n path.join(root, 'AGENTS.md'),\n V3_CODEX_START_MARKER,\n V3_CODEX_END_MARKER,\n content,\n [\n [LEGACY_CODEX_START_MARKER, LEGACY_CODEX_END_MARKER],\n [LEGACY_ZCODE_START_MARKER, LEGACY_ZCODE_END_MARKER],\n ],\n );\n break;\n case 'copilot':\n await replaceManagedV3Block(\n path.join(root, '.github', 'copilot-instructions.md'),\n V3_COPILOT_START_MARKER,\n V3_COPILOT_END_MARKER,\n content,\n [[LEGACY_CODEX_START_MARKER, LEGACY_CODEX_END_MARKER]],\n );\n break;\n case 'zcode':\n await replaceManagedV3Block(\n path.join(root, 'AGENTS.md'),\n V3_ZCODE_START_MARKER,\n V3_ZCODE_END_MARKER,\n content,\n [\n [LEGACY_CODEX_START_MARKER, LEGACY_CODEX_END_MARKER],\n [LEGACY_ZCODE_START_MARKER, LEGACY_ZCODE_END_MARKER],\n ],\n );\n break;\n }\n await retireLegacyPlatformFiles(root, platform);\n for (const mode of V3_MODE_NAMES) {\n await writeV3ModeEntry(\n v3ModeEntryPath(root, platform, mode),\n renderV3ModeEntry(mode, platform),\n );\n }\n return inspectV3Adapter(root, platform);\n}\n\n/**\n * Proves all deterministic adapter writes are safe before initialization or\n * repair publishes its first file. I/O can still fail later, but user-owned\n * targets, malformed managed settings, and unsafe paths cannot leave a known\n * partial install behind.\n */\nexport async function assertV3AdapterInstallable(\n projectRoot: string,\n platform: PlatformName,\n): Promise<void> {\n const root = path.resolve(projectRoot);\n await assertPlatformAdapterPathsSafe(root, platform);\n await assertV3ModeEntriesWritable(root, platform);\n await renderV3AdapterCandidate(root, platform);\n\n const existing = new Map<V3AdapterFileTarget, string | null>();\n for (const target of legacyAdapterTargetsForPlatform(platform, true)) {\n existing.set(target, await readAdapterTarget(root, target));\n }\n planLegacyAdapterRetirement(existing);\n}\n\n/** Physical adapter status intentionally does not infer hook approval. */\nexport async function inspectV3Adapter(\n projectRoot: string,\n platform: PlatformName,\n): Promise<V3PlatformAdapterStatus> {\n const root = path.resolve(projectRoot);\n await assertPlatformAdapterPathsSafe(root, platform);\n const target = targetFor(platform);\n const bootstrapInstalled = await adapterTargetPresent(root, platform);\n const modeEntriesInstalled = (\n await Promise.all(\n V3_MODE_NAMES.map((mode) =>\n v3ModeEntryPresent(v3ModeEntryPath(root, platform, mode)),\n ),\n )\n ).every(Boolean);\n const installed = bootstrapInstalled && modeEntriesInstalled;\n return {\n version: V3_ADAPTER_VERSION,\n installed,\n ready: installed,\n target,\n detail: installed\n ? 'mancode bootstrap and original mode entries are present; session identity is explicit-required.'\n : 'mancode bootstrap or one of its original mode entries is not installed.',\n capabilities: capabilitiesFor(platform),\n };\n}\n\n/** Actual on-disk inventory for compatibility gates; never trust manifest echo. */\nexport async function inspectV3AdapterVersions(\n projectRoot: string,\n): Promise<Record<PlatformName, string>> {\n const platforms: PlatformName[] = [\n 'claude-code',\n 'codex',\n 'cursor',\n 'copilot',\n 'zcode',\n ];\n const entries = await Promise.all(\n platforms.map(async (platform) => {\n const status = await inspectV3Adapter(projectRoot, platform);\n return [platform, status.ready ? status.version : 'missing'] as const;\n }),\n );\n return Object.fromEntries(entries) as Record<PlatformName, string>;\n}\n\n/** Removes only the V3 bootstrap owned by this renderer, never V3 authority. */\nexport async function removeV3Adapter(\n projectRoot: string,\n platform: PlatformName,\n): Promise<void> {\n const root = path.resolve(projectRoot);\n await assertPlatformAdapterPathsSafe(root, platform);\n let preserveSharedModeEntries = false;\n switch (platform) {\n case 'claude-code':\n await removeManagedFile(\n path.join(root, '.claude', 'skills', 'mancode-v3', 'SKILL.md'),\n );\n break;\n case 'cursor':\n await removeManagedFile(\n path.join(root, '.cursor', 'rules', 'mancode-v3.mdc'),\n );\n break;\n case 'codex':\n await removeManagedV3Block(\n path.join(root, 'AGENTS.md'),\n V3_CODEX_START_MARKER,\n V3_CODEX_END_MARKER,\n );\n preserveSharedModeEntries = await managedBlockPresent(\n path.join(root, 'AGENTS.md'),\n V3_ZCODE_START_MARKER,\n V3_ZCODE_END_MARKER,\n );\n break;\n case 'copilot':\n await removeManagedV3Block(\n path.join(root, '.github', 'copilot-instructions.md'),\n V3_COPILOT_START_MARKER,\n V3_COPILOT_END_MARKER,\n );\n break;\n case 'zcode':\n await removeManagedV3Block(\n path.join(root, 'AGENTS.md'),\n V3_ZCODE_START_MARKER,\n V3_ZCODE_END_MARKER,\n );\n preserveSharedModeEntries = await managedBlockPresent(\n path.join(root, 'AGENTS.md'),\n V3_CODEX_START_MARKER,\n V3_CODEX_END_MARKER,\n );\n break;\n }\n if (!preserveSharedModeEntries) {\n for (const mode of V3_MODE_NAMES) {\n await removeV3ModeEntry(v3ModeEntryPath(root, platform, mode));\n }\n }\n await removeRetiredLegacyPlatformFiles(root, platform);\n}\n\nexport function renderV3Bootstrap(platform: PlatformName): string {\n const platformLabel = platformLabelFor(platform);\n const sessionArguments = sessionArgumentsFor(platform);\n const sessionCreationGuidance =\n platform === 'codex' || platform === 'zcode'\n ? 'When status has no `currentSession`, first reuse any explicit session ID already returned in this conversation. Only when neither exists, create one once with `mancode context session new --client codex` in Codex or `mancode context session new --client zcode` in ZCode.'\n : `When status has no \\`currentSession\\`, first reuse any explicit session ID already returned in this conversation. Only when neither exists, create one once with \\`mancode context session new --client ${platform}\\`.`;\n const spikePlatform =\n platform === 'codex' || platform === 'zcode'\n ? 'the active Codex or ZCode host'\n : platform;\n const modeEntry = capabilitiesFor(platform).nativeModeEntry\n ? 'Use the platform mode entry only as a shortcut; resolve a Context Pack first.'\n : 'This platform has no native mancode mode entry; use the CLI commands explicitly.';\n return [\n '# mancode bootstrap',\n '',\n V3_ADAPTER_MANAGED_MARKER,\n '',\n `- Platform: ${platformLabel}. This file is a non-authoritative bootstrap.`,\n '- Locate the project root before running mancode commands.',\n '- First run `mancode status --json` from the project root.',\n '- Treat status values such as `authority: \"v3\"` and `v3_active` as internal machine fields. In operator-facing narration, say `mancode`; never prefix a mode or action with a version label.',\n '- An explicitly invoked original `man`, `manba`, `manteam`, `manps`, or `mansolo` entry supplies its authorized action. Its mode-specific steps override conflicting generic no-task or mutation guidance below.',\n '- In particular, `manps` may run local health scans without an actor, session, or TaskRef. `mansolo` needs them only for an explicit governed handoff.',\n '- If status has no `localIdentity.actorId`, ask for a display name and run `mancode team identity create --name \"<display name>\"` before creating a session.',\n '- If status reports `currentSession`, reuse it. `currentTask: null` and `MANCODE_TASK_REQUIRED` do not make a session stale.',\n `- ${sessionCreationGuidance} Pass its returned \\`sessionId\\` and matching client as \\`${sessionArguments}\\` to every later session command; an \\`export\\` inside one command tool does not persist to later command tools.`,\n '- Outside an invoked original mode entry, if no current task and no task is explicitly supplied, report \"no task bound\" and stop. Do not probe workflow subcommands to work around `MANCODE_TASK_REQUIRED`.',\n '- Bootstrap discovery is read-only: before the operator explicitly requests task work, do not run `mancode init`, `mancode migrate`, `mancode workflow`, or inspect mancode installed package/source.',\n `- With an existing or supplied task, read its Context Pack with \\`mancode context show --purpose orient ${sessionArguments}\\`; for anonymous diagnosis, include an explicit \\`--task <namespace:id>\\`.`,\n '- After an operator explicitly requests task work, perform mutations only through `mancode workflow`, `mancode team`, and `mancode context` commands with their required revision and session arguments.',\n '- For a mode entry, request the matching Context Pack purpose: `plan`, `implement`, `review`, `verify`, or `handoff`.',\n '- Do not persist task, mode, or session state in this adapter file or any legacy state file.',\n `- ${modeEntry}`,\n `- No approved session or prompt hook is assumed. After a real-host spike is recorded for ${spikePlatform}, a verified host may provide MANCODE_HOST_SESSION_KEY; otherwise mutations require an explicit \\`--session\\`.`,\n ].join('\\n');\n}\n\n/**\n * One renderer backs every original mode name. The entry contains navigation\n * only; V3 stores remain the sole authority for sessions, tasks, and workflow\n * revisions.\n */\nexport function renderV3ModeEntry(\n mode: V3ModeName,\n platform: PlatformName,\n): string {\n const definition = V3_MODE_DEFINITIONS[mode];\n const sessionArguments = sessionArgumentsFor(platform);\n const sessionClientGuidance = sessionClientGuidanceFor(platform);\n const sessionCreationGuidance =\n platform === 'codex' || platform === 'zcode'\n ? 'If status has no current session, reuse an explicit session ID already retained in this conversation. Only if neither exists, run `mancode context session new --client codex` in Codex or `mancode context session new --client zcode` in ZCode exactly once, then retain the returned session ID.'\n : `If status has no current session, reuse an explicit session ID already retained in this conversation. Only if neither exists, run \\`mancode context session new --client ${platform}\\` exactly once and retain the returned session ID.`;\n let authoritySteps: string[];\n if (mode === 'manps') {\n authoritySteps = [\n '1. Run `mancode status --json` from the project root and require active mancode authority.',\n '2. Run the health action below directly. A local scan needs no TaskRef, actor identity, or explicit session.',\n '3. Never read or write legacy mode authority before or after the scan.',\n ];\n } else if (mode === 'mansolo') {\n authoritySteps = [\n '1. Run `mancode status --json` from the project root. Never read or write legacy mode authority.',\n '2. If no governed task is being handed off, continue with focused solo work without creating a persistent mode, actor, session, or TaskRef.',\n `3. For an explicit governed handoff, ensure \\`localIdentity.actorId\\`, reuse or create the current session, and bind the existing TaskRef. ${sessionCreationGuidance} ${sessionClientGuidance}`,\n `4. For that governed task only, read \\`mancode context show --purpose implement ${sessionArguments}\\` using the bound or explicit TaskRef.`,\n ];\n } else if (mode === 'man') {\n authoritySteps = [\n '1. Run `mancode status --json` from the project root. Never read or write the legacy authority file.',\n '2. If the request is only a read-only project orientation, introduction, explanation, or summary, inspect the repository and answer directly without creating an actor, session, TaskRef, or workflow. Do not turn an orientation request into a `plan_only` workflow.',\n '3. Only for requested governed task work, if `localIdentity.actorId` is absent, ask for a display name and run `mancode team identity create --name \"<display name>\"`.',\n `4. Reuse \\`currentSession.sessionId\\` when present. ${sessionCreationGuidance} ${sessionClientGuidance}`,\n `5. Reuse the current TaskRef. To bind a supplied existing task, run \\`mancode context resume <namespace:ULID> ${sessionArguments}\\`.`,\n `6. For an existing task, read only the needed Context Pack with \\`mancode context show --purpose ${definition.contextPurpose} ${sessionArguments}\\`; include \\`--task <namespace:ULID>\\` when it is not yet bound. For a new task, create it through the mode action first, then read the returned TaskRef's Context Pack.`,\n ];\n } else {\n authoritySteps = [\n '1. Run `mancode status --json` from the project root. Never read or write the legacy authority file.',\n '2. If `localIdentity.actorId` is absent, ask for a display name and run `mancode team identity create --name \"<display name>\"`.',\n `3. Reuse \\`currentSession.sessionId\\` when present. ${sessionCreationGuidance} ${sessionClientGuidance}`,\n `4. Reuse the current TaskRef. To bind a supplied existing task, run \\`mancode context resume <namespace:ULID> ${sessionArguments}\\`.`,\n `5. For an existing task, read only the needed Context Pack with \\`mancode context show --purpose ${definition.contextPurpose} ${sessionArguments}\\`; include \\`--task <namespace:ULID>\\` when it is not yet bound. For a new task, create it through the mode action first, then read the returned TaskRef's Context Pack.`,\n ];\n }\n const frontmatter = [\n '---',\n ...(platform === 'claude-code' ||\n platform === 'codex' ||\n platform === 'zcode'\n ? [`name: ${mode}`]\n : []),\n ...(platform === 'copilot' ? [\"agent: 'agent'\"] : []),\n `description: ${JSON.stringify(definition.description)}`,\n '---',\n ];\n const mutationGuidance =\n mode === 'manps'\n ? 'The local scan and an explicitly requested remediation do not require a TaskRef, workflow revision, actor, or session. Never turn their report files into workflow authority.'\n : mode === 'mansolo'\n ? 'Only an explicit governed handoff mutation requires the bound TaskRef, explicit session, and latest expected revision. Ordinary focused solo work persists no mode state.'\n : 'For every mutation, use the TaskRef, explicit session, matching client, and latest expected revision reported by mancode. Do not emulate the legacy `--step` protocol or persist mode state in an adapter file.';\n const actions = definition.actions.map((action) =>\n action.replaceAll('--session <id>', sessionArguments),\n );\n return [\n ...frontmatter,\n '',\n V3_MODE_ENTRY_MANAGED_MARKER,\n '',\n `# mancode mode: ${mode}`,\n '',\n `Purpose: ${definition.purpose}.`,\n '',\n '## Enter through mancode',\n '',\n ...authoritySteps,\n '',\n '## Mode action',\n '',\n ...actions,\n '',\n 'Treat status values such as `authority: \"v3\"` and `v3_active` as internal machine fields. In operator-facing narration, say `mancode`; never prefix this mode or its actions with a version label.',\n '',\n mutationGuidance,\n '',\n ].join('\\n');\n}\n\nfunction sessionArgumentsFor(platform: PlatformName): string {\n const client =\n platform === 'codex' || platform === 'zcode' ? '<active-client>' : platform;\n return `--session <id> --client ${client}`;\n}\n\nfunction sessionClientGuidanceFor(platform: PlatformName): string {\n return platform === 'codex' || platform === 'zcode'\n ? 'Use `--client codex` in Codex or `--client zcode` in ZCode on every command that uses this session.'\n : `Use \\`--client ${platform}\\` on every command that uses this session.`;\n}\n\nconst V3_MODE_DEFINITIONS: Record<\n V3ModeName,\n {\n description: string;\n purpose: string;\n contextPurpose:\n | 'orient'\n | 'plan'\n | 'implement'\n | 'review'\n | 'verify'\n | 'handoff';\n actions: string[];\n }\n> = {\n man: {\n description: 'Plan and execute governed work through mancode.',\n purpose: 'clarify, plan, implement, verify, and review governed work',\n contextPurpose: 'plan',\n actions: [\n '- For a read-only project orientation, inspect and answer directly; do not create governance records.',\n '- For a new task, run `mancode workflow create man \"<task>\" --session <id>`.',\n '- Write requirements as semantic JSON with `version: 1`, `goal`, `confirmedScope`, `excludedScope`, `technicalDecisions`, `defaults`, `blockingUnknowns`, all seven `coverage` dimensions, and `acceptanceCriteria`; mancode generates canonical internal IDs and digests.',\n '- Finalize requirements with `mancode workflow requirements <namespace:ULID> finalize --file <requirements.json> --expected-revision <n> --session <id>`.',\n '- Revise or confirm the plan with `mancode workflow plan <namespace:ULID> revise|confirm --expected-revision <n> ... --session <id>`.',\n '- Apply verification and review ledgers with their mancode `apply --file` commands, then use `mancode workflow complete <namespace:ULID> --expected-revision <n> --session <id>`.',\n ],\n },\n manba: {\n description: 'Diagnose and verify a bug through mancode.',\n purpose: 'reproduce, diagnose, fix, and verify a regression',\n contextPurpose: 'implement',\n actions: [\n '- For a new diagnostic task, run `mancode workflow create manba \"<task>\" --session <id>`.',\n '- When this is a child investigation, add `--parent <namespace:ULID>`; report and merge the typed outcome through the mancode child commands.',\n '- Change lifecycle only with `mancode workflow update <namespace:ULID> --status <status> --expected-revision <n> --session <id>` and finish with `workflow complete` plus the typed `--outcome`.',\n ],\n },\n manteam: {\n description: 'Coordinate shared governed work through mancode.',\n purpose: 'plan and execute work with explicit team ownership and handoff',\n contextPurpose: 'plan',\n actions: [\n '- Confirm team membership with `mancode team status`; join invited participants before assigning shared work.',\n '- For a new shared task, run `mancode workflow create manteam \"<task>\" --visibility shared --coordination team --confirm-shared --session <id>`.',\n '- Use claims, checkpoints, sync, and handoffs through `mancode team`; never infer ownership from an adapter prompt.',\n '- Use the same mancode requirements, plan, verification, review, and completion commands as `man`, adding `--sync` whenever the active transport requires it.',\n ],\n },\n manps: {\n description: 'Inspect project health through mancode.',\n purpose: 'scan project health and review bounded remediation',\n contextPurpose: 'review',\n actions: [\n '- Run `mancode manps [area]` through the same public command entry (`all`, `deps`, `security`, `dead-code`, or `config`).',\n '- Add `--remediate` only when the operator explicitly requests an interactive remediation review.',\n ],\n },\n mansolo: {\n description: 'Return to focused solo execution through mancode.',\n purpose: 'perform a small focused task or accept an explicit solo handoff',\n contextPurpose: 'implement',\n actions: [\n '- Do not create or persist a legacy solo mode. Ordinary focused work needs no TaskRef; if the operator expects a governed task, use its bound TaskRef or report that none is bound.',\n '- For a governed-to-solo transition, use `mancode workflow handoff <namespace:ULID> --to solo --expected-revision <n> --session <id>`.',\n ],\n },\n};\n\nasync function renderV3AdapterCandidate(\n root: string,\n platform: PlatformName,\n): Promise<string> {\n switch (platform) {\n case 'claude-code': {\n const existing = await readAdapterTarget(root, 'claude-skill');\n return managedFilePlan(\n 'claude-skill',\n existing,\n renderClaudeSkill(renderV3Bootstrap(platform)),\n ).targetContent;\n }\n case 'cursor': {\n const existing = await readAdapterTarget(root, 'cursor-rule');\n return managedFilePlan(\n 'cursor-rule',\n existing,\n renderCursorRule(renderV3Bootstrap(platform)),\n ).targetContent;\n }\n case 'codex': {\n const existing = (await readAdapterTarget(root, 'agents')) ?? '';\n return replaceManagedV3BlockText(\n removeLegacyAgentsBlocks(existing),\n V3_CODEX_START_MARKER,\n V3_CODEX_END_MARKER,\n renderV3Bootstrap(platform),\n );\n }\n case 'copilot': {\n const existing =\n (await readAdapterTarget(root, 'copilot-instructions')) ?? '';\n return replaceManagedV3BlockText(\n removeManagedBlock(existing),\n V3_COPILOT_START_MARKER,\n V3_COPILOT_END_MARKER,\n renderV3Bootstrap(platform),\n );\n }\n case 'zcode': {\n const existing = (await readAdapterTarget(root, 'agents')) ?? '';\n return replaceManagedV3BlockText(\n removeLegacyAgentsBlocks(existing),\n V3_ZCODE_START_MARKER,\n V3_ZCODE_END_MARKER,\n renderV3Bootstrap(platform),\n );\n }\n }\n}\n\nfunction renderClaudeSkill(content: string): string {\n return [\n '---',\n 'name: mancode-v3',\n 'description: \"Internal bootstrap for the original mancode mode entries.\"',\n 'user-invocable: false',\n '---',\n '',\n content,\n '',\n ].join('\\n');\n}\n\nfunction renderCursorRule(content: string): string {\n return [\n '---',\n 'description: \"Stable bootstrap for mancode context and workflow commands.\"',\n 'alwaysApply: true',\n 'globs: \"**/*\"',\n '---',\n '',\n content,\n '',\n ].join('\\n');\n}\n\nasync function adapterTargetPresent(\n root: string,\n platform: PlatformName,\n): Promise<boolean> {\n switch (platform) {\n case 'claude-code':\n return managedFilePresent(\n path.join(root, '.claude', 'skills', 'mancode-v3', 'SKILL.md'),\n );\n case 'cursor':\n return managedFilePresent(\n path.join(root, '.cursor', 'rules', 'mancode-v3.mdc'),\n );\n case 'codex':\n return managedBlockPresent(\n path.join(root, 'AGENTS.md'),\n V3_CODEX_START_MARKER,\n V3_CODEX_END_MARKER,\n );\n case 'copilot':\n return managedBlockPresent(\n path.join(root, '.github', 'copilot-instructions.md'),\n V3_COPILOT_START_MARKER,\n V3_COPILOT_END_MARKER,\n );\n case 'zcode':\n return managedBlockPresent(\n path.join(root, 'AGENTS.md'),\n V3_ZCODE_START_MARKER,\n V3_ZCODE_END_MARKER,\n );\n }\n}\n\nasync function writeManagedFile(\n filePath: string,\n content: string,\n): Promise<void> {\n const existing = await readTextIfExists(filePath);\n if (existing !== null && !existing.includes(V3_ADAPTER_MANAGED_MARKER)) {\n throw new Error('MANCODE_V3_ADAPTER_TARGET_USER_AUTHORED');\n }\n await mkdir(path.dirname(filePath), { recursive: true });\n await atomicWrite(filePath, content);\n}\n\nasync function writeV3ModeEntry(\n filePath: string,\n content: string,\n): Promise<void> {\n const existing = await readTextIfExists(filePath);\n const managed =\n existing === null ||\n existing.includes(V3_MODE_ENTRY_MANAGED_MARKER) ||\n LEGACY_MODE_ENTRY_MANAGED_MARKERS.some((marker) =>\n existing.includes(marker),\n );\n if (!managed) {\n throw new Error('MANCODE_V3_MODE_ENTRY_USER_AUTHORED');\n }\n await mkdir(path.dirname(filePath), { recursive: true });\n await atomicWrite(filePath, content);\n}\n\nasync function assertV3ModeEntriesWritable(\n root: string,\n platform: PlatformName,\n): Promise<void> {\n for (const mode of V3_MODE_NAMES) {\n const existing = await readTextIfExists(\n v3ModeEntryPath(root, platform, mode),\n );\n if (\n existing !== null &&\n !existing.includes(V3_MODE_ENTRY_MANAGED_MARKER) &&\n !LEGACY_MODE_ENTRY_MANAGED_MARKERS.some((marker) =>\n existing.includes(marker),\n )\n ) {\n throw new Error('MANCODE_V3_MODE_ENTRY_USER_AUTHORED');\n }\n }\n}\n\nasync function removeV3ModeEntry(filePath: string): Promise<void> {\n const existing = await readTextIfExists(filePath);\n if (existing?.includes(V3_MODE_ENTRY_MANAGED_MARKER)) {\n await rm(filePath, { force: true });\n await removeDirectoryIfEmpty(path.dirname(filePath));\n }\n}\n\nasync function v3ModeEntryPresent(filePath: string): Promise<boolean> {\n const existing = await readTextIfExists(filePath);\n return existing?.includes(V3_MODE_ENTRY_MANAGED_MARKER) ?? false;\n}\n\nasync function removeDirectoryIfEmpty(directory: string): Promise<void> {\n try {\n await rmdir(directory);\n } catch (error) {\n if (\n isNodeError(error) &&\n (error.code === 'ENOENT' ||\n error.code === 'ENOTEMPTY' ||\n error.code === 'EEXIST')\n ) {\n return;\n }\n throw error;\n }\n}\n\nasync function removeManagedFile(filePath: string): Promise<void> {\n const existing = await readTextIfExists(filePath);\n if (existing?.includes(V3_ADAPTER_MANAGED_MARKER)) {\n await rm(filePath, { force: true });\n }\n}\n\nasync function replaceManagedV3Block(\n filePath: string,\n startMarker: string,\n endMarker: string,\n content: string,\n legacyMarkers?: readonly (readonly [string, string])[],\n): Promise<void> {\n const current = (await readTextIfExists(filePath)) ?? '';\n const existing = (legacyMarkers ?? []).reduce(\n (contentWithoutLegacy, [legacyStart, legacyEnd]) =>\n removeManagedBlock(contentWithoutLegacy, legacyStart, legacyEnd),\n current,\n );\n const block = [startMarker, content, endMarker].join('\\n');\n await mkdir(path.dirname(filePath), { recursive: true });\n await atomicWrite(\n filePath,\n replaceManagedBlock(existing, block, startMarker, endMarker),\n );\n}\n\nfunction removeLegacyAgentsBlocks(existing: string): string {\n return removeManagedBlock(\n removeManagedBlock(\n existing,\n LEGACY_CODEX_START_MARKER,\n LEGACY_CODEX_END_MARKER,\n ),\n LEGACY_ZCODE_START_MARKER,\n LEGACY_ZCODE_END_MARKER,\n );\n}\n\nfunction replaceManagedV3BlockText(\n existing: string,\n startMarker: string,\n endMarker: string,\n content: string,\n): string {\n return replaceManagedBlock(\n existing,\n [startMarker, content, endMarker].join('\\n'),\n startMarker,\n endMarker,\n );\n}\n\nfunction managedFilePlan(\n target: V3AdapterFileTarget,\n beforeContent: string | null,\n targetContent: string,\n): V3AdapterFilePlan {\n if (\n beforeContent !== null &&\n !beforeContent.includes(V3_ADAPTER_MANAGED_MARKER)\n ) {\n throw new Error('MANCODE_V3_ADAPTER_TARGET_USER_AUTHORED');\n }\n return { target, beforeContent, targetContent };\n}\n\nfunction managedModeEntryPlan(\n target: V3ModeEntryFileTarget,\n beforeContent: string | null,\n targetContent: string,\n): V3AdapterFilePlan {\n if (\n beforeContent !== null &&\n !beforeContent.includes(V3_MODE_ENTRY_MANAGED_MARKER) &&\n !LEGACY_MODE_ENTRY_MANAGED_MARKERS.some((marker) =>\n beforeContent.includes(marker),\n )\n ) {\n throw new Error('MANCODE_V3_MODE_ENTRY_USER_AUTHORED');\n }\n return { target, beforeContent, targetContent };\n}\n\nfunction planLegacyAdapterRetirement(\n existing: ReadonlyMap<V3AdapterFileTarget, string | null>,\n): V3AdapterFilePlan[] {\n const plans: V3AdapterFilePlan[] = [];\n const settings = existing.get('claude-settings') ?? null;\n if (settings !== null) {\n const cleaned = removeLegacyClaudeSettings(settings);\n if (cleaned !== settings) {\n plans.push({\n target: 'claude-settings',\n beforeContent: settings,\n targetContent: cleaned,\n });\n }\n }\n\n const legacySolo = existing.get('claude-legacy-solo') ?? null;\n if (\n legacySolo?.includes(\n '<!-- Managed by mancode:claude-skill. Do not edit this marker. -->',\n )\n ) {\n plans.push({\n target: 'claude-legacy-solo',\n beforeContent: legacySolo,\n targetContent: renderRetiredClaudeSoloEntry(),\n });\n }\n\n for (const target of V3_LEGACY_ADAPTER_FILE_TARGETS) {\n if (!target.startsWith('cursor-legacy-')) continue;\n const beforeContent = existing.get(target) ?? null;\n if (\n beforeContent?.includes(\n '<!-- Managed by mancode:cursor-rule. Do not edit this marker. -->',\n )\n ) {\n plans.push({\n target,\n beforeContent,\n targetContent: renderRetiredCursorRule(target),\n });\n }\n }\n for (const target of V3_LEGACY_ADAPTER_FILE_TARGETS) {\n const alias = parseLegacyModeAliasTarget(target);\n if (alias === null) continue;\n const beforeContent = existing.get(target) ?? null;\n if (\n beforeContent !== null &&\n isGeneratedLegacyModeAlias(beforeContent, alias.alias)\n ) {\n plans.push({\n target,\n beforeContent,\n targetContent: renderRetiredModeAlias(target),\n });\n }\n }\n return plans;\n}\n\nasync function retireLegacyPlatformFiles(\n root: string,\n platform: PlatformName,\n): Promise<void> {\n const targets = legacyAdapterTargetsForPlatform(platform, true);\n if (targets.length === 0) return;\n const existing = new Map<V3AdapterFileTarget, string | null>();\n for (const target of targets) {\n existing.set(target, await readAdapterTarget(root, target));\n }\n for (const plan of planLegacyAdapterRetirement(existing)) {\n await applyV3AdapterFilePlan(root, plan);\n }\n}\n\nasync function removeRetiredLegacyPlatformFiles(\n root: string,\n platform: PlatformName,\n): Promise<void> {\n const targets = legacyAdapterTargetsForPlatform(platform, false);\n for (const target of targets) {\n const filePath = v3AdapterTargetPath(root, target);\n const content = await readTextIfExists(filePath);\n const retiredModeEntry =\n target === 'claude-legacy-solo' ||\n parseLegacyModeAliasTarget(target) !== null;\n const retired = content?.includes(\n retiredModeEntry\n ? V3_MODE_ENTRY_MANAGED_MARKER\n : V3_ADAPTER_MANAGED_MARKER,\n );\n if (retired) {\n await rm(filePath, { force: true });\n if (\n target === 'claude-legacy-solo' ||\n target.startsWith('claude-alias-') ||\n target.startsWith('agents-alias-')\n ) {\n await removeDirectoryIfEmpty(path.dirname(filePath));\n }\n }\n }\n}\n\nfunction legacyAdapterTargetsForPlatform(\n platform: PlatformName,\n includeSettings: boolean,\n): V3LegacyAdapterFileTarget[] {\n if (platform === 'claude-code') {\n return [\n ...(includeSettings ? (['claude-settings'] as const) : []),\n 'claude-legacy-solo',\n ...V3_LEGACY_ADAPTER_FILE_TARGETS.filter((target) =>\n target.startsWith('claude-alias-'),\n ),\n ];\n }\n if (platform === 'cursor') {\n return V3_LEGACY_ADAPTER_FILE_TARGETS.filter((target) =>\n /^(cursor-legacy|cursor-alias)-/u.test(target),\n );\n }\n if (platform === 'codex' || platform === 'zcode') {\n return V3_LEGACY_ADAPTER_FILE_TARGETS.filter((target) =>\n target.startsWith('agents-alias-'),\n );\n }\n return V3_LEGACY_ADAPTER_FILE_TARGETS.filter((target) =>\n target.startsWith('copilot-alias-'),\n );\n}\n\nfunction removeLegacyClaudeSettings(content: string): string {\n const hasKnownLegacyReference = LEGACY_CLAUDE_SETTINGS_RAW_HINTS.some(\n (value) => content.includes(value),\n );\n if (!hasKnownLegacyReference) return content;\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n throw new Error('MANCODE_V3_CLAUDE_SETTINGS_INVALID');\n }\n if (!isRecord(parsed)) {\n throw new Error('MANCODE_V3_CLAUDE_SETTINGS_INVALID');\n }\n const hasGeneratedHook = containsGeneratedClaudeHookValue(parsed.hooks);\n const hasGeneratedSkill =\n isRecord(parsed.skills) &&\n Object.values(parsed.skills).some(\n (value) =>\n typeof value === 'string' && LEGACY_CLAUDE_SKILL_PATHS.has(value),\n );\n if (!hasGeneratedHook && !hasGeneratedSkill) return content;\n const settings: Record<string, unknown> = { ...parsed };\n if ('hooks' in settings) {\n const hooks = removeGeneratedClaudeHookValue(settings.hooks);\n if (hooks === undefined) settings.hooks = undefined;\n else settings.hooks = hooks;\n }\n if (isRecord(settings.skills)) {\n const skills = Object.fromEntries(\n Object.entries(settings.skills).filter(\n ([, value]) =>\n typeof value !== 'string' || !LEGACY_CLAUDE_SKILL_PATHS.has(value),\n ),\n );\n if (Object.keys(skills).length === 0) settings.skills = undefined;\n else settings.skills = skills;\n }\n return `${JSON.stringify(settings, null, 2)}\\n`;\n}\n\nfunction containsGeneratedClaudeHookValue(value: unknown): boolean {\n if (Array.isArray(value)) {\n return value.some(containsGeneratedClaudeHookValue);\n }\n if (!isRecord(value)) return false;\n if (\n typeof value.command === 'string' &&\n isGeneratedClaudeHookCommand(value.command)\n ) {\n return true;\n }\n return Object.values(value).some(containsGeneratedClaudeHookValue);\n}\n\nfunction removeGeneratedClaudeHookValue(value: unknown): unknown | undefined {\n if (Array.isArray(value)) {\n const cleaned = value\n .map(removeGeneratedClaudeHookValue)\n .filter((entry) => entry !== undefined);\n return cleaned.length > 0 ? cleaned : undefined;\n }\n if (!isRecord(value)) return value;\n if (\n typeof value.command === 'string' &&\n isGeneratedClaudeHookCommand(value.command)\n ) {\n return undefined;\n }\n if (Array.isArray(value.hooks)) {\n const hooks = value.hooks\n .map(removeGeneratedClaudeHookValue)\n .filter((entry) => entry !== undefined);\n return hooks.length > 0 ? { ...value, hooks } : undefined;\n }\n const cleaned = Object.entries(value).flatMap(([key, entry]) => {\n const next = removeGeneratedClaudeHookValue(entry);\n return next === undefined ? [] : [[key, next] as const];\n });\n return cleaned.length > 0 ? Object.fromEntries(cleaned) : undefined;\n}\n\nfunction isGeneratedClaudeHookCommand(command: string): boolean {\n return GENERATED_CLAUDE_HOOK_COMMANDS.has(command.trim());\n}\n\nfunction renderRetiredClaudeSoloEntry(): string {\n return [\n '---',\n 'name: solo',\n 'description: \"Compatibility alias for the mancode mansolo entry.\"',\n 'user-invocable: false',\n '---',\n '',\n V3_MODE_ENTRY_MANAGED_MARKER,\n '',\n '# mancode mode compatibility alias',\n '',\n 'Use the `mansolo` mode entry. Resolve mancode status, identity, session, TaskRef, and Context Pack there; do not use legacy mode persistence.',\n '',\n ].join('\\n');\n}\n\nfunction renderRetiredCursorRule(target: V3LegacyAdapterFileTarget): string {\n const legacyName = target.replace('cursor-legacy-', '');\n const mode =\n legacyName === 'solo'\n ? 'mansolo'\n : legacyName === 'mamba'\n ? 'manba'\n : legacyName === 'man8'\n ? 'man'\n : legacyName;\n const guidance =\n mode === 'context' || mode === 'practice'\n ? 'Run `mancode status --json`, then use the matching mancode mode command.'\n : `Use the \\`/${mode}\\` mancode mode command.`;\n return [\n '---',\n 'description: \"Retired legacy mancode rule; current mancode mode entries are authoritative.\"',\n 'alwaysApply: false',\n 'globs: \"__mancode_v3_retired_rule__\"',\n '---',\n '',\n V3_ADAPTER_MANAGED_MARKER,\n '',\n '# mancode compatibility redirect',\n '',\n guidance,\n 'Do not use legacy mode persistence or legacy workflow paths.',\n '',\n ].join('\\n');\n}\n\nfunction renderRetiredModeAlias(target: V3AdapterFileTarget): string {\n const parsed = parseLegacyModeAliasTarget(target);\n if (parsed === null) {\n throw new Error('MANCODE_V3_ADAPTER_TARGET_INVALID');\n }\n const publicMode = parsed.alias === 'mamba' ? 'manba' : 'man';\n const frontmatter = [\n '---',\n ...(parsed.family === 'claude' || parsed.family === 'agents'\n ? [`name: ${parsed.alias}`]\n : []),\n ...(parsed.family === 'copilot' ? [\"agent: 'agent'\"] : []),\n ...(parsed.family === 'claude' ? ['user-invocable: false'] : []),\n `description: ${JSON.stringify(`Compatibility alias for the mancode ${publicMode} entry.`)}`,\n '---',\n ];\n return [\n ...frontmatter,\n '',\n V3_MODE_ENTRY_MANAGED_MARKER,\n '',\n '# mancode mode compatibility alias',\n '',\n `The legacy name \\`${parsed.alias}\\` maps to the public mancode mode \\`${publicMode}\\`. Use that original mancode mode entry instead.`,\n '',\n 'Resolve status, identity, session, TaskRef, and Context Pack through mancode there. Do not use legacy mode persistence or the legacy workflow protocol.',\n '',\n ].join('\\n');\n}\n\nfunction isGeneratedLegacyModeAlias(\n content: string,\n alias: LegacyModeAlias,\n): boolean {\n if (\n content.includes(V3_MODE_ENTRY_MANAGED_MARKER) ||\n LEGACY_MODE_ENTRY_MANAGED_MARKERS.some((marker) => content.includes(marker))\n ) {\n return true;\n }\n if (alias !== 'man8') return false;\n return (\n content.includes('# mancode · /man8 (4 AM Warmup)') ||\n (content.includes('# mancode man8 — Investigate and Plan') &&\n content.includes('## Mode Persistence'))\n );\n}\n\nfunction legacyAdapterRelativePath(target: V3AdapterFileTarget): string | null {\n if (target === 'claude-settings')\n return path.join('.claude', 'settings.json');\n if (target === 'claude-legacy-solo') {\n return path.join('.claude', 'skills', 'solo', 'SKILL.md');\n }\n if (target.startsWith('cursor-legacy-')) {\n const name = target.slice('cursor-legacy-'.length);\n return path.join('.cursor', 'rules', `mancode-${name}.mdc`);\n }\n const alias = parseLegacyModeAliasTarget(target);\n if (alias === null) return null;\n switch (alias.family) {\n case 'claude':\n return path.join('.claude', 'skills', alias.alias, 'SKILL.md');\n case 'agents':\n return path.join('.agents', 'skills', alias.alias, 'SKILL.md');\n case 'cursor':\n return path.join('.cursor', 'commands', `${alias.alias}.md`);\n case 'copilot':\n return path.join('.github', 'prompts', `${alias.alias}.prompt.md`);\n }\n}\n\nfunction parseLegacyModeAliasTarget(target: V3AdapterFileTarget): {\n family: 'claude' | 'agents' | 'cursor' | 'copilot';\n alias: LegacyModeAlias;\n} | null {\n const match = /^(claude|agents|cursor|copilot)-alias-(mamba|man8)$/u.exec(\n target,\n );\n if (!match) return null;\n return {\n family: match[1] as 'claude' | 'agents' | 'cursor' | 'copilot',\n alias: match[2] as LegacyModeAlias,\n };\n}\n\nfunction renderModeEntryForFileTarget(target: V3ModeEntryFileTarget): string {\n const parsed = parseModeEntryFileTarget(target);\n if (parsed === null) {\n throw new Error('MANCODE_V3_ADAPTER_TARGET_INVALID');\n }\n return renderV3ModeEntry(parsed.mode, parsed.platform);\n}\n\nfunction parseModeEntryFileTarget(\n target: V3AdapterFileTarget,\n): { platform: PlatformName; mode: V3ModeName } | null {\n const match =\n /^(claude|agents|cursor|copilot)-mode-(manba|man|manteam|manps|mansolo)$/u.exec(\n target,\n );\n if (!match) return null;\n const family = match[1];\n const mode = match[2] as V3ModeName;\n const platform: PlatformName =\n family === 'claude'\n ? 'claude-code'\n : family === 'agents'\n ? 'codex'\n : family === 'cursor'\n ? 'cursor'\n : 'copilot';\n return { platform, mode };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function readAdapterTarget(\n root: string,\n target: V3AdapterFileTarget,\n): Promise<string | null> {\n const filePath = v3AdapterTargetPath(root, target);\n await assertAdapterPathSafe(root, filePath);\n try {\n const entry = await lstat(filePath);\n if (!entry.isFile() || entry.isSymbolicLink()) {\n throw new Error('MANCODE_ARTIFACT_PATH_UNSAFE');\n }\n } catch (error) {\n if (isNodeError(error) && error.code === 'ENOENT') return null;\n throw error;\n }\n return readFile(filePath, 'utf8');\n}\n\nasync function assertPlatformAdapterPathsSafe(\n root: string,\n platform: PlatformName,\n): Promise<void> {\n const targets = new Set<string>([\n path.join(root, targetFor(platform)),\n ...V3_MODE_NAMES.map((mode) => v3ModeEntryPath(root, platform, mode)),\n ...legacyAdapterTargetsForPlatform(platform, true).map((target) =>\n v3AdapterTargetPath(root, target),\n ),\n ]);\n for (const target of targets) {\n await assertAdapterPathSafe(root, target);\n }\n}\n\n/** Rejects a symlink or non-directory in any fixed adapter path segment. */\nasync function assertAdapterPathSafe(\n root: string,\n target: string,\n): Promise<void> {\n const relative = path.relative(root, target);\n if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {\n throw new Error('MANCODE_ARTIFACT_PATH_UNSAFE');\n }\n const rootEntry = await lstat(root);\n if (!rootEntry.isDirectory() || rootEntry.isSymbolicLink()) {\n throw new Error('MANCODE_ARTIFACT_PATH_UNSAFE');\n }\n const segments = relative.split(path.sep);\n let current = root;\n for (let index = 0; index < segments.length; index += 1) {\n current = path.join(current, segments[index] ?? '');\n try {\n const entry = await lstat(current);\n if (\n entry.isSymbolicLink() ||\n (index < segments.length - 1 && !entry.isDirectory())\n ) {\n throw new Error('MANCODE_ARTIFACT_PATH_UNSAFE');\n }\n } catch (error) {\n if (isNodeError(error) && error.code === 'ENOENT') return;\n throw error;\n }\n }\n}\n\nasync function removeManagedV3Block(\n filePath: string,\n startMarker: string,\n endMarker: string,\n): Promise<void> {\n const existing = await readTextIfExists(filePath);\n if (existing === null || !hasManagedBlock(existing, startMarker, endMarker)) {\n return;\n }\n const cleaned = removeManagedBlock(existing, startMarker, endMarker);\n if (cleaned.trim()) {\n await atomicWrite(filePath, `${cleaned.trimEnd()}\\n`);\n } else {\n await rm(filePath, { force: true });\n }\n}\n\nasync function managedFilePresent(filePath: string): Promise<boolean> {\n const content = await readTextIfExists(filePath);\n return content?.includes(V3_ADAPTER_MANAGED_MARKER) ?? false;\n}\n\nasync function managedBlockPresent(\n filePath: string,\n startMarker: string,\n endMarker: string,\n): Promise<boolean> {\n const content = await readTextIfExists(filePath);\n return content !== null && hasManagedBlock(content, startMarker, endMarker);\n}\n\nasync function readTextIfExists(filePath: string): Promise<string | null> {\n for (let attempt = 1; attempt <= ADAPTER_READ_MAX_ATTEMPTS; attempt += 1) {\n try {\n return await readFile(filePath, 'utf8');\n } catch (error) {\n if (isNodeError(error) && error.code === 'ENOENT') return null;\n if (\n !isRetriableAdapterReadError(error) ||\n attempt === ADAPTER_READ_MAX_ATTEMPTS\n ) {\n throw error;\n }\n await delay(ADAPTER_READ_RETRY_DELAY_MS * attempt);\n }\n }\n throw new Error('MANCODE_V3_ADAPTER_READ_RETRY_EXHAUSTED');\n}\n\nasync function atomicWrite(filePath: string, content: string): Promise<void> {\n const temporary = path.join(\n path.dirname(filePath),\n `.${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`,\n );\n try {\n await writeFile(temporary, content, { encoding: 'utf8', flag: 'wx' });\n await rename(temporary, filePath);\n } finally {\n await rm(temporary, { force: true }).catch(() => undefined);\n }\n}\n\nfunction targetFor(platform: PlatformName): string {\n switch (platform) {\n case 'claude-code':\n return '.claude/skills/mancode-v3/SKILL.md';\n case 'cursor':\n return '.cursor/rules/mancode-v3.mdc';\n case 'codex':\n case 'zcode':\n return 'AGENTS.md';\n case 'copilot':\n return '.github/copilot-instructions.md';\n }\n}\n\nfunction platformLabelFor(platform: PlatformName): string {\n switch (platform) {\n case 'claude-code':\n return 'Claude Code';\n case 'cursor':\n return 'Cursor';\n case 'codex':\n return 'Codex or ZCode (shared AGENTS.md bootstrap)';\n case 'copilot':\n return 'GitHub Copilot';\n case 'zcode':\n return 'Codex or ZCode (shared AGENTS.md bootstrap)';\n }\n}\n\nfunction capabilitiesFor(_platform: PlatformName): V3AdapterCapabilities {\n return {\n nativeModeEntry: true,\n sessionHook: false,\n promptHook: false,\n sessionIdentity: 'explicit-required',\n };\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\nfunction isRetriableAdapterReadError(error: unknown): boolean {\n return (\n isNodeError(error) && RETRIABLE_ADAPTER_READ_CODES.has(error.code ?? '')\n );\n}\n\nasync function delay(milliseconds: number): Promise<void> {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, milliseconds);\n });\n}\n","export const DEFAULT_MANCODE_START_MARKER = '<!-- mancode:start -->';\nexport const DEFAULT_MANCODE_END_MARKER = '<!-- mancode:end -->';\n\nexport function removeManagedBlock(\n existing: string,\n startMarker = DEFAULT_MANCODE_START_MARKER,\n endMarker = DEFAULT_MANCODE_END_MARKER,\n): string {\n const start = findMarkerLine(existing, startMarker);\n const end = findMarkerLine(existing, endMarker);\n\n if (start === null && end === null) return existing;\n if (start === null || end === null) return existing;\n if (end.start < start.start) return existing;\n\n const before = existing.slice(0, start.start);\n const after = existing.slice(end.end);\n const merged = `${before}${after}`;\n return cleanUpOrphanedNewlines(merged);\n}\n\nexport function hasManagedBlock(\n existing: string,\n startMarker = DEFAULT_MANCODE_START_MARKER,\n endMarker = DEFAULT_MANCODE_END_MARKER,\n): boolean {\n const start = findMarkerLine(existing, startMarker);\n const end = findMarkerLine(existing, endMarker);\n return start !== null && end !== null && end.start > start.start;\n}\n\nfunction cleanUpOrphanedNewlines(content: string): string {\n const trimmed = content.replace(/\\n{3,}/gu, '\\n\\n').replace(/\\n+$/u, '\\n');\n return trimmed || '';\n}\n\nexport function replaceManagedBlock(\n existing: string,\n block: string,\n startMarker = DEFAULT_MANCODE_START_MARKER,\n endMarker = DEFAULT_MANCODE_END_MARKER,\n): string {\n const normalizedBlock = normalizeManagedBlock(block, startMarker, endMarker);\n const start = findMarkerLine(existing, startMarker);\n const end = findMarkerLine(existing, endMarker);\n\n if ((start === null) !== (end === null)) {\n throw new Error('managed block is malformed: missing start or end marker');\n }\n\n if (start === null && end === null) {\n const trimmedExisting = trimTrailingNewlines(existing);\n if (!trimmedExisting) return `${normalizedBlock}\\n`;\n return `${trimmedExisting}\\n\\n${normalizedBlock}\\n`;\n }\n\n if (!start || !end) {\n throw new Error('managed block is malformed: missing start or end marker');\n }\n\n if (end.start < start.start) {\n throw new Error('managed block is malformed: end marker precedes start');\n }\n\n return `${existing.slice(0, start.start)}${normalizedBlock}${existing.slice(\n end.end,\n )}`;\n}\n\nfunction normalizeManagedBlock(\n block: string,\n startMarker: string,\n endMarker: string,\n): string {\n const trimmedBlock = block.trim();\n const hasStart = trimmedBlock.startsWith(startMarker);\n const hasEnd = trimmedBlock.endsWith(endMarker);\n\n if (hasStart && hasEnd) return trimmedBlock;\n if (hasStart || hasEnd) {\n throw new Error('managed block content includes only one marker');\n }\n\n return `${startMarker}\\n${trimmedBlock}\\n${endMarker}`;\n}\n\nfunction trimTrailingNewlines(value: string): string {\n return value.replace(/\\n+$/u, '');\n}\n\nfunction findMarkerLine(\n content: string,\n marker: string,\n): { start: number; end: number } | null {\n let offset = 0;\n let inFence: { char: '`' | '~'; length: number } | null = null;\n\n for (const lineWithBreak of content.matchAll(/[^\\n]*(?:\\n|$)/gu)) {\n const rawLine = lineWithBreak[0];\n if (!rawLine) break;\n\n const line = rawLine.replace(/\\n$/u, '').replace(/\\r$/u, '');\n const fence = line.match(/^(`{3,}|~{3,})/u)?.[1];\n if (fence) {\n const char = fence[0] as '`' | '~';\n if (!inFence) {\n inFence = { char, length: fence.length };\n } else if (inFence.char === char && fence.length >= inFence.length) {\n inFence = null;\n }\n } else if (!inFence && line === marker) {\n return {\n start: offset,\n end: offset + marker.length,\n };\n }\n\n offset += rawLine.length;\n }\n\n return null;\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,UAAU;;;ACTV,IAAM,+BAA+B;AACrC,IAAM,6BAA6B;AAEnC,SAAS,mBACd,UACA,cAAc,8BACd,YAAY,4BACJ;AACR,QAAM,QAAQ,eAAe,UAAU,WAAW;AAClD,QAAM,MAAM,eAAe,UAAU,SAAS;AAE9C,MAAI,UAAU,QAAQ,QAAQ,KAAM,QAAO;AAC3C,MAAI,UAAU,QAAQ,QAAQ,KAAM,QAAO;AAC3C,MAAI,IAAI,QAAQ,MAAM,MAAO,QAAO;AAEpC,QAAM,SAAS,SAAS,MAAM,GAAG,MAAM,KAAK;AAC5C,QAAM,QAAQ,SAAS,MAAM,IAAI,GAAG;AACpC,QAAM,SAAS,GAAG,MAAM,GAAG,KAAK;AAChC,SAAO,wBAAwB,M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EACX;AACF;AAEA,SAAS,gBAAgB,WAAgD;AACvE,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,YAAY;AAAA,IACZ,iBAAiB;AAAA,EACnB;AACF;AAEA,SAAS,YAAY,OAAgD;AACnE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU;AAClE;AAEA,SAAS,4BAA4B,OAAyB;AAC5D,SACE,YAAY,KAAK,KAAK,6BAA6B,IAAI,MAAM,QAAQ,EAAE;AAE3E;AAEA,eAAe,MAAM,cAAqC;AACxD,QAAM,IAAI,QAAc,CAAC,YAAY;AACnC,eAAW,SAAS,YAAY;AAAA,EAClC,CAAC;AACH;","names":["cleaned"]}
@@ -6714,14 +6714,9 @@ var V3ContextStore = class {
6714
6714
  })
6715
6715
  };
6716
6716
  }
6717
- /**
6718
- * Lists non-terminal children from canonical metadata only. Callers that
6719
- * need a completion gate must hold the parent task lock while invoking it;
6720
- * V3 child creation takes that same parent lock before publishing.
6721
- */
6722
- async listActiveChildTaskRefs(parentTaskRef) {
6723
- const parent = parseTaskRefValue(parentTaskRef);
6724
- const children = [];
6717
+ /** Lists every canonical V3 workflow without relying on a session pointer. */
6718
+ async listWorkflowMetadata() {
6719
+ const workflows = [];
6725
6720
  for (const namespace of ["local", "shared"]) {
6726
6721
  const directory = path9.join(".mancode", namespace, "workflows");
6727
6722
  const entries = await readDirectoryEntriesWithin(
@@ -6730,7 +6725,7 @@ var V3ContextStore = class {
6730
6725
  );
6731
6726
  for (const taskId of entries.sort(compareUtf83)) {
6732
6727
  try {
6733
- assertUlid(taskId, "workflow child directory");
6728
+ assertUlid(taskId, "workflow directory");
6734
6729
  } catch {
6735
6730
  throw new Error("MANCODE_CONTEXT_COLLECTION_ENTRY_INVALID");
6736
6731
  }
@@ -6745,12 +6740,26 @@ var V3ContextStore = class {
6745
6740
  "metadata.json",
6746
6741
  parseWorkflowMetadata
6747
6742
  );
6748
- if (metadata.parent !== null && sameTaskRef(metadata.parent.taskRef, parent) && !isTerminalWorkflowStatus(metadata.status)) {
6749
- children.push(metadata.taskRef);
6743
+ if (!sameTaskRef(metadata.taskRef, taskRef)) {
6744
+ throw new Error("MANCODE_CONTEXT_TASK_LOCATION_MISMATCH");
6750
6745
  }
6746
+ workflows.push(metadata);
6751
6747
  }
6752
6748
  }
6753
- return children.sort(
6749
+ return workflows.sort(
6750
+ (left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt) || compareUtf83(left.taskRef.namespace, right.taskRef.namespace) || compareUtf83(left.taskRef.taskId, right.taskRef.taskId)
6751
+ );
6752
+ }
6753
+ /**
6754
+ * Lists non-terminal children from canonical metadata only. Callers that
6755
+ * need a completion gate must hold the parent task lock while invoking it;
6756
+ * V3 child creation takes that same parent lock before publishing.
6757
+ */
6758
+ async listActiveChildTaskRefs(parentTaskRef) {
6759
+ const parent = parseTaskRefValue(parentTaskRef);
6760
+ return (await this.listWorkflowMetadata()).filter(
6761
+ (metadata) => metadata.parent !== null && sameTaskRef(metadata.parent.taskRef, parent) && !isTerminalWorkflowStatus(metadata.status)
6762
+ ).map((metadata) => metadata.taskRef).sort(
6754
6763
  (left, right) => compareUtf83(left.namespace, right.namespace) || compareUtf83(left.taskId, right.taskId)
6755
6764
  );
6756
6765
  }
@@ -7114,4 +7123,4 @@ export {
7114
7123
  V3ContextStore,
7115
7124
  storedTaskAggregateDigest
7116
7125
  };
7117
- //# sourceMappingURL=chunk-O3QAKAPJ.js.map
7126
+ //# sourceMappingURL=chunk-LMXUPBCN.js.map