diff --git a/apps/web/app/divisions/[divisionId]/page.tsx b/apps/web/app/divisions/[divisionId]/page.tsx new file mode 100644 index 0000000..00fae41 --- /dev/null +++ b/apps/web/app/divisions/[divisionId]/page.tsx @@ -0,0 +1,107 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { STAGE_LABEL, byRank } from "@offai/core"; +import { Avatar } from "@/components/avatar"; +import { ReportCard } from "@/components/report-card"; +import { getDivisionWeek, getOrg, getRecentReports } from "@/lib/data"; +import { formatUsd } from "@/lib/format"; + +type Props = { params: Promise<{ divisionId: string }> }; + +export async function generateMetadata({ params }: Props): Promise { + const { divisionId } = await params; + const division = (await getOrg()).divisions.find((item) => item.id === divisionId); + return { title: division?.name ?? "본부" }; +} + +export default async function DivisionPage({ params }: Props) { + const { divisionId } = await params; + const org = await getOrg(); + const division = org.divisions.find((item) => item.id === divisionId); + if (!division) notFound(); + const [reports, week] = await Promise.all([getRecentReports(60, { divisionId }), getDivisionWeek()]); + const stats = week.get(divisionId); + const people = division.teams.reduce((sum, team) => sum + team.roles.length, 0); + + return ( + <> + +
+
+ +
+

{division.name}

+

+ 본부장 {division.head.name} · 경력 {division.head.years}년{division.head.background && ` · ${division.head.background}`} +

+

{division.mission}

+
+
+
+
+
팀
+
{division.teams.length}
+
+
+
직원
+
{people}
+
+
+
최근 7일 세션
+
{stats?.sessions ?? 0}
+
+
+
최근 7일 사용
+
{formatUsd(stats?.costCents ?? 0)}
+
+
+
+ +
+

+ 소속 팀 +

+ +
+ +
+

+ 본부 보고함 +

+ {reports.length === 0 ? ( +

아직 보고가 없습니다.

+ ) : ( +
    + {reports.map((report) => ( +
  1. + +
  2. + ))} +
+ )} +
+ + ); +} diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index 410180e..459f11d 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -1785,3 +1785,447 @@ body:has(.bleed) .site-header__inner { .report-flow { margin-bottom: 24px; } + +/* ───────── live / staff / activity ───────── */ +.live { + display: inline-flex; + align-items: center; + font-size: 12px; + color: var(--muted); + margin-bottom: 12px; +} + +.now { + margin-bottom: 24px; +} + +.now__boards { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(520px, 100%), 1fr)); + gap: 12px; +} + +.staff { + padding: 14px 16px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--surface); +} + +.staff__title { + font-size: 14px; + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 10px; +} + +.staff__title .muted { + font-weight: 400; + font-size: 12px; +} + +.staff__grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; +} + +.staff__card { + display: flex; + gap: 10px; + padding: 8px 10px; + border-radius: 8px; + border: 1px solid var(--line); + min-width: 0; +} + +.staff__card--working { + border-color: color-mix(in srgb, var(--working) 50%, transparent); +} + +.staff__card--reported { + border-color: color-mix(in srgb, var(--accent) 50%, transparent); +} + +.staff__card--lead { + background: var(--bg); +} + +.staff__text { + min-width: 0; + font-size: 13px; +} + +.staff__state { + font-weight: 600; + font-size: 12px; +} + +.staff__card--working .staff__state { + color: var(--working); +} + +.staff__card--reported .staff__state { + color: var(--accent); +} + +.staff__card--idle .staff__state { + color: var(--muted); +} + +.staff__detail { + color: var(--muted); + font-size: 12px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.activity-groups { + display: flex; + flex-direction: column; + gap: 16px; +} + +.activity-group__title { + font-size: 14px; + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 8px; +} + +.activity-group__title .muted { + font-weight: 400; + font-size: 12px; +} + +.activity { + display: flex; + flex-direction: column; + gap: 2px; + border-left: 1px solid var(--line-strong); + margin-left: 12px; + padding-left: 14px; +} + +.activity__item { + display: flex; + gap: 10px; + padding: 6px 0; + margin-left: -28px; +} + +.activity__dot { + width: 26px; + height: 26px; + flex: none; + border-radius: 50%; + background: var(--line-strong); +} + +.activity__main { + min-width: 0; + flex: 1; +} + +.activity__head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 8px; + font-size: 13px; +} + +.activity__head time { + margin-left: auto; + color: var(--muted); + font-size: 12px; +} + +.activity__kind { + font-size: 11px; + font-weight: 600; + color: var(--muted); + border: 1px solid var(--line-strong); + border-radius: 4px; + padding: 0 5px; +} + +.activity__item--delegated .activity__kind { + color: var(--accent); + border-color: color-mix(in srgb, var(--accent) 40%, transparent); +} + +.activity__item--member_report .activity__kind { + color: var(--working); + border-color: color-mix(in srgb, var(--working) 40%, transparent); +} + +.activity__item--policy .activity__kind { + color: #dc2626; + border-color: color-mix(in srgb, #dc2626 40%, transparent); +} + +.activity__code { + display: block; + margin-top: 2px; + font-family: var(--mono); + font-size: 12px; + color: var(--muted); + white-space: pre-wrap; + word-break: break-all; +} + +.activity__detail { + font-size: 13px; + color: var(--muted); +} + +.activity__text summary { + cursor: pointer; + font-size: 13px; +} + +.activity__text pre { + white-space: pre-wrap; + word-break: break-word; + font-family: var(--font); + font-size: 13px; + margin: 6px 0 0; + padding: 8px 10px; + border-radius: 6px; + background: var(--bg); + border: 1px solid var(--line); +} + +/* ───────── projects ───────── */ +.projects { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(560px, 100%), 1fr)); + gap: 16px; +} + +.project { + padding: 16px 18px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--surface); +} + +.project__head { + display: flex; + justify-content: space-between; + align-items: baseline; + gap: 12px; + margin-bottom: 12px; +} + +.project__head h2 { + font-size: 16px; +} + +.project__head a { + text-decoration: none; +} + +.project__head a:hover { + text-decoration: underline; +} + +.project__tasks { + display: flex; + flex-direction: column; + gap: 10px; +} + +.project-task { + padding: 12px 0 2px; + border-top: 1px solid var(--line); + display: flex; + flex-direction: column; + gap: 8px; +} + +.project-task__top { + display: flex; + justify-content: space-between; + gap: 12px; + font-size: 14px; +} + +.stepper { + display: flex; + gap: 4px; + font-size: 11px; +} + +.stepper li { + flex: 1; + text-align: center; + padding: 3px 0; + border-radius: 4px; + background: var(--bg); + color: var(--muted); + border: 1px solid var(--line); +} + +.stepper .is-done { + color: var(--text); +} + +.stepper .is-current { + background: var(--text); + color: var(--bg); + border-color: var(--text); + font-weight: 600; +} + +.project-task__now { + display: flex; + align-items: center; + gap: 8px; + font-size: 13px; + min-width: 0; +} + +.project-task__now p { + flex: 1; + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.project-task__activity { + color: var(--muted); +} + +.small-meta { + font-size: 12px; + white-space: nowrap; +} + +/* ───────── division / team inbox / ceo ───────── */ +.division__link { + text-decoration: none; +} + +.division__link:hover { + text-decoration: underline; +} + +.division-hero { + display: flex; + gap: 14px; + align-items: center; +} + +.division-teams { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(300px, 100%), 1fr)); + gap: 10px; + margin-bottom: 28px; +} + +.division-team { + display: flex; + flex-direction: column; + gap: 6px; + padding: 12px 14px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--surface); + text-decoration: none; + font-size: 13px; +} + +.division-team:hover { + border-color: var(--accent); +} + +.team-inbox { + margin-bottom: 20px; +} + +.team-inbox .feed__list { + margin-top: 12px; +} + +.ceo { + margin-bottom: 28px; +} + +.ceo__grid { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 2fr); + gap: 12px; +} + +.ceo__todo { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); + gap: 8px; +} + +.ceo__todo li a, +.ceo__todo li span { + display: block; + padding: 12px 14px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--surface); + text-decoration: none; + font-size: 13px; + color: var(--muted); + height: 100%; +} + +.ceo__todo li a:hover { + border-color: var(--accent); +} + +.ceo__todo strong { + display: block; + font-size: 22px; + color: var(--text); + font-variant-numeric: tabular-nums; +} + +.ceo__todo .is-bad strong { + color: #dc2626; +} + +.ceo__divisions { + padding: 12px 16px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--surface); + font-size: 13px; +} + +.ceo__divisions h3 { + font-size: 13px; + margin-bottom: 8px; +} + +.ceo__divisions ul { + display: flex; + flex-direction: column; + gap: 6px; +} + +.desk--reported .desk__monitor { + background: var(--accent); +} + +@media (max-width: 960px) { + .ceo__grid { + grid-template-columns: 1fr; + } + + .staff__grid { + grid-template-columns: 1fr; + } +} diff --git a/apps/web/app/nav.tsx b/apps/web/app/nav.tsx index f5f4260..5a08f83 100644 --- a/apps/web/app/nav.tsx +++ b/apps/web/app/nav.tsx @@ -6,6 +6,7 @@ import { usePathname } from "next/navigation"; const LINKS = [ { href: "/", label: "조직도" }, { href: "/office", label: "자리 배치도" }, + { href: "/projects", label: "프로젝트" }, { href: "/tasks", label: "작업" }, { href: "/reports", label: "보고" }, { href: "/approvals", label: "승인함" }, @@ -18,7 +19,7 @@ export function Nav({ pendingApprovals }: { pendingApprovals: number }) { {visible.length === 0 ? ( diff --git a/apps/web/app/tasks/[taskId]/page.tsx b/apps/web/app/tasks/[taskId]/page.tsx index 1029ca6..45bf7e4 100644 --- a/apps/web/app/tasks/[taskId]/page.tsx +++ b/apps/web/app/tasks/[taskId]/page.tsx @@ -2,8 +2,10 @@ import type { Metadata } from "next"; import Link from "next/link"; import { notFound } from "next/navigation"; import { STAGE_LABEL, STATUS_LABEL } from "@offai/core"; +import { ActivityTimeline, StaffBoard } from "@/components/activity"; +import { AutoRefresh } from "@/components/auto-refresh"; import { ReportCard } from "@/components/report-card"; -import { getOrg, getTask, getTaskReports, type RunSummary } from "@/lib/data"; +import { getOrg, getTask, getTaskActivities, getTaskReports, type RunSummary } from "@/lib/data"; import { formatDate, formatUsd } from "@/lib/format"; import { approveDeploy, retryTask } from "../../actions"; import { Notice } from "../../notice"; @@ -23,10 +25,18 @@ const RUN_STATUS = { running: "실행 중", completed: "완료", failed: "실패 export default async function TaskPage({ params, searchParams }: Props) { const [{ taskId }, query] = await Promise.all([params, searchParams]); - const [task, org, reports] = await Promise.all([getTask(taskId), getOrg(), getTaskReports(taskId)]); + const [task, org, reports, activities] = await Promise.all([getTask(taskId), getOrg(), getTaskReports(taskId), getTaskActivities(taskId)]); if (!task) notFound(); const teamName = (id: string | null) => org.divisions.flatMap((division) => division.teams).find((team) => team.id === id)?.name ?? id ?? "-"; const github = `https://github.com/${task.repo}`; + const live = task.status === "running" || task.status === "awaiting_approval"; + // 현재 단계의 최근 세션들 (팀별 마지막 세션) + const stageRuns = task.runs.filter((run) => run.stage === task.stage); + const latestByTeam = new Map(stageRuns.map((run) => [run.teamId, run])); + const boards = [...latestByTeam.values()].map((run) => ({ + run, + items: activities.filter((item) => item.runId === run.id), + })); return ( <> @@ -79,6 +89,7 @@ export default async function TaskPage({ params, searchParams }: Props) { + {task.reason && (

@@ -90,8 +101,28 @@ export default async function TaskPage({ params, searchParams }: Props) {

릴리스팀이 배포 요청서를 PR에 남겼습니다. production 배포를 마친 뒤 ‘배포 완료 기록’을 누르세요.

)} + {boards.length > 0 && ( +
+

+ 지금 누가 무엇을 +

+
+ {boards.map(({ run, items }) => ( + + ))} +
+
+ )} +
+
+

