From ef33332dc5df30f355c880b6e59c01b4d993f1e6 Mon Sep 17 00:00:00 2001 From: wusumac <736139669@qq.com> Date: Tue, 15 Sep 2026 11:40:51 +0800 Subject: [PATCH] refactor(hub,cli,web): move team memory into the repo (runner side) Team memory now lives with the code, like CLAUDE.md:
/.hapi/team/ on the machine where the agent runs. Worktrees resolve to the main repo so every member shares one directory. The CLI creates charter.md + handoffs/ at session start (team env only), points the agent at it in the system prompt, and reports the path in session metadata; the web reads it through the session file API, so remote runners work too. Hub keeps only coordination data (teams.db): members/tasks/messages/status. Its memory-dir management and the /memory API are removed. --- cli/.hapi/team/charter.md | 14 ++ cli/src/agent/sessionFactory.ts | 5 + cli/src/modules/team/teamMemory.test.ts | 48 ++++++ cli/src/modules/team/teamMemory.ts | 80 +++++++++ cli/src/modules/team/teamPrompt.ts | 7 + hub/src/startHub.ts | 3 +- hub/src/teams/teamService.test.ts | 52 +----- hub/src/teams/teamService.ts | 159 +----------------- hub/src/web/routes/teams.test.ts | 91 +--------- hub/src/web/routes/teams.ts | 24 --- shared/src/schemas.ts | 2 + web/src/api/client.ts | 15 +- web/src/components/teams/TeamChatPage.tsx | 46 +++-- web/src/components/teams/TeamMemoryDialog.tsx | 41 ++--- web/src/components/teams/TeamSidePanel.tsx | 86 +++++++--- web/src/hooks/queries/useTeamMemory.ts | 28 --- web/src/lib/locales/en.ts | 1 + web/src/lib/locales/zh-CN.ts | 1 + web/src/lib/query-keys.ts | 2 - web/src/types/team.ts | 11 -- 20 files changed, 287 insertions(+), 429 deletions(-) create mode 100644 cli/.hapi/team/charter.md create mode 100644 cli/src/modules/team/teamMemory.test.ts create mode 100644 cli/src/modules/team/teamMemory.ts delete mode 100644 web/src/hooks/queries/useTeamMemory.ts diff --git a/cli/.hapi/team/charter.md b/cli/.hapi/team/charter.md new file mode 100644 index 00000000..cf342d2b --- /dev/null +++ b/cli/.hapi/team/charter.md @@ -0,0 +1,14 @@ +# Refactor auth — 团队规约 + +> 团队记忆与代码放在一起,成员用普通文件工具读写;提交与否由团队决定。 + +## 目标 +(lead 或人类补充这个团队要达成什么) + +## 协作规则 +- 广播消息不会主动推送:开工前用 team_read 拉取,完成后用 team_send 汇报。 +- 需要人类决策时用 team_send 的 to="human" 或 kind="decision"。 +- 交接产物写到 handoffs/ 目录,文件名用任务 id 或简短主题。 + +## 决策记录 +(重要取舍追加到这里,说明日期、背景、结论) diff --git a/cli/src/agent/sessionFactory.ts b/cli/src/agent/sessionFactory.ts index 8e566a05..34649e04 100644 --- a/cli/src/agent/sessionFactory.ts +++ b/cli/src/agent/sessionFactory.ts @@ -80,6 +80,8 @@ export function buildMachineMetadata(options?: { } } +import { resolveTeamMemoryDir } from '@/modules/team/teamMemory' + export function buildSessionMetadata(options: { flavor: string startedBy: SessionStartedBy @@ -108,6 +110,9 @@ export function buildSessionMetadata(options: { lifecycleState: 'running', lifecycleStateSince: now, flavor: options.flavor, + ...(process.env.HAPI_TEAM_ID?.trim() + ? { teamMemoryPath: resolveTeamMemoryDir() } + : {}), capabilities: { terminal: true }, diff --git a/cli/src/modules/team/teamMemory.test.ts b/cli/src/modules/team/teamMemory.test.ts new file mode 100644 index 00000000..0fdb10b6 --- /dev/null +++ b/cli/src/modules/team/teamMemory.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { ensureTeamMemory, resolveMainRepoRoot, resolveTeamMemoryDir } from './teamMemory' + +function makeRepos() { + const root = mkdtempSync(join(tmpdir(), 'hapi-team-memory-')) + const main = join(root, 'repo') + const worktree = join(root, 'wt') + mkdirSync(join(main, '.git', 'worktrees', 'feat'), { recursive: true }) + mkdirSync(worktree, { recursive: true }) + writeFileSync(join(worktree, '.git'), `gitdir: ${join(main, '.git', 'worktrees', 'feat')}\n`, 'utf8') + return { root, main, worktree } +} + +describe('teamMemory', () => { + it('resolves the repo root for a plain checkout and a linked worktree', () => { + const { root, main, worktree } = makeRepos() + try { + expect(resolveMainRepoRoot(main)).toBe(main) + expect(resolveMainRepoRoot(worktree)).toBe(main) + expect(resolveTeamMemoryDir(worktree)).toBe(join(main, '.hapi', 'team')) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('creates charter.md + handoffs only for team sessions', () => { + const { root, worktree } = makeRepos() + try { + expect(ensureTeamMemory({}, worktree)).toBeNull() + + const dir = ensureTeamMemory({ HAPI_TEAM_ID: 'team-1', HAPI_TEAM_NAME: 'Auth 重构' }, worktree) + expect(dir).toBe(join(root, 'repo', '.hapi', 'team')) + const charter = readFileSync(join(dir!, 'charter.md'), 'utf8') + expect(charter).toContain('Auth 重构') + + // Idempotent: an existing charter is not overwritten. + writeFileSync(join(dir!, 'charter.md'), 'custom', 'utf8') + ensureTeamMemory({ HAPI_TEAM_ID: 'team-1' }, worktree) + expect(readFileSync(join(dir!, 'charter.md'), 'utf8')).toBe('custom') + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) +}) diff --git a/cli/src/modules/team/teamMemory.ts b/cli/src/modules/team/teamMemory.ts new file mode 100644 index 00000000..3e4cb0c5 --- /dev/null +++ b/cli/src/modules/team/teamMemory.ts @@ -0,0 +1,80 @@ +import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { join, resolve } from 'node:path' + +/** + * Team memory lives with the code, like CLAUDE.md / project docs: + * `
/.hapi/team/` on the machine where the agent runs. + * + * Worktrees point at the main repository so every member's worktree shares one + * memory directory (a linked worktree's `.git` is a file: `gitdir:
/.git/worktrees/`). + */ +export function resolveMainRepoRoot(cwd: string = process.cwd()): string { + const dotGit = join(cwd, '.git') + let isDirectory = false + try { + isDirectory = statSync(dotGit).isDirectory() + } catch { + isDirectory = false + } + if (isDirectory) { + return cwd + } + try { + const content = readFileSync(dotGit, 'utf8') + const match = content.match(/^gitdir:\s*(.+)\s*$/m) + if (match?.[1]) { + //
/.git/worktrees/ ->
+ return resolve(match[1].trim(), '..', '..', '..') + } + } catch { + // not a worktree + } + return cwd +} + +export function resolveTeamMemoryDir(cwd: string = process.cwd()): string { + return join(resolveMainRepoRoot(cwd), '.hapi', 'team') +} + +/** + * Ensure the team memory dir + charter.md exist for a team member session. + * Returns the directory, or null when the session is not in a team. + */ +export function ensureTeamMemory(env: NodeJS.ProcessEnv = process.env, cwd: string = process.cwd()): string | null { + const teamId = env.HAPI_TEAM_ID?.trim() + if (!teamId) { + return null + } + const dir = resolveTeamMemoryDir(cwd) + try { + mkdirSync(join(dir, 'handoffs'), { recursive: true }) + const charter = join(dir, 'charter.md') + if (!existsSync(charter)) { + const name = env.HAPI_TEAM_NAME?.trim() || teamId.slice(0, 8) + writeFileSync(charter, charterTemplate(name), 'utf8') + } + } catch { + // Best effort: the agent can still create the files itself. + } + return dir +} + +function charterTemplate(teamName: string): string { + return [ + `# ${teamName} — 团队规约`, + '', + '> 团队记忆与代码放在一起,成员用普通文件工具读写;提交与否由团队决定。', + '', + '## 目标', + '(lead 或人类补充这个团队要达成什么)', + '', + '## 协作规则', + '- 广播消息不会主动推送:开工前用 team_read 拉取,完成后用 team_send 汇报。', + '- 需要人类决策时用 team_send 的 to="human" 或 kind="decision"。', + '- 交接产物写到 handoffs/ 目录,文件名用任务 id 或简短主题。', + '', + '## 决策记录', + '(重要取舍追加到这里,说明日期、背景、结论)', + '' + ].join('\n') +} diff --git a/cli/src/modules/team/teamPrompt.ts b/cli/src/modules/team/teamPrompt.ts index 0cae8cc6..f6ed9b4d 100644 --- a/cli/src/modules/team/teamPrompt.ts +++ b/cli/src/modules/team/teamPrompt.ts @@ -1,4 +1,5 @@ import { trimIdent } from '@/utils/trimIdent' +import { ensureTeamMemory } from './teamMemory' /** * System-prompt block injected into team member sessions. @@ -15,12 +16,18 @@ export function getTeamPromptBlock(toolPrefix: string, env: NodeJS.ProcessEnv = } const name = env.HAPI_TEAM_NAME?.trim() || teamId.slice(0, 8) const role = env.HAPI_TEAM_ROLE?.trim() || 'member' + // Memory lives with the code: /.hapi/team/ (worktrees share the main repo). + const memoryDir = ensureTeamMemory(env) + const memoryLine = memoryDir + ? `- Team memory lives with the code: ${memoryDir}/ (charter.md = team charter, handoffs/ = handoff notes). Read/write it with your normal file tools.` + : null return trimIdent(` You are a member of HAPI agent team "${name}" (your role: ${role}). - Start by calling ${toolPrefix}team_status to pick up your assignment, and ${toolPrefix}team_read to pull team messages (broadcasts are not pushed to you). - Report progress, completion, and blockers with ${toolPrefix}team_send (kind=status or task-update). Batch updates; do not chat back and forth. - Your normal replies to the human are synced into the team group chat automatically - do not use team_send just to answer the human. Use ${toolPrefix}team_send with to="human" (or kind="decision") only when you genuinely need a human decision; it notifies them out-of-band. - Only use ${toolPrefix}spawn_peer when the human or the lead explicitly asks you to. + ${memoryLine ?? ''} `) } diff --git a/hub/src/startHub.ts b/hub/src/startHub.ts index d5bc9ddc..190124b3 100644 --- a/hub/src/startHub.ts +++ b/hub/src/startHub.ts @@ -289,8 +289,7 @@ export async function startHub(options: StartHubOptions = {}): Promise syncEngine?.publishEvent(event), - teamRuntime, - { memoryRoot: join(config.dataDir, 'teams') } + teamRuntime ) : null if (teamService) { diff --git a/hub/src/teams/teamService.test.ts b/hub/src/teams/teamService.test.ts index 8d3d4361..c3ca3c2f 100644 --- a/hub/src/teams/teamService.test.ts +++ b/hub/src/teams/teamService.test.ts @@ -1,8 +1,4 @@ import { describe, expect, it } from 'bun:test' -import { mkdtempSync, rmSync } from 'node:fs' -import { writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' import type { SyncEvent } from '@hapi/protocol/types' import { TeamService, TeamServiceError, type TeamRuntime, type TeamSessionView, type TeamSpawnMemberInput } from './teamService' @@ -408,49 +404,6 @@ describe('TeamService spawning', () => { }) }) -describe('TeamService memory', () => { - it('materializes charter.md + handoffs and lists/reads files', async () => { - const dir = mkdtempSync(join(tmpdir(), 'hapi-team-memory-')) - const service = new TeamService(new TeamStore(':memory:'), () => {}, null, { memoryRoot: dir }) - try { - const team = service.createTeam('alpha', { name: 'Refactor auth' }) - // createTeam materializes the dir fire-and-forget. - let files = await service.listMemoryFiles('alpha', team.id) - for (let attempt = 0; attempt < 50 && !files.some((file) => file.path === 'charter.md'); attempt++) { - await new Promise((resolve) => setTimeout(resolve, 10)) - files = await service.listMemoryFiles('alpha', team.id) - } - expect(files.map((file) => file.path)).toContain('charter.md') - - const charter = await service.readMemoryFile('alpha', team.id, 'charter.md') - expect(charter.content).toContain('Refactor auth') - expect(charter.content).toContain('团队规约') - - await writeFile(join(dir, team.id, 'handoffs', 'T1.md'), 'done') - const after = await service.listMemoryFiles('alpha', team.id) - expect(after.some((file) => file.path === 'handoffs/T1.md')).toBe(true) - } finally { - service.close() - rmSync(dir, { recursive: true, force: true }) - } - }) - - it('rejects traversal paths and unknown files', async () => { - const dir = mkdtempSync(join(tmpdir(), 'hapi-team-memory-')) - const service = new TeamService(new TeamStore(':memory:'), () => {}, null, { memoryRoot: dir }) - try { - const team = service.createTeam('alpha', { name: 'Refactor auth' }) - await expect(service.readMemoryFile('alpha', team.id, '../../etc/passwd')).rejects.toThrow('Invalid path') - await expect(service.readMemoryFile('alpha', team.id, '/etc/passwd')).rejects.toThrow('Invalid path') - await expect(service.readMemoryFile('alpha', team.id, 'missing.md')).rejects.toThrow('File not found') - await expect(service.listMemoryFiles('alpha', 'unknown-team')).rejects.toThrow('Team not found') - } finally { - service.close() - rmSync(dir, { recursive: true, force: true }) - } - }) -}) - describe('TeamService web task management', () => { function setup() { const { runtime, sessions, delivered } = createRuntime() @@ -662,9 +615,8 @@ describe('TeamService human ping bridging', () => { describe('TeamService lead brief', () => { it('delivers a lead brief when the team is created with a lead session', async () => { - const dir = mkdtempSync(join(tmpdir(), 'hapi-team-lead-brief-')) const { runtime, sessions, delivered } = createRuntime() - const service = new TeamService(new TeamStore(':memory:'), () => {}, runtime, { memoryRoot: dir }) + const service = new TeamService(new TeamStore(':memory:'), () => {}, runtime) addCallerSession(sessions) try { service.createTeam('alpha', { name: 'Refactor auth', leadSessionId: 'sess-lead' }) @@ -672,10 +624,8 @@ describe('TeamService lead brief', () => { expect(delivered).toHaveLength(1) expect(delivered[0]?.sessionId).toBe('sess-lead') expect(delivered[0]?.text).toContain('Lead') - expect(delivered[0]?.text).toContain('团队记忆目录') } finally { service.close() - rmSync(dir, { recursive: true, force: true }) } }) }) diff --git a/hub/src/teams/teamService.ts b/hub/src/teams/teamService.ts index 53f62d7b..b6b5c1a2 100644 --- a/hub/src/teams/teamService.ts +++ b/hub/src/teams/teamService.ts @@ -1,5 +1,3 @@ -import { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises' -import { join, resolve, sep } from 'node:path' import type { AgentFlavor, SyncEvent } from '@hapi/protocol/types' import { @@ -68,18 +66,6 @@ export class TeamServiceError extends Error { } } -export interface TeamMemoryFile { - path: string - size: number - updatedAt: number -} - -export interface TeamMemoryFileContent { - path: string - content: string - updatedAt: number -} - export interface TeamStatus { team: TeamRecord me: TeamMemberRecord @@ -114,7 +100,6 @@ export class TeamService { private readonly store: TeamStore private readonly publish: (event: SyncEvent) => void private readonly runtime: TeamRuntime | null - private readonly memoryRoot: string | null private readonly messageLog = new Map() /** Sessions already announced as down, keyed `${teamId}:${sessionId}`. */ private readonly downNotified = new Set() @@ -128,13 +113,11 @@ export class TeamService { constructor( store: TeamStore, publish: (event: SyncEvent) => void = () => {}, - runtime: TeamRuntime | null = null, - options: { memoryRoot?: string } = {} + runtime: TeamRuntime | null = null ) { this.store = store this.publish = publish this.runtime = runtime - this.memoryRoot = options.memoryRoot ?? null } // ------------------------------------------------------------ team basics @@ -173,8 +156,6 @@ export class TeamService { this.store.addMember(team.id, input.leadSessionId, 'lead') } this.publishUpdate(team) - // Fire-and-forget: materialize the team memory dir (charter.md + handoffs/). - void this.ensureTeamMemory(team).catch(() => {}) // Tell the lead what it is - a lead session spawned through the normal // spawn path has no HAPI_TEAM_* env, so the brief is its team context. if (input.leadSessionId) { @@ -737,7 +718,7 @@ export class TeamService { fromKind: 'hub', fromSessionId: null, fromRole: 'hub', - text: buildLeadBrief(team, this.teamMemoryDir(team.id)) + text: buildLeadBrief(team) }) await runtime.deliverPeerMessage({ sessionId: leadSessionId, text }) } catch { @@ -777,7 +758,7 @@ export class TeamService { fromKind: team.leadSessionId ? 'session' : 'hub', fromSessionId: team.leadSessionId, fromRole: 'lead', - text: buildAssignmentBrief(team, role, taskBrief, taskId, this.teamMemoryDir(team.id)) + text: buildAssignmentBrief(team, role, taskBrief, taskId) }) await runtime.deliverPeerMessage({ sessionId: targetSessionId, text }) } catch { @@ -785,97 +766,6 @@ export class TeamService { } } - // ----------------------------------------------------------------- memory - - /** Absolute path of a team's memory dir, or null when memory is disabled. */ - teamMemoryDir(teamId: string): string | null { - return this.memoryRoot ? join(this.memoryRoot, teamId) : null - } - - private async ensureTeamMemory(team: TeamRecord): Promise { - const dir = this.teamMemoryDir(team.id) - if (!dir) return - await mkdir(join(dir, 'handoffs'), { recursive: true }) - const charter = join(dir, 'charter.md') - try { - await stat(charter) - } catch { - await writeFile(charter, charterTemplate(team), 'utf8') - } - } - - async listMemoryFiles(namespace: string, teamId: string): Promise { - const team = this.store.getTeam(teamId, namespace) - if (!team) { - throw new TeamServiceError('not_found', 'Team not found') - } - const dir = this.teamMemoryDir(team.id) - if (!dir) return [] - - const files: TeamMemoryFile[] = [] - const walk = async (current: string, prefix: string, depth: number): Promise => { - if (depth > 3) return - let entries - try { - entries = await readdir(current, { withFileTypes: true }) - } catch { - return - } - for (const entry of entries) { - if (entry.name.startsWith('.')) continue - const relative = prefix ? `${prefix}/${entry.name}` : entry.name - if (entry.isDirectory()) { - await walk(join(current, entry.name), relative, depth + 1) - continue - } - if (!entry.isFile()) continue - try { - const info = await stat(join(current, entry.name)) - files.push({ path: relative, size: info.size, updatedAt: info.mtimeMs }) - } catch { - } - } - } - await walk(dir, '', 1) - return files.sort((a, b) => a.path.localeCompare(b.path)) - } - - async readMemoryFile(namespace: string, teamId: string, relativePath: string): Promise { - const team = this.store.getTeam(teamId, namespace) - if (!team) { - throw new TeamServiceError('not_found', 'Team not found') - } - const dir = this.teamMemoryDir(team.id) - if (!dir) { - throw new TeamServiceError('not_found', 'File not found') - } - const normalized = sanitizeRelativePath(relativePath) - const root = resolve(dir) - const absolute = resolve(root, normalized) - if (absolute !== root && !absolute.startsWith(root + sep)) { - throw new TeamServiceError('invalid', 'Invalid path') - } - let info - try { - info = await stat(absolute) - } catch { - throw new TeamServiceError('not_found', 'File not found') - } - if (!info.isFile()) { - throw new TeamServiceError('not_found', 'File not found') - } - if (info.size > MAX_MEMORY_FILE_BYTES) { - throw new TeamServiceError('invalid', 'File is too large to preview') - } - let content: string - try { - content = await readFile(absolute, 'utf8') - } catch { - throw new TeamServiceError('invalid', 'File is not readable as text') - } - return { path: normalized, content, updatedAt: info.mtimeMs } - } - /** * A team member's session ended (CLI exited / archived). Announce it in the * team log and wake the lead so work can be reassigned. When the lead @@ -1080,15 +970,14 @@ function taskTitle(brief: string): string { return title.length > 120 ? `${title.slice(0, 117)}...` : title } -function buildLeadBrief(team: TeamRecord, memoryDir: string | null): string { +function buildLeadBrief(team: TeamRecord): string { return [ `你是 HAPI 团队「${team.name}」的 Lead。`, '', '职责:拆解任务、派生成员、汇总进展,必要时把决策升级给人类。', '可用工具:team_status(成员/任务/预算)、team_read(拉取团队消息,广播不会主动推送)、team_send(汇报/分派/通知人类)、spawn_peer(派生成员,需用户批准)。', '需要人类决策时用 team_send 的 to="human" 或 kind="decision";人类也会在群聊里发言、加成员或调整任务。', - '你在自己会话里的正常回复会自动同步到团队群聊(人类可见),不需要用 team_send 转述。', - ...(memoryDir ? ['', `团队记忆目录(hub 主机):${memoryDir}/(charter.md 是团队规约,交接产物写到 handoffs/)`] : []) + '你在自己会话里的正常回复会自动同步到团队群聊(人类可见),不需要用 team_send 转述。' ].join('\n') } @@ -1100,15 +989,13 @@ function buildAssignmentBrief( team: TeamRecord, role: string, taskBrief: string, - taskId: string | null, - memoryDir: string | null + taskId: string | null ): string { return [ `你已被加入 HAPI 团队「${team.name}」,角色:${role}。`, '', `你的任务:${taskBrief}`, ...(taskId ? [`任务 id:${taskId}`] : []), - ...(memoryDir ? ['', `团队记忆目录(hub 主机):${memoryDir}/(charter.md 是团队规约,交接产物写到 handoffs/)`] : []), '', '团队规范:', '- 开工前可调用 team_read 拉取团队消息(广播不会主动推送)。', @@ -1125,40 +1012,6 @@ function defaultWorktreeName(team: TeamRecord, role: string): string { return teamSlug ? `${teamSlug}-${roleSlug}` : roleSlug } -const MAX_MEMORY_FILE_BYTES = 256 * 1024 - -function sanitizeRelativePath(value: string): string { - const normalized = value.replace(/\\/g, '/').trim() - if (!normalized || normalized.includes('\0')) { - throw new TeamServiceError('invalid', 'Invalid path') - } - const segments = normalized.split('/') - if (normalized.startsWith('/') || segments.some((segment) => segment === '' || segment === '..')) { - throw new TeamServiceError('invalid', 'Invalid path') - } - return normalized -} - -function charterTemplate(team: TeamRecord): string { - return [ - `# ${team.name} — 团队规约`, - '', - '> 本文件由 Hub 自动生成,团队成员与人类都可编辑。', - '', - '## 目标', - '(lead 或人类补充这个团队要达成什么)', - '', - '## 协作规则', - '- 广播消息不会主动推送:开工前用 team_read 拉取,完成后用 team_send 汇报。', - '- 需要人类决策时用 team_send 的 to="human" 或 kind="decision"。', - '- 交接产物写到 handoffs/ 目录,文件名用任务 id 或简短主题。', - '', - '## 决策记录', - '(重要取舍追加到这里,说明日期、背景、结论)', - '' - ].join('\n') -} - function slug(value: string): string { return value .toLowerCase() diff --git a/hub/src/web/routes/teams.test.ts b/hub/src/web/routes/teams.test.ts index e530bb16..7cb9818b 100644 --- a/hub/src/web/routes/teams.test.ts +++ b/hub/src/web/routes/teams.test.ts @@ -11,7 +11,7 @@ import { TeamStore } from '../../teams/teamStore' import type { WebAppEnv } from '../middleware/auth' import { createTeamsRoutes } from './teams' -function createApp(getNamespace: () => string = () => 'alpha', memoryRoot?: string) { +function createApp(getNamespace: () => string = () => 'alpha') { const events: SyncEvent[] = [] const sessions = new Map() sessions.set('sess-lead', { @@ -45,7 +45,7 @@ function createApp(getNamespace: () => string = () => 'alpha', memoryRoot?: stri }, sleep: async () => {} } - const service = new TeamService(new TeamStore(':memory:'), (event) => events.push(event), runtime, memoryRoot ? { memoryRoot } : {}) + const service = new TeamService(new TeamStore(':memory:'), (event) => events.push(event), runtime) const app = new Hono() app.use('*', async (c, next) => { c.set('namespace', getNamespace()) @@ -129,93 +129,6 @@ describe('Agent Team member routes', () => { expect(leaderOnly.status).toBe(404) }) - it('lists and reads team memory files over HTTP', async () => { - const dir = mkdtempSync(join(tmpdir(), 'hapi-team-memory-routes-')) - try { - const { app } = createApp(() => 'alpha', dir) - const teamId = await createTeam(app) - await mkdir(join(dir, teamId, 'handoffs'), { recursive: true }) - await writeFile(join(dir, teamId, 'handoffs', 'note.md'), '# note') - // ensureTeamMemory runs fire-and-forget in createTeam; poll briefly. - let listBody: { files: Array<{ path: string }> } = { files: [] } - for (let attempt = 0; attempt < 50; attempt++) { - const list = await app.request(`/api/teams/${teamId}/memory`) - listBody = await list.json() as { files: Array<{ path: string }> } - if (listBody.files.some((file) => file.path === 'handoffs/note.md')) break - await new Promise((resolve) => setTimeout(resolve, 10)) - } - expect(listBody.files.map((file) => file.path)).toEqual(['charter.md', 'handoffs/note.md']) - - const file = await app.request(`/api/teams/${teamId}/memory/file?path=handoffs/note.md`) - expect(file.status).toBe(200) - expect((await file.json() as { content: string }).content).toBe('# note') - - const traversal = await app.request(`/api/teams/${teamId}/memory/file?path=../../etc/passwd`) - expect(traversal.status).toBe(400) - const missing = await app.request(`/api/teams/${teamId}/memory/file?path=nope.md`) - expect(missing.status).toBe(404) - } finally { - rmSync(dir, { recursive: true, force: true }) - } - }) - - it('creates tasks, updates them as the human, and manages the team', async () => { - const { app, delivered } = createApp() - const teamId = await createTeam(app) - const spawned = await app.request(`/api/teams/${teamId}/spawn`, { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ fromSessionId: 'sess-lead', role: 'builder' }) - }) - expect(spawned.status).toBe(201) - delivered.length = 0 - - const created = await app.request(`/api/teams/${teamId}/tasks`, { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ title: '写迁移脚本', assigneeSessionId: 'sess-builder' }) - }) - expect(created.status).toBe(201) - const task = (await created.json() as { task: { id: string } }).task - expect(delivered).toHaveLength(1) - - const updated = await app.request(`/api/teams/${teamId}/tasks/${task.id}`, { - method: 'PATCH', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ status: 'doing', assigneeSessionId: 'sess-builder' }) - }) - expect(updated.status).toBe(200) - expect((await updated.json() as { task: { status: string } }).task.status).toBe('doing') - - const invalid = await app.request(`/api/teams/${teamId}/tasks/${task.id}`, { - method: 'PATCH', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({}) - }) - expect(invalid.status).toBe(400) - - const led = await app.request(`/api/teams/${teamId}`, { - method: 'PATCH', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ leadSessionId: 'sess-lead' }) - }) - expect(led.status).toBe(200) - expect((await led.json() as { team: { leadSessionId: string } }).team.leadSessionId).toBe('sess-lead') - - const renamed = await app.request(`/api/teams/${teamId}`, { - method: 'PATCH', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ name: 'Auth 重构 v2' }) - }) - expect(renamed.status).toBe(200) - expect((await renamed.json() as { team: { name: string } }).team.name).toBe('Auth 重构 v2') - - const removed = await app.request(`/api/teams/${teamId}`, { method: 'DELETE' }) - expect(removed.status).toBe(200) - const missing = await app.request(`/api/teams/${teamId}`) - expect(missing.status).toBe(404) - }) - it('adopts an existing session as a team member', async () => { const { app, delivered } = createApp() const teamId = await createTeam(app) diff --git a/hub/src/web/routes/teams.ts b/hub/src/web/routes/teams.ts index 53e0f692..dec7a99d 100644 --- a/hub/src/web/routes/teams.ts +++ b/hub/src/web/routes/teams.ts @@ -224,30 +224,6 @@ export function createTeamsRoutes(teams: TeamService): Hono { } }) - app.get('/teams/:id/memory', async (c) => { - c.header('Cache-Control', 'no-store') - try { - const files = await teams.listMemoryFiles(c.get('namespace'), c.req.param('id')) - return c.json({ files }) - } catch (error) { - return teamErrorResponse(c, error) - } - }) - - app.get('/teams/:id/memory/file', async (c) => { - c.header('Cache-Control', 'no-store') - const path = c.req.query('path') - if (!path) { - return c.json({ error: 'path is required' }, 400) - } - try { - const file = await teams.readMemoryFile(c.get('namespace'), c.req.param('id'), path) - return c.json(file) - } catch (error) { - return teamErrorResponse(c, error) - } - }) - app.post('/teams/:id/human-messages', async (c) => { const json = await c.req.json().catch(() => null) const parsed = TeamHumanMessageRequestSchema.safeParse(json) diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index 958d94aa..ac3e1808 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -106,6 +106,8 @@ export const MetadataSchema = z.object({ tools: z.array(z.string()).optional(), slashCommands: z.array(z.string()).optional(), homeDir: z.string().optional(), + /** Absolute path of the team memory dir (repo-local, team sessions only). */ + teamMemoryPath: z.string().optional(), happyHomeDir: z.string().optional(), happyLibDir: z.string().optional(), happyToolsDir: z.string().optional(), diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 58775cb2..f5032b5d 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -43,7 +43,7 @@ import type { SessionShareCreateResponse, SessionShareExchangeResponse } from '@/types/api' -import type { TeamDetail, TeamMemoryFile, TeamMemoryFileContent, TeamMessage, TeamSummary, TeamTask, TeamWithMembers } from '@/types/team' +import type { TeamDetail, TeamMessage, TeamSummary, TeamTask, TeamWithMembers } from '@/types/team' import type { AgentAvailabilityResponse, AgyModelsResponse, @@ -437,19 +437,6 @@ export class ApiClient { ) } - async getTeamMemory(teamId: string): Promise<{ files: TeamMemoryFile[] }> { - return await this.request<{ files: TeamMemoryFile[] }>( - `/api/teams/${encodeURIComponent(teamId)}/memory` - ) - } - - async getTeamMemoryFile(teamId: string, path: string): Promise { - const params = new URLSearchParams({ path }) - return await this.request( - `/api/teams/${encodeURIComponent(teamId)}/memory/file?${params.toString()}` - ) - } - async addTeamMember( teamId: string, body: { sessionId: string; role: string; task?: string } diff --git a/web/src/components/teams/TeamChatPage.tsx b/web/src/components/teams/TeamChatPage.tsx index 36777797..807afb6d 100644 --- a/web/src/components/teams/TeamChatPage.tsx +++ b/web/src/components/teams/TeamChatPage.tsx @@ -7,7 +7,8 @@ import { useToast } from '@/lib/toast-context' import { queryKeys } from '@/lib/query-keys' import { useTeam } from '@/hooks/queries/useTeam' import { useTeamMessages } from '@/hooks/queries/useTeamMessages' -import { useTeamMemory } from '@/hooks/queries/useTeamMemory' +import { useSession } from '@/hooks/queries/useSession' +import { useSessionDirectory } from '@/hooks/queries/useSessionDirectory' import type { TeamMessage } from '@/types/team' import { TeamTimeline } from './TeamTimeline' import { TeamSidePanel } from './TeamSidePanel' @@ -38,7 +39,6 @@ export function TeamChatPage() { const { detail, isLoading, error } = useTeam(api, teamId) const { messages, error: messagesError } = useTeamMessages(api, teamId) - const { files: memoryFiles } = useTeamMemory(api, teamId) const [filter, setFilter] = useState('all') const [taskId, setTaskId] = useState('') @@ -46,7 +46,7 @@ export function TeamChatPage() { const [to, setTo] = useState('all') const [sending, setSending] = useState(false) const [panelOpen, setPanelOpen] = useState(() => isWideViewport()) - const [memoryPath, setMemoryPath] = useState(null) + const [memoryFilePath, setMemoryFilePath] = useState(null) const [taskDialogId, setTaskDialogId] = useState(null) const [settingsOpen, setSettingsOpen] = useState(false) @@ -54,6 +54,19 @@ export function TeamChatPage() { const tasks = detail?.tasks ?? [] const leadSessionId = detail?.team.leadSessionId ?? null + // Team memory lives in the repo (lead's machine): read it through the + // session file API so remote runners work too. + const { session: leadSession } = useSession(api, leadSessionId) + const memoryRoot = leadSession?.metadata?.teamMemoryPath ?? null + const [memoryDir, setMemoryDir] = useState('') + const memoryAbsoluteDir = memoryRoot ? (memoryDir ? `${memoryRoot}/${memoryDir}` : memoryRoot) : '' + const { entries: memoryEntries, isLoading: memoryLoading } = useSessionDirectory( + api, + leadSessionId, + memoryAbsoluteDir, + { enabled: Boolean(leadSessionId && memoryRoot) } + ) + const visibleMessages = useMemo(() => { if (filter === 'key') { return messages.filter((message) => isKeyMessage(message, leadSessionId)) @@ -132,13 +145,24 @@ export function TeamChatPage() { const panel = ( setMemoryDir((current) => (current ? `${current}/${name}` : name)), + onGoBack: () => setMemoryDir((current) => current.split('/').slice(0, -1).join('/')), + onOpenFile: (name) => { + if (memoryRoot) { + setMemoryFilePath(`${memoryAbsoluteDir}/${name}`) + } + } + }} activeTaskId={filter === 'task' ? taskId : null} onOpenSession={(sessionId) => navigate({ to: '/sessions/$sessionId', params: { sessionId } })} onSelectTask={(selectedTaskId) => setTaskDialogId(selectedTaskId)} onCreateTask={(input) => createTask.mutate(input)} creatingTask={createTask.isPending} - onOpenMemoryFile={(path) => setMemoryPath(path)} onClose={() => setPanelOpen(false)} /> ) @@ -334,11 +358,13 @@ export function TeamChatPage() { ) : null} - setMemoryPath(null)} - /> + {leadSessionId ? ( + setMemoryFilePath(null)} + /> + ) : null} void }) { @@ -22,47 +17,45 @@ export function TeamMemoryDialog(props: { const { t } = useTranslation() const query = useQuery({ - queryKey: queryKeys.teamMemoryFile(props.teamId, props.path ?? ''), + queryKey: queryKeys.sessionFile(props.leadSessionId, props.path ?? ''), queryFn: async () => { if (!api || !props.path) throw new Error('API unavailable') - return await api.getTeamMemoryFile(props.teamId, props.path) + return await api.readSessionFile(props.leadSessionId, props.path) }, enabled: Boolean(api && props.path), - staleTime: 10_000, + staleTime: 5_000, retry: false, }) - const isMarkdown = props.path ? MARKDOWN_EXTENSIONS.some((extension) => props.path!.toLowerCase().endsWith(extension)) : false + const isMarkdown = props.path + ? MARKDOWN_EXTENSIONS.some((extension) => props.path!.toLowerCase().endsWith(extension)) + : false + const content = query.data?.success ? query.data.content ?? '' : '' return (
{query.isLoading ? (
{t('team.memory.loading')}
- ) : query.error ? ( + ) : query.error || (query.data && !query.data.success) ? (
- {query.error instanceof Error ? query.error.message : t('team.memory.failed')} + {query.data?.error ?? (query.error instanceof Error ? query.error.message : t('team.memory.failed'))}
- ) : query.data ? ( + ) : ( <> -
- - {new Date(query.data.updatedAt).toLocaleString()} - - {formatSize(new Blob([query.data.content]).size)} -
+
{props.path}
{isMarkdown ? ( - + ) : ( -
{query.data.content}
+
{content}
)} - ) : null} + )}
) diff --git a/web/src/components/teams/TeamSidePanel.tsx b/web/src/components/teams/TeamSidePanel.tsx index 45c40a4f..39c11d07 100644 --- a/web/src/components/teams/TeamSidePanel.tsx +++ b/web/src/components/teams/TeamSidePanel.tsx @@ -1,5 +1,6 @@ import { useState } from 'react' -import type { TeamDetail, TeamMemoryFile, TeamTask } from '@/types/team' +import type { DirectoryEntry } from '@/types/api' +import type { TeamDetail, TeamTask } from '@/types/team' import { useTranslation } from '@/lib/use-translation' import { memberStatusLabel, statusDotClass } from './teamStatus' @@ -58,14 +59,22 @@ function TaskColumn(props: { */ export function TeamSidePanel(props: { detail: TeamDetail | null - memoryFiles: TeamMemoryFile[] + /** Team memory (repo-local, read through the lead session's file API). */ + memory: { + root: string | null + relativeDir: string + entries: DirectoryEntry[] + isLoading: boolean + onEnterDir: (name: string) => void + onGoBack: () => void + onOpenFile: (name: string) => void + } activeTaskId: string | null onOpenSession: (sessionId: string) => void /** Opens the task editor dialog (status/assignee + timeline). */ onSelectTask: (taskId: string) => void onCreateTask: (input: { title: string; assigneeSessionId: string | null }) => void creatingTask: boolean - onOpenMemoryFile: (path: string) => void onClose?: () => void }) { const { t } = useTranslation() @@ -183,24 +192,59 @@ export function TeamSidePanel(props: { {t('team.memory.title')}
- {props.memoryFiles.length === 0 ? ( - {t('team.memory.empty')} - ) : null} - {props.memoryFiles.map((file) => ( - - ))} + {!props.memory.root ? ( + + {t('team.memory.repoHint')} + + ) : ( + <> +
+ {props.memory.relativeDir ? ( + + ) : null} + + .hapi/team{props.memory.relativeDir ? `/${props.memory.relativeDir}` : ''} + +
+ {props.memory.isLoading ? ( + {t('team.memory.loading')} + ) : props.memory.entries.length === 0 ? ( + {t('team.memory.empty')} + ) : null} + {props.memory.entries.map((entry) => ( + + ))} + + )}
diff --git a/web/src/hooks/queries/useTeamMemory.ts b/web/src/hooks/queries/useTeamMemory.ts deleted file mode 100644 index ab9de384..00000000 --- a/web/src/hooks/queries/useTeamMemory.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { useQuery } from '@tanstack/react-query' -import type { ApiClient } from '@/api/client' -import type { TeamMemoryFile } from '@/types/team' -import { queryKeys } from '@/lib/query-keys' - -export function useTeamMemory(api: ApiClient | null, teamId: string | null): { - files: TeamMemoryFile[] - isLoading: boolean -} { - const query = useQuery({ - queryKey: queryKeys.teamMemory(teamId ?? ''), - queryFn: async () => { - if (!api || !teamId) { - throw new Error('API unavailable') - } - return await api.getTeamMemory(teamId) - }, - enabled: Boolean(api && teamId), - staleTime: 10_000, - refetchInterval: 30_000, - retry: false, - }) - - return { - files: query.data?.files ?? [], - isLoading: query.isLoading, - } -} diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index aacb3484..baa9d157 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -1419,4 +1419,5 @@ export default { 'newSession.member.task': 'Task brief (optional)', 'newSession.member.taskPlaceholder': 'What should this member do first?', 'newSession.member.roleRequired': 'Enter a role name for the new member', + 'team.memory.repoHint': 'Team memory lives with the code: /.hapi/team/ (created when the lead session starts). Open it here or in the lead session files.', } as const diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 7351b575..187c4e01 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -1418,4 +1418,5 @@ export default { 'newSession.member.task': '任务说明(可选)', 'newSession.member.taskPlaceholder': '这个成员一开始要做什么?', 'newSession.member.roleRequired': '请填写成员角色名称', + 'team.memory.repoHint': '团队记忆跟着代码走:/.hapi/team/(Lead 会话启动时生成),也可在 Lead 会话的文件页查看。', } as const diff --git a/web/src/lib/query-keys.ts b/web/src/lib/query-keys.ts index 46156740..6da68c8a 100644 --- a/web/src/lib/query-keys.ts +++ b/web/src/lib/query-keys.ts @@ -45,6 +45,4 @@ export const queryKeys = { teams: ['teams'] as const, team: (teamId: string) => ['team', teamId] as const, teamMessages: (teamId: string) => ['team-messages', teamId] as const, - teamMemory: (teamId: string) => ['team-memory', teamId] as const, - teamMemoryFile: (teamId: string, path: string) => ['team-memory-file', teamId, path] as const, } diff --git a/web/src/types/team.ts b/web/src/types/team.ts index 1a365676..da432d0d 100644 --- a/web/src/types/team.ts +++ b/web/src/types/team.ts @@ -57,14 +57,3 @@ export interface TeamDetail { tasks: TeamTask[] } -export interface TeamMemoryFile { - path: string - size: number - updatedAt: number -} - -export interface TeamMemoryFileContent { - path: string - content: string - updatedAt: number -}