All files / src/trpc/routers architect.ts

71.69% Statements 76/106
57.69% Branches 45/78
78.57% Functions 11/14
71.28% Lines 72/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366                                                                          16x               16x 16x         16x           20x 16x 16x 16x 11x 11x 15x 4x 4x             24x   16x       11x                 3x 3x 3x   3x 3x             3x               3x   3x                                     8x 8x 8x   8x 8x               8x 8x   4x         8x 1x       8x   4x       8x 1x           7x               7x   7x   7x                                                                                                                                                                                                             10x 10x 10x 10x   10x 10x           10x 10x               10x 10x 3x       10x 10x 10x 3x 3x 3x   2x 1x 1x 1x     10x 1x   10x 1x           9x 10x                 9x   9x   9x                                      
/**
 * Architect Router — discuss, plan, refine, detail spawn procedures
 */
 
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import type { ProcedureBuilder } from '../trpc.js';
import {
  requireAgentManager,
  requireInitiativeRepository,
  requirePhaseRepository,
  requirePageRepository,
  requireTaskRepository,
} from './_helpers.js';
import {
  buildDiscussPrompt,
  buildPlanPrompt,
  buildRefinePrompt,
  buildDetailPrompt,
} from '../../agent/prompts/index.js';
import { isPlanningCategory } from '../../git/branch-naming.js';
import type { PhaseRepository } from '../../db/repositories/phase-repository.js';
import type { TaskRepository } from '../../db/repositories/task-repository.js';
import type { PageRepository } from '../../db/repositories/page-repository.js';
import type { Phase, Task } from '../../db/schema.js';
import type { PageForSerialization } from '../../agent/content-serializer.js';
 
async function gatherInitiativeContext(
  phaseRepo: PhaseRepository | undefined,
  taskRepo: TaskRepository | undefined,
  pageRepo: PageRepository | undefined,
  initiativeId: string,
): Promise<{
  phases: Array<Phase & { dependsOn?: string[] }>;
  tasks: Task[];
  pages: PageForSerialization[];
}> {
  const [rawPhases, deps, initiativeTasks, pages] = await Promise.all([
    phaseRepo?.findByInitiativeId(initiativeId) ?? [],
    phaseRepo?.findDependenciesByInitiativeId(initiativeId) ?? [],
    taskRepo?.findByInitiativeId(initiativeId) ?? [],
    pageRepo?.findByInitiativeId(initiativeId) ?? [],
  ]);
 
  // Merge dependencies into each phase as a dependsOn array
  const depsByPhase = new Map<string, string[]>();
  for (const dep of deps) {
    const arr = depsByPhase.get(dep.phaseId) ?? [];
    arr.push(dep.dependsOnPhaseId);
    depsByPhase.set(dep.phaseId, arr);
  }
  const phases = rawPhases.map((ph) => ({
    ...ph,
    dependsOn: depsByPhase.get(ph.id) ?? [],
  }));
 
  // Collect tasks from all phases (some tasks only have phaseId, not initiativeId)
  const taskIds = new Set(initiativeTasks.map((t) => t.id));
  const allTasks = [...initiativeTasks];
  Eif (taskRepo) {
    for (const ph of rawPhases) {
      const phaseTasks = await taskRepo.findByPhaseId(ph.id);
      for (const t of phaseTasks) {
        if (!taskIds.has(t.id)) {
          taskIds.add(t.id);
          allTasks.push(t);
        }
      }
    }
  }
 
  // Only include implementation tasks in agent context — planning tasks are irrelevant noise
  const implementationTasks = allTasks.filter(t => !isPlanningCategory(t.category));
 
  return { phases, tasks: implementationTasks, pages };
}
 
