company-service.js 44.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
/**
 * CompanyService — 公司实例管理
 *
 * 数据目录: data/{companyId}/
 * 模板库:   system/templates/
 *
 * 核心职责:
 *   1. Company CRUD (create/get/list/shutdown)
 *   2. Agent 招聘 (hire: 模板优先 → base 元 agent 继承兜底)
 *   3. resolveAgentDir(companyId, agentId) 统一寻址
 */

const fs = require('fs');
const path = require('path');
const { lookupSharedAgentMd, ensureSystemAgentRow, orgGraphMembership, upsertOrgGraphNode } = require('./graph-service');
const { getDb } = require('./graph-db');

const ROOT_DATA_DIR = path.resolve(__dirname, '../../data');
const DATA_DIR = path.join(ROOT_DATA_DIR, 'companies');
const TEMPLATES_DIR = path.resolve(__dirname, '../../system/templates');
const GLOBAL_AGENTS_DIR = path.resolve(__dirname, '../../system/agents');

// 模板使用计数的**运行态**落点(27-P3B §四 W13)。
//
// 以前 `_updateTemplateUsedCount()` 每次 hire 都原地 +1 改写
// `system/templates/_registry.json` —— 那是一份**人工维护**的模板清单(name /
// description / benchmarkScore / trainedAt 都是手写的,`template-refs.test.js`
// 还拿它当「模板本体集的登记表」校验)。结果任何一次真跑都会在工作区留一条
// `M system/templates/_registry.json`,跟 agent 自写的 todo.md 一样是持续晃动的噪声,
// 而边界守卫扫的就是整仓 git status。
//
// 所以计数搬到 data/ 下的独立运行态文件(已 .gitignore),registry 里的
// `usedCount` 退化成**冻结的历史基线**,对外读回时基线 + 增量相加,
// 前端 badge(CompanyDashboard.vue `tpl.usedCount`)看到的数字不回退。
const TEMPLATE_USAGE_PATH = path.join(ROOT_DATA_DIR, 'template-usage.json');

// 元 agent("标准基座员工 Base Agent")模板 id —— 自带 RESEARCH → PLAN → EXECUTE → VERIFY
// 四段式生命周期。模板库里没有对应角色时,新 agent 一律从它继承骨架
// (docs/todo/system-design/27-p2-org-graph.md §4.1 第 7 步 / 27-e2e §八bis)。
const BASE_META_AGENT_ID = 'base';

// ── 招聘的两层,与「谁算 org 节点」(27-P3B §四 W7 / 27-REQ R-18.2 末段)──────
//
// 招聘有两层,但只有 **org 层**的被雇者才是公司 org graph 上的一个节点:
//   org  层:orggraph-planning 按它规划的 org graph 雇进来的角色(org-planner / org-coder /
//            org-validator …),以及公司还没有图时人工从界面雇的员工 ——
//            P2 §4.2 的「hire 成功后写一行 org_graph_nodes」说的是它们;
//   work 层:workgraph-planning 每接到一个任务、按它规划出的 work graph 现雇的本体
//            (prd-planning / benchmark-validator / validator-triager / coder-validator …)。
//            这些本体是某个 org node **内部**工作流的节点,写进 org_graph_nodes 不只是
//            把控制台左栏画歪:`work-graph-db.js:473` 起 org run 时读的就是这张表的 active 行,
//            混进去的行会变成一个真的会被执行的 org 节点;而 POST /org-graph 又会把不在
//            规划 agent 节点列表里的行标 removed —— 两边互相打架。
//
// **判据不问调用方,只看数据**。原因是唯一会雇 work 层本体的真实调用方是
// `POST /api/company/:companyId/hire`(workgraph-planning 在 CLI 里 curl 它),
// 该路由按字段解构 body、不透传未知字段,所以「加个 opts.layer 参数」在本轮是一个
// 永远没人传的死开关。何况「谁雇的」本来也不该决定「它是不是组织节点」。三条判据:
//
//   ① 本体自称是图基础设施(config.json 的 type ∈ NON_ORG_AGENT_TYPES)→ 永不入图。
//      meta-bootstrap 那半条 P2 就有了(否则建公司到规划跑完之间 GET /org-graph 会返回
//      一张只有 orggraph-planning 的假组织图);W7 把它推广到 meta-planning,覆盖
//      graph-engine.resolvePlanningAgentName() 按需雇的 workgraph-planning,以及
//      workgraph-planning 自己雇的 prd/sdd/brd-planning、goal-benchmark。
//   ② 本体在 system/work-graph-templates/*.json 里被点名当 work graph 节点 → 永不入图
//      (planner-validator / validator-triager / benchmark-validator / testdata-validator,
//      这些 type='validator' 的本体判据①盖不住,而 org-validator 只当 ownerOrgNode 出现、
//      不是 nodes[] 里的 systemAgentId,所以不会被误伤)。
//   ③ 公司已经有一张**成型的**组织工作流图(存在 active 的 org_graph_edges),
//      而这次雇的角色不在图上 → 不入图:图一旦成型,作者就是 orggraph-planning
//      (POST /org-graph),hire() 不再往上追加节点。这条兜住 ①② 都不认识的、
//      按 executor.json 的 {{implAgent}} / {{validatorAgent}} 动态选出来的本体。
//      判据用「有没有边」而不是「有没有节点」,因为 P1/P2 的 hire 自己就会造节点,
//      拿节点当信号会把「同一家公司连雇两个人,第二个不入图」这条 P2 语义废掉
//      (server/tests/integration/graph-agent-p1-hire.test.js 就是这么用的)。
//      顺带修掉一个老问题:org 节点 role_name='org-coder' 绑定本体 'coder' 时,
//      在成型图上再雇一次 'coder' 以前会多出一行同义节点,现在不会了。
//
// 默认行为(都不命中)= 写。P1/P2 既有语义「雇一个角色 → org graph 出现这个节点」
// 在「公司还没有成型的图」这个前提下原样保住(graph-agent-p1-acceptance.test.js 判据 1)。
//
// 已知残留:单 org node 的最小图没有边,判据③不生效,这时只有 ①② 认识的本体会被拦下;
// 一个既不是 meta-* 又没在骨架里点过名的本体(executor.json 的占位符现填)仍会入图。
// 真跑到那一步再看,别为它提前加规则。
const NON_ORG_AGENT_TYPES = new Set(['meta-bootstrap', 'meta-planning']);
const WORK_GRAPH_TEMPLATES_DIR = path.resolve(__dirname, '../../system/work-graph-templates');

