Commit 226489d394fdd788e6008d4e4223106bf17ce55e

Authored by yibo
1 parent 8421f55f

feat(graph-agent): P1 virtual reference addressing — stop duplicating agent.md across companies

hire() now checks system_agents (source_kind='template') before provisioning a new
company agent: if the role has a shared template row, skip copying agent.md and
instead let AgentManager.getAgentConfig()/PromptBuilder.build() resolve the prompt
from the shared legacy_path at call time, with per-company context assembled from a
new company-context.md. Roles without a template row (including the 6 ids that exist
in both system/agents/ and system/templates/, e.g. evolver-youtube-crawler) fall back
to the existing full-copy behavior unchanged.

- server/services/graph-service.js (new): lookupSharedAgentMd(), upsertOrgGraphNode()
- server/services/company-service.js: hire() reference-mode branch, _provisionReferenceAgent()
- server/src/core/agent-manager.js: getAgentConfig() resolves prompt/companyContextPath
- server/src/core/prompt-builder.js: build() concatenates company-context.md
- unit + integration tests covering all 6 acceptance criteria from
  docs/todo/system-design/27-p1-virtual-reference.md §6, including a regression test
  against the real idearun:evolver-youtube-crawler naming-collision case

Full regression suite (587 tests) passes; independent adversarial review found 0
blocking/major issues.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
docs/todo/system-design/27-p1-virtual-reference.md 0 → 100644
  1 +# 27-P1. 虚拟引用寻址 — 需求与设计文档
  2 +
  3 +> **所属**: [27 Graph Agent 架构](./27-graph-agent-architecture.md) 的 Phase P1("虚拟引用")
  4 +> **版本**: v0.2(设计阶段,未实现;因 P0 完工同步更新)
  5 +> **日期**: 2026-08-15
  6 +> **前置**: P0 地基已**全部完工**并提交(commit `8421f55`)——`seedGlobalAgents()`/`seedTemplates()`/`seedCompanyAgents()`/`verifyCounts()` 四步全部实现,`system_agents.legacy_path` 可用,`org_graph_nodes` 已经把**现有全部公司雇佣关系**回填完毕(不再是空表)。P0 实施过程中发现一个直接影响 P1 设计的问题:**`system/agents/` 与 `system/templates/` 存在 6 个同名但内容可能不同步的 id**,详见 [27 号文档 §7](./27-graph-agent-architecture.md#七p0-实施发现2026-08-15) 与下文 §4.6——本版本已针对这个问题修正了查表逻辑。
  7 +
  8 +---
  9 +
  10 +## 一、目标与非目标
  11 +
  12 +### 目标(本阶段要交付什么)
  13 +
  14 +按 27 号文档 P1 行的原始定义:
  15 +
  16 +> 停止文件拷贝,改为引用。改造 `AgentManager.getAgentConfig()` + `PromptBuilder.build()` 支持 `(agentId, companyId)` 寻址;`company-service.hire()` 改为创建 org_graph 引用节点而非 `_copyTemplate()`。
  17 +
  18 +经过对现有代码的走查(见第三节),这句话在真正落地时需要收窄——不是"完全停止拷贝",而是**只让 `agent.md` 这一份文件摆脱物理拷贝**,理由见第四节的关键约束分析。
  19 +
  20 +### 非目标(本阶段明确不做)
  21 +
  22 +- **不做** `soul.md` / `identity.md` / `tools.md` / `.claude/skills/` 的去重——原因是运行时 CLI 进程按 `cwd` 相对路径读取它们(证据见 §3.3),贸然去重会在 runtime 直接读不到文件。这些文件的去重留给后续阶段(等这些模板文件内部的相对引用被统一改写为绝对共享路径之后再做)。
  23 +- **不做** Org Graph 前端展示、`company.json.agents[]` 的废弃——`org_graph_nodes` 在 P1 只是**追加写入**,不替换任何现有读取路径。
  24 +- **不做** `memory-service.js` / `heartbeat-service.js` / `task-service.js` / `agent-chat.js` 里重复的 `id.includes(':')` 寻址逻辑的统一收编——P1 刻意不碰这些文件,把 blast radius 限制在 `agent-manager.js` + `prompt-builder.js` + `company-service.js` 三个文件内(见第八节)。
  25 +- **不做**存量公司数据迁移——旧公司(P1 上线前已 `hire()` 过的 agent)永远走原有的物理拷贝路径,不强制转换。
  26 +- **不做** `system/agents/` 与 `system/templates/` 之间 6 个同名 id 的内容合并决策——这是 27 号文档 §7 抛出的产品问题(哪份文件才是权威版本),P1 只做到"绕开风险、不读错文件",不做"解决冲突"。见 §4.6。
  27 +
  28 +---
  29 +
  30 +## 二、背景:为什么只能先做 agent.md
  31 +
  32 +27 号文档 §1 列的四个问题里,P1 直接对应的是第 1 条"状态碎片化":
  33 +
  34 +> 同一角色在 10 家公司名下就有 10 份互不相干的 `agent.md`/`memory.md`。模板更新后,已雇佣的实例不会同步。
  35 +
  36 +但 `memory.md` 是运行时持续写入的**私有**状态(每家公司的 Agent 记忆本来就该不同),不在去重范围内——27 号文档自己在 §3.2 也是这么定义 `scope=public` 的 `memory.md`(跨公司共享的是"能力"记忆,不是任意私有工作记忆)。真正符合"应该共享但目前被拷贝成 N 份"定义的,是**角色定义文件**:`agent.md`/`soul.md`/`identity.md`/`tools.md`。
  37 +
  38 +P1 要解决的具体问题:Innovator 把某个角色的 `agent.md` evolve 到 v1.4,但已经雇佣过 v1.1 版本的 5 家公司,实例文件永远停在 v1.1,除非手动逐个覆盖。
  39 +
  40 +---
  41 +
  42 +## 三、现状代码走查(决定设计边界的关键证据)
  43 +
  44 +### 3.1 寻址入口:`AgentManager.getAgentConfig()`
  45 +
  46 +`server/src/core/agent-manager.js:124-202`。对 `"companyId:role"` 格式的地址,走的是"动态兜底"分支(第 131-191 行),不是 `this.config.agents` 静态配置——company-hired 的 agent **从来没有**进入过静态配置,每次都靠这个分支现场拼出 `agentConfig`:
  47 +
  48 +```js
  49 +agentConfig = {
  50 + type: 'orchestrator', protocol: 'claude-cli', ...,
  51 + prompt: path.join(agentDir, 'agent.md'), // ← P1 要改的就是这一行的来源
  52 + workDir: agentDir, // ← 这一行必须保持不变(见 3.3)
  53 + ...
  54 +};
  55 +```
  56 +
  57 +拼出来的结果会缓存进 `this.config.agents[agentName]`(第 187-190 行),下一步 `PromptBuilder.build()` 直接读这个缓存,**不会**重新解析地址。这意味着 P1 的核心改动点只有一个:**这个分支怎么决定 `prompt` 字段指向哪。**
  58 +
  59 +### 3.2 `PromptBuilder.build()` 不需要感知寻址
  60 +
  61 +`server/src/core/prompt-builder.js:130-177`。它读的是 `this.config.agents[agentName].prompt`,对这个路径来自哪里完全无感。也就是说:**只要 agent-manager.js 把 `prompt` 字段指对地方,PromptBuilder 本身理论上不用改——除非要把"公共 agent.md + 私有 company-context"拼成两段(见 3.4)。**
  62 +
  63 +### 3.3 关键约束:`workDir` 决定了哪些文件必须留在私有目录
  64 +
  65 +`system/templates/qa-judge/agent.md:483-489`:"参考文档"一节用的是相对路径:
  66 +
  67 +```
  68 +- `soul.md` - 判官人格与思维方式
  69 +- `identity.md` - 身份信息与核心原则
  70 +- `../../workspace/innovator/qa_judge_ideal_model.md` - 理想能力模型
  71 +```
  72 +
  73 +Claude CLI 子进程以 `workDir`(= `agentDir`,私有目录)为 `cwd` 启动,之后自己用文件工具按相对路径读取 `soul.md`。**如果这些文件不物理存在于私有目录,agent 运行时直接读不到。** 这就排除了"把整个 agent 目录指向共享位置"这个最简单的方案——那样会导致同一个共享目录被多家公司的 CLI 进程并发写入/读取,且 Claude CLI 自身的项目级状态(存在 `~/.claude/projects/<按路径 hash>/`)也会被多家公司共用同一路径而串数据。**结论:`workDir` 必须继续指向私有目录,不能改。**
  74 +
  75 +### 3.4 隐藏耦合:`agent.md` 今天不是纯共享文件,会被写脏
  76 +
  77 +`server/services/company-service.js:687-704`(`_injectCompanyContext` 第 2 步):`hire()` 复制模板后,**直接把公司归属信息追加进复制出来的 `agent.md`**:
  78 +
  79 +```js
  80 +const companyContext = ['', '---', '', '## 所属公司', `- **公司ID**: ${companyId}`, ...].join('\n');
  81 +fs.writeFileSync(agentMdPath, content + companyContext, 'utf-8');
  82 +```
  83 +
  84 +这意味着如果简单粗暴地让 `prompt` 直接指向共享 `legacy_path/agent.md`,会丢失这段"我是哪家公司的员工"的上下文——而这段上下文对 Agent 的行为是必需的(决定它向谁汇报、服务于什么使命)。**P1 必须把这段追加内容从"写死进文件"改成"运行时拼接"**,这正好对应 27 号文档 §3.6 说的"PromptBuilder 装配公共定义 + 私有语境"。
  85 +
  86 +`user.md` 不受影响:它是**整份重写**(`company-service.js:707-729`),不是追加共享内容,本来就是纯私有文件,P1 不用动它。
  87 +
  88 +---
  89 +
  90 +## 四、设计方案
  91 +
  92 +### 4.1 数据流总览
  93 +
  94 +```
  95 +hire(companyId, role)
  96 + │
  97 + ├─ 查 system_agents 表: SELECT * WHERE id = role AND source_kind = 'template'
  98 + │ (注意:只匹配 'template',不匹配 'global_agent'——原因见 §4.6)
  99 + │
  100 + ├─ 命中
  101 + │ → 引用模式:
  102 + │ · 私有目录仍创建(config.json / soul.md / identity.md / tools.md /
  103 + │ heartbeat.md / plan.md / todo.md / cron.json / .claude/ / skills/
  104 + │ 照今天原样拷贝 —— 不变)
  105 + │ · 不拷贝 agent.md
  106 + │ · config.json 新增字段 systemAgentRef = role
  107 + │ · 新写 company-context.md(取代原本追加进 agent.md 的那段内容)
  108 + │ · INSERT org_graph_nodes(company_id, system_agent_id, role_name)
  109 + │ (幂等,见 4.4 的唯一索引)
  110 + │
  111 + └─ 未命中(system_agents 里没有 source_kind='template' 的这一行——
  112 + 可能是新模板还没跑 seed,也可能是 §4.6 那 6 个命名冲突 id 之一)
  113 + → 回退到今天的 _copyTemplate() 全量拷贝(含 agent.md),行为零变化
  114 + → console.warn 提示"运行 npm run graph:seed 以启用引用模式,或该 id 存在命名空间冲突见 27 号文档 §7"
  115 +```
  116 +
  117 +### 4.2 `AgentManager.getAgentConfig()` 改动(agent-manager.js:131-191)
  118 +
  119 +在现有动态兜底分支里,`agentDir` 存在之后,新增一步:读 `agentDir/config.json` 的 `systemAgentRef` 字段。
  120 +
  121 +```js
  122 +if (fs.existsSync(agentDir)) {
  123 + const config = readConfigIfExists(agentDir); // 已有的 _readAgentConfig 等价逻辑
  124 + const ref = config?.systemAgentRef;
  125 + const sharedAgentMdPath = ref ? lookupSharedAgentMd(ref) : null; // 见 4.3
  126 +
  127 + agentConfig = {
  128 + type: 'orchestrator', protocol: 'claude-cli', ...,
  129 + prompt: sharedAgentMdPath || path.join(agentDir, 'agent.md'), // 引用模式 vs legacy 二选一
  130 + companyContextPath: ref ? path.join(agentDir, 'company-context.md') : null, // 新增,供 PromptBuilder 用
  131 + workDir: agentDir, // 不变
  132 + ...
  133 + };
  134 +}
  135 +```
  136 +
  137 +`lookupSharedAgentMd(systemAgentId)`:
  138 +
  139 +```sql
  140 +SELECT legacy_path FROM system_agents WHERE id = ? AND source_kind = 'template'
  141 +```
  142 +
  143 +**`source_kind` 过滤是硬性要求,不是可选优化**——见 §4.6。查到行后拼 `path.join(ROOT, legacy_path, 'agent.md')`;查不到则整体走 legacy 全量拷贝分支。这个查询函数放在**新文件** `server/services/graph-service.js`(P1 自己的模块,不改动 P0 owner 的 `graph-db.js`/`graph-seed-service.js`,避免并行开发冲突),内部调用 `graph-db.js` 导出的 `getDb()`。
  144 +
  145 +### 4.3 `PromptBuilder.build()` 改动(prompt-builder.js:130-177)
  146 +
  147 +`agentConfig.companyContextPath` 非空时,在 `getAgentPrompt()` 读完共享 `agent.md` 之后,再读一份 `company-context.md` 并作为独立 part 拼进去,位置对应今天"agent.md 正文 + 追加的所属公司段"的顺序:
  148 +
  149 +```js
  150 +if (isSkillBased) {
  151 + ...
  152 +} else {
  153 + ...
  154 + const agentPrompt = this.getAgentPrompt(agentName); // 现在可能来自共享路径
  155 + if (agentPrompt) parts.push(agentPrompt);
  156 + if (agent.companyContextPath && fs.existsSync(agent.companyContextPath)) {
  157 + parts.push(this.loadFile(agent.companyContextPath)); // 新增
  158 + }
  159 +}
  160 +```
  161 +
  162 +对 legacy 拷贝模式的 agent(`companyContextPath` 为 `null`),这个分支不生效,行为完全不变。
  163 +
  164 +### 4.4 `company-service.hire()` 改动(company-service.js:189-230, 621-648, 667-739)
  165 +
  166 +- `_copyTemplate()` 新增一个引用模式变体(暂命名 `_provisionReferenceAgent()`):复制 `TEMPLATE_FILES` 时跳过 `agent.md`,其余不变。
  167 +- `_injectCompanyContext()` 引用模式下:第 2 步(追加进 agent.md)改成写一个新文件 `company-context.md`(内容就是原来那段 `## 所属公司` 文本 + `opts.customAgent`),不再碰 `agent.md`(因为它现在压根不在私有目录里)。第 1、3、4 步(config.json / user.md / soul.md 自定义)完全不变。
  168 +- `hire()` 成功后,除了今天已有的 `company.agents.push(roleName)` + `_saveCompany()`(**继续保留,不替换**——很多地方还在读 `company.json.agents[]`),额外调用 `graph-service.upsertOrgGraphNode(companyId, roleName, roleName)`。这一步失败不应该让 `hire()` 整体失败(try/catch + warn),因为 P1 阶段 org_graph_nodes 只是审计记录,不是唯一真相源。
  169 +
  170 +### 4.5 schema 微调:`org_graph_nodes` 唯一索引
  171 +
  172 +现有 `graph-db.js`(P0 产物)的 `org_graph_nodes` 没有约束同一 `(company_id, role_name)` 不能重复插入。P1 需要在 `hire()` 幂等重跑时不产生重复行。这是**加法**,不改 P0 已有的表结构定义,用独立语句追加:
  173 +
  174 +```sql
  175 +CREATE UNIQUE INDEX IF NOT EXISTS idx_org_graph_nodes_company_role
  176 + ON org_graph_nodes(company_id, role_name);
  177 +```
  178 +
  179 +放在 `graph-service.js` 里首次调用时执行(`CREATE ... IF NOT EXISTS` 幂等),不需要动 `graph-db.js`。加之前建议先跑一次 `SELECT company_id, role_name, COUNT(*) FROM org_graph_nodes GROUP BY 1,2 HAVING COUNT(*) > 1` 确认 `seedCompanyAgents()` 回填的历史数据里没有已存在的重复行(按其去重逻辑推断不应该有,但加唯一索引前验证一次成本很低)。
  180 +
  181 +### 4.6 关键风险:`agent-id` 命名空间冲突(真实存在,不是假设)
  182 +
  183 +27 号文档 §7 记录了一个 P0 实施时才暴露的事实:`agent-creator` / `digester` / `evolver` / `evolver-youtube-crawler` / `hunter` / `innovator` 这 6 个 id,在 `system/agents/` 和 `system/templates/` 下**同时存在**,物理上是两份可能已经不同步的文件。`seedTemplates()` 遇到冲突时让 `global_agent` 行赢(跳过 template 行的写入),保证 `system_agents.id` 唯一性不被破坏——但这只是保护了数据库,没有回答"该读哪份文件"。
  184 +
  185 +这不是纸上谈兵:`data/companies/idearun/agents/` 里已经真实雇佣了 `evolver-youtube-crawler`,正是冲突名单里的一个。而 `company-service.hire()` 的模板查找**永远只看 `TEMPLATES_DIR`**(`company-service.js:199`,`path.join(TEMPLATES_DIR, roleName)`),从来不看 `system/agents/`。
  186 +
  187 +**如果 P1 的查表逻辑写成 `WHERE id = role`(不加 `source_kind` 过滤)**,对 `evolver-youtube-crawler` 这类 id 会查到 `global_agent` 行,`legacy_path` 指向 `system/agents/evolver-youtube-crawler/`——但 `idearun` 当初实际雇佣时拷贝的是 `system/templates/evolver-youtube-crawler/agent.md`。这两份文件如果内容不同,P1 上线后 `idearun` 的 `evolver-youtube-crawler` 在下一次调用时会突然读到一份**它从未被雇佣时使用过的 agent.md**——对用户来说是一次无法预期的、未经确认的角色定义漂移。
  188 +
  189 +**修正**:§4.1/§4.2 已经把查表条件改成 `WHERE id = role AND source_kind = 'template'`。对这 6 个冲突 id,这个条件永远查不到行(因为 `seedTemplates()` 跳过了它们),于是自动落进"未命中 → legacy 全量拷贝"分支——即这 6 个 id 在 P1 阶段**天然被排除在引用模式之外**,不会有虚拟引用行为,直到 27 号文档 §7 提出的"该以哪份文件为准"这个产品问题被人工决定之后,才应该考虑把它们纳入。
  190 +
  191 +---
  192 +
  193 +## 五、与 P0(已完工)的衔接点
  194 +
  195 +P0 已经把 `seedCompanyAgents()` 也做完了:`org_graph_nodes` 现在不是空表,已经为**所有现存公司雇佣关系**(含 `idearun` 的 6 个角色)各建了一行。这对 P1 意味着:
  196 +
  197 +- P1 的 `hire()` 改动(§4.4)在写入新的 `org_graph_nodes` 行时,不能假设自己是"第一个写入者"——历史数据已经在那,§4.5 的唯一索引就是为了让新写入和历史数据共存时不产生重复行。
  198 +- P1 不需要(也不应该)对 `seedCompanyAgents()` 已经创建的 `source_kind='company_hired'` 行做任何处理——那些是"公司自己培养、没有对应模板"的角色,天然不满足 §4.1 的 `source_kind='template'` 命中条件,会正确地继续走 legacy 路径。
  199 +- 唯一需要在 P1 动工前处理的衔接项就是 §4.6 的命名冲突排除逻辑——这一点已经通过查表条件的过滤自动满足,**不需要额外的迁移或人工介入**。
  200 +
  201 +---
  202 +
  203 +## 六、验收标准
  204 +
  205 +沿用 27 号文档给出的验收标准,细化为可直接验证的检查项:
  206 +
  207 +1. 对一个已在 `system_agents` 表中的模板角色(如 `qa-judge`)执行 `hire(companyId, 'qa-judge')`:
  208 + - 私有目录下**没有** `agent.md` 文件
  209 + - 私有目录下**有** `company-context.md`,内容包含公司 ID/名称/使命
  210 + - `config.json` 含 `systemAgentRef: "qa-judge"`
  211 + - `org_graph_nodes` 表新增一行 `(companyId, 'qa-judge', 'qa-judge')`
  212 +2. 对该 agent 调用 `callAgent()`:`buildFullPrompt()` 产出的最终 prompt 中,agent.md 正文来自 `system/templates/qa-judge/agent.md`(与共享文件内容一致,改共享文件后无需重新 hire 即可生效),且包含 company-context.md 的所属公司段落。
  213 +3. 对一个**不在** `system_agents` 表中的模板角色执行 `hire()`:退回到今天的行为(完整拷贝含 `agent.md`),并在日志里看到 reseed 提示。
  214 +4. 找一家 P1 上线前已经 `hire()` 过的旧公司(纯目录拷贝,无 `systemAgentRef`):`callAgent()` 行为不变,`getAgentConfig()`/`PromptBuilder.build()` 都不进入新分支。
  215 +5. 重复对同一 `(companyId, role)` 调用 `hire()`:第二次直接命中 `already_exists` 短路(这一步逻辑不变),`org_graph_nodes` 不产生重复行。
  216 +6. **命名冲突回归用例**(对应 §4.6):用一家**新**测试公司(不是 `idearun`——它是 P1 上线前的存量雇佣,天然走 legacy 分支,测不出这个问题)对角色名 `evolver-youtube-crawler` 执行一次全新的 `hire()`。断言:`hire()` 内部的 `system_agents` 查表**查不到**行(因为唯一的 template 行被 seed 时跳过了),因此整个走 legacy 全量拷贝分支(含 `agent.md`),而不是误把 `global_agent` 行的 `legacy_path`(`system/agents/evolver-youtube-crawler/`)当成引用来源。这条用例失败就意味着 §4.6 的 `source_kind='template'` 过滤条件被写错了。
  217 +
  218 +---
  219 +
  220 +## 七、影响面 / Blast Radius
  221 +
  222 +P1 改动限定在三个文件 + 一个新文件:
  223 +
  224 +| 文件 | 改动类型 |
  225 +|------|----------|
  226 +| `server/src/core/agent-manager.js` | 修改:动态兜底分支的 `prompt` 来源判断 |
  227 +| `server/src/core/prompt-builder.js` | 修改:`build()` 增加 `companyContextPath` 拼接分支 |
  228 +| `server/services/company-service.js` | 修改:`hire()` / `_copyTemplate()` / `_injectCompanyContext()` 分叉出引用模式路径 |
  229 +| `server/services/graph-service.js` | 新增:`lookupSharedAgentMd()` / `upsertOrgGraphNode()` |
  230 +
  231 +**明确不改**,但依赖同一批私有目录路径的下游——之所以不改是因为引用模式下私有目录的物理位置、`config.json`、`memory/`、`.claude/` 全部保持原样,这些文件仍然照常存在:
  232 +
  233 +| 文件 | 为什么不受影响 |
  234 +|------|----------------|
  235 +| `server/services/memory-service.js` | 只读 `data/companies/{id}/agents/{role}/memory/`,P1 不改这个目录的存在 |
  236 +| `server/services/heartbeat-service.js` | 同上,读 `config.json`/`heartbeat.md`,两者仍照常私有存在 |
  237 +| `server/services/task-service.js` | 同上 |
  238 +| `server/routes/agent-chat.js` | 同上,且 `agentName.includes(':')` 的解析方式完全不变 |
  239 +
  240 +如果后续阶段要把 `soul.md`/`identity.md`/`tools.md` 也去重,才需要重新评估这四个文件。
  241 +
  242 +---
  243 +
  244 +## 八、测试计划
  245 +
  246 +- 单元测试:`graph-service.js` 的 `upsertOrgGraphNode` 幂等性、`lookupSharedAgentMd` 对存在/不存在两种情况的返回。
  247 +- 集成测试(复用 `server/scripts/test-company-e2e.js` 的模式):`hire()` 引用模式全流程 → `callAgent()` → 断言最终 prompt 内容分段正确。
  248 +- 回归测试:跑一遍现有 `server/tests/**` 中涉及 `company-service.js` / `agent-manager.js` 的用例,确认 legacy 拷贝模式路径零回归。
  249 +
  250 +---
  251 +
  252 +## 九、Open Questions(留给实现阶段核实)
  253 +
  254 +1. **SKILL.md 模式的 agent**:`PromptBuilder.build()` 里 `isSkillBased`(`promptPath.endsWith('SKILL.md')`)分支目前直接把 SKILL.md 当唯一 prompt 来源,不叠加 protocol。当前梳理的模板样本(`qa-judge` 等)都是 `agent.md` 模式,没有验证 SKILL.md 模式模板是否也存在同样的"追加公司上下文"问题。实现前需要抽查 `system/templates/*` 里是不是有 `prompt` 指向 `.claude/skills/*/SKILL.md` 的模板。
  255 +2. **`opts.customAgent` 的语义**:今天允许调用方在 `hire()` 时传一段自定义文本追加进 `agent.md`。P1 把它挪进 `company-context.md` 后,语义上从"追加进角色定义"变成"追加进公司专属上下文",需要确认现有调用方(如果有)不依赖它出现在 `agent.md` 本身的物理路径里。
  256 +3. **共享 `agent.md` 被 Evolver 重写时的一致性**:P1 只解决"读"的问题(新 hire 读到最新版)。如果 Evolver 正在原地重写 `system/templates/{role}/agent.md` 的同时有 agent 正在被调用读取,会不会读到半写状态?这个问题在 P0 之前就存在(模板文件本来就会被 Evolver 直接改写),P1 没有让它变得更差,但既然现在读路径变得"更热"(被更多公司共享读取),值得在实现时评估要不要加一层读写锁或原子替换(写临时文件 + rename)。
  257 +4. **6 个命名冲突 id 何时纳入引用模式**:§4.6 的过滤条件让 `agent-creator`/`digester`/`evolver`/`evolver-youtube-crawler`/`hunter`/`innovator` 这 6 个 id 在 P1 阶段永远走 legacy 分支。这是刻意的临时状态,不是长期方案——一旦 27 号文档 §7 提出的"哪份文件权威"问题有了产品决策,需要回来把这 6 个 id 的处理方式补上(可能是人工合并文件、也可能是确认两份本来就该是不同东西、重新命名去冲突)。这一项应该在排 P2(Org Graph)之前找时间处理掉,因为 P2 要让 CEO/HR agent 直接在 org graph 上招聘,到时候这 6 个 id 的歧义会更早暴露给用户。
... ...
server/services/company-service.js
... ... @@ -12,6 +12,7 @@
12 12  
13 13 const fs = require('fs');
14 14 const path = require('path');
  15 +const { lookupSharedAgentMd, upsertOrgGraphNode } = require('./graph-service');
15 16  
16 17 const ROOT_DATA_DIR = path.resolve(__dirname, '../../data');
17 18 const DATA_DIR = path.join(ROOT_DATA_DIR, 'companies');
... ... @@ -198,9 +199,18 @@ class CompanyService {
198 199 // 阶段 A: 在模板库中查找
199 200 const templateDir = path.join(TEMPLATES_DIR, roleName);
200 201 if (fs.existsSync(templateDir)) {
201   - // ✅ 模板存在 → 复制骨架到公司
202   - this._copyTemplate(templateDir, targetDir);
203   - this._injectCompanyContext(companyId, roleName, opts);
  202 + // system_agents 里是否有这个角色的共享 agent.md(source_kind='template')?
  203 + // 有 → 引用模式(不拷贝 agent.md);没有(含 6 个命名冲突 id)→ legacy 全量拷贝,行为零变化
  204 + const sharedAgentMdPath = lookupSharedAgentMd(roleName);
  205 +
  206 + if (sharedAgentMdPath) {
  207 + this._provisionReferenceAgent(templateDir, targetDir);
  208 + this._injectCompanyContext(companyId, roleName, opts, { referenceMode: true });
  209 + } else {
  210 + // ✅ 模板存在 → 复制骨架到公司(legacy 全量拷贝,含 agent.md)
  211 + this._copyTemplate(templateDir, targetDir);
  212 + this._injectCompanyContext(companyId, roleName, opts);
  213 + }
204 214 this._updateTemplateUsedCount(roleName);
205 215  
206 216 // 更新公司的 agents 列表
... ... @@ -215,7 +225,14 @@ class CompanyService {
215 225 company.updatedAt = new Date().toISOString();
216 226 this._saveCompany(company);
217 227  
218   - console.log(`[Company] ✅ ${companyId} 招聘 ${roleName} (从模板)`);
  228 + // Org Graph 引用节点记录(审计用途,失败不影响雇佣结果本身)
  229 + try {
  230 + upsertOrgGraphNode(companyId, roleName, roleName);
  231 + } catch (err) {
  232 + console.warn(`[Company] ⚠️ org_graph_nodes 写入失败(不影响雇佣结果): ${err.message}`);
  233 + }
  234 +
  235 + console.log(`[Company] ✅ ${companyId} 招聘 ${roleName} (从模板${sharedAgentMdPath ? ',引用模式' : ''})`);
219 236 return { status: 'hired_from_template', agentId: roleName, agentDir: targetDir };
220 237 }
221 238  
... ... @@ -647,6 +664,43 @@ class CompanyService {
647 664 fs.writeFileSync(path.join(memoryDir, 'memory.md'), '# 我的记忆\n\n## 关键事实\n\n_(刚入职,尚无记忆)_\n\n## 已验证的模式\n\n## 失败教训\n', 'utf-8');
648 665 }
649 666  
  667 + /**
  668 + * 复制模板骨架到目标目录 — 引用模式变体
  669 + *
  670 + * 和 _copyTemplate() 几乎一样,唯一区别是跳过 'agent.md'(这份文件改为运行时
  671 + * 引用共享的 legacy_path/agent.md,见 graph-service.lookupSharedAgentMd)。
  672 + * 其余骨架文件 / .claude/ / skills/ / memory 初始化完全一致。
  673 + */
  674 + _provisionReferenceAgent(srcDir, destDir) {
  675 + fs.mkdirSync(destDir, { recursive: true });
  676 +
  677 + // 复制白名单中的骨架文件,跳过 agent.md
  678 + for (const file of TEMPLATE_FILES) {
  679 + if (file === 'agent.md') continue;
  680 + const srcFile = path.join(srcDir, file);
  681 + if (fs.existsSync(srcFile)) {
  682 + fs.copyFileSync(srcFile, path.join(destDir, file));
  683 + }
  684 + }
  685 +
  686 + // 复制 .claude/ 目录 (包含 skills/main_skill/SKILL.md 等)
  687 + const srcClaude = path.join(srcDir, '.claude');
  688 + if (fs.existsSync(srcClaude)) {
  689 + this._copyDirRecursive(srcClaude, path.join(destDir, '.claude'));
  690 + }
  691 +
  692 + // 复制 skills/ 目录 (旧结构兼容)
  693 + const srcSkills = path.join(srcDir, 'skills');
  694 + if (fs.existsSync(srcSkills)) {
  695 + this._copyDirRecursive(srcSkills, path.join(destDir, 'skills'));
  696 + }
  697 +
  698 + // 初始化空的 memory 目录
  699 + const memoryDir = path.join(destDir, 'memory');
  700 + fs.mkdirSync(memoryDir, { recursive: true });
  701 + fs.writeFileSync(path.join(memoryDir, 'memory.md'), '# 我的记忆\n\n## 关键事实\n\n_(刚入职,尚无记忆)_\n\n## 已验证的模式\n\n## 失败教训\n', 'utf-8');
  702 + }
  703 +
650 704 _copyDirRecursive(src, dest) {
651 705 fs.mkdirSync(dest, { recursive: true });
652 706 const entries = fs.readdirSync(src, { withFileTypes: true });
... ... @@ -663,8 +717,16 @@ class CompanyService {
663 717  
664 718 /**
665 719 * 注入公司上下文到新复制的 Agent
  720 + *
  721 + * @param {string} companyId
  722 + * @param {string} agentId
  723 + * @param {object} opts
  724 + * @param {object} [modeOpts]
  725 + * @param {boolean} [modeOpts.referenceMode=false] - 引用模式:私有目录里没有 agent.md
  726 + * (见 hire() 的 _provisionReferenceAgent 分支),所属公司信息不再追加进 agent.md,
  727 + * 而是全新写入 company-context.md。默认 false,legacy 行为完全不变。
666 728 */
667   - _injectCompanyContext(companyId, agentId, opts = {}) {
  729 + _injectCompanyContext(companyId, agentId, opts = {}, { referenceMode = false } = {}) {
668 730 const company = this.get(companyId);
669 731 if (!company) return;
670 732  
... ... @@ -681,26 +743,35 @@ class CompanyService {
681 743 } else {
682 744 config.parent_id = company.ceo || 'ceo';
683 745 }
  746 + if (referenceMode) {
  747 + config.systemAgentRef = agentId;
  748 + }
684 749 fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
685 750 }
686 751  
687   - // 2. 追加公司信息到 agent.md
688   - const agentMdPath = path.join(agentDir, 'agent.md');
689   - if (fs.existsSync(agentMdPath)) {
690   - const content = fs.readFileSync(agentMdPath, 'utf-8');
691   - const companyContext = [
692   - '',
693   - '---',
694   - '',
695   - '## 所属公司',
696   - `- **公司ID**: ${companyId}`,
697   - `- **公司名称**: ${company.name}`,
698   - `- **公司使命**: ${company.description || '待定义'}`,
699   - '',
700   - `> 你是 **${company.name}** 的员工。你的所有工作都应围绕公司的使命和目标展开。`,
701   - opts.customAgent || '',
702   - ].join('\n');
703   - fs.writeFileSync(agentMdPath, content + companyContext, 'utf-8');
  752 + // 2. 追加公司信息到 agent.md(legacy)/ 全新写入 company-context.md(引用模式,agent.md 不在私有目录里)
  753 + const companyContext = [
  754 + '',
  755 + '---',
  756 + '',
  757 + '## 所属公司',
  758 + `- **公司ID**: ${companyId}`,
  759 + `- **公司名称**: ${company.name}`,
  760 + `- **公司使命**: ${company.description || '待定义'}`,
  761 + '',
  762 + `> 你是 **${company.name}** 的员工。你的所有工作都应围绕公司的使命和目标展开。`,
  763 + opts.customAgent || '',
  764 + ].join('\n');
  765 +
  766 + if (referenceMode) {
  767 + const contextPath = path.join(agentDir, 'company-context.md');
  768 + fs.writeFileSync(contextPath, companyContext.replace(/^\n+/, ''), 'utf-8');
  769 + } else {
  770 + const agentMdPath = path.join(agentDir, 'agent.md');
  771 + if (fs.existsSync(agentMdPath)) {
  772 + const content = fs.readFileSync(agentMdPath, 'utf-8');
  773 + fs.writeFileSync(agentMdPath, content + companyContext, 'utf-8');
  774 + }
704 775 }
705 776  
706 777 // 3. 重写 user.md: 指明上级关系
... ...
server/services/graph-service.js 0 → 100644
  1 +/**
  2 + * Graph Service — P1 虚拟引用寻址支撑函数(新文件,P1 专属)
  3 + *
  4 + * 不修改 P0 已有的 graph-db.js / graph-seed-service.js(那是并行工作线),
  5 + * 只通过 graph-db.js 导出的 getDb() 读写同一个 SQLite 连接。
  6 + *
  7 + * 详细需求与设计见 docs/todo/system-design/27-p1-virtual-reference.md。
  8 + */
  9 +
  10 +const path = require('path');
  11 +const { getDb } = require('./graph-db');
  12 +
  13 +const ROOT = path.resolve(__dirname, '../..');
  14 +
  15 +let indexEnsured = false;
  16 +
  17 +/**
  18 + * 查询某个 system_agent id 对应的共享 agent.md 绝对路径。
  19 + *
  20 + * 只匹配 source_kind = 'template'(不匹配 'global_agent')——这是本次设计修复的一个
  21 + * 真实 bug:system/agents/ 和 system/templates/ 下有 6 个同名 id
  22 + * (agent-creator/digester/evolver/evolver-youtube-crawler/hunter/innovator)
  23 + * 内容可能不同步,hire() 只从 system/templates/ 拷贝过文件,如果查表命中了
  24 + * global_agent 那一行会读错文件(详见 27-graph-agent-architecture.md §7、
  25 + * 27-p1-virtual-reference.md §4.6)。
  26 + *
  27 + * @param {string} systemAgentId
  28 + * @returns {string|null} 共享 agent.md 的绝对路径;查不到对应 template 行时返回 null
  29 + */
  30 +function lookupSharedAgentMd(systemAgentId) {
  31 + const db = getDb();
  32 + const row = db
  33 + .prepare(`SELECT legacy_path FROM system_agents WHERE id = ? AND source_kind = 'template'`)
  34 + .get(systemAgentId);
  35 +
  36 + if (!row) return null;
  37 +
  38 + return path.resolve(ROOT, row.legacy_path, 'agent.md');
  39 +}
  40 +
  41 +function ensureOrgGraphNodeIndex(db) {
  42 + if (indexEnsured) return;
  43 + db.exec(`
  44 + CREATE UNIQUE INDEX IF NOT EXISTS idx_org_graph_nodes_company_role
  45 + ON org_graph_nodes(company_id, role_name)
  46 + `);
  47 + indexEnsured = true;
  48 +}
  49 +
  50 +/**
  51 + * 为 (companyId, roleName) 建立/复用一条 org_graph_nodes 引用记录。
  52 + *
  53 + * hire() 每次成功后都会调用(不论走引用模式还是 legacy 全量拷贝模式),因此不能假设
  54 + * system_agents 里已经有 systemAgentId 对应的行——没有时按 seedCompanyAgents()
  55 + * (graph-seed-service.js 约 213-295 行)对同样场景的字段约定 fallback 插入一行
  56 + * source_kind='company_hired' 的 system_agents 记录。
  57 + *
  58 + * 幂等:org_graph_nodes(company_id, role_name) 唯一索引 + INSERT ... ON CONFLICT DO NOTHING,
  59 + * 重复调用不产生重复行。
  60 + *
  61 + * @param {string} companyId
  62 + * @param {string} systemAgentId
  63 + * @param {string} roleName
  64 + * @returns {void}
  65 + */
  66 +function upsertOrgGraphNode(companyId, systemAgentId, roleName) {
  67 + const db = getDb();
  68 + ensureOrgGraphNodeIndex(db);
  69 +
  70 + const now = new Date().toISOString();
  71 +
  72 + const tx = db.transaction(() => {
  73 + const existingAgent = db.prepare(`SELECT id FROM system_agents WHERE id = ?`).get(systemAgentId);
  74 +
  75 + if (!existingAgent) {
  76 + db.prepare(`
  77 + INSERT INTO system_agents (id, name, scope, owner_company_id, source_kind, legacy_path, status, benchmark_score, created_at, updated_at)
  78 + VALUES (@id, @name, 'company', @owner_company_id, 'company_hired', @legacy_path, 'active', NULL, @created_at, @updated_at)
  79 + `).run({
  80 + id: systemAgentId,
  81 + name: systemAgentId,
  82 + owner_company_id: companyId,
  83 + legacy_path: `data/companies/${companyId}/agents/${roleName}`,
  84 + created_at: now,
  85 + updated_at: now,
  86 + });
  87 + }
  88 +
  89 + db.prepare(`
  90 + INSERT INTO org_graph_nodes (company_id, system_agent_id, role_name, created_at)
  91 + VALUES (@company_id, @system_agent_id, @role_name, @created_at)
  92 + ON CONFLICT(company_id, role_name) DO NOTHING
  93 + `).run({
  94 + company_id: companyId,
  95 + system_agent_id: systemAgentId,
  96 + role_name: roleName,
  97 + created_at: now,
  98 + });
  99 + });
  100 +
  101 + tx();
  102 +}
  103 +
  104 +module.exports = {
  105 + lookupSharedAgentMd,
  106 + upsertOrgGraphNode,
  107 +};
... ...
server/src/core/agent-manager.js
... ... @@ -143,13 +143,41 @@ class AgentManager extends EventEmitter {
143 143  
144 144 // 1. Check if it's an independent Agent
145 145 if (fs.existsSync(agentDir)) {
  146 + // P1 虚拟引用寻址:company-hired 的 agent 可能在 config.json 里带
  147 + // systemAgentRef(company-service.hire() 走引用模式雇佣时写入),
  148 + // 此时 agent.md 不再物理拷贝进私有目录,改为指向共享的
  149 + // system_agents.legacy_path/agent.md(见 docs/todo/system-design/27-p1-virtual-reference.md §4.2)。
  150 + let promptPath = path.join(agentDir, 'agent.md');
  151 + let companyContextPath = null;
  152 + const configJsonPath = path.join(agentDir, 'config.json');
  153 + if (fs.existsSync(configJsonPath)) {
  154 + let ref;
  155 + try {
  156 + const dirConfig = JSON.parse(fs.readFileSync(configJsonPath, 'utf-8'));
  157 + ref = dirConfig?.systemAgentRef;
  158 + } catch (e) {
  159 + // config.json 损坏/不可解析:退回 legacy 行为,不让寻址崩溃
  160 + ref = undefined;
  161 + }
  162 + if (ref) {
  163 + const sharedAgentMdPath = require('../../services/graph-service').lookupSharedAgentMd(ref);
  164 + if (sharedAgentMdPath) {
  165 + promptPath = sharedAgentMdPath;
  166 + companyContextPath = path.join(agentDir, 'company-context.md');
  167 + }
  168 + // sharedAgentMdPath 为 null(理论上不应发生,防御性处理):
  169 + // promptPath/companyContextPath 保持上面初始化的 legacy 默认值。
  170 + }
  171 + }
  172 +
146 173 agentConfig = {
147 174 type: 'orchestrator',
148 175 protocol: 'claude-cli',
149 176 transport: 'pipe',
150 177 launcher: 'claude-local',
151 178 client: 'claude-local',
152   - prompt: path.join(agentDir, 'agent.md'),
  179 + prompt: promptPath,
  180 + companyContextPath,
153 181 workDir: agentDir, // CLI 进程在 Agent 自己的目录下运行,自动读取 .claude/skills/
154 182 description: `Dynamic Agent ${agentName}`
155 183 };
... ...
server/src/core/prompt-builder.js
... ... @@ -156,6 +156,9 @@ class PromptBuilder {
156 156 }
157 157 const agentPrompt = this.getAgentPrompt(agentName);
158 158 if (agentPrompt) parts.push(agentPrompt);
  159 + if (agent.companyContextPath && fs.existsSync(agent.companyContextPath)) {
  160 + parts.push(this.loadFile(agent.companyContextPath));
  161 + }
159 162 }
160 163  
161 164 // User Task
... ...
server/src/tests/unit/prompt-builder.test.js
1   -import { describe, it, expect, beforeEach } from 'vitest';
  1 +import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2 2 const path = require('path');
3 3 const fs = require('fs');
4 4 const { PromptBuilder } = require('../../core/prompt-builder');
... ... @@ -105,6 +105,52 @@ describe(&#39;PromptBuilder&#39;, () =&gt; {
105 105 });
106 106 });
107 107  
  108 + describe('build - companyContextPath (P1 virtual reference)', () => {
  109 + const os = require('os');
  110 + let tmpFile;
  111 +
  112 + afterEach(() => {
  113 + if (tmpFile && fs.existsSync(tmpFile)) {
  114 + fs.unlinkSync(tmpFile);
  115 + }
  116 + tmpFile = undefined;
  117 + });
  118 +
  119 + it('appends company-context.md content when companyContextPath exists', () => {
  120 + tmpFile = path.join(os.tmpdir(), `company-context-${Date.now()}.md`);
  121 + fs.writeFileSync(tmpFile, '## 所属公司\n- **公司ID**: test-co', 'utf-8');
  122 +
  123 + config.agents.coder.companyContextPath = tmpFile;
  124 + const result = builder.build('coder');
  125 +
  126 + expect(result).toContain('## 所属公司');
  127 + expect(result).toContain('test-co');
  128 + });
  129 +
  130 + // <timestamp> in getSystemStateXML() is wall-clock and can legitimately
  131 + // differ by a millisecond between two build() calls, so strip it before
  132 + // comparing outputs for structural equality.
  133 + const stripTimestamp = (s) => s.replace(/<timestamp>.*?<\/timestamp>/, '<timestamp/>');
  134 +
  135 + it('does not change output when companyContextPath is null (legacy mode)', () => {
  136 + const baseline = stripTimestamp(builder.build('coder'));
  137 +
  138 + config.agents.coder.companyContextPath = null;
  139 + const withNull = stripTimestamp(builder.build('coder'));
  140 +
  141 + expect(withNull).toBe(baseline);
  142 + });
  143 +
  144 + it('does not change output when companyContextPath points to a nonexistent file', () => {
  145 + const baseline = stripTimestamp(builder.build('coder'));
  146 +
  147 + config.agents.coder.companyContextPath = path.join(os.tmpdir(), 'does-not-exist-xyz.md');
  148 + const withMissing = stripTimestamp(builder.build('coder'));
  149 +
  150 + expect(withMissing).toBe(baseline);
  151 + });
  152 + });
  153 +
108 154 describe('caching', () => {
109 155 it('should cache loaded files', () => {
110 156 // 第一次加载
... ...
server/tests/integration/graph-agent-p1-acceptance.test.js 0 → 100644
  1 +/**
  2 + * End-to-end acceptance test — P1 虚拟引用寻址
  3 + *
  4 + * Verifies all 6 acceptance criteria from
  5 + * docs/todo/system-design/27-p1-virtual-reference.md §6, against the real
  6 + * hire() -> getAgentConfig() -> promptBuilder.build() pipeline (not mocks),
  7 + * including the §4.6 / §7 naming-collision regression (criterion 6) using
  8 + * the real `evolver-youtube-crawler` id that genuinely collides between
  9 + * system/agents/ and system/templates/ in this repo.
  10 + *
  11 + * Isolation:
  12 + * - GRAPH_DB_PATH points at a throwaway SQLite file for the whole file
  13 + * (same pattern as server/tests/unit/graph-db.test.js) — the real
  14 + * data/graph.sqlite is opened once, read-only, only to assert that the
  15 + * production seed data for the collision id actually has the shape the
  16 + * design doc claims (no `source_kind='template'` row) before mirroring
  17 + * that exact shape into the isolated test DB. No writes ever hit the
  18 + * real data/graph.sqlite.
  19 + * - All hired agents live under temporary company ids
  20 + * (`tmp-p1-acceptance-*`) removed in afterAll.
  21 + * - The one legacy (pre-P1) company used for criterion 4 is the real
  22 + * `idearun` company, accessed read-only only (getAgentConfig / build),
  23 + * never hired into or written to.
  24 + */
  25 +import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  26 +import fs from 'fs';
  27 +import path from 'path';
  28 +import Database from 'better-sqlite3';
  29 +
  30 +describe('P1 virtual reference addressing — full acceptance suite (27-p1-virtual-reference.md §6)', () => {
  31 + const REPO_ROOT = path.resolve(__dirname, '../../..');
  32 + const TEST_DB_PATH = '/tmp/test-graph-agent-p1-acceptance.sqlite';
  33 + const REAL_GRAPH_DB_PATH = path.join(REPO_ROOT, 'data/graph.sqlite');
  34 + const DATA_DIR = path.join(REPO_ROOT, 'data/companies');
  35 + const TEMPLATES_DIR = path.join(REPO_ROOT, 'system/templates');
  36 +
  37 + const RUN_ID = Date.now();
  38 + const CO_QA = `tmp-p1-acceptance-qa-${RUN_ID}`;
  39 + const CO_UNKNOWN = `tmp-p1-acceptance-unknown-${RUN_ID}`;
  40 + const CO_COLLISION = `tmp-p1-acceptance-collision-${RUN_ID}`;
  41 + const UNKNOWN_ROLE = `tmp-p1-nonexistent-role-${RUN_ID}-${Math.random().toString(36).slice(2)}`;
  42 + const COLLISION_ROLE = 'evolver-youtube-crawler'; // real 27§4.6/§7 collision id
  43 + const REGISTRY_PATH = path.join(TEMPLATES_DIR, '_registry.json');
  44 +
  45 + let graphDb;
  46 + let CompanyService;
  47 + let companyService;
  48 + let AgentManager;
  49 + let registrySnapshot; // hire() bumps _registry.json usedCount for real templates as a side
  50 + // effect (company-service.js _updateTemplateUsedCount) — snapshot/restore so hiring the
  51 + // real qa-judge/evolver-youtube-crawler templates in this test never leaves a permanent
  52 + // diff on a tracked file.
  53 +
  54 + beforeAll(() => {
  55 + registrySnapshot = fs.readFileSync(REGISTRY_PATH, 'utf-8');
  56 + // --- Sanity check against the REAL (already-seeded, committed 8421f55) graph.sqlite,
  57 + // read-only: confirm the production seed data genuinely has the shape the design doc
  58 + // claims for the collision id (no source_kind='template' row). This is what makes
  59 + // criterion 6 a real regression test instead of a test of hand-picked fixture data.
  60 + expect(fs.existsSync(REAL_GRAPH_DB_PATH)).toBe(true);
  61 + const realDb = new Database(REAL_GRAPH_DB_PATH, { readonly: true });
  62 + try {
  63 + const rows = realDb.prepare('SELECT source_kind, legacy_path FROM system_agents WHERE id = ?').all(COLLISION_ROLE);
  64 + expect(rows.length).toBeGreaterThan(0);
  65 + expect(rows.some(r => r.source_kind === 'template')).toBe(false);
  66 + expect(rows.some(r => r.source_kind === 'global_agent')).toBe(true);
  67 + } finally {
  68 + realDb.close();
  69 + }
  70 + // Also confirm the physical files this test depends on actually exist in the repo,
  71 + // so a passing test means something (not vacuously true because fixtures were missing).
  72 + expect(fs.existsSync(path.join(TEMPLATES_DIR, 'qa-judge', 'agent.md'))).toBe(true);
  73 + expect(fs.existsSync(path.join(TEMPLATES_DIR, COLLISION_ROLE, 'agent.md'))).toBe(true);
  74 + expect(fs.existsSync(path.join(REPO_ROOT, 'system/agents', COLLISION_ROLE, 'agent.md'))).toBe(true);
  75 + expect(fs.existsSync(path.join(DATA_DIR, 'idearun', 'agents', COLLISION_ROLE, 'agent.md'))).toBe(true);
  76 +
  77 + // --- Now switch to the isolated test DB for everything the test actually mutates.
  78 + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH);
  79 + process.env.GRAPH_DB_PATH = TEST_DB_PATH;
  80 + delete require.cache[require.resolve('../../services/graph-db')];
  81 + delete require.cache[require.resolve('../../services/graph-service')];
  82 + delete require.cache[require.resolve('../../services/company-service')];
  83 + delete require.cache[require.resolve('../../src/core/agent-manager')];
  84 + delete require.cache[require.resolve('../../src/core/prompt-builder')];
  85 + graphDb = require('../../services/graph-db');
  86 + ({ CompanyService } = require('../../services/company-service'));
  87 + AgentManager = require('../../src/core/agent-manager');
  88 + companyService = new CompanyService();
  89 +
  90 + const db = graphDb.getDb();
  91 + const now = new Date().toISOString();
  92 +
  93 + // Mirror the real production seed for qa-judge (source_kind='template').
  94 + db.prepare(`
  95 + INSERT INTO system_agents (id, name, scope, owner_company_id, source_kind, legacy_path, status, benchmark_score, created_at, updated_at)
  96 + VALUES (?, ?, 'public', NULL, 'template', ?, 'active', NULL, ?, ?)
  97 + `).run('qa-judge', 'qa-judge', 'system/templates/qa-judge', now, now);
  98 +
  99 + // Mirror the real production seed for the collision id: only the global_agent row
  100 + // exists (seedTemplates() skipped the template row because seedGlobalAgents() claimed
  101 + // the id first) — verified against the real DB above.
  102 + db.prepare(`
  103 + INSERT INTO system_agents (id, name, scope, owner_company_id, source_kind, legacy_path, status, benchmark_score, created_at, updated_at)
  104 + VALUES (?, ?, 'public', NULL, 'global_agent', ?, 'active', NULL, ?, ?)
  105 + `).run(COLLISION_ROLE, COLLISION_ROLE, `system/agents/${COLLISION_ROLE}`, now, now);
  106 +
  107 + companyService.create({ id: CO_QA, name: 'P1 Acceptance QA Co', description: 'Verifies QA-judge lives here.' });
  108 + companyService.create({ id: CO_UNKNOWN, name: 'P1 Acceptance Unknown-role Co', description: 'Untrained role fallback.' });
  109 + companyService.create({ id: CO_COLLISION, name: 'P1 Acceptance Collision Co', description: 'Naming collision regression.' });
  110 + });
  111 +
  112 + afterAll(() => {
  113 + for (const id of [CO_QA, CO_UNKNOWN, CO_COLLISION]) {
  114 + try { fs.rmSync(path.join(DATA_DIR, id), { recursive: true, force: true }); } catch {}
  115 + }
  116 + try { fs.unlinkSync(TEST_DB_PATH); } catch {}
  117 + try { fs.unlinkSync(`${TEST_DB_PATH}-shm`); } catch {}
  118 + try { fs.unlinkSync(`${TEST_DB_PATH}-wal`); } catch {}
  119 + delete process.env.GRAPH_DB_PATH;
  120 + if (registrySnapshot !== undefined) fs.writeFileSync(REGISTRY_PATH, registrySnapshot, 'utf-8');
  121 + });
  122 +
  123 + // ─────────────────────────────────────────────────────────────────
  124 + // Criterion 1: hire() of a system_agents template role -> reference mode
  125 + // ─────────────────────────────────────────────────────────────────
  126 + it('criterion 1: hire(companyId, "qa-judge") uses reference mode (no agent.md, company-context.md, systemAgentRef, org_graph_nodes row)', () => {
  127 + const result = companyService.hire(CO_QA, 'qa-judge', {});
  128 + expect(result.status).toBe('hired_from_template');
  129 +
  130 + const agentDir = result.agentDir;
  131 + expect(fs.existsSync(path.join(agentDir, 'agent.md'))).toBe(false);
  132 +
  133 + const contextPath = path.join(agentDir, 'company-context.md');
  134 + expect(fs.existsSync(contextPath)).toBe(true);
  135 + const context = fs.readFileSync(contextPath, 'utf-8');
  136 + expect(context).toContain(CO_QA);
  137 + expect(context).toContain('P1 Acceptance QA Co');
  138 + expect(context).toContain('Verifies QA-judge lives here.');
  139 +
  140 + const config = JSON.parse(fs.readFileSync(path.join(agentDir, 'config.json'), 'utf-8'));
  141 + expect(config.systemAgentRef).toBe('qa-judge');
  142 +
  143 + const db = graphDb.getDb();
  144 + const node = db.prepare('SELECT * FROM org_graph_nodes WHERE company_id = ? AND role_name = ?').get(CO_QA, 'qa-judge');
  145 + expect(node).toBeTruthy();
  146 + expect(node.system_agent_id).toBe('qa-judge');
  147 + });
  148 +
  149 + // ─────────────────────────────────────────────────────────────────
  150 + // Criterion 2: final prompt = real shared agent.md content + company-context.md
  151 + // ─────────────────────────────────────────────────────────────────
  152 + it('criterion 2: buildFullPrompt() assembles the real shared system/templates/qa-judge/agent.md content plus the company-context.md section', () => {
  153 + const manager = new AgentManager({}, REPO_ROOT);
  154 + const agentName = `${CO_QA}:qa-judge`;
  155 + const { agent } = manager.getAgentConfig(agentName);
  156 +
  157 + const expectedSharedPath = path.resolve(REPO_ROOT, 'system/templates/qa-judge', 'agent.md');
  158 + expect(agent.prompt).toBe(expectedSharedPath);
  159 +
  160 + const realSharedContent = fs.readFileSync(expectedSharedPath, 'utf-8');
  161 + const fullPrompt = manager.buildFullPrompt(agentName, 'test task');
  162 +
  163 + // The full assembled prompt carries the exact real content of the shared template file.
  164 + expect(fullPrompt).toContain(realSharedContent);
  165 + // ... and the private company-context.md section (proves the two-part assembly from §4.3).
  166 + expect(fullPrompt).toContain('## 所属公司');
  167 + expect(fullPrompt).toContain(CO_QA);
  168 + expect(fullPrompt).toContain('P1 Acceptance QA Co');
  169 +
  170 + // Regression guard for the "改共享文件后无需重新 hire 即可生效" claim in criterion 2:
  171 + // prompt-builder must not have baked a stale copy into the private dir — there is no
  172 + // agent.md in the private dir to have gone stale in the first place.
  173 + const agentDir = path.join(DATA_DIR, CO_QA, 'agents/qa-judge');
  174 + expect(fs.existsSync(path.join(agentDir, 'agent.md'))).toBe(false);
  175 + });
  176 +
  177 + // ─────────────────────────────────────────────────────────────────
  178 + // Criterion 3: role absent from system_agents -> legacy full copy, no error
  179 + // ─────────────────────────────────────────────────────────────────
  180 + it('criterion 3: hiring a role not in system_agents falls back to legacy full copy (including agent.md) without throwing', () => {
  181 + // UNKNOWN_ROLE has no system_agents row (never seeded) AND no template directory at
  182 + // all, so hire() must return needs_training rather than throw. To exercise the
  183 + // "template exists on disk but has no system_agents row" branch specifically (the one
  184 + // §4.1/§4.2 describe as the legacy-fallback trigger), also create a throwaway template
  185 + // dir that deliberately is NOT registered in system_agents.
  186 + const looseTemplateRole = `tmp-p1-loose-template-${RUN_ID}`;
  187 + const looseTemplateDir = path.join(TEMPLATES_DIR, looseTemplateRole);
  188 + fs.mkdirSync(looseTemplateDir, { recursive: true });
  189 + fs.writeFileSync(path.join(looseTemplateDir, 'agent.md'), '# unregistered fixture agent\n', 'utf-8');
  190 + fs.writeFileSync(path.join(looseTemplateDir, 'config.json'), JSON.stringify({ type: 'skill', name: looseTemplateRole }), 'utf-8');
  191 +
  192 + try {
  193 + let result;
  194 + expect(() => { result = companyService.hire(CO_UNKNOWN, looseTemplateRole, {}); }).not.toThrow();
  195 + expect(result.status).toBe('hired_from_template');
  196 +
  197 + const agentDir = result.agentDir;
  198 + expect(fs.existsSync(path.join(agentDir, 'agent.md'))).toBe(true);
  199 + const content = fs.readFileSync(path.join(agentDir, 'agent.md'), 'utf-8');
  200 + expect(content).toContain('unregistered fixture agent');
  201 + expect(fs.existsSync(path.join(agentDir, 'company-context.md'))).toBe(false);
  202 +
  203 + const config = JSON.parse(fs.readFileSync(path.join(agentDir, 'config.json'), 'utf-8'));
  204 + expect(config.systemAgentRef).toBeUndefined();
  205 + } finally {
  206 + try { fs.rmSync(looseTemplateDir, { recursive: true, force: true }); } catch {}
  207 + }
  208 +
  209 + // And confirm hire() also degrades gracefully (no throw, needs_training) for a role that
  210 + // has neither a system_agents row nor a template directory at all.
  211 + let unknownResult;
  212 + expect(() => { unknownResult = companyService.hire(CO_UNKNOWN, UNKNOWN_ROLE, {}); }).not.toThrow();
  213 + expect(unknownResult.status).toBe('needs_training');
  214 + expect(unknownResult.needsTraining).toBe(true);
  215 + });
  216 +
  217 + // ─────────────────────────────────────────────────────────────────
  218 + // Criterion 6 (design doc numbering) — naming collision regression
  219 + // ─────────────────────────────────────────────────────────────────
  220 + it('criterion 6 [KEY REGRESSION]: hire("evolver-youtube-crawler") on a brand-new company falls back to legacy full copy, never redirecting to system/agents/', () => {
  221 + const result = companyService.hire(CO_COLLISION, COLLISION_ROLE, {});
  222 + expect(result.status).toBe('hired_from_template');
  223 +
  224 + const agentDir = result.agentDir;
  225 + const agentMdPath = path.join(agentDir, 'agent.md');
  226 + expect(fs.existsSync(agentMdPath)).toBe(true); // legacy path -> agent.md IS physically copied
  227 +
  228 + const copiedContent = fs.readFileSync(agentMdPath, 'utf-8');
  229 + const templateContent = fs.readFileSync(path.join(TEMPLATES_DIR, COLLISION_ROLE, 'agent.md'), 'utf-8');
  230 + const globalAgentContent = fs.readFileSync(path.join(REPO_ROOT, 'system/agents', COLLISION_ROLE, 'agent.md'), 'utf-8');
  231 +
  232 + // These two source files are confirmed to genuinely differ in this repo (27§7).
  233 + expect(templateContent).not.toBe(globalAgentContent);
  234 +
  235 + // The copied file must match system/templates/ (what _copyTemplate() actually reads),
  236 + // and must NOT be — or even coincidentally equal — the system/agents/ (global_agent) version.
  237 + // (companyContext gets appended in legacy mode, so compare via startsWith/contains rather
  238 + // than strict equality.)
  239 + expect(copiedContent.startsWith(templateContent)).toBe(true);
  240 + expect(copiedContent).not.toContain(globalAgentContent.split('\n')[0]); // global_agent's distinct H1 heading
  241 +
  242 + // Reference-mode artifacts must be absent — this id must NOT have taken the reference branch.
  243 + expect(fs.existsSync(path.join(agentDir, 'company-context.md'))).toBe(false);
  244 + const config = JSON.parse(fs.readFileSync(path.join(agentDir, 'config.json'), 'utf-8'));
  245 + expect(config.systemAgentRef).toBeUndefined();
  246 +
  247 + // graph-service.lookupSharedAgentMd itself must report "no reference" for this id,
  248 + // proving the source_kind='template' filter — not just hire()'s outer branching — is correct.
  249 + const graphService = require('../../services/graph-service');
  250 + expect(graphService.lookupSharedAgentMd(COLLISION_ROLE)).toBeNull();
  251 +
  252 + // Still gets an audit org_graph_nodes row even on the legacy path.
  253 + const db = graphDb.getDb();
  254 + const node = db.prepare('SELECT * FROM org_graph_nodes WHERE company_id = ? AND role_name = ?').get(CO_COLLISION, COLLISION_ROLE);
  255 + expect(node).toBeTruthy();
  256 + });
  257 +
  258 + // ─────────────────────────────────────────────────────────────────
  259 + // Criterion 5 (design doc numbering) — idempotency
  260 + // ─────────────────────────────────────────────────────────────────
  261 + it('criterion 5: hiring the same (companyId, role) twice short-circuits to already_exists and does not duplicate org_graph_nodes', () => {
  262 + const first = companyService.hire(CO_QA, 'qa-judge', {}); // already hired in criterion-1 test above
  263 + expect(first.status).toBe('already_exists');
  264 +
  265 + const second = companyService.hire(CO_QA, 'qa-judge', {});
  266 + expect(second.status).toBe('already_exists');
  267 +
  268 + const db = graphDb.getDb();
  269 + const count = db.prepare('SELECT COUNT(*) AS c FROM org_graph_nodes WHERE company_id = ? AND role_name = ?').get(CO_QA, 'qa-judge').c;
  270 + expect(count).toBe(1);
  271 + });
  272 +
  273 + // ─────────────────────────────────────────────────────────────────
  274 + // Criterion 4 (design doc numbering) — pre-P1 legacy company unaffected
  275 + // ─────────────────────────────────────────────────────────────────
  276 + it('criterion 4: a pre-P1 legacy company (real "idearun", never touched by this test) still resolves through the old private-agent.md path, not the new reference branch', () => {
  277 + // Read-only against real, already-hired production data — proves old instances are
  278 + // untouched by the new code path rather than merely "not tested".
  279 + const legacyAgentDir = path.join(DATA_DIR, 'idearun', 'agents', COLLISION_ROLE);
  280 + expect(fs.existsSync(path.join(legacyAgentDir, 'agent.md'))).toBe(true);
  281 + const legacyConfig = JSON.parse(fs.readFileSync(path.join(legacyAgentDir, 'config.json'), 'utf-8'));
  282 + expect(legacyConfig.systemAgentRef).toBeUndefined();
  283 +
  284 + const manager = new AgentManager({}, REPO_ROOT);
  285 + const agentName = `idearun:${COLLISION_ROLE}`;
  286 + const { agent } = manager.getAgentConfig(agentName);
  287 +
  288 + // Must resolve to the agent's own private agent.md, not any shared/legacy_path location.
  289 + expect(agent.prompt).toBe(path.join(legacyAgentDir, 'agent.md'));
  290 + expect(agent.companyContextPath).toBeFalsy();
  291 + expect(agent.workDir).toBe(legacyAgentDir);
  292 + });
  293 +});
... ...
server/tests/integration/graph-agent-p1-hire.test.js 0 → 100644
  1 +/**
  2 + * Integration Test — company-service.hire() P1 引用模式
  3 + *
  4 + * 覆盖 docs/todo/system-design/27-p1-virtual-reference.md §6 验收标准 1/3/5:
  5 + * 1. system_agents 里有 source_kind='template' 行的角色(qa-judge) → 引用模式:
  6 + * 私有目录没有 agent.md,有 company-context.md(含公司 ID),config.json 有
  7 + * systemAgentRef,org_graph_nodes 新增一行。
  8 + * 2. 不在 system_agents 里的角色 → 完全 legacy 行为(含 agent.md 被拷贝)。
  9 + * 3. 幂等性:同一 (companyId, role) 调用 hire() 两次,第二次 already_exists,
  10 + * org_graph_nodes 不重复。
  11 + *
  12 + * 用 GRAPH_DB_PATH 覆盖到临时 SQLite 文件(同 graph-service.test.js / graph-db.test.js
  13 + * 的模式),永不触碰真实 data/graph.sqlite;用临时公司 id,测试完清理 data/companies/
  14 + * 下对应目录,不污染真实数据。
  15 + */
  16 +import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  17 +import fs from 'fs';
  18 +import path from 'path';
  19 +
  20 +describe('company-service.hire() — P1 virtual reference mode', () => {
  21 + const TEST_DB_PATH = '/tmp/test-graph-agent-p1-hire.sqlite';
  22 + const REPO_ROOT = path.resolve(__dirname, '../../..');
  23 + const DATA_DIR = path.join(REPO_ROOT, 'data/companies');
  24 + const TEMPLATES_DIR = path.join(REPO_ROOT, 'system/templates');
  25 +
  26 + const TEST_COMPANY_ID = `tmp-p1-hire-test-co-${Date.now()}`;
  27 + const LEGACY_TEMPLATE_ROLE = `tmp-p1-legacy-role-${Date.now()}`;
  28 + const legacyTemplateDir = path.join(TEMPLATES_DIR, LEGACY_TEMPLATE_ROLE);
  29 +
  30 + let graphDb;
  31 + let CompanyService;
  32 + let companyService;
  33 +
  34 + beforeAll(() => {
  35 + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH);
  36 + process.env.GRAPH_DB_PATH = TEST_DB_PATH;
  37 + delete require.cache[require.resolve('../../services/graph-db')];
  38 + delete require.cache[require.resolve('../../services/graph-service')];
  39 + delete require.cache[require.resolve('../../services/company-service')];
  40 + graphDb = require('../../services/graph-db');
  41 + ({ CompanyService } = require('../../services/company-service'));
  42 + companyService = new CompanyService();
  43 +
  44 + // Seed a 'template' row for qa-judge pointing at the real template dir (already exists
  45 + // in the repo with a real agent.md) — this is exactly what npm run graph:seed produced
  46 + // in commit 8421f55, just re-created here against the isolated test DB.
  47 + const db = graphDb.getDb();
  48 + const now = new Date().toISOString();
  49 + db.prepare(`
  50 + INSERT INTO system_agents (id, name, scope, owner_company_id, source_kind, legacy_path, status, benchmark_score, created_at, updated_at)
  51 + VALUES (?, ?, 'public', NULL, 'template', ?, 'active', NULL, ?, ?)
  52 + `).run('qa-judge', 'qa-judge', 'system/templates/qa-judge', now, now);
  53 +
  54 + // Fixture template dir for the "role not in system_agents" legacy-fallback case.
  55 + // Deliberately NOT inserted into system_agents, so lookupSharedAgentMd() returns null
  56 + // and hire() must fall back to the full legacy copy (including agent.md).
  57 + fs.mkdirSync(legacyTemplateDir, { recursive: true });
  58 + fs.writeFileSync(path.join(legacyTemplateDir, 'agent.md'), '# legacy fixture agent\n', 'utf-8');
  59 + fs.writeFileSync(path.join(legacyTemplateDir, 'config.json'), JSON.stringify({ type: 'skill', name: LEGACY_TEMPLATE_ROLE }), 'utf-8');
  60 +
  61 + // Company fixture (CompanyService.hire() requires an existing company).
  62 + companyService.create({ id: TEST_COMPANY_ID, name: 'P1 Hire Test Co', description: 'test fixture' });
  63 + });
  64 +
  65 + afterAll(() => {
  66 + try { fs.rmSync(path.join(DATA_DIR, TEST_COMPANY_ID), { recursive: true, force: true }); } catch {}
  67 + try { fs.rmSync(legacyTemplateDir, { recursive: true, force: true }); } catch {}
  68 + try { fs.unlinkSync(TEST_DB_PATH); } catch {}
  69 + try { fs.unlinkSync(`${TEST_DB_PATH}-shm`); } catch {}
  70 + try { fs.unlinkSync(`${TEST_DB_PATH}-wal`); } catch {}
  71 + delete process.env.GRAPH_DB_PATH;
  72 + });
  73 +
  74 + it('reference mode: hiring a system_agents template role does not copy agent.md, writes company-context.md, sets systemAgentRef, records org_graph_nodes', () => {
  75 + const result = companyService.hire(TEST_COMPANY_ID, 'qa-judge', {});
  76 +
  77 + expect(result.status).toBe('hired_from_template');
  78 + const agentDir = result.agentDir;
  79 +
  80 + expect(fs.existsSync(path.join(agentDir, 'agent.md'))).toBe(false);
  81 +
  82 + const contextPath = path.join(agentDir, 'company-context.md');
  83 + expect(fs.existsSync(contextPath)).toBe(true);
  84 + const contextContent = fs.readFileSync(contextPath, 'utf-8');
  85 + expect(contextContent).toContain(TEST_COMPANY_ID);
  86 + expect(contextContent).toContain('## 所属公司');
  87 +
  88 + const config = JSON.parse(fs.readFileSync(path.join(agentDir, 'config.json'), 'utf-8'));
  89 + expect(config.systemAgentRef).toBe('qa-judge');
  90 +
  91 + // Non-shared files must still be provisioned privately (workDir constraint, §3.3 of the design doc).
  92 + expect(fs.existsSync(path.join(agentDir, 'soul.md'))).toBe(true);
  93 + expect(fs.existsSync(path.join(agentDir, 'identity.md'))).toBe(true);
  94 + expect(fs.existsSync(path.join(agentDir, 'memory/memory.md'))).toBe(true);
  95 +
  96 + const db = graphDb.getDb();
  97 + const node = db.prepare('SELECT * FROM org_graph_nodes WHERE company_id = ? AND role_name = ?').get(TEST_COMPANY_ID, 'qa-judge');
  98 + expect(node).toBeTruthy();
  99 + expect(node.system_agent_id).toBe('qa-judge');
  100 + });
  101 +
  102 + it('legacy fallback: hiring a role absent from system_agents copies agent.md and writes no company-context.md / systemAgentRef', () => {
  103 + const result = companyService.hire(TEST_COMPANY_ID, LEGACY_TEMPLATE_ROLE, {});
  104 +
  105 + expect(result.status).toBe('hired_from_template');
  106 + const agentDir = result.agentDir;
  107 +
  108 + expect(fs.existsSync(path.join(agentDir, 'agent.md'))).toBe(true);
  109 + const agentMdContent = fs.readFileSync(path.join(agentDir, 'agent.md'), 'utf-8');
  110 + expect(agentMdContent).toContain('legacy fixture agent');
  111 + expect(agentMdContent).toContain('## 所属公司'); // still appended in-place, legacy behavior
  112 +
  113 + expect(fs.existsSync(path.join(agentDir, 'company-context.md'))).toBe(false);
  114 +
  115 + const config = JSON.parse(fs.readFileSync(path.join(agentDir, 'config.json'), 'utf-8'));
  116 + expect(config.systemAgentRef).toBeUndefined();
  117 +
  118 + // Still gets an org_graph_nodes audit row even though it went through the legacy path.
  119 + const db = graphDb.getDb();
  120 + const node = db.prepare('SELECT * FROM org_graph_nodes WHERE company_id = ? AND role_name = ?').get(TEST_COMPANY_ID, LEGACY_TEMPLATE_ROLE);
  121 + expect(node).toBeTruthy();
  122 + });
  123 +
  124 + it('idempotency: hiring the same (companyId, role) twice returns already_exists the second time and does not duplicate org_graph_nodes', () => {
  125 + const role = 'qa-judge'; // already hired by the first test above
  126 +
  127 + const second = companyService.hire(TEST_COMPANY_ID, role, {});
  128 + expect(second.status).toBe('already_exists');
  129 +
  130 + const db = graphDb.getDb();
  131 + const count = db.prepare('SELECT COUNT(*) AS c FROM org_graph_nodes WHERE company_id = ? AND role_name = ?').get(TEST_COMPANY_ID, role).c;
  132 + expect(count).toBe(1);
  133 + });
  134 +});
... ...
server/tests/unit/agent-manager-p1.test.js 0 → 100644
  1 +/**
  2 + * Unit Tests — AgentManager.getAgentConfig() P1 虚拟引用寻址
  3 + *
  4 + * 覆盖 docs/todo/system-design/27-p1-virtual-reference.md §4.2 / §6-1,2,4:
  5 + * - config.json 带 systemAgentRef 且 system_agents 表命中 template 行 → prompt 指向共享
  6 + * agent.md,companyContextPath 指向私有 company-context.md
  7 + * - config.json 没有 systemAgentRef(legacy agent) → prompt 仍指向私有 agent.md,行为不变
  8 + *
  9 + * Uses GRAPH_DB_PATH env override (same pattern as graph-service.test.js) so the real
  10 + * data/graph.sqlite is never touched. Also creates a temporary company directory under
  11 + * data/companies/ that is removed in afterAll.
  12 + */
  13 +import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  14 +import fs from 'fs';
  15 +import path from 'path';
  16 +
  17 +describe('AgentManager.getAgentConfig() — P1 virtual reference addressing', () => {
  18 + const TEST_DB_PATH = '/tmp/test-agent-manager-p1-graph.sqlite';
  19 + const REPO_ROOT = path.resolve(__dirname, '../../..');
  20 + const TMP_COMPANY_ID = `tmp-p1-test-co-${Date.now()}`;
  21 + const AGENTS_ROOT = path.join(REPO_ROOT, 'data/companies', TMP_COMPANY_ID, 'agents');
  22 +
  23 + let graphDb;
  24 + let AgentManager;
  25 +
  26 + beforeAll(() => {
  27 + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH);
  28 + process.env.GRAPH_DB_PATH = TEST_DB_PATH;
  29 + delete require.cache[require.resolve('../../services/graph-db')];
  30 + delete require.cache[require.resolve('../../services/graph-service')];
  31 + delete require.cache[require.resolve('../../src/core/agent-manager')];
  32 + graphDb = require('../../services/graph-db');
  33 + AgentManager = require('../../src/core/agent-manager');
  34 +
  35 + // Seed a template row for "qa-judge-p1-test" pointing at a fixture-free legacy_path
  36 + // (the shared agent.md just needs to exist so lookupSharedAgentMd's result is a real file).
  37 + const db = graphDb.getDb();
  38 + const now = new Date().toISOString();
  39 + db.prepare(`
  40 + INSERT INTO system_agents (id, name, scope, owner_company_id, source_kind, legacy_path, status, benchmark_score, created_at, updated_at)
  41 + VALUES (?, ?, 'public', NULL, 'template', ?, 'active', NULL, ?, ?)
  42 + `).run('qa-judge', 'qa-judge', 'system/templates/qa-judge', now, now);
  43 +
  44 + fs.mkdirSync(AGENTS_ROOT, { recursive: true });
  45 + });
  46 +
  47 + afterAll(() => {
  48 + try { fs.rmSync(path.join(REPO_ROOT, 'data/companies', TMP_COMPANY_ID), { recursive: true, force: true }); } catch {}
  49 + try { fs.unlinkSync(TEST_DB_PATH); } catch {}
  50 + try { fs.unlinkSync(`${TEST_DB_PATH}-shm`); } catch {}
  51 + try { fs.unlinkSync(`${TEST_DB_PATH}-wal`); } catch {}
  52 + delete process.env.GRAPH_DB_PATH;
  53 + });
  54 +
  55 + function makeAgentDir(role, configJson) {
  56 + const dir = path.join(AGENTS_ROOT, role);
  57 + fs.mkdirSync(dir, { recursive: true });
  58 + if (configJson !== undefined) {
  59 + fs.writeFileSync(path.join(dir, 'config.json'), JSON.stringify(configJson), 'utf-8');
  60 + }
  61 + // Legacy agent.md always present in the private dir (P1 doesn't delete it if it exists
  62 + // for the reference-mode case — company-service.hire() simply never writes it there).
  63 + fs.writeFileSync(path.join(dir, 'agent.md'), '# legacy private agent.md\n', 'utf-8');
  64 + return dir;
  65 + }
  66 +
  67 + it('reference mode: systemAgentRef present + template row found -> prompt points at shared agent.md, companyContextPath set', () => {
  68 + const role = 'qa-judge-referenced';
  69 + const agentDir = makeAgentDir(role, { systemAgentRef: 'qa-judge' });
  70 +
  71 + const manager = new AgentManager({}, REPO_ROOT);
  72 + const { agent } = manager.getAgentConfig(`${TMP_COMPANY_ID}:${role}`);
  73 +
  74 + const expectedSharedPath = path.resolve(REPO_ROOT, 'system/templates/qa-judge', 'agent.md');
  75 + expect(agent.prompt).toBe(expectedSharedPath);
  76 + expect(agent.companyContextPath).toBe(path.join(agentDir, 'company-context.md'));
  77 + // Hard constraint: workDir must remain the private directory (CLI cwd for soul.md/identity.md/.claude/skills/).
  78 + expect(agent.workDir).toBe(agentDir);
  79 + });
  80 +
  81 + it('legacy mode: no systemAgentRef -> prompt points at private agent.md, companyContextPath falsy', () => {
  82 + const role = 'legacy-role';
  83 + const agentDir = makeAgentDir(role, { someOtherField: true });
  84 +
  85 + const manager = new AgentManager({}, REPO_ROOT);
  86 + const { agent } = manager.getAgentConfig(`${TMP_COMPANY_ID}:${role}`);
  87 +
  88 + expect(agent.prompt).toBe(path.join(agentDir, 'agent.md'));
  89 + expect(agent.companyContextPath).toBeFalsy();
  90 + expect(agent.workDir).toBe(agentDir);
  91 + });
  92 +
  93 + it('legacy mode: no config.json at all -> prompt points at private agent.md, companyContextPath falsy', () => {
  94 + const role = 'no-config-role';
  95 + const agentDir = makeAgentDir(role, undefined);
  96 +
  97 + const manager = new AgentManager({}, REPO_ROOT);
  98 + const { agent } = manager.getAgentConfig(`${TMP_COMPANY_ID}:${role}`);
  99 +
  100 + expect(agent.prompt).toBe(path.join(agentDir, 'agent.md'));
  101 + expect(agent.companyContextPath).toBeFalsy();
  102 + expect(agent.workDir).toBe(agentDir);
  103 + });
  104 +
  105 + it('defensive fallback: systemAgentRef present but no matching template row -> falls back to private agent.md', () => {
  106 + const role = 'dangling-ref-role';
  107 + const agentDir = makeAgentDir(role, { systemAgentRef: 'does-not-exist-in-system-agents' });
  108 +
  109 + const manager = new AgentManager({}, REPO_ROOT);
  110 + const { agent } = manager.getAgentConfig(`${TMP_COMPANY_ID}:${role}`);
  111 +
  112 + expect(agent.prompt).toBe(path.join(agentDir, 'agent.md'));
  113 + expect(agent.companyContextPath).toBeNull();
  114 + expect(agent.workDir).toBe(agentDir);
  115 + });
  116 +});
... ...
server/tests/unit/graph-service.test.js 0 → 100644
  1 +/**
  2 + * Unit Tests — graph-service.js (P1)
  3 + *
  4 + * Uses GRAPH_DB_PATH env override (same pattern as graph-db.test.js /
  5 + * graph-seed-service.test.js) so the real data/graph.sqlite is never touched.
  6 + */
  7 +import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
  8 +import fs from 'fs';
  9 +import path from 'path';
  10 +
  11 +describe('graph-service', () => {
  12 + let graphDb;
  13 + let graphService;
  14 + const TEST_DB_PATH = '/tmp/test-graph-service.sqlite';
  15 +
  16 + beforeAll(() => {
  17 + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH);
  18 + process.env.GRAPH_DB_PATH = TEST_DB_PATH;
  19 + delete require.cache[require.resolve('../../services/graph-db')];
  20 + delete require.cache[require.resolve('../../services/graph-service')];
  21 + graphDb = require('../../services/graph-db');
  22 + graphService = require('../../services/graph-service');
  23 + });
  24 +
  25 + afterAll(() => {
  26 + try { fs.unlinkSync(TEST_DB_PATH); } catch {}
  27 + try { fs.unlinkSync(`${TEST_DB_PATH}-shm`); } catch {}
  28 + try { fs.unlinkSync(`${TEST_DB_PATH}-wal`); } catch {}
  29 + delete process.env.GRAPH_DB_PATH;
  30 + });
  31 +
  32 + beforeEach(() => {
  33 + // Fresh tables between tests so assertions don't depend on ordering.
  34 + const db = graphDb.getDb();
  35 + db.exec('DELETE FROM org_graph_nodes; DELETE FROM system_agents;');
  36 + });
  37 +
  38 + function insertSystemAgent({ id, source_kind, legacy_path, scope = 'public', owner_company_id = null }) {
  39 + const db = graphDb.getDb();
  40 + const now = new Date().toISOString();
  41 + db.prepare(`
  42 + INSERT INTO system_agents (id, name, scope, owner_company_id, source_kind, legacy_path, status, benchmark_score, created_at, updated_at)
  43 + VALUES (?, ?, ?, ?, ?, ?, 'active', NULL, ?, ?)
  44 + `).run(id, id, scope, owner_company_id, source_kind, legacy_path, now, now);
  45 + }
  46 +
  47 + describe('lookupSharedAgentMd', () => {
  48 + it('returns the resolved agent.md path when a template row exists', () => {
  49 + insertSystemAgent({ id: 'qa-judge', source_kind: 'template', legacy_path: 'system/templates/qa-judge' });
  50 +
  51 + const result = graphService.lookupSharedAgentMd('qa-judge');
  52 +
  53 + expect(result).toBe(path.resolve(__dirname, '../../..', 'system/templates/qa-judge', 'agent.md'));
  54 + });
  55 +
  56 + it('returns null when the only matching row is source_kind=global_agent (naming-collision regression)', () => {
  57 + // Regression case: evolver-youtube-crawler exists under BOTH system/agents/ and
  58 + // system/templates/ but the template row got skipped by seedTemplates() because
  59 + // seedGlobalAgents() claimed the id first. Only a global_agent row exists here —
  60 + // lookupSharedAgentMd must NOT fall back to it, or idearun's already-hired copy
  61 + // (which was physically copied from system/templates/) would silently start
  62 + // reading a different file it was never hired with.
  63 + insertSystemAgent({
  64 + id: 'evolver-youtube-crawler',
  65 + source_kind: 'global_agent',
  66 + legacy_path: 'system/agents/evolver-youtube-crawler',
  67 + });
  68 +
  69 + const result = graphService.lookupSharedAgentMd('evolver-youtube-crawler');
  70 +
  71 + expect(result).toBeNull();
  72 + });
  73 +
  74 + it('returns null when the id does not exist at all', () => {
  75 + const result = graphService.lookupSharedAgentMd('does-not-exist');
  76 + expect(result).toBeNull();
  77 + });
  78 + });
  79 +
  80 + describe('upsertOrgGraphNode', () => {
  81 + it('creates an org_graph_nodes row when system_agents already has the id', () => {
  82 + insertSystemAgent({ id: 'qa-judge', source_kind: 'template', legacy_path: 'system/templates/qa-judge' });
  83 +
  84 + graphService.upsertOrgGraphNode('acme-co', 'qa-judge', 'qa-judge');
  85 +
  86 + const db = graphDb.getDb();
  87 + const node = db.prepare('SELECT * FROM org_graph_nodes WHERE company_id = ? AND role_name = ?').get('acme-co', 'qa-judge');
  88 + expect(node).toBeTruthy();
  89 + expect(node.system_agent_id).toBe('qa-judge');
  90 +
  91 + // Must not have touched/duplicated the existing system_agents row.
  92 + const agentCount = db.prepare('SELECT COUNT(*) AS c FROM system_agents WHERE id = ?').get('qa-judge').c;
  93 + expect(agentCount).toBe(1);
  94 + });
  95 +
  96 + it('inserts a fallback company_hired system_agents row when the id is missing', () => {
  97 + graphService.upsertOrgGraphNode('acme-co', 'custom-role', 'custom-role');
  98 +
  99 + const db = graphDb.getDb();
  100 + const agent = db.prepare('SELECT * FROM system_agents WHERE id = ?').get('custom-role');
  101 + expect(agent).toBeTruthy();
  102 + expect(agent.scope).toBe('company');
  103 + expect(agent.owner_company_id).toBe('acme-co');
  104 + expect(agent.source_kind).toBe('company_hired');
  105 + expect(agent.legacy_path).toBe('data/companies/acme-co/agents/custom-role');
  106 + expect(agent.status).toBe('active');
  107 + expect(agent.benchmark_score).toBeNull();
  108 +
  109 + const node = db.prepare('SELECT * FROM org_graph_nodes WHERE company_id = ? AND role_name = ?').get('acme-co', 'custom-role');
  110 + expect(node).toBeTruthy();
  111 + expect(node.system_agent_id).toBe('custom-role');
  112 + });
  113 +
  114 + it('is idempotent: calling twice for the same (companyId, roleName) does not duplicate org_graph_nodes rows', () => {
  115 + insertSystemAgent({ id: 'qa-judge', source_kind: 'template', legacy_path: 'system/templates/qa-judge' });
  116 +
  117 + graphService.upsertOrgGraphNode('acme-co', 'qa-judge', 'qa-judge');
  118 + graphService.upsertOrgGraphNode('acme-co', 'qa-judge', 'qa-judge');
  119 +
  120 + const db = graphDb.getDb();
  121 + const count = db.prepare('SELECT COUNT(*) AS c FROM org_graph_nodes WHERE company_id = ? AND role_name = ?').get('acme-co', 'qa-judge').c;
  122 + expect(count).toBe(1);
  123 + });
  124 + });
  125 +});
... ...