From d6ea79073db00498bf7bd7c5c828d98c309e84e0 Mon Sep 17 00:00:00 2001 From: aperolschpritz Date: Sat, 3 Oct 2026 18:49:19 +0000 Subject: [PATCH 01/23] feat: allow apps and agents in the same project Remove Project Type so every Project can contain both Apps and Agents. - drop projectType column, enum, guards, and generated zod field - remove projectType from REST project write/response (breaking) - combine project workloads into one table and show Agents as graph nodes - gate Agent creation on Agent Sandbox add-on availability - update CONTEXT.md and add ADR-0010 --- CONTEXT.md | 26 +--- docs/adr/0010-unify-app-and-agent-projects.md | 14 ++ .../migration.sql | 14 ++ prisma/schema.prisma | 1 - src/__tests__/git-test-repositories.utils.ts | 1 - .../server/api/v1/api.integration.spec.ts | 15 +- .../v1/subitem-identity.integration.spec.ts | 36 ++--- .../services/agent-domain.integration.spec.ts | 2 +- .../agent-file-mount.integration.spec.ts | 2 +- .../services/agent-volume.integration.spec.ts | 2 +- .../agent.service.integration.spec.ts | 4 +- .../services/app.service.integration.spec.ts | 2 +- .../build.service.integration.spec.ts | 1 - ...-to-extended.migration.integration.spec.ts | 2 +- ...network-policy.service.integration.spec.ts | 2 - .../project-service.integration.spec.ts | 15 +- .../services/project-type.integration.spec.ts | 34 ----- .../volume-backup.service.integration.spec.ts | 12 +- .../agent-components/agent-table.tsx | 132 ------------------ .../[projectId]/app-components/apps-table.tsx | 92 ------------ .../app-components/project-network-graph.tsx | 111 ++++++++++----- .../project-network-graph-projection.ts | 33 ++++- .../use-project-network-graph.ts | 4 +- .../app-components/project-overview.tsx | 36 +++-- .../[projectId]/create-project-actions.tsx | 30 ++-- src/app/project/[projectId]/page.tsx | 44 +++--- .../project/[projectId]/workloads-table.tsx | 130 +++++++++++++++++ src/app/projects/actions.ts | 7 +- src/app/projects/edit-project-dialog.tsx | 49 ++----- src/app/projects/project-page.tsx | 6 +- src/app/projects/projects-table.tsx | 19 ++- .../integrations/llm-gateways/actions.ts | 6 - .../integrations/llm-gateways/page.tsx | 2 +- src/app/sidebar-client.tsx | 20 ++- src/server/api/v1/project/route.ts | 3 - ...gent-harness-opencode.service.unit.spec.ts | 2 +- .../agent-runtime.service.unit.spec.ts | 2 +- src/server/services/agent-template.service.ts | 5 +- .../agent-template.service.unit.spec.ts | 11 +- src/server/services/agent.service.ts | 8 -- .../services/agent.service.unit.spec.ts | 24 +--- src/server/services/app.service.ts | 7 - src/server/services/app.service.unit.spec.ts | 28 ++-- src/server/services/project.service.ts | 14 -- .../services/project.service.unit.spec.ts | 39 ++---- src/server/services/svc.service.unit.spec.ts | 1 - src/shared/model/generated-zod/project.ts | 1 - src/shared/model/project-type.model.ts | 6 - 48 files changed, 445 insertions(+), 612 deletions(-) create mode 100644 docs/adr/0010-unify-app-and-agent-projects.md create mode 100644 prisma/migrations/20261003090000_remove_project_type/migration.sql delete mode 100644 src/__tests__/integration/server/services/project-type.integration.spec.ts delete mode 100644 src/app/project/[projectId]/agent-components/agent-table.tsx delete mode 100644 src/app/project/[projectId]/app-components/apps-table.tsx create mode 100644 src/app/project/[projectId]/workloads-table.tsx delete mode 100644 src/shared/model/project-type.model.ts diff --git a/CONTEXT.md b/CONTEXT.md index 74da9303..ee9d7553 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -115,7 +115,7 @@ A configured domain that exposes an **App** through Traefik. _Avoid_: public app address, ingress rule **Project Network Graph**: -A visual representation of the effective traffic routes between the Apps and Agents visible from an **App Project**, including Traefik ingress permitted by each **App Domain** even when that App has Network Policies disabled. +A visual representation of the effective traffic routes between the Apps and Agents visible from a **Project**, including Traefik ingress permitted by each **App Domain** even when that App has Network Policies disabled. _Avoid_: network-policy-only graph, deployment topology **Agent**: @@ -178,12 +178,8 @@ _Avoid_: agent API key, model API key A model name exposed by an **LLM Gateway** for selection by an **Agent**. _Avoid_: provider model id when the LiteLLM alias is meant -**Project Type**: -The workload category a **Project** can contain: either App or Agent. -_Avoid_: mixed project, project mode - **Project Workload**: -The kind of deployable resource allowed by a **Project Type**. +A deployable resource contained in a **Project**: either an **App** or an **Agent**. _Avoid_: mixed workload, generic app **Volume**: @@ -218,14 +214,6 @@ _Avoid_: app permission when the workload may be an Agent A **Project Workload** whose runtime instance is ready to serve user interaction or traffic. _Avoid_: deployed when describing user-visible readiness -**App Project**: -A **Project** whose **Project Type** allows only **Apps**. -_Avoid_: normal project, container project - -**Agent Project**: -A **Project** whose **Project Type** allows only **Agents**. -_Avoid_: agent workspace, agent group - **Source**: The origin QuickStack uses to build or run an **App**. @@ -343,11 +331,9 @@ _Avoid_: manual initial port requirement ## Relationships - An **App** can have zero or one **Configured Source**. -- A **Project** has exactly one **Project Type**. -- A **Project Type** is assigned when a **Project** is created and cannot be changed later. -- An **App Project** can contain zero or more **Apps** and no **Agents**. -- An **Agent Project** can contain zero or more **Agents** and no **Apps**. -- An **Agent** belongs to exactly one **Agent Project**. +- A **Project** can contain zero or more **Apps** and zero or more **Agents**. +- An **App** belongs to exactly one **Project**. +- An **Agent** belongs to exactly one **Project**. - An **Agent** has exactly one **Agent Name**. - An **Agent** has exactly one **Agent Source**. - An **Agent** has exactly one **Agent Model Configuration**. @@ -359,7 +345,7 @@ _Avoid_: manual initial port requirement - A running **Agent** has exactly one **Agent Runtime Secret**. - An **Agent** uses exactly one **LLM Gateway**. - QuickStack uses a **LiteLLM Admin Key** to list **LiteLLM Model Aliases** and manage Agent virtual keys. -- A **Project Workload** means an **App** inside an **App Project** or an **Agent** inside an **Agent Project**. +- A **Project Workload** means an **App** or an **Agent** inside a **Project**. - A **Workload Permission** belongs to exactly one **Project Workload**. - An **App** can have zero or more **App Environment Variables**. - An **App** can have zero or more **App Build Arguments**. diff --git a/docs/adr/0010-unify-app-and-agent-projects.md b/docs/adr/0010-unify-app-and-agent-projects.md new file mode 100644 index 00000000..293004d5 --- /dev/null +++ b/docs/adr/0010-unify-app-and-agent-projects.md @@ -0,0 +1,14 @@ +# Let Projects Contain Both Apps and Agents + +A **Project** no longer has a **Project Type**. Every **Project** can contain zero or more **Apps** and zero or more **Agents** at the same time, so an App and an Agent Sandbox may share one Project. The `projectType` column, the `ProjectType` enum, the per-kind creation guards in the App, Agent, Agent Template, and LiteLLM Gateway code paths, and the `projectType` field of the REST project write and response models are removed. Creating an **Agent** stays gated by the availability of the Agent Sandbox Cluster Add-on, which is now the only capability gate. + +The network policy layer already supported mixed workloads: an App rule may target an App or an Agent, while an Agent egress rule may target an App only. This decision keeps that asymmetry — no Agent-to-Agent egress rule is introduced. The **Project Network Graph** now projects both Apps and Agents as nodes and draws App/Agent connections. + +## Consequences + +- Existing single-category Projects remain valid and silently become general Projects; no workload data migration is required because `App.projectId` and `Agent.projectId` already exist. Only the `projectType` column is dropped. +- The REST project write no longer requires `projectType`, and project responses no longer contain it. This is a breaking change for REST API clients that send or read the field. +- Workload permissions were already modelled on the generic **Project Workload**, so project-level and per-workload permissions are unchanged. +- A mixed Project shares one namespace, so App and Agent resources coexist in the same Kubernetes namespace; existing name prefixes remain sufficient to avoid collisions. +- The Project overview presents Apps and Agents in one combined workload table, and the graph shows Agent nodes. Clicking an Agent navigates to its detail page. +- Rejected alternatives: keeping `projectType` with an added `MIXED` value (keeps the category the change exists to remove) and replacing it with per-Project capability flags (unnecessary while Agent creation is gated only by the Cluster Add-on). diff --git a/prisma/migrations/20261003090000_remove_project_type/migration.sql b/prisma/migrations/20261003090000_remove_project_type/migration.sql new file mode 100644 index 00000000..2910f23e --- /dev/null +++ b/prisma/migrations/20261003090000_remove_project_type/migration.sql @@ -0,0 +1,14 @@ +-- RedefineTables +PRAGMA defer_foreign_keys=ON; +PRAGMA foreign_keys=OFF; +CREATE TABLE "new_Project" ( + "id" TEXT NOT NULL PRIMARY KEY, + "name" TEXT NOT NULL, + "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" DATETIME NOT NULL +); +INSERT INTO "new_Project" ("createdAt", "id", "name", "updatedAt") SELECT "createdAt", "id", "name", "updatedAt" FROM "Project"; +DROP TABLE "Project"; +ALTER TABLE "new_Project" RENAME TO "Project"; +PRAGMA foreign_keys=ON; +PRAGMA defer_foreign_keys=OFF; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index abd54f99..97a77f85 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -222,7 +222,6 @@ model RoleAgentPermission { model Project { id String @id @default(uuid()) name String - projectType String @default("APP") // APP, AGENT apps App[] agents Agent[] roleProjectPermissions RoleProjectPermission[] diff --git a/src/__tests__/git-test-repositories.utils.ts b/src/__tests__/git-test-repositories.utils.ts index de122b0f..24a5bb2c 100644 --- a/src/__tests__/git-test-repositories.utils.ts +++ b/src/__tests__/git-test-repositories.utils.ts @@ -39,7 +39,6 @@ export function createGitApp(input: Pick { const updatedProject = await expectApiJson( await apiFetch('/api/v1/projects', apiKey, { method: 'POST', - body: { id: createdProject.id, name: `${projectName} Updated`, projectType: 'APP' }, + body: { id: createdProject.id, name: `${projectName} Updated` }, }), ); expect(updatedProject).toMatchObject({ @@ -158,7 +158,7 @@ describe('REST API v1 integration', () => { it('create, read, update and delete agent through the api', async () => { const apiKey = await createAdminApiKey(); - const { createdProject } = await createApiProject(apiKey, 'AGENT'); + const { createdProject } = await createApiProject(apiKey); const gateway = await dataAccess.client.llmGateway.create({ data: { name: 'API Test Gateway', @@ -208,7 +208,6 @@ describe('REST API v1 integration', () => { modelAlias: ['gpt-4o'], project: { id: createdProject.id, - projectType: 'AGENT', }, llmGateway: { id: gateway.id, @@ -251,7 +250,7 @@ describe('REST API v1 integration', () => { it('returns sandbox access URL for existing agent domain', async () => { const apiKey = await createAdminApiKey(); - const { createdProject } = await createApiProject(apiKey, 'AGENT'); + const { createdProject } = await createApiProject(apiKey); const gateway = await dataAccess.client.llmGateway.create({ data: { name: 'API Access URL Gateway', @@ -300,7 +299,7 @@ describe('REST API v1 integration', () => { it('returns 400 when sandbox access URL is requested with unknown domain for agent', async () => { const apiKey = await createAdminApiKey(); - const { createdProject } = await createApiProject(apiKey, 'AGENT'); + const { createdProject } = await createApiProject(apiKey); const gateway = await dataAccess.client.llmGateway.create({ data: { name: 'API Missing Domain Gateway', @@ -417,14 +416,14 @@ async function createGitAppForProject(projectId: string, apiKey: string) { return createdApp as AppExtendedModel; } -async function createApiProject(apiKey: string, projectType: 'APP' | 'AGENT' = 'APP') { +async function createApiProject(apiKey: string) { const suffix = Date.now(); - const projectName = `API ${projectType} Project ${suffix}`; + const projectName = `API Project ${suffix}`; const createdProject = await expectApiJson( await apiFetch('/api/v1/projects', apiKey, { method: 'POST', - body: { name: projectName, projectType }, + body: { name: projectName }, }) ) as Project; expect(createdProject.name).toBe(projectName); diff --git a/src/__tests__/integration/server/api/v1/subitem-identity.integration.spec.ts b/src/__tests__/integration/server/api/v1/subitem-identity.integration.spec.ts index 0db0ca53..61998236 100644 --- a/src/__tests__/integration/server/api/v1/subitem-identity.integration.spec.ts +++ b/src/__tests__/integration/server/api/v1/subitem-identity.integration.spec.ts @@ -54,7 +54,7 @@ describe('REST API v1 integration - nested subitem identity', () => { it('strips nested App subitem ids when creating from a copied GET payload', async () => { const apiKey = await createAdminApiKey(); - const appProject = await createProject(apiKey, 'APP'); + const appProject = await createProject(apiKey); const sourceApp = await expectApiJson(await apiFetch('/api/v1/apps', apiKey, { method: 'POST', body: createAppPayload(undefined, appProject.id, 'API Source App'), @@ -104,7 +104,7 @@ describe('REST API v1 integration - nested subitem identity', () => { it('replaces all App subitem collections through the API', async () => { const apiKey = await createAdminApiKey(); - const project = await createProject(apiKey, 'APP'); + const project = await createProject(apiKey); const app = await expectApiJson(await apiFetch('/api/v1/apps', apiKey, { method: 'POST', body: createAppPayload(undefined, project.id, 'Full Schema Write App'), @@ -133,7 +133,7 @@ describe('REST API v1 integration - nested subitem identity', () => { it('preserves App network policy rule IDs when updating through the API', async () => { const apiKey = await createAdminApiKey(); - const project = await createProject(apiKey, 'APP'); + const project = await createProject(apiKey); const targetApp = await dataAccess.client.app.create({ data: { name: 'Policy Target App', projectId: project.id }, }); @@ -178,7 +178,7 @@ describe('REST API v1 integration - nested subitem identity', () => { it('rejects an App write when its network policy configuration is omitted', async () => { const apiKey = await createAdminApiKey(); - const project = await createProject(apiKey, 'APP'); + const project = await createProject(apiKey); const { appNetworkPolicy: _appNetworkPolicy, ...payload } = createAppPayload(undefined, project.id, 'Missing Policy App'); const problem = await expectApiProblem(await apiFetch('/api/v1/apps', apiKey, { @@ -191,7 +191,7 @@ describe('REST API v1 integration - nested subitem identity', () => { it('removes an App network policy configuration when the API receives null', async () => { const apiKey = await createAdminApiKey(); - const project = await createProject(apiKey, 'APP'); + const project = await createProject(apiKey); const app = await expectApiJson(await apiFetch('/api/v1/apps', apiKey, { method: 'POST', body: createAppPayload(undefined, project.id, 'Policy Removal App'), @@ -215,7 +215,7 @@ describe('REST API v1 integration - nested subitem identity', () => { it('rejects an App network policy configuration ID from another App through the API', async () => { const apiKey = await createAdminApiKey(); - const project = await createProject(apiKey, 'APP'); + const project = await createProject(apiKey); const app = await expectApiJson(await apiFetch('/api/v1/apps', apiKey, { method: 'POST', body: createAppPayload(undefined, project.id, 'Policy Owner App'), @@ -245,7 +245,7 @@ describe('REST API v1 integration - nested subitem identity', () => { it('rejects duplicate App network policy rules through the API', async () => { const apiKey = await createAdminApiKey(); - const project = await createProject(apiKey, 'APP'); + const project = await createProject(apiKey); const targetApp = await dataAccess.client.app.create({ data: { name: 'Policy Target App', projectId: project.id }, }); @@ -274,7 +274,7 @@ describe('REST API v1 integration - nested subitem identity', () => { it('rejects self-referencing App network policy rules through the API', async () => { const apiKey = await createAdminApiKey(); - const project = await createProject(apiKey, 'APP'); + const project = await createProject(apiKey); const app = await expectApiJson(await apiFetch('/api/v1/apps', apiKey, { method: 'POST', body: createAppPayload(undefined, project.id, 'Self Reference Source App'), @@ -302,8 +302,8 @@ describe('REST API v1 integration - nested subitem identity', () => { it('strips nested Agent subitem ids when creating from a copied GET payload', async () => { const apiKey = await createAdminApiKey(); - const agentProject = await createProject(apiKey, 'AGENT'); - const appProject = await createProject(apiKey, 'APP'); + const agentProject = await createProject(apiKey); + const appProject = await createProject(apiKey); const targetApp = await dataAccess.client.app.create({ data: { name: 'Policy Target App', projectId: appProject.id }, }); @@ -360,8 +360,8 @@ describe('REST API v1 integration - nested subitem identity', () => { it('rejects an Agent write when its network policy configuration is omitted', async () => { const apiKey = await createAdminApiKey(); - const agentProject = await createProject(apiKey, 'AGENT'); - const appProject = await createProject(apiKey, 'APP'); + const agentProject = await createProject(apiKey); + const appProject = await createProject(apiKey); const targetApp = await dataAccess.client.app.create({ data: { name: 'Policy Target App', projectId: appProject.id } }); const gateway = await dataAccess.client.llmGateway.create({ data: { name: 'Agent Policy Gateway', baseUrl: 'https://litellm.example.com', encryptedAdminKey: 'encrypted:test-key' }, @@ -378,8 +378,8 @@ describe('REST API v1 integration - nested subitem identity', () => { it('removes an Agent network policy configuration when the API receives null', async () => { const apiKey = await createAdminApiKey(); - const agentProject = await createProject(apiKey, 'AGENT'); - const appProject = await createProject(apiKey, 'APP'); + const agentProject = await createProject(apiKey); + const appProject = await createProject(apiKey); const targetApp = await dataAccess.client.app.create({ data: { name: 'Policy Target App', projectId: appProject.id } }); const gateway = await dataAccess.client.llmGateway.create({ data: { name: 'Agent Policy Gateway', baseUrl: 'https://litellm.example.com', encryptedAdminKey: 'encrypted:test-key' }, @@ -400,8 +400,8 @@ describe('REST API v1 integration - nested subitem identity', () => { it('rejects an Agent network policy configuration ID from another Agent through the API', async () => { const apiKey = await createAdminApiKey(); - const agentProject = await createProject(apiKey, 'AGENT'); - const appProject = await createProject(apiKey, 'APP'); + const agentProject = await createProject(apiKey); + const appProject = await createProject(apiKey); const targetApp = await dataAccess.client.app.create({ data: { name: 'Policy Target App', projectId: appProject.id } }); const gateway = await dataAccess.client.llmGateway.create({ data: { name: 'Agent Policy Gateway', baseUrl: 'https://litellm.example.com', encryptedAdminKey: 'encrypted:test-key' }, @@ -435,10 +435,10 @@ async function createAdminApiKey() { return restApiKeyService.create(user.id, 'integration-test'); } -async function createProject(apiKey: string, projectType: 'APP' | 'AGENT') { +async function createProject(apiKey: string) { return await expectApiJson(await apiFetch('/api/v1/projects', apiKey, { method: 'POST', - body: { name: `${projectType} Project ${crypto.randomUUID()}`, projectType }, + body: { name: `Project ${crypto.randomUUID()}` }, })) as Project; } diff --git a/src/__tests__/integration/server/services/agent-domain.integration.spec.ts b/src/__tests__/integration/server/services/agent-domain.integration.spec.ts index 90785847..a4315f24 100644 --- a/src/__tests__/integration/server/services/agent-domain.integration.spec.ts +++ b/src/__tests__/integration/server/services/agent-domain.integration.spec.ts @@ -21,7 +21,7 @@ describe('agent-domain.service', () => { // Create prerequisite records const project = await dataAccess.client.project.create({ - data: { name: 'Test Project', projectType: 'AGENT' }, + data: { name: 'Test Project' }, }); projectId = project.id; diff --git a/src/__tests__/integration/server/services/agent-file-mount.integration.spec.ts b/src/__tests__/integration/server/services/agent-file-mount.integration.spec.ts index 354a860b..199cf195 100644 --- a/src/__tests__/integration/server/services/agent-file-mount.integration.spec.ts +++ b/src/__tests__/integration/server/services/agent-file-mount.integration.spec.ts @@ -20,7 +20,7 @@ describe('agent-file-mount.service', () => { vi.clearAllMocks(); const project = await dataAccess.client.project.create({ - data: { name: 'Test Project', projectType: 'AGENT' }, + data: { name: 'Test Project' }, }); projectId = project.id; diff --git a/src/__tests__/integration/server/services/agent-volume.integration.spec.ts b/src/__tests__/integration/server/services/agent-volume.integration.spec.ts index f0a9c572..79e9baae 100644 --- a/src/__tests__/integration/server/services/agent-volume.integration.spec.ts +++ b/src/__tests__/integration/server/services/agent-volume.integration.spec.ts @@ -20,7 +20,7 @@ describe('agent-volume.service', () => { vi.clearAllMocks(); const project = await dataAccess.client.project.create({ - data: { name: 'Test Project', projectType: 'AGENT' }, + data: { name: 'Test Project' }, }); projectId = project.id; diff --git a/src/__tests__/integration/server/services/agent.service.integration.spec.ts b/src/__tests__/integration/server/services/agent.service.integration.spec.ts index 24049646..e589fa90 100644 --- a/src/__tests__/integration/server/services/agent.service.integration.spec.ts +++ b/src/__tests__/integration/server/services/agent.service.integration.spec.ts @@ -19,11 +19,11 @@ describe('agent.service integration - saveAgentExtendedModel', () => { beforeEach(async () => { const agentProject = await dataAccess.client.project.create({ - data: { name: 'Agent Project', projectType: 'AGENT' }, + data: { name: 'Agent Project' }, }); const appProject = await dataAccess.client.project.create({ - data: { name: 'App Project', projectType: 'APP' }, + data: { name: 'App Project' }, }); const gateway = await dataAccess.client.llmGateway.create({ diff --git a/src/__tests__/integration/server/services/app.service.integration.spec.ts b/src/__tests__/integration/server/services/app.service.integration.spec.ts index 9b655227..1947c2b8 100644 --- a/src/__tests__/integration/server/services/app.service.integration.spec.ts +++ b/src/__tests__/integration/server/services/app.service.integration.spec.ts @@ -22,7 +22,7 @@ describe('app.service integration - subitem ownership guards', () => { async function createProjectAndApps() { const project = await dataAccess.client.project.create({ - data: { name: 'App Project', projectType: 'APP' }, + data: { name: 'App Project' }, }); const sourceApp = await dataAccess.client.app.create({ data: { id: 'source-app', name: 'Source App', projectId: project.id }, diff --git a/src/__tests__/integration/server/services/build.service.integration.spec.ts b/src/__tests__/integration/server/services/build.service.integration.spec.ts index a8cec98b..f7b3a782 100644 --- a/src/__tests__/integration/server/services/build.service.integration.spec.ts +++ b/src/__tests__/integration/server/services/build.service.integration.spec.ts @@ -337,7 +337,6 @@ function createBuildApp(input: BuildIntegrationInput & { id: string; projectId: project: { id: input.projectId, name: input.projectId, - projectType: 'APP', createdAt: new Date(), updatedAt: new Date(), }, diff --git a/src/__tests__/integration/server/services/configuration-migrations/network-policy-to-extended.migration.integration.spec.ts b/src/__tests__/integration/server/services/configuration-migrations/network-policy-to-extended.migration.integration.spec.ts index 0cc902eb..fa2531ec 100644 --- a/src/__tests__/integration/server/services/configuration-migrations/network-policy-to-extended.migration.integration.spec.ts +++ b/src/__tests__/integration/server/services/configuration-migrations/network-policy-to-extended.migration.integration.spec.ts @@ -10,7 +10,7 @@ describe('network-policy-to-extended migration', () => { async function createProject(id: string) { return dataAccess.client.project.create({ - data: { id, name: id, projectType: 'APP' }, + data: { id, name: id }, }); } diff --git a/src/__tests__/integration/server/services/network-policy.service.integration.spec.ts b/src/__tests__/integration/server/services/network-policy.service.integration.spec.ts index bc00d4ca..de839242 100644 --- a/src/__tests__/integration/server/services/network-policy.service.integration.spec.ts +++ b/src/__tests__/integration/server/services/network-policy.service.integration.spec.ts @@ -236,7 +236,6 @@ function createNetworkPolicyApp(overrides: Pick { describe('save', () => { it('creates a new project in database', async () => { - await projectService.save({ name: 'Test Project', projectType: 'APP' }); + await projectService.save({ name: 'Test Project' }); const projectsDirectlyFromDatabase = await dbCtx.getDataAccess().client.project.findMany(); const projectsFromService = await projectService.getAll(); @@ -33,21 +33,20 @@ describe('project.service', () => { expect(projectsDirectlyFromDatabase).toHaveLength(1); expect(projectsDirectlyFromDatabase[0].name).toBe('Test Project'); - expect(projectsDirectlyFromDatabase[0].projectType).toBe('APP'); expect(projectsDirectlyFromDatabase[0].id).toMatch(/^proj-/); expect(revalidateTag).toHaveBeenCalledWith(Tags.projects()); }); it('creates a new namespace in k3s cluster', async () => { const projectName = 'Test Project 2'; - const savedProject = await projectService.save({ name: projectName, projectType: 'APP' }); + const savedProject = await projectService.save({ name: projectName }); const allNamespaces = await namespaceService.getNamespaces(); expect(allNamespaces.find(namespace => namespace === savedProject.id)).toBeTruthy(); }); it('updates an existing project', async () => { - const created = await projectService.save({ name: 'Initial Project', projectType: 'APP' }); + const created = await projectService.save({ name: 'Initial Project' }); const updated = await projectService.save({ id: created.id, @@ -69,8 +68,8 @@ describe('project.service', () => { describe('getAllProjects', () => { it('returns projects sorted by name asc', async () => { - await projectService.save({ name: 'Zulu', projectType: 'APP' }); - await projectService.save({ name: 'Alpha', projectType: 'APP' }); + await projectService.save({ name: 'Zulu' }); + await projectService.save({ name: 'Alpha' }); const projects = await projectService.getAll(); @@ -82,7 +81,7 @@ describe('project.service', () => { describe('getById', () => { it('returns an existing project by id', async () => { - const created = await projectService.save({ name: 'By Id Project', projectType: 'APP' }); + const created = await projectService.save({ name: 'By Id Project' }); const loaded = await projectService.getById(created.id); @@ -97,7 +96,7 @@ describe('project.service', () => { describe('deleteById', () => { it('deletes existing project and triggers side effects', async () => { - const created = await projectService.save({ name: 'Project To Delete', projectType: 'APP' }); + const created = await projectService.save({ name: 'Project To Delete' }); await projectService.deleteById(created.id); diff --git a/src/__tests__/integration/server/services/project-type.integration.spec.ts b/src/__tests__/integration/server/services/project-type.integration.spec.ts deleted file mode 100644 index a75e66d9..00000000 --- a/src/__tests__/integration/server/services/project-type.integration.spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -// @vitest-environment node - -import Database from 'better-sqlite3'; -import { readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; - -describe('Project Type persistence', () => { - it('migrates existing Projects to App Projects', () => { - const db = new Database(':memory:'); - db.exec(` - CREATE TABLE "Project" ( - "id" TEXT NOT NULL PRIMARY KEY, - "name" TEXT NOT NULL, - "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" DATETIME NOT NULL - ); - INSERT INTO "Project" ("id", "name", "updatedAt") - VALUES ('proj-existing', 'Existing Project', CURRENT_TIMESTAMP); - `); - - const migration = readFileSync( - resolve('prisma/migrations/20260622114500_add_project_type/migration.sql'), - 'utf8', - ); - db.exec(migration); - - const project = db.prepare( - 'SELECT "projectType" FROM "Project" WHERE "id" = ?', - ).get('proj-existing') as { projectType: string }; - - expect(project.projectType).toBe('APP'); - db.close(); - }); -}); diff --git a/src/__tests__/integration/server/services/volume-backup.service.integration.spec.ts b/src/__tests__/integration/server/services/volume-backup.service.integration.spec.ts index 56f40170..a718030f 100644 --- a/src/__tests__/integration/server/services/volume-backup.service.integration.spec.ts +++ b/src/__tests__/integration/server/services/volume-backup.service.integration.spec.ts @@ -87,7 +87,7 @@ describe('volume-backup.service pre-deployment backups integration', () => { } it('runs opted-in backups of the app and its directly connected apps in the same project', async () => { - const project = await dataAccess.client.project.create({ data: { name: 'P', projectType: 'APP' } }); + const project = await dataAccess.client.project.create({ data: { name: 'P' } }); const app = await createApp(project.id, 'app-target'); const connectedViaIncoming = await createApp(project.id, 'app-incoming'); const connectedViaOutgoing = await createApp(project.id, 'app-outgoing'); @@ -115,8 +115,8 @@ describe('volume-backup.service pre-deployment backups integration', () => { }); it('ignores connected apps from other projects', async () => { - const project = await dataAccess.client.project.create({ data: { name: 'P', projectType: 'APP' } }); - const otherProject = await dataAccess.client.project.create({ data: { name: 'Other', projectType: 'APP' } }); + const project = await dataAccess.client.project.create({ data: { name: 'P' } }); + const otherProject = await dataAccess.client.project.create({ data: { name: 'Other' } }); const app = await createApp(project.id, 'app-target'); const foreignApp = await createApp(otherProject.id, 'app-foreign'); @@ -132,7 +132,7 @@ describe('volume-backup.service pre-deployment backups integration', () => { }); it('aborts the deployment when a non-silent backup fails, after running the remaining backups', async () => { - const project = await dataAccess.client.project.create({ data: { name: 'P', projectType: 'APP' } }); + const project = await dataAccess.client.project.create({ data: { name: 'P' } }); const app = await createApp(project.id, 'app-target'); const base = Date.now(); @@ -155,7 +155,7 @@ describe('volume-backup.service pre-deployment backups integration', () => { }); it('continues the deployment when a silent backup fails', async () => { - const project = await dataAccess.client.project.create({ data: { name: 'P', projectType: 'APP' } }); + const project = await dataAccess.client.project.create({ data: { name: 'P' } }); const app = await createApp(project.id, 'app-target'); const failing = await createBackup(app.id, { createdAt: new Date(), backupBeforeDeployment: true, failSilently: true }); @@ -170,7 +170,7 @@ describe('volume-backup.service pre-deployment backups integration', () => { }); it('does nothing when no schedule opted in', async () => { - const project = await dataAccess.client.project.create({ data: { name: 'P', projectType: 'APP' } }); + const project = await dataAccess.client.project.create({ data: { name: 'P' } }); const app = await createApp(project.id, 'app-target'); await createBackup(app.id, { createdAt: new Date(), backupBeforeDeployment: false }); diff --git a/src/app/project/[projectId]/agent-components/agent-table.tsx b/src/app/project/[projectId]/agent-components/agent-table.tsx deleted file mode 100644 index d2ee2bfe..00000000 --- a/src/app/project/[projectId]/agent-components/agent-table.tsx +++ /dev/null @@ -1,132 +0,0 @@ -'use client'; - -import { SimpleDataTable } from "@/components/custom/simple-data-table"; -import { UserSession } from "@/shared/model/sim-session.model"; -import { AgentExtendedModel } from "@/shared/model/agent-extended.model"; -import { Bot, Edit2, Eye, MoreHorizontal, Trash } from "lucide-react"; -import { UserGroupUtils } from "@/shared/utils/role.utils"; -import CreateProjectActions from "../create-project-actions"; -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; -import { useConfirmDialog, useDialog } from "@/frontend/states/zustand.states"; -import { Toast } from "@/frontend/utils/toast.utils"; -import { deleteAgent } from "../actions"; -import { RenameAgentDialog } from "./rename-agent-dialog"; -import { - Empty, - EmptyContent, - EmptyDescription, - EmptyHeader, - EmptyMedia, - EmptyTitle, -} from "@/components/ui/empty"; - -interface AgentListClientProps { - agents: AgentExtendedModel[]; - session: UserSession; - projectId: string; -} - -export default function AgentListClient({ agents, session, projectId }: AgentListClientProps) { - const canCreate = UserGroupUtils.sessionCanCreateProjectWorkloadsForProject(session, projectId); - const canDelete = UserGroupUtils.sessionCanDeleteAgentsForProject(session, projectId); - const { openConfirmDialog } = useConfirmDialog(); - const { openDialog } = useDialog(); - - if (agents.length === 0 && !canCreate) { - return ( - - - - - - No Agents - - No agents available in this project. - - - - ); - } - - if (agents.length === 0) { - return ( - - - - - - No Agents yet - - Create your first Agent to get started. - - - - - - - ); - } - - return ( -
- ( - - {item.name} - - )], - ['llmGateway.name', 'LLM Gateway', true], - ['modelAlias', 'Model Aliases', true, (item: AgentExtendedModel) => item.modelAlias.join(', ')], - ['createdAt', 'Created', true, (item: AgentExtendedModel) => - new Date(item.createdAt).toLocaleDateString() - ], - ]} - data={agents} - actionCol={(item) => ( -
- - - Open menu - - } /> - - - Actions - - - - Show Agent Details - - - {canCreate && ( - openDialog(, { maxWidth: 'max-w-md' })}> - Rename Agent - - )} - {canDelete && ( - <> - - openConfirmDialog({ - title: "Delete Agent", - description: "Are you sure you want to delete this agent? All data will be lost and this action cannot be undone.", - }).then((result) => result ? Toast.fromAction(() => deleteAgent(item.id), 'Agent deleted successfully') : undefined)} - > - Delete Agent - - - )} - - -
- )} - tableIdentifier="agent-list" - /> -
- ); -} diff --git a/src/app/project/[projectId]/app-components/apps-table.tsx b/src/app/project/[projectId]/app-components/apps-table.tsx deleted file mode 100644 index b45a5bf9..00000000 --- a/src/app/project/[projectId]/app-components/apps-table.tsx +++ /dev/null @@ -1,92 +0,0 @@ -'use client' - -import { Button } from "@/components/ui/button"; - -import Link from "next/link"; -import { SimpleDataTable } from "@/components/custom/simple-data-table"; -import { formatDateTime } from "@/frontend/utils/format.utils"; -import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; -import { Edit2, Eye, MoreHorizontal, Trash } from "lucide-react"; -import { Toast } from "@/frontend/utils/toast.utils"; -import { AppExtendedModel } from "@/shared/model/app-extended.model"; -import { deleteApp } from "../actions"; -import { useConfirmDialog } from "@/frontend/states/zustand.states"; -import { EditAppDialog } from "./edit-app-dialog"; -import { UserSession } from "@/shared/model/sim-session.model"; -import { UserGroupUtils } from "@/shared/utils/role.utils"; -import PodStatusIndicator from "@/components/custom/pod-status-indicator"; -import { PathBuilderUtils } from "@/shared/utils/path-builder.utils"; - - -export default function AppTable({ - app: apps, - projectId, - session -}: { - app: AppExtendedModel[], - projectId: string, - session: UserSession -}) { - - const { openConfirmDialog: openDialog } = useConfirmDialog(); - const drawerHref = (appId: string) => - PathBuilderUtils.projectAppDrawer(projectId, appId, 'deployments', 'table'); - - return <> - - {item.name} - ], - ['sourceType', 'Source Type', false, (item) => item.sourceType === 'GIT' ? 'Git HTTPS' : item.sourceType === 'GIT_SSH' ? 'Git SSH' : 'Container'], - ['replicas', 'Replica Count', false], - ['memoryLimit', 'Memory Limit', false], - ['memoryReservation', 'Memory Reservation', false], - ['cpuLimit', 'CPU Limit', false], - ['cpuReservation', 'CPU Reservation', false], - ["createdAt", "Created At", true, (item) => formatDateTime(item.createdAt)], - ["updatedAt", "Updated At", false, (item) => formatDateTime(item.updatedAt)], - ['status', 'Status', true, (item) => ], - ]} - data={apps} - onItemClickLink={(item) => drawerHref(item.id)} - actionCol={(item) => - <> -
-
- - - Open menu - - } /> - - - Actions - - - - Show App Details - - - - {UserGroupUtils.sessionCanCreateNewAppsForProject(session, projectId) && - - - Edit App Name - - } - {UserGroupUtils.sessionCanDeleteAppsForProject(session, projectId) && openDialog({ - title: "Delete App", - description: "Are you sure you want to delete this app? All data will be lost and this action cannot be undone.", - }).then((result) => result ? Toast.fromAction(() => deleteApp(item.id)) : undefined)}> - Delete App - } - - -
- } - /> - -} diff --git a/src/app/project/[projectId]/app-components/project-network-graph.tsx b/src/app/project/[projectId]/app-components/project-network-graph.tsx index 0ed1efb4..aeb7a8d5 100644 --- a/src/app/project/[projectId]/app-components/project-network-graph.tsx +++ b/src/app/project/[projectId]/app-components/project-network-graph.tsx @@ -35,6 +35,7 @@ import PodStatusIndicator from '@/components/custom/pod-status-indicator'; import BuildStatusIndicator from '@/components/custom/build-status-indicator'; import { cn } from '@/frontend/utils/utils'; import type { AppExtendedModel } from '@/shared/model/app-extended.model'; +import type { AgentExtendedModel } from '@/shared/model/agent-extended.model'; import type { UserSession } from '@/shared/model/sim-session.model'; import { UserGroupUtils } from '@/shared/utils/role.utils'; import { RolePermissionEnum } from '@/shared/model/role-extended.model.ts'; @@ -57,6 +58,7 @@ import AppNetworkPolicyRuleDialog from '@/app/project/app/[appId]/advanced/app-n import { saveAppNetworkPolicyConfiguration } from '@/app/project/app/[appId]/advanced/actions'; import { deleteApp } from '@/app/project/[projectId]/actions'; import { EditAppDialog } from '@/app/project/[projectId]/app-components/edit-app-dialog'; +import { CreateAgentDialog } from '@/app/project/[projectId]/agent-components/create-agent-dialog'; import ChooseTemplateDialog from '@/app/project/[projectId]/choose-template-dialog'; import type { ProjectNetworkGraphPositions } from '@/shared/model/project-network-graph-layout.model'; import type { S3Target } from '@prisma/client'; @@ -86,6 +88,8 @@ type ConnectionEdgeData = { type ProjectNetworkGraphProps = { apps: AppExtendedModel[]; + agents: AgentExtendedModel[]; + agentsAvailable: boolean; projectId: string; session: UserSession; savedPositions: ProjectNetworkGraphPositions; @@ -95,6 +99,12 @@ type ProjectNetworkGraphProps = { gitSshPublicKeysByApp: Record; }; +function stripWorkloadPrefix(nodeId: string | undefined) { + if (!nodeId) return undefined; + const separatorIndex = nodeId.indexOf(':'); + return separatorIndex >= 0 ? nodeId.slice(separatorIndex + 1) : nodeId; +} + const WorkloadNode = memo(function WorkloadNode({ data, }: NodeProps>) { @@ -194,22 +204,24 @@ const edgeTypes = { connection: ConnectionEdge }; function ProjectNetworkGraphCanvasContextMenu({ projectId, canCreateApps, + canCreateAgents, children, }: { projectId: string; canCreateApps: boolean; + canCreateAgents: boolean; children: ReactNode; }) { const { openDialog } = useDialog(); - const openTemplateDialog = (templateType: 'database' | 'template') => { + const openTemplateDialog = (templateType: 'database' | 'template' | 'agent-template') => { openDialog( , { maxWidth: '1000px' }, ); }; - if (!canCreateApps) return children; + if (!canCreateApps && !canCreateAgents) return children; return ( @@ -217,20 +229,34 @@ function ProjectNetworkGraphCanvasContextMenu({ {children} - - - - Create Empty App + {canCreateApps && <> + + + + Create Empty App + + + openTemplateDialog('template')}> + + Create App from Template + + openTemplateDialog('database')}> + + Create Database + + } + {canCreateAgents && <> + + + + Create Empty Agent + + + openTemplateDialog('agent-template')}> + + Create Agent from Template - - openTemplateDialog('template')}> - - Create App from Template - - openTemplateDialog('database')}> - - Create Database - + } ); @@ -264,6 +290,8 @@ export default function ProjectNetworkGraph(props: ProjectNetworkGraphProps) { function ProjectNetworkGraphEditor({ apps, + agents, + agentsAvailable, projectId, session, savedPositions, @@ -290,9 +318,14 @@ function ProjectNetworkGraphEditor({ const graphApps = useMemo(() => apps.map(app => AppNetworkPolicyDraftUtils.applyToApp(app, drafts[app.id])), [apps, drafts]); const canEditLayout = UserGroupUtils.sessionHasWriteAccessToProject(session, projectId); const canCreateApps = UserGroupUtils.sessionCanCreateNewAppsForProject(session, projectId); - const { layout, saveNodePosition, resetLayout } = useProjectNetworkGraph(graphApps, projectId, savedPositions); + const canCreateAgents = agentsAvailable && UserGroupUtils.sessionCanCreateProjectWorkloadsForProject(session, projectId); + const { layout, saveNodePosition, resetLayout } = useProjectNetworkGraph(graphApps, agents, projectId, savedPositions); const dirty = Object.keys(drafts).some(appId => !AppNetworkPolicyDraftUtils.equals(drafts[appId], baseline[appId])); const localAppIds = useMemo(() => new Set(apps.map(app => app.id)), [apps]); + const localWorkloadIds = useMemo(() => new Set([ + ...apps.map(app => app.id), + ...agents.map(agent => agent.id), + ]), [apps, agents]); const drawerSession = useProjectNetworkGraphDrawerSession({ searchParams, appIds: localAppIds, @@ -322,13 +355,21 @@ function ProjectNetworkGraphEditor({ const cancelConnectionTargetLeave = () => { if (connectionTargetLeaveTimer.current) clearTimeout(connectionTargetLeaveTimer.current); }; - const selectableTargets: NetworkPolicySelectableTarget[] = apps.map(app => ({ - id: app.id, - name: app.name, - type: 'APP', - appType: app.appType, - project: { id: app.projectId, name: app.project.name }, - })); + const selectableTargets: NetworkPolicySelectableTarget[] = [ + ...apps.map(app => ({ + id: app.id, + name: app.name, + type: 'APP' as const, + appType: app.appType, + project: { id: app.projectId, name: app.project.name }, + })), + ...agents.map(agent => ({ + id: agent.id, + name: agent.name, + type: 'AGENT' as const, + project: { id: agent.projectId, name: agent.project.name }, + })), + ]; const updateDraft = useCallback((appId: string, update: (draft: AppNetworkPolicyDraft) => AppNetworkPolicyDraft) => { setDrafts(current => ({ ...current, [appId]: update(current[appId]) })); @@ -540,6 +581,7 @@ function ProjectNetworkGraphEditor({ { reactFlowRef.current = instance; }} @@ -560,20 +602,20 @@ function ProjectNetworkGraphEditor({ nodesConnectable elementsSelectable={false} isValidConnection={(connection: Connection) => { - const source = connection.source?.replace('APP:', ''); - const target = connection.target?.replace('APP:', ''); + const source = stripWorkloadPrefix(connection.source); + const target = stripWorkloadPrefix(connection.target); return connection.sourceHandle === 'source-egress' && connection.targetHandle === 'target-ingress' && !!source && !!target && source !== target && localAppIds.has(source) - && localAppIds.has(target) + && localWorkloadIds.has(target) && writable(source); }} onConnect={(connection: Connection) => { - const source = connection.source?.replace('APP:', ''); - const target = connection.target?.replace('APP:', ''); + const source = stripWorkloadPrefix(connection.source); + const target = stripWorkloadPrefix(connection.target); if (source && target) openConnectionDialog(source, target); }} onConnectStart={(_event, { nodeId, handleId }) => { @@ -591,9 +633,9 @@ function ProjectNetworkGraphEditor({ }} onNodeMouseEnter={(_event, node) => { cancelConnectionTargetLeave(); - const source = connectionSourceNodeId?.replace('APP:', ''); - const target = node.id.replace('APP:', ''); - if (source && source !== target && localAppIds.has(source) && localAppIds.has(target) && writable(source)) { + const source = stripWorkloadPrefix(connectionSourceNodeId); + const target = stripWorkloadPrefix(node.id); + if (source && target && source !== target && localAppIds.has(source) && localWorkloadIds.has(target) && writable(source)) { setConnectionTargetNodeId(node.id); } }} @@ -613,9 +655,12 @@ function ProjectNetworkGraphEditor({ } as CSSProperties} onNodeClick={(_event, node) => { const data = node.data as NetworkGraphNode; - if (data.kind !== 'INTERNET') { - drawerSession.selectNode(data); + if (data.kind === 'INTERNET') return; + if (data.kind === 'AGENT') { + router.push(`/project/agent/${stripWorkloadPrefix(data.id)}`); + return; } + drawerSession.selectNode(data); }} > diff --git a/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-projection.ts b/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-projection.ts index 7244c5d8..06580191 100644 --- a/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-projection.ts +++ b/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-projection.ts @@ -1,4 +1,5 @@ import type { AppExtendedModel } from '@/shared/model/app-extended.model'; +import type { AgentExtendedModel } from '@/shared/model/agent-extended.model'; import type { AppNetworkPolicyRuleProvenance } from '@/shared/utils/app-network-policy-draft.utils'; export type WorkloadType = 'APP' | 'AGENT'; @@ -104,9 +105,9 @@ function consolidateConnections(edges: NetworkGraphEdge[]) { } /** Projects effective App Network Policy Configuration and App Domain traffic into graph facts. */ -export function buildProjectNetworkGraph(apps: AppExtendedModel[]): ProjectNetworkGraphData { - const projectId = apps[0]?.projectId; - const internalAppIds = new Set(apps.map(app => app.id)); +export function buildProjectNetworkGraph(apps: AppExtendedModel[], agents: AgentExtendedModel[] = []): ProjectNetworkGraphData { + const projectId = apps[0]?.projectId ?? agents[0]?.projectId; + const internalWorkloadIds = new Set([...apps.map(app => app.id), ...agents.map(agent => agent.id)]); const nodes = new Map(); const edges = new Map(); const addNode = (node: NetworkGraphNode) => { if (!nodes.has(node.id)) nodes.set(node.id, node); }; @@ -138,7 +139,7 @@ export function buildProjectNetworkGraph(apps: AppExtendedModel[]): ProjectNetwo if (!target) continue; const targetType: WorkloadType = rule.targetApp ? 'APP' : 'AGENT'; const targetNodeId = workloadNodeId(targetType, target.id); - const external = targetType !== 'APP' || !internalAppIds.has(target.id); + const external = !internalWorkloadIds.has(target.id); addNode({ id: targetNodeId, kind: targetType, name: target.name, projectId: target.projectId, external, caption: external && target.projectId !== projectId ? 'Other project' : targetType === 'AGENT' ? 'Agent sandbox' : undefined, @@ -159,6 +160,30 @@ export function buildProjectNetworkGraph(apps: AppExtendedModel[]): ProjectNetwo for (const domain of app.appDomains) addEdge('INTERNET', appNodeId, 'INTERNET_INGRESS', `${domain.hostname}:${domain.port}`, false); } } + + for (const agent of agents) { + const agentNodeId = workloadNodeId('AGENT', agent.id); + addNode({ id: agentNodeId, kind: 'AGENT', name: agent.name, projectId: agent.projectId, external: false, caption: 'Agent sandbox' }); + + if (agent.agentNetworkPolicy) { + for (const rule of agent.agentNetworkPolicy.rules) { + const targetApp = rule.targetApp; + if (!targetApp) continue; + const targetNodeId = workloadNodeId('APP', targetApp.id); + const external = !internalWorkloadIds.has(targetApp.id); + addNode({ + id: targetNodeId, kind: 'APP', name: targetApp.name, projectId: targetApp.projectId, external, + caption: external && targetApp.projectId !== projectId ? 'Other project' : undefined, + }); + addEdge(agentNodeId, targetNodeId, 'EGRESS', formatRuleLabel(rule.port, rule.protocol), external); + } + if (agent.agentNetworkPolicy.allowInternetAccess !== false) { + addNode({ id: 'INTERNET', kind: 'INTERNET', name: 'Internet', external: false }); + addEdge(agentNodeId, 'INTERNET', 'INTERNET_EGRESS', '', false); + } + } + } + const rawEdges = Array.from(edges.values()).map(edge => ({ ...edge, labels: aggregateLabels(edge.labels) })); return { nodes: Array.from(nodes.values()), edges: consolidateConnections(rawEdges) }; } diff --git a/src/app/project/[projectId]/app-components/project-network-graph/use-project-network-graph.ts b/src/app/project/[projectId]/app-components/project-network-graph/use-project-network-graph.ts index 45fda7b5..2fd8da0b 100644 --- a/src/app/project/[projectId]/app-components/project-network-graph/use-project-network-graph.ts +++ b/src/app/project/[projectId]/app-components/project-network-graph/use-project-network-graph.ts @@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import ELK from 'elkjs/lib/elk.bundled.js'; import type { AppExtendedModel } from '@/shared/model/app-extended.model'; +import type { AgentExtendedModel } from '@/shared/model/agent-extended.model'; import { buildProjectNetworkGraph, type NetworkGraphNode, type ProjectNetworkGraphData } from './project-network-graph-projection'; import type { NetworkGraphPosition, ProjectNetworkGraphPositions } from '@/shared/model/project-network-graph-layout.model'; import { resetProjectNetworkGraphLayout, saveProjectNetworkGraphPosition } from '../../actions'; @@ -44,10 +45,11 @@ export function applySavedNetworkGraphPositions( export function useProjectNetworkGraph( apps: AppExtendedModel[], + agents: AgentExtendedModel[], projectId: string, savedPositions: ProjectNetworkGraphPositions, ) { - const graph = useMemo(() => buildProjectNetworkGraph(apps), [apps]); + const graph = useMemo(() => buildProjectNetworkGraph(apps, agents), [apps, agents]); const [layout, setLayout] = useState(); const requestId = useRef(0); const persistedPositions = useRef(savedPositions); diff --git a/src/app/project/[projectId]/app-components/project-overview.tsx b/src/app/project/[projectId]/app-components/project-overview.tsx index 8bcc34ec..ce2b7c78 100644 --- a/src/app/project/[projectId]/app-components/project-overview.tsx +++ b/src/app/project/[projectId]/app-components/project-overview.tsx @@ -1,7 +1,6 @@ 'use client'; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; -import AppTable from "./apps-table"; import ProjectNetworkGraph from "../app-components/project-network-graph"; import { UserSession } from "@/shared/model/sim-session.model"; import { useEffect, useState } from "react"; @@ -13,14 +12,18 @@ import CreateProjectActions from "../create-project-actions"; import PageTitle from "@/components/custom/page-title"; import { TabNavigationUtils } from "@/frontend/utils/tab-navigation.utils"; import { AppExtendedModel } from "@/shared/model/app-extended.model"; +import { AgentExtendedModel } from "@/shared/model/agent-extended.model"; import type { ProjectNetworkGraphPositions } from '@/shared/model/project-network-graph-layout.model'; -import { useDialog } from '@/frontend/states/zustand.states'; +import { useDialog } from "@/frontend/states/zustand.states"; import NewNetworkPolicyExplanationDialog from './new-network-policy-explanation-dialog'; import type { S3Target } from '@prisma/client'; import type { VolumeBackupExtendedModel } from '@/shared/model/volume-backup-extended.model'; +import WorkloadsTable from '../workloads-table'; interface ProjectOverviewProps { apps: AppExtendedModel[]; + agents: AgentExtendedModel[]; + agentsAvailable: boolean; session: UserSession; projectId: string; projectName: string; @@ -44,6 +47,8 @@ function tabStorageKey() { export default function AppProjectOverview({ apps, + agents, + agentsAvailable, session, projectId, projectName, @@ -89,19 +94,20 @@ export default function AppProjectOverview({ }; const canCreate = UserGroupUtils.sessionCanCreateProjectWorkloadsForProject(session, projectId); + const hasWorkloads = apps.length > 0 || agents.length > 0; - if (apps.length === 0 && !canCreate) { + if (!hasWorkloads && !canCreate) { return ( <> - + - No Apps + No Workloads - No apps available in this project. + No apps or agents available in this project. @@ -109,20 +115,20 @@ export default function AppProjectOverview({ ); } - if (apps.length === 0) { + if (!hasWorkloads) { return ( <> - - + + - No Apps yet + No Workloads yet - Create your first App to get started. + Create your first App or Agent to get started. @@ -132,7 +138,7 @@ export default function AppProjectOverview({ return ( - +
@@ -142,15 +148,17 @@ export default function AppProjectOverview({ - {canCreate && } + {canCreate && }
- +
{ openDialog( , @@ -38,22 +38,22 @@ export default function CreateProjectActions({ return ( <> - Create {isAgentProject ? 'Agent' : 'App'}} /> + Create} /> - {isAgentProject ? ( + Apps + + Empty App + + openTemplateDialog('database')}> Database + openTemplateDialog('template')}> App Template + {agentsAvailable && ( <> + + Agents Empty Agent - openTemplateDialog('agent-template')}> Template - - ) : ( - <> - - Empty App - - openTemplateDialog('database')}> Database - openTemplateDialog('template')}> Template + openTemplateDialog('agent-template')}> Agent Template )} diff --git a/src/app/project/[projectId]/page.tsx b/src/app/project/[projectId]/page.tsx index ed7bdb3b..d3ef6cbc 100644 --- a/src/app/project/[projectId]/page.tsx +++ b/src/app/project/[projectId]/page.tsx @@ -5,18 +5,16 @@ import projectService from "@/server/services/project.service"; import AppProjectOverview from "./app-components/project-overview"; import appService from "@/server/services/app.service"; import agentService from "@/server/services/agent.service"; -import PageTitle from "@/components/custom/page-title"; import ProjectBreadcrumbs from "./project-breadcrumbs"; -import CreateProjectActions from "./create-project-actions"; import { UserGroupUtils } from "@/shared/utils/role.utils"; -import AgentListClient from "./agent-components/agent-table"; import projectNetworkGraphLayoutService from '@/server/services/project-network-graph-layout.service'; import { ensureReadProject, RequesterIdentity } from '@/server/utils/shared-authorization.utils'; -import paramService, { ParamService } from '@/server/services/param.service'; -import s3TargetService from '@/server/services/s3-target.service'; -import volumeBackupService from '@/server/services/volume-backup.service'; -import clusterService from '@/server/services/cluster.service'; -import appGitSshKeyService from '@/server/services/app-git-ssh-key.service'; +import paramService, { ParamService } from "@/server/services/param.service"; +import s3TargetService from "@/server/services/s3-target.service"; +import volumeBackupService from "@/server/services/volume-backup.service"; +import clusterService from "@/server/services/cluster.service"; +import appGitSshKeyService from "@/server/services/app-git-ssh-key.service"; +import agentSandboxAddonService from "@/server/services/addons/agent-sandbox-addon.service"; export default async function AppsPage({ params @@ -34,29 +32,17 @@ export default async function AppsPage({ const identity: RequesterIdentity = { type: 'session', session }; ensureReadProject(identity, projectId); const project = await projectService.getById(projectId); - const isAgentProject = project.projectType === 'AGENT'; + const agentsAvailable = await agentSandboxAddonService.isAvailable(); - if (isAgentProject) { - const agents = await agentService.getAllByProjectId(projectId); - const relevantAgents = agents.filter((agent) => - UserGroupUtils.sessionHasReadAccessForAgent(session, agent.id)); - return ( -
- - {UserGroupUtils.sessionCanCreateProjectWorkloadsForProject(session, projectId) && - } - - - -
- ); - } - - const data = await appService.getAllAppsByProjectId(projectId); + const [data, agents] = await Promise.all([ + appService.getAllAppsByProjectId(projectId), + agentService.getAllByProjectId(projectId), + ]); const relevantApps = data.filter((app) => UserGroupUtils.sessionHasReadAccessForApp(session, app.id)); + const relevantAgents = agents.filter((agent) => + UserGroupUtils.sessionHasReadAccessForAgent(session, agent.id)); + const [ networkGraphPositions, hasAcknowledgedNewNetworkPolicyExplanation, @@ -84,6 +70,8 @@ export default async function AppsPage({ ({ kind: 'APP' as const, ...app })), + ...agents.map((agent) => ({ kind: 'AGENT' as const, ...agent })), + ]; + + const workloadHref = (item: WorkloadRow) => item.kind === 'AGENT' + ? `/project/agent/${item.id}` + : PathBuilderUtils.projectAppDrawer(projectId, item.id, 'deployments', 'table'); + + return ( + + {item.name} + + )], + ['kind', 'Type', true, (item: WorkloadRow) => item.kind === 'AGENT' ? 'Agent' : 'App'], + ['status', 'Status', true, (item: WorkloadRow) => item.kind === 'APP' + ? + : {item.warmPoolReplicas} warm], + ['sourceType', 'Source Type', false], + ['llmGateway', 'LLM Gateway', false, (item: WorkloadRow) => item.kind === 'AGENT' ? item.llmGateway.name : ''], + ['modelAlias', 'Model Aliases', false, (item: WorkloadRow) => item.kind === 'AGENT' ? item.modelAlias.join(', ') : ''], + ['createdAt', 'Created At', true, (item: WorkloadRow) => formatDateTime(item.createdAt)], + ['updatedAt', 'Updated At', false, (item: WorkloadRow) => formatDateTime(item.updatedAt)], + ]} + data={data} + actionCol={(item) => ( +
+ + + Open menu + + } /> + + + Actions + + + + Show {item.kind === 'AGENT' ? 'Agent' : 'App'} Details + + + {item.kind === 'APP' ? ( + <> + {canCreateApps && ( + + + Edit App Name + + + )} + {canDeleteApps && ( + openConfirmDialog({ + title: "Delete App", + description: "Are you sure you want to delete this app? All data will be lost and this action cannot be undone.", + }).then((result) => result ? Toast.fromAction(() => deleteApp(item.id)) : undefined)}> + Delete App + + )} + + ) : ( + <> + {canCreateAgents && ( + openDialog(, { maxWidth: 'max-w-md' })}> + Rename Agent + + )} + {canDeleteAgents && ( + openConfirmDialog({ + title: "Delete Agent", + description: "Are you sure you want to delete this agent? All data will be lost and this action cannot be undone.", + }).then((result) => result ? Toast.fromAction(() => deleteAgent(item.id), 'Agent deleted successfully') : undefined)}> + Delete Agent + + )} + + )} + + +
+ )} + tableIdentifier="workload-list" + />; +} diff --git a/src/app/projects/actions.ts b/src/app/projects/actions.ts index 2672bf1e..3eb97942 100644 --- a/src/app/projects/actions.ts +++ b/src/app/projects/actions.ts @@ -4,21 +4,18 @@ import { SuccessActionResult } from "@/shared/model/server-action-error-return.m import projectService from "@/server/services/project.service"; import { getAdminUserSession, saveFormAction, simpleAction } from "@/server/utils/action-wrapper.utils"; import { z } from "zod"; -import { ProjectTypeModel } from "@/shared/model/project-type.model"; const createProjectSchema = z.object({ projectName: z.string().min(1), - projectType: ProjectTypeModel, projectId: z.string().optional() }); -export const createProject = async (projectName: string, projectType: string, projectId?: string) => - saveFormAction({ projectName, projectType, projectId }, createProjectSchema, async (validatedData) => { +export const createProject = async (projectName: string, projectId?: string) => + saveFormAction({ projectName, projectId }, createProjectSchema, async (validatedData) => { await getAdminUserSession(); await projectService.save({ id: validatedData.projectId ?? undefined, name: validatedData.projectName, - projectType: validatedData.projectType, }); return new SuccessActionResult(undefined, "Project created successfully."); }); diff --git a/src/app/projects/edit-project-dialog.tsx b/src/app/projects/edit-project-dialog.tsx index 58d1a317..9e8e12f5 100644 --- a/src/app/projects/edit-project-dialog.tsx +++ b/src/app/projects/edit-project-dialog.tsx @@ -9,34 +9,22 @@ import { } from '@/components/ui/dialog'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from '@/components/ui/select'; import { Toast } from '@/frontend/utils/toast.utils'; import { useDialogContext } from '@/frontend/states/dialog-context'; import { useDialog } from '@/frontend/states/zustand.states'; -import { ProjectType } from '@/shared/model/project-type.model'; import { Project } from '@prisma/client'; import { useState } from 'react'; import { createProject } from './actions'; -function EditProjectForm({ existingItem, agentsAvailable }: { +function EditProjectForm({ existingItem }: { existingItem?: Project; - agentsAvailable: boolean; }) { const { closeDialog } = useDialogContext(); const [name, setName] = useState(existingItem?.name ?? ''); - const [projectType, setProjectType] = useState( - agentsAvailable ? existingItem?.projectType as ProjectType | undefined : 'APP', - ); const submit = async () => { - if (!name.trim() || !projectType) return; - await Toast.fromAction(() => createProject(name.trim(), projectType, existingItem?.id)); + if (!name.trim()) return; + await Toast.fromAction(() => createProject(name.trim(), existingItem?.id)); closeDialog(); }; @@ -45,8 +33,8 @@ function EditProjectForm({ existingItem, agentsAvailable }: { {existingItem ? 'Edit Project' : 'Create Project'} {existingItem - ? 'Rename this Project. Project Type cannot be changed.' - : 'Choose the workload type this Project will contain.'} + ? 'Rename this Project.' + : 'Projects can contain both Apps and Agent Sandboxes.'}
@@ -58,29 +46,9 @@ function EditProjectForm({ existingItem, agentsAvailable }: { onChange={(event) => setName(event.target.value)} />
-
- - -
- @@ -88,15 +56,14 @@ function EditProjectForm({ existingItem, agentsAvailable }: { ; } -export function EditProjectDialog({ children, existingItem, agentsAvailable }: { +export function EditProjectDialog({ children, existingItem }: { children?: React.ReactNode; existingItem?: Project; - agentsAvailable: boolean; }) { const { openDialog } = useDialog(); const handleOpen = () => { - openDialog(, { maxWidth: '425px' }); + openDialog(, { maxWidth: '425px' }); }; return
{children}
; diff --git a/src/app/projects/project-page.tsx b/src/app/projects/project-page.tsx index e492e4fd..57b28859 100644 --- a/src/app/projects/project-page.tsx +++ b/src/app/projects/project-page.tsx @@ -9,13 +9,11 @@ import { EditProjectDialog } from "./edit-project-dialog"; import ProjectsBreadcrumbs from "./projects-breadcrumbs"; import { Plus } from "lucide-react"; import { UserGroupUtils } from "@/shared/utils/role.utils"; -import agentSandboxAddonService from "@/server/services/addons/agent-sandbox-addon.service"; export default async function ProjectPage() { const session = await getAuthUserSession(); const data = await projectService.getAllWithCounts(); - const agentsAvailable = await agentSandboxAddonService.isAvailable(); const relevantProjectsForUser = data.filter((project) => UserGroupUtils.sessionHasReadAccessToProject(session, project.id)); @@ -23,11 +21,11 @@ export default async function ProjectPage() {

Projects

- {UserGroupUtils.isAdmin(session) && + {UserGroupUtils.isAdmin(session) && }
- +
) diff --git a/src/app/projects/projects-table.tsx b/src/app/projects/projects-table.tsx index e0e8afb8..2a03ace7 100644 --- a/src/app/projects/projects-table.tsx +++ b/src/app/projects/projects-table.tsx @@ -13,15 +13,13 @@ import { useConfirmDialog } from "@/frontend/states/zustand.states"; import { EditProjectDialog } from "./edit-project-dialog"; import { UserSession } from "@/shared/model/sim-session.model"; import { UserGroupUtils } from "@/shared/utils/role.utils"; -import ProjectStatusIndicator from "@/components/custom/project-status-indicator"; import { ProjectWithCountsModel } from "@/shared/model/project-extended.model"; import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty"; -export default function ProjectsTable({ data, session, agentsAvailable }: { +export default function ProjectsTable({ data, session }: { data: ProjectWithCountsModel[]; session: UserSession; - agentsAvailable: boolean; }) { const { openConfirmDialog: openDialog } = useConfirmDialog(); @@ -68,7 +66,7 @@ export default function ProjectsTable({ data, session, agentsAvailable }: { - + @@ -85,10 +83,11 @@ export default function ProjectsTable({ data, session, agentsAvailable }: { {item.name} )], - ['projectType', 'Type', true, (item) => item.projectType === 'AGENT' ? 'Agent' : 'App'], - ['status', 'Status', true, (item) => item.projectType === 'APP' - ? - : {item._count.agents === 0 ? 'No Agents' : item._count.agents + ' Agents'}], + ['workloads', 'Workloads', true, (item) => ( + + {item._count.apps} {item._count.apps === 1 ? 'App' : 'Apps'}, {item._count.agents} {item._count.agents === 1 ? 'Agent' : 'Agents'} + + )], ["createdAt", "Created At", true, (item) => formatDateTime(item.createdAt)], ["updatedAt", "Updated At", false, (item) => formatDateTime(item.updatedAt)], ]} @@ -109,12 +108,12 @@ export default function ProjectsTable({ data, session, agentsAvailable }: { - Show {item.projectType === 'AGENT' ? 'Agents' : 'Apps'} of Project + Show Workloads of Project {UserGroupUtils.isAdmin(session) && <> - + Edit Project Name diff --git a/src/app/settings/integrations/llm-gateways/actions.ts b/src/app/settings/integrations/llm-gateways/actions.ts index d13607b1..1ea345bb 100644 --- a/src/app/settings/integrations/llm-gateways/actions.ts +++ b/src/app/settings/integrations/llm-gateways/actions.ts @@ -58,7 +58,6 @@ export const deployLiteLlmGatewayInstance = async (inputData: z.infer todo: updatein future when new network policy is implemented for apps diff --git a/src/app/settings/integrations/llm-gateways/page.tsx b/src/app/settings/integrations/llm-gateways/page.tsx index 4ea9fb85..c35fcc9c 100644 --- a/src/app/settings/integrations/llm-gateways/page.tsx +++ b/src/app/settings/integrations/llm-gateways/page.tsx @@ -21,7 +21,7 @@ export default async function LlmGatewaysPage() { - project.projectType === 'APP')}> + diff --git a/src/app/sidebar-client.tsx b/src/app/sidebar-client.tsx index 95d7937f..8ef0c1c6 100644 --- a/src/app/sidebar-client.tsx +++ b/src/app/sidebar-client.tsx @@ -150,16 +150,17 @@ export function SidebarCient({ Projects } /> - {UserGroupUtils.isAdmin(session) && + {UserGroupUtils.isAdmin(session) && } {projects.map((item) => { - const isAgentProject = item.projectType === 'AGENT'; - const workloads = isAgentProject ? (item.agents || []) : item.apps; - const currentlySelectedWorkloadId = isAgentProject ? currentlySelectedAgentId : currentlySelectedAppId; + const workloads = [ + ...(item.apps || []).map(app => ({ ...app, kind: 'APP' as const })), + ...(item.agents || []).map(agent => ({ ...agent, kind: 'AGENT' as const })), + ]; return ( @@ -181,9 +182,14 @@ export function SidebarCient({ align={isMobile ? "end" : "start"} className="min-w-56 rounded-lg" > - {workloads.map((workload) => ( - {workload.name}} /> - ))} + {workloads.map((workload) => { + const isSelected = workload.kind === 'AGENT' + ? currentlySelectedAgentId === workload.id + : currentlySelectedAppId === workload.id; + return ( + {workload.name}} /> + ); + })} ) : null} diff --git a/src/server/api/v1/project/route.ts b/src/server/api/v1/project/route.ts index cd7eb80a..385dd934 100644 --- a/src/server/api/v1/project/route.ts +++ b/src/server/api/v1/project/route.ts @@ -7,13 +7,11 @@ import { ProjectModel } from '@/shared/model/generated-zod'; import { ApiUtils } from '../../../utils/api-response.utils'; import { Project } from '@prisma/client'; import { ApiNotFoundException, ApiUnauthorizedException } from '@/shared/model/service.exception.model'; -import { ProjectTypeModel } from '@/shared/model/project-type.model'; const projectWriteSchema = ProjectModel .omit({ createdAt: true, updatedAt: true }) .extend({ id: z.string().optional(), - projectType: ProjectTypeModel, }); export const projectRoutes = new Elysia() @@ -64,7 +62,6 @@ export const projectRoutes = new Elysia() return await projectService.save({ id: existing?.id, name: body.name, - projectType: body.projectType, }); }, { body: projectWriteSchema, diff --git a/src/server/services/agent-harness-opencode.service.unit.spec.ts b/src/server/services/agent-harness-opencode.service.unit.spec.ts index a1f46edc..df94a4fc 100644 --- a/src/server/services/agent-harness-opencode.service.unit.spec.ts +++ b/src/server/services/agent-harness-opencode.service.unit.spec.ts @@ -48,7 +48,7 @@ function makeAgent(overrides: Partial = {}): AgentExtendedMo warmPoolReplicas: 0, createdAt: new Date('2026-01-01T00:00:00Z'), updatedAt: new Date('2026-01-01T00:00:00Z'), - project: { id: 'proj-test-agent', name: 'Project', projectType: 'AGENT', createdAt: new Date('2026-01-01T00:00:00Z'), updatedAt: new Date('2026-01-01T00:00:00Z') }, + project: { id: 'proj-test-agent', name: 'Project', createdAt: new Date('2026-01-01T00:00:00Z'), updatedAt: new Date('2026-01-01T00:00:00Z') }, llmGateway: { baseUrl: 'https://litellm.example.com' }, agentDomains: [], agentVolumes: [], diff --git a/src/server/services/agent-runtime.service.unit.spec.ts b/src/server/services/agent-runtime.service.unit.spec.ts index 9109a159..8552dad3 100644 --- a/src/server/services/agent-runtime.service.unit.spec.ts +++ b/src/server/services/agent-runtime.service.unit.spec.ts @@ -71,7 +71,7 @@ import agentRuntimeService from './agent-runtime.service'; import { ServiceException } from '@/shared/model/service.exception.model'; const AGENT_ID = 'agent-test-runner'; -const PROJECT = { id: 'proj-1', name: 'test-project', projectType: 'AGENT' }; +const PROJECT = { id: 'proj-1', name: 'test-project' }; const GATEWAY = { id: 'gw-1', name: 'My Gateway', baseUrl: 'https://litellm.example.com', encryptedAdminKey: 'encrypted:adminkey' }; const SANDBOX_NAMESPACE = 'proj-1'; const USER_ID = 'user-123'; diff --git a/src/server/services/agent-template.service.ts b/src/server/services/agent-template.service.ts index dd684614..c6c61072 100644 --- a/src/server/services/agent-template.service.ts +++ b/src/server/services/agent-template.service.ts @@ -79,14 +79,11 @@ class AgentTemplateService { return await dataAccess.client.$transaction(async (tx) => { const project = await tx.project.findUnique({ where: { id: projectId }, - select: { id: true, projectType: true }, + select: { id: true }, }); if (!project) { throw new ServiceException("Project not found."); } - if (project.projectType !== "AGENT") { - throw new ServiceException("Agent templates can only be created in Agent Projects."); - } const createdAgents: AgentExtendedModel[] = []; const context = { diff --git a/src/server/services/agent-template.service.unit.spec.ts b/src/server/services/agent-template.service.unit.spec.ts index 89703f19..35a10344 100644 --- a/src/server/services/agent-template.service.unit.spec.ts +++ b/src/server/services/agent-template.service.unit.spec.ts @@ -99,12 +99,11 @@ import agentTemplateService from "./agent-template.service"; import namespaceService from "./namespace.service"; import { opencodeAgentTemplate } from "@/shared/templates/agents/opencode.template"; import { geminiCliAgentTemplate } from "@/shared/templates/agents/gemini-cli.template"; -import { ServiceException } from "@/shared/model/service.exception.model"; describe("agent-template.service", () => { beforeEach(() => { vi.clearAllMocks(); - dbProjectMocks.findUnique.mockResolvedValue({ id: "project-1", projectType: "AGENT" }); + dbProjectMocks.findUnique.mockResolvedValue({ id: "project-1" }); dbGatewayMocks.findUnique.mockResolvedValue({ id: "gateway-1", baseUrl: "https://litellm.example" }); dbAgentMocks.findUnique.mockResolvedValue(null); dbAgentMocks.create.mockResolvedValue({ id: "agent-opencode", projectId: "project-1" }); @@ -152,7 +151,7 @@ describe("agent-template.service", () => { healthCheckPeriodSeconds: 15, healthCheckTimeoutSeconds: 5, healthCheckFailureThreshold: 3, - project: { id: "project-1", projectType: "AGENT" }, + project: { id: "project-1" }, llmGateway: { id: "gateway-1", baseUrl: "https://litellm.example" }, agentDomains: [], agentVolumes: [], @@ -218,14 +217,14 @@ describe("agent-template.service", () => { expect(namespaceService.createNamespaceIfNotExists).toHaveBeenCalledWith("project-1"); }); - it("rejects non-agent projects", async () => { - dbProjectMocks.findUnique.mockResolvedValue({ id: "project-1", projectType: "APP" }); + it("rejects a missing project", async () => { + dbProjectMocks.findUnique.mockResolvedValue(null); const template = structuredClone(opencodeAgentTemplate); template.templates[0].llmGatewayId = "gateway-1"; template.templates[0].modelAlias = ["gpt-4o"]; await expect(agentTemplateService.createAgentFromTemplate("project-1", template)) - .rejects.toThrow(ServiceException); + .rejects.toThrow("Project not found."); expect(dbAgentMocks.create).not.toHaveBeenCalled(); expect(dbAgentMocks.update).not.toHaveBeenCalled(); }); diff --git a/src/server/services/agent.service.ts b/src/server/services/agent.service.ts index 4e44b7f3..6eb311ef 100644 --- a/src/server/services/agent.service.ts +++ b/src/server/services/agent.service.ts @@ -250,14 +250,6 @@ class AgentService { } if (isCreate) { - const project = await tx.project.findUnique({ - where: { id: data.projectId as string }, - select: { projectType: true }, - }); - if (!project || project.projectType !== 'AGENT') { - throw new ServiceException("Agents can only be created in Agent Projects."); - } - savedItem = await tx.agent.create({ data: { id: KubeObjectNameUtils.toAgentId(data.name as string), diff --git a/src/server/services/agent.service.unit.spec.ts b/src/server/services/agent.service.unit.spec.ts index cf4e5c1b..5b9e8e85 100644 --- a/src/server/services/agent.service.unit.spec.ts +++ b/src/server/services/agent.service.unit.spec.ts @@ -228,7 +228,7 @@ function mockAgent(id: string, name: string, projectId: string = 'proj-test-agen function mockAgentWithRelations(id: string, name: string, projectId: string = 'proj-test-agent', overrides: Record = {}) { return { ...mockAgent(id, name, projectId), - project: { id: projectId, name: 'Test Project', projectType: 'AGENT' }, + project: { id: projectId, name: 'Test Project' }, llmGateway: { id: 'gateway-1', name: 'Test Gateway', baseUrl: 'https://litellm.example.com', encryptedAdminKey: 'encrypted:gw-key' }, ...overrides, }; @@ -259,7 +259,6 @@ describe('agent.service', () => { vi.mocked(ingressService.deleteAgentIngress).mockResolvedValue(undefined); vi.mocked(ingressService.createOrUpdateAgentIngress).mockResolvedValue(undefined); vi.mocked(secretService.getDecodedSecret).mockResolvedValue(null); - vi.mocked(dataAccess.client.project.findUnique).mockResolvedValue({ projectType: 'AGENT' } as any); }); describe('saveAgent', () => { @@ -283,23 +282,6 @@ describe('agent.service', () => { modelAlias: JSON.stringify(['gpt-4o']), }), }); - expect(dataAccess.client.project.findUnique).toHaveBeenCalledWith({ - where: { id: 'proj-test-agent' }, - select: { projectType: true }, - }); - }); - - it('rejects creates in non-Agent projects', async () => { - vi.mocked(dataAccess.client.project.findUnique).mockResolvedValue({ projectType: 'APP' } as any); - - await expect(agentService.saveAgent({ - name: 'My Agent', - projectId: 'proj-test-agent', - llmGatewayId: 'gateway-1', - modelAlias: ['gpt-4o'], - })).rejects.toThrow('Agents can only be created in Agent Projects.'); - - expect(dataAccess.client.agent.create).not.toHaveBeenCalled(); }); it('updates an existing agent when id is provided', async () => { @@ -324,8 +306,8 @@ describe('agent.service', () => { describe('getAll', () => { it('returns all agents with relations sorted by project and name', async () => { const agents = [ - mockAgentWithRelations('agent-z', 'Zulu', 'project-b', { project: { id: 'project-b', name: 'Beta', projectType: 'AGENT' } }), - mockAgentWithRelations('agent-a', 'Alpha', 'project-a', { project: { id: 'project-a', name: 'Alpha', projectType: 'AGENT' } }), + mockAgentWithRelations('agent-z', 'Zulu', 'project-b', { project: { id: 'project-b', name: 'Beta' } }), + mockAgentWithRelations('agent-a', 'Alpha', 'project-a', { project: { id: 'project-a', name: 'Alpha' } }), ]; vi.mocked(dataAccess.client.agent.findMany).mockResolvedValue(agents as any); diff --git a/src/server/services/app.service.ts b/src/server/services/app.service.ts index f91a2a59..dc1a0705 100644 --- a/src/server/services/app.service.ts +++ b/src/server/services/app.service.ts @@ -242,13 +242,6 @@ class AppService { data: item }); } else { - const project = await client.project.findUnique({ - where: { id: item.projectId as string }, - select: { projectType: true }, - }); - if (!project || project.projectType !== 'APP') { - throw new ServiceException("Apps can only be created in App Projects."); - } item.id = KubeObjectNameUtils.toAppId(item.name as string); savedItem = await client.app.create({ data: item as Prisma.AppUncheckedCreateInput diff --git a/src/server/services/app.service.unit.spec.ts b/src/server/services/app.service.unit.spec.ts index b07ba58b..f0d4ea2b 100644 --- a/src/server/services/app.service.unit.spec.ts +++ b/src/server/services/app.service.unit.spec.ts @@ -104,21 +104,22 @@ describe('app.service', () => { ); }); - it('rejects App creation in an Agent Project', async () => { - vi.mocked(dataAccess.client.project.findUnique).mockResolvedValue({ - id: 'proj-agents', - name: 'Agents', - projectType: 'AGENT', - createdAt: new Date(), - updatedAt: new Date(), - }); + it('creates an App in any Project', async () => { + vi.mocked(dataAccess.client.app.create).mockResolvedValue({ id: 'app-new-app' } as never); - await expect(appService.save({ - name: 'Wrong Workload', - projectId: 'proj-agents', - })).rejects.toThrow('Apps can only be created in App Projects.'); + const saved = await appService.save({ + name: 'New App', + projectId: 'proj-mixed', + }); - expect(dataAccess.client.app.create).not.toHaveBeenCalled(); + expect(dataAccess.client.app.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + name: 'New App', + projectId: 'proj-mixed', + id: expect.stringMatching(/^app-/), + }), + }); + expect(saved.id).toBe('app-new-app'); }); it('rejects moving an App Domain from another App by id', async () => { @@ -250,7 +251,6 @@ function createApp(overrides: Partial): AppExtendedModel { project: { id: 'demo-project', name: 'Demo Project', - projectType: 'APP', createdAt: new Date(), updatedAt: new Date(), }, diff --git a/src/server/services/project.service.ts b/src/server/services/project.service.ts index 693ccb0b..e709ce23 100644 --- a/src/server/services/project.service.ts +++ b/src/server/services/project.service.ts @@ -6,13 +6,10 @@ import { KubeObjectNameUtils } from "../utils/kube-object-name.utils"; import namespaceService from "./namespace.service"; import buildService from "./build.service"; import { ProjectExtendedModel, ProjectNavigationModel, ProjectWithCountsModel } from "@/shared/model/project-extended.model"; -import { ProjectType, ProjectTypeModel } from "@/shared/model/project-type.model"; -import { ServiceException } from "@/shared/model/service.exception.model"; type ProjectSaveInput = { id?: string; name: string; - projectType?: ProjectType; }; class ProjectService { @@ -57,7 +54,6 @@ class ProjectService { select: { id: true, name: true, - projectType: true, createdAt: true, updatedAt: true, apps: { @@ -87,7 +83,6 @@ class ProjectService { select: { id: true, name: true, - projectType: true, createdAt: true, updatedAt: true, _count: { @@ -126,10 +121,6 @@ class ProjectService { let savedItem: Project; try { if (item.id) { - const existingItem = await this.getById(item.id); - if (item.projectType && item.projectType !== existingItem.projectType) { - throw new ServiceException("Project Type cannot be changed."); - } savedItem = await dataAccess.client.project.update({ where: { id: item.id @@ -137,16 +128,11 @@ class ProjectService { data: { name: item.name } }); } else { - const projectType = ProjectTypeModel.safeParse(item.projectType); - if (!projectType.success) { - throw new ServiceException("Project Type is required."); - } item.id = KubeObjectNameUtils.toProjectId(item.name); savedItem = await dataAccess.client.project.create({ data: { id: item.id, name: item.name, - projectType: projectType.data, } }); } diff --git a/src/server/services/project.service.unit.spec.ts b/src/server/services/project.service.unit.spec.ts index f9b97a80..f240dd86 100644 --- a/src/server/services/project.service.unit.spec.ts +++ b/src/server/services/project.service.unit.spec.ts @@ -24,59 +24,48 @@ import dataAccess from '@/server/adapter/db.client'; import namespaceService from '@/server/services/namespace.service'; import projectService from './project.service'; -describe('project.service Project Type', () => { +describe('project.service save', () => { beforeEach(() => { vi.clearAllMocks(); }); - it('requires Project Type when creating a Project', async () => { - await expect(projectService.save({ name: 'Missing Type' })).rejects.toThrow( - 'Project Type is required.', - ); - - expect(dataAccess.client.project.create).not.toHaveBeenCalled(); - }); - - it('persists the selected Project Type', async () => { + it('creates a Project with a generated id and namespace', async () => { vi.mocked(dataAccess.client.project.create).mockResolvedValue({ id: 'proj-agent-project', name: 'Agent Project', - projectType: 'AGENT', createdAt: new Date(), updatedAt: new Date(), }); - const project = await projectService.save({ - name: 'Agent Project', - projectType: 'AGENT', - }); + const project = await projectService.save({ name: 'Agent Project' }); expect(dataAccess.client.project.create).toHaveBeenCalledWith({ data: { id: expect.stringMatching(/^proj-agent-project/), name: 'Agent Project', - projectType: 'AGENT', }, }); expect(namespaceService.createNamespaceIfNotExists).toHaveBeenCalledWith(project.id); }); - it('rejects changing Project Type after creation', async () => { - vi.mocked(dataAccess.client.project.findFirstOrThrow).mockResolvedValue({ + it('renames an existing Project', async () => { + vi.mocked(dataAccess.client.project.update).mockResolvedValue({ id: 'proj-agent-project', - name: 'Agent Project', - projectType: 'AGENT', + name: 'Renamed Agent Project', createdAt: new Date(), updatedAt: new Date(), }); - await expect(projectService.save({ + const project = await projectService.save({ id: 'proj-agent-project', name: 'Renamed Agent Project', - projectType: 'APP', - })).rejects.toThrow('Project Type cannot be changed.'); + }); - expect(dataAccess.client.project.update).not.toHaveBeenCalled(); + expect(dataAccess.client.project.update).toHaveBeenCalledWith({ + where: { id: 'proj-agent-project' }, + data: { name: 'Renamed Agent Project' }, + }); + expect(project.name).toBe('Renamed Agent Project'); }); }); @@ -98,7 +87,6 @@ describe('project.service lean read queries', () => { expect(query.select).toEqual(expect.objectContaining({ id: true, name: true, - projectType: true, createdAt: true, updatedAt: true, apps: { select: { id: true, name: true } }, @@ -120,7 +108,6 @@ describe('project.service lean read queries', () => { expect(query.select).toEqual(expect.objectContaining({ id: true, name: true, - projectType: true, createdAt: true, updatedAt: true, _count: { select: { apps: true, agents: true } }, diff --git a/src/server/services/svc.service.unit.spec.ts b/src/server/services/svc.service.unit.spec.ts index 3168fa1f..6773dc02 100644 --- a/src/server/services/svc.service.unit.spec.ts +++ b/src/server/services/svc.service.unit.spec.ts @@ -168,7 +168,6 @@ function createApp(overrides: Partial): AppExtendedModel { project: { id: 'demo-project', name: 'Demo Project', - projectType: 'APP', createdAt: new Date(), updatedAt: new Date(), }, diff --git a/src/shared/model/generated-zod/project.ts b/src/shared/model/generated-zod/project.ts index b2fd8d83..f3a0f651 100644 --- a/src/shared/model/generated-zod/project.ts +++ b/src/shared/model/generated-zod/project.ts @@ -5,7 +5,6 @@ import { CompleteApp, RelatedAppModel, CompleteAgent, RelatedAgentModel, Complet export const ProjectModel = z.object({ id: z.string(), name: z.string(), - projectType: z.string(), createdAt: z.date(), updatedAt: z.date(), }) diff --git a/src/shared/model/project-type.model.ts b/src/shared/model/project-type.model.ts deleted file mode 100644 index 2507fe61..00000000 --- a/src/shared/model/project-type.model.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { z } from 'zod'; - -export const ProjectTypeModel = z.enum(['APP', 'AGENT']); - -export type ProjectType = z.infer; - From fe190cce97a374b0c0ca0fd80b65a32eec689a85 Mon Sep 17 00:00:00 2001 From: aperolschpritz Date: Sat, 3 Oct 2026 19:11:17 +0000 Subject: [PATCH 02/23] feat: add Agent Sandbox drawer Give Agent Sandboxes a right-side drawer like Apps, reusing existing components. - new AgentSandboxDrawer with Sandboxes, Builds, Configuration tabs - compact deploy/rebuild/delete header actions and nested configuration drawers - drawer session supports AGENT nodes via drawerAgentId - route table, sidebar, graph and post-create entry points to the drawer - UI terminology: Agent Sandbox and Sandbox Instance --- .../agent-sandbox-drawer-settings.tsx | 129 ++++++++++ .../agent-sandbox-drawer.tsx | 231 ++++++++++++++++++ .../agent-sandbox-status-actions.tsx | 107 ++++++++ .../agent-components/create-agent-dialog.tsx | 3 +- .../app-details-drawer.tsx | 2 +- .../app-components/project-network-graph.tsx | 35 ++- ...oject-network-graph-drawer-session.spec.ts | 24 +- .../project-network-graph-drawer-session.ts | 63 +++-- .../project-network-graph-projection.ts | 4 +- .../app-components/project-overview.tsx | 7 + .../[projectId]/create-project-actions.tsx | 6 +- src/app/project/[projectId]/page.tsx | 10 + .../project/[projectId]/workloads-table.tsx | 6 +- .../sandboxes/agent-sandboxes-card.tsx | 14 +- .../[appId]/advanced/network-policy-graph.tsx | 2 +- src/app/sidebar-client.tsx | 4 +- .../utils/agent-drawer-navigation.utils.ts | 21 ++ src/shared/utils/path-builder.utils.ts | 16 ++ 18 files changed, 639 insertions(+), 45 deletions(-) create mode 100644 src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-drawer-settings.tsx create mode 100644 src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-drawer.tsx create mode 100644 src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-status-actions.tsx create mode 100644 src/shared/utils/agent-drawer-navigation.utils.ts diff --git a/src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-drawer-settings.tsx b/src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-drawer-settings.tsx new file mode 100644 index 00000000..cb23d2ef --- /dev/null +++ b/src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-drawer-settings.tsx @@ -0,0 +1,129 @@ +'use client'; + +import { + Boxes, + Container, + HardDrive, + KeyRound, + MessageSquareText, + Network, +} from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { SettingsSection } from '@/app/project/[projectId]/app-components/app-drawer-components/settings-section'; +import { useNestedDrawer } from '@/app/project/[projectId]/app-components/app-drawer-components/nested-drawer'; +import AgentSourceCard from '@/app/project/agent/[agentId]/general/agent-source-card'; +import AgentModelConfigurationCard from '@/app/project/agent/[agentId]/general/agent-model-configuration-card'; +import AgentSystemPromptCard from '@/app/project/agent/[agentId]/general/agent-system-prompt-card'; +import AgentContainerConfigCard from '@/app/project/agent/[agentId]/general/agent-container-config-card'; +import AgentRateLimitsCard from '@/app/project/agent/[agentId]/general/agent-rate-limits-card'; +import AgentVolumesCard from '@/app/project/agent/[agentId]/general/agent-volumes-card'; +import AgentNetworkPolicyCard from '@/app/project/agent/[agentId]/general/agent-network-policy-card'; +import AgentEnvVarsCard from '@/app/project/agent/[agentId]/general/agent-env-vars-card'; +import HealthCheckSettings from '@/app/project/app/[appId]/advanced/health-check-settings'; +import { saveAgentHealthCheck } from '@/app/project/agent/[agentId]/general/actions'; +import DomainsCard from '@/components/custom/domains-card'; +import FileMountsCard from '@/components/custom/file-mounts-card'; +import type { AgentExtendedModel } from '@/shared/model/agent-extended.model'; + +export default function AgentSandboxDrawerSettings({ + agent, + readonly, + storageClasses, + runtimeClasses, +}: { + agent: AgentExtendedModel; + readonly: boolean; + storageClasses: string[]; + runtimeClasses: string[]; +}) { + const { openNestedDrawer } = useNestedDrawer(); + + return ( +
+ + + + + + + + + + + + +
+ +
+
+ + + + + + + + + + + + + + +
+ ); +} diff --git a/src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-drawer.tsx b/src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-drawer.tsx new file mode 100644 index 00000000..88b0b35f --- /dev/null +++ b/src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-drawer.tsx @@ -0,0 +1,231 @@ +'use client'; + +import { type Ref } from 'react'; +import { + Bot, + Hammer, + Pencil, + Settings, + X, +} from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { + Drawer, + DrawerContent, + DrawerDescription, + DrawerHeader, + DrawerTitle, +} from '@/components/ui/drawer'; +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; +import { + Empty, + EmptyDescription, + EmptyHeader, + EmptyMedia, + EmptyTitle, +} from '@/components/ui/empty'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { useDialog } from '@/frontend/states/zustand.states'; +import { DrawerTabScrollArea } from '@/app/project/[projectId]/app-components/app-drawer-components/app-details-drawer'; +import { NestedDrawerProvider } from '@/app/project/[projectId]/app-components/app-drawer-components/nested-drawer'; +import AgentSandboxesCard from '@/app/project/agent/[agentId]/sandboxes/agent-sandboxes-card'; +import WorkloadBuildsTable from '@/components/custom/workload-builds-table'; +import { RenameAgentDialog } from '@/app/project/[projectId]/agent-components/rename-agent-dialog'; +import { AgentSandboxStatusActions } from './agent-sandbox-status-actions'; +import AgentSandboxDrawerSettings from './agent-sandbox-drawer-settings'; +import type { AgentExtendedModel } from '@/shared/model/agent-extended.model'; +import { RolePermissionEnum } from '@/shared/model/role-extended.model.ts'; +import type { AgentSandboxTemplateInfo } from '@/shared/model/agent-sandbox-template-info.model'; +import { + AgentDrawerNavigationUtils, + type AgentDrawerTab, +} from '@/shared/utils/agent-drawer-navigation.utils'; +import { formatDateTime } from '@/frontend/utils/format.utils'; + +export function AgentSandboxDrawer({ + contentRef, + agent, + role, + templateInfo, + storageClasses, + runtimeClasses, + open, + onOpenChange, + onOpenChangeComplete, + requestedTab, + onTabChange, +}: { + contentRef?: Ref; + agent?: AgentExtendedModel; + role?: RolePermissionEnum; + templateInfo?: AgentSandboxTemplateInfo; + storageClasses: string[]; + runtimeClasses: string[]; + open: boolean; + onOpenChange: (open: boolean) => void; + onOpenChangeComplete: (open: boolean) => void; + requestedTab?: string | null; + onTabChange: (tab: AgentDrawerTab) => void; +}) { + const { openDialog } = useDialog(); + const readonly = role !== RolePermissionEnum.READWRITE; + const hasGitSource = agent?.sourceType === 'GIT' || agent?.sourceType === 'GIT_SSH'; + const activeTab = AgentDrawerNavigationUtils.resolveTab(requestedTab, { readonly, hasGitSource: !!hasGitSource }); + + const handleTabChange = (tab: string) => { + onTabChange(AgentDrawerNavigationUtils.resolveTab(tab, { readonly, hasGitSource: !!hasGitSource })); + }; + + const openRenameDialog = () => { + if (!agent) return; + openDialog(, { maxWidth: 'max-w-md' }); + }; + + return ( + + + + + + +
+
+ +
+
+ + {agent?.name ?? 'Agent Sandbox'} + {agent && role === RolePermissionEnum.READWRITE && ( + + )} + + + Agent Sandbox{agent ? ` · ${agent.project.name}` : ''} + {templateInfo?.lastDeployedAt + ? ` · Last deployed ${formatDateTime(templateInfo.lastDeployedAt)}` + : ''} + +
+ {agent && ( + onOpenChange(false)} + /> + )} +
+ {agent && role ? ( + + + + + Sandboxes + + {!readonly && hasGitSource && ( + + + Builds + + )} + {!readonly && ( + + + Configuration + + )} + + + ) : ( +
+ )} +
+ {agent && role ? ( + <> + + + + + + {!readonly && hasGitSource && ( + + + + + + )} + {!readonly && ( + + + + + + )} + + ) : ( + + + + + + Agent Sandbox unavailable + + This Agent Sandbox could not be loaded. It may have been deleted. + + + + )} +
+
+
+
+ ); +} diff --git a/src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-status-actions.tsx b/src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-status-actions.tsx new file mode 100644 index 00000000..a002e09f --- /dev/null +++ b/src/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-status-actions.tsx @@ -0,0 +1,107 @@ +'use client'; + +import { Hammer, Rocket, Trash2 } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from '@/components/ui/tooltip'; +import { useRouter } from 'next/navigation'; +import { useConfirmDialog } from '@/frontend/states/zustand.states'; +import { Toast } from '@/frontend/utils/toast.utils'; +import { deployAgent, deleteAgent } from '@/app/project/agent/[agentId]/overview/actions'; +import type { AgentExtendedModel } from '@/shared/model/agent-extended.model'; + +export function AgentSandboxStatusActions({ + agent, + readonly, + onDeleted, +}: { + agent: AgentExtendedModel; + readonly: boolean; + onDeleted?: () => void; +}) { + const router = useRouter(); + const { openConfirmDialog } = useConfirmDialog(); + + if (readonly) return null; + + const supportsRebuild = agent.sourceType === 'GIT' || agent.sourceType === 'GIT_SSH'; + + const handleDelete = async () => { + const confirmed = await openConfirmDialog({ + title: 'Delete Agent Sandbox', + description: 'Are you sure you want to delete this Agent Sandbox? All Sandbox Instances, sandbox definitions, and credentials will be removed. This action cannot be undone.', + okButton: 'Delete Agent Sandbox', + }); + if (!confirmed) return; + + await Toast.fromAction( + () => deleteAgent(agent.id), + 'Agent Sandbox deleted successfully.', + 'Deleting Agent Sandbox...', + ); + onDeleted?.(); + router.refresh(); + }; + + return ( + +
+ + void Toast.fromAction(() => deployAgent(agent.id))} + > + + Deploy + + } + /> + Deploy configuration + + {supportsRebuild && ( + + void Toast.fromAction(() => deployAgent(agent.id, true))} + > + + Rebuild + + } + /> + Rebuild + + )} + + void handleDelete()} + > + + Delete + + } + /> + Delete Agent Sandbox + +
+
+ ); +} diff --git a/src/app/project/[projectId]/agent-components/create-agent-dialog.tsx b/src/app/project/[projectId]/agent-components/create-agent-dialog.tsx index 5d5e1cb7..fae2131b 100644 --- a/src/app/project/[projectId]/agent-components/create-agent-dialog.tsx +++ b/src/app/project/[projectId]/agent-components/create-agent-dialog.tsx @@ -22,6 +22,7 @@ import { Toast } from "@/frontend/utils/toast.utils"; import { Actions } from "@/frontend/utils/nextjs-actions.utils"; import { createAgent, getLlmGateways, getModelAliasesForGateway } from "../actions"; import { useRouter } from "next/navigation"; +import { PathBuilderUtils } from "@/shared/utils/path-builder.utils"; import { Loader2 } from "lucide-react"; import { useDialog } from "@/frontend/states/zustand.states"; import { useDialogContext } from "@/frontend/states/dialog-context"; @@ -97,7 +98,7 @@ function CreateAgentForm({ projectId }: { projectId: string }) { if (result.status === 'success') { closeDialog(); - router.push(`/project/agent/${result.data!.id}`); + router.push(PathBuilderUtils.projectAgentDrawer(projectId, result.data!.id, 'sandboxes')); } setSubmitting(false); }; diff --git a/src/app/project/[projectId]/app-components/app-drawer-components/app-details-drawer.tsx b/src/app/project/[projectId]/app-components/app-drawer-components/app-details-drawer.tsx index 0f4f7d37..2df64324 100644 --- a/src/app/project/[projectId]/app-components/app-drawer-components/app-details-drawer.tsx +++ b/src/app/project/[projectId]/app-components/app-drawer-components/app-details-drawer.tsx @@ -81,7 +81,7 @@ export type AppDetailsDrawerNode = { caption?: string; }; -function DrawerTabScrollArea({ children }: { children: ReactNode }) { +export function DrawerTabScrollArea({ children }: { children: ReactNode }) { return (
{children}
diff --git a/src/app/project/[projectId]/app-components/project-network-graph.tsx b/src/app/project/[projectId]/app-components/project-network-graph.tsx index aeb7a8d5..a68db873 100644 --- a/src/app/project/[projectId]/app-components/project-network-graph.tsx +++ b/src/app/project/[projectId]/app-components/project-network-graph.tsx @@ -68,6 +68,8 @@ import { useProjectNetworkGraphDrawerSession, } from './project-network-graph/project-network-graph-drawer-session'; import { AppDetailsDrawer } from './app-drawer-components/app-details-drawer'; +import { AgentSandboxDrawer } from '@/app/project/[projectId]/agent-components/agent-drawer-components/agent-sandbox-drawer'; +import type { AgentSandboxTemplateInfo } from '@/shared/model/agent-sandbox-template-info.model'; const hiddenHandleClassName = 'size-1.5! border-0! bg-transparent! opacity-0! pointer-events-none'; const connectionSourceHandleClassName = 'z-20! size-4! border-2! border-background! bg-qs-500! opacity-0! shadow-md! transition-all duration-150 group-hover:opacity-100! [&.connectingfrom]:opacity-0! hover:bg-qs-600!'; @@ -95,8 +97,10 @@ type ProjectNetworkGraphProps = { savedPositions: ProjectNetworkGraphPositions; s3Targets: S3Target[]; storageClasses: string[]; + runtimeClasses: string[]; volumeBackupsByApp: Record; gitSshPublicKeysByApp: Record; + agentTemplateInfoByAgent: Record; }; function stripWorkloadPrefix(nodeId: string | undefined) { @@ -249,12 +253,12 @@ function ProjectNetworkGraphCanvasContextMenu({ - Create Empty Agent + Create Empty Agent Sandbox openTemplateDialog('agent-template')}> - Create Agent from Template + Create Agent Sandbox from Template } @@ -297,8 +301,10 @@ function ProjectNetworkGraphEditor({ savedPositions, s3Targets, storageClasses, + runtimeClasses, volumeBackupsByApp, gitSshPublicKeysByApp, + agentTemplateInfoByAgent, }: ProjectNetworkGraphProps) { const router = useRouter(); const searchParams = useSearchParams(); @@ -322,6 +328,7 @@ function ProjectNetworkGraphEditor({ const { layout, saveNodePosition, resetLayout } = useProjectNetworkGraph(graphApps, agents, projectId, savedPositions); const dirty = Object.keys(drafts).some(appId => !AppNetworkPolicyDraftUtils.equals(drafts[appId], baseline[appId])); const localAppIds = useMemo(() => new Set(apps.map(app => app.id)), [apps]); + const localAgentIds = useMemo(() => new Set(agents.map(agent => agent.id)), [agents]); const localWorkloadIds = useMemo(() => new Set([ ...apps.map(app => app.id), ...agents.map(agent => agent.id), @@ -329,6 +336,7 @@ function ProjectNetworkGraphEditor({ const drawerSession = useProjectNetworkGraphDrawerSession({ searchParams, appIds: localAppIds, + agentIds: localAgentIds, }); const { selectedNodeId } = drawerSession; const writable = useCallback( @@ -522,6 +530,8 @@ function ProjectNetworkGraphEditor({ const selectedNode = nodes.find(node => node.id === selectedNodeId)?.data as NetworkGraphNode | undefined; const selectedApp = selectedNode?.kind === 'APP' ? apps.find(app => app.id === selectedNode.id.replace('APP:', '')) : undefined; const selectedAppRole = selectedApp ? UserGroupUtils.getRolePermissionForApp(session, selectedApp.id) ?? undefined : undefined; + const selectedAgent = selectedNode?.kind === 'AGENT' ? agents.find(agent => agent.id === selectedNode.id.replace('AGENT:', '')) : undefined; + const selectedAgentRole = selectedAgent ? UserGroupUtils.getRolePermissionForProjectWorkload(session, selectedAgent.id) ?? undefined : undefined; useEffect(() => { if (!selectedNodeId || selectedNode?.kind !== 'APP') return; @@ -656,10 +666,6 @@ function ProjectNetworkGraphEditor({ onNodeClick={(_event, node) => { const data = node.data as NetworkGraphNode; if (data.kind === 'INTERNET') return; - if (data.kind === 'AGENT') { - router.push(`/project/agent/${stripWorkloadPrefix(data.id)}`); - return; - } drawerSession.selectNode(data); }} > @@ -693,7 +699,7 @@ function ProjectNetworkGraphEditor({ {edges.length === 0 && nodes.length === 0 &&

No active network policy connections yet.

} - {selectedNode && setEnvironmentAppId(undefined)} />} + {selectedNode && selectedNode.kind === 'AGENT' && { + if (selectedAgent) drawerSession.openAgentTab(selectedAgent.id, tab); + }} + />} ); diff --git a/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-drawer-session.spec.ts b/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-drawer-session.spec.ts index 1adc2a47..551ff470 100644 --- a/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-drawer-session.spec.ts +++ b/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-drawer-session.spec.ts @@ -22,11 +22,14 @@ describe('DrawerSessionUtils.resolveTab', () => { }); describe('useProjectNetworkGraphDrawerSession', () => { + const noAgentIds = new Set(); + const noAppIds = new Set(); + test('keeps its interface stable across an unrelated parent render', () => { const searchParams = new URLSearchParams('drawerTab=deployments'); const appIds = new Set(['app-1']); const { result, rerender } = renderHook(() => - useProjectNetworkGraphDrawerSession({ searchParams, appIds }), + useProjectNetworkGraphDrawerSession({ searchParams, appIds, agentIds: noAgentIds }), ); const session = result.current; @@ -39,7 +42,7 @@ describe('useProjectNetworkGraphDrawerSession', () => { const searchParams = new URLSearchParams('drawerAppId=app-1&drawerTab=logs'); const appIds = new Set(['app-1']); const { result } = renderHook(() => - useProjectNetworkGraphDrawerSession({ searchParams, appIds }), + useProjectNetworkGraphDrawerSession({ searchParams, appIds, agentIds: noAgentIds }), ); expect(result.current.selectedNodeId).toBe('APP:app-1'); @@ -60,9 +63,24 @@ describe('useProjectNetworkGraphDrawerSession', () => { const searchParams = new URLSearchParams('drawerAppId=missing&drawerTab=logs'); const appIds = new Set(['app-1']); const { result } = renderHook(() => - useProjectNetworkGraphDrawerSession({ searchParams, appIds }), + useProjectNetworkGraphDrawerSession({ searchParams, appIds, agentIds: noAgentIds }), ); expect(result.current.selectedNodeId).toBeUndefined(); }); + + test('selects an agent node from the URL', () => { + const searchParams = new URLSearchParams('drawerAgentId=agent-1&drawerTab=sandboxes'); + const agentIds = new Set(['agent-1']); + const { result } = renderHook(() => + useProjectNetworkGraphDrawerSession({ + searchParams, + appIds: noAppIds, + agentIds, + }), + ); + + expect(result.current.selectedNodeId).toBe('AGENT:agent-1'); + expect(result.current.requestedTab).toBe('sandboxes'); + }); }); diff --git a/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-drawer-session.ts b/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-drawer-session.ts index 2ec278ea..7649f89a 100644 --- a/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-drawer-session.ts +++ b/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-drawer-session.ts @@ -8,6 +8,10 @@ import { defaultAppDrawerTab, type AppDrawerTab, } from '@/shared/utils/app-drawer-navigation.utils'; +import { + defaultAgentDrawerTab, + type AgentDrawerTab, +} from '@/shared/utils/agent-drawer-navigation.utils'; import type { NetworkGraphNode } from './project-network-graph-projection'; export const drawerTabValues = appDrawerTabValues; @@ -16,26 +20,30 @@ export const DrawerSessionUtils = AppDrawerNavigationUtils; type QueryParams = Pick; +type DrawerTarget = { kind: 'APP' | 'AGENT'; id: string }; + export function useProjectNetworkGraphDrawerSession({ searchParams, appIds, + agentIds, }: { searchParams: QueryParams; appIds: Set; + agentIds: Set; }) { const [selectedNodeId, setSelectedNodeId] = useState(); const [open, setOpen] = useState(false); const requestedTab = searchParams.get('drawerTab'); - const updateQuery = useCallback((appId?: string, tab?: DrawerTab) => { + const updateQuery = useCallback((target?: DrawerTarget, tab?: AppDrawerTab | AgentDrawerTab) => { const params = new URLSearchParams(searchParams.toString()); + params.delete('drawerAppId'); + params.delete('drawerAgentId'); + params.delete('drawerTab'); - if (!appId) { - params.delete('drawerAppId'); - params.delete('drawerTab'); - } else { - params.set('drawerAppId', appId); - params.set('drawerTab', tab ?? defaultAppDrawerTab); + if (target) { + params.set(target.kind === 'AGENT' ? 'drawerAgentId' : 'drawerAppId', target.id); + params.set('drawerTab', tab ?? (target.kind === 'AGENT' ? defaultAgentDrawerTab : defaultAppDrawerTab)); } TabNavigationUtils.replaceQuery(params); @@ -43,15 +51,25 @@ export function useProjectNetworkGraphDrawerSession({ useEffect(() => { const requestedAppId = searchParams.get('drawerAppId'); - - if (!requestedAppId) return; - if (!appIds.has(requestedAppId)) { - updateQuery(); + const requestedAgentId = searchParams.get('drawerAgentId'); + + if (requestedAppId) { + if (!appIds.has(requestedAppId)) { + updateQuery(); + return; + } + setSelectedNodeId(`APP:${requestedAppId}`); return; } - setSelectedNodeId(`APP:${requestedAppId}`); - }, [appIds, searchParams, updateQuery]); + if (requestedAgentId) { + if (!agentIds.has(requestedAgentId)) { + updateQuery(); + return; + } + setSelectedNodeId(`AGENT:${requestedAgentId}`); + } + }, [agentIds, appIds, searchParams, updateQuery]); useEffect(() => { if (selectedNodeId) setOpen(true); @@ -60,14 +78,27 @@ export function useProjectNetworkGraphDrawerSession({ const selectNode = useCallback((node: NetworkGraphNode) => { setSelectedNodeId(node.id); if (selectedNodeId === node.id) setOpen(true); - updateQuery(node.kind === 'APP' ? node.id.replace('APP:', '') : undefined); + if (node.kind === 'APP') { + updateQuery({ kind: 'APP', id: node.id.replace('APP:', '') }); + } else if (node.kind === 'AGENT') { + updateQuery({ kind: 'AGENT', id: node.id.replace('AGENT:', '') }); + } else { + updateQuery(); + } }, [selectedNodeId, updateQuery]); const openAppTab = useCallback((appId: string, tab: DrawerTab) => { const nodeId = `APP:${appId}`; setSelectedNodeId(nodeId); if (selectedNodeId === nodeId) setOpen(true); - updateQuery(appId, tab); + updateQuery({ kind: 'APP', id: appId }, tab); + }, [selectedNodeId, updateQuery]); + + const openAgentTab = useCallback((agentId: string, tab: AgentDrawerTab) => { + const nodeId = `AGENT:${agentId}`; + setSelectedNodeId(nodeId); + if (selectedNodeId === nodeId) setOpen(true); + updateQuery({ kind: 'AGENT', id: agentId }, tab); }, [selectedNodeId, updateQuery]); const onOpenChange = useCallback((nextOpen: boolean) => { @@ -89,11 +120,13 @@ export function useProjectNetworkGraphDrawerSession({ requestedTab, selectNode, openAppTab, + openAgentTab, onOpenChange, onOpenChangeComplete, }), [ onOpenChange, onOpenChangeComplete, + openAgentTab, openAppTab, open, requestedTab, diff --git a/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-projection.ts b/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-projection.ts index 06580191..9b766a66 100644 --- a/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-projection.ts +++ b/src/app/project/[projectId]/app-components/project-network-graph/project-network-graph-projection.ts @@ -142,7 +142,7 @@ export function buildProjectNetworkGraph(apps: AppExtendedModel[], agents: Agent const external = !internalWorkloadIds.has(target.id); addNode({ id: targetNodeId, kind: targetType, name: target.name, projectId: target.projectId, external, - caption: external && target.projectId !== projectId ? 'Other project' : targetType === 'AGENT' ? 'Agent sandbox' : undefined, + caption: external && target.projectId !== projectId ? 'Other project' : targetType === 'AGENT' ? 'Agent Sandbox' : undefined, }); const label = formatRuleLabel(rule.port, rule.protocol); const ruleProvenance = [{ ownerAppId: app.id, ruleKey: rule.id }]; @@ -163,7 +163,7 @@ export function buildProjectNetworkGraph(apps: AppExtendedModel[], agents: Agent for (const agent of agents) { const agentNodeId = workloadNodeId('AGENT', agent.id); - addNode({ id: agentNodeId, kind: 'AGENT', name: agent.name, projectId: agent.projectId, external: false, caption: 'Agent sandbox' }); + addNode({ id: agentNodeId, kind: 'AGENT', name: agent.name, projectId: agent.projectId, external: false, caption: 'Agent Sandbox' }); if (agent.agentNetworkPolicy) { for (const rule of agent.agentNetworkPolicy.rules) { diff --git a/src/app/project/[projectId]/app-components/project-overview.tsx b/src/app/project/[projectId]/app-components/project-overview.tsx index ce2b7c78..6a202759 100644 --- a/src/app/project/[projectId]/app-components/project-overview.tsx +++ b/src/app/project/[projectId]/app-components/project-overview.tsx @@ -18,6 +18,7 @@ import { useDialog } from "@/frontend/states/zustand.states"; import NewNetworkPolicyExplanationDialog from './new-network-policy-explanation-dialog'; import type { S3Target } from '@prisma/client'; import type { VolumeBackupExtendedModel } from '@/shared/model/volume-backup-extended.model'; +import type { AgentSandboxTemplateInfo } from '@/shared/model/agent-sandbox-template-info.model'; import WorkloadsTable from '../workloads-table'; interface ProjectOverviewProps { @@ -31,8 +32,10 @@ interface ProjectOverviewProps { showNewNetworkPolicyExplanation: boolean; s3Targets: S3Target[]; storageClasses: string[]; + runtimeClasses: string[]; volumeBackupsByApp: Record; gitSshPublicKeysByApp: Record; + agentTemplateInfoByAgent: Record; } type ProjectOverviewTab = 'table' | 'graph'; @@ -56,8 +59,10 @@ export default function AppProjectOverview({ showNewNetworkPolicyExplanation, s3Targets, storageClasses, + runtimeClasses, volumeBackupsByApp, gitSshPublicKeysByApp, + agentTemplateInfoByAgent, }: ProjectOverviewProps) { const searchParams = useSearchParams(); const { openDialog } = useDialog(); @@ -164,8 +169,10 @@ export default function AppProjectOverview({ savedPositions={networkGraphPositions} s3Targets={s3Targets} storageClasses={storageClasses} + runtimeClasses={runtimeClasses} volumeBackupsByApp={volumeBackupsByApp} gitSshPublicKeysByApp={gitSshPublicKeysByApp} + agentTemplateInfoByAgent={agentTemplateInfoByAgent} /> diff --git a/src/app/project/[projectId]/create-project-actions.tsx b/src/app/project/[projectId]/create-project-actions.tsx index cb1a41bf..5d350d74 100644 --- a/src/app/project/[projectId]/create-project-actions.tsx +++ b/src/app/project/[projectId]/create-project-actions.tsx @@ -49,11 +49,11 @@ export default function CreateProjectActions({ {agentsAvailable && ( <> - Agents + Agent Sandboxes - Empty Agent + Empty Agent Sandbox - openTemplateDialog('agent-template')}> Agent Template + openTemplateDialog('agent-template')}> Agent Sandbox Template )} diff --git a/src/app/project/[projectId]/page.tsx b/src/app/project/[projectId]/page.tsx index d3ef6cbc..be2c6a42 100644 --- a/src/app/project/[projectId]/page.tsx +++ b/src/app/project/[projectId]/page.tsx @@ -15,6 +15,7 @@ import volumeBackupService from "@/server/services/volume-backup.service"; import clusterService from "@/server/services/cluster.service"; import appGitSshKeyService from "@/server/services/app-git-ssh-key.service"; import agentSandboxAddonService from "@/server/services/addons/agent-sandbox-addon.service"; +import { CatchUtils } from "@/shared/utils/catch.utils"; export default async function AppsPage({ params @@ -48,13 +49,16 @@ export default async function AppsPage({ hasAcknowledgedNewNetworkPolicyExplanation, s3Targets, storageClasses, + runtimeClasses, volumeBackups, gitSshPublicKeys, + agentTemplateInfoByAgent, ] = await Promise.all([ projectNetworkGraphLayoutService.getPositions(projectId), paramService.getBoolean(ParamService.FEATURE_NEW_NETWORK_POLICY_EXPLENATION), s3TargetService.getAll(), clusterService.getStorageClasses(), + clusterService.getRuntimeClasses(), Promise.all(relevantApps.map(async (app) => [ app.id, await volumeBackupService.getForApp(app.id), @@ -63,6 +67,10 @@ export default async function AppsPage({ app.id, await appGitSshKeyService.getPublicKey(app.id), ] as const)), + Promise.all(relevantAgents.map(async (agent) => [ + agent.id, + await CatchUtils.resultOrUndefined(() => agentService.getSandboxTemplateDeployInfo(agent.id)), + ] as const)), ]); return ( @@ -78,8 +86,10 @@ export default async function AppsPage({ showNewNetworkPolicyExplanation={!hasAcknowledgedNewNetworkPolicyExplanation} s3Targets={s3Targets} storageClasses={storageClasses} + runtimeClasses={runtimeClasses} volumeBackupsByApp={Object.fromEntries(volumeBackups)} gitSshPublicKeysByApp={Object.fromEntries(gitSshPublicKeys)} + agentTemplateInfoByAgent={Object.fromEntries(agentTemplateInfoByAgent)} /> diff --git a/src/app/project/[projectId]/workloads-table.tsx b/src/app/project/[projectId]/workloads-table.tsx index 694e8402..12277d45 100644 --- a/src/app/project/[projectId]/workloads-table.tsx +++ b/src/app/project/[projectId]/workloads-table.tsx @@ -47,7 +47,7 @@ export default function WorkloadsTable({ ]; const workloadHref = (item: WorkloadRow) => item.kind === 'AGENT' - ? `/project/agent/${item.id}` + ? PathBuilderUtils.projectAgentDrawer(projectId, item.id, 'sandboxes', 'table') : PathBuilderUtils.projectAppDrawer(projectId, item.id, 'deployments', 'table'); return )], - ['kind', 'Type', true, (item: WorkloadRow) => item.kind === 'AGENT' ? 'Agent' : 'App'], + ['kind', 'Type', true, (item: WorkloadRow) => item.kind === 'AGENT' ? 'Agent Sandbox' : 'App'], ['status', 'Status', true, (item: WorkloadRow) => item.kind === 'APP' ? : {item.warmPoolReplicas} warm], @@ -81,7 +81,7 @@ export default function WorkloadsTable({ - Show {item.kind === 'AGENT' ? 'Agent' : 'App'} Details + Show {item.kind === 'AGENT' ? 'Agent Sandbox' : 'App'} Details {item.kind === 'APP' ? ( diff --git a/src/app/project/agent/[agentId]/sandboxes/agent-sandboxes-card.tsx b/src/app/project/agent/[agentId]/sandboxes/agent-sandboxes-card.tsx index 495d9513..e3702246 100644 --- a/src/app/project/agent/[agentId]/sandboxes/agent-sandboxes-card.tsx +++ b/src/app/project/agent/[agentId]/sandboxes/agent-sandboxes-card.tsx @@ -264,10 +264,10 @@ export default function AgentSandboxesCard({
- Agent Sandboxes + Sandbox Instances - Start and manage agent sandboxes for this agent. - {sandboxes.length > 0 && ` ${sandboxes.length} sandbox${sandboxes.length !== 1 ? 's' : ''} running.`} + Start and manage Sandbox Instances for this Agent Sandbox. + {sandboxes.length > 0 && ` ${sandboxes.length} sandbox instance${sandboxes.length !== 1 ? 's' : ''} running.`}
{!readonly && ( @@ -278,7 +278,7 @@ export default function AgentSandboxesCard({ size="sm" > - Start New Sandbox + Start Sandbox Instance )}
@@ -290,9 +290,9 @@ export default function AgentSandboxesCard({ - No running Sandboxes + No running Sandbox Instances - There are currently no running sandboxes for this agent. Click "Start New Sandbox" to create one. + There are currently no running Sandbox Instances for this Agent Sandbox. Click "Start Sandbox Instance" to create one. @@ -302,7 +302,7 @@ export default function AgentSandboxesCard({ size="sm" > - Start New Sandbox + Start Sandbox Instance diff --git a/src/app/project/app/[appId]/advanced/network-policy-graph.tsx b/src/app/project/app/[appId]/advanced/network-policy-graph.tsx index 47daa018..2208963a 100644 --- a/src/app/project/app/[appId]/advanced/network-policy-graph.tsx +++ b/src/app/project/app/[appId]/advanced/network-policy-graph.tsx @@ -370,7 +370,7 @@ export default function NetworkPolicyGraph({ const [workloadType, workloadId] = String(node.id).split(':'); const peer = node.data as PeerNodeData; router.push(workloadType === 'AGENT' - ? `/project/agent/${workloadId}` + ? PathBuilderUtils.projectAgentDrawer(peer.projectId, workloadId) : PathBuilderUtils.projectAppDrawer(peer.projectId, workloadId)); }} > diff --git a/src/app/sidebar-client.tsx b/src/app/sidebar-client.tsx index 8ef0c1c6..bfdfd387 100644 --- a/src/app/sidebar-client.tsx +++ b/src/app/sidebar-client.tsx @@ -85,7 +85,7 @@ export function SidebarCient({ const projectId = path.split('/')[2]; setCurrentlySelectedProjectId(projectId); setCurrentlySelectedAppId(searchParams.get('drawerAppId')); - setCurrentlySelectedAgentId(null); + setCurrentlySelectedAgentId(searchParams.get('drawerAgentId')); } else { setCurrentlySelectedProjectId(null); @@ -187,7 +187,7 @@ export function SidebarCient({ ? currentlySelectedAgentId === workload.id : currentlySelectedAppId === workload.id; return ( - {workload.name}} /> + {workload.name}} /> ); })} diff --git a/src/shared/utils/agent-drawer-navigation.utils.ts b/src/shared/utils/agent-drawer-navigation.utils.ts new file mode 100644 index 00000000..24ed9799 --- /dev/null +++ b/src/shared/utils/agent-drawer-navigation.utils.ts @@ -0,0 +1,21 @@ +export const agentDrawerTabValues = [ + 'sandboxes', + 'builds', + 'configuration', +] as const; + +export type AgentDrawerTab = (typeof agentDrawerTabValues)[number]; + +export const defaultAgentDrawerTab: AgentDrawerTab = 'sandboxes'; + +export class AgentDrawerNavigationUtils { + static resolveTab( + requestedTab: string | null | undefined, + options: { readonly: boolean; hasGitSource: boolean }, + ): AgentDrawerTab { + if (!agentDrawerTabValues.includes(requestedTab as AgentDrawerTab)) return defaultAgentDrawerTab; + if (requestedTab === 'builds' && (options.readonly || !options.hasGitSource)) return defaultAgentDrawerTab; + if (requestedTab === 'configuration' && options.readonly) return defaultAgentDrawerTab; + return requestedTab as AgentDrawerTab; + } +} diff --git a/src/shared/utils/path-builder.utils.ts b/src/shared/utils/path-builder.utils.ts index 47775a2b..a7f6d627 100644 --- a/src/shared/utils/path-builder.utils.ts +++ b/src/shared/utils/path-builder.utils.ts @@ -1,4 +1,5 @@ import { defaultAppDrawerTab, type AppDrawerTab } from './app-drawer-navigation.utils'; +import { defaultAgentDrawerTab, type AgentDrawerTab } from './agent-drawer-navigation.utils'; export class PathBuilderUtils { static projectAppDrawer( @@ -15,4 +16,19 @@ export class PathBuilderUtils { return `/project/${encodeURIComponent(projectId)}?${params.toString()}`; } + + static projectAgentDrawer( + projectId: string, + agentId: string, + drawerTab: AgentDrawerTab = defaultAgentDrawerTab, + projectTab?: string, + ) { + const params = new URLSearchParams({ + drawerAgentId: agentId, + drawerTab, + }); + if (projectTab) params.set('tab', projectTab); + + return `/project/${encodeURIComponent(projectId)}?${params.toString()}`; + } } From d8bbf87e2760d51f76ef5fce68f412ab39e04dd5 Mon Sep 17 00:00:00 2001 From: aperolschpritz Date: Tue, 6 Oct 2026 18:20:35 +0000 Subject: [PATCH 03/23] chore: sync matt pocock skills to v1.3.1 - update 18 existing skills from upstream - add pr, implement-spec, retro skills - remove resolving-merge-conflicts (dropped upstream) - rename CONTEXT.md/CONTEXT-FORMAT.md to GLOSSARY.md/GLOSSARY-FORMAT.md - refresh skills-lock.json hashes and entries --- .agents/skills/code-review/SKILL.md | 54 +++--- .agents/skills/codebase-design/DEEPENING.md | 8 +- .../skills/codebase-design/DESIGN-IT-TWICE.md | 20 +-- .agents/skills/codebase-design/SKILL.md | 26 +-- .agents/skills/diagnosing-bugs/SKILL.md | 60 +++---- .../scripts/hitl-loop.template.sh | 4 +- .agents/skills/domain-modeling/ADR-FORMAT.md | 22 +-- .../{CONTEXT-FORMAT.md => GLOSSARY-FORMAT.md} | 20 +-- .agents/skills/domain-modeling/SKILL.md | 34 ++-- .agents/skills/elysia-api-routes/SKILL.md | 2 +- .agents/skills/grill-me/SKILL.md | 2 +- .agents/skills/grill-with-docs/SKILL.md | 2 +- .agents/skills/grilling/SKILL.md | 14 +- .agents/skills/handoff/SKILL.md | 4 +- .agents/skills/implement-spec/SKILL.md | 40 +++++ .../skills/implement-spec/agents/openai.yaml | 5 + .agents/skills/implement/SKILL.md | 4 +- .../HTML-REPORT.md | 38 ++-- .../improve-codebase-architecture/SKILL.md | 50 +++--- .agents/skills/pr/CREDITS.md | 3 + .agents/skills/pr/SKILL.md | 170 ++++++++++++++++++ .agents/skills/pr/agents/openai.yaml | 3 + .agents/skills/research/SKILL.md | 2 +- .../skills/resolving-merge-conflicts/SKILL.md | 14 -- .../agents/openai.yaml | 3 - .agents/skills/retro/SKILL.md | 44 +++++ .agents/skills/retro/agents/openai.yaml | 5 + .agents/skills/tdd/SKILL.md | 18 +- .agents/skills/to-spec/SKILL.md | 8 +- .agents/skills/to-tickets/SKILL.md | 32 ++-- .agents/skills/triage/AGENT-BRIEF.md | 18 +- .agents/skills/triage/OUT-OF-SCOPE.md | 30 ++-- .agents/skills/triage/SKILL.md | 58 +++--- .agents/skills/wayfinder/SKILL.md | 74 ++++---- .../writing-for-agents/SKILL-MECHANICS.md | 10 +- .agents/skills/writing-for-agents/SKILL.md | 50 +++--- CONTEXT.md => GLOSSARY.md | 0 docs/agents/domain.md | 40 +++-- skills-lock.json | 52 +++--- 39 files changed, 664 insertions(+), 379 deletions(-) rename .agents/skills/domain-modeling/{CONTEXT-FORMAT.md => GLOSSARY-FORMAT.md} (70%) create mode 100644 .agents/skills/implement-spec/SKILL.md create mode 100644 .agents/skills/implement-spec/agents/openai.yaml create mode 100644 .agents/skills/pr/CREDITS.md create mode 100644 .agents/skills/pr/SKILL.md create mode 100644 .agents/skills/pr/agents/openai.yaml delete mode 100644 .agents/skills/resolving-merge-conflicts/SKILL.md delete mode 100644 .agents/skills/resolving-merge-conflicts/agents/openai.yaml create mode 100644 .agents/skills/retro/SKILL.md create mode 100644 .agents/skills/retro/agents/openai.yaml rename CONTEXT.md => GLOSSARY.md (100%) diff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.md index 2d276fe8..e28d7acb 100644 --- a/.agents/skills/code-review/SKILL.md +++ b/.agents/skills/code-review/SKILL.md @@ -1,32 +1,32 @@ --- name: code-review -description: Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes — Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to "review since X". +description: "Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to \"review since X\"." --- Two-axis review of the diff between `HEAD` and a fixed point the user supplies: -- **Standards** — does the code conform to this repo's documented coding standards? -- **Spec** — does the code faithfully implement the originating issue / spec? +- **Standards**: does the code conform to this repo's documented coding standards? +- **Spec**: does the code faithfully implement the originating issue / spec? Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings. -The issue tracker should have been provided to you — run `/setup-matt-pocock-skills` if `docs/agents/issue-tracker.md` is missing. +The issue tracker should have been provided to you. If `docs/agents/issue-tracker.md` is missing, tell the user to run `/setup-matt-pocock-skills`. ## Process ### 1. Pin the fixed point -Whatever the user said is the fixed point — a commit SHA, branch name, tag, `main`, `HEAD~5`, etc. If they didn't specify one, ask for it. +Whatever the user said is the fixed point (a commit SHA, branch name, tag, `main`, `HEAD~5`, etc.). If they didn't specify one, ask for it. Capture the diff command once: `git diff ...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log ..HEAD --oneline`. -Before going further, confirm the fixed point resolves (`git rev-parse `) and the diff is non-empty. A bad ref or empty diff should fail here — not inside two parallel sub-agents. +Before going further, confirm the fixed point resolves (`git rev-parse `) and the diff is non-empty. A bad ref or empty diff should fail here, not inside two parallel sub-agents. ### 2. Identify the spec source Look for the originating spec, in this order: -1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.) — fetch via the workflow in `docs/agents/issue-tracker.md`. +1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.), fetched via the workflow in `docs/agents/issue-tracker.md`. 2. A path the user passed as an argument. 3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature. 4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available". @@ -35,35 +35,35 @@ Look for the originating spec, in this order: Anything in the repo that documents how code should be written, such as `CODING_STANDARDS.md` or `CONTRIBUTING.md`. -On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below — a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it: +On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below: a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it: - **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell. -- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation — and, like any standard here, skip anything tooling already enforces. +- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation. Like any standard here, skip anything tooling already enforces. Each smell reads *what it is* → *how to fix*; match it against the diff: -- **Mysterious Name** — a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky. -- **Duplicated Code** — the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both. -- **Feature Envy** — a method that reaches into another object's data more than its own. → move the method onto the data it envies. -- **Data Clumps** — the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that. -- **Primitive Obsession** — a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type. -- **Repeated Switches** — the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share. -- **Shotgun Surgery** — one logical change forces scattered edits across many files in the diff. → gather what changes together into one module. -- **Divergent Change** — one file or module is edited for several unrelated reasons. → split so each module changes for one reason. -- **Speculative Generality** — abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows. -- **Message Chains** — long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object. -- **Middle Man** — a class or function that mostly just delegates onward. → cut it, call the real target direct. -- **Refused Bequest** — a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition. +- **Mysterious Name**: a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky. +- **Duplicated Code**: the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both. +- **Feature Envy**: a method that reaches into another object's data more than its own. → move the method onto the data it envies. +- **Data Clumps**: the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that. +- **Primitive Obsession**: a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type. +- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share. +- **Shotgun Surgery**: one logical change forces scattered edits across many files in the diff. → gather what changes together into one module. +- **Divergent Change**: one file or module is edited for several unrelated reasons. → split so each module changes for one reason. +- **Speculative Generality**: abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows. +- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object. +- **Middle Man**: a class or function that mostly just delegates onward. → cut it, call the real target direct. +- **Refused Bequest**: a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition. ### 4. Spawn both sub-agents in parallel -**Standards sub-agent prompt** — include: +**Standards sub-agent prompt** should include: - The full diff command and commit list. -- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full — the sub-agent has no other access to it. -- The brief: "Report — per file/hunk where relevant — (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls — documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words." +- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full (the sub-agent has no other access to it). +- The brief: "Report, per file/hunk where relevant, (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls: documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words." -**Spec sub-agent prompt** — include: +**Spec sub-agent prompt** should include: - The diff command and commit list. - The path or fetched contents of the spec. @@ -73,9 +73,9 @@ If the spec is missing, skip the Spec sub-agent and note this in the final repor ### 5. Aggregate -Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings — the two axes are deliberately separate (see _Why two axes_). +Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings, because the two axes are deliberately separate (see _Why two axes_). -End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes — that's the reranking the separation exists to prevent. +End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes: that's the reranking the separation exists to prevent. ## Why two axes diff --git a/.agents/skills/codebase-design/DEEPENING.md b/.agents/skills/codebase-design/DEEPENING.md index 3938457b..cd94075c 100644 --- a/.agents/skills/codebase-design/DEEPENING.md +++ b/.agents/skills/codebase-design/DEEPENING.md @@ -1,6 +1,6 @@ # Deepening -How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md) — **module**, **interface**, **seam**, **adapter**. +How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**. ## Dependency categories @@ -8,7 +8,7 @@ When assessing a candidate for deepening, classify its dependencies. The categor ### 1. In-process -Pure computation, in-memory state, no I/O. Always deepenable — merge the modules and test through the new interface directly. No adapter needed. +Pure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed. ### 2. Local-substitutable @@ -31,7 +31,7 @@ Third-party services (Stripe, Twilio, etc.) you don't control. The deepened modu ## Testing strategy: replace, don't layer -- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them. +- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them. - Write new tests at the deepened module's interface. The **interface is the test surface**. - Tests assert on observable outcomes through the interface, not internal state. -- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. +- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/.agents/skills/codebase-design/DESIGN-IT-TWICE.md b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md index 8419ad6f..d0990138 100644 --- a/.agents/skills/codebase-design/DESIGN-IT-TWICE.md +++ b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md @@ -1,8 +1,8 @@ # Design It Twice -When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best. +When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout): your first idea is unlikely to be the best. -Uses the vocabulary in [SKILL.md](SKILL.md) — **module**, **interface**, **seam**, **adapter**, **leverage**. +Uses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**. ## Process @@ -12,7 +12,7 @@ Before spawning sub-agents, write a user-facing explanation of the problem space - The constraints any new interface would need to satisfy - The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) -- A rough illustrative code sketch to ground the constraints — not a proposal, just a way to make the constraints concrete +- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. @@ -22,23 +22,23 @@ Spawn 3+ sub-agents in parallel. Each must produce a **radically different** int Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: -- Agent 1: "Minimize the interface — aim for 1–3 entry points max. Maximise leverage per entry point." -- Agent 2: "Maximise flexibility — support many use cases and extension." -- Agent 3: "Optimise for the most common caller — make the default case trivial." +- Agent 1: "Minimize the interface: aim for 1–3 entry points max. Maximise leverage per entry point." +- Agent 2: "Maximise flexibility: support many use cases and extension." +- Agent 3: "Optimise for the most common caller: make the default case trivial." - Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." -Include both [SKILL.md](SKILL.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. +Include both [SKILL.md](SKILL.md) vocabulary and GLOSSARY.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. Each sub-agent outputs: -1. Interface (types, methods, params — plus invariants, ordering, error modes) +1. Interface (types, methods, params, plus invariants, ordering, error modes) 2. Usage example showing how callers use it 3. What the implementation hides behind the seam 4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) -5. Trade-offs — where leverage is high, where it's thin +5. Trade-offs: where leverage is high, where it's thin ### 3. Present and compare Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. -After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated — the user wants a strong read, not a menu. +After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu. diff --git a/.agents/skills/codebase-design/SKILL.md b/.agents/skills/codebase-design/SKILL.md index 16620c24..3f63c814 100644 --- a/.agents/skills/codebase-design/SKILL.md +++ b/.agents/skills/codebase-design/SKILL.md @@ -9,23 +9,23 @@ Design **deep modules**: a lot of behaviour behind a small interface, placed at ## Glossary -Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. +Use these terms exactly: don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. -**Module** — anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. +**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. -**Interface** — everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow — they refer only to the type-level surface). +**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface). -**Implementation** — what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. +**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. -**Depth** — leverage at the interface: the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation. +**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation. -**Seam** _(Michael Feathers)_ — a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context). +**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context). -**Adapter** — a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). +**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). -**Leverage** — what callers get from depth: more capability per unit of interface they learn. One implementation pays back across N call sites and M tests. +**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests. -**Locality** — what maintainers get from depth: change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere. +**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere. ## Deep vs shallow @@ -59,7 +59,7 @@ When designing an interface, ask: ## Principles -- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. +- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. - **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. - **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. - **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. @@ -105,10 +105,10 @@ Good interfaces make testing natural: ## Rejected framings - **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. -- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know. +- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know. - **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. ## Going deeper -- **Deepening a cluster given its dependencies** — see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing. -- **Exploring alternative interfaces** — see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement. +- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing. +- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement. diff --git a/.agents/skills/diagnosing-bugs/SKILL.md b/.agents/skills/diagnosing-bugs/SKILL.md index 7f8acf7e..1b929e29 100644 --- a/.agents/skills/diagnosing-bugs/SKILL.md +++ b/.agents/skills/diagnosing-bugs/SKILL.md @@ -7,26 +7,26 @@ description: Diagnosis loop for hard bugs and performance regressions. Use when A discipline for hard bugs. Skip phases only when explicitly justified. -When exploring the codebase, read `CONTEXT.md` (if it exists) to get a clear mental model of the relevant modules, and check ADRs in the area you're touching. +When exploring the codebase, read `GLOSSARY.md` (if it exists) to get a clear mental model of the relevant modules, and check ADRs in the area you're touching. ## Redact -This skill has you show commands, outputs and captured artifacts. **Redact every secret first** — write `` in its place. Build loops against env vars, so the credential stays in the environment rather than in what you show. Captured artifacts carry auth headers: quote only the lines that carry the signal. +This skill has you show commands, outputs and captured artifacts. **Redact every secret first**: write `` in its place. Build loops against env vars, so the credential stays in the environment rather than in what you show. Captured artifacts carry auth headers: quote only the lines that carry the signal. If the redacted output is not enough to diagnose the bug, say so and ask the user. -## Phase 1 — Build a feedback loop +## Phase 1: Build a feedback loop -**This is the skill.** Everything else is mechanical. If you have a **tight** pass/fail signal for the bug — one that goes red on _this_ bug — you will find the cause; bisection, hypothesis-testing, and instrumentation all just consume it. If you don't have one, no amount of staring at code will save you. +**This is the skill.** Everything else is mechanical. If you have a **tight** pass/fail signal for the bug (one that goes red on _this_ bug), you will find the cause; bisection, hypothesis-testing, and instrumentation all just consume it. If you don't have one, no amount of staring at code will save you. Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.** -### Ways to construct one — try them in roughly this order +### Ways to construct one, in roughly this order -1. **Failing test** at whatever seam reaches the bug — unit, integration, e2e. +1. **Failing test** at whatever seam reaches the bug: unit, integration, e2e. 2. **Curl / HTTP script** against a running dev server. 3. **CLI invocation** with a fixture input, diffing stdout against a known-good snapshot. -4. **Headless browser script** (Playwright / Puppeteer) — drives the UI, asserts on DOM/console/network. +4. **Headless browser script** (Playwright / Puppeteer) that drives the UI and asserts on DOM/console/network. 5. **Replay a captured trace.** Save a real network request / payload / event log to disk; replay it through the code path in isolation. 6. **Throwaway harness.** Spin up a minimal subset of the system (one service, mocked deps) that exercises the bug code path with a single function call. 7. **Property / fuzz loop.** If the bug is "sometimes wrong output", run 1000 random inputs and look for the failure mode. @@ -44,48 +44,48 @@ Treat the loop as a product. Once you have _a_ loop, **tighten** it: - Can I make the signal sharper? (Assert on the specific symptom, not "didn't crash".) - Can I make it more deterministic? (Pin time, seed RNG, isolate filesystem, freeze network.) -A 30-second flaky loop is barely better than no loop; a 2-second deterministic one is tight — a debugging superpower. +A 30-second flaky loop is barely better than no loop; a 2-second deterministic one is tight, a debugging superpower. ### Non-deterministic bugs -The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not — keep raising the rate until it's debuggable. +The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not, so keep raising the rate until it's debuggable. ### When you genuinely cannot build a loop Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a redacted captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop. -### Completion criterion — a tight loop that goes red +### Completion criterion: a tight loop that goes red -Phase 1 is done when the loop is **tight** and **red-capable**: you can name **one command** — a script path, a test invocation, a curl — that you have **already run at least once** (show the invocation and its output, redacted), and that is: +Phase 1 is done when the loop is **tight** and **red-capable**: you can name **one command** (a script path, a test invocation, a curl) that you have **already run at least once** (show the invocation and its output, redacted), and that is: -- [ ] **Red-capable** — it drives the actual bug code path and asserts the **user's exact symptom**, so it can go red on this bug and green once fixed. Not "runs without erroring" — it must be able to _catch this specific bug_. -- [ ] **Deterministic** — same verdict every run (flaky bugs: a pinned, high reproduction rate, per above). -- [ ] **Fast** — seconds, not minutes. -- [ ] **Agent-runnable** — you can run it unattended; a human in the loop only via `scripts/hitl-loop.template.sh`. +- [ ] **Red-capable**: it drives the actual bug code path and asserts the **user's exact symptom**, so it can go red on this bug and green once fixed. Not "runs without erroring"; it must be able to _catch this specific bug_. +- [ ] **Deterministic**: same verdict every run (flaky bugs: a pinned, high reproduction rate, per above). +- [ ] **Fast**: seconds, not minutes. +- [ ] **Agent-runnable**: you can run it unattended; a human in the loop only via `scripts/hitl-loop.template.sh`. -If you catch yourself reading code to build a theory before this command exists, **stop — jumping straight to a hypothesis is the exact failure this skill prevents.** No red-capable command, no Phase 2. +If you catch yourself reading code to build a theory before this command exists, **stop: jumping straight to a hypothesis is the exact failure this skill prevents.** No red-capable command, no Phase 2. -## Phase 2 — Reproduce + minimise +## Phase 2: Reproduce + minimise -Run the loop. Watch it go red — the bug appears. +Run the loop. Watch it go red as the bug appears. Confirm: -- [ ] The loop produces the failure mode the **user** described — not a different failure that happens to be nearby. Wrong bug = wrong fix. +- [ ] The loop produces the failure mode the **user** described, not a different failure that happens to be nearby. Wrong bug = wrong fix. - [ ] The failure is reproducible across multiple runs (or, for non-deterministic bugs, reproducible at a high enough rate to debug against). - [ ] You have captured the exact symptom (error message, wrong output, slow timing) so later phases can verify the fix actually addresses it. ### Minimise -Once it's red, shrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut — keep only what's load-bearing for the failure. +Once it's red, shrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut, and keep only what's load-bearing for the failure. Why bother: a minimal repro shrinks the hypothesis space in Phase 3 (fewer moving parts left to suspect) and becomes the clean regression test in Phase 5. -Done when **every remaining element is load-bearing** — removing any one of them makes the loop go green. +Done when **every remaining element is load-bearing**: removing any one of them makes the loop go green. Do not proceed until you have reproduced **and** minimised. -## Phase 3 — Hypothesise +## Phase 3: Hypothesise Generate **3–5 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea. @@ -93,11 +93,11 @@ Each hypothesis must be **falsifiable**: state the prediction it makes. > Format: "If is the cause, then will make the bug disappear / will make it worse." -If you cannot state the prediction, the hypothesis is a vibe — discard or sharpen it. +If you cannot state the prediction, the hypothesis is a vibe: discard or sharpen it. -**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it — proceed with your ranking if the user is AFK. +**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it; proceed with your ranking if the user is AFK. -## Phase 4 — Instrument +## Phase 4: Instrument Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.** @@ -111,9 +111,9 @@ Tool preference: **Perf branch.** For performance regressions, logs are usually wrong. Instead: establish a baseline measurement (timing harness, `performance.now()`, profiler, query plan), then bisect. Measure first, fix second. -## Phase 5 — Fix + regression test +## Phase 5: Fix + regression test -Write the regression test **before the fix** — but only if there is a **correct seam** for it. +Write the regression test **before the fix**, but only if there is a **correct seam** for it. A correct seam is one where the test exercises the **real bug pattern** as it occurs at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers, unit test that can't replicate the chain that triggered the bug), a regression test there gives false confidence. @@ -127,7 +127,7 @@ If a correct seam exists: 4. Watch it pass. 5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario. -## Phase 6 — Cleanup + post-mortem +## Phase 6: Cleanup Required before declaring done: @@ -135,6 +135,4 @@ Required before declaring done: - [ ] Regression test passes (or absence of seam is documented) - [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix) - [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location) -- [ ] The hypothesis that turned out correct is stated in the commit / PR message — so the next debugger learns - -**Then ask: what would have prevented this bug?** If the answer involves architectural change (no good test seam, tangled callers, hidden coupling) hand off to the `/improve-codebase-architecture` skill with the specifics. Make the recommendation **after** the fix is in, not before — you have more information now than when you started. +- [ ] The hypothesis that turned out correct is stated in the commit / PR message, so the next debugger learns diff --git a/.agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh b/.agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh index 43daedd1..24319846 100644 --- a/.agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +++ b/.agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh @@ -12,8 +12,8 @@ # # At the end, captured values are printed as KEY=VALUE for the agent to parse. # -# `capture` prints its value back to the terminal, where the agent reads it — so -# capture observations, and leave signing in to the user as a `step`. +# `capture` prints its value back to the terminal, where the agent reads it, +# so capture observations, and leave signing in to the user as a `step`. set -euo pipefail diff --git a/.agents/skills/domain-modeling/ADR-FORMAT.md b/.agents/skills/domain-modeling/ADR-FORMAT.md index da7e78ec..d7e61f30 100644 --- a/.agents/skills/domain-modeling/ADR-FORMAT.md +++ b/.agents/skills/domain-modeling/ADR-FORMAT.md @@ -2,7 +2,7 @@ ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc. -Create the `docs/adr/` directory lazily — only when the first ADR is needed. +Create the `docs/adr/` directory lazily: only when the first ADR is needed. ## Template @@ -12,15 +12,15 @@ Create the `docs/adr/` directory lazily — only when the first ADR is needed. {1-3 sentences: what's the context, what did we decide, and why.} ``` -That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why* — not in filling out sections. +That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections. ## Optional sections Only include these when they add genuine value. Most ADRs won't need them. -- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`) — useful when decisions are revisited -- **Considered Options** — only when the rejected alternatives are worth remembering -- **Consequences** — only when non-obvious downstream effects need to be called out +- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited +- **Considered Options**: only when the rejected alternatives are worth remembering +- **Consequences**: only when non-obvious downstream effects need to be called out ## Numbering @@ -30,18 +30,18 @@ Scan `docs/adr/` for the highest existing number and increment by one. All three of these must be true: -1. **Hard to reverse** — the cost of changing your mind later is meaningful -2. **Surprising without context** — a future reader will look at the code and wonder "why on earth did they do it this way?" -3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons -If a decision is easy to reverse, skip it — you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing." +If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing." ### What qualifies - **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres." - **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP." -- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library — just the ones that would take a quarter to swap out. +- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out. - **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s. - **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate. - **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract." -- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it — otherwise someone will suggest GraphQL again in six months. +- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months. diff --git a/.agents/skills/domain-modeling/CONTEXT-FORMAT.md b/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md similarity index 70% rename from .agents/skills/domain-modeling/CONTEXT-FORMAT.md rename to .agents/skills/domain-modeling/GLOSSARY-FORMAT.md index eaf2a185..9c0b4c7a 100644 --- a/.agents/skills/domain-modeling/CONTEXT-FORMAT.md +++ b/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md @@ -1,4 +1,4 @@ -# CONTEXT.md Format +# GLOSSARY.md Format ## Structure @@ -31,18 +31,18 @@ _Avoid_: Client, buyer, account ## Single vs multi-context repos -**Single context (most repos):** One `CONTEXT.md` at the repo root. +**Single context (most repos):** One `GLOSSARY.md` at the repo root. -**Multiple contexts:** A `CONTEXT-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other: +**Multiple contexts:** A `GLOSSARY-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other: ```md -# Context Map +# Glossary Map ## Contexts -- [Ordering](./src/ordering/CONTEXT.md) — receives and tracks customer orders -- [Billing](./src/billing/CONTEXT.md) — generates invoices and processes payments -- [Fulfillment](./src/fulfillment/CONTEXT.md) — manages warehouse picking and shipping +- [Ordering](./src/ordering/GLOSSARY.md): receives and tracks customer orders +- [Billing](./src/billing/GLOSSARY.md): generates invoices and processes payments +- [Fulfillment](./src/fulfillment/GLOSSARY.md): manages warehouse picking and shipping ## Relationships @@ -53,8 +53,8 @@ _Avoid_: Client, buyer, account The skill infers which structure applies: -- If `CONTEXT-MAP.md` exists, read it to find contexts -- If only a root `CONTEXT.md` exists, single context -- If neither exists, create a root `CONTEXT.md` lazily when the first term is resolved +- If `GLOSSARY-MAP.md` exists, read it to find contexts +- If only a root `GLOSSARY.md` exists, single context +- If neither exists, create a root `GLOSSARY.md` lazily when the first term is resolved When multiple contexts exist, infer which one the current topic relates to. If unclear, ask. diff --git a/.agents/skills/domain-modeling/SKILL.md b/.agents/skills/domain-modeling/SKILL.md index d0f7e1a5..a4438c68 100644 --- a/.agents/skills/domain-modeling/SKILL.md +++ b/.agents/skills/domain-modeling/SKILL.md @@ -1,11 +1,11 @@ --- name: domain-modeling -description: Build and sharpen a project's domain model. Use when the user wants to pin down domain terminology or a ubiquitous language, record an architectural decision, or when another skill needs to maintain the domain model. +description: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR. --- # Domain Modeling -Actively build and sharpen the project's domain model as you design. This is the *active* discipline — challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `CONTEXT.md` for vocabulary is not this skill — that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.) +Actively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `GLOSSARY.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.) ## File structure @@ -13,7 +13,7 @@ Most repos have a single context: ``` / -├── CONTEXT.md +├── GLOSSARY.md ├── docs/ │ └── adr/ │ ├── 0001-event-sourced-orders.md @@ -21,33 +21,33 @@ Most repos have a single context: └── src/ ``` -If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives: +If a `GLOSSARY-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives: ``` / -├── CONTEXT-MAP.md +├── GLOSSARY-MAP.md ├── docs/ │ └── adr/ ← system-wide decisions ├── src/ │ ├── ordering/ -│ │ ├── CONTEXT.md +│ │ ├── GLOSSARY.md │ │ └── docs/adr/ ← context-specific decisions │ └── billing/ -│ ├── CONTEXT.md +│ ├── GLOSSARY.md │ └── docs/adr/ ``` -Create files lazily — only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed. +Create files lazily: only when you have something to write. If no `GLOSSARY.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed. ## During the session ### Challenge against the glossary -When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y — which is it?" +When the user uses a term that conflicts with the existing language in `GLOSSARY.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y. Which is it?" ### Sharpen fuzzy language -When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account' — do you mean the Customer or the User? Those are different things." +When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account': do you mean the Customer or the User? Those are different things." ### Discuss concrete scenarios @@ -55,20 +55,20 @@ When domain relationships are being discussed, stress-test them with specific sc ### Cross-reference with code -When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible — which is right?" +When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible. Which is right?" -### Update CONTEXT.md inline +### Update GLOSSARY.md inline -When a term is resolved, update `CONTEXT.md` right there. Don't batch these up — capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md). +When a term is resolved, update `GLOSSARY.md` right there. Don't batch these up: capture them as they happen. Use the format in [GLOSSARY-FORMAT.md](./GLOSSARY-FORMAT.md). -`CONTEXT.md` should be totally devoid of implementation details. Do not treat `CONTEXT.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else. +`GLOSSARY.md` should be totally devoid of implementation details. Do not treat `GLOSSARY.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else. ### Offer ADRs sparingly Only offer to create an ADR when all three are true: -1. **Hard to reverse** — the cost of changing your mind later is meaningful -2. **Surprising without context** — a future reader will wonder "why did they do it this way?" -3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will wonder "why did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md). diff --git a/.agents/skills/elysia-api-routes/SKILL.md b/.agents/skills/elysia-api-routes/SKILL.md index 7c963e06..ecbaaa83 100644 --- a/.agents/skills/elysia-api-routes/SKILL.md +++ b/.agents/skills/elysia-api-routes/SKILL.md @@ -88,4 +88,4 @@ Use POST upsert semantics: - Check that every accepted input has a route-level Zod schema. - Check that every route has `response: ApiUtils.mapResponseModel(...)`. - Check that expected failures are thrown as exceptions; route mounting maps them centrally with `ApiUtils.mapError(...)`. -- Check `CONTEXT.md` for REST API domain terms and write semantics before changing behavior. +- Check `GLOSSARY.md` for REST API domain terms and write semantics before changing behavior. diff --git a/.agents/skills/grill-me/SKILL.md b/.agents/skills/grill-me/SKILL.md index 9470cfcf..3947ff9c 100644 --- a/.agents/skills/grill-me/SKILL.md +++ b/.agents/skills/grill-me/SKILL.md @@ -4,4 +4,4 @@ description: A relentless interview to sharpen a plan or design. disable-model-invocation: true --- -Run a `/grilling` session. +Call the Skill tool with "grilling". diff --git a/.agents/skills/grill-with-docs/SKILL.md b/.agents/skills/grill-with-docs/SKILL.md index bed05d2b..62b9efb6 100644 --- a/.agents/skills/grill-with-docs/SKILL.md +++ b/.agents/skills/grill-with-docs/SKILL.md @@ -4,4 +4,4 @@ description: A relentless interview to sharpen a plan or design, which also crea disable-model-invocation: true --- -Run a `/grilling` session, using the `/domain-modeling` skill. +Call the Skill tool twice, for "grilling" and "domain-modeling". diff --git a/.agents/skills/grilling/SKILL.md b/.agents/skills/grilling/SKILL.md index 95bd01ee..8ca78c6d 100644 --- a/.agents/skills/grilling/SKILL.md +++ b/.agents/skills/grilling/SKILL.md @@ -5,18 +5,24 @@ description: Grill the user relentlessly about a plan, decision, or idea. Use wh Interview the user relentlessly until you reach a shared understanding. Map this as a **design tree**: every decision branches into the decisions that hang off it. -Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled — the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round. +Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled: the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round. -Each question should be formatted like so: +Format a round like so: ``` ❓ **Q1** - ****: +➡️ + +--- + +❓ **Q2** - ****: + ➡️ ``` -Each round the user answers reshapes the tree — settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one. +Each round the user answers reshapes the tree: settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one. -Finding _facts_ is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it — don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report — ask the rest of the frontier now. The _decisions_ are the user's — put each to them and wait. +Finding _facts_ is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it; don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report; ask the rest of the frontier now. The _decisions_ are the user's: put each to them and wait. The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Do not act on it until the user confirms you have reached a shared understanding. diff --git a/.agents/skills/handoff/SKILL.md b/.agents/skills/handoff/SKILL.md index 043d9e13..a224edc6 100644 --- a/.agents/skills/handoff/SKILL.md +++ b/.agents/skills/handoff/SKILL.md @@ -5,9 +5,9 @@ argument-hint: "What will the next session be used for?" disable-model-invocation: true --- -Write a handoff document summarising the current conversation so a fresh agent can continue the work. Save to the temporary directory of the user's OS - not the current workspace. +Write a handoff document summarising the current conversation so a fresh agent can continue the work. Save to the temporary directory of the user's OS (`$TMPDIR`, else `/tmp`; `%TEMP%` on Windows) - not the current workspace. -Include a "suggested skills" section in the document, which suggests skills that the agent should invoke. +Include a "suggested skills" section in the document, naming which skills the next agent should call the Skill tool for. Do not duplicate content already captured in other artifacts (specs, plans, ADRs, issues, commits, diffs). Reference them by path or URL instead. diff --git a/.agents/skills/implement-spec/SKILL.md b/.agents/skills/implement-spec/SKILL.md new file mode 100644 index 00000000..18392379 --- /dev/null +++ b/.agents/skills/implement-spec/SKILL.md @@ -0,0 +1,40 @@ +--- +name: implement-spec +description: "Implement the result of /to-spec and /to-tickets in code." +disable-model-invocation: true +--- + +You have been provided a spec. This spec should have tickets associated with it, describing how to implement the spec. + +The issue tracker should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. + +The goal is the entire spec implemented on a single **integration branch**, with every ticket resolved the way the issue tracker closes work. + +The tickets are not a list of steps. They are a **task graph** with blocking relationships between them. This means there is always a **frontier** of tickets which are ready to be grabbed. + +Communication to and from subagents should be sparse. Communicate primarily through **context pointers**: to the spec, tickets, research notes, and previous commits. Don't duplicate information already available via pointers. + +**Implementer subagents** should be run in the background where possible for maximum concurrency. + +## Steps + +1. Read the spec and tickets to understand the task graph. + +2. (optional) Use an **exploration subagent** to conduct any exploration required by the tickets - relevant codebase files or external documentation. Ensure the exploration subagent can save files - it should save its markdown notes in a directory outside the repo, accessible by all future subagents. This lets **implementer subagents** focus on implementation rather than exploration. + +3. Create the integration branch. If the issue tracker closes work through PRs, or the user asks for one, open a draft PR after the first merge in step 5 (a branch with no commits ahead of main can't open one), marked as closing the spec and tickets. + +4. Use **implementer subagents** to implement each ticket, each in its own worktree on its own branch. Each implementer subagent: + - confirms its worktree is based on the integration branch before starting, and resets onto it if not; + - calls the Skill tool with `tdd` to build the ticket; + - merges the integration branch tip into its own branch before reporting done + +5. Once an **implementer subagent** completes, merge its work to the integration branch with a **merger subagent**. + +6. If this changes the **frontier** of available tickets, kick off more **implementer subagents** to work on the new tickets. This allows for maximum concurrency. + +7. Once all tickets are complete, call the Skill tool with `code-review` on the integration branch. Fix all issues raised by the code review in a single **implementer subagent**. + +8. If a draft PR exists, mark it ready for review. Otherwise, resolve each ticket the way the issue tracker closes work, and report the integration branch. + +9. Clean up all **implementer subagent** worktrees. diff --git a/.agents/skills/implement-spec/agents/openai.yaml b/.agents/skills/implement-spec/agents/openai.yaml new file mode 100644 index 00000000..f5e91af2 --- /dev/null +++ b/.agents/skills/implement-spec/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Implement Spec" + short_description: "Implement the result of /to-spec and /to-tickets in code." +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/implement/SKILL.md b/.agents/skills/implement/SKILL.md index 7a0b11f5..edcd514c 100644 --- a/.agents/skills/implement/SKILL.md +++ b/.agents/skills/implement/SKILL.md @@ -6,10 +6,10 @@ disable-model-invocation: true Implement the work described by the user in the spec or tickets. -Use /tdd where possible, at pre-agreed seams. +Call the Skill tool with "tdd" where possible, at pre-agreed seams. Run typechecking regularly, single test files regularly, and the full test suite once at the end. -Once done, use /code-review to review the work. +Once done, call the Skill tool with "code-review" to review the work. Commit your work to the current branch. diff --git a/.agents/skills/improve-codebase-architecture/HTML-REPORT.md b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md index 17f6d2c7..e39e8255 100644 --- a/.agents/skills/improve-codebase-architecture/HTML-REPORT.md +++ b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md @@ -1,6 +1,6 @@ # HTML Report Format -The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two — don't lean on Mermaid for everything, it'll start to look generic. +The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic. ## Scaffold @@ -9,7 +9,7 @@ The architectural review is rendered as a single self-contained HTML file in the - Architecture review — {{repo name}} + Architecture review for {{repo name}}