let workGraphBodyIds = null; // 懒加载 + 进程内缓存(骨架是随代码发布的静态文件)

/** system/work-graph-templates/*.json 里 nodes[].systemAgentId 的全集(跳过 {{占位符}}) */
function workGraphTemplateBodies() {
  if (workGraphBodyIds) return workGraphBodyIds;
  workGraphBodyIds = new Set();
  try {
    for (const f of fs.readdirSync(WORK_GRAPH_TEMPLATES_DIR)) {
      if (!f.endsWith('.json')) continue;
      const tpl = JSON.parse(fs.readFileSync(path.join(WORK_GRAPH_TEMPLATES_DIR, f), 'utf-8'));
      for (const n of tpl.nodes || []) {
        const id = n && n.systemAgentId;
        if (id && !id.startsWith('{{')) workGraphBodyIds.add(id);
      }
    }
  } catch (err) {
    // 读不到就退化成「这条判据不生效」,另外两条还在,绝不因此挡住招聘
    console.warn(`[Company] ⚠️ 读 work graph 骨架失败,W7 判据②本轮跳过: ${err.message}`);
  }
  return workGraphBodyIds;
}

/**
 * 这次招聘要不要在 org_graph_nodes 里记一行?判据见上方注释。
 *
 * @param {string} companyId
 * @param {string} roleName
 * @param {object|null} agentConfig 被雇 agent 的 config.json(取 type)
 * @returns {{ record: boolean, reason: string }} reason 用于日志,说明是哪一条判据生效
 */
function decideOrgNodeRecording(companyId, roleName, agentConfig) {
  const type = agentConfig && agentConfig.type;
  if (NON_ORG_AGENT_TYPES.has(type)) {
    return { record: false, reason: `type=${type},图基础设施本体从不作为 org 节点` };
  }
  if (workGraphTemplateBodies().has(roleName)) {
    return { record: false, reason: 'work graph 骨架里点名的 work 层本体' };
  }

  const { hasWorkflow, isNode } = orgGraphMembership(companyId, roleName);
  if (hasWorkflow && !isNode) {
    return { record: false, reason: '公司已有成型的 org graph,而该角色不在图上(work 层本体)' };
  }

  return { record: true, reason: isNode ? '该角色就是图上的 org 节点' : '公司还没有成型的 org graph(P2 语义:雇进来就记一行)' };
}

// 模板骨架文件白名单 (复制这些,不复制 memory/workspace/conversations 等运行态数据)
const TEMPLATE_FILES = [
  'agent.md', 'soul.md', 'identity.md', 'user.md', 'tools.md',
  'heartbeat.md', 'plan.md', 'todo.md', 'cron.json', 'config.json',
];

class CompanyService {

  // ═══════════════════════════════════════
  //  Company CRUD
  // ═══════════════════════════════════════

  /**
   * 创建一家新公司
   * @param {object} opts - { id, name, goal, description }
   *   goal        company-goal:这家公司要达成什么(定性,OKR 树的输入,orggraph-planning 规划流水线的主依据)
   *   description 这家公司是干什么的(背景)
   *   两者的区分见 docs/todo/system-design/27-naming-conventions.md §四
   */
  create({ id, name, goal = '', description = '' }) {
    const companyDir = path.join(DATA_DIR, id);
    if (fs.existsSync(companyDir)) {
      throw new Error(`公司 ${id} 已存在`);
    }

    // 创建目录结构
    const subdirs = ['agents', 'okr', 'pipelines', 'workspace', 'workspace/assets', 'workspace/output', 'docs', 'logs/pipeline_runs', 'logs/audit'];
    for (const sub of subdirs) {
      fs.mkdirSync(path.join(companyDir, sub), { recursive: true });
    }

    const now = new Date().toISOString();
    const company = {
      id,
      name,
      goal,
      description,
      status: 'creating',       // creating → running → paused → shutdown
      createdAt: now,
      updatedAt: now,
      createdBy: 'master',
      ceo: null,
      sop: null,
      agents: [],
      heartbeat: {
        enabled: false,         // CEO 上任后才开启
        intervalMinutes: 30,
      },
      config: {
        timezone: 'Asia/Shanghai',
        maxAgents: 20,
      },
    };

    this._saveCompany(company);



    // 重新保存(agents 列表已更新)
    this._saveCompany(company);

    console.log(`[Company] 🏢 创建公司: ${id} (${name})`);
    return company;
  }

  /**
   * 获取公司详情
   */
  get(companyId) {
    const fp = path.join(DATA_DIR, companyId, 'company.json');
    if (!fs.existsSync(fp)) return null;
    return JSON.parse(fs.readFileSync(fp, 'utf-8'));
  }

  /**
   * 列出所有公司
   */
  list() {
    if (!fs.existsSync(DATA_DIR)) return [];

    return fs.readdirSync(DATA_DIR, { withFileTypes: true })
      .filter(d => d.isDirectory() && fs.existsSync(path.join(DATA_DIR, d.name, 'company.json')))
      .map(d => {
        const company = this.get(d.name);
        if (!company) return null;
        return {
          id: company.id,
          name: company.name,
          status: company.status,
          agentCount: company.agents ? company.agents.length : 0,
          ceo: company.ceo,
          updatedAt: company.updatedAt,
        };
      })
      .filter(Boolean);
  }