+ 작업 과정 {activities.length} +

+ +
+

보고 흐름 {reports.length} diff --git a/apps/web/app/teams/[teamId]/page.tsx b/apps/web/app/teams/[teamId]/page.tsx index d13a1a1..84b5a17 100644 --- a/apps/web/app/teams/[teamId]/page.tsx +++ b/apps/web/app/teams/[teamId]/page.tsx @@ -3,7 +3,8 @@ import Link from "next/link"; import { notFound } from "next/navigation"; import { EFFORTS, MODEL_IDS, RANKS, STAGE_LABEL, byRank, findTeam, type Rank, type Role } from "@offai/core"; import { Avatar } from "@/components/avatar"; -import { getOrg, isPreview } from "@/lib/data"; +import { ReportCard } from "@/components/report-card"; +import { getOrg, getRecentReports, isPreview } from "@/lib/data"; import { MODEL_LABEL, formatUsd } from "@/lib/format"; import { addRole, removeRole, updateTeam } from "../../actions"; import { Notice, PreviewBanner } from "../../notice"; @@ -24,17 +25,19 @@ const STAFF_RANKS = RANKS.filter((rank) => rank !== "팀장"); export default async function TeamPage({ params, searchParams }: Props) { const [{ teamId }, query] = await Promise.all([params, searchParams]); - const ref = findTeam(await getOrg(), teamId); + const org = await getOrg(); + const ref = findTeam(org, teamId); if (!ref) notFound(); const { division, team } = ref; const readOnly = isPreview(); + const reports = await getRecentReports(30, { teamId }); return ( <>
@@ -54,6 +57,26 @@ export default async function TeamPage({ params, searchParams }: Props) {
{readOnly ? : } +
+

+ 팀 보고함 {reports.length} +

+ {reports.length === 0 ? ( +

아직 보고가 없습니다. 팀원 보고와 팀장 보고가 이곳에 쌓입니다.

+ ) : ( +
+ 최근 보고 {reports.length}건 +
    + {reports.map((report) => ( +
  1. + +
  2. + ))} +
+
+ )} +
+
diff --git a/apps/web/components/activity.tsx b/apps/web/components/activity.tsx new file mode 100644 index 0000000..aaba795 --- /dev/null +++ b/apps/web/components/activity.tsx @@ -0,0 +1,164 @@ +import { STAGE_LABEL, byRank, findTeam, type Org, type Role, type Team } from "@offai/core"; +import { Avatar } from "@/components/avatar"; +import type { ActivityItem, RunSummary } from "@/lib/data"; +import { formatDate } from "@/lib/format"; + +function findRole(org: Org, roleId: string | null): { role: Role; team: Team; divisionId: string } | null { + if (!roleId) return null; + for (const division of org.divisions) { + for (const team of division.teams) { + const role = team.roles.find((item) => item.id === roleId); + if (role) return { role, team, divisionId: division.id }; + } + } + return null; +} + +function who(org: Org, roleId: string | null): string { + const found = findRole(org, roleId); + return found ? `${found.role.person.name} ${found.role.rank}` : "팀원"; +} + +const KIND_LABEL: Record = { + session_started: "세션 시작", + member_joined: "투입", + delegated: "지시", + member_report: "보고", + tool: "작업", + lead_message: "메모", + policy: "정책", + session_finished: "세션 종료", +}; + +/** 활동 한 줄의 제목 (누가 → 누구에게 무엇을) */ +function headline(org: Org, item: ActivityItem): string { + const actor = who(org, item.actorRoleId); + switch (item.kind) { + case "delegated": + return `${actor} → ${who(org, item.targetRoleId)}에게 지시`; + case "member_report": + return `${actor} → ${who(org, item.targetRoleId)}에게 보고`; + case "member_joined": + return `${actor} 투입`; + case "policy": + return `${actor} 명령이 정책에 막힘`; + default: + return actor; + } +} + +/** 세션별로 묶은 작업 과정 타임라인 */ +export function ActivityTimeline({ org, items, runs }: { org: Org; items: ActivityItem[]; runs: RunSummary[] }) { + if (items.length === 0) return

아직 기록된 활동이 없습니다.

; + const groups = new Map(); + for (const item of items) { + const key = item.runId ?? "none"; + groups.set(key, [...(groups.get(key) ?? []), item]); + } + return ( +
+ {[...groups.entries()].map(([runId, list]) => { + const run = runs.find((item) => item.id === runId); + const team = findTeam(org, list[0]!.teamId)?.team; + return ( +
+

+ {team?.name ?? list[0]!.teamId} + {run && {STAGE_LABEL[run.stage]}} + {run && {run.status === "running" ? "진행 중" : run.status === "completed" ? "완료" : "실패"}} +

+
    + {list.map((item) => { + const actor = findRole(org, item.actorRoleId); + const long = item.kind === "delegated" || item.kind === "member_report" || item.kind === "lead_message"; + return ( +
  1. + {actor ? ( + + ) : ( +
  2. + ); + })} +
+
+ ); + })} +
+ ); +} + +type MemberStatus = { label: string; tone: "working" | "reported" | "idle" | "lead"; detail: string }; + +/** 팀원별 현재 상태: 최근 세션 활동에서 계산한다 */ +export function staffStatus(team: Team, items: ActivityItem[], runActive: boolean): Map { + const result = new Map(); + for (const role of team.roles) result.set(role.id, { label: "대기", tone: "idle", detail: "아직 투입되지 않음" }); + for (const item of items) { + if (item.kind === "delegated" && item.targetRoleId && result.has(item.targetRoleId)) { + result.set(item.targetRoleId, { label: "작업 중", tone: "working", detail: `지시: ${item.detail.split("\n")[0]}` }); + } + if (!item.actorRoleId || !result.has(item.actorRoleId)) continue; + const role = team.roles.find((r) => r.id === item.actorRoleId)!; + if (role.rank === "팀장") { + result.set(role.id, { label: runActive ? "주관 중" : "세션 종료", tone: "lead", detail: item.detail.split("\n")[0] ?? "" }); + } else if (item.kind === "member_report") { + result.set(role.id, { label: "보고 완료", tone: "reported", detail: item.detail.split("\n")[0] ?? "" }); + } else if (item.kind !== "member_joined" || result.get(role.id)?.tone === "idle") { + result.set(role.id, { label: "작업 중", tone: "working", detail: item.kind === "member_joined" ? "투입됨" : item.detail.split("\n")[0] ?? "" }); + } + } + return result; +} + +/** 지금 누가 무엇을 하고 있는지: 팀별 직원 카드 */ +export function StaffBoard({ org, teamId, items, runActive }: { org: Org; teamId: string; items: ActivityItem[]; runActive: boolean }) { + const ref = findTeam(org, teamId); + if (!ref) return null; + const status = staffStatus(ref.team, items, runActive); + return ( +
+

+ {ref.team.name} {runActive ?

+
    + {byRank(ref.team.roles).map((role) => { + const current = status.get(role.id)!; + return ( +
  • + +
    +

    + {role.person.name} {role.rank} · {role.name} +

    +

    {current.label}

    +

    + {current.detail} +

    +
    +
  • + ); + })} +
+
+ ); +} diff --git a/apps/web/components/auto-refresh.tsx b/apps/web/components/auto-refresh.tsx new file mode 100644 index 0000000..6ecd656 --- /dev/null +++ b/apps/web/components/auto-refresh.tsx @@ -0,0 +1,22 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useEffect } from "react"; + +/** 진행 중인 화면을 주기적으로 다시 불러온다 (탭이 보일 때만) */ +export function AutoRefresh({ active, intervalMs = 5000 }: { active: boolean; intervalMs?: number }) { + const router = useRouter(); + useEffect(() => { + if (!active) return; + const timer = window.setInterval(() => { + if (document.visibilityState === "visible") router.refresh(); + }, intervalMs); + return () => window.clearInterval(timer); + }, [active, intervalMs, router]); + return active ? ( +

+

+ ) : null; +} diff --git a/apps/web/components/report-card.tsx b/apps/web/components/report-card.tsx index 124c0fc..1a9ac04 100644 --- a/apps/web/components/report-card.tsx +++ b/apps/web/components/report-card.tsx @@ -13,20 +13,22 @@ export function ReportCard({ report, org, showTask = false }: Props) { const lead = team ? leadOf(team) : undefined; const next = report.nextTeamId ? (findTeam(org, report.nextTeamId)?.team.name ?? report.nextTeamId) : report.nextHuman; - const author = - report.level === "division" + const member = report.level === "member" && team ? team.roles.find((role) => role.id === report.roleId) : undefined; + const author = member + ? { seed: member.id, name: member.person.name, gender: member.person.gender, title: `${team?.name ?? ""} ${member.rank} · 경력 ${member.person.years}년` } + : report.level === "division" ? { seed: `head-${report.divisionId}`, name: division?.head.name ?? "본부장", gender: division?.head.gender ?? "female", title: `${division?.name ?? report.divisionId} 본부장 · 경력 ${division?.head.years ?? 0}년` } : { seed: lead?.id ?? report.teamId ?? "team", name: lead?.person.name ?? "팀장", gender: lead?.person.gender ?? "male", title: `${team?.name ?? report.teamId} 팀장${lead ? ` · 경력 ${lead.person.years}년` : ""}` }; return (
- +
{author.name} {author.title} - {report.level === "division" ? "본부 보고" : "팀 보고"} + {report.level === "division" ? "본부 보고" : report.level === "team" ? "팀 보고" : "팀원 보고"} {STAGE_LABEL[report.stage]} {OUTCOME_LABEL[report.outcome]} diff --git a/apps/web/lib/data.ts b/apps/web/lib/data.ts index 98779b0..bcf50be 100644 --- a/apps/web/lib/data.ts +++ b/apps/web/lib/data.ts @@ -67,7 +67,8 @@ export async function getOrg(): Promise { return (await getOrgWithVersion()).org; } -const spentSql = sql`coalesce((select sum(${schema.runs.costCents}) from ${schema.runs} where ${schema.runs.taskId} = ${schema.tasks.id}), 0)::int`; +// 하위 쿼리 안에서 tasks.id 를 명시해야 runs.id 로 잘못 해석되지 않는다 +const spentSql = sql`coalesce((select sum(r.cost_cents) from runs r where r.task_id = "tasks"."id"), 0)::int`; export async function getTasks(): Promise { const db = getDb(); @@ -170,10 +171,11 @@ export type ReportItem = { taskId: string; taskTitle: string; issueNumber: number | null; - level: "team" | "division"; + level: "member" | "team" | "division"; stage: Stage; divisionId: string; teamId: string | null; + roleId: string | null; outcome: Report["outcome"]; summary: string; body: string; @@ -191,6 +193,7 @@ const reportColumns = { stage: schema.reports.stage, divisionId: schema.reports.divisionId, teamId: schema.reports.teamId, + roleId: schema.reports.roleId, outcome: schema.reports.outcome, summary: schema.reports.summary, body: schema.reports.body, @@ -199,13 +202,18 @@ const reportColumns = { createdAt: schema.reports.createdAt, }; -export async function getRecentReports(limit = 100): Promise { +export async function getRecentReports(limit = 100, filter: { divisionId?: string; teamId?: string } = {}): Promise { const db = getDb(); if (!db) return []; + const conditions = [ + filter.divisionId ? eq(schema.reports.divisionId, filter.divisionId) : undefined, + filter.teamId ? eq(schema.reports.teamId, filter.teamId) : undefined, + ].filter((item) => item !== undefined); return db .select(reportColumns) .from(schema.reports) .innerJoin(schema.tasks, eq(schema.tasks.id, schema.reports.taskId)) + .where(conditions.length ? and(...conditions) : undefined) .orderBy(desc(schema.reports.createdAt)) .limit(limit); } @@ -271,3 +279,126 @@ export async function getDivisionWeek(now = new Date()): Promise { + const db = getDb(); + if (!db || !/^[0-9a-f-]{36}$/i.test(taskId)) return []; + const rows = await db + .select() + .from(schema.activities) + .where(eq(schema.activities.taskId, taskId)) + .orderBy(desc(schema.activities.id)) + .limit(500); + return rows.reverse(); +} + +export type MemberState = { state: "working" | "reported" | "idle"; detail: string; taskId: string; at: Date }; + +/** + * 실행 중인 세션의 직원별 현재 상태 (자리 배치도·작업 상세용) + * - working: 투입·지시 이후 아직 보고 전, 또는 최근 명령 실행 + * - reported: 팀장에게 보고 완료 + */ +export async function getMemberStates(): Promise> { + const db = getDb(); + const states = new Map(); + if (!db) return states; + const rows = await db + .select({ + taskId: schema.activities.taskId, + kind: schema.activities.kind, + actor: schema.activities.actorRoleId, + target: schema.activities.targetRoleId, + detail: schema.activities.detail, + createdAt: schema.activities.createdAt, + }) + .from(schema.activities) + .innerJoin(schema.runs, eq(schema.runs.id, schema.activities.runId)) + .where(eq(schema.runs.status, "running")) + .orderBy(schema.activities.id); + for (const row of rows) { + if (row.kind === "delegated" && row.target) { + states.set(row.target, { state: "working", detail: `지시받음: ${row.detail}`, taskId: row.taskId, at: row.createdAt }); + } + if (!row.actor) continue; + const reported = row.kind === "member_report"; + states.set(row.actor, { state: reported ? "reported" : "working", detail: reported ? `보고: ${row.detail}` : row.detail, taskId: row.taskId, at: row.createdAt }); + } + return states; +} + +export type ProjectTask = TaskSummary & { lastActivity: { detail: string; actorRoleId: string | null; at: Date } | null }; + +/** 프로젝트(레포)별 진행 중 작업과 최근 활동 */ +export async function getProjects(repos: readonly string[]): Promise<{ repo: string; active: ProjectTask[]; doneCount: number }[]> { + const db = getDb(); + if (!db) return repos.map((repo) => ({ repo, active: [], doneCount: 0 })); + const tasks = await getTasks(); + const latest = await db + .selectDistinctOn([schema.activities.taskId], { + taskId: schema.activities.taskId, + detail: schema.activities.detail, + actorRoleId: schema.activities.actorRoleId, + at: schema.activities.createdAt, + }) + .from(schema.activities) + .orderBy(schema.activities.taskId, desc(schema.activities.id)); + const byTask = new Map(latest.map((row) => [row.taskId, { detail: row.detail, actorRoleId: row.actorRoleId, at: row.at }])); + const allRepos = [...new Set([...repos, ...tasks.map((task) => task.repo)])]; + return allRepos.map((repo) => { + const mine = tasks.filter((task) => task.repo === repo); + return { + repo, + active: mine.filter((task) => task.status !== "done").map((task) => ({ ...task, lastActivity: byTask.get(task.id) ?? null })), + doneCount: mine.filter((task) => task.status === "done").length, + }; + }); +} + +export type ExecutiveDigest = { + running: number; + awaitingMerge: number; + awaitingDeploy: number; + escalated: number; + approvals: number; + divisionToday: ReportItem[]; +}; + +/** 대표 보고: 사람이 처리할 일과 본부별 최근 24시간 보고 */ +export async function getExecutiveDigest(now = new Date()): Promise { + const db = getDb(); + const empty: ExecutiveDigest = { running: 0, awaitingMerge: 0, awaitingDeploy: 0, escalated: 0, approvals: 0, divisionToday: [] }; + if (!db) return empty; + const counts = await db + .select({ status: schema.tasks.status, count: sql`count(*)::int` }) + .from(schema.tasks) + .groupBy(schema.tasks.status); + const count = (status: TaskStatus) => counts.find((row) => row.status === status)?.count ?? 0; + const since = new Date(now.getTime() - 24 * 3_600_000); + const divisionToday = await db + .selectDistinctOn([schema.reports.divisionId], reportColumns) + .from(schema.reports) + .innerJoin(schema.tasks, eq(schema.tasks.id, schema.reports.taskId)) + .where(and(eq(schema.reports.level, "division"), gte(schema.reports.createdAt, since))) + .orderBy(schema.reports.divisionId, desc(schema.reports.createdAt)); + return { + running: count("running") + count("queued"), + awaitingMerge: count("awaiting_merge"), + awaitingDeploy: count("awaiting_deploy"), + escalated: count("escalated"), + approvals: (await getPendingApprovalCount()) || count("awaiting_approval"), + divisionToday, + }; +} diff --git a/apps/worker/src/flow.test.ts b/apps/worker/src/flow.test.ts index 0e30060..a13e1dd 100644 --- a/apps/worker/src/flow.test.ts +++ b/apps/worker/src/flow.test.ts @@ -112,7 +112,7 @@ describe.skipIf(!url)("작업 흐름 (Postgres)", () => { }); beforeEach(async () => { - await db.execute(sql`truncate table reports, task_events, approvals, runs, tasks, agents, settings, org_versions restart identity cascade`); + await db.execute(sql`truncate table activities, reports, task_events, approvals, runs, tasks, agents, settings, org_versions restart identity cascade`); const version = await saveOrg(db, DEFAULT_ORG, "test"); await setSetting(db, SYNCED_ORG_SETTING, String(version)); await setSetting(db, ENVIRONMENT_SETTING, "env_test"); @@ -267,6 +267,45 @@ describe.skipIf(!url)("작업 흐름 (Postgres)", () => { expect(await currentTask()).toMatchObject({ stage: "verify", status: "queued" }); }); + it("세션 안의 팀원 투입·지시·명령·보고를 직원 단위로 기록한다", async () => { + await orchestrator.handleWebhook({ type: "enqueue", repo: REPO, issueNumber: 12, title: "Activity", body: "", labels: ["🖥️ web"] }); + scripts = { plan: async () => report("completed", { spec: "명세" }) }; + await step(); + scripts = { + implement: async (_input, hooks) => { + await hooks.onActivity({ kind: "member_joined", threadId: "sthr_1", agentName: "offai/web/web-engineer" }); + await hooks.onActivity({ kind: "delegated", threadId: "sthr_1", agentName: "offai/web/web-engineer", text: "footer 링크를 /contact 로 바꿔 주세요" }); + await hooks.onActivity({ kind: "tool", threadId: null, tool: "read", input: { file_path: "app/footer.tsx" } }); + await hooks.onActivity({ kind: "tool", threadId: "sthr_1", tool: "bash", input: { command: "pnpm test" } }); + await hooks.decideTool({ id: "tu_9", name: "bash", input: { command: "git push origin main" }, threadId: "sthr_1" }); + await hooks.onActivity({ kind: "member_report", threadId: "sthr_1", agentName: "offai/web/web-engineer", text: "footer 수정 완료\n테스트 통과" }); + github.branches.add("feat/12-activity"); + return report("completed"); + }, + }; + await step(); + + const rows = await db.select().from(schema.activities).orderBy(schema.activities.id); + const implementRows = rows.filter((row) => row.teamId === "web"); + expect(implementRows.map((row) => [row.kind, row.actorRoleId, row.targetRoleId])).toEqual([ + ["session_started", "web-lead", null], + ["member_joined", "web-engineer", null], + ["delegated", "web-lead", "web-engineer"], + ["tool", "web-lead", null], + ["tool", "web-engineer", null], + ["policy", "web-engineer", null], + ["member_report", "web-engineer", "web-lead"], + ["session_finished", "web-lead", null], + ]); + expect(implementRows[3]!.detail).toBe("파일 읽기 app/footer.tsx"); + expect(implementRows[4]!.detail).toBe("$ pnpm test"); + expect(implementRows[5]!.detail).toContain("main 직접 push 금지"); + + const memberReports = await db.select().from(schema.reports).where(eq(schema.reports.level, "member")); + expect(memberReports).toHaveLength(1); + expect(memberReports[0]).toMatchObject({ roleId: "web-engineer", teamId: "web", summary: "footer 수정 완료" }); + }); + it("브랜치를 push 하지 않으면 PR 없이 사람에게 넘긴다", async () => { await orchestrator.handleWebhook({ type: "enqueue", repo: REPO, issueNumber: 12, title: "No push", body: "", labels: [] }); scripts = { plan: async () => report("completed", { spec: "명세" }), implement: async () => report("completed") }; diff --git a/apps/worker/src/orchestrator.ts b/apps/worker/src/orchestrator.ts index 3df2514..664f149 100644 --- a/apps/worker/src/orchestrator.ts +++ b/apps/worker/src/orchestrator.ts @@ -1,6 +1,8 @@ import type Anthropic from "@anthropic-ai/sdk"; import { GITMOJI, + STAGE_LABEL, + leadOf, OUTCOME_LABEL, buildHandoff, findTeam, @@ -34,7 +36,7 @@ export type GitHubPort = Pick< GitHub, "defaultBranch" | "changedFiles" | "branchExists" | "findOpenPr" | "createPr" | "comment" | "createIssue" | "installationToken" >; -import { runSession, type RunResult, type ToolDecision } from "./runner"; +import { runSession, type RunResult, type SessionActivity, type ToolDecision } from "./runner"; import type { WebhookCommand } from "./webhook"; type Task = typeof schema.tasks.$inferSelect; @@ -298,6 +300,65 @@ export class Orchestrator { await db.update(schema.tasks).set({ teamId: ref.team.id, updatedAt: new Date() }).where(eq(schema.tasks.id, task.id)); await addTaskEvent(db, task.id, ref.team.name, `${ref.team.name} 세션 시작`); + // 세션 안의 활동을 직원 단위로 기록한다 (threadId → 직원) + const lead = leadOf(ref.team); + const threads = new Map(); + const roleOf = (roleId: string | null | undefined) => (roleId ? ref.team.roles.find((role) => role.id === roleId) : undefined); + const roleByAgentName = (agentName: string | null) => { + const roleId = agentName?.split("/").pop(); + return roleOf(roleId)?.id ?? null; + }; + const label = (roleId: string | null) => { + const role = roleOf(roleId); + return role ? `${role.person.name} ${role.rank}` : "팀원"; + }; + const record = (kind: schema.ActivityKind, actorRoleId: string | null, targetRoleId: string | null, detail: string) => + db.insert(schema.activities).values({ taskId: task.id, runId: run.id, teamId: ref.team.id, kind, actorRoleId, targetRoleId, detail: clip(detail, 2000) }); + await record("session_started", lead.id, null, `${ref.team.name} ${STAGE_LABEL[task.stage]} 세션 시작 — ${lead.person.name} 팀장 주관`); + + const onActivity = async (activity: SessionActivity) => { + switch (activity.kind) { + case "member_joined": { + const roleId = roleByAgentName(activity.agentName); + if (roleId) threads.set(activity.threadId, roleId); + await record("member_joined", roleId, null, `${label(roleId)} 투입`); + return; + } + case "delegated": { + const target = roleByAgentName(activity.agentName) ?? threads.get(activity.threadId) ?? null; + await record("delegated", lead.id, target, activity.text); + return; + } + case "member_report": { + const actor = roleByAgentName(activity.agentName) ?? threads.get(activity.threadId) ?? null; + await record("member_report", actor, lead.id, activity.text); + if (actor) { + await db.insert(schema.reports).values({ + taskId: task.id, + runId: run.id, + level: "member", + stage: task.stage, + divisionId: ref.division.id, + teamId: ref.team.id, + roleId: actor, + outcome: "completed", + summary: clip(activity.text.split("\n").find((line) => line.trim()) ?? activity.text, 200), + body: clip(activity.text, 4000), + }); + } + return; + } + case "tool": { + const actor = activity.threadId ? (threads.get(activity.threadId) ?? null) : lead.id; + await record("tool", actor, null, describeTool(activity.tool, activity.input)); + return; + } + case "lead_message": + await record("lead_message", lead.id, null, activity.text); + return; + } + }; + const commitType = branchTypeFor(task.labels); const branchReady = task.branch !== null && (await github.branchExists(task.repo, task.branch)); const checkoutBranch = task.stage === "implement" ? (branchReady && task.branch ? task.branch : baseBranch) : task.stage === "verify" && task.branch ? task.branch : baseBranch; @@ -340,7 +401,15 @@ export class Orchestrator { onCost: async (costCents) => { await db.update(schema.runs).set({ costCents }).where(eq(schema.runs.id, run.id)); }, - decideTool: (event) => this.decideTool(task.id, run.id, event), + decideTool: async (event) => { + const actor = event.threadId ? (threads.get(event.threadId) ?? null) : lead.id; + const decision = await this.decideTool(task.id, run.id, event); + if (event.name === "bash" && decision.result === "deny") { + await record("policy", actor, null, `명령 거부: ${decision.message ?? ""}`); + } + return decision; + }, + onActivity, log: (message) => log.info(`[${ref.team.id}] ${message}`), }, ); @@ -366,7 +435,7 @@ export class Orchestrator { summary: result.ok ? result.report.summary : result.error, body: result.ok ? reportBody(result.report) : "", }); - const lead = ref.team.roles.find((role) => role.rank === "팀장"); + await record("session_finished", lead.id, null, result.ok ? `세션 종료 — ${OUTCOME_LABEL[result.report.outcome]}: ${result.report.summary}` : `세션 종료 — 진행 불가: ${result.error}`); await addTaskEvent( db, task.id, @@ -590,3 +659,28 @@ function list(title: string, items: string[]): string { return items.length ? `${title}\n${items.map((item) => `- ${item}`).join("\n")}\n\n` : ""; } + +function clip(text: string, max: number): string { + return text.length > max ? `${text.slice(0, max - 1)}…` : text; +} + +/** 도구 호출을 사람이 읽을 한 줄로 */ +export function describeTool(tool: string, input: Record): string { + const str = (key: string) => (typeof input[key] === "string" ? (input[key] as string) : ""); + switch (tool) { + case "bash": + return str("command") ? `$ ${clip(str("command"), 300)}` : "bash 재시작"; + case "read": + return `파일 읽기 ${str("file_path")}`; + case "write": + return `파일 작성 ${str("file_path")}`; + case "edit": + return `파일 수정 ${str("file_path")}`; + case "glob": + return `파일 찾기 ${str("pattern")}`; + case "grep": + return `코드 검색 ${str("pattern")}${str("path") ? ` (${str("path")})` : ""}`; + default: + return tool; + } +} diff --git a/apps/worker/src/runner.ts b/apps/worker/src/runner.ts index b85d756..0e5b11a 100644 --- a/apps/worker/src/runner.ts +++ b/apps/worker/src/runner.ts @@ -8,11 +8,20 @@ type ToolUseEvent = Anthropic.Beta.Sessions.BetaManagedAgentsAgentToolUseEvent | export type ToolDecision = { result: "allow" | "deny"; message?: string }; +/** 세션 안에서 일어난 일 (누가 무엇을). threadId 로 팀원을 구분한다. */ +export type SessionActivity = + | { kind: "member_joined"; threadId: string; agentName: string } + | { kind: "delegated"; threadId: string; agentName: string | null; text: string } + | { kind: "member_report"; threadId: string; agentName: string | null; text: string } + | { kind: "tool"; threadId: string | null; tool: string; input: Record } + | { kind: "lead_message"; text: string }; + export type RunHooks = { onSession(sessionId: string): Promise; /** 멈춘 도구 호출을 판정한다. 사람 승인을 기다리는 동안 resolve 되지 않을 수 있다. */ decideTool(event: { id: string; name: string; input: Record; threadId: string | null }): Promise; onCost(costCents: number): Promise; + onActivity(activity: SessionActivity): Promise; log(message: string): void; }; @@ -33,6 +42,16 @@ export type RunResult = | { ok: false; sessionId: string | null; error: string; costCents: number }; /** list_cost.amount 를 센트로 바꾼다 (정수 문자열이면 이미 센트) */ +type ContentBlock = { type: string; text?: string }; + +function textOf(content: readonly ContentBlock[]): string { + return content + .filter((block) => block.type === "text" && typeof block.text === "string") + .map((block) => block.text) + .join("\n") + .trim(); +} + export function costToCents(amount: string): number { if (/^\d+$/.test(amount)) return Number.parseInt(amount, 10); const value = Number.parseFloat(amount); @@ -100,9 +119,32 @@ export async function runSession(client: Anthropic, input: RunInput, hooks: RunH switch (event.type) { case "agent.tool_use": case "agent.mcp_tool_use": + await hooks.onActivity({ kind: "tool", threadId: event.session_thread_id ?? null, tool: event.name, input: event.input }); if (event.evaluated_permission === "ask") await answerTool(event); return null; + case "session.thread_created": + await hooks.onActivity({ kind: "member_joined", threadId: event.session_thread_id, agentName: event.agent_name }); + return null; + + case "agent.thread_message_sent": { + const text = textOf(event.content); + if (text) await hooks.onActivity({ kind: "delegated", threadId: event.to_session_thread_id, agentName: event.to_agent_name ?? null, text }); + return null; + } + + case "agent.thread_message_received": { + const text = textOf(event.content); + if (text) await hooks.onActivity({ kind: "member_report", threadId: event.from_session_thread_id, agentName: event.from_agent_name ?? null, text }); + return null; + } + + case "agent.message": { + const text = textOf(event.content); + if (text) await hooks.onActivity({ kind: "lead_message", text }); + return null; + } + case "agent.custom_tool_use": { if (event.name !== REPORT_TOOL_NAME) { await send([ diff --git a/packages/db/drizzle/0003_lethal_sir_ram.sql b/packages/db/drizzle/0003_lethal_sir_ram.sql new file mode 100644 index 0000000..d847422 --- /dev/null +++ b/packages/db/drizzle/0003_lethal_sir_ram.sql @@ -0,0 +1,17 @@ +CREATE TABLE "activities" ( + "id" serial PRIMARY KEY NOT NULL, + "task_id" uuid NOT NULL, + "run_id" uuid, + "team_id" text NOT NULL, + "kind" text NOT NULL, + "actor_role_id" text, + "target_role_id" text, + "detail" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "reports" ADD COLUMN "role_id" text;--> statement-breakpoint +ALTER TABLE "activities" ADD CONSTRAINT "activities_task_id_tasks_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."tasks"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "activities" ADD CONSTRAINT "activities_run_id_runs_id_fk" FOREIGN KEY ("run_id") REFERENCES "public"."runs"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "activities_task_idx" ON "activities" USING btree ("task_id","id");--> statement-breakpoint +CREATE INDEX "activities_run_idx" ON "activities" USING btree ("run_id","id"); \ No newline at end of file diff --git a/packages/db/drizzle/meta/0003_snapshot.json b/packages/db/drizzle/meta/0003_snapshot.json new file mode 100644 index 0000000..f043ff9 --- /dev/null +++ b/packages/db/drizzle/meta/0003_snapshot.json @@ -0,0 +1,966 @@ +{ + "id": "03663477-3e92-42ff-8f4c-ed07ca76fb3b", + "prevId": "6db02269-beed-483c-9d01-9b43a38c0cd1", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.activities": { + "name": "activities", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_role_id": { + "name": "actor_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_role_id": { + "name": "target_role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "activities_task_idx": { + "name": "activities_task_idx", + "columns": [ + { + "expression": "task_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "activities_run_idx": { + "name": "activities_run_idx", + "columns": [ + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "activities_task_id_tasks_id_fk": { + "name": "activities_task_id_tasks_id_fk", + "tableFrom": "activities", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "activities_run_id_runs_id_fk": { + "name": "activities_run_id_runs_id_fk", + "tableFrom": "activities", + "tableTo": "runs", + "columnsFrom": [ + "run_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agents": { + "name": "agents", + "schema": "", + "columns": { + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "agent_id": { + "name": "agent_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent_version": { + "name": "agent_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "config_hash": { + "name": "config_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.approvals": { + "name": "approvals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_use_id": { + "name": "tool_use_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "command": { + "name": "command", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decided_at": { + "name": "decided_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "approvals_tool_use_idx": { + "name": "approvals_tool_use_idx", + "columns": [ + { + "expression": "tool_use_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "approvals_status_idx": { + "name": "approvals_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "approvals_task_id_tasks_id_fk": { + "name": "approvals_task_id_tasks_id_fk", + "tableFrom": "approvals", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "approvals_run_id_runs_id_fk": { + "name": "approvals_run_id_runs_id_fk", + "tableFrom": "approvals", + "tableTo": "runs", + "columnsFrom": [ + "run_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.org_versions": { + "name": "org_versions", + "schema": "", + "columns": { + "version": { + "name": "version", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "edited_by": { + "name": "edited_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reports": { + "name": "reports", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stage": { + "name": "stage", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "division_id": { + "name": "division_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "next_team_id": { + "name": "next_team_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_human": { + "name": "next_human", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "reports_task_idx": { + "name": "reports_task_idx", + "columns": [ + { + "expression": "task_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "reports_created_idx": { + "name": "reports_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "reports_task_id_tasks_id_fk": { + "name": "reports_task_id_tasks_id_fk", + "tableFrom": "reports", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "reports_run_id_runs_id_fk": { + "name": "reports_run_id_runs_id_fk", + "tableFrom": "reports", + "tableTo": "runs", + "columnsFrom": [ + "run_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.runs": { + "name": "runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "stage": { + "name": "stage", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "division_id": { + "name": "division_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "budget_cents": { + "name": "budget_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "cost_cents": { + "name": "cost_cents", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "report": { + "name": "report", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "runs_task_idx": { + "name": "runs_task_idx", + "columns": [ + { + "expression": "task_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "runs_division_month_idx": { + "name": "runs_division_month_idx", + "columns": [ + { + "expression": "division_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "runs_task_id_tasks_id_fk": { + "name": "runs_task_id_tasks_id_fk", + "tableFrom": "runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_events": { + "name": "task_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "task_events_task_idx": { + "name": "task_events_task_idx", + "columns": [ + { + "expression": "task_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "task_events_task_id_tasks_id_fk": { + "name": "task_events_task_id_tasks_id_fk", + "tableFrom": "task_events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "repo": { + "name": "repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_number": { + "name": "issue_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "labels": { + "name": "labels", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "stage": { + "name": "stage", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reworks": { + "name": "reworks", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "team_id": { + "name": "team_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "spec": { + "name": "spec", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "findings": { + "name": "findings", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_repo_issue_idx": { + "name": "tasks_repo_issue_idx", + "columns": [ + { + "expression": "repo", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tasks_status_idx": { + "name": "tasks_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index 4b0052b..c87e02f 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1794291283513, "tag": "0002_loving_ricochet", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1794291827087, + "tag": "0003_lethal_sir_ram", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index d92fe65..098f676 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -125,7 +125,7 @@ export const settings = pgTable("settings", { updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }); -export const REPORT_LEVELS = ["team", "division"] as const; +export const REPORT_LEVELS = ["member", "team", "division"] as const; export type ReportLevel = (typeof REPORT_LEVELS)[number]; /** @@ -145,6 +145,8 @@ export const reports = pgTable( divisionId: text("division_id").notNull(), /** 본부 보고는 null */ teamId: text("team_id"), + /** 팀원 보고일 때 보고한 직원 */ + roleId: text("role_id"), outcome: text("outcome").$type().notNull(), summary: text("summary").notNull(), /** 인계용 상세 (Markdown) */ @@ -157,3 +159,27 @@ export const reports = pgTable( }, (table) => [index("reports_task_idx").on(table.taskId, table.createdAt), index("reports_created_idx").on(table.createdAt)], ); + +export const ACTIVITY_KINDS = ["session_started", "member_joined", "delegated", "member_report", "tool", "lead_message", "policy", "session_finished"] as const; +export type ActivityKind = (typeof ACTIVITY_KINDS)[number]; + +/** 세션 안에서 누가 무엇을 했는지 (작업 과정 상세 보기) */ +export const activities = pgTable( + "activities", + { + id: serial("id").primaryKey(), + taskId: uuid("task_id") + .notNull() + .references(() => tasks.id, { onDelete: "cascade" }), + runId: uuid("run_id").references(() => runs.id, { onDelete: "cascade" }), + teamId: text("team_id").notNull(), + kind: text("kind").$type().notNull(), + /** 행동한 직원 (알 수 없으면 null) */ + actorRoleId: text("actor_role_id"), + /** 지시를 받은 직원 등 상대 */ + targetRoleId: text("target_role_id"), + detail: text("detail").notNull(), + createdAt: createdAt(), + }, + (table) => [index("activities_task_idx").on(table.taskId, table.id), index("activities_run_idx").on(table.runId, table.id)], +);