export function architectProcedures(publicProcedure: ProcedureBuilder) {
  return {
    spawnArchitectDiscuss: publicProcedure
      .input(z.object({
        name: z.string().min(1).optional(),
        initiativeId: z.string().min(1),
        context: z.string().optional(),
        provider: z.string().optional(),
      }))
      .mutation(async ({ ctx, input }) => {
        const agentManager = requireAgentManager(ctx);
        const initiativeRepo = requireInitiativeRepository(ctx);
        const taskRepo = requireTaskRepository(ctx);
 
        const initiative = await initiativeRepo.findById(input.initiativeId);
        Iif (!initiative) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Initiative '${input.initiativeId}' not found`,
          });
        }
 
        const task = await taskRepo.create({
          initiativeId: input.initiativeId,
          name: `Discuss: ${initiative.name}`,
          description: input.context ?? 'Gather context and requirements for initiative',
          category: 'discuss',
          status: 'in_progress',
        });
 
        const prompt = buildDiscussPrompt();
 
        return agentManager.spawn({
          name: input.name,
          taskId: task.id,
          prompt,
          mode: 'discuss',
          provider: input.provider,
          initiativeId: input.initiativeId,
          inputContext: { initiative },
        });
      }),
 
    spawnArchitectPlan: publicProcedure
      .input(z.object({
        name: z.string().min(1).optional(),
        initiativeId: z.string().min(1),
        contextSummary: z.string().optional(),
        provider: z.string().optional(),
      }))
      .mutation(async ({ ctx, input }) => {
        const agentManager = requireAgentManager(ctx);
        const initiativeRepo = requireInitiativeRepository(ctx);
        const taskRepo = requireTaskRepository(ctx);
 
        const initiative = await initiativeRepo.findById(input.initiativeId);
        Iif (!initiative) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Initiative '${input.initiativeId}' not found`,
          });
        }
 
        // Auto-dismiss stale plan agents
        const allAgents = await agentManager.list();
        const staleAgents = allAgents.filter(
          (a) =>
            a.mode === 'plan' &&
            a.initiativeId === input.initiativeId &&
            ['crashed', 'idle'].includes(a.status) &&
            !a.userDismissedAt,
        );
        for (const stale of staleAgents) {
          await agentManager.dismiss(stale.id);
        }
 
        // Reject if a plan agent is already active for this initiative
        const activePlanAgents = allAgents.filter(
          (a) =>
            a.mode === 'plan' &&
            a.initiativeId === input.initiativeId &&
            ['running', 'waiting_for_input'].includes(a.status),
        );
        if (activePlanAgents.length > 0) {
          throw new TRPCError({
            code: 'CONFLICT',
            message: 'A plan agent is already running for this initiative',
          });
        }
 
        const task = await taskRepo.create({
          initiativeId: input.initiativeId,
          name: `Plan: ${initiative.name}`,
          description: 'Plan initiative into phases',
          category: 'plan',
          status: 'in_progress',
        });
 
        const context = await gatherInitiativeContext(ctx.phaseRepository, ctx.taskRepository, ctx.pageRepository, input.initiativeId);
 
        const prompt = buildPlanPrompt();
 
        return agentManager.spawn({
          name: input.name,
          taskId: task.id,
          prompt,
          mode: 'plan',
          provider: input.provider,
          initiativeId: input.initiativeId,
          inputContext: {
            initiative,
            pages: context.pages.length > 0 ? context.pages : undefined,
            phases: context.phases.length > 0 ? context.phases : undefined,
            tasks: context.tasks.length > 0 ? context.tasks : undefined,
          },
        });
      }),
 
    spawnArchitectRefine: publicProcedure
      .input(z.object({
        name: z.string().min(1).optional(),
        initiativeId: z.string().min(1),
        instruction: z.string().optional(),
        provider: z.string().optional(),
      }))
      .mutation(async ({ ctx, input }) => {
        const agentManager = requireAgentManager(ctx);
        const initiativeRepo = requireInitiativeRepository(ctx);
        const pageRepo = requirePageRepository(ctx);
        const taskRepo = requireTaskRepository(ctx);
 
        const initiative = await initiativeRepo.findById(input.initiativeId);
        if (!initiative) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Initiative '${input.initiativeId}' not found`,
          });
        }
 
        // Bug #10: Auto-dismiss stale (crashed/idle) refine agents before checking for active ones
        const allAgents = await agentManager.list();
        const staleAgents = allAgents.filter(
          (a) =>
            a.mode === 'refine' &&
            a.initiativeId === input.initiativeId &&
            ['crashed', 'idle'].includes(a.status) &&
            !a.userDismissedAt,
        );
        for (const stale of staleAgents) {
          await agentManager.dismiss(stale.id);
        }
 
        // Bug #9: Prevent concurrent refine agents on the same initiative
        const activeRefineAgents = allAgents.filter(
          (a) =>
            a.mode === 'refine' &&
            a.initiativeId === input.initiativeId &&
            ['running', 'waiting_for_input'].includes(a.status),
        );
        if (activeRefineAgents.length > 0) {
          throw new TRPCError({
            code: 'CONFLICT',
            message: `A refine agent is already running for this initiative`,
          });
        }
 
        const pages = await pageRepo.findByInitiativeId(input.initiativeId);
 
        if (pages.length === 0) {
          throw new TRPCError({
            code: 'BAD_REQUEST',
            message: 'Initiative has no page content to refine',
          });
        }
 
        const task = await taskRepo.create({
          initiativeId: input.initiativeId,
          name: `Refine: ${initiative.name}`,
          description: input.instruction ?? 'Review and propose edits to initiative content',
          category: 'refine',
          status: 'in_progress',
        });
 
        const prompt = buildRefinePrompt();
 
        return agentManager.spawn({
          name: input.name,
          taskId: task.id,
          prompt,
          mode: 'refine',
          provider: input.provider,
          initiativeId: input.initiativeId,
          inputContext: { initiative, pages },
        });
      }),
 
    spawnArchitectDetail: publicProcedure
      .input(z.object({
        name: z.string().min(1).optional(),
        phaseId: z.string().min(1),
        taskName: z.string().min(1).optional(),
        context: z.string().optional(),
        provider: z.string().optional(),
      }))
      .mutation(async ({ ctx, input }) => {
        const agentManager = requireAgentManager(ctx);
        const phaseRepo = requirePhaseRepository(ctx);
        const taskRepo = requireTaskRepository(ctx);
        const initiativeRepo = requireInitiativeRepository(ctx);
 
        const phase = await phaseRepo.findById(input.phaseId);
        Iif (!phase) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Phase '${input.phaseId}' not found`,
          });
        }
        const initiative = await initiativeRepo.findById(phase.initiativeId);
        Iif (!initiative) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Initiative '${phase.initiativeId}' not found`,
          });
        }
 
        // Auto-dismiss stale detail agents for this phase
        const allAgents = await agentManager.list();
        const detailAgents = allAgents.filter(
          (a) => a.mode === 'detail' && !a.userDismissedAt,
        );
 
        // Look up tasks to find which phase each detail agent targets
        const activeForPhase: typeof detailAgents = [];
        const staleForPhase: typeof detailAgents = [];
        for (const agent of detailAgents) {
          Iif (!agent.taskId) continue;
          const agentTask = await taskRepo.findById(agent.taskId);
          if (agentTask?.phaseId !== input.phaseId) continue;
 
          if (['crashed', 'idle'].includes(agent.status)) {
            staleForPhase.push(agent);
          E} else if (['running', 'waiting_for_input'].includes(agent.status)) {
            activeForPhase.push(agent);
          }
        }
        for (const stale of staleForPhase) {
          await agentManager.dismiss(stale.id);
        }
        if (activeForPhase.length > 0) {
          throw new TRPCError({
            code: 'CONFLICT',
            message: `A detail agent is already running for phase "${phase.name}"`,
          });
        }
 
        const detailTaskName = input.taskName ?? `Detail: ${phase.name}`;
        const task = await taskRepo.create({
          phaseId: phase.id,
          initiativeId: phase.initiativeId,
          name: detailTaskName,
          description: input.context ?? `Detail phase "${phase.name}" into executable tasks`,
          category: 'detail',
          status: 'in_progress',
        });
 
        const context = await gatherInitiativeContext(ctx.phaseRepository, ctx.taskRepository, ctx.pageRepository, phase.initiativeId);
 
        const prompt = buildDetailPrompt();
 
        return agentManager.spawn({
          name: input.name,
          taskId: task.id,
          prompt,
          mode: 'detail',
          provider: input.provider,
          initiativeId: phase.initiativeId,
          inputContext: {
            initiative,
            phase,
            task,
            pages: context.pages.length > 0 ? context.pages : undefined,
            phases: context.phases.length > 0 ? context.phases : undefined,
            tasks: context.tasks.length > 0 ? context.tasks : undefined,
          },
        });
      }),
  };
}