  /**
   * 更新公司信息
   */
  update(companyId, updates) {
    const company = this.get(companyId);
    if (!company) return null;

    if (updates.name !== undefined) company.name = updates.name;
    if (updates.goal !== undefined) company.goal = updates.goal;
    if (updates.description !== undefined) company.description = updates.description;
    if (updates.status !== undefined) {
      company.status = updates.status;
      // Track startedAt for uptime calculation
      if (updates.status === 'running' && !company.startedAt) {
        company.startedAt = new Date().toISOString();
      } else if (updates.status === 'shutdown' || updates.status === 'paused') {
        company.startedAt = null;
      }
    }
    if (updates.sop !== undefined) company.sop = updates.sop;
    if (updates.heartbeat !== undefined) company.heartbeat = { ...company.heartbeat, ...updates.heartbeat };
    company.updatedAt = new Date().toISOString();

    this._saveCompany(company);
    return company;
  }

  /**
   * 关停公司 (软关停: 标记状态, 停止心跳, 保留数据)
   */
  shutdown(companyId) {
    const company = this.get(companyId);
    if (!company) return null;

    company.status = 'shutdown';
    company.heartbeat.enabled = false;
    company.startedAt = null;
    company.updatedAt = new Date().toISOString();

    this._saveCompany(company);
    console.log(`[Company] 🛑 关停公司: ${companyId}`);
    return company;
  }

  /**
   * 删除公司 (仅删除 company.json 定义即可,暂时不清理目录数据)
   */
  delete(companyId) {
    const company = this.get(companyId);
    if (!company) return null;

    const fp = path.join(DATA_DIR, companyId, 'company.json');
    if (fs.existsSync(fp)) {
      // 通过重命名或者直接删除 company.json 来让 list 无法读取
      fs.renameSync(fp, path.join(DATA_DIR, companyId, 'company.deleted.json'));
    }

    console.log(`[Company] 🗑️ 删除公司: ${companyId}`);
    return company;
  }

  // ═══════════════════════════════════════
  //  Agent 招聘系统 (Hiring Pipeline)
  // ═══════════════════════════════════════

  /**
   * 招聘一个 Agent 到公司
   *
   * 流程: 模板库查找 → 复制 → 注入公司上下文
   *       模板不存在 → 从 base 元 agent 继承骨架 (hireFromBaseMetaAgent),
   *                    仍返回 { needsTraining: true },由上层调用 agent-creator + innovator 填充定义
   *
   * @param {string} companyId
   * @param {string} roleName - 角色名 (如 "ceo", "content-writer")
   * @param {object} opts - { customAgent, customSoul, ... } 可选的上下文覆盖
   * @returns {object} { status, agentId, agentDir, needsTraining? }
   */
  hire(companyId, roleName, opts = {}) {
    const company = this.get(companyId);
    if (!company) throw new Error(`公司 ${companyId} 不存在`);

    const targetDir = path.join(DATA_DIR, companyId, 'agents', roleName);
    if (fs.existsSync(targetDir)) {
      return { status: 'already_exists', agentId: roleName, agentDir: targetDir };
    }

    // 阶段 A: 在模板库中查找
    const templateDir = path.join(TEMPLATES_DIR, roleName);
    if (fs.existsSync(templateDir)) {
      // system_agents 里是否有这个角色的共享 agent.md(source_kind='template')?
      // 有 → 引用模式(不拷贝 agent.md);没有(含 6 个命名冲突 id)→ legacy 全量拷贝,行为零变化
      const sharedAgentMdPath = lookupSharedAgentMd(roleName);

      if (sharedAgentMdPath) {
        this._provisionReferenceAgent(templateDir, targetDir);
        this._injectCompanyContext(companyId, roleName, opts, { referenceMode: true });
      } else {
        // ✅ 模板存在 → 复制骨架到公司(legacy 全量拷贝,含 agent.md)
        this._copyTemplate(templateDir, targetDir);
        this._injectCompanyContext(companyId, roleName, opts);
      }
      this._updateTemplateUsedCount(roleName);

      // 更新公司的 agents 列表
      if (!company.agents.includes(roleName)) {
        company.agents.push(roleName);
      }
      // 如果是 CEO,标记到 company.ceo
      const agentConfig = this._readAgentConfig(targetDir);
      if (agentConfig && agentConfig.type === 'cxo') {
        company.ceo = roleName;
      }
      company.updatedAt = new Date().toISOString();
      this._saveCompany(company);

      // Org Graph 引用节点记录(审计用途,失败不影响雇佣结果本身)。判据见 NON_ORG_AGENT_TYPES 上方注释。
      this._recordHireInGraph(companyId, roleName, agentConfig);

      console.log(`[Company] ✅ ${companyId} 招聘 ${roleName} (从模板${sharedAgentMdPath ? ',引用模式' : ''})`);
      return { status: 'hired_from_template', agentId: roleName, agentDir: targetDir };
    }

    // 阶段 B: 模板不存在 → 先从 base 元 agent 继承出骨架,再交给 agent-creator 填充角色定义
    const inherited = this.hireFromBaseMetaAgent(companyId, roleName, opts);
    if (inherited) return inherited;

    // 兜底: 连 base 元 agent 都不存在(不应发生)→ 退回原有的纯 needs_training 行为
    console.log(`[Company] ⚠️ 模板库中不存在 "${roleName}",且 base 元 agent 缺失,需要 agent-creator + innovator 培养`);
    return {
      status: 'needs_training',
      agentId: roleName,
      agentDir: targetDir,
      needsTraining: true,
    };
  }

  /**
   * 从 base 元 agent 继承出一个新角色的骨架(27-p2-org-graph.md §4.1 第 7 步)
   *
   * 模板库里没有这个角色时的招聘路径:不再直接返回 needs_training 让上层从零培养,
   * 而是先把 system/templates/base/ 的骨架文件拷到
   * data/companies/{companyId}/agents/{roleName}/ —— 新 agent 因此自动带上 base 的
   * RESEARCH → PLAN → EXECUTE → VERIFY 四段式生命周期;角色特有的定义仍由上层触发
   * agent-creator 填充(所以返回值保留 needsTraining: true)。
   *
   * @param {string} companyId
   * @param {string} roleName
   * @param {object} opts - 与 hire() 同:{ type, name, description, customAgent, customSoul, customUser }
   * @returns {object|null} { status:'hired_from_base', agentId, agentDir, needsTraining:true };
   *                        base 模板缺失时返回 null,由调用方决定兜底行为
   */
  hireFromBaseMetaAgent(companyId, roleName, opts = {}) {
    const company = this.get(companyId);
    if (!company) throw new Error(`公司 ${companyId} 不存在`);

    const baseDir = path.join(TEMPLATES_DIR, BASE_META_AGENT_ID);
    if (!fs.existsSync(baseDir)) return null;

    const targetDir = path.join(DATA_DIR, companyId, 'agents', roleName);
    if (fs.existsSync(targetDir)) {
      return { status: 'already_exists', agentId: roleName, agentDir: targetDir };
    }

    // 1. 拷贝 base 骨架(沿用 TEMPLATE_FILES 白名单 + .claude/ + skills/ + 空 memory)
    this._copyTemplate(baseDir, targetDir);
    this._injectCompanyContext(companyId, roleName, opts);

    // 2. config.json: 标记为待培养 + 记录继承来源(_injectCompanyContext 写的是 active,这里覆盖)
    const configPath = path.join(targetDir, 'config.json');
    const config = this._readAgentConfig(targetDir) || {};
    config.status = 'training';
    config.companyId = companyId;
    config.inheritedFrom = BASE_META_AGENT_ID;
    if (opts.type) config.type = opts.type;
    if (opts.name) config.name = opts.name;
    if (opts.description) config.description = opts.description;
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');

    // 3. 更新公司 agents 列表
    if (!company.agents.includes(roleName)) {
      company.agents.push(roleName);
    }
    company.updatedAt = new Date().toISOString();
    this._saveCompany(company);

    // 4. Org Graph 节点 + scope 治理(失败不影响雇佣结果本身)。
    //    这条路径下 config.json 刚由本函数写出(type 来自 opts.type),直接把它喂给判据。
    this._recordHireInGraph(companyId, roleName, config);
    try {
      this._ensureCompanyScopedAgent(companyId, roleName);
    } catch (err) {
      console.warn(`[Company] ⚠️ system_agents scope 校正失败(不影响雇佣结果): ${err.message}`);
    }

    console.log(`[Company] 🧬 ${companyId} 招聘 ${roleName}(从 base 元 agent 继承,待 agent-creator 填充定义)`);
    return {
      status: 'hired_from_base',
      agentId: roleName,
      agentDir: targetDir,
      needsTraining: true,
      message: `Agent "${roleName}" 已从 base 元 agent 继承骨架(含四段式生命周期),状态: training。等待 agent-creator 补充角色定义。`,
    };
  }

  /**
   * 把一次成功的招聘落到图上(hire() 与 hireFromBaseMetaAgent() 共用的收尾动作)。
   *
   * org 层 → 记一行 org_graph_nodes(顺带补 system_agents,upsertOrgGraphNode 内部做)。
   * work 层 → **不记** org_graph_nodes,但**仍然补** system_agents 那一行:
   *           work_graph_nodes.system_agent_id 是指向 system_agents 的外键,
   *           少了这行,workgraph-planning 雇完人再提交 work graph 会直接外键挂
   *           (27-P3B §四 W1 记录过同一条失效链)。
   *
   * 图写失败一律降级成告警,不影响雇佣结果本身(保持 P1/P2 既有行为)。
   */
  _recordHireInGraph(companyId, roleName, agentConfig) {
    const { record, reason } = decideOrgNodeRecording(companyId, roleName, agentConfig);
    try {
      if (record) {
        upsertOrgGraphNode(companyId, roleName, roleName);
      } else {
        ensureSystemAgentRow(companyId, roleName, roleName);
        console.log(`[Company] ⏭️ ${roleName} 不写入 org_graph_nodes(${reason}),仅登记 system_agents`);
      }
    } catch (err) {
      console.warn(`[Company] ⚠️ 图登记失败(不影响雇佣结果): ${err.message}`);
    }
  }

  /**
   * 校正新建 agent 在 system_agents 里的归属:scope='company' + owner_company_id=本公司
   * (27-graph-agent-architecture.md §3.2)。
   *
   * graph-service.upsertOrgGraphNode() 的 fallback 插入已经是 scope='company',但它只在
   * system_agents 里没有这行时才插;这里显式再兜一次,保证「公司自建 agent 一律 company 域」
   * 这条不变量不依赖上游实现细节。
   * 限定 source_kind='company_hired' —— 绝不把 global_agent / template 那两类公共 agent 降级。
   */
  _ensureCompanyScopedAgent(companyId, agentId) {
    getDb().prepare(`
      UPDATE system_agents
         SET scope = 'company', owner_company_id = @company_id, updated_at = @updated_at
       WHERE id = @id
         AND source_kind = 'company_hired'
         AND (scope <> 'company' OR owner_company_id IS NOT @company_id)
    `).run({ id: agentId, company_id: companyId, updated_at: new Date().toISOString() });
  }

  /**
   * 用 AgentScaffold 直接创建 Agent 骨架到公司
   * (Phase 2: 不走 HTTP,直接调用脚手架)
   *
   * @param {string} companyId
   * @param {string} roleName
   * @param {object} opts - { type, name, description, parentId }
   * @returns {Promise<object>} { agentDir, agentId }
   */
  async scaffoldNewAgent(companyId, roleName, opts = {}) {
    const company = this.get(companyId);
    if (!company) throw new Error(`公司 ${companyId} 不存在`);

    const companyAgentsDir = path.join(DATA_DIR, companyId, 'agents');
    if (!fs.existsSync(companyAgentsDir)) {
      fs.mkdirSync(companyAgentsDir, { recursive: true });
    }

    // 使用 ESM 导入 AgentScaffold
    const { AgentScaffold } = await import('../../packages/agent-core/AgentScaffold.js');
    const scaffold = new AgentScaffold(companyAgentsDir);

    const agentDir = await scaffold.create({
      id: roleName,
      type: opts.type || 'skill',
      name: opts.name || roleName,
      parentId: opts.parentId || company.ceo || 'ceo',
      goalId: opts.goalId || null,
    });

    // 注入公司上下文
    this._injectCompanyContext(companyId, roleName, opts);

    // 标记为 training 状态
    const configPath = path.join(agentDir, 'config.json');
    if (fs.existsSync(configPath)) {
      const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
      config.status = 'training';
      config.companyId = companyId;
      fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
    }

    // 更新公司
    if (!company.agents.includes(roleName)) {
      company.agents.push(roleName);
    }
    company.updatedAt = new Date().toISOString();
    this._saveCompany(company);

    console.log(`[Company] 🎓 ${companyId} 创建新 Agent 骨架: ${roleName} (training)`);
    return { agentDir, agentId: roleName };
  }

  /**
   * 将训练合格的 Agent 沉淀为模板
   * (Phase 2: Benchmark ≥ 95 后调用)
   *
   * @param {string} companyId
   * @param {string} agentId
   * @param {number} benchmarkScore
   * @returns {object} { status, templateId }
   */
  depositTemplate(companyId, agentId, benchmarkScore) {
    if (benchmarkScore < 95) {
      return {
        status: 'rejected',
        message: `评分 ${benchmarkScore} 未达标 (需 ≥ 95)`,
        agentId,
      };
    }

    const agentDir = path.join(DATA_DIR, companyId, 'agents', agentId);
    if (!fs.existsSync(agentDir)) {
      throw new Error(`Agent ${agentId} 在 ${companyId} 中不存在`);
    }

    const templateDir = path.join(TEMPLATES_DIR, agentId);
    // 如果模板已存在且分数更低,覆盖
    if (fs.existsSync(templateDir)) {
      fs.rmSync(templateDir, { recursive: true, force: true });
    }

    // 只复制骨架文件到模板 (不含 memory/workspace/conversations)
    fs.mkdirSync(templateDir, { recursive: true });
    for (const file of TEMPLATE_FILES) {
      const srcFile = path.join(agentDir, file);
      if (fs.existsSync(srcFile)) {
        // 复制模板时去掉公司特定信息 (对 config.json 特殊处理)
        if (file === 'config.json') {
          const config = JSON.parse(fs.readFileSync(srcFile, 'utf-8'));
          delete config.companyId;
          config.status = 'ready';
          config.benchmarkScore = benchmarkScore;
          config.trainedAt = new Date().toISOString().slice(0, 10);
          fs.writeFileSync(path.join(templateDir, file), JSON.stringify(config, null, 2), 'utf-8');
        } else {
          fs.copyFileSync(srcFile, path.join(templateDir, file));
        }
      }
    }

    // 复制 skills/ 目录
    const srcSkills = path.join(agentDir, 'skills');
    if (fs.existsSync(srcSkills)) {
      this._copyDirRecursive(srcSkills, path.join(templateDir, 'skills'));
    }

    // 更新模板注册表
    const registryPath = path.join(TEMPLATES_DIR, '_registry.json');
    let registry = [];
    if (fs.existsSync(registryPath)) {
      registry = JSON.parse(fs.readFileSync(registryPath, 'utf-8'));
    }
    // 移除旧条目 (如果存在)
    registry = registry.filter(t => t.id !== agentId);
    const agentConfig = this._readAgentConfig(templateDir);
    registry.push({
      id: agentId,
      name: agentConfig?.name || agentId,
      type: agentConfig?.type || 'skill',
      description: agentConfig?.description || '',
      benchmarkScore,
      trainedAt: new Date().toISOString().slice(0, 10),
      usedCount: 0,
    });
    fs.writeFileSync(registryPath, JSON.stringify(registry, null, 2) + '\n', 'utf-8');

    // 将 Agent 状态从 training → active
    const configPath = path.join(agentDir, 'config.json');
    if (fs.existsSync(configPath)) {
      const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
      config.status = 'active';
      fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
    }

    console.log(`[Company] 📦 Agent ${agentId} 沉淀为模板 (benchmark: ${benchmarkScore})`);
    return { status: 'deposited', templateId: agentId, benchmarkScore };
  }

  /**
   * 完整招聘流程 (Phase 2: 模板优先 → 骨架创建兜底)
   * 如果模板不存在,会创建骨架并返回 training 状态
   * 上层(路由)负责异步触发 agent-creator + innovator 实际训练
   *
   * @param {string} companyId
   * @param {string} roleName
   * @param {object} opts - { type, name, description, customAgent, customSoul, customUser }
   * @returns {Promise<object>}
   */
  async hireWithTraining(companyId, roleName, opts = {}) {
    // 先走标准招聘流程
    const result = this.hire(companyId, roleName, opts);

    // P2 起模板缺失会走 hire() 内的 base 元 agent 继承分支(status='hired_from_base',
    // 已建好目录 + config.status='training' + needsTraining=true),无需再跑 scaffoldNewAgent。
    // 只有 base 元 agent 本身缺失时 hire() 才会退回 needs_training,走下面的脚手架兜底。
    if (result.status !== 'needs_training') {
      return result;
    }

    // 模板不存在 → 创建骨架 (Phase 2)
    const scaffold = await this.scaffoldNewAgent(companyId, roleName, {
      type: opts.type || 'skill',
      name: opts.name || roleName,
      description: opts.description || '',
      parentId: opts.parentId,
      customAgent: opts.customAgent,
      customSoul: opts.customSoul,
      customUser: opts.customUser,
    });

    return {
      status: 'training',
      agentId: roleName,
      agentDir: scaffold.agentDir,
      message: `Agent "${roleName}" 骨架已创建,状态: training。需要 agent-creator 定义 + innovator 训练至 ≥95 后才可上岗。`,
    };
  }

  /**
   * 解雇 (suspend) 公司内的 Agent
   */
  fire(companyId, agentId) {
    const company = this.get(companyId);
    if (!company) return null;

    const agentDir = path.join(DATA_DIR, companyId, 'agents', agentId);
    if (!fs.existsSync(agentDir)) return null;

    // 更新 config.json 状态
    const configPath = path.join(agentDir, 'config.json');
    if (fs.existsSync(configPath)) {
      const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
      config.status = 'suspended';
      fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
    }

    // 从公司 agents 列表移除
    company.agents = company.agents.filter(a => a !== agentId);
    company.updatedAt = new Date().toISOString();
    this._saveCompany(company);

    console.log(`[Company] 🚪 ${companyId} 解雇 ${agentId}`);
    return { status: 'suspended', agentId };
  }

  /**
   * 列出公司内的所有 Agent (含状态)
   */
  listAgents(companyId) {
    const agentsDir = path.join(DATA_DIR, companyId, 'agents');
    if (!fs.existsSync(agentsDir)) return [];

    return fs.readdirSync(agentsDir, { withFileTypes: true })
      .filter(d => d.isDirectory())
      .map(d => {
        const config = this._readAgentConfig(path.join(agentsDir, d.name));
        return {
          id: d.name,
          name: config?.name || d.name,
          type: config?.type || 'unknown',
          status: config?.status || 'unknown',
          companyId,
        };
      });
  }

  // ═══════════════════════════════════════
  //  模板库管理
  // ═══════════════════════════════════════

  /**
   * 列出所有可用模板
   */
  listTemplates() {
    // 始终从目录扫描,合并 _registry.json 中的元数据(benchmarkScore, usedCount 等)
    if (!fs.existsSync(TEMPLATES_DIR)) return [];

    const registryPath = path.join(TEMPLATES_DIR, '_registry.json');
    let registryMap = {};
    if (fs.existsSync(registryPath)) {
      try {
        const registry = JSON.parse(fs.readFileSync(registryPath, 'utf-8'));
        for (const entry of registry) registryMap[entry.id] = entry;
      } catch {}
    }

    // usedCount 的读回环:registry 里是冻结的人工基线,data/template-usage.json 里是
    // 每次 hire 累加的增量,两边相加才是对外的真实次数(W13)。
    const usageMap = this._readTemplateUsage();

    const templates = fs.readdirSync(TEMPLATES_DIR, { withFileTypes: true })
      .filter(d => d.isDirectory() && !d.name.startsWith('_'))
      .map(d => {
        const templateDir = path.join(TEMPLATES_DIR, d.name);
        const config = this._readAgentConfig(templateDir);
        const regEntry = registryMap[d.name] || {};

        let evolvingVersionCount = 0;
        let benchmarkVersionCount = 0;
        const evolvingDir = path.join(templateDir, 'memory', 'evolving');
        const benchmarkDir = path.join(templateDir, 'memory', 'benchmark');
        
        if (fs.existsSync(evolvingDir)) {
          evolvingVersionCount = fs.readdirSync(evolvingDir, { withFileTypes: true })
                                   .filter(e => e.isDirectory() && e.name.startsWith('v')).length;
        }
        if (fs.existsSync(benchmarkDir)) {
          benchmarkVersionCount = fs.readdirSync(benchmarkDir, { withFileTypes: true })
                                    .filter(e => e.isDirectory() && e.name.startsWith('v')).length;
        }

        // Get directory modification time for sorting
        let updatedAt = null;
        try {
          const configStat = fs.statSync(path.join(templateDir, 'config.json'));
          updatedAt = configStat.mtime.toISOString();
        } catch {
          try {
            const dirStat = fs.statSync(templateDir);
            updatedAt = dirStat.mtime.toISOString();
          } catch {}
        }

        return {
          id: d.name,
          name: regEntry.name || config?.name || d.name,
          type: regEntry.type || config?.type || 'unknown',
          description: regEntry.description || config?.description || '',
          benchmarkScore: regEntry.benchmarkScore || config?.benchmarkScore || null,
          trainedAt: regEntry.trainedAt || config?.trainedAt || null,
          usedCount: (regEntry.usedCount || 0) + (usageMap[d.name] || 0),
          fullPath: templateDir,
          evolvingVersionCount,
          benchmarkVersionCount,
          updatedAt,
        };
      });

    return templates;
  }

  /**
   * 重建模板注册表
   */
  rebuildTemplateRegistry() {
    if (!fs.existsSync(TEMPLATES_DIR)) {
      fs.mkdirSync(TEMPLATES_DIR, { recursive: true });
      return [];
    }

    const registry = fs.readdirSync(TEMPLATES_DIR, { withFileTypes: true })
      .filter(d => d.isDirectory() && !d.name.startsWith('_'))
      .map(d => {
        const templateDir = path.join(TEMPLATES_DIR, d.name);
        const config = this._readAgentConfig(templateDir);
        
        let evolvingVersionCount = 0;
        let benchmarkVersionCount = 0;
        const evolvingDir = path.join(templateDir, 'memory', 'evolving');
        const benchmarkDir = path.join(templateDir, 'memory', 'benchmark');
        
        if (fs.existsSync(evolvingDir)) {
          evolvingVersionCount = fs.readdirSync(evolvingDir, { withFileTypes: true })
                                   .filter(e => e.isDirectory() && e.name.startsWith('v')).length;
        }
        if (fs.existsSync(benchmarkDir)) {
          benchmarkVersionCount = fs.readdirSync(benchmarkDir, { withFileTypes: true })
                                    .filter(e => e.isDirectory() && e.name.startsWith('v')).length;
        }

        return {
          id: d.name,
          name: config?.name || d.name,
          type: config?.type || 'unknown',
          description: config?.description || '',
          benchmarkScore: config?.benchmarkScore || null,
          trainedAt: config?.trainedAt || null,
          usedCount: config?.usedCount || 0,
          fullPath: templateDir,
          evolvingVersionCount,
          benchmarkVersionCount
        };
      });

    fs.writeFileSync(
      path.join(TEMPLATES_DIR, '_registry.json'),
      JSON.stringify(registry, null, 2),
      'utf-8'
    );

    return registry;
  }

  // ═══════════════════════════════════════
  //  Agent 统一寻址
  // ═══════════════════════════════════════

  /**
   * 统一定位 Agent 目录
   * @param {string|null} companyId - null 表示全局 Agent
   * @param {string} agentId
   * @returns {string|null} 绝对路径, 不存在则返回 null
   */
  static resolveAgentDir(companyId, agentId) {
    if (companyId) {
      // 公司内 Agent
      const dir = path.join(DATA_DIR, companyId, 'agents', agentId);
      if (fs.existsSync(dir)) return dir;
    }
    // 全局 Agent
    const globalDir = path.join(GLOBAL_AGENTS_DIR, agentId);
    if (fs.existsSync(globalDir)) return globalDir;
    return null;
  }

  // ═══════════════════════════════════════
  //  私有方法
  // ═══════════════════════════════════════

  _saveCompany(company) {
    const dir = path.join(DATA_DIR, company.id);
    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
    fs.writeFileSync(path.join(dir, 'company.json'), JSON.stringify(company, null, 2), 'utf-8');
  }

  _readAgentConfig(agentDir) {
    const fp = path.join(agentDir, 'config.json');
    if (!fs.existsSync(fp)) return null;
    try { return JSON.parse(fs.readFileSync(fp, 'utf-8')); }
    catch { return null; }
  }

  /**
   * 复制模板骨架到目标目录 (只复制 md/json 骨架文件,不复制运行态数据)
   */
  _copyTemplate(srcDir, destDir) {
    fs.mkdirSync(destDir, { recursive: true });

    // 复制白名单中的骨架文件
    for (const file of TEMPLATE_FILES) {
      const srcFile = path.join(srcDir, file);
      if (fs.existsSync(srcFile)) {
        fs.copyFileSync(srcFile, path.join(destDir, file));
      }
    }

    // 复制 .claude/ 目录 (包含 skills/main_skill/SKILL.md 等)
    const srcClaude = path.join(srcDir, '.claude');
    if (fs.existsSync(srcClaude)) {
      this._copyDirRecursive(srcClaude, path.join(destDir, '.claude'));
    }

    // 复制 skills/ 目录 (旧结构兼容)
    const srcSkills = path.join(srcDir, 'skills');
    if (fs.existsSync(srcSkills)) {
      this._copyDirRecursive(srcSkills, path.join(destDir, 'skills'));
    }

    // 初始化空的 memory 目录
    const memoryDir = path.join(destDir, 'memory');
    fs.mkdirSync(memoryDir, { recursive: true });
    fs.writeFileSync(path.join(memoryDir, 'memory.md'), '# 我的记忆\n\n## 关键事实\n\n_(刚入职,尚无记忆)_\n\n## 已验证的模式\n\n## 失败教训\n', 'utf-8');
  }

  /**
   * 复制模板骨架到目标目录 — 引用模式变体
   *
   * 和 _copyTemplate() 几乎一样,唯一区别是跳过 'agent.md'(这份文件改为运行时
   * 引用共享的 legacy_path/agent.md,见 graph-service.lookupSharedAgentMd)。
   * 其余骨架文件 / .claude/ / skills/ / memory 初始化完全一致。
   */
  _provisionReferenceAgent(srcDir, destDir) {
    fs.mkdirSync(destDir, { recursive: true });

    // 复制白名单中的骨架文件,跳过 agent.md
    for (const file of TEMPLATE_FILES) {
      if (file === 'agent.md') continue;
      const srcFile = path.join(srcDir, file);
      if (fs.existsSync(srcFile)) {
        fs.copyFileSync(srcFile, path.join(destDir, file));
      }
    }

    // 复制 .claude/ 目录 (包含 skills/main_skill/SKILL.md 等)
    const srcClaude = path.join(srcDir, '.claude');
    if (fs.existsSync(srcClaude)) {
      this._copyDirRecursive(srcClaude, path.join(destDir, '.claude'));
    }

    // 复制 skills/ 目录 (旧结构兼容)
    const srcSkills = path.join(srcDir, 'skills');
    if (fs.existsSync(srcSkills)) {
      this._copyDirRecursive(srcSkills, path.join(destDir, 'skills'));
    }

    // 初始化空的 memory 目录
    const memoryDir = path.join(destDir, 'memory');
    fs.mkdirSync(memoryDir, { recursive: true });
    fs.writeFileSync(path.join(memoryDir, 'memory.md'), '# 我的记忆\n\n## 关键事实\n\n_(刚入职,尚无记忆)_\n\n## 已验证的模式\n\n## 失败教训\n', 'utf-8');
  }

  _copyDirRecursive(src, dest) {
    fs.mkdirSync(dest, { recursive: true });
    const entries = fs.readdirSync(src, { withFileTypes: true });
    for (const entry of entries) {
      const srcPath = path.join(src, entry.name);
      const destPath = path.join(dest, entry.name);
      if (entry.isDirectory()) {
        this._copyDirRecursive(srcPath, destPath);
      } else {
        fs.copyFileSync(srcPath, destPath);
      }
    }
  }

  /**
   * 注入公司上下文到新复制的 Agent
   *
   * @param {string} companyId
   * @param {string} agentId
   * @param {object} opts
   * @param {object} [modeOpts]
   * @param {boolean} [modeOpts.referenceMode=false] - 引用模式:私有目录里没有 agent.md
   *   (见 hire() 的 _provisionReferenceAgent 分支),所属公司信息不再追加进 agent.md,
   *   而是全新写入 company-context.md。默认 false,legacy 行为完全不变。
   */
  _injectCompanyContext(companyId, agentId, opts = {}, { referenceMode = false } = {}) {
    const company = this.get(companyId);
    if (!company) return;

    const agentDir = path.join(DATA_DIR, companyId, 'agents', agentId);

    // 1. 更新 config.json: 添加 companyId, 设置状态为 active
    const configPath = path.join(agentDir, 'config.json');
    if (fs.existsSync(configPath)) {
      const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
      config.companyId = companyId;
      config.status = 'active';
      if (config.type === 'cxo') {
        config.parent_id = 'master';
      } else {
        config.parent_id = company.ceo || 'ceo';
      }
      if (referenceMode) {
        config.systemAgentRef = agentId;
      }
      fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
    }

    // 2. 追加公司信息到 agent.md(legacy)/ 全新写入 company-context.md(引用模式,agent.md 不在私有目录里)
    const companyContext = [
      '',
      '---',
      '',
      '## 所属公司',
      `- **公司ID**: ${companyId}`,
      `- **公司名称**: ${company.name}`,
      `- **公司使命**: ${company.description || '待定义'}`,
      '',
      `> 你是 **${company.name}** 的员工。你的所有工作都应围绕公司的使命和目标展开。`,
      opts.customAgent || '',
    ].join('\n');

    if (referenceMode) {
      const contextPath = path.join(agentDir, 'company-context.md');
      fs.writeFileSync(contextPath, companyContext.replace(/^\n+/, ''), 'utf-8');
    } else {
      const agentMdPath = path.join(agentDir, 'agent.md');
      if (fs.existsSync(agentMdPath)) {
        const content = fs.readFileSync(agentMdPath, 'utf-8');
        fs.writeFileSync(agentMdPath, content + companyContext, 'utf-8');
      }
    }

    // 3. 重写 user.md: 指明上级关系
    const userMdPath = path.join(agentDir, 'user.md');
    const userContent = [
      '# 与上级的关系',
      '',
      '## 所属公司',
      `- **公司**: ${company.name} (${companyId})`,
      '',
      '## 汇报对象',
    ];
    const agentConfig = this._readAgentConfig(agentDir);
    if (agentConfig && agentConfig.type === 'cxo') {
      userContent.push('- **直接汇报**: Master (公司创始人/董事会)');
      userContent.push('- **管理范围**: 公司内所有 Agent');
    } else {
      userContent.push(`- **直接汇报**: ${company.ceo || 'CEO'} (公司 CEO)`);
      userContent.push('- **协同**: 公司内其他同事');
    }
    userContent.push('', '## 沟通规则');
    userContent.push('1. 完成任务后主动向上级汇报结果');
    userContent.push('2. 遇到阻碍时及时上报,附带解决建议');
    userContent.push('3. 保持透明,坏消息更要及时同步');
    userContent.push(opts.customUser || '');
    fs.writeFileSync(userMdPath, userContent.join('\n'), 'utf-8');

    // 4. 追加公司文化到 soul.md (如有自定义)
    if (opts.customSoul) {
      const soulPath = path.join(agentDir, 'soul.md');
      if (fs.existsSync(soulPath)) {
        const soulContent = fs.readFileSync(soulPath, 'utf-8');
        fs.writeFileSync(soulPath, soulContent + '\n\n## 公司文化\n' + opts.customSoul + '\n', 'utf-8');
      }
    }
  }

  /**
   * 读回模板使用增量计数(见 TEMPLATE_USAGE_PATH 注释)。
   * 文件不存在 / 内容坏掉 → 返回空对象,调用方退化成只用 registry 基线。
   * @returns {Record<string, number>}
   */
  _readTemplateUsage() {
    try {
      const raw = JSON.parse(fs.readFileSync(TEMPLATE_USAGE_PATH, 'utf-8'));
      return (raw && typeof raw === 'object' && !Array.isArray(raw)) ? raw : {};
    } catch {
      return {};
    }
  }

  /**
   * 更新模板使用次数 —— 只写运行态计数文件,**不再碰** `_registry.json`。
   * 唯一调用方:hire() 走模板命中分支时(本文件内)。
   */
  _updateTemplateUsedCount(templateId) {
    try {
      const usage = this._readTemplateUsage();
      usage[templateId] = (usage[templateId] || 0) + 1;
      fs.mkdirSync(path.dirname(TEMPLATE_USAGE_PATH), { recursive: true });
      fs.writeFileSync(TEMPLATE_USAGE_PATH, JSON.stringify(usage, null, 2) + '\n', 'utf-8');
    } catch (err) {
      console.warn(`[Company] ⚠️ 更新模板使用次数失败: ${err.message}`);
    }
  }
}

module.exports = { CompanyService };