refactor(server): move the team runtime into a postponed package (P1.1)
Team mode stays in the repository but is not built or shipped (ADR-0003). - The team server (index.ts, config, db, daemons, plugins, proactive, routes, scheduler, services, ws, drizzle migrations) and its tests move from @waggle/server to packages/team-server (@waggle/team-server, private). It keeps its own copies of the logger and the agent-group executor, so it does not import @waggle/server. @clerk/fastify, bullmq, ioredis, postgres, drizzle-orm, drizzle-kit, cron-parser and @waggle/waggle-dance leave @waggle/server; the launcher drops the same team-only dependencies. - build:packages no longer builds waggle-dance or the worker: nothing in the community edition imports them, and the worker's project reference would otherwise build the team server. The worker now imports from team-server; the team Dockerfile builds both explicitly. - The sidecar no longer starts the team server when DATABASE_URL is set, and loses the team routes (/api/team/*, /api/teams), the WaggleDance routes and bridge (/api/waggle-dance/*), the Team server binding and egress guard, the WebSocket team client, the TeamSync cache and pushes, team audit forwarding, team workspace registration and the team capability-policy lookup in chat. The in-process room signal bus stays: agent groups, fleet runs and external tool runs use it. middleware/audit.ts was dead and is deleted. - @waggle/core loses TeamSync and the teamServer part of WaggleConfig. A teamServer key in config.json is ignored and kept on save, as P0.1 does for the tier keys. Workspaces lose teamServerUrl and teamUserId; teamId and teamRole stay because workspaces from a shared data directory still carry them and the viewer write guards read them. POST /api/workspaces ignores team fields. - The sidecar bundle no longer marks the team packages as external. The agent still references the TeamSync type in orchestrator.ts and pattern-write-back.ts; those files are being rewritten in P1.5 and drop it there. Logs UF-030 and UF-031 (team sync and team policy defects found while removing the code).
This commit is contained in:
25
packages/team-server/README.md
Normal file
25
packages/team-server/README.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# @waggle/team-server
|
||||
|
||||
The multi-user team server: Fastify with Clerk authentication, PostgreSQL through drizzle,
|
||||
Redis and BullMQ jobs, a WebSocket gateway, cron and the team routes (teams, agents, tasks,
|
||||
messages, knowledge, resources, audit, analytics, capability governance).
|
||||
|
||||
**Postponed.** Team mode stays in the repository but is not built, bundled or shipped in the
|
||||
community edition ([ADR-0003](../../docs/oss/adr/0003-team-mode-postponed.md)). This package is
|
||||
not part of `npm run build:packages`, and the local sidecar (`@waggle/server`) does not import
|
||||
or start it. Do not add features here until the owner decides otherwise.
|
||||
|
||||
`packages/worker` and `packages/waggle-dance` belong to the same postponed team runtime.
|
||||
|
||||
## Running it anyway
|
||||
|
||||
The server needs PostgreSQL and Redis (see `docker-compose.yml`) and a Clerk secret key.
|
||||
|
||||
```bash
|
||||
cd packages/team-server
|
||||
DATABASE_URL=postgres://waggle:waggle_dev@localhost:5434/waggle npx tsx src/db/migrate.ts
|
||||
DATABASE_URL=... REDIS_URL=redis://localhost:6381 CLERK_SECRET_KEY=... npx tsx src/index.ts
|
||||
```
|
||||
|
||||
Most tests in `tests/` need the same services and are listed in `vitest.infra-suites.ts`;
|
||||
`npm run test:infra` runs them.
|
||||
10
packages/team-server/drizzle.config.ts
Normal file
10
packages/team-server/drizzle.config.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from 'drizzle-kit';
|
||||
|
||||
export default defineConfig({
|
||||
schema: './src/db/schema.ts',
|
||||
out: './drizzle',
|
||||
dialect: 'postgresql',
|
||||
dbCredentials: {
|
||||
url: process.env.DATABASE_URL ?? 'postgres://waggle:waggle_dev@localhost:5434/waggle',
|
||||
},
|
||||
});
|
||||
229
packages/team-server/drizzle/0000_wild_glorian.sql
Normal file
229
packages/team-server/drizzle/0000_wild_glorian.sql
Normal file
@@ -0,0 +1,229 @@
|
||||
CREATE TABLE "agent_audit_log" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"team_id" uuid,
|
||||
"agent_name" text NOT NULL,
|
||||
"action_type" text NOT NULL,
|
||||
"description" text NOT NULL,
|
||||
"before_state" jsonb,
|
||||
"after_state" jsonb,
|
||||
"requires_approval" boolean DEFAULT false NOT NULL,
|
||||
"approved" boolean,
|
||||
"approved_by" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "agent_group_members" (
|
||||
"group_id" uuid NOT NULL,
|
||||
"agent_id" uuid NOT NULL,
|
||||
"role_in_group" text DEFAULT 'worker' NOT NULL,
|
||||
"execution_order" integer DEFAULT 0 NOT NULL,
|
||||
CONSTRAINT "agent_group_members_group_id_agent_id_pk" PRIMARY KEY("group_id","agent_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "agent_groups" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"description" text,
|
||||
"strategy" text DEFAULT 'parallel' NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "agent_jobs" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"team_id" uuid NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"job_type" text NOT NULL,
|
||||
"status" text DEFAULT 'queued' NOT NULL,
|
||||
"input" jsonb NOT NULL,
|
||||
"output" jsonb,
|
||||
"started_at" timestamp with time zone,
|
||||
"completed_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "agents" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"team_id" uuid,
|
||||
"name" text NOT NULL,
|
||||
"role" text,
|
||||
"system_prompt" text,
|
||||
"model" text DEFAULT 'claude-haiku-4-5' NOT NULL,
|
||||
"tools" jsonb DEFAULT '[]'::jsonb NOT NULL,
|
||||
"config" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "cron_schedules" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"team_id" uuid NOT NULL,
|
||||
"created_by" uuid NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"cron_expr" text NOT NULL,
|
||||
"job_type" text NOT NULL,
|
||||
"job_config" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"enabled" boolean DEFAULT true NOT NULL,
|
||||
"last_run_at" timestamp with time zone,
|
||||
"next_run_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "messages" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"team_id" uuid NOT NULL,
|
||||
"sender_id" uuid NOT NULL,
|
||||
"type" text NOT NULL,
|
||||
"subtype" text NOT NULL,
|
||||
"content" jsonb NOT NULL,
|
||||
"reference_id" uuid,
|
||||
"routing" jsonb,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "proactive_patterns" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"trigger" jsonb NOT NULL,
|
||||
"suggestion_type" text NOT NULL,
|
||||
"template" text NOT NULL,
|
||||
"enabled" boolean DEFAULT true NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "scout_findings" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid,
|
||||
"team_id" uuid,
|
||||
"source" text NOT NULL,
|
||||
"category" text NOT NULL,
|
||||
"title" text NOT NULL,
|
||||
"summary" text,
|
||||
"relevance_score" real DEFAULT 0 NOT NULL,
|
||||
"url" text,
|
||||
"status" text DEFAULT 'new' NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "suggestions_log" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"pattern_id" uuid NOT NULL,
|
||||
"context" jsonb NOT NULL,
|
||||
"status" text DEFAULT 'pending' NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "tasks" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"team_id" uuid NOT NULL,
|
||||
"title" text NOT NULL,
|
||||
"description" text,
|
||||
"status" text DEFAULT 'open' NOT NULL,
|
||||
"priority" text DEFAULT 'normal' NOT NULL,
|
||||
"created_by" uuid NOT NULL,
|
||||
"assigned_to" uuid,
|
||||
"parent_task_id" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "team_entities" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"team_id" uuid NOT NULL,
|
||||
"entity_type" text NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"properties" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"shared_by" uuid NOT NULL,
|
||||
"valid_from" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"valid_to" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "team_members" (
|
||||
"team_id" uuid NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"role" text DEFAULT 'member' NOT NULL,
|
||||
"role_description" text,
|
||||
"interests" jsonb,
|
||||
"joined_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "team_members_team_id_user_id_pk" PRIMARY KEY("team_id","user_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "team_relations" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"team_id" uuid NOT NULL,
|
||||
"source_id" uuid NOT NULL,
|
||||
"target_id" uuid NOT NULL,
|
||||
"relation_type" text NOT NULL,
|
||||
"confidence" real DEFAULT 1 NOT NULL,
|
||||
"properties" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "team_resources" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"team_id" uuid NOT NULL,
|
||||
"resource_type" text NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"description" text,
|
||||
"config" jsonb NOT NULL,
|
||||
"shared_by" uuid NOT NULL,
|
||||
"rating" real DEFAULT 0 NOT NULL,
|
||||
"use_count" integer DEFAULT 0 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "teams" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"slug" text NOT NULL,
|
||||
"owner_id" uuid NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "teams_slug_unique" UNIQUE("slug")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "users" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"clerk_id" text NOT NULL,
|
||||
"display_name" text NOT NULL,
|
||||
"email" text NOT NULL,
|
||||
"avatar_url" text,
|
||||
"mind_path" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "users_clerk_id_unique" UNIQUE("clerk_id"),
|
||||
CONSTRAINT "users_email_unique" UNIQUE("email")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "agent_audit_log" ADD CONSTRAINT "agent_audit_log_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "agent_audit_log" ADD CONSTRAINT "agent_audit_log_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "agent_audit_log" ADD CONSTRAINT "agent_audit_log_approved_by_users_id_fk" FOREIGN KEY ("approved_by") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "agent_group_members" ADD CONSTRAINT "agent_group_members_group_id_agent_groups_id_fk" FOREIGN KEY ("group_id") REFERENCES "public"."agent_groups"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "agent_group_members" ADD CONSTRAINT "agent_group_members_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "agent_groups" ADD CONSTRAINT "agent_groups_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "agent_jobs" ADD CONSTRAINT "agent_jobs_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "agent_jobs" ADD CONSTRAINT "agent_jobs_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "agents" ADD CONSTRAINT "agents_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "agents" ADD CONSTRAINT "agents_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "cron_schedules" ADD CONSTRAINT "cron_schedules_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "cron_schedules" ADD CONSTRAINT "cron_schedules_created_by_users_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "messages" ADD CONSTRAINT "messages_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "messages" ADD CONSTRAINT "messages_sender_id_users_id_fk" FOREIGN KEY ("sender_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "scout_findings" ADD CONSTRAINT "scout_findings_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "scout_findings" ADD CONSTRAINT "scout_findings_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "suggestions_log" ADD CONSTRAINT "suggestions_log_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "suggestions_log" ADD CONSTRAINT "suggestions_log_pattern_id_proactive_patterns_id_fk" FOREIGN KEY ("pattern_id") REFERENCES "public"."proactive_patterns"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "tasks" ADD CONSTRAINT "tasks_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "tasks" ADD CONSTRAINT "tasks_created_by_users_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "tasks" ADD CONSTRAINT "tasks_assigned_to_users_id_fk" FOREIGN KEY ("assigned_to") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_entities" ADD CONSTRAINT "team_entities_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_entities" ADD CONSTRAINT "team_entities_shared_by_users_id_fk" FOREIGN KEY ("shared_by") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_members" ADD CONSTRAINT "team_members_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_members" ADD CONSTRAINT "team_members_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_relations" ADD CONSTRAINT "team_relations_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_relations" ADD CONSTRAINT "team_relations_source_id_team_entities_id_fk" FOREIGN KEY ("source_id") REFERENCES "public"."team_entities"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_relations" ADD CONSTRAINT "team_relations_target_id_team_entities_id_fk" FOREIGN KEY ("target_id") REFERENCES "public"."team_entities"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_resources" ADD CONSTRAINT "team_resources_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_resources" ADD CONSTRAINT "team_resources_shared_by_users_id_fk" FOREIGN KEY ("shared_by") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "teams" ADD CONSTRAINT "teams_owner_id_users_id_fk" FOREIGN KEY ("owner_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;
|
||||
45
packages/team-server/drizzle/0001_redundant_sauron.sql
Normal file
45
packages/team-server/drizzle/0001_redundant_sauron.sql
Normal file
@@ -0,0 +1,45 @@
|
||||
CREATE TABLE "team_capability_overrides" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"team_id" uuid NOT NULL,
|
||||
"capability_name" text NOT NULL,
|
||||
"capability_type" text NOT NULL,
|
||||
"decision" text NOT NULL,
|
||||
"reason" text DEFAULT '' NOT NULL,
|
||||
"decided_by" uuid NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"decided_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "team_capability_policies" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"team_id" uuid NOT NULL,
|
||||
"role" text NOT NULL,
|
||||
"allowed_sources" jsonb DEFAULT '[]'::jsonb NOT NULL,
|
||||
"blocked_tools" jsonb DEFAULT '[]'::jsonb NOT NULL,
|
||||
"approval_threshold" text DEFAULT 'none' NOT NULL,
|
||||
"updated_by" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "team_capability_requests" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"team_id" uuid NOT NULL,
|
||||
"requested_by" uuid NOT NULL,
|
||||
"capability_name" text NOT NULL,
|
||||
"capability_type" text NOT NULL,
|
||||
"justification" text NOT NULL,
|
||||
"status" text DEFAULT 'pending' NOT NULL,
|
||||
"decided_by" uuid,
|
||||
"decision_reason" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"decided_at" timestamp with time zone
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "team_capability_overrides" ADD CONSTRAINT "team_capability_overrides_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_capability_overrides" ADD CONSTRAINT "team_capability_overrides_decided_by_users_id_fk" FOREIGN KEY ("decided_by") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_capability_policies" ADD CONSTRAINT "team_capability_policies_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_capability_policies" ADD CONSTRAINT "team_capability_policies_updated_by_users_id_fk" FOREIGN KEY ("updated_by") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_capability_requests" ADD CONSTRAINT "team_capability_requests_team_id_teams_id_fk" FOREIGN KEY ("team_id") REFERENCES "public"."teams"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_capability_requests" ADD CONSTRAINT "team_capability_requests_requested_by_users_id_fk" FOREIGN KEY ("requested_by") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "team_capability_requests" ADD CONSTRAINT "team_capability_requests_decided_by_users_id_fk" FOREIGN KEY ("decided_by") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;
|
||||
1604
packages/team-server/drizzle/meta/0000_snapshot.json
Normal file
1604
packages/team-server/drizzle/meta/0000_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
1924
packages/team-server/drizzle/meta/0001_snapshot.json
Normal file
1924
packages/team-server/drizzle/meta/0001_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
20
packages/team-server/drizzle/meta/_journal.json
Normal file
20
packages/team-server/drizzle/meta/_journal.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1772915372224,
|
||||
"tag": "0000_wild_glorian",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1772915372225,
|
||||
"tag": "0001_redundant_sauron",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
36
packages/team-server/package.json
Normal file
36
packages/team-server/package.json
Normal file
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "@waggle/team-server",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Waggle team server. Postponed: not built or shipped in the community edition (ADR-0003).",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node ../../node_modules/vitest/vitest.mjs run --root ../.. --config vitest.config.ts packages/team-server/tests --maxWorkers=1 --silent",
|
||||
"start": "node dist/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clerk/fastify": "^3.1.3",
|
||||
"@fastify/cors": "^10.0.0",
|
||||
"@fastify/websocket": "^11.0.0",
|
||||
"@waggle/agent": "*",
|
||||
"@waggle/shared": "*",
|
||||
"@waggle/waggle-dance": "*",
|
||||
"bullmq": "^5.0.0",
|
||||
"cron-parser": "^4.9.0",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"fastify": "^5.3.0",
|
||||
"fastify-plugin": "^5.0.0",
|
||||
"ioredis": "^5.4.0",
|
||||
"postgres": "^3.4.0",
|
||||
"zod": "^3.24.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/ws": "^8.18.1",
|
||||
"drizzle-kit": "^0.31.0"
|
||||
}
|
||||
}
|
||||
42
packages/team-server/src/config.ts
Normal file
42
packages/team-server/src/config.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
export interface ServerConfig {
|
||||
port: number;
|
||||
host: string;
|
||||
databaseUrl: string;
|
||||
redisUrl: string;
|
||||
clerkSecretKey: string;
|
||||
clerkPublishableKey: string;
|
||||
corsOrigin: string[];
|
||||
}
|
||||
|
||||
export function loadConfig(): ServerConfig {
|
||||
return {
|
||||
port: parseInt(process.env.PORT ?? '3100', 10),
|
||||
host: process.env.HOST ?? '0.0.0.0',
|
||||
databaseUrl: (() => {
|
||||
const url = process.env.DATABASE_URL;
|
||||
if (!url) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('DATABASE_URL environment variable is required');
|
||||
}
|
||||
return 'postgres://localhost:5434/waggle';
|
||||
}
|
||||
return url;
|
||||
})(),
|
||||
redisUrl: process.env.REDIS_URL ?? 'redis://localhost:6381',
|
||||
clerkSecretKey: process.env.CLERK_SECRET_KEY ?? '',
|
||||
clerkPublishableKey: process.env.CLERK_PUBLISHABLE_KEY ?? '',
|
||||
corsOrigin: (() => {
|
||||
const origins = process.env.CORS_ORIGIN;
|
||||
if (!origins) {
|
||||
// Fail closed in production: a missing CORS_ORIGIN must not silently
|
||||
// fall back to a localhost dev origin (which both blocks the real prod
|
||||
// frontend AND leaves an unintended localhost origin allowed).
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('CORS_ORIGIN environment variable is required in production');
|
||||
}
|
||||
return ['http://localhost:5173'];
|
||||
}
|
||||
return origins.split(',').map((o) => o.trim()).filter(Boolean);
|
||||
})(),
|
||||
};
|
||||
}
|
||||
126
packages/team-server/src/daemons/hive-mind.ts
Normal file
126
packages/team-server/src/daemons/hive-mind.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { eq, and, desc, gte, sql } from 'drizzle-orm';
|
||||
import { agentJobs, teamResources, tasks, messages, teamMembers } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export class HiveMindAgent {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async generateWeeklyDigest(teamId: string): Promise<{ digest: WeeklyDigest; messageId: string }> {
|
||||
const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Aggregate metrics
|
||||
const jobsCompleted = await this.db.select().from(agentJobs)
|
||||
.where(and(
|
||||
eq(agentJobs.teamId, teamId),
|
||||
eq(agentJobs.status, 'completed'),
|
||||
gte(agentJobs.completedAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
const tasksCompleted = await this.db.select().from(tasks)
|
||||
.where(and(
|
||||
eq(tasks.teamId, teamId),
|
||||
eq(tasks.status, 'done'),
|
||||
));
|
||||
|
||||
const resourcesShared = await this.db.select().from(teamResources)
|
||||
.where(and(
|
||||
eq(teamResources.teamId, teamId),
|
||||
gte(teamResources.createdAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
const waggleMessages = await this.db.select().from(messages)
|
||||
.where(and(
|
||||
eq(messages.teamId, teamId),
|
||||
gte(messages.createdAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
// Detect duplicate work (similar task titles by different users)
|
||||
const duplicates = this.detectDuplicateWork(tasksCompleted);
|
||||
|
||||
// Find high-rated resources as best practices
|
||||
const bestPractices = await this.db.select().from(teamResources)
|
||||
.where(and(
|
||||
eq(teamResources.teamId, teamId),
|
||||
gte(teamResources.rating, sql`3.0`),
|
||||
))
|
||||
.orderBy(desc(teamResources.rating))
|
||||
.limit(5);
|
||||
|
||||
const digest: WeeklyDigest = {
|
||||
period: { from: oneWeekAgo, to: new Date() },
|
||||
metrics: {
|
||||
jobsCompleted: jobsCompleted.length,
|
||||
tasksCompleted: tasksCompleted.length,
|
||||
resourcesShared: resourcesShared.length,
|
||||
waggleMessages: waggleMessages.length,
|
||||
},
|
||||
duplicateWork: duplicates,
|
||||
bestPractices: bestPractices.map(r => ({ name: r.name, type: r.resourceType, rating: r.rating })),
|
||||
recommendations: this.generateRecommendations(jobsCompleted, duplicates, bestPractices),
|
||||
};
|
||||
|
||||
// Get a team member to attribute the broadcast to
|
||||
const [firstMember] = await this.db.select().from(teamMembers)
|
||||
.where(eq(teamMembers.teamId, teamId))
|
||||
.limit(1);
|
||||
|
||||
const senderId = firstMember?.userId ?? '';
|
||||
|
||||
// Broadcast digest as Waggle Dance message
|
||||
const [msg] = await this.db.insert(messages).values({
|
||||
teamId,
|
||||
senderId,
|
||||
type: 'broadcast',
|
||||
subtype: 'discovery',
|
||||
content: { type: 'weekly_digest', digest },
|
||||
}).returning();
|
||||
|
||||
return { digest, messageId: msg.id };
|
||||
}
|
||||
|
||||
private detectDuplicateWork(tasksList: Array<{ title: string; createdBy: string }>): DuplicateWork[] {
|
||||
// Group by similar titles (case-insensitive first 20 chars)
|
||||
const groups = new Map<string, { titles: string[]; users: Set<string> }>();
|
||||
for (const task of tasksList) {
|
||||
const key = task.title.toLowerCase().substring(0, 20);
|
||||
if (!groups.has(key)) groups.set(key, { titles: [], users: new Set() });
|
||||
groups.get(key)!.titles.push(task.title);
|
||||
groups.get(key)!.users.add(task.createdBy);
|
||||
}
|
||||
return Array.from(groups.values())
|
||||
.filter(g => g.users.size > 1)
|
||||
.map(g => ({ titles: g.titles, users: Array.from(g.users) }));
|
||||
}
|
||||
|
||||
private generateRecommendations(jobs: unknown[], duplicates: DuplicateWork[], bestPractices: unknown[]): string[] {
|
||||
const recommendations: string[] = [];
|
||||
if (duplicates.length > 0) {
|
||||
recommendations.push(`${duplicates.length} potential duplicate work detected. Consider checking the hive before starting tasks.`);
|
||||
}
|
||||
if (bestPractices.length > 0) {
|
||||
recommendations.push(`${bestPractices.length} highly-rated resources available. Share them team-wide.`);
|
||||
}
|
||||
if (jobs.length > 50) {
|
||||
recommendations.push('High job volume this week. Consider automating recurring tasks with cron schedules.');
|
||||
}
|
||||
return recommendations;
|
||||
}
|
||||
}
|
||||
|
||||
interface DuplicateWork {
|
||||
titles: string[];
|
||||
users: string[];
|
||||
}
|
||||
|
||||
interface WeeklyDigest {
|
||||
period: { from: Date; to: Date };
|
||||
metrics: {
|
||||
jobsCompleted: number;
|
||||
tasksCompleted: number;
|
||||
resourcesShared: number;
|
||||
waggleMessages: number;
|
||||
};
|
||||
duplicateWork: DuplicateWork[];
|
||||
bestPractices: Array<{ name: string; type: string; rating: number }>;
|
||||
recommendations: string[];
|
||||
}
|
||||
127
packages/team-server/src/daemons/scout.ts
Normal file
127
packages/team-server/src/daemons/scout.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { eq, and, desc } from 'drizzle-orm';
|
||||
import { scoutFindings, agents, teamMembers, teamResources } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
interface Finding {
|
||||
source: string;
|
||||
category: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
relevanceScore: number;
|
||||
url: string | null;
|
||||
}
|
||||
|
||||
export class ScoutAgent {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async scan(userId: string, teamId: string): Promise<Array<typeof scoutFindings.$inferSelect>> {
|
||||
const findings: Finding[] = [];
|
||||
|
||||
// Source 1: Check team resources for newly shared items
|
||||
findings.push(...await this.checkTeamResources(teamId));
|
||||
|
||||
// Source 2: Mock marketplace check (would check npm/MCP registry in production)
|
||||
findings.push(...await this.checkMarketplace(userId));
|
||||
|
||||
// Score relevance based on user's agent configs and role
|
||||
const scored = await this.scoreRelevance(findings, userId, teamId);
|
||||
|
||||
// Filter out findings with titles already dismissed by this user
|
||||
const existingDismissed = await this.db.select().from(scoutFindings)
|
||||
.where(and(
|
||||
eq(scoutFindings.userId, userId),
|
||||
eq(scoutFindings.status, 'dismissed'),
|
||||
));
|
||||
const dismissedTitles = new Set(existingDismissed.map(f => f.title));
|
||||
const filtered = scored.filter(f => !dismissedTitles.has(f.title));
|
||||
|
||||
// Store findings
|
||||
const stored = [];
|
||||
for (const finding of filtered) {
|
||||
const [entry] = await this.db.insert(scoutFindings).values({
|
||||
userId,
|
||||
teamId,
|
||||
source: finding.source,
|
||||
category: finding.category,
|
||||
title: finding.title,
|
||||
summary: finding.summary,
|
||||
relevanceScore: finding.relevanceScore,
|
||||
url: finding.url,
|
||||
status: 'new',
|
||||
}).returning();
|
||||
stored.push(entry);
|
||||
}
|
||||
|
||||
return stored;
|
||||
}
|
||||
|
||||
private async checkTeamResources(teamId: string): Promise<Finding[]> {
|
||||
const recent = await this.db.select().from(teamResources)
|
||||
.where(eq(teamResources.teamId, teamId))
|
||||
.orderBy(desc(teamResources.createdAt))
|
||||
.limit(5);
|
||||
|
||||
return recent.map(r => ({
|
||||
source: 'team' as const,
|
||||
category: r.resourceType === 'skill' ? 'skill' : 'practice',
|
||||
title: `New team resource: ${r.name}`,
|
||||
summary: r.description ?? `A ${r.resourceType} shared by a team member`,
|
||||
relevanceScore: 0.5,
|
||||
url: null,
|
||||
}));
|
||||
}
|
||||
|
||||
private async checkMarketplace(_userId: string): Promise<Finding[]> {
|
||||
// Mock: In production, would check npm registry for MCP packages, skill marketplace, etc.
|
||||
return [];
|
||||
}
|
||||
|
||||
private async scoreRelevance(findings: Finding[], userId: string, teamId: string): Promise<Finding[]> {
|
||||
// Load user's agent configs for interest matching
|
||||
const userAgents = await this.db.select().from(agents)
|
||||
.where(eq(agents.userId, userId));
|
||||
|
||||
// Load member interests
|
||||
const [membership] = await this.db.select().from(teamMembers)
|
||||
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)));
|
||||
|
||||
const interests = (membership?.interests as string[]) ?? [];
|
||||
const agentTools = userAgents.flatMap(a => (a.tools as string[]) ?? []);
|
||||
|
||||
return findings.map(f => {
|
||||
let score = f.relevanceScore;
|
||||
// Boost if matches user interests
|
||||
if (interests.some(i => f.title.toLowerCase().includes(i.toLowerCase()))) score += 0.3;
|
||||
// Boost if matches agent tool names
|
||||
if (agentTools.some(t => f.title.toLowerCase().includes(t.toLowerCase()))) score += 0.2;
|
||||
return { ...f, relevanceScore: Math.min(score, 1.0) };
|
||||
});
|
||||
}
|
||||
|
||||
async adopt(findingId: string, userId: string) {
|
||||
const [updated] = await this.db.update(scoutFindings)
|
||||
.set({ status: 'adopted' })
|
||||
.where(and(
|
||||
eq(scoutFindings.id, findingId),
|
||||
eq(scoutFindings.userId, userId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async dismiss(findingId: string, userId: string) {
|
||||
const [updated] = await this.db.update(scoutFindings)
|
||||
.set({ status: 'dismissed' })
|
||||
.where(and(
|
||||
eq(scoutFindings.id, findingId),
|
||||
eq(scoutFindings.userId, userId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async listFindings(userId: string) {
|
||||
return this.db.select().from(scoutFindings)
|
||||
.where(eq(scoutFindings.userId, userId));
|
||||
}
|
||||
}
|
||||
94
packages/team-server/src/daemons/subconscious.ts
Normal file
94
packages/team-server/src/daemons/subconscious.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { eq, desc, and, sql } from 'drizzle-orm';
|
||||
import { agentJobs, agentAuditLog } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import { SUBCONSCIOUS_INTERACTION_THRESHOLD } from '@waggle/shared';
|
||||
|
||||
export class SubconsciousAgent {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async shouldReflect(userId: string): Promise<boolean> {
|
||||
// Count completed jobs since last reflection
|
||||
const lastReflection = await this.db.select().from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.userId, userId),
|
||||
eq(agentAuditLog.actionType, 'subconscious_reflection'),
|
||||
))
|
||||
.orderBy(desc(agentAuditLog.createdAt))
|
||||
.limit(1);
|
||||
|
||||
const since = lastReflection[0]?.createdAt ?? new Date(0);
|
||||
const sinceIso = since.toISOString();
|
||||
|
||||
const recentJobs = await this.db.select().from(agentJobs)
|
||||
.where(and(
|
||||
eq(agentJobs.userId, userId),
|
||||
eq(agentJobs.status, 'completed'),
|
||||
sql`${agentJobs.completedAt} > ${sinceIso}::timestamptz`,
|
||||
));
|
||||
|
||||
return recentJobs.length >= SUBCONSCIOUS_INTERACTION_THRESHOLD;
|
||||
}
|
||||
|
||||
async reflect(userId: string): Promise<{ auditEntry: typeof agentAuditLog.$inferSelect; insights: Insight[] }> {
|
||||
// Get recent completed jobs
|
||||
const recentJobs = await this.db.select().from(agentJobs)
|
||||
.where(and(
|
||||
eq(agentJobs.userId, userId),
|
||||
eq(agentJobs.status, 'completed'),
|
||||
))
|
||||
.orderBy(desc(agentJobs.completedAt))
|
||||
.limit(20);
|
||||
|
||||
// Analyze patterns
|
||||
const insights = this.analyzePatterns(recentJobs);
|
||||
|
||||
// Log the reflection
|
||||
const [auditEntry] = await this.db.insert(agentAuditLog).values({
|
||||
userId,
|
||||
agentName: 'subconscious',
|
||||
actionType: 'subconscious_reflection',
|
||||
description: `Reflected on ${recentJobs.length} recent jobs. Found ${insights.length} insights.`,
|
||||
afterState: { insights },
|
||||
requiresApproval: insights.some(i => i.type === 'prompt_change'),
|
||||
}).returning();
|
||||
|
||||
return { auditEntry, insights };
|
||||
}
|
||||
|
||||
private analyzePatterns(jobs: Array<typeof agentJobs.$inferSelect>): Insight[] {
|
||||
const insights: Insight[] = [];
|
||||
|
||||
// Pattern: repeated job types
|
||||
const typeCounts = new Map<string, number>();
|
||||
for (const job of jobs) {
|
||||
typeCounts.set(job.jobType, (typeCounts.get(job.jobType) ?? 0) + 1);
|
||||
}
|
||||
for (const [type, count] of typeCounts) {
|
||||
if (count >= 5) {
|
||||
insights.push({
|
||||
type: 'prompt_change',
|
||||
description: `Job type "${type}" executed ${count} times recently`,
|
||||
recommendation: `Consider optimizing the system prompt for ${type} tasks`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Pattern: failed jobs
|
||||
const failedCount = jobs.filter(j => j.status === 'failed').length;
|
||||
if (failedCount >= 3) {
|
||||
insights.push({
|
||||
type: 'tool_issue',
|
||||
description: `${failedCount} jobs failed recently`,
|
||||
recommendation: 'Review tool configurations and consider adding error handling',
|
||||
});
|
||||
}
|
||||
|
||||
return insights;
|
||||
}
|
||||
}
|
||||
|
||||
interface Insight {
|
||||
type: string;
|
||||
description: string;
|
||||
recommendation: string;
|
||||
}
|
||||
16
packages/team-server/src/db/connection.ts
Normal file
16
packages/team-server/src/db/connection.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { drizzle } from 'drizzle-orm/postgres-js';
|
||||
import postgres from 'postgres';
|
||||
import * as schema from './schema.js';
|
||||
|
||||
export function createDb(connectionString: string) {
|
||||
const client = postgres(connectionString);
|
||||
return drizzle(client, { schema });
|
||||
}
|
||||
|
||||
export type Db = ReturnType<typeof createDb>;
|
||||
|
||||
/** The transaction handle drizzle passes to `db.transaction(cb)`. */
|
||||
export type DbTransaction = Parameters<Parameters<Db['transaction']>[0]>[0];
|
||||
|
||||
/** A query executor that is either the root db or an open transaction. */
|
||||
export type DbExecutor = Db | DbTransaction;
|
||||
20
packages/team-server/src/db/migrate.ts
Normal file
20
packages/team-server/src/db/migrate.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { migrate } from 'drizzle-orm/postgres-js/migrator';
|
||||
import { createDb } from './connection.js';
|
||||
import { createLogger } from '../logger.js';
|
||||
|
||||
const log = createLogger('migrate');
|
||||
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
if (!connectionString) throw new Error('DATABASE_URL environment variable is required');
|
||||
|
||||
async function main() {
|
||||
const db = createDb(connectionString!);
|
||||
await migrate(db, { migrationsFolder: './drizzle' });
|
||||
log.info('Migrations complete');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
log.error('Migration failed:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
234
packages/team-server/src/db/schema.ts
Normal file
234
packages/team-server/src/db/schema.ts
Normal file
@@ -0,0 +1,234 @@
|
||||
import {
|
||||
pgTable, uuid, text, timestamp, boolean, real, integer, jsonb, primaryKey,
|
||||
} from 'drizzle-orm/pg-core';
|
||||
|
||||
export const users = pgTable('users', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
clerkId: text('clerk_id').unique().notNull(),
|
||||
displayName: text('display_name').notNull(),
|
||||
email: text('email').unique().notNull(),
|
||||
avatarUrl: text('avatar_url'),
|
||||
mindPath: text('mind_path'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teams = pgTable('teams', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
name: text('name').notNull(),
|
||||
slug: text('slug').unique().notNull(),
|
||||
ownerId: uuid('owner_id').references(() => users.id).notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamMembers = pgTable('team_members', {
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
role: text('role').notNull().default('member'),
|
||||
roleDescription: text('role_description'),
|
||||
interests: jsonb('interests').$type<string[]>(),
|
||||
joinedAt: timestamp('joined_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
}, (t) => [primaryKey({ columns: [t.teamId, t.userId] })]);
|
||||
|
||||
export const agents = pgTable('agents', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
teamId: uuid('team_id').references(() => teams.id),
|
||||
name: text('name').notNull(),
|
||||
role: text('role'),
|
||||
systemPrompt: text('system_prompt'),
|
||||
model: text('model').notNull().default('claude-haiku-4-5'),
|
||||
tools: jsonb('tools').$type<string[]>().notNull().default([]),
|
||||
config: jsonb('config').$type<Record<string, unknown>>().notNull().default({}),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const agentGroups = pgTable('agent_groups', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
name: text('name').notNull(),
|
||||
description: text('description'),
|
||||
strategy: text('strategy').notNull().default('parallel'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const agentGroupMembers = pgTable('agent_group_members', {
|
||||
groupId: uuid('group_id').references(() => agentGroups.id).notNull(),
|
||||
agentId: uuid('agent_id').references(() => agents.id).notNull(),
|
||||
roleInGroup: text('role_in_group').notNull().default('worker'),
|
||||
executionOrder: integer('execution_order').notNull().default(0),
|
||||
}, (t) => [primaryKey({ columns: [t.groupId, t.agentId] })]);
|
||||
|
||||
export const tasks = pgTable('tasks', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
title: text('title').notNull(),
|
||||
description: text('description'),
|
||||
status: text('status').notNull().default('open'),
|
||||
priority: text('priority').notNull().default('normal'),
|
||||
createdBy: uuid('created_by').references(() => users.id).notNull(),
|
||||
assignedTo: uuid('assigned_to').references(() => users.id),
|
||||
parentTaskId: uuid('parent_task_id'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const messages = pgTable('messages', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
senderId: uuid('sender_id').references(() => users.id).notNull(),
|
||||
type: text('type').notNull(),
|
||||
subtype: text('subtype').notNull(),
|
||||
content: jsonb('content').$type<Record<string, unknown>>().notNull(),
|
||||
referenceId: uuid('reference_id'),
|
||||
routing: jsonb('routing').$type<Array<{ userId: string; reason: string }>>(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamEntities = pgTable('team_entities', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
entityType: text('entity_type').notNull(),
|
||||
name: text('name').notNull(),
|
||||
properties: jsonb('properties').$type<Record<string, unknown>>().notNull().default({}),
|
||||
sharedBy: uuid('shared_by').references(() => users.id).notNull(),
|
||||
validFrom: timestamp('valid_from', { withTimezone: true }).defaultNow().notNull(),
|
||||
validTo: timestamp('valid_to', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamRelations = pgTable('team_relations', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
sourceId: uuid('source_id').references(() => teamEntities.id).notNull(),
|
||||
targetId: uuid('target_id').references(() => teamEntities.id).notNull(),
|
||||
relationType: text('relation_type').notNull(),
|
||||
confidence: real('confidence').notNull().default(1.0),
|
||||
properties: jsonb('properties').$type<Record<string, unknown>>().notNull().default({}),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamResources = pgTable('team_resources', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
resourceType: text('resource_type').notNull(),
|
||||
name: text('name').notNull(),
|
||||
description: text('description'),
|
||||
config: jsonb('config').$type<Record<string, unknown>>().notNull(),
|
||||
sharedBy: uuid('shared_by').references(() => users.id).notNull(),
|
||||
rating: real('rating').notNull().default(0),
|
||||
useCount: integer('use_count').notNull().default(0),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamCapabilityPolicies = pgTable('team_capability_policies', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
role: text('role').notNull(),
|
||||
allowedSources: jsonb('allowed_sources').$type<string[]>().notNull().default([]),
|
||||
blockedTools: jsonb('blocked_tools').$type<string[]>().notNull().default([]),
|
||||
approvalThreshold: text('approval_threshold').notNull().default('none'),
|
||||
updatedBy: uuid('updated_by').references(() => users.id),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamCapabilityOverrides = pgTable('team_capability_overrides', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
capabilityName: text('capability_name').notNull(),
|
||||
capabilityType: text('capability_type').notNull(),
|
||||
decision: text('decision').notNull(),
|
||||
reason: text('reason').notNull().default(''),
|
||||
decidedBy: uuid('decided_by').references(() => users.id).notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
decidedAt: timestamp('decided_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const teamCapabilityRequests = pgTable('team_capability_requests', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
requestedBy: uuid('requested_by').references(() => users.id).notNull(),
|
||||
capabilityName: text('capability_name').notNull(),
|
||||
capabilityType: text('capability_type').notNull(),
|
||||
justification: text('justification').notNull(),
|
||||
status: text('status').notNull().default('pending'),
|
||||
decidedBy: uuid('decided_by').references(() => users.id),
|
||||
decisionReason: text('decision_reason'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
decidedAt: timestamp('decided_at', { withTimezone: true }),
|
||||
});
|
||||
|
||||
export const agentJobs = pgTable('agent_jobs', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
jobType: text('job_type').notNull(),
|
||||
status: text('status').notNull().default('queued'),
|
||||
input: jsonb('input').$type<Record<string, unknown>>().notNull(),
|
||||
output: jsonb('output').$type<Record<string, unknown>>(),
|
||||
startedAt: timestamp('started_at', { withTimezone: true }),
|
||||
completedAt: timestamp('completed_at', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const cronSchedules = pgTable('cron_schedules', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
teamId: uuid('team_id').references(() => teams.id).notNull(),
|
||||
createdBy: uuid('created_by').references(() => users.id).notNull(),
|
||||
name: text('name').notNull(),
|
||||
cronExpr: text('cron_expr').notNull(),
|
||||
jobType: text('job_type').notNull(),
|
||||
jobConfig: jsonb('job_config').$type<Record<string, unknown>>().notNull().default({}),
|
||||
enabled: boolean('enabled').notNull().default(true),
|
||||
lastRunAt: timestamp('last_run_at', { withTimezone: true }),
|
||||
nextRunAt: timestamp('next_run_at', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const scoutFindings = pgTable('scout_findings', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id').references(() => users.id),
|
||||
teamId: uuid('team_id').references(() => teams.id),
|
||||
source: text('source').notNull(),
|
||||
category: text('category').notNull(),
|
||||
title: text('title').notNull(),
|
||||
summary: text('summary'),
|
||||
relevanceScore: real('relevance_score').notNull().default(0),
|
||||
url: text('url'),
|
||||
status: text('status').notNull().default('new'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const proactivePatterns = pgTable('proactive_patterns', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
name: text('name').notNull(),
|
||||
trigger: jsonb('trigger').$type<Record<string, unknown>>().notNull(),
|
||||
suggestionType: text('suggestion_type').notNull(),
|
||||
template: text('template').notNull(),
|
||||
enabled: boolean('enabled').notNull().default(true),
|
||||
});
|
||||
|
||||
export const suggestionsLog = pgTable('suggestions_log', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
patternId: uuid('pattern_id').references(() => proactivePatterns.id).notNull(),
|
||||
context: jsonb('context').$type<Record<string, unknown>>().notNull(),
|
||||
status: text('status').notNull().default('pending'),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const agentAuditLog = pgTable('agent_audit_log', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
userId: uuid('user_id').references(() => users.id).notNull(),
|
||||
teamId: uuid('team_id').references(() => teams.id),
|
||||
agentName: text('agent_name').notNull(),
|
||||
actionType: text('action_type').notNull(),
|
||||
description: text('description').notNull(),
|
||||
beforeState: jsonb('before_state').$type<Record<string, unknown>>(),
|
||||
afterState: jsonb('after_state').$type<Record<string, unknown>>(),
|
||||
requiresApproval: boolean('requires_approval').notNull().default(false),
|
||||
approved: boolean('approved'),
|
||||
approvedBy: uuid('approved_by').references(() => users.id),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
98
packages/team-server/src/index.ts
Normal file
98
packages/team-server/src/index.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import Fastify from 'fastify';
|
||||
import { resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import cors from '@fastify/cors';
|
||||
import websocket from '@fastify/websocket';
|
||||
import { loadConfig, type ServerConfig } from './config.js';
|
||||
import { createDb, type Db } from './db/connection.js';
|
||||
import redisPlugin from './plugins/redis.js';
|
||||
import authPlugin from './plugins/auth.js';
|
||||
import { webhookRoutes } from './routes/webhooks.js';
|
||||
import { teamRoutes } from './routes/teams.js';
|
||||
import { agentRoutes } from './routes/agents.js';
|
||||
import { taskRoutes } from './routes/tasks.js';
|
||||
import { messageRoutes } from './routes/messages.js';
|
||||
import { knowledgeRoutes } from './routes/knowledge.js';
|
||||
import { resourceRoutes } from './routes/resources.js';
|
||||
import { jobRoutes } from './routes/jobs.js';
|
||||
import { cronRoutes } from './routes/cron.js';
|
||||
import { suggestionRoutes } from './routes/suggestions.js';
|
||||
import { scoutRoutes } from './routes/scout.js';
|
||||
import { auditRoutes } from './routes/audit.js';
|
||||
import { capabilityGovernanceRoutes } from './routes/capability-governance.js';
|
||||
import { analyticsRoutes } from './routes/analytics.js';
|
||||
import { wsGateway } from './ws/gateway.js';
|
||||
import { JobService } from './services/job-service.js';
|
||||
import { CronRunner } from './scheduler/cron-runner.js';
|
||||
import { createLogger } from './logger.js';
|
||||
|
||||
const log = createLogger('server');
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
config: ServerConfig;
|
||||
db: Db;
|
||||
jobService: JobService;
|
||||
}
|
||||
}
|
||||
|
||||
export async function buildServer(configOverrides?: Partial<ServerConfig>) {
|
||||
const config = { ...loadConfig(), ...configOverrides };
|
||||
|
||||
const server = Fastify({ logger: true });
|
||||
|
||||
server.decorate('config', config);
|
||||
|
||||
const db = createDb(config.databaseUrl);
|
||||
server.decorate('db', db);
|
||||
|
||||
await server.register(cors, { origin: config.corsOrigin });
|
||||
await server.register(websocket);
|
||||
await server.register(redisPlugin);
|
||||
await server.register(authPlugin);
|
||||
await server.register(webhookRoutes);
|
||||
await server.register(teamRoutes);
|
||||
await server.register(agentRoutes);
|
||||
await server.register(taskRoutes);
|
||||
await server.register(messageRoutes);
|
||||
await server.register(knowledgeRoutes);
|
||||
// Job service (must be decorated before job routes)
|
||||
const jobService = new JobService(db, config.redisUrl);
|
||||
server.decorate('jobService', jobService);
|
||||
const cronRunner = new CronRunner(db, jobService, error => {
|
||||
server.log.error({ err: error }, 'Cron scheduler tick failed');
|
||||
});
|
||||
server.addHook('onReady', async () => {
|
||||
cronRunner.start();
|
||||
});
|
||||
server.addHook('onClose', async () => {
|
||||
await cronRunner.stop();
|
||||
await jobService.close();
|
||||
});
|
||||
|
||||
await server.register(resourceRoutes);
|
||||
await server.register(jobRoutes);
|
||||
await server.register(cronRoutes);
|
||||
await server.register(suggestionRoutes);
|
||||
await server.register(scoutRoutes);
|
||||
await server.register(auditRoutes);
|
||||
await server.register(capabilityGovernanceRoutes);
|
||||
await server.register(analyticsRoutes);
|
||||
await server.register(wsGateway);
|
||||
|
||||
// Health check
|
||||
server.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }));
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
// Start server if run directly
|
||||
export function isDirectModule(entryPath: string | undefined, moduleUrl: string): boolean {
|
||||
return entryPath !== undefined && pathToFileURL(resolve(entryPath)).href === moduleUrl;
|
||||
}
|
||||
|
||||
if (isDirectModule(process.argv[1], import.meta.url)) {
|
||||
const server = await buildServer();
|
||||
await server.listen({ port: server.config.port, host: server.config.host });
|
||||
log.info(`Waggle server listening on ${server.config.host}:${server.config.port}`);
|
||||
}
|
||||
47
packages/team-server/src/logger.ts
Normal file
47
packages/team-server/src/logger.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Structured logger for the Waggle team server, a copy of the local
|
||||
* sidecar's logger (packages/server/src/local/logger.ts) so this package
|
||||
* does not depend on @waggle/server.
|
||||
*
|
||||
* Replaces raw console.log/warn/error with tagged, leveled output.
|
||||
* All messages are prefixed with [waggle] and a component tag.
|
||||
* In M2 this writes to stdout; can be extended to file/telemetry later.
|
||||
*/
|
||||
|
||||
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
||||
|
||||
const LEVEL_PREFIX: Record<LogLevel, string> = {
|
||||
debug: '\x1b[90m[debug]\x1b[0m',
|
||||
info: '',
|
||||
warn: '\x1b[33m[warn]\x1b[0m',
|
||||
error: '\x1b[31m[error]\x1b[0m',
|
||||
};
|
||||
|
||||
function formatMessage(tag: string, level: LogLevel, msg: string, data?: unknown): string {
|
||||
const prefix = LEVEL_PREFIX[level];
|
||||
const base = `[waggle:${tag}] ${prefix ? prefix + ' ' : ''}${msg}`;
|
||||
if (data !== undefined) {
|
||||
const detail = typeof data === 'string' ? data : JSON.stringify(data);
|
||||
return `${base} ${detail}`;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
debug(msg: string, data?: unknown): void;
|
||||
info(msg: string, data?: unknown): void;
|
||||
warn(msg: string, data?: unknown): void;
|
||||
error(msg: string, data?: unknown): void;
|
||||
}
|
||||
|
||||
export function createLogger(tag: string): Logger {
|
||||
return {
|
||||
debug(msg, data) { console.debug(formatMessage(tag, 'debug', msg, data)); },
|
||||
info(msg, data) { console.log(formatMessage(tag, 'info', msg, data)); },
|
||||
warn(msg, data) { console.warn(formatMessage(tag, 'warn', msg, data)); },
|
||||
error(msg, data) { console.error(formatMessage(tag, 'error', msg, data)); },
|
||||
};
|
||||
}
|
||||
|
||||
/** Default server logger */
|
||||
export const log = createLogger('server');
|
||||
61
packages/team-server/src/plugins/auth.ts
Normal file
61
packages/team-server/src/plugins/auth.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import fp from 'fastify-plugin';
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { createClerkClient, verifyToken } from '@clerk/fastify';
|
||||
import { UserService } from '../services/user-service.js';
|
||||
|
||||
export type AuthenticateFn = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
userId: string; // our internal user UUID
|
||||
clerkId: string;
|
||||
}
|
||||
interface FastifyInstance {
|
||||
authenticate: AuthenticateFn;
|
||||
_authHandler: { fn: AuthenticateFn };
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(async function authPlugin(fastify: FastifyInstance) {
|
||||
const clerkSecretKey = fastify.config.clerkSecretKey;
|
||||
const clerk = createClerkClient({ secretKey: clerkSecretKey });
|
||||
const userService = new UserService(fastify.db);
|
||||
|
||||
const clerkAuth: AuthenticateFn = async function (request, reply) {
|
||||
const token = request.headers.authorization?.replace('Bearer ', '');
|
||||
if (!token) {
|
||||
return reply.code(401).send({ error: 'Missing authorization token' });
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await verifyToken(token, { secretKey: clerkSecretKey });
|
||||
request.clerkId = payload.sub;
|
||||
|
||||
// Look up internal user, auto-provision if not found
|
||||
let user = await userService.getByClerkId(payload.sub);
|
||||
|
||||
if (!user) {
|
||||
// Auto-create user from Clerk JWT claims (self-healing: works even if webhook was missed)
|
||||
const clerkUser = await clerk.users.getUser(payload.sub);
|
||||
user = await userService.upsertFromClerk({
|
||||
clerkId: payload.sub,
|
||||
displayName: `${clerkUser.firstName ?? ''} ${clerkUser.lastName ?? ''}`.trim() || payload.sub,
|
||||
email: clerkUser.emailAddresses?.[0]?.emailAddress ?? '',
|
||||
avatarUrl: clerkUser.imageUrl ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
request.userId = user.id;
|
||||
} catch {
|
||||
return reply.code(401).send({ error: 'Invalid token' });
|
||||
}
|
||||
};
|
||||
|
||||
// Use an indirection object so tests can swap the auth handler after routes are registered
|
||||
const handler = { fn: clerkAuth };
|
||||
fastify.decorate('_authHandler', handler);
|
||||
|
||||
fastify.decorate('authenticate', async function (request: FastifyRequest, reply: FastifyReply) {
|
||||
return handler.fn(request, reply);
|
||||
});
|
||||
});
|
||||
24
packages/team-server/src/plugins/redis.ts
Normal file
24
packages/team-server/src/plugins/redis.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import fp from 'fastify-plugin';
|
||||
import Redis from 'ioredis';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
redis: Redis;
|
||||
redisSub: Redis;
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(async function redisPlugin(fastify: FastifyInstance) {
|
||||
const redisUrl = fastify.config.redisUrl;
|
||||
const redis = new Redis(redisUrl);
|
||||
const redisSub = new Redis(redisUrl);
|
||||
|
||||
fastify.decorate('redis', redis);
|
||||
fastify.decorate('redisSub', redisSub);
|
||||
|
||||
fastify.addHook('onClose', async () => {
|
||||
await redis.quit();
|
||||
await redisSub.quit();
|
||||
});
|
||||
});
|
||||
39
packages/team-server/src/proactive/patterns.ts
Normal file
39
packages/team-server/src/proactive/patterns.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
export interface PatternDef {
|
||||
name: string;
|
||||
triggerCondition: string;
|
||||
suggestionType: string;
|
||||
template: string;
|
||||
}
|
||||
|
||||
export const BUILT_IN_PATTERNS: PatternDef[] = [
|
||||
{
|
||||
name: 'recurring_task',
|
||||
triggerCondition: 'Same task type executed 3+ times',
|
||||
suggestionType: 'cron',
|
||||
template: 'This task runs frequently. Would you like to automate it as a scheduled job?',
|
||||
},
|
||||
{
|
||||
name: 'data_report',
|
||||
triggerCondition: 'Job output contains structured data/metrics',
|
||||
suggestionType: 'dashboard',
|
||||
template: 'This produces data regularly. Want to create a dashboard for it?',
|
||||
},
|
||||
{
|
||||
name: 'relevant_to_others',
|
||||
triggerCondition: 'Job output matches other team member interests',
|
||||
suggestionType: 'share',
|
||||
template: 'This result might be relevant to {targetUser}. Share it?',
|
||||
},
|
||||
{
|
||||
name: 'expensive_model',
|
||||
triggerCondition: 'Job used expensive model for simple task',
|
||||
suggestionType: 'upgrade',
|
||||
template: 'This task could use a cheaper model. Try {cheaperModel} next time?',
|
||||
},
|
||||
{
|
||||
name: 'manual_repetition',
|
||||
triggerCondition: 'User performs same manual steps repeatedly',
|
||||
suggestionType: 'skill',
|
||||
template: 'You keep doing this manually. Want to create a reusable skill for it?',
|
||||
},
|
||||
];
|
||||
182
packages/team-server/src/routes/agents.ts
Normal file
182
packages/team-server/src/routes/agents.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { AgentGroupMemberNotFoundError, AgentService } from '../services/agent-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { createAgentSchema, createAgentGroupSchema } from '@waggle/shared';
|
||||
|
||||
export async function agentRoutes(fastify: FastifyInstance) {
|
||||
const agentService = new AgentService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
// POST /api/agents — create sub-agent definition
|
||||
fastify.post('/api/agents', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const parsed = createAgentSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const agent = await agentService.create(request.userId, parsed.data);
|
||||
return reply.code(201).send(agent);
|
||||
});
|
||||
|
||||
// GET /api/agents — list user's agents
|
||||
fastify.get('/api/agents', { preHandler: [fastify.authenticate] }, async (request) => {
|
||||
return agentService.list(request.userId);
|
||||
});
|
||||
|
||||
// PATCH /api/agents/:id — update agent config
|
||||
fastify.patch('/api/agents/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
// Verify ownership by attempting update scoped to userId
|
||||
const existing = await agentService.getById(id);
|
||||
if (!existing) {
|
||||
return reply.code(404).send({ error: 'Agent not found' });
|
||||
}
|
||||
if (existing.userId !== request.userId) {
|
||||
return reply.code(403).send({ error: 'Not authorized to update this agent' });
|
||||
}
|
||||
|
||||
const body = request.body as Record<string, unknown>;
|
||||
const updated = await agentService.update(id, request.userId, body);
|
||||
if (!updated) {
|
||||
return reply.code(400).send({ error: 'No valid fields to update' });
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
|
||||
// DELETE /api/agents/:id — delete agent
|
||||
fastify.delete('/api/agents/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
const existing = await agentService.getById(id);
|
||||
if (!existing) {
|
||||
return reply.code(404).send({ error: 'Agent not found' });
|
||||
}
|
||||
if (existing.userId !== request.userId) {
|
||||
return reply.code(403).send({ error: 'Not authorized to delete this agent' });
|
||||
}
|
||||
|
||||
await agentService.delete(id, request.userId);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// POST /api/agent-groups — create agent group with members
|
||||
fastify.post('/api/agent-groups', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const parsed = createAgentGroupSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
try {
|
||||
const group = await agentService.createGroup(request.userId, parsed.data);
|
||||
return reply.code(201).send(group);
|
||||
} catch (error) {
|
||||
if (error instanceof AgentGroupMemberNotFoundError) {
|
||||
return reply.code(404).send({ error: 'Agent not found' });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/agent-groups — list user's groups
|
||||
fastify.get('/api/agent-groups', { preHandler: [fastify.authenticate] }, async (request) => {
|
||||
return agentService.listGroups(request.userId);
|
||||
});
|
||||
|
||||
// GET /api/agent-groups/:id — get group with members
|
||||
fastify.get('/api/agent-groups/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
const group = await agentService.getGroup(id, request.userId);
|
||||
if (!group) {
|
||||
return reply.code(404).send({ error: 'Agent group not found' });
|
||||
}
|
||||
return group;
|
||||
});
|
||||
|
||||
// PATCH /api/agent-groups/:id — update group name, description, strategy, or members
|
||||
fastify.patch('/api/agent-groups/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = request.body as {
|
||||
name?: string;
|
||||
description?: string;
|
||||
strategy?: string;
|
||||
members?: Array<{ agentId: string; roleInGroup?: string; executionOrder?: number }>;
|
||||
};
|
||||
|
||||
try {
|
||||
const updated = await agentService.updateGroup(id, request.userId, body);
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Agent group not found' });
|
||||
}
|
||||
return updated;
|
||||
} catch (error) {
|
||||
if (error instanceof AgentGroupMemberNotFoundError) {
|
||||
return reply.code(404).send({ error: 'Agent not found' });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/agent-groups/:id — delete group and its members
|
||||
fastify.delete('/api/agent-groups/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
const deleted = await agentService.deleteGroup(id, request.userId);
|
||||
if (!deleted) {
|
||||
return reply.code(404).send({ error: 'Agent group not found' });
|
||||
}
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// POST /api/agent-groups/:id/run — execute group on a task
|
||||
fastify.post('/api/agent-groups/:id/run', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
// Verify group ownership
|
||||
const group = await agentService.getGroup(id, request.userId);
|
||||
if (!group) {
|
||||
return reply.code(404).send({ error: 'Agent group not found' });
|
||||
}
|
||||
|
||||
const body = request.body as { task?: string; teamId?: string } | undefined;
|
||||
const task = body?.task ?? '';
|
||||
if (!task.trim()) {
|
||||
return reply.code(400).send({ error: 'task is required' });
|
||||
}
|
||||
if (!body?.teamId) {
|
||||
return reply.code(400).send({ error: 'teamId is required to queue a group run' });
|
||||
}
|
||||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(body.teamId)) {
|
||||
return reply.code(400).send({ error: 'teamId must be a valid UUID' });
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(body.teamId, request.userId);
|
||||
if (!membership) {
|
||||
return reply.code(404).send({ error: 'Team not found' });
|
||||
}
|
||||
|
||||
// Build workflow template from group definition
|
||||
const { buildWorkflowFromGroup } = await import('../services/agent-group-executor.js');
|
||||
const workflow = buildWorkflowFromGroup({ ...group, description: group.description ?? undefined }, task);
|
||||
|
||||
// Queue the same job type handled by the worker. The former path only
|
||||
// inserted a database row with an unsupported job type, so runs stayed
|
||||
// queued forever and no worker ever executed the workflow.
|
||||
const job = await fastify.jobService.createJob(body.teamId, request.userId, 'group', {
|
||||
groupId: id,
|
||||
taskInput: { task },
|
||||
});
|
||||
|
||||
return reply.code(202).send({
|
||||
jobId: job.id,
|
||||
workflow: {
|
||||
name: workflow.name,
|
||||
steps: workflow.steps.length,
|
||||
strategy: group.strategy,
|
||||
aggregation: workflow.aggregation,
|
||||
},
|
||||
message: `Group "${group.name}" execution started with ${workflow.steps.length} agents using ${group.strategy} strategy.`,
|
||||
});
|
||||
});
|
||||
}
|
||||
44
packages/team-server/src/routes/analytics.ts
Normal file
44
packages/team-server/src/routes/analytics.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { AnalyticsService } from '../services/analytics-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
|
||||
const ROLE_HIERARCHY: Record<string, number> = { member: 1, admin: 2, owner: 3 };
|
||||
|
||||
export async function analyticsRoutes(fastify: FastifyInstance) {
|
||||
const analyticsService = new AnalyticsService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function requireAdmin(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const userLevel = ROLE_HIERARCHY[membership.role] ?? 0;
|
||||
if (userLevel < ROLE_HIERARCHY['admin']) {
|
||||
reply.code(403).send({ error: 'Admin access required' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// GET /api/admin/teams/:slug/analytics — team usage analytics dashboard
|
||||
fastify.get('/api/admin/teams/:slug/analytics', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await requireAdmin(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const analytics = await analyticsService.getAnalytics(team.id);
|
||||
return analytics;
|
||||
});
|
||||
}
|
||||
99
packages/team-server/src/routes/audit.ts
Normal file
99
packages/team-server/src/routes/audit.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { AuditService } from '../services/audit-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
|
||||
const ROLE_HIERARCHY: Record<string, number> = { member: 1, admin: 2, owner: 3 };
|
||||
|
||||
export async function auditRoutes(fastify: FastifyInstance) {
|
||||
const auditService = new AuditService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function requireAdmin(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const userLevel = ROLE_HIERARCHY[membership.role] ?? 0;
|
||||
if (userLevel < ROLE_HIERARCHY['admin']) {
|
||||
reply.code(403).send({ error: 'Admin access required' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// GET /api/admin/teams/:slug/audit -- list audit entries
|
||||
fastify.get('/api/admin/teams/:slug/audit', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await requireAdmin(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { actionType?: string; agentName?: string };
|
||||
const entries = await auditService.list(team.id, {
|
||||
actionType: query.actionType,
|
||||
agentName: query.agentName,
|
||||
});
|
||||
return entries;
|
||||
});
|
||||
|
||||
// GET /api/admin/teams/:slug/audit/pending -- list pending approvals
|
||||
fastify.get('/api/admin/teams/:slug/audit/pending', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await requireAdmin(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
return auditService.getPendingApprovals(team.id);
|
||||
});
|
||||
|
||||
// POST /api/admin/teams/:slug/audit/:id/approve -- approve pending action
|
||||
fastify.post('/api/admin/teams/:slug/audit/:id/approve', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await requireAdmin(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const entry = await auditService.getById(id);
|
||||
if (!entry) {
|
||||
return reply.code(404).send({ error: 'Audit entry not found' });
|
||||
}
|
||||
if (entry.teamId !== team.id) {
|
||||
return reply.code(404).send({ error: 'Audit entry not found' });
|
||||
}
|
||||
|
||||
const updated = await auditService.approve(id, request.userId);
|
||||
return updated;
|
||||
});
|
||||
|
||||
// POST /api/admin/teams/:slug/audit/:id/reject -- reject pending action
|
||||
fastify.post('/api/admin/teams/:slug/audit/:id/reject', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await requireAdmin(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const entry = await auditService.getById(id);
|
||||
if (!entry) {
|
||||
return reply.code(404).send({ error: 'Audit entry not found' });
|
||||
}
|
||||
if (entry.teamId !== team.id) {
|
||||
return reply.code(404).send({ error: 'Audit entry not found' });
|
||||
}
|
||||
|
||||
const updated = await auditService.reject(id, request.userId);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
289
packages/team-server/src/routes/capability-governance.ts
Normal file
289
packages/team-server/src/routes/capability-governance.ts
Normal file
@@ -0,0 +1,289 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { TeamCapabilityGovernance } from '../services/team-capability-governance.js';
|
||||
import { MessageService } from '../services/message-service.js';
|
||||
|
||||
const ROLE_HIERARCHY: Record<string, number> = {
|
||||
member: 1,
|
||||
admin: 2,
|
||||
owner: 3,
|
||||
};
|
||||
|
||||
const VALID_ROLES = ['owner', 'admin', 'member'];
|
||||
const VALID_SOURCES = ['native', 'skill', 'plugin', 'mcp', 'subagent'];
|
||||
const VALID_THRESHOLDS = ['low', 'medium', 'high', 'none'];
|
||||
|
||||
export async function capabilityGovernanceRoutes(fastify: FastifyInstance) {
|
||||
const teamService = new TeamService(fastify.db);
|
||||
const governance = new TeamCapabilityGovernance(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return { team, membership };
|
||||
}
|
||||
|
||||
function requireAdmin(membership: { role: string }, reply: FastifyReply): boolean {
|
||||
const level = ROLE_HIERARCHY[membership.role] ?? 0;
|
||||
if (level < ROLE_HIERARCHY.admin) {
|
||||
reply.code(403).send({ error: 'Admin or owner role required' });
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// --- Policies ---
|
||||
|
||||
// GET /api/teams/:slug/capability-policies — list all policies
|
||||
fastify.get('/api/teams/:slug/capability-policies', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
|
||||
const policies = await governance.listPolicies(ctx.team.id);
|
||||
return policies;
|
||||
});
|
||||
|
||||
// PUT /api/teams/:slug/capability-policies/:role — update policy
|
||||
fastify.put('/api/teams/:slug/capability-policies/:role', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, role } = request.params as { slug: string; role: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
if (!requireAdmin(ctx.membership, reply)) return;
|
||||
|
||||
if (!VALID_ROLES.includes(role)) {
|
||||
return reply.code(400).send({ error: `Invalid role. Must be one of: ${VALID_ROLES.join(', ')}` });
|
||||
}
|
||||
|
||||
const body = request.body as {
|
||||
allowedSources?: string[];
|
||||
blockedTools?: string[];
|
||||
approvalThreshold?: string;
|
||||
};
|
||||
|
||||
if (body.allowedSources) {
|
||||
for (const s of body.allowedSources) {
|
||||
if (!VALID_SOURCES.includes(s)) {
|
||||
return reply.code(400).send({ error: `Invalid source: ${s}. Must be one of: ${VALID_SOURCES.join(', ')}` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (body.approvalThreshold && !VALID_THRESHOLDS.includes(body.approvalThreshold)) {
|
||||
return reply.code(400).send({ error: `Invalid threshold. Must be one of: ${VALID_THRESHOLDS.join(', ')}` });
|
||||
}
|
||||
|
||||
const policy = await governance.upsertPolicy(ctx.team.id, role, body, request.userId);
|
||||
return policy;
|
||||
});
|
||||
|
||||
// --- Overrides ---
|
||||
|
||||
// GET /api/teams/:slug/capability-overrides — list all overrides
|
||||
fastify.get('/api/teams/:slug/capability-overrides', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
|
||||
const overrides = await governance.listOverrides(ctx.team.id);
|
||||
return overrides;
|
||||
});
|
||||
|
||||
// POST /api/teams/:slug/capability-overrides — create override
|
||||
fastify.post('/api/teams/:slug/capability-overrides', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
if (!requireAdmin(ctx.membership, reply)) return;
|
||||
|
||||
const body = request.body as {
|
||||
capabilityName?: string;
|
||||
capabilityType?: string;
|
||||
decision?: string;
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
if (!body.capabilityName || !body.capabilityType || !body.decision) {
|
||||
return reply.code(400).send({ error: 'capabilityName, capabilityType, and decision are required' });
|
||||
}
|
||||
|
||||
if (body.decision !== 'approved' && body.decision !== 'blocked') {
|
||||
return reply.code(400).send({ error: 'decision must be approved or blocked' });
|
||||
}
|
||||
|
||||
try {
|
||||
const override = await governance.createOverride(
|
||||
ctx.team.id,
|
||||
{
|
||||
capabilityName: body.capabilityName,
|
||||
capabilityType: body.capabilityType,
|
||||
decision: body.decision as 'approved' | 'blocked',
|
||||
reason: body.reason,
|
||||
},
|
||||
request.userId,
|
||||
);
|
||||
return reply.code(201).send(override);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '';
|
||||
const code = (err && typeof err === 'object' && 'code' in err) ? (err as { code?: unknown }).code : undefined;
|
||||
if (message.includes('unique') || message.includes('UNIQUE') || code === '23505') {
|
||||
return reply.code(409).send({ error: 'Override already exists for this capability' });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/teams/:slug/capability-overrides/:id — delete override
|
||||
fastify.delete('/api/teams/:slug/capability-overrides/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
if (!requireAdmin(ctx.membership, reply)) return;
|
||||
|
||||
const deleted = await governance.deleteOverride(ctx.team.id, id);
|
||||
if (!deleted) {
|
||||
return reply.code(404).send({ error: 'Override not found' });
|
||||
}
|
||||
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// --- Requests ---
|
||||
|
||||
// POST /api/teams/:slug/capability-requests — submit request
|
||||
fastify.post('/api/teams/:slug/capability-requests', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
|
||||
const body = request.body as {
|
||||
capabilityName?: string;
|
||||
capabilityType?: string;
|
||||
justification?: string;
|
||||
};
|
||||
|
||||
if (!body.capabilityName || !body.capabilityType || !body.justification) {
|
||||
return reply.code(400).send({ error: 'capabilityName, capabilityType, and justification are required' });
|
||||
}
|
||||
|
||||
const result = await governance.submitRequest(ctx.team.id, request.userId, {
|
||||
capabilityName: body.capabilityName,
|
||||
capabilityType: body.capabilityType,
|
||||
justification: body.justification,
|
||||
});
|
||||
|
||||
if (result.duplicate) {
|
||||
return reply.code(409).send({ error: 'A pending request for this capability already exists' });
|
||||
}
|
||||
|
||||
return reply.code(201).send(result.request);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/capability-requests — list requests
|
||||
fastify.get('/api/teams/:slug/capability-requests', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
|
||||
const query = request.query as { status?: string };
|
||||
const allRequests = await governance.listRequests(ctx.team.id, query.status);
|
||||
|
||||
// Non-admin users only see their own requests
|
||||
const level = ROLE_HIERARCHY[ctx.membership.role] ?? 0;
|
||||
if (level < ROLE_HIERARCHY.admin) {
|
||||
return allRequests.filter((r) => r.requestedBy === request.userId);
|
||||
}
|
||||
|
||||
return allRequests;
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug/capability-requests/:id — decide request
|
||||
fastify.patch('/api/teams/:slug/capability-requests/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const ctx = await resolveTeam(request, reply, slug);
|
||||
if (!ctx) return;
|
||||
if (!requireAdmin(ctx.membership, reply)) return;
|
||||
|
||||
const body = request.body as { status?: string; reason?: string };
|
||||
|
||||
if (!body.status || (body.status !== 'approved' && body.status !== 'rejected')) {
|
||||
return reply.code(400).send({ error: 'status must be approved or rejected' });
|
||||
}
|
||||
|
||||
const capRequest = await governance.getRequest(ctx.team.id, id);
|
||||
if (!capRequest) {
|
||||
return reply.code(404).send({ error: 'Request not found' });
|
||||
}
|
||||
|
||||
if (capRequest.status !== 'pending') {
|
||||
return reply.code(400).send({ error: 'Request has already been decided' });
|
||||
}
|
||||
|
||||
const decided = await governance.decideRequest(
|
||||
ctx.team.id,
|
||||
id,
|
||||
request.userId,
|
||||
body.status as 'approved' | 'rejected',
|
||||
body.reason,
|
||||
);
|
||||
|
||||
// On approve: auto-create override
|
||||
if (body.status === 'approved') {
|
||||
try {
|
||||
await governance.createOverride(
|
||||
ctx.team.id,
|
||||
{
|
||||
capabilityName: capRequest.capabilityName,
|
||||
capabilityType: capRequest.capabilityType,
|
||||
decision: 'approved',
|
||||
reason: body.reason,
|
||||
},
|
||||
request.userId,
|
||||
);
|
||||
} catch (_err) {
|
||||
// Override may already exist — ignore conflict
|
||||
}
|
||||
}
|
||||
|
||||
// Send Waggle Dance notification (non-critical)
|
||||
try {
|
||||
const messageService = new MessageService(fastify.db);
|
||||
await messageService.send(ctx.team.id, request.userId, {
|
||||
type: 'response',
|
||||
subtype: 'capability_decision',
|
||||
content: { capabilityName: capRequest.capabilityName, decision: body.status, reason: body.reason ?? '' },
|
||||
routing: [{ userId: capRequest.requestedBy, reason: 'capability_request_decision' }],
|
||||
});
|
||||
} catch (_err) {
|
||||
// Non-critical — don't fail the request
|
||||
}
|
||||
|
||||
return decided;
|
||||
});
|
||||
}
|
||||
84
packages/team-server/src/routes/cron.ts
Normal file
84
packages/team-server/src/routes/cron.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { CronService } from '../services/cron-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { createCronSchema } from '@waggle/shared';
|
||||
|
||||
export async function cronRoutes(fastify: FastifyInstance) {
|
||||
const cronService = new CronService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// POST /api/teams/:slug/cron — create a cron schedule
|
||||
fastify.post('/api/teams/:slug/cron', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = createCronSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
try {
|
||||
const schedule = await cronService.create(team.id, request.userId, parsed.data);
|
||||
return reply.code(201).send(schedule);
|
||||
} catch (err: unknown) {
|
||||
return reply.code(400).send({ error: 'Invalid cron expression', message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/cron — list schedules for team
|
||||
fastify.get('/api/teams/:slug/cron', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const schedules = await cronService.list(team.id);
|
||||
return schedules;
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug/cron/:id — update a cron schedule
|
||||
fastify.patch('/api/teams/:slug/cron/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const body = request.body as {
|
||||
name?: string;
|
||||
cronExpr?: string;
|
||||
enabled?: boolean;
|
||||
jobConfig?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
try {
|
||||
const updated = await cronService.update(team.id, id, body);
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Schedule not found' });
|
||||
}
|
||||
return updated;
|
||||
} catch (err: unknown) {
|
||||
return reply.code(400).send({ error: 'Invalid cron expression', message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
});
|
||||
}
|
||||
101
packages/team-server/src/routes/jobs.ts
Normal file
101
packages/team-server/src/routes/jobs.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { queueJobSchema } from '@waggle/shared';
|
||||
import { AgentService } from '../services/agent-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
|
||||
export async function jobRoutes(fastify: FastifyInstance) {
|
||||
const agentService = new AgentService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
// GET /api/jobs?teamSlug=... - list jobs for a team
|
||||
fastify.get('/api/jobs', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { teamSlug, limit } = request.query as { teamSlug?: string; limit?: string };
|
||||
if (!teamSlug) {
|
||||
return reply.code(400).send({ error: 'teamSlug query parameter is required' });
|
||||
}
|
||||
|
||||
const team = await teamService.getBySlug(teamSlug);
|
||||
if (!team) return reply.code(404).send({ error: 'Team not found' });
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) return reply.code(403).send({ error: 'Not a member of this team' });
|
||||
|
||||
const jobs = await fastify.jobService.listByTeam(team.id, limit ? parseInt(limit, 10) : 50);
|
||||
return jobs;
|
||||
});
|
||||
|
||||
// POST /api/jobs - queue a new job
|
||||
fastify.post('/api/jobs', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const parsed = queueJobSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const teamId = parsed.data.teamId;
|
||||
if (!teamId) {
|
||||
return reply.code(400).send({ error: 'teamId is required' });
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(teamId, request.userId);
|
||||
if (!membership) {
|
||||
return reply.code(404).send({ error: 'Team not found' });
|
||||
}
|
||||
|
||||
if (parsed.data.jobType === 'group') {
|
||||
const groupId = parsed.data.input.groupId;
|
||||
if (typeof groupId !== 'string') {
|
||||
return reply.code(400).send({ error: 'groupId is required for group jobs' });
|
||||
}
|
||||
|
||||
const group = await agentService.getGroup(groupId, request.userId);
|
||||
if (!group) {
|
||||
return reply.code(404).send({ error: 'Agent group not found' });
|
||||
}
|
||||
}
|
||||
|
||||
const job = await fastify.jobService.createJob(
|
||||
teamId,
|
||||
request.userId,
|
||||
parsed.data.jobType,
|
||||
parsed.data.input,
|
||||
);
|
||||
return reply.code(202).send({ jobId: job.id, status: job.status });
|
||||
});
|
||||
|
||||
// POST /api/jobs/:id/cancel - cancel a running or queued job
|
||||
fastify.post('/api/jobs/:id/cancel', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const job = await fastify.jobService.getJob(id);
|
||||
if (!job) return reply.code(404).send({ error: 'Job not found' });
|
||||
|
||||
const membership = await teamService.getMembership(job.teamId, request.userId);
|
||||
if (!membership) return reply.code(404).send({ error: 'Job not found' });
|
||||
|
||||
if (job.status !== 'queued' && job.status !== 'running') {
|
||||
return reply.code(409).send({ error: `Cannot cancel job with status "${job.status}"` });
|
||||
}
|
||||
|
||||
const updated = await fastify.jobService.cancelJob(id);
|
||||
return { cancelled: true, jobId: updated?.id ?? id };
|
||||
});
|
||||
|
||||
// GET /api/jobs/:id - get job status
|
||||
fastify.get('/api/jobs/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const job = await fastify.jobService.getJob(id);
|
||||
if (!job) return reply.code(404).send({ error: 'Job not found' });
|
||||
|
||||
const membership = await teamService.getMembership(job.teamId, request.userId);
|
||||
if (!membership) return reply.code(404).send({ error: 'Job not found' });
|
||||
|
||||
return job;
|
||||
});
|
||||
}
|
||||
108
packages/team-server/src/routes/knowledge.ts
Normal file
108
packages/team-server/src/routes/knowledge.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { KnowledgeService } from '../services/knowledge-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { createEntitySchema, createRelationSchema } from '@waggle/shared';
|
||||
|
||||
export async function knowledgeRoutes(fastify: FastifyInstance) {
|
||||
const knowledgeService = new KnowledgeService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// POST /api/teams/:slug/entities — share entity to team graph
|
||||
fastify.post('/api/teams/:slug/entities', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = createEntitySchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const entity = await knowledgeService.createEntity(team.id, request.userId, parsed.data);
|
||||
return reply.code(201).send(entity);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/entities — list/search entities
|
||||
fastify.get('/api/teams/:slug/entities', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { type?: string; search?: string };
|
||||
const filters: { entityType?: string; search?: string } = {};
|
||||
if (query.type) filters.entityType = query.type;
|
||||
if (query.search) filters.search = query.search;
|
||||
|
||||
const entities = await knowledgeService.listEntities(team.id, filters);
|
||||
return entities;
|
||||
});
|
||||
|
||||
// POST /api/teams/:slug/relations — create relation
|
||||
fastify.post('/api/teams/:slug/relations', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = createRelationSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const relation = await knowledgeService.createRelation(team.id, parsed.data);
|
||||
if (!relation) {
|
||||
return reply.code(404).send({ error: 'Entity not found' });
|
||||
}
|
||||
return reply.code(201).send(relation);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/graph — query graph traversal
|
||||
fastify.get('/api/teams/:slug/graph', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { startId?: string; depth?: string; relationTypes?: string };
|
||||
if (!query.startId) {
|
||||
return reply.code(400).send({ error: 'startId query parameter is required' });
|
||||
}
|
||||
|
||||
const depth = query.depth ? parseInt(query.depth, 10) : 2;
|
||||
if (isNaN(depth) || depth < 1 || depth > 10) {
|
||||
return reply.code(400).send({ error: 'depth must be between 1 and 10' });
|
||||
}
|
||||
|
||||
const relationTypes = query.relationTypes
|
||||
? query.relationTypes.split(',').map((s) => s.trim())
|
||||
: undefined;
|
||||
|
||||
const result = await knowledgeService.queryGraph(team.id, query.startId, depth, relationTypes);
|
||||
if (!result) {
|
||||
return reply.code(404).send({ error: 'Entity not found' });
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
96
packages/team-server/src/routes/messages.ts
Normal file
96
packages/team-server/src/routes/messages.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { MessageService } from '../services/message-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { sendMessageSchema } from '@waggle/shared';
|
||||
import { validateMessageTypeCombo } from '@waggle/waggle-dance';
|
||||
import type { MessageType, MessageSubtype } from '@waggle/shared';
|
||||
import { z } from 'zod';
|
||||
|
||||
const hiveCheckSchema = z.object({
|
||||
topic: z.string().min(1).max(500),
|
||||
scope: z.string().max(200).optional(),
|
||||
});
|
||||
|
||||
export async function messageRoutes(fastify: FastifyInstance) {
|
||||
const messageService = new MessageService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// POST /api/teams/:slug/messages — send Waggle Dance message
|
||||
fastify.post('/api/teams/:slug/messages', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = sendMessageSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
// Validate type-subtype combination using waggle-dance protocol
|
||||
if (!validateMessageTypeCombo(parsed.data.type as MessageType, parsed.data.subtype as MessageSubtype)) {
|
||||
return reply.code(400).send({
|
||||
error: `Invalid type-subtype combination: ${parsed.data.type}/${parsed.data.subtype}`,
|
||||
});
|
||||
}
|
||||
|
||||
const message = await messageService.send(
|
||||
team.id,
|
||||
request.userId,
|
||||
parsed.data,
|
||||
fastify.redis,
|
||||
);
|
||||
return reply.code(201).send(message);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/messages — list messages
|
||||
fastify.get('/api/teams/:slug/messages', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { type?: string; subtype?: string };
|
||||
const filters: { type?: string; subtype?: string } = {};
|
||||
if (query.type) filters.type = query.type;
|
||||
if (query.subtype) filters.subtype = query.subtype;
|
||||
|
||||
const messageList = await messageService.list(team.id, filters);
|
||||
return messageList;
|
||||
});
|
||||
|
||||
// POST /api/teams/:slug/messages/hive-check — check the hive
|
||||
fastify.post('/api/teams/:slug/messages/hive-check', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = hiveCheckSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const result = await messageService.checkHive(team.id, parsed.data);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
78
packages/team-server/src/routes/resources.ts
Normal file
78
packages/team-server/src/routes/resources.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { ResourceService } from '../services/resource-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { createResourceSchema } from '@waggle/shared';
|
||||
|
||||
export async function resourceRoutes(fastify: FastifyInstance) {
|
||||
const resourceService = new ResourceService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// POST /api/teams/:slug/resources — share a resource
|
||||
fastify.post('/api/teams/:slug/resources', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = createResourceSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const resource = await resourceService.share(team.id, request.userId, parsed.data);
|
||||
return reply.code(201).send(resource);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/resources — list resources
|
||||
fastify.get('/api/teams/:slug/resources', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { type?: string };
|
||||
const resources = await resourceService.list(team.id, query.type);
|
||||
return resources;
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug/resources/:id — rate a resource (also increments useCount)
|
||||
fastify.patch('/api/teams/:slug/resources/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const body = request.body as { rating?: number };
|
||||
if (body.rating === undefined || typeof body.rating !== 'number' || body.rating < 0 || body.rating > 5) {
|
||||
return reply.code(400).send({ error: 'rating must be a number between 0 and 5' });
|
||||
}
|
||||
|
||||
// Rate (uses running average) then increment use count
|
||||
const rated = await resourceService.rate(team.id, id, body.rating);
|
||||
if (!rated) {
|
||||
return reply.code(404).send({ error: 'Resource not found' });
|
||||
}
|
||||
|
||||
const updated = await resourceService.incrementUseCount(team.id, id);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
35
packages/team-server/src/routes/scout.ts
Normal file
35
packages/team-server/src/routes/scout.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { ScoutAgent } from '../daemons/scout.js';
|
||||
|
||||
export async function scoutRoutes(fastify: FastifyInstance) {
|
||||
const scout = new ScoutAgent(fastify.db);
|
||||
|
||||
// GET /api/scout/findings — list findings for the authenticated user
|
||||
fastify.get('/api/scout/findings', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request) => {
|
||||
return scout.listFindings(request.userId);
|
||||
});
|
||||
|
||||
// PATCH /api/scout/findings/:id — adopt or dismiss a finding
|
||||
fastify.patch('/api/scout/findings/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = request.body as { status?: string };
|
||||
|
||||
if (!body.status || !['adopted', 'dismissed'].includes(body.status)) {
|
||||
return reply.code(400).send({ error: 'status must be one of: adopted, dismissed' });
|
||||
}
|
||||
|
||||
const action = body.status === 'adopted'
|
||||
? scout.adopt(id, request.userId)
|
||||
: scout.dismiss(id, request.userId);
|
||||
const updated = await action;
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Finding not found' });
|
||||
}
|
||||
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
36
packages/team-server/src/routes/suggestions.ts
Normal file
36
packages/team-server/src/routes/suggestions.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { ProactiveService } from '../services/proactive-service.js';
|
||||
|
||||
export async function suggestionRoutes(fastify: FastifyInstance) {
|
||||
const proactiveService = new ProactiveService(fastify.db);
|
||||
|
||||
// GET /api/suggestions — list pending suggestions for the authenticated user
|
||||
fastify.get('/api/suggestions', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request) => {
|
||||
return proactiveService.listPending(request.userId);
|
||||
});
|
||||
|
||||
// PATCH /api/suggestions/:id — accept, dismiss, or snooze a suggestion
|
||||
fastify.patch('/api/suggestions/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const body = request.body as { status?: string };
|
||||
|
||||
if (!body.status || !['accepted', 'dismissed', 'snoozed'].includes(body.status)) {
|
||||
return reply.code(400).send({ error: 'status must be one of: accepted, dismissed, snoozed' });
|
||||
}
|
||||
|
||||
const updated = await proactiveService.updateStatus(
|
||||
id,
|
||||
request.userId,
|
||||
body.status as 'accepted' | 'dismissed' | 'snoozed',
|
||||
);
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Suggestion not found' });
|
||||
}
|
||||
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
115
packages/team-server/src/routes/tasks.ts
Normal file
115
packages/team-server/src/routes/tasks.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { TaskService } from '../services/task-service.js';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { createTaskSchema, updateTaskSchema } from '@waggle/shared';
|
||||
|
||||
export async function taskRoutes(fastify: FastifyInstance) {
|
||||
const taskService = new TaskService(fastify.db);
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return team;
|
||||
}
|
||||
|
||||
// POST /api/teams/:slug/tasks — create task
|
||||
fastify.post('/api/teams/:slug/tasks', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = createTaskSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const task = await taskService.create(team.id, request.userId, parsed.data);
|
||||
return reply.code(201).send(task);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/tasks — list tasks
|
||||
fastify.get('/api/teams/:slug/tasks', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const query = request.query as { status?: string; assignee?: string; priority?: string };
|
||||
const filters: { status?: string; assignee?: string; priority?: string } = {};
|
||||
if (query.status) filters.status = query.status;
|
||||
if (query.assignee) filters.assignee = query.assignee;
|
||||
if (query.priority) filters.priority = query.priority;
|
||||
|
||||
const taskList = await taskService.list(team.id, filters);
|
||||
return taskList;
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug/tasks/:id — get task details
|
||||
fastify.get('/api/teams/:slug/tasks/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const task = await taskService.get(id);
|
||||
if (!task || task.teamId !== team.id) {
|
||||
return reply.code(404).send({ error: 'Task not found' });
|
||||
}
|
||||
|
||||
return task;
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug/tasks/:id — update task
|
||||
fastify.patch('/api/teams/:slug/tasks/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const parsed = updateTaskSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
const existing = await taskService.get(id);
|
||||
if (!existing || existing.teamId !== team.id) {
|
||||
return reply.code(404).send({ error: 'Task not found' });
|
||||
}
|
||||
|
||||
const updated = await taskService.update(id, parsed.data);
|
||||
return updated;
|
||||
});
|
||||
|
||||
// POST /api/teams/:slug/tasks/:id/claim — claim task
|
||||
fastify.post('/api/teams/:slug/tasks/:id/claim', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { slug, id } = request.params as { slug: string; id: string };
|
||||
const team = await resolveTeam(request, reply, slug);
|
||||
if (!team) return;
|
||||
|
||||
const existing = await taskService.get(id);
|
||||
if (!existing || existing.teamId !== team.id) {
|
||||
return reply.code(404).send({ error: 'Task not found' });
|
||||
}
|
||||
|
||||
const claimed = await taskService.claim(id, request.userId);
|
||||
return claimed;
|
||||
});
|
||||
}
|
||||
184
packages/team-server/src/routes/teams.ts
Normal file
184
packages/team-server/src/routes/teams.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
import { users } from '../db/schema.js';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { createTeamSchema, inviteMemberSchema, updateMemberSchema } from '@waggle/shared';
|
||||
|
||||
const ROLE_HIERARCHY: Record<string, number> = { member: 1, admin: 2, owner: 3 };
|
||||
|
||||
async function requireTeamRole(
|
||||
server: FastifyInstance,
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
slug: string,
|
||||
minRole: 'member' | 'admin' | 'owner',
|
||||
) {
|
||||
const teamService = new TeamService(server.db);
|
||||
const team = await teamService.getBySlug(slug);
|
||||
if (!team) {
|
||||
reply.code(404).send({ error: 'Team not found' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, request.userId);
|
||||
if (!membership) {
|
||||
reply.code(403).send({ error: 'Not a member of this team' });
|
||||
return null;
|
||||
}
|
||||
|
||||
const userLevel = ROLE_HIERARCHY[membership.role] ?? 0;
|
||||
const requiredLevel = ROLE_HIERARCHY[minRole] ?? 0;
|
||||
if (userLevel < requiredLevel) {
|
||||
reply.code(403).send({ error: 'Insufficient permissions' });
|
||||
return null;
|
||||
}
|
||||
|
||||
return { team, membership };
|
||||
}
|
||||
|
||||
export async function teamRoutes(fastify: FastifyInstance) {
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
// POST /api/teams — create team
|
||||
fastify.post('/api/teams', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const parsed = createTeamSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
// Check slug uniqueness
|
||||
const existing = await teamService.getBySlug(parsed.data.slug);
|
||||
if (existing) {
|
||||
return reply.code(409).send({ error: 'Team slug already exists' });
|
||||
}
|
||||
|
||||
const team = await teamService.create(request.userId, parsed.data);
|
||||
return reply.code(201).send(team);
|
||||
});
|
||||
|
||||
// GET /api/teams — list user's teams
|
||||
fastify.get('/api/teams', { preHandler: [fastify.authenticate] }, async (request) => {
|
||||
return teamService.listForUser(request.userId);
|
||||
});
|
||||
|
||||
// GET /api/teams/:slug — get team details with members
|
||||
fastify.get('/api/teams/:slug', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'member');
|
||||
if (!result) return;
|
||||
|
||||
const members = await teamService.getMembers(result.team.id);
|
||||
return { ...result.team, members };
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug — update team (admin+)
|
||||
fastify.patch('/api/teams/:slug', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
|
||||
if (!result) return;
|
||||
|
||||
const body = request.body as { name?: string };
|
||||
if (!body.name || typeof body.name !== 'string' || body.name.length < 1 || body.name.length > 100) {
|
||||
return reply.code(400).send({ error: 'Invalid name' });
|
||||
}
|
||||
|
||||
const updated = await teamService.update(result.team.id, { name: body.name });
|
||||
return updated;
|
||||
});
|
||||
|
||||
// POST /api/teams/:slug/members — invite member (admin+)
|
||||
fastify.post('/api/teams/:slug/members', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { slug } = request.params as { slug: string };
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
|
||||
if (!result) return;
|
||||
|
||||
const parsed = inviteMemberSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
// Look up user by email
|
||||
const [targetUser] = await fastify.db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.email, parsed.data.email))
|
||||
.limit(1);
|
||||
|
||||
if (!targetUser) {
|
||||
return reply.code(404).send({ error: 'User not found with that email' });
|
||||
}
|
||||
|
||||
// Check if already a member
|
||||
const existingMembership = await teamService.getMembership(result.team.id, targetUser.id);
|
||||
if (existingMembership) {
|
||||
return reply.code(409).send({ error: 'User is already a member of this team' });
|
||||
}
|
||||
|
||||
const member = await teamService.addMember(result.team.id, targetUser.id, parsed.data.role);
|
||||
return reply.code(201).send(member);
|
||||
});
|
||||
|
||||
// DELETE /api/teams/:slug/members/:userId — remove member (admin+)
|
||||
fastify.delete('/api/teams/:slug/members/:userId', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { slug, userId } = request.params as { slug: string; userId: string };
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
|
||||
if (!result) return;
|
||||
|
||||
try {
|
||||
const removed = await teamService.removeMember(result.team.id, userId);
|
||||
if (!removed) {
|
||||
return reply.code(404).send({ error: 'Member not found' });
|
||||
}
|
||||
return reply.code(204).send();
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.message === 'Cannot remove the team owner') {
|
||||
return reply.code(403).send({ error: err.message });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// PATCH /api/teams/:slug/members/:userId — update member
|
||||
fastify.patch('/api/teams/:slug/members/:userId', { preHandler: [fastify.authenticate] }, async (request, reply) => {
|
||||
const { slug, userId: targetUserId } = request.params as { slug: string; userId: string };
|
||||
|
||||
const parsed = updateMemberSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
// Determine required role: role changes need admin+, self-updates for roleDescription/interests are ok
|
||||
const isSelfUpdate = request.userId === targetUserId;
|
||||
const isRoleChange = parsed.data.role !== undefined;
|
||||
|
||||
if (isRoleChange || !isSelfUpdate) {
|
||||
// Need admin+ for role changes or updating other members
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
|
||||
if (!result) return;
|
||||
|
||||
try {
|
||||
const updated = await teamService.updateMember(result.team.id, targetUserId, parsed.data);
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Member not found' });
|
||||
}
|
||||
return updated;
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.message === 'Cannot change the team owner role') {
|
||||
return reply.code(403).send({ error: err.message });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
} else {
|
||||
// Self-update: only roleDescription and interests (no role field)
|
||||
const result = await requireTeamRole(fastify, request, reply, slug, 'member');
|
||||
if (!result) return;
|
||||
|
||||
const { role: _discard, ...safeData } = parsed.data;
|
||||
const updated = await teamService.updateMember(result.team.id, targetUserId, safeData);
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Member not found' });
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
});
|
||||
}
|
||||
57
packages/team-server/src/routes/webhooks.ts
Normal file
57
packages/team-server/src/routes/webhooks.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { verifyWebhook } from '@clerk/fastify/webhooks';
|
||||
import { users } from '../db/schema.js';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
/** Subset of the Clerk user webhook payload `data` object that we consume. */
|
||||
interface ClerkWebhookUserData {
|
||||
id: string;
|
||||
first_name?: string | null;
|
||||
last_name?: string | null;
|
||||
email_addresses?: Array<{ email_address?: string }>;
|
||||
image_url?: string | null;
|
||||
}
|
||||
|
||||
export async function webhookRoutes(fastify: FastifyInstance) {
|
||||
fastify.post('/api/webhooks/clerk', async (request, reply) => {
|
||||
let event: { type: string; data: ClerkWebhookUserData };
|
||||
try {
|
||||
event = await verifyWebhook(request) as typeof event;
|
||||
} catch (error) {
|
||||
fastify.log.warn({ err: error }, 'Clerk webhook verification failed');
|
||||
return reply.code(400).send({ error: 'Invalid webhook signature' });
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'user.created': {
|
||||
const d = event.data;
|
||||
await fastify.db.insert(users).values({
|
||||
clerkId: d.id,
|
||||
displayName: `${d.first_name ?? ''} ${d.last_name ?? ''}`.trim() || d.id,
|
||||
email: d.email_addresses?.[0]?.email_address ?? '',
|
||||
avatarUrl: d.image_url ?? null,
|
||||
}).onConflictDoNothing();
|
||||
break;
|
||||
}
|
||||
case 'user.updated': {
|
||||
const d = event.data;
|
||||
await fastify.db.update(users)
|
||||
.set({
|
||||
displayName: `${d.first_name ?? ''} ${d.last_name ?? ''}`.trim(),
|
||||
email: d.email_addresses?.[0]?.email_address ?? '',
|
||||
avatarUrl: d.image_url ?? null,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(users.clerkId, d.id));
|
||||
break;
|
||||
}
|
||||
case 'user.deleted': {
|
||||
const d = event.data;
|
||||
await fastify.db.delete(users).where(eq(users.clerkId, d.id));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return reply.code(200).send({ received: true });
|
||||
});
|
||||
}
|
||||
110
packages/team-server/src/scheduler/cron-runner.ts
Normal file
110
packages/team-server/src/scheduler/cron-runner.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { lte, eq, and } from 'drizzle-orm';
|
||||
import { createHash } from 'node:crypto';
|
||||
import cronParser from 'cron-parser';
|
||||
const { parseExpression } = cronParser;
|
||||
import { cronSchedules } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import type { JobService } from '../services/job-service.js';
|
||||
import { scheduledJobTypeSchema } from '@waggle/shared';
|
||||
|
||||
function occurrenceJobId(scheduleId: string, scheduledFor: Date): string {
|
||||
const bytes = createHash('sha256')
|
||||
.update(scheduleId)
|
||||
.update('\0')
|
||||
.update(scheduledFor.toISOString())
|
||||
.digest()
|
||||
.subarray(0, 16);
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x80;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
const hex = bytes.toString('hex');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
|
||||
export class CronRunner {
|
||||
private interval: ReturnType<typeof setInterval> | null = null;
|
||||
private tickInFlight: Promise<number> | null = null;
|
||||
|
||||
constructor(
|
||||
private db: Db,
|
||||
private jobService: JobService,
|
||||
private onError: (error: unknown) => void = () => undefined,
|
||||
) {}
|
||||
|
||||
start(intervalMs = 60_000) {
|
||||
if (this.interval) return;
|
||||
if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
|
||||
throw new Error('Cron interval must be a positive number');
|
||||
}
|
||||
|
||||
const runTick = () => {
|
||||
if (this.tickInFlight) return;
|
||||
const tick = this.tick()
|
||||
.catch(error => {
|
||||
this.onError(error);
|
||||
return 0;
|
||||
})
|
||||
.finally(() => {
|
||||
if (this.tickInFlight === tick) this.tickInFlight = null;
|
||||
});
|
||||
this.tickInFlight = tick;
|
||||
};
|
||||
|
||||
runTick();
|
||||
this.interval = setInterval(runTick, intervalMs);
|
||||
this.interval.unref?.();
|
||||
}
|
||||
|
||||
async stop() {
|
||||
if (this.interval) {
|
||||
clearInterval(this.interval);
|
||||
this.interval = null;
|
||||
}
|
||||
await this.tickInFlight;
|
||||
}
|
||||
|
||||
async tick() {
|
||||
const now = new Date();
|
||||
|
||||
// Find all enabled schedules that are due
|
||||
const due = await this.db.select().from(cronSchedules)
|
||||
.where(and(
|
||||
eq(cronSchedules.enabled, true),
|
||||
lte(cronSchedules.nextRunAt, now),
|
||||
));
|
||||
|
||||
let queuedCount = 0;
|
||||
for (const schedule of due) {
|
||||
const jobType = scheduledJobTypeSchema.safeParse(schedule.jobType);
|
||||
if (!jobType.success || !schedule.nextRunAt) continue;
|
||||
|
||||
try {
|
||||
// Validate legacy rows before queueing so a poison cron expression
|
||||
// cannot create a duplicate job on every scheduler pass.
|
||||
const nextRunAt = parseExpression(schedule.cronExpr).next().toDate();
|
||||
|
||||
await this.jobService.createJob(
|
||||
schedule.teamId,
|
||||
schedule.createdBy,
|
||||
jobType.data,
|
||||
schedule.jobConfig as Record<string, unknown>,
|
||||
occurrenceJobId(schedule.id, schedule.nextRunAt),
|
||||
);
|
||||
|
||||
const [advanced] = await this.db.update(cronSchedules)
|
||||
.set({ lastRunAt: now, nextRunAt })
|
||||
.where(and(
|
||||
eq(cronSchedules.id, schedule.id),
|
||||
eq(cronSchedules.nextRunAt, schedule.nextRunAt),
|
||||
))
|
||||
.returning({ id: cronSchedules.id });
|
||||
if (advanced) queuedCount++;
|
||||
} catch (error) {
|
||||
// One malformed or temporarily failing schedule must not starve the
|
||||
// remaining due work. The lifecycle runner supplies the server logger.
|
||||
this.onError(error);
|
||||
}
|
||||
}
|
||||
|
||||
return queuedCount;
|
||||
}
|
||||
}
|
||||
100
packages/team-server/src/services/agent-group-executor.ts
Normal file
100
packages/team-server/src/services/agent-group-executor.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Agent Group Executor — converts agent group definitions into
|
||||
* SubagentOrchestrator workflow templates and executes them.
|
||||
*
|
||||
* Strategies:
|
||||
* - sequential: Execute members in executionOrder, each waits for previous
|
||||
* - parallel: Execute all members simultaneously
|
||||
* - coordinator: First member coordinates, others are workers
|
||||
*
|
||||
* The local sidecar keeps its own copy in
|
||||
* packages/server/src/services/agent-group-executor.ts.
|
||||
*/
|
||||
|
||||
import type { WorkflowTemplate, WorkflowStep } from '@waggle/agent';
|
||||
|
||||
interface AgentGroupMember {
|
||||
agentId: string;
|
||||
roleInGroup: string;
|
||||
executionOrder: number;
|
||||
// Joined from agents table:
|
||||
name?: string;
|
||||
role?: string;
|
||||
systemPrompt?: string;
|
||||
model?: string;
|
||||
tools?: string[];
|
||||
}
|
||||
|
||||
interface AgentGroupData {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
strategy: string;
|
||||
members: AgentGroupMember[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an agent group with its members into a WorkflowTemplate
|
||||
* that the SubagentOrchestrator can execute.
|
||||
*/
|
||||
export function buildWorkflowFromGroup(group: AgentGroupData, task: string): WorkflowTemplate {
|
||||
const strategy = group.strategy || 'sequential';
|
||||
|
||||
const steps: WorkflowStep[] = [...group.members]
|
||||
.sort((a, b) => (a.executionOrder ?? 0) - (b.executionOrder ?? 0))
|
||||
.map((member, index, arr) => {
|
||||
const personaInstructions = member.systemPrompt?.trim()
|
||||
? `\n\n## Agent Instructions\n${member.systemPrompt.trim()}`
|
||||
: '';
|
||||
const step: WorkflowStep = {
|
||||
name: member.name ?? `agent-${member.agentId}`,
|
||||
role: member.roleInGroup ?? member.role ?? 'worker',
|
||||
task: `${task}${personaInstructions}`,
|
||||
tools: member.tools,
|
||||
maxTurns: 10,
|
||||
model: member.model,
|
||||
};
|
||||
|
||||
switch (strategy) {
|
||||
case 'sequential':
|
||||
// Each step depends on the previous one
|
||||
if (index > 0) {
|
||||
const prevName = arr[index - 1].name ?? `agent-${arr[index - 1].agentId}`;
|
||||
step.dependsOn = [prevName];
|
||||
step.contextFrom = [prevName];
|
||||
}
|
||||
break;
|
||||
|
||||
case 'parallel':
|
||||
// No dependencies — all run simultaneously
|
||||
break;
|
||||
|
||||
case 'coordinator':
|
||||
// First member is coordinator, others depend on coordinator's output
|
||||
if (index === 0) {
|
||||
step.role = 'coordinator';
|
||||
step.task = `You are the coordinator. Break down this task and delegate to your team:\n\n${step.task}`;
|
||||
} else {
|
||||
const coordinatorName = arr[0].name ?? `agent-${arr[0].agentId}`;
|
||||
step.dependsOn = [coordinatorName];
|
||||
step.contextFrom = [coordinatorName];
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return step;
|
||||
});
|
||||
|
||||
// Choose aggregation based on strategy
|
||||
const aggregation: WorkflowTemplate['aggregation'] =
|
||||
strategy === 'coordinator' ? 'synthesize' :
|
||||
strategy === 'parallel' ? 'concatenate' :
|
||||
'last';
|
||||
|
||||
return {
|
||||
name: group.name,
|
||||
description: group.description ?? `Agent group: ${group.name}`,
|
||||
steps,
|
||||
aggregation,
|
||||
};
|
||||
}
|
||||
241
packages/team-server/src/services/agent-service.ts
Normal file
241
packages/team-server/src/services/agent-service.ts
Normal file
@@ -0,0 +1,241 @@
|
||||
import { eq, and, inArray } from 'drizzle-orm';
|
||||
import { agents, agentGroups, agentGroupMembers, agentJobs } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export class AgentGroupMemberNotFoundError extends Error {}
|
||||
|
||||
export class AgentService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
private async groupMembersOwned(userId: string, agentIds: string[]): Promise<boolean> {
|
||||
const uniqueAgentIds = [...new Set(agentIds)];
|
||||
if (uniqueAgentIds.length === 0) return true;
|
||||
|
||||
const ownedAgents = await this.db
|
||||
.select({ id: agents.id })
|
||||
.from(agents)
|
||||
.where(and(eq(agents.userId, userId), inArray(agents.id, uniqueAgentIds)));
|
||||
|
||||
return ownedAgents.length === uniqueAgentIds.length;
|
||||
}
|
||||
|
||||
private async assertGroupMembersOwned(userId: string, agentIds: string[]): Promise<void> {
|
||||
if (!(await this.groupMembersOwned(userId, agentIds))) {
|
||||
throw new AgentGroupMemberNotFoundError();
|
||||
}
|
||||
}
|
||||
|
||||
async create(userId: string, data: {
|
||||
name: string;
|
||||
role?: string;
|
||||
systemPrompt?: string;
|
||||
model?: string;
|
||||
tools?: string[];
|
||||
config?: Record<string, unknown>;
|
||||
teamId?: string;
|
||||
}) {
|
||||
const [agent] = await this.db.insert(agents).values({
|
||||
userId,
|
||||
name: data.name,
|
||||
role: data.role,
|
||||
systemPrompt: data.systemPrompt,
|
||||
model: data.model ?? 'claude-haiku-4-5',
|
||||
tools: data.tools ?? [],
|
||||
config: data.config ?? {},
|
||||
teamId: data.teamId,
|
||||
}).returning();
|
||||
return agent;
|
||||
}
|
||||
|
||||
async list(userId: string) {
|
||||
return this.db
|
||||
.select()
|
||||
.from(agents)
|
||||
.where(eq(agents.userId, userId));
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
const [agent] = await this.db
|
||||
.select()
|
||||
.from(agents)
|
||||
.where(eq(agents.id, id))
|
||||
.limit(1);
|
||||
return agent ?? null;
|
||||
}
|
||||
|
||||
async update(id: string, userId: string, data: {
|
||||
name?: string;
|
||||
role?: string;
|
||||
systemPrompt?: string;
|
||||
model?: string;
|
||||
tools?: string[];
|
||||
config?: Record<string, unknown>;
|
||||
}) {
|
||||
const setData: Record<string, unknown> = {};
|
||||
if (data.name !== undefined) setData.name = data.name;
|
||||
if (data.role !== undefined) setData.role = data.role;
|
||||
if (data.systemPrompt !== undefined) setData.systemPrompt = data.systemPrompt;
|
||||
if (data.model !== undefined) setData.model = data.model;
|
||||
if (data.tools !== undefined) setData.tools = data.tools;
|
||||
if (data.config !== undefined) setData.config = data.config;
|
||||
|
||||
if (Object.keys(setData).length === 0) return null;
|
||||
|
||||
const [updated] = await this.db
|
||||
.update(agents)
|
||||
.set(setData)
|
||||
.where(and(eq(agents.id, id), eq(agents.userId, userId)))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async delete(id: string, userId: string) {
|
||||
// First remove agent from any groups
|
||||
await this.db
|
||||
.delete(agentGroupMembers)
|
||||
.where(eq(agentGroupMembers.agentId, id));
|
||||
|
||||
const result = await this.db
|
||||
.delete(agents)
|
||||
.where(and(eq(agents.id, id), eq(agents.userId, userId)))
|
||||
.returning();
|
||||
return result.length > 0;
|
||||
}
|
||||
|
||||
async createGroup(userId: string, data: {
|
||||
name: string;
|
||||
description?: string;
|
||||
strategy: string;
|
||||
members: Array<{ agentId: string; roleInGroup?: string; executionOrder?: number }>;
|
||||
}) {
|
||||
await this.assertGroupMembersOwned(userId, data.members.map((member) => member.agentId));
|
||||
|
||||
return this.db.transaction(async (tx) => {
|
||||
const [group] = await tx.insert(agentGroups).values({
|
||||
userId,
|
||||
name: data.name,
|
||||
description: data.description,
|
||||
strategy: data.strategy,
|
||||
}).returning();
|
||||
|
||||
if (data.members.length > 0) {
|
||||
await tx.insert(agentGroupMembers).values(
|
||||
data.members.map((m) => ({
|
||||
groupId: group.id,
|
||||
agentId: m.agentId,
|
||||
roleInGroup: m.roleInGroup ?? 'worker',
|
||||
executionOrder: m.executionOrder ?? 0,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const members = await tx
|
||||
.select()
|
||||
.from(agentGroupMembers)
|
||||
.where(eq(agentGroupMembers.groupId, group.id));
|
||||
|
||||
return { ...group, members };
|
||||
});
|
||||
}
|
||||
|
||||
async listGroups(userId: string) {
|
||||
return this.db
|
||||
.select()
|
||||
.from(agentGroups)
|
||||
.where(eq(agentGroups.userId, userId));
|
||||
}
|
||||
|
||||
async getGroup(groupId: string, userId: string) {
|
||||
const [group] = await this.db
|
||||
.select()
|
||||
.from(agentGroups)
|
||||
.where(and(eq(agentGroups.id, groupId), eq(agentGroups.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
if (!group) return null;
|
||||
|
||||
const members = await this.db
|
||||
.select()
|
||||
.from(agentGroupMembers)
|
||||
.where(eq(agentGroupMembers.groupId, groupId));
|
||||
|
||||
if (!(await this.groupMembersOwned(userId, members.map((member) => member.agentId)))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { ...group, members };
|
||||
}
|
||||
|
||||
async updateGroup(groupId: string, userId: string, data: {
|
||||
name?: string;
|
||||
description?: string;
|
||||
strategy?: string;
|
||||
members?: Array<{ agentId: string; roleInGroup?: string; executionOrder?: number }>;
|
||||
}) {
|
||||
// Verify ownership
|
||||
const existing = await this.getGroup(groupId, userId);
|
||||
if (!existing) return null;
|
||||
if (data.members) {
|
||||
await this.assertGroupMembersOwned(userId, data.members.map((member) => member.agentId));
|
||||
}
|
||||
|
||||
return this.db.transaction(async (tx) => {
|
||||
// Update group fields if any provided
|
||||
const updates: Record<string, unknown> = {};
|
||||
if (data.name != null) updates.name = data.name;
|
||||
if (data.description != null) updates.description = data.description;
|
||||
if (data.strategy != null) updates.strategy = data.strategy;
|
||||
|
||||
if (Object.keys(updates).length > 0) {
|
||||
updates.updatedAt = new Date();
|
||||
await tx.update(agentGroups).set(updates).where(eq(agentGroups.id, groupId));
|
||||
}
|
||||
|
||||
// Replace members if provided
|
||||
if (data.members) {
|
||||
await tx.delete(agentGroupMembers).where(eq(agentGroupMembers.groupId, groupId));
|
||||
if (data.members.length > 0) {
|
||||
await tx.insert(agentGroupMembers).values(
|
||||
data.members.map(m => ({
|
||||
groupId,
|
||||
agentId: m.agentId,
|
||||
roleInGroup: m.roleInGroup ?? 'worker',
|
||||
executionOrder: m.executionOrder ?? 0,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Return updated group with members
|
||||
const [group] = await tx.select().from(agentGroups).where(eq(agentGroups.id, groupId));
|
||||
const members = await tx.select().from(agentGroupMembers).where(eq(agentGroupMembers.groupId, groupId));
|
||||
return { ...group, members };
|
||||
});
|
||||
}
|
||||
|
||||
async deleteGroup(groupId: string, userId: string): Promise<boolean> {
|
||||
const existing = await this.getGroup(groupId, userId);
|
||||
if (!existing) return false;
|
||||
|
||||
await this.db.transaction(async (tx) => {
|
||||
await tx.delete(agentGroupMembers).where(eq(agentGroupMembers.groupId, groupId));
|
||||
await tx.delete(agentGroups).where(eq(agentGroups.id, groupId));
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
async createJob(userId: string, data: {
|
||||
teamId: string;
|
||||
jobType: string;
|
||||
input: Record<string, unknown>;
|
||||
}) {
|
||||
const [job] = await this.db.insert(agentJobs).values({
|
||||
userId,
|
||||
teamId: data.teamId,
|
||||
jobType: data.jobType,
|
||||
status: 'queued',
|
||||
input: data.input,
|
||||
}).returning();
|
||||
return job;
|
||||
}
|
||||
}
|
||||
291
packages/team-server/src/services/analytics-service.ts
Normal file
291
packages/team-server/src/services/analytics-service.ts
Normal file
@@ -0,0 +1,291 @@
|
||||
import { eq, and, sql, count, desc, gte, lt } from 'drizzle-orm';
|
||||
import {
|
||||
teamMembers, users, tasks, agentAuditLog, agentJobs,
|
||||
teamCapabilityRequests, messages,
|
||||
} from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export interface AnalyticsResponse {
|
||||
activeUsers: { daily: number; weekly: number; monthly: number };
|
||||
tokenUsage: {
|
||||
total: number;
|
||||
byUser: Array<{ userId: string; name: string; tokens: number; cost: number }>;
|
||||
};
|
||||
topTools: Array<{ name: string; invocations: number }>;
|
||||
topCommands: Array<{ name: string; count: number }>;
|
||||
capabilityGaps: Array<{ tool: string; requestCount: number; suggestion: string }>;
|
||||
performanceTrends: {
|
||||
correctionRate: number;
|
||||
correctionTrend: number;
|
||||
avgResponseTime: number;
|
||||
};
|
||||
}
|
||||
|
||||
export class AnalyticsService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async getAnalytics(teamId: string): Promise<AnalyticsResponse> {
|
||||
const [activeUsers, tokenUsage, topTools, topCommands, capabilityGaps, performanceTrends] =
|
||||
await Promise.all([
|
||||
this.getActiveUsers(teamId),
|
||||
this.getTokenUsage(teamId),
|
||||
this.getTopTools(teamId),
|
||||
this.getTopCommands(teamId),
|
||||
this.getCapabilityGaps(teamId),
|
||||
this.getPerformanceTrends(teamId),
|
||||
]);
|
||||
|
||||
return {
|
||||
activeUsers,
|
||||
tokenUsage,
|
||||
topTools,
|
||||
topCommands,
|
||||
capabilityGaps,
|
||||
performanceTrends,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Count active users based on audit log activity within time windows.
|
||||
* Falls back to member count if no activity found.
|
||||
*/
|
||||
private async getActiveUsers(teamId: string) {
|
||||
const now = new Date();
|
||||
const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
const oneMonthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
const [dailyResult] = await this.db
|
||||
.select({ count: sql<number>`count(distinct ${agentAuditLog.userId})` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, oneDayAgo),
|
||||
));
|
||||
|
||||
const [weeklyResult] = await this.db
|
||||
.select({ count: sql<number>`count(distinct ${agentAuditLog.userId})` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
const [monthlyResult] = await this.db
|
||||
.select({ count: sql<number>`count(distinct ${agentAuditLog.userId})` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, oneMonthAgo),
|
||||
));
|
||||
|
||||
return {
|
||||
daily: Number(dailyResult?.count ?? 0),
|
||||
weekly: Number(weeklyResult?.count ?? 0),
|
||||
monthly: Number(monthlyResult?.count ?? 0),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute token usage from completed jobs.
|
||||
* Since we don't have a dedicated token tracking table, we estimate from
|
||||
* job outputs that may contain token counts, or fall back to job counts as proxy.
|
||||
*/
|
||||
private async getTokenUsage(teamId: string) {
|
||||
// Get all members for this team
|
||||
const members = await this.db
|
||||
.select({
|
||||
userId: teamMembers.userId,
|
||||
displayName: users.displayName,
|
||||
})
|
||||
.from(teamMembers)
|
||||
.innerJoin(users, eq(teamMembers.userId, users.id))
|
||||
.where(eq(teamMembers.teamId, teamId));
|
||||
|
||||
// Count completed jobs per user as a proxy for usage
|
||||
const jobCounts = await this.db
|
||||
.select({
|
||||
userId: agentJobs.userId,
|
||||
jobCount: sql<number>`count(*)`,
|
||||
})
|
||||
.from(agentJobs)
|
||||
.where(and(
|
||||
eq(agentJobs.teamId, teamId),
|
||||
eq(agentJobs.status, 'completed'),
|
||||
))
|
||||
.groupBy(agentJobs.userId);
|
||||
|
||||
const jobCountMap = new Map(jobCounts.map((j) => [j.userId, Number(j.jobCount)]));
|
||||
|
||||
// Estimate tokens: ~1000 tokens per completed job (rough proxy)
|
||||
const TOKENS_PER_JOB = 1000;
|
||||
const COST_PER_1K_TOKENS = 0.005;
|
||||
|
||||
const byUser = members.map((m) => {
|
||||
const jobs = jobCountMap.get(m.userId) ?? 0;
|
||||
const tokens = jobs * TOKENS_PER_JOB;
|
||||
return {
|
||||
userId: m.userId,
|
||||
name: m.displayName,
|
||||
tokens,
|
||||
cost: Math.round((tokens / 1000) * COST_PER_1K_TOKENS * 100) / 100,
|
||||
};
|
||||
});
|
||||
|
||||
const total = byUser.reduce((sum, u) => sum + u.tokens, 0);
|
||||
|
||||
return { total, byUser };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get top tools from audit log action types (tool invocations are logged as actions).
|
||||
*/
|
||||
private async getTopTools(teamId: string) {
|
||||
const results = await this.db
|
||||
.select({
|
||||
name: agentAuditLog.actionType,
|
||||
invocations: sql<number>`count(*)`,
|
||||
})
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
))
|
||||
.groupBy(agentAuditLog.actionType)
|
||||
.orderBy(desc(sql`count(*)`))
|
||||
.limit(10);
|
||||
|
||||
return results.map((r) => ({
|
||||
name: r.name,
|
||||
invocations: Number(r.invocations),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get top commands from audit log entries where actionType starts with 'command:'.
|
||||
* Falls back to all action types containing 'command' or starting with '/'.
|
||||
*/
|
||||
private async getTopCommands(teamId: string) {
|
||||
const results = await this.db
|
||||
.select({
|
||||
name: agentAuditLog.actionType,
|
||||
count: sql<number>`count(*)`,
|
||||
})
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
sql`${agentAuditLog.actionType} LIKE 'command:%'`,
|
||||
))
|
||||
.groupBy(agentAuditLog.actionType)
|
||||
.orderBy(desc(sql`count(*)`))
|
||||
.limit(10);
|
||||
|
||||
return results.map((r) => {
|
||||
const stripped = r.name.replace(/^command:/, '');
|
||||
return {
|
||||
name: stripped.startsWith('/') ? stripped : `/${stripped}`,
|
||||
count: Number(r.count),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Identify capability gaps from denied/pending capability requests.
|
||||
*/
|
||||
private async getCapabilityGaps(teamId: string) {
|
||||
const results = await this.db
|
||||
.select({
|
||||
tool: teamCapabilityRequests.capabilityName,
|
||||
requestCount: sql<number>`count(*)`,
|
||||
})
|
||||
.from(teamCapabilityRequests)
|
||||
.where(and(
|
||||
eq(teamCapabilityRequests.teamId, teamId),
|
||||
sql`${teamCapabilityRequests.status} IN ('pending', 'rejected')`,
|
||||
))
|
||||
.groupBy(teamCapabilityRequests.capabilityName)
|
||||
.orderBy(desc(sql`count(*)`))
|
||||
.limit(10);
|
||||
|
||||
return results.map((r) => ({
|
||||
tool: r.tool,
|
||||
requestCount: Number(r.requestCount),
|
||||
suggestion: `Install ${r.tool} connector or add to allowed tools`,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute performance trends from audit log.
|
||||
* - correctionRate: fraction of actions that were corrections/rejections
|
||||
* - correctionTrend: difference between this week and last week correction rates
|
||||
* - avgResponseTime: average time between job creation and completion (seconds)
|
||||
*/
|
||||
private async getPerformanceTrends(teamId: string) {
|
||||
const now = new Date();
|
||||
const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
const twoWeeksAgo = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// This week's correction rate
|
||||
const [thisWeekTotal] = await this.db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
const [thisWeekRejected] = await this.db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, oneWeekAgo),
|
||||
eq(agentAuditLog.approved, false),
|
||||
));
|
||||
|
||||
// Last week's correction rate
|
||||
const [lastWeekTotal] = await this.db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, twoWeeksAgo),
|
||||
lt(agentAuditLog.createdAt, oneWeekAgo),
|
||||
));
|
||||
|
||||
const [lastWeekRejected] = await this.db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
gte(agentAuditLog.createdAt, twoWeeksAgo),
|
||||
lt(agentAuditLog.createdAt, oneWeekAgo),
|
||||
eq(agentAuditLog.approved, false),
|
||||
));
|
||||
|
||||
const thisWeekRate = Number(thisWeekTotal?.count) > 0
|
||||
? Number(thisWeekRejected?.count ?? 0) / Number(thisWeekTotal.count)
|
||||
: 0;
|
||||
|
||||
const lastWeekRate = Number(lastWeekTotal?.count) > 0
|
||||
? Number(lastWeekRejected?.count ?? 0) / Number(lastWeekTotal.count)
|
||||
: 0;
|
||||
|
||||
// Average response time from completed jobs
|
||||
const [avgTime] = await this.db
|
||||
.select({
|
||||
avgSeconds: sql<number>`coalesce(avg(extract(epoch from (${agentJobs.completedAt} - ${agentJobs.createdAt}))), 0)`,
|
||||
})
|
||||
.from(agentJobs)
|
||||
.where(and(
|
||||
eq(agentJobs.teamId, teamId),
|
||||
eq(agentJobs.status, 'completed'),
|
||||
sql`${agentJobs.completedAt} IS NOT NULL`,
|
||||
));
|
||||
|
||||
return {
|
||||
correctionRate: Math.round(thisWeekRate * 100) / 100,
|
||||
correctionTrend: Math.round((thisWeekRate - lastWeekRate) * 100) / 100,
|
||||
avgResponseTime: Math.round(Number(avgTime?.avgSeconds ?? 0) * 10) / 10,
|
||||
};
|
||||
}
|
||||
}
|
||||
74
packages/team-server/src/services/audit-service.ts
Normal file
74
packages/team-server/src/services/audit-service.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { eq, and, desc, isNull } from 'drizzle-orm';
|
||||
import { agentAuditLog } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export class AuditService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async log(entry: {
|
||||
userId: string;
|
||||
teamId?: string;
|
||||
agentName: string;
|
||||
actionType: string;
|
||||
description: string;
|
||||
beforeState?: Record<string, unknown>;
|
||||
afterState?: Record<string, unknown>;
|
||||
requiresApproval?: boolean;
|
||||
}) {
|
||||
const [created] = await this.db.insert(agentAuditLog).values({
|
||||
userId: entry.userId,
|
||||
teamId: entry.teamId ?? null,
|
||||
agentName: entry.agentName,
|
||||
actionType: entry.actionType,
|
||||
description: entry.description,
|
||||
beforeState: entry.beforeState ?? null,
|
||||
afterState: entry.afterState ?? null,
|
||||
requiresApproval: entry.requiresApproval ?? false,
|
||||
}).returning();
|
||||
return created;
|
||||
}
|
||||
|
||||
async list(teamId: string, filters?: { actionType?: string; agentName?: string }) {
|
||||
const conditions = [eq(agentAuditLog.teamId, teamId)];
|
||||
if (filters?.actionType) conditions.push(eq(agentAuditLog.actionType, filters.actionType));
|
||||
if (filters?.agentName) conditions.push(eq(agentAuditLog.agentName, filters.agentName));
|
||||
|
||||
return this.db.select().from(agentAuditLog)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(agentAuditLog.createdAt))
|
||||
.limit(100);
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
const [entry] = await this.db.select().from(agentAuditLog)
|
||||
.where(eq(agentAuditLog.id, id))
|
||||
.limit(1);
|
||||
return entry ?? null;
|
||||
}
|
||||
|
||||
async approve(entryId: string, approvedBy: string) {
|
||||
const [updated] = await this.db.update(agentAuditLog)
|
||||
.set({ approved: true, approvedBy })
|
||||
.where(eq(agentAuditLog.id, entryId))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async reject(entryId: string, approvedBy: string) {
|
||||
const [updated] = await this.db.update(agentAuditLog)
|
||||
.set({ approved: false, approvedBy })
|
||||
.where(eq(agentAuditLog.id, entryId))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async getPendingApprovals(teamId: string) {
|
||||
return this.db.select().from(agentAuditLog)
|
||||
.where(and(
|
||||
eq(agentAuditLog.teamId, teamId),
|
||||
eq(agentAuditLog.requiresApproval, true),
|
||||
isNull(agentAuditLog.approved),
|
||||
))
|
||||
.orderBy(desc(agentAuditLog.createdAt));
|
||||
}
|
||||
}
|
||||
90
packages/team-server/src/services/cron-service.ts
Normal file
90
packages/team-server/src/services/cron-service.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import cronParser from 'cron-parser';
|
||||
const { parseExpression } = cronParser;
|
||||
import { cronSchedules } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import { scheduledJobTypeSchema } from '@waggle/shared';
|
||||
|
||||
export function getNextRunAt(cronExpr: string): Date {
|
||||
const interval = parseExpression(cronExpr);
|
||||
return interval.next().toDate();
|
||||
}
|
||||
|
||||
export class CronService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async create(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
data: { name: string; cronExpr: string; jobType: string; jobConfig?: Record<string, unknown> },
|
||||
) {
|
||||
// Validate cron expression by parsing it
|
||||
const nextRunAt = getNextRunAt(data.cronExpr);
|
||||
const jobType = scheduledJobTypeSchema.safeParse(data.jobType);
|
||||
if (!jobType.success) {
|
||||
throw new Error(`Unsupported scheduled job type: ${data.jobType}`);
|
||||
}
|
||||
|
||||
const [schedule] = await this.db.insert(cronSchedules).values({
|
||||
teamId,
|
||||
createdBy: userId,
|
||||
name: data.name,
|
||||
cronExpr: data.cronExpr,
|
||||
jobType: jobType.data,
|
||||
jobConfig: data.jobConfig ?? {},
|
||||
enabled: true,
|
||||
nextRunAt,
|
||||
}).returning();
|
||||
|
||||
return schedule;
|
||||
}
|
||||
|
||||
async list(teamId: string) {
|
||||
return this.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.teamId, teamId));
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
const [schedule] = await this.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.id, id));
|
||||
return schedule ?? null;
|
||||
}
|
||||
|
||||
async update(teamId: string, id: string, data: { name?: string; cronExpr?: string; enabled?: boolean; jobConfig?: Record<string, unknown> }) {
|
||||
const updates: Record<string, unknown> = {};
|
||||
|
||||
if (data.name !== undefined) updates.name = data.name;
|
||||
if (data.enabled !== undefined) updates.enabled = data.enabled;
|
||||
if (data.jobConfig !== undefined) updates.jobConfig = data.jobConfig;
|
||||
|
||||
if (data.cronExpr !== undefined) {
|
||||
updates.cronExpr = data.cronExpr;
|
||||
updates.nextRunAt = getNextRunAt(data.cronExpr);
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length === 0) return null;
|
||||
|
||||
const [updated] = await this.db.update(cronSchedules)
|
||||
.set(updates)
|
||||
.where(and(
|
||||
eq(cronSchedules.id, id),
|
||||
eq(cronSchedules.teamId, teamId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async markRun(id: string) {
|
||||
const schedule = await this.getById(id);
|
||||
if (!schedule) return null;
|
||||
|
||||
const now = new Date();
|
||||
const nextRunAt = getNextRunAt(schedule.cronExpr);
|
||||
|
||||
const [updated] = await this.db.update(cronSchedules)
|
||||
.set({ lastRunAt: now, nextRunAt })
|
||||
.where(eq(cronSchedules.id, id))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
}
|
||||
103
packages/team-server/src/services/job-service.ts
Normal file
103
packages/team-server/src/services/job-service.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { Queue } from 'bullmq';
|
||||
import { eq, desc } from 'drizzle-orm';
|
||||
import { agentJobs } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export class JobService {
|
||||
private queue: Queue;
|
||||
|
||||
constructor(private db: Db, redisUrl: string, queueName = 'waggle-jobs') {
|
||||
const url = new URL(redisUrl);
|
||||
this.queue = new Queue(queueName, {
|
||||
connection: {
|
||||
host: url.hostname,
|
||||
port: parseInt(url.port || '6379'),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async createJob(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
jobType: string,
|
||||
input: Record<string, unknown>,
|
||||
jobId?: string,
|
||||
) {
|
||||
const [created] = await this.db.insert(agentJobs).values({
|
||||
...(jobId ? { id: jobId } : {}),
|
||||
teamId,
|
||||
userId,
|
||||
jobType,
|
||||
status: 'queued',
|
||||
input,
|
||||
}).onConflictDoNothing({ target: agentJobs.id }).returning();
|
||||
|
||||
const job = created ?? (jobId ? await this.getJob(jobId) : null);
|
||||
if (!job) throw new Error('Failed to create job');
|
||||
if (job.teamId !== teamId || job.userId !== userId || job.jobType !== jobType) {
|
||||
throw new Error('Job idempotency key collision');
|
||||
}
|
||||
|
||||
await this.queue.add(job.jobType, {
|
||||
jobId: job.id,
|
||||
teamId: job.teamId,
|
||||
userId: job.userId,
|
||||
jobType: job.jobType,
|
||||
input: job.input,
|
||||
}, { jobId: job.id });
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
async getJob(jobId: string) {
|
||||
const [job] = await this.db.select().from(agentJobs).where(eq(agentJobs.id, jobId));
|
||||
return job ?? null;
|
||||
}
|
||||
|
||||
async listByTeam(teamId: string, limit = 50) {
|
||||
return this.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.teamId, teamId))
|
||||
.orderBy(desc(agentJobs.createdAt))
|
||||
.limit(Math.min(limit, 100));
|
||||
}
|
||||
|
||||
async updateJobStatus(jobId: string, status: string, output?: Record<string, unknown>) {
|
||||
const updates: Record<string, unknown> = { status };
|
||||
if (status === 'running') updates.startedAt = new Date();
|
||||
if (status === 'completed' || status === 'failed') {
|
||||
updates.completedAt = new Date();
|
||||
if (output) updates.output = output;
|
||||
}
|
||||
const [updated] = await this.db.update(agentJobs)
|
||||
.set(updates)
|
||||
.where(eq(agentJobs.id, jobId))
|
||||
.returning();
|
||||
return updated;
|
||||
}
|
||||
|
||||
async cancelJob(jobId: string) {
|
||||
// Update DB status
|
||||
const updated = await this.updateJobStatus(jobId, 'cancelled');
|
||||
|
||||
// Try to remove from BullMQ queue
|
||||
try {
|
||||
const bullJob = await this.queue.getJob(jobId);
|
||||
if (bullJob) {
|
||||
const state = await bullJob.getState();
|
||||
if (state === 'waiting' || state === 'delayed') {
|
||||
await bullJob.remove();
|
||||
} else if (state === 'active') {
|
||||
await bullJob.moveToFailed(new Error('Cancelled by user'), 'cancelled', true);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Queue removal failed — DB status is still updated
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
async close() {
|
||||
await this.queue.close();
|
||||
}
|
||||
}
|
||||
168
packages/team-server/src/services/knowledge-service.ts
Normal file
168
packages/team-server/src/services/knowledge-service.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import { eq, and, or, ilike, inArray } from 'drizzle-orm';
|
||||
import { teamEntities, teamRelations } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export interface EntityFilters {
|
||||
entityType?: string;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
export class KnowledgeService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async createEntity(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
data: {
|
||||
entityType: string;
|
||||
name: string;
|
||||
properties?: Record<string, unknown>;
|
||||
validFrom?: string;
|
||||
validTo?: string;
|
||||
},
|
||||
) {
|
||||
const values: typeof teamEntities.$inferInsert = {
|
||||
teamId,
|
||||
entityType: data.entityType,
|
||||
name: data.name,
|
||||
properties: data.properties ?? {},
|
||||
sharedBy: userId,
|
||||
};
|
||||
if (data.validFrom) values.validFrom = new Date(data.validFrom);
|
||||
if (data.validTo) values.validTo = new Date(data.validTo);
|
||||
|
||||
const [entity] = await this.db.insert(teamEntities).values(values).returning();
|
||||
return entity;
|
||||
}
|
||||
|
||||
async listEntities(teamId: string, filters?: EntityFilters) {
|
||||
const conditions = [eq(teamEntities.teamId, teamId)];
|
||||
|
||||
if (filters?.entityType) {
|
||||
conditions.push(eq(teamEntities.entityType, filters.entityType));
|
||||
}
|
||||
if (filters?.search) {
|
||||
conditions.push(ilike(teamEntities.name, `%${filters.search}%`));
|
||||
}
|
||||
|
||||
return this.db
|
||||
.select()
|
||||
.from(teamEntities)
|
||||
.where(and(...conditions));
|
||||
}
|
||||
|
||||
async getEntity(entityId: string) {
|
||||
const [entity] = await this.db
|
||||
.select()
|
||||
.from(teamEntities)
|
||||
.where(eq(teamEntities.id, entityId))
|
||||
.limit(1);
|
||||
return entity ?? null;
|
||||
}
|
||||
|
||||
async createRelation(
|
||||
teamId: string,
|
||||
data: {
|
||||
sourceId: string;
|
||||
targetId: string;
|
||||
relationType: string;
|
||||
confidence?: number;
|
||||
properties?: Record<string, unknown>;
|
||||
},
|
||||
) {
|
||||
const endpointIds = [...new Set([data.sourceId, data.targetId])];
|
||||
const ownedEndpoints = await this.db
|
||||
.select({ id: teamEntities.id })
|
||||
.from(teamEntities)
|
||||
.where(and(
|
||||
eq(teamEntities.teamId, teamId),
|
||||
inArray(teamEntities.id, endpointIds),
|
||||
));
|
||||
if (ownedEndpoints.length !== endpointIds.length) return null;
|
||||
|
||||
const [relation] = await this.db.insert(teamRelations).values({
|
||||
teamId,
|
||||
sourceId: data.sourceId,
|
||||
targetId: data.targetId,
|
||||
relationType: data.relationType,
|
||||
confidence: data.confidence ?? 1.0,
|
||||
properties: data.properties ?? {},
|
||||
}).returning();
|
||||
return relation;
|
||||
}
|
||||
|
||||
async queryGraph(
|
||||
teamId: string,
|
||||
startEntityId: string,
|
||||
depth: number = 2,
|
||||
relationTypes?: string[],
|
||||
) {
|
||||
const [startEntity] = await this.db
|
||||
.select()
|
||||
.from(teamEntities)
|
||||
.where(and(
|
||||
eq(teamEntities.id, startEntityId),
|
||||
eq(teamEntities.teamId, teamId),
|
||||
))
|
||||
.limit(1);
|
||||
if (!startEntity) return null;
|
||||
|
||||
const visited = new Set<string>([startEntityId]);
|
||||
const resultEntities: Array<typeof teamEntities.$inferSelect> = [startEntity];
|
||||
const resultRelations: Array<typeof teamRelations.$inferSelect> = [];
|
||||
|
||||
let frontier = [startEntityId];
|
||||
|
||||
for (let d = 0; d < depth && frontier.length > 0; d++) {
|
||||
// Find relations connected to frontier entities
|
||||
const rels = await this.db
|
||||
.select()
|
||||
.from(teamRelations)
|
||||
.where(
|
||||
and(
|
||||
eq(teamRelations.teamId, teamId),
|
||||
or(
|
||||
inArray(teamRelations.sourceId, frontier),
|
||||
inArray(teamRelations.targetId, frontier),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Apply relationTypes filter if provided
|
||||
const filteredRels = relationTypes
|
||||
? rels.filter((r) => relationTypes.includes(r.relationType))
|
||||
: rels;
|
||||
|
||||
const nextFrontier: string[] = [];
|
||||
for (const rel of filteredRels) {
|
||||
resultRelations.push(rel);
|
||||
for (const id of [rel.sourceId, rel.targetId]) {
|
||||
if (!visited.has(id)) {
|
||||
visited.add(id);
|
||||
nextFrontier.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (nextFrontier.length > 0) {
|
||||
const entities = await this.db
|
||||
.select()
|
||||
.from(teamEntities)
|
||||
.where(
|
||||
and(
|
||||
eq(teamEntities.teamId, teamId),
|
||||
inArray(teamEntities.id, nextFrontier),
|
||||
),
|
||||
);
|
||||
resultEntities.push(...entities);
|
||||
}
|
||||
|
||||
frontier = nextFrontier;
|
||||
}
|
||||
|
||||
return {
|
||||
entities: resultEntities,
|
||||
relations: resultRelations,
|
||||
};
|
||||
}
|
||||
}
|
||||
119
packages/team-server/src/services/message-service.ts
Normal file
119
packages/team-server/src/services/message-service.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { eq, and, desc, sql } from 'drizzle-orm';
|
||||
import { messages, teamEntities, tasks } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import type { HiveQuery, HiveQueryResult } from '@waggle/waggle-dance';
|
||||
import type Redis from 'ioredis';
|
||||
|
||||
export interface MessageFilters {
|
||||
type?: string;
|
||||
subtype?: string;
|
||||
}
|
||||
|
||||
export class MessageService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async send(
|
||||
teamId: string,
|
||||
senderId: string,
|
||||
data: {
|
||||
type: string;
|
||||
subtype: string;
|
||||
content: Record<string, unknown>;
|
||||
referenceId?: string;
|
||||
routing?: Array<{ userId: string; reason: string }>;
|
||||
},
|
||||
redis?: Redis,
|
||||
) {
|
||||
const [message] = await this.db.insert(messages).values({
|
||||
teamId,
|
||||
senderId,
|
||||
type: data.type,
|
||||
subtype: data.subtype,
|
||||
content: data.content,
|
||||
referenceId: data.referenceId ?? null,
|
||||
routing: data.routing ?? null,
|
||||
}).returning();
|
||||
|
||||
// Publish to Redis for real-time delivery
|
||||
if (redis) {
|
||||
await redis.publish(`team:${teamId}:waggle`, JSON.stringify(message));
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
async list(teamId: string, filters?: MessageFilters) {
|
||||
const conditions = [eq(messages.teamId, teamId)];
|
||||
|
||||
if (filters?.type) {
|
||||
conditions.push(eq(messages.type, filters.type));
|
||||
}
|
||||
if (filters?.subtype) {
|
||||
conditions.push(eq(messages.subtype, filters.subtype));
|
||||
}
|
||||
|
||||
return this.db
|
||||
.select()
|
||||
.from(messages)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(messages.createdAt));
|
||||
}
|
||||
|
||||
async checkHive(teamId: string, query: HiveQuery): Promise<HiveQueryResult> {
|
||||
const searchTerm = `%${query.topic}%`;
|
||||
|
||||
// Search team_entities by name or entityType matching the topic
|
||||
const entities = await this.db
|
||||
.select({
|
||||
id: teamEntities.id,
|
||||
name: teamEntities.name,
|
||||
entityType: teamEntities.entityType,
|
||||
properties: teamEntities.properties,
|
||||
})
|
||||
.from(teamEntities)
|
||||
.where(
|
||||
and(
|
||||
eq(teamEntities.teamId, teamId),
|
||||
sql`(${teamEntities.name} ILIKE ${searchTerm} OR ${teamEntities.entityType} ILIKE ${searchTerm})`,
|
||||
),
|
||||
)
|
||||
.limit(10);
|
||||
|
||||
// Search tasks by title or description matching the topic
|
||||
const relatedTasks = await this.db
|
||||
.select({
|
||||
id: tasks.id,
|
||||
title: tasks.title,
|
||||
status: tasks.status,
|
||||
createdBy: tasks.createdBy,
|
||||
})
|
||||
.from(tasks)
|
||||
.where(
|
||||
and(
|
||||
eq(tasks.teamId, teamId),
|
||||
sql`(${tasks.title} ILIKE ${searchTerm} OR ${tasks.description} ILIKE ${searchTerm})`,
|
||||
),
|
||||
)
|
||||
.limit(10);
|
||||
|
||||
// Search recent broadcast messages
|
||||
const relatedMessages = await this.db
|
||||
.select({
|
||||
id: messages.id,
|
||||
type: messages.type,
|
||||
subtype: messages.subtype,
|
||||
content: messages.content,
|
||||
})
|
||||
.from(messages)
|
||||
.where(
|
||||
and(
|
||||
eq(messages.teamId, teamId),
|
||||
eq(messages.type, 'broadcast'),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(messages.createdAt))
|
||||
.limit(10);
|
||||
|
||||
return { entities, relatedTasks, relatedMessages };
|
||||
}
|
||||
}
|
||||
102
packages/team-server/src/services/proactive-service.ts
Normal file
102
packages/team-server/src/services/proactive-service.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { eq, and, desc } from 'drizzle-orm';
|
||||
import { proactivePatterns, suggestionsLog } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import { MAX_SUGGESTIONS_PER_INTERACTION } from '@waggle/shared';
|
||||
import { BUILT_IN_PATTERNS } from '../proactive/patterns.js';
|
||||
|
||||
export class ProactiveService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async ensurePatternsSeeded() {
|
||||
const existing = await this.db.select().from(proactivePatterns);
|
||||
if (existing.length === 0) {
|
||||
for (const p of BUILT_IN_PATTERNS) {
|
||||
await this.db.insert(proactivePatterns).values({
|
||||
name: p.name,
|
||||
trigger: { condition: p.triggerCondition },
|
||||
suggestionType: p.suggestionType,
|
||||
template: p.template,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async evaluate(userId: string, jobContext: Record<string, unknown>) {
|
||||
// Check if user already has max pending suggestions
|
||||
const pending = await this.db.select().from(suggestionsLog)
|
||||
.where(and(
|
||||
eq(suggestionsLog.userId, userId),
|
||||
eq(suggestionsLog.status, 'pending'),
|
||||
));
|
||||
|
||||
if (pending.length >= MAX_SUGGESTIONS_PER_INTERACTION) return null;
|
||||
|
||||
// Get active patterns
|
||||
const patterns = await this.db.select().from(proactivePatterns)
|
||||
.where(eq(proactivePatterns.enabled, true));
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const shouldTrigger = this.matchPattern(pattern, jobContext);
|
||||
if (!shouldTrigger) continue;
|
||||
|
||||
// Check if already dismissed for this pattern
|
||||
const dismissed = await this.db.select().from(suggestionsLog)
|
||||
.where(and(
|
||||
eq(suggestionsLog.userId, userId),
|
||||
eq(suggestionsLog.patternId, pattern.id),
|
||||
eq(suggestionsLog.status, 'dismissed'),
|
||||
));
|
||||
|
||||
if (dismissed.length > 0) continue;
|
||||
|
||||
// Create suggestion
|
||||
const [suggestion] = await this.db.insert(suggestionsLog).values({
|
||||
userId,
|
||||
patternId: pattern.id,
|
||||
context: jobContext,
|
||||
status: 'pending',
|
||||
}).returning();
|
||||
|
||||
return { ...suggestion, pattern };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private matchPattern(
|
||||
pattern: { suggestionType: string },
|
||||
context: Record<string, unknown>,
|
||||
): boolean {
|
||||
const triggerType = pattern.suggestionType;
|
||||
if (triggerType === 'cron' && context.repeatCount && (context.repeatCount as number) >= 3) return true;
|
||||
if (triggerType === 'dashboard' && context.hasData) return true;
|
||||
if (triggerType === 'share' && context.relevantUsers) return true;
|
||||
if (triggerType === 'upgrade' && context.expensiveModel) return true;
|
||||
if (triggerType === 'skill' && context.manualSteps) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
async listPending(userId: string) {
|
||||
return this.db.select().from(suggestionsLog)
|
||||
.where(and(
|
||||
eq(suggestionsLog.userId, userId),
|
||||
eq(suggestionsLog.status, 'pending'),
|
||||
))
|
||||
.orderBy(desc(suggestionsLog.createdAt));
|
||||
}
|
||||
|
||||
async updateStatus(
|
||||
suggestionId: string,
|
||||
userId: string,
|
||||
status: 'accepted' | 'dismissed' | 'snoozed',
|
||||
) {
|
||||
const [updated] = await this.db.update(suggestionsLog)
|
||||
.set({ status })
|
||||
.where(and(
|
||||
eq(suggestionsLog.id, suggestionId),
|
||||
eq(suggestionsLog.userId, userId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
}
|
||||
89
packages/team-server/src/services/resource-service.ts
Normal file
89
packages/team-server/src/services/resource-service.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { teamResources } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export class ResourceService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async share(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
data: {
|
||||
resourceType: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
config: Record<string, unknown>;
|
||||
},
|
||||
) {
|
||||
const [resource] = await this.db.insert(teamResources).values({
|
||||
teamId,
|
||||
resourceType: data.resourceType,
|
||||
name: data.name,
|
||||
description: data.description ?? null,
|
||||
config: data.config,
|
||||
sharedBy: userId,
|
||||
rating: 0,
|
||||
useCount: 0,
|
||||
}).returning();
|
||||
return resource;
|
||||
}
|
||||
|
||||
async list(teamId: string, resourceType?: string) {
|
||||
const conditions = [eq(teamResources.teamId, teamId)];
|
||||
|
||||
if (resourceType) {
|
||||
conditions.push(eq(teamResources.resourceType, resourceType));
|
||||
}
|
||||
|
||||
return this.db
|
||||
.select()
|
||||
.from(teamResources)
|
||||
.where(and(...conditions));
|
||||
}
|
||||
|
||||
async rate(teamId: string, resourceId: string, rating: number) {
|
||||
const [resource] = await this.db
|
||||
.select()
|
||||
.from(teamResources)
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.limit(1);
|
||||
if (!resource) return null;
|
||||
|
||||
const newRating = resource.useCount > 0
|
||||
? (resource.rating * resource.useCount + rating) / (resource.useCount + 1)
|
||||
: rating;
|
||||
|
||||
const [updated] = await this.db.update(teamResources)
|
||||
.set({ rating: newRating })
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.returning();
|
||||
return updated;
|
||||
}
|
||||
|
||||
async incrementUseCount(teamId: string, resourceId: string) {
|
||||
const [resource] = await this.db
|
||||
.select()
|
||||
.from(teamResources)
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.limit(1);
|
||||
if (!resource) return null;
|
||||
|
||||
const [updated] = await this.db.update(teamResources)
|
||||
.set({ useCount: resource.useCount + 1 })
|
||||
.where(and(
|
||||
eq(teamResources.id, resourceId),
|
||||
eq(teamResources.teamId, teamId),
|
||||
))
|
||||
.returning();
|
||||
return updated;
|
||||
}
|
||||
}
|
||||
91
packages/team-server/src/services/task-service.ts
Normal file
91
packages/team-server/src/services/task-service.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { tasks } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export interface TaskFilters {
|
||||
status?: string;
|
||||
assignee?: string;
|
||||
priority?: string;
|
||||
}
|
||||
|
||||
export class TaskService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async create(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
data: { title: string; description?: string; priority?: string; parentTaskId?: string },
|
||||
) {
|
||||
const [task] = await this.db.insert(tasks).values({
|
||||
teamId,
|
||||
title: data.title,
|
||||
description: data.description,
|
||||
priority: data.priority ?? 'normal',
|
||||
createdBy: userId,
|
||||
parentTaskId: data.parentTaskId,
|
||||
}).returning();
|
||||
return task;
|
||||
}
|
||||
|
||||
async list(teamId: string, filters?: TaskFilters) {
|
||||
const conditions = [eq(tasks.teamId, teamId)];
|
||||
|
||||
if (filters?.status) {
|
||||
conditions.push(eq(tasks.status, filters.status));
|
||||
}
|
||||
if (filters?.assignee) {
|
||||
conditions.push(eq(tasks.assignedTo, filters.assignee));
|
||||
}
|
||||
if (filters?.priority) {
|
||||
conditions.push(eq(tasks.priority, filters.priority));
|
||||
}
|
||||
|
||||
return this.db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(...conditions));
|
||||
}
|
||||
|
||||
async get(taskId: string) {
|
||||
const [task] = await this.db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(eq(tasks.id, taskId))
|
||||
.limit(1);
|
||||
return task ?? null;
|
||||
}
|
||||
|
||||
async update(
|
||||
taskId: string,
|
||||
data: {
|
||||
title?: string;
|
||||
description?: string;
|
||||
status?: string;
|
||||
priority?: string;
|
||||
assignedTo?: string | null;
|
||||
},
|
||||
) {
|
||||
const setData: Record<string, unknown> = { updatedAt: new Date() };
|
||||
if (data.title !== undefined) setData.title = data.title;
|
||||
if (data.description !== undefined) setData.description = data.description;
|
||||
if (data.status !== undefined) setData.status = data.status;
|
||||
if (data.priority !== undefined) setData.priority = data.priority;
|
||||
if (data.assignedTo !== undefined) setData.assignedTo = data.assignedTo;
|
||||
|
||||
const [updated] = await this.db
|
||||
.update(tasks)
|
||||
.set(setData)
|
||||
.where(eq(tasks.id, taskId))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async claim(taskId: string, userId: string) {
|
||||
const [updated] = await this.db
|
||||
.update(tasks)
|
||||
.set({ assignedTo: userId, status: 'claimed', updatedAt: new Date() })
|
||||
.where(eq(tasks.id, taskId))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
}
|
||||
379
packages/team-server/src/services/team-capability-governance.ts
Normal file
379
packages/team-server/src/services/team-capability-governance.ts
Normal file
@@ -0,0 +1,379 @@
|
||||
import { eq, and, desc } from 'drizzle-orm';
|
||||
import { RISK_LEVELS, riskRank, type RiskLevel } from '@waggle/shared';
|
||||
import {
|
||||
teamCapabilityPolicies,
|
||||
teamCapabilityOverrides,
|
||||
teamCapabilityRequests,
|
||||
} from '../db/schema.js';
|
||||
import type { DbExecutor } from '../db/connection.js';
|
||||
|
||||
export interface EffectivePermissions {
|
||||
role: string;
|
||||
allowedSources: string[];
|
||||
blockedTools: string[];
|
||||
approvalThreshold: string;
|
||||
overrides: Map<string, 'approved' | 'blocked'>;
|
||||
}
|
||||
|
||||
export type PermissionResult =
|
||||
| 'allowed'
|
||||
| 'blocked'
|
||||
| 'needs_approval'
|
||||
| 'source_not_allowed';
|
||||
|
||||
/**
|
||||
* Rank a governance risk string on the canonical scale (P7/D15 A2b). The
|
||||
* governance domain adds a 'none' tier (below 'low') that the canonical set
|
||||
* doesn't have. Anything else falls back to canonical riskRank, so 'critical'
|
||||
* (rank 3) correctly outranks 'low' (0) — the previous local map omitted
|
||||
* 'critical', so `?? 0` sorted a critical risk BELOW low (a silent RBAC defect).
|
||||
*/
|
||||
function governanceRiskRank(level: string): number {
|
||||
if (level === 'none') return -1;
|
||||
return (RISK_LEVELS as readonly string[]).includes(level)
|
||||
? riskRank(level as RiskLevel)
|
||||
: -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a given risk level exceeds the threshold.
|
||||
* Threshold 'none' means nothing triggers approval.
|
||||
*/
|
||||
export function riskExceedsThreshold(risk: string, threshold: string): boolean {
|
||||
if (threshold === 'none') return false;
|
||||
return governanceRiskRank(risk) > governanceRiskRank(threshold);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve permission for a single capability against effective permissions.
|
||||
*
|
||||
* Resolution order:
|
||||
* 1. Check overrides — if override exists, return its decision immediately
|
||||
* 2. Check role policy (source allowed? tool blocked?)
|
||||
* 3. If policy allows but risk exceeds threshold → needs_approval
|
||||
* 4. Otherwise → allowed
|
||||
*/
|
||||
export function resolvePermission(
|
||||
perms: EffectivePermissions,
|
||||
capabilityName: string,
|
||||
capabilityType: string,
|
||||
risk: string = 'low',
|
||||
): PermissionResult {
|
||||
// 1. Override wins
|
||||
const override = perms.overrides.get(capabilityName);
|
||||
if (override === 'approved') return 'allowed';
|
||||
if (override === 'blocked') return 'blocked';
|
||||
|
||||
// 2. Blocked tool check
|
||||
if (perms.blockedTools.includes(capabilityName)) return 'blocked';
|
||||
|
||||
// 3. Source allowed check
|
||||
if (!perms.allowedSources.includes(capabilityType)) return 'source_not_allowed';
|
||||
|
||||
// 4. Risk threshold check
|
||||
if (riskExceedsThreshold(risk, perms.approvalThreshold)) return 'needs_approval';
|
||||
|
||||
return 'allowed';
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter a list of capabilities by permissions, returning only those allowed or needing approval.
|
||||
*/
|
||||
export function filterByPermissions(
|
||||
perms: EffectivePermissions,
|
||||
capabilities: Array<{ name: string; type: string; risk?: string }>,
|
||||
): Array<{ name: string; type: string; risk?: string; result: PermissionResult }> {
|
||||
return capabilities.map((cap) => ({
|
||||
...cap,
|
||||
result: resolvePermission(perms, cap.name, cap.type, cap.risk ?? 'low'),
|
||||
}));
|
||||
}
|
||||
|
||||
export interface DefaultPolicy {
|
||||
role: string;
|
||||
allowedSources: string[];
|
||||
blockedTools: string[];
|
||||
approvalThreshold: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the 3 default role policies for a new team.
|
||||
*/
|
||||
export function getDefaultPolicies(): DefaultPolicy[] {
|
||||
return [
|
||||
{
|
||||
role: 'owner',
|
||||
allowedSources: ['native', 'skill', 'plugin', 'mcp'],
|
||||
blockedTools: [],
|
||||
approvalThreshold: 'none',
|
||||
},
|
||||
{
|
||||
role: 'admin',
|
||||
allowedSources: ['native', 'skill', 'plugin', 'mcp'],
|
||||
blockedTools: [],
|
||||
approvalThreshold: 'none',
|
||||
},
|
||||
{
|
||||
role: 'member',
|
||||
allowedSources: ['native', 'skill'],
|
||||
blockedTools: ['bash', 'delete_skill'],
|
||||
approvalThreshold: 'medium',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export class TeamCapabilityGovernance {
|
||||
constructor(private db: DbExecutor) {}
|
||||
|
||||
/**
|
||||
* Get effective permissions for a role in a team, including overrides.
|
||||
*/
|
||||
async getEffectivePermissions(teamId: string, role: string): Promise<EffectivePermissions> {
|
||||
// Get role policy
|
||||
const [policy] = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityPolicies)
|
||||
.where(and(
|
||||
eq(teamCapabilityPolicies.teamId, teamId),
|
||||
eq(teamCapabilityPolicies.role, role),
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
// Get overrides for this team
|
||||
const overrideRows = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityOverrides)
|
||||
.where(eq(teamCapabilityOverrides.teamId, teamId));
|
||||
|
||||
const overrides = new Map<string, 'approved' | 'blocked'>();
|
||||
for (const row of overrideRows) {
|
||||
overrides.set(row.capabilityName, row.decision as 'approved' | 'blocked');
|
||||
}
|
||||
|
||||
if (!policy) {
|
||||
// Fallback: no policy found, restrictive defaults
|
||||
return {
|
||||
role,
|
||||
allowedSources: [],
|
||||
blockedTools: [],
|
||||
approvalThreshold: 'none',
|
||||
overrides,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
role,
|
||||
allowedSources: policy.allowedSources as string[],
|
||||
blockedTools: policy.blockedTools as string[],
|
||||
approvalThreshold: policy.approvalThreshold,
|
||||
overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async listPolicies(teamId: string) {
|
||||
return this.db
|
||||
.select()
|
||||
.from(teamCapabilityPolicies)
|
||||
.where(eq(teamCapabilityPolicies.teamId, teamId));
|
||||
}
|
||||
|
||||
async upsertPolicy(
|
||||
teamId: string,
|
||||
role: string,
|
||||
data: {
|
||||
allowedSources?: string[];
|
||||
blockedTools?: string[];
|
||||
approvalThreshold?: string;
|
||||
},
|
||||
updatedBy: string,
|
||||
) {
|
||||
const [existing] = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityPolicies)
|
||||
.where(and(
|
||||
eq(teamCapabilityPolicies.teamId, teamId),
|
||||
eq(teamCapabilityPolicies.role, role),
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
if (existing) {
|
||||
const [updated] = await this.db
|
||||
.update(teamCapabilityPolicies)
|
||||
.set({
|
||||
...(data.allowedSources !== undefined && { allowedSources: data.allowedSources }),
|
||||
...(data.blockedTools !== undefined && { blockedTools: data.blockedTools }),
|
||||
...(data.approvalThreshold !== undefined && { approvalThreshold: data.approvalThreshold }),
|
||||
updatedBy,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(teamCapabilityPolicies.id, existing.id))
|
||||
.returning();
|
||||
return updated;
|
||||
}
|
||||
|
||||
const defaults = getDefaultPolicies().find((p) => p.role === role);
|
||||
const [created] = await this.db
|
||||
.insert(teamCapabilityPolicies)
|
||||
.values({
|
||||
teamId,
|
||||
role,
|
||||
allowedSources: data.allowedSources ?? defaults?.allowedSources ?? [],
|
||||
blockedTools: data.blockedTools ?? defaults?.blockedTools ?? [],
|
||||
approvalThreshold: data.approvalThreshold ?? defaults?.approvalThreshold ?? 'none',
|
||||
updatedBy,
|
||||
})
|
||||
.returning();
|
||||
return created;
|
||||
}
|
||||
|
||||
async seedDefaultPolicies(teamId: string, seedBy: string) {
|
||||
const defaults = getDefaultPolicies();
|
||||
const results = [];
|
||||
for (const policy of defaults) {
|
||||
const [row] = await this.db
|
||||
.insert(teamCapabilityPolicies)
|
||||
.values({
|
||||
teamId,
|
||||
role: policy.role,
|
||||
allowedSources: policy.allowedSources,
|
||||
blockedTools: policy.blockedTools,
|
||||
approvalThreshold: policy.approvalThreshold,
|
||||
updatedBy: seedBy,
|
||||
})
|
||||
.returning();
|
||||
results.push(row);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// --- Overrides ---
|
||||
|
||||
async listOverrides(teamId: string) {
|
||||
return this.db
|
||||
.select()
|
||||
.from(teamCapabilityOverrides)
|
||||
.where(eq(teamCapabilityOverrides.teamId, teamId))
|
||||
.orderBy(desc(teamCapabilityOverrides.createdAt));
|
||||
}
|
||||
|
||||
async createOverride(
|
||||
teamId: string,
|
||||
data: {
|
||||
capabilityName: string;
|
||||
capabilityType: string;
|
||||
decision: 'approved' | 'blocked';
|
||||
reason?: string;
|
||||
},
|
||||
decidedBy: string,
|
||||
) {
|
||||
const [row] = await this.db
|
||||
.insert(teamCapabilityOverrides)
|
||||
.values({
|
||||
teamId,
|
||||
capabilityName: data.capabilityName,
|
||||
capabilityType: data.capabilityType,
|
||||
decision: data.decision,
|
||||
reason: data.reason ?? '',
|
||||
decidedBy,
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
async deleteOverride(teamId: string, overrideId: string) {
|
||||
const [deleted] = await this.db
|
||||
.delete(teamCapabilityOverrides)
|
||||
.where(and(
|
||||
eq(teamCapabilityOverrides.teamId, teamId),
|
||||
eq(teamCapabilityOverrides.id, overrideId),
|
||||
))
|
||||
.returning();
|
||||
return deleted ?? null;
|
||||
}
|
||||
|
||||
// --- Requests ---
|
||||
|
||||
async listRequests(teamId: string, status?: string) {
|
||||
const conditions = [eq(teamCapabilityRequests.teamId, teamId)];
|
||||
if (status) {
|
||||
conditions.push(eq(teamCapabilityRequests.status, status));
|
||||
}
|
||||
return this.db
|
||||
.select()
|
||||
.from(teamCapabilityRequests)
|
||||
.where(and(...conditions))
|
||||
.orderBy(desc(teamCapabilityRequests.createdAt));
|
||||
}
|
||||
|
||||
async submitRequest(
|
||||
teamId: string,
|
||||
requestedBy: string,
|
||||
data: {
|
||||
capabilityName: string;
|
||||
capabilityType: string;
|
||||
justification: string;
|
||||
},
|
||||
): Promise<{ duplicate: true } | { duplicate: false; request: typeof teamCapabilityRequests.$inferSelect }> {
|
||||
// Duplicate check: pending request for same capability by same user
|
||||
const [existing] = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityRequests)
|
||||
.where(and(
|
||||
eq(teamCapabilityRequests.teamId, teamId),
|
||||
eq(teamCapabilityRequests.requestedBy, requestedBy),
|
||||
eq(teamCapabilityRequests.capabilityName, data.capabilityName),
|
||||
eq(teamCapabilityRequests.status, 'pending'),
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
if (existing) return { duplicate: true };
|
||||
|
||||
const [request] = await this.db
|
||||
.insert(teamCapabilityRequests)
|
||||
.values({
|
||||
teamId,
|
||||
requestedBy,
|
||||
capabilityName: data.capabilityName,
|
||||
capabilityType: data.capabilityType,
|
||||
justification: data.justification,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return { duplicate: false, request };
|
||||
}
|
||||
|
||||
async getRequest(teamId: string, requestId: string) {
|
||||
const [row] = await this.db
|
||||
.select()
|
||||
.from(teamCapabilityRequests)
|
||||
.where(and(
|
||||
eq(teamCapabilityRequests.teamId, teamId),
|
||||
eq(teamCapabilityRequests.id, requestId),
|
||||
))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
async decideRequest(
|
||||
teamId: string,
|
||||
requestId: string,
|
||||
decidedBy: string,
|
||||
decision: 'approved' | 'rejected',
|
||||
reason?: string,
|
||||
) {
|
||||
const [updated] = await this.db
|
||||
.update(teamCapabilityRequests)
|
||||
.set({
|
||||
status: decision,
|
||||
decidedBy,
|
||||
decisionReason: reason ?? null,
|
||||
decidedAt: new Date(),
|
||||
})
|
||||
.where(and(
|
||||
eq(teamCapabilityRequests.teamId, teamId),
|
||||
eq(teamCapabilityRequests.id, requestId),
|
||||
))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
}
|
||||
139
packages/team-server/src/services/team-service.ts
Normal file
139
packages/team-server/src/services/team-service.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import { eq, and, sql } from 'drizzle-orm';
|
||||
import { teams, teamMembers, users } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
import { TeamCapabilityGovernance } from './team-capability-governance.js';
|
||||
|
||||
export class TeamService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async create(ownerId: string, data: { name: string; slug: string }) {
|
||||
return this.db.transaction(async (tx) => {
|
||||
const [team] = await tx.insert(teams).values({
|
||||
name: data.name,
|
||||
slug: data.slug,
|
||||
ownerId,
|
||||
}).returning();
|
||||
|
||||
await tx.insert(teamMembers).values({
|
||||
teamId: team.id,
|
||||
userId: ownerId,
|
||||
role: 'owner',
|
||||
});
|
||||
|
||||
// Seed default capability policies
|
||||
const governance = new TeamCapabilityGovernance(tx);
|
||||
await governance.seedDefaultPolicies(team.id, ownerId);
|
||||
|
||||
return team;
|
||||
});
|
||||
}
|
||||
|
||||
async getBySlug(slug: string) {
|
||||
const [team] = await this.db.select().from(teams).where(eq(teams.slug, slug)).limit(1);
|
||||
return team ?? null;
|
||||
}
|
||||
|
||||
async listForUser(userId: string) {
|
||||
const rows = await this.db
|
||||
.select({
|
||||
id: teams.id,
|
||||
name: teams.name,
|
||||
slug: teams.slug,
|
||||
ownerId: teams.ownerId,
|
||||
createdAt: teams.createdAt,
|
||||
role: teamMembers.role,
|
||||
})
|
||||
.from(teamMembers)
|
||||
.innerJoin(teams, eq(teamMembers.teamId, teams.id))
|
||||
.where(eq(teamMembers.userId, userId));
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
async update(teamId: string, data: { name: string }) {
|
||||
const [updated] = await this.db
|
||||
.update(teams)
|
||||
.set({ name: data.name })
|
||||
.where(eq(teams.id, teamId))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async addMember(teamId: string, userId: string, role: 'admin' | 'member') {
|
||||
const [member] = await this.db.insert(teamMembers).values({
|
||||
teamId,
|
||||
userId,
|
||||
role,
|
||||
}).returning();
|
||||
return member;
|
||||
}
|
||||
|
||||
async removeMember(teamId: string, userId: string) {
|
||||
// Prevent removing the owner
|
||||
const membership = await this.getMembership(teamId, userId);
|
||||
if (!membership) return false;
|
||||
if (membership.role === 'owner') {
|
||||
throw new Error('Cannot remove the team owner');
|
||||
}
|
||||
|
||||
await this.db
|
||||
.delete(teamMembers)
|
||||
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)));
|
||||
return true;
|
||||
}
|
||||
|
||||
async updateMember(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
data: { role?: 'admin' | 'member'; roleDescription?: string; interests?: string[] },
|
||||
) {
|
||||
if (data.role !== undefined) {
|
||||
const membership = await this.getMembership(teamId, userId);
|
||||
if (!membership) return null;
|
||||
if (membership.role === 'owner') {
|
||||
throw new Error('Cannot change the team owner role');
|
||||
}
|
||||
}
|
||||
|
||||
const setData: Record<string, unknown> = {};
|
||||
if (data.role !== undefined) setData.role = data.role;
|
||||
if (data.roleDescription !== undefined) setData.roleDescription = data.roleDescription;
|
||||
if (data.interests !== undefined) setData.interests = data.interests;
|
||||
|
||||
if (Object.keys(setData).length === 0) return null;
|
||||
|
||||
const [updated] = await this.db
|
||||
.update(teamMembers)
|
||||
.set(setData)
|
||||
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)))
|
||||
.returning();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async getMembership(teamId: string, userId: string) {
|
||||
const [membership] = await this.db
|
||||
.select()
|
||||
.from(teamMembers)
|
||||
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)))
|
||||
.limit(1);
|
||||
return membership ?? null;
|
||||
}
|
||||
|
||||
async getMembers(teamId: string) {
|
||||
const rows = await this.db
|
||||
.select({
|
||||
userId: teamMembers.userId,
|
||||
role: teamMembers.role,
|
||||
roleDescription: teamMembers.roleDescription,
|
||||
interests: teamMembers.interests,
|
||||
joinedAt: teamMembers.joinedAt,
|
||||
displayName: users.displayName,
|
||||
email: users.email,
|
||||
avatarUrl: users.avatarUrl,
|
||||
})
|
||||
.from(teamMembers)
|
||||
.innerJoin(users, eq(teamMembers.userId, users.id))
|
||||
.where(eq(teamMembers.teamId, teamId));
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
59
packages/team-server/src/services/user-service.ts
Normal file
59
packages/team-server/src/services/user-service.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { users } from '../db/schema.js';
|
||||
import type { Db } from '../db/connection.js';
|
||||
|
||||
export interface ClerkUserData {
|
||||
clerkId: string;
|
||||
displayName: string;
|
||||
email: string;
|
||||
avatarUrl?: string | null;
|
||||
}
|
||||
|
||||
export class UserService {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
async getByClerkId(clerkId: string) {
|
||||
const [user] = await this.db.select().from(users).where(eq(users.clerkId, clerkId)).limit(1);
|
||||
return user ?? null;
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
const [user] = await this.db.select().from(users).where(eq(users.id, id)).limit(1);
|
||||
return user ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or update a user from Clerk JWT claims.
|
||||
* Used by auth plugin for auto-provisioning on first auth,
|
||||
* and by webhook for ongoing sync.
|
||||
*/
|
||||
async upsertFromClerk(data: ClerkUserData) {
|
||||
const existing = await this.getByClerkId(data.clerkId);
|
||||
|
||||
if (existing) {
|
||||
// Update display name / email / avatar if changed
|
||||
await this.db.update(users)
|
||||
.set({
|
||||
displayName: data.displayName,
|
||||
email: data.email,
|
||||
avatarUrl: data.avatarUrl ?? null,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(users.clerkId, data.clerkId));
|
||||
// Return fresh copy
|
||||
return (await this.getByClerkId(data.clerkId))!;
|
||||
}
|
||||
|
||||
// Insert new user
|
||||
const [created] = await this.db.insert(users)
|
||||
.values({
|
||||
clerkId: data.clerkId,
|
||||
displayName: data.displayName,
|
||||
email: data.email,
|
||||
avatarUrl: data.avatarUrl ?? null,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return created;
|
||||
}
|
||||
}
|
||||
46
packages/team-server/src/ws/connection-manager.ts
Normal file
46
packages/team-server/src/ws/connection-manager.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import type { WebSocket } from 'ws';
|
||||
import type { WsServerEvent } from '@waggle/shared';
|
||||
|
||||
export class ConnectionManager {
|
||||
private connections = new Map<string, Map<string, WebSocket>>(); // teamId -> userId -> ws
|
||||
|
||||
add(teamId: string, userId: string, ws: WebSocket): void {
|
||||
if (!this.connections.has(teamId)) {
|
||||
this.connections.set(teamId, new Map());
|
||||
}
|
||||
this.connections.get(teamId)!.set(userId, ws);
|
||||
}
|
||||
|
||||
remove(teamId: string, userId: string): void {
|
||||
this.connections.get(teamId)?.delete(userId);
|
||||
if (this.connections.get(teamId)?.size === 0) {
|
||||
this.connections.delete(teamId);
|
||||
}
|
||||
}
|
||||
|
||||
broadcast(teamId: string, event: WsServerEvent, excludeUserId?: string): void {
|
||||
const team = this.connections.get(teamId);
|
||||
if (!team) return;
|
||||
const data = JSON.stringify(event);
|
||||
for (const [userId, ws] of team) {
|
||||
if (userId !== excludeUserId && ws.readyState === ws.OPEN) {
|
||||
ws.send(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sendTo(teamId: string, userId: string, event: WsServerEvent): void {
|
||||
const ws = this.connections.get(teamId)?.get(userId);
|
||||
if (ws && ws.readyState === ws.OPEN) {
|
||||
ws.send(JSON.stringify(event));
|
||||
}
|
||||
}
|
||||
|
||||
getConnectedUsers(teamId: string): string[] {
|
||||
return Array.from(this.connections.get(teamId)?.keys() ?? []);
|
||||
}
|
||||
|
||||
getTeamCount(): number {
|
||||
return this.connections.size;
|
||||
}
|
||||
}
|
||||
264
packages/team-server/src/ws/gateway.ts
Normal file
264
packages/team-server/src/ws/gateway.ts
Normal file
@@ -0,0 +1,264 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { WsClientEvent, WsServerEvent } from '@waggle/shared';
|
||||
import { createClerkClient, verifyToken } from '@clerk/fastify';
|
||||
import { ConnectionManager } from './connection-manager.js';
|
||||
import { teams, messages, users } from '../db/schema.js';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { TeamService } from '../services/team-service.js';
|
||||
|
||||
export const connectionManager = new ConnectionManager();
|
||||
|
||||
/**
|
||||
* Validate that a string looks like a JWT (3 dot-separated base64url segments).
|
||||
* This is a structural check, not a cryptographic verification.
|
||||
*/
|
||||
function isJwtStructure(token: string): boolean {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return false;
|
||||
// Each segment should be non-empty and valid base64url
|
||||
const base64urlRegex = /^[A-Za-z0-9_-]+$/;
|
||||
return parts.every((part) => part.length > 0 && base64urlRegex.test(part));
|
||||
}
|
||||
|
||||
// Overridable verifier for testing — allows tests to swap in a mock
|
||||
export type WsTokenVerifier = (token: string) => Promise<{ sub: string }>;
|
||||
let _wsTokenVerifier: WsTokenVerifier | null = null;
|
||||
|
||||
/** Override the WS token verifier (for testing only) */
|
||||
export function setWsTokenVerifier(verifier: WsTokenVerifier | null): void {
|
||||
_wsTokenVerifier = verifier;
|
||||
}
|
||||
|
||||
export async function wsGateway(fastify: FastifyInstance) {
|
||||
const teamService = new TeamService(fastify.db);
|
||||
|
||||
// Create Clerk client for JWT verification if secret key is available
|
||||
const clerkSecretKey = fastify.config.clerkSecretKey;
|
||||
const clerk = clerkSecretKey
|
||||
? createClerkClient({ secretKey: clerkSecretKey })
|
||||
: null;
|
||||
|
||||
// Hard fail in production if no JWT verification path is configured. Without
|
||||
// either a Clerk client or a test override, the gateway would have no way to
|
||||
// cryptographically verify incoming tokens — the previous fallback (unsigned
|
||||
// JWT decode) is forgeable. NODE_ENV !== 'production' (dev / desktop /
|
||||
// testing) is allowed to start without the key, but connections without a
|
||||
// verifier are rejected at request time below.
|
||||
if (!clerk && !_wsTokenVerifier && process.env.NODE_ENV === 'production') {
|
||||
throw new Error(
|
||||
'[ws-gateway] CLERK_SECRET_KEY required in production. WebSocket gateway ' +
|
||||
'refuses to start without cryptographic JWT verification configured. ' +
|
||||
'Set CLERK_SECRET_KEY in environment or settings.json.',
|
||||
);
|
||||
}
|
||||
if (!clerk && !_wsTokenVerifier) {
|
||||
fastify.log.warn(
|
||||
'[ws-gateway] CLERK_SECRET_KEY absent; WebSocket connections will be rejected. ' +
|
||||
'This is dev/desktop mode — set CLERK_SECRET_KEY for cloud/SaaS deployments.',
|
||||
);
|
||||
}
|
||||
|
||||
fastify.get('/ws', { websocket: true }, (socket, request) => {
|
||||
let userId: string | null = null;
|
||||
let teamId: string | null = null;
|
||||
|
||||
socket.on('message', async (raw: Buffer | string) => {
|
||||
try {
|
||||
const event = JSON.parse(raw.toString()) as WsClientEvent;
|
||||
|
||||
switch (event.type) {
|
||||
case 'authenticate': {
|
||||
const token = event.token;
|
||||
|
||||
// Reject tokens that are not JWTs (plain userIds, random strings)
|
||||
if (!isJwtStructure(token)) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
message: 'Invalid token: must be a valid JWT',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let sub: string;
|
||||
|
||||
if (_wsTokenVerifier) {
|
||||
// Test override path
|
||||
const result = await _wsTokenVerifier(token);
|
||||
sub = result.sub;
|
||||
} else if (clerk) {
|
||||
// Production path: full Clerk JWT verification. `clerk` is only
|
||||
// non-null when clerkSecretKey is set, so the secretKey below is
|
||||
// always present here.
|
||||
const payload = await verifyToken(token, { secretKey: clerkSecretKey });
|
||||
sub = payload.sub;
|
||||
} else {
|
||||
// No verifier available — reject. The startup check above ensures
|
||||
// production cannot reach this branch. Dev/desktop without a key
|
||||
// hits this and is rejected at connection time (no silent decode).
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
message: 'Authentication unavailable: server has no JWT verifier configured',
|
||||
}),
|
||||
);
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// Look up internal user by Clerk ID
|
||||
const [user] = await fastify.db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.clerkId, sub));
|
||||
|
||||
if (!user) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
message: 'User not found',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (teamId && userId) {
|
||||
connectionManager.remove(teamId, userId);
|
||||
}
|
||||
teamId = null;
|
||||
userId = user.id;
|
||||
socket.send(JSON.stringify({ type: 'authenticated', userId }));
|
||||
} catch {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
message: 'Token verification failed',
|
||||
}),
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'join_team': {
|
||||
if (!userId) {
|
||||
socket.send(JSON.stringify({ type: 'error', message: 'Not authenticated' }));
|
||||
return;
|
||||
}
|
||||
|
||||
const [team] = await fastify.db
|
||||
.select()
|
||||
.from(teams)
|
||||
.where(eq(teams.slug, event.teamSlug));
|
||||
|
||||
if (!team) {
|
||||
socket.send(JSON.stringify({ type: 'error', message: 'Team not found' }));
|
||||
return;
|
||||
}
|
||||
|
||||
const membership = await teamService.getMembership(team.id, userId);
|
||||
if (!membership) {
|
||||
socket.send(JSON.stringify({ type: 'error', message: 'Team not found' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Leave previous team if any
|
||||
if (teamId && userId) {
|
||||
connectionManager.remove(teamId, userId);
|
||||
}
|
||||
|
||||
teamId = team.id;
|
||||
connectionManager.add(teamId, userId, socket);
|
||||
|
||||
// Subscribe to Redis channel for this team
|
||||
const channel = `team:${teamId}:waggle`;
|
||||
try {
|
||||
const existingChannels = await fastify.redisSub.call('PUBSUB', 'CHANNELS', channel) as string[];
|
||||
// Only subscribe if not already subscribed (redisSub is shared)
|
||||
if (!existingChannels || !existingChannels.includes(channel)) {
|
||||
await fastify.redisSub.subscribe(channel);
|
||||
}
|
||||
} catch {
|
||||
// Redis subscribe failure is non-fatal — real-time updates won't work
|
||||
// but join should still succeed
|
||||
}
|
||||
|
||||
socket.send(JSON.stringify({ type: 'joined_team', teamSlug: event.teamSlug }));
|
||||
break;
|
||||
}
|
||||
|
||||
case 'send_message': {
|
||||
if (!userId || !teamId) {
|
||||
socket.send(JSON.stringify({ type: 'error', message: 'Not in a team' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Persist message
|
||||
const [msg] = await fastify.db
|
||||
.insert(messages)
|
||||
.values({
|
||||
teamId,
|
||||
senderId: userId,
|
||||
type: event.messageType,
|
||||
subtype: event.subtype,
|
||||
content: event.content,
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Publish to Redis for cross-process delivery
|
||||
await fastify.redis.publish(
|
||||
`team:${teamId}:waggle`,
|
||||
JSON.stringify(msg),
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
socket.send(JSON.stringify({ type: 'error', message: 'Invalid message' }));
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
if (teamId && userId) {
|
||||
connectionManager.remove(teamId, userId);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Forward Redis pub/sub messages to WebSocket clients
|
||||
fastify.redisSub.on('message', (channel: string, data: string) => {
|
||||
const match = channel.match(/^team:(.+):waggle$/);
|
||||
if (!match) return;
|
||||
const tId = match[1];
|
||||
try {
|
||||
const event: WsServerEvent = { type: 'waggle_message', message: JSON.parse(data) };
|
||||
connectionManager.broadcast(tId, event);
|
||||
} catch {
|
||||
// Ignore malformed messages from Redis
|
||||
}
|
||||
});
|
||||
|
||||
// Subscribe to job progress channels via pattern matching
|
||||
await fastify.redisSub.psubscribe('job:*:progress');
|
||||
|
||||
// Forward job progress events to WebSocket clients
|
||||
fastify.redisSub.on('pmessage', (_pattern: string, channel: string, data: string) => {
|
||||
const jobMatch = channel.match(/^job:(.+):progress$/);
|
||||
if (!jobMatch) return;
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
const event: WsServerEvent = {
|
||||
type: 'job_progress',
|
||||
jobId: jobMatch[1],
|
||||
progress: parsed,
|
||||
};
|
||||
// Route to the team that owns this job
|
||||
if (parsed.teamId) {
|
||||
connectionManager.broadcast(parsed.teamId, event);
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed messages from Redis
|
||||
}
|
||||
});
|
||||
}
|
||||
234
packages/team-server/tests/audit.test.ts
Normal file
234
packages/team-server/tests/audit.test.ts
Normal file
@@ -0,0 +1,234 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { buildServer } from '../src/index.js';
|
||||
import { users, teams, teamMembers, agentAuditLog } from '../src/db/schema.js';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { AuditService } from '../src/services/audit-service.js';
|
||||
|
||||
describe('Audit & Traceability (Task 3.23)', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let ownerId: string;
|
||||
let memberId: string;
|
||||
let teamSlug: string;
|
||||
let teamId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up leftover test data
|
||||
await server.db.execute(sql`DELETE FROM agent_audit_log WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'audit_%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'audit-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'audit-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'audit-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'audit-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'audit-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'audit_%'`);
|
||||
|
||||
// Create test users
|
||||
const [owner] = await server.db.insert(users).values({
|
||||
clerkId: 'audit_owner',
|
||||
displayName: 'Audit Owner',
|
||||
email: 'audit_owner@test.com',
|
||||
}).returning();
|
||||
ownerId = owner.id;
|
||||
|
||||
const [member] = await server.db.insert(users).values({
|
||||
clerkId: 'audit_member',
|
||||
displayName: 'Audit Member',
|
||||
email: 'audit_member@test.com',
|
||||
}).returning();
|
||||
memberId = member.id;
|
||||
|
||||
// Create team
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'Audit Test Team',
|
||||
slug: 'audit-test',
|
||||
ownerId,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
teamSlug = team.slug;
|
||||
|
||||
await server.db.insert(teamMembers).values([
|
||||
{ teamId, userId: ownerId, role: 'owner' },
|
||||
{ teamId, userId: memberId, role: 'member' },
|
||||
]);
|
||||
|
||||
// Override auth handler for testing
|
||||
server._authHandler.fn = async function (request: FastifyRequest, reply: FastifyReply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM agent_audit_log WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'audit_%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'audit-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'audit-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'audit-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'audit-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'audit-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'audit_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('logs an audit entry via AuditService', async () => {
|
||||
const auditService = new AuditService(server.db);
|
||||
const entry = await auditService.log({
|
||||
userId: ownerId,
|
||||
teamId,
|
||||
agentName: 'memory-weaver',
|
||||
actionType: 'consolidation',
|
||||
description: 'Consolidated 5 memory fragments into 1 summary',
|
||||
beforeState: { fragmentCount: 5 },
|
||||
afterState: { summaryId: 'abc123' },
|
||||
});
|
||||
|
||||
expect(entry).toBeDefined();
|
||||
expect(entry.agentName).toBe('memory-weaver');
|
||||
expect(entry.actionType).toBe('consolidation');
|
||||
expect(entry.description).toBe('Consolidated 5 memory fragments into 1 summary');
|
||||
expect(entry.beforeState).toEqual({ fragmentCount: 5 });
|
||||
expect(entry.afterState).toEqual({ summaryId: 'abc123' });
|
||||
expect(entry.requiresApproval).toBe(false);
|
||||
expect(entry.approved).toBeNull();
|
||||
});
|
||||
|
||||
it('lists audit entries for team', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/admin/teams/${teamSlug}/audit`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.length).toBeGreaterThanOrEqual(1);
|
||||
expect(body[0].agentName).toBe('memory-weaver');
|
||||
});
|
||||
|
||||
it('filters by actionType', async () => {
|
||||
// Add another entry with different actionType
|
||||
const auditService = new AuditService(server.db);
|
||||
await auditService.log({
|
||||
userId: ownerId,
|
||||
teamId,
|
||||
agentName: 'scout',
|
||||
actionType: 'discovery',
|
||||
description: 'Found new relevant paper',
|
||||
});
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/admin/teams/${teamSlug}/audit?actionType=discovery`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.length).toBe(1);
|
||||
expect(body[0].actionType).toBe('discovery');
|
||||
expect(body[0].agentName).toBe('scout');
|
||||
});
|
||||
|
||||
it('approves a pending entry', async () => {
|
||||
const auditService = new AuditService(server.db);
|
||||
const pending = await auditService.log({
|
||||
userId: ownerId,
|
||||
teamId,
|
||||
agentName: 'hive-mind',
|
||||
actionType: 'share_knowledge',
|
||||
description: 'Share pricing analysis with team graph',
|
||||
requiresApproval: true,
|
||||
});
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/admin/teams/${teamSlug}/audit/${pending.id}/approve`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.approved).toBe(true);
|
||||
expect(body.approvedBy).toBe(ownerId);
|
||||
});
|
||||
|
||||
it('rejects a pending entry', async () => {
|
||||
const auditService = new AuditService(server.db);
|
||||
const pending = await auditService.log({
|
||||
userId: ownerId,
|
||||
teamId,
|
||||
agentName: 'subconscious',
|
||||
actionType: 'auto_task',
|
||||
description: 'Create follow-up task from meeting notes',
|
||||
requiresApproval: true,
|
||||
});
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/admin/teams/${teamSlug}/audit/${pending.id}/reject`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.approved).toBe(false);
|
||||
expect(body.approvedBy).toBe(ownerId);
|
||||
});
|
||||
|
||||
it('only team admins can access audit endpoints (non-admin gets 403)', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/admin/teams/${teamSlug}/audit`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.error).toBe('Admin access required');
|
||||
});
|
||||
|
||||
it('returns 404 for non-existent audit entry on approve', async () => {
|
||||
const fakeId = '00000000-0000-0000-0000-000000000000';
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/admin/teams/${teamSlug}/audit/${fakeId}/approve`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('lists pending approvals', async () => {
|
||||
const auditService = new AuditService(server.db);
|
||||
// Create a new pending entry
|
||||
await auditService.log({
|
||||
userId: ownerId,
|
||||
teamId,
|
||||
agentName: 'hive-mind',
|
||||
actionType: 'bulk_share',
|
||||
description: 'Share 10 entities with team',
|
||||
requiresApproval: true,
|
||||
});
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/admin/teams/${teamSlug}/audit/pending`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
// All returned entries should require approval and have null approved
|
||||
for (const entry of body) {
|
||||
expect(entry.requiresApproval).toBe(true);
|
||||
expect(entry.approved).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
167
packages/team-server/tests/auth.test.ts
Normal file
167
packages/team-server/tests/auth.test.ts
Normal file
@@ -0,0 +1,167 @@
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { describe, it, expect, afterAll, beforeAll } from 'vitest';
|
||||
import { buildServer } from '../src/index.js';
|
||||
import { users } from '../src/db/schema.js';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { UserService } from '../src/services/user-service.js';
|
||||
|
||||
const SIGNING_KEY = Buffer.from('waggle-clerk-auth-integration-test-secret');
|
||||
const SIGNING_SECRET = `whsec_${SIGNING_KEY.toString('base64')}`;
|
||||
|
||||
function signedHeaders(payload: object) {
|
||||
const id = 'msg_waggle_clerk_auth_integration';
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
const signature = createHmac('sha256', SIGNING_KEY)
|
||||
.update(`${id}.${timestamp}.${JSON.stringify(payload)}`)
|
||||
.digest('base64');
|
||||
|
||||
return {
|
||||
'svix-id': id,
|
||||
'svix-timestamp': String(timestamp),
|
||||
'svix-signature': `v1,${signature}`,
|
||||
};
|
||||
}
|
||||
|
||||
describe('Clerk webhook', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let originalSigningSecret: string | undefined;
|
||||
|
||||
beforeAll(async () => {
|
||||
originalSigningSecret = process.env.CLERK_WEBHOOK_SIGNING_SECRET;
|
||||
process.env.CLERK_WEBHOOK_SIGNING_SECRET = SIGNING_SECRET;
|
||||
server = await buildServer();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'test_%'`);
|
||||
await server.close();
|
||||
if (originalSigningSecret === undefined) {
|
||||
delete process.env.CLERK_WEBHOOK_SIGNING_SECRET;
|
||||
} else {
|
||||
process.env.CLERK_WEBHOOK_SIGNING_SECRET = originalSigningSecret;
|
||||
}
|
||||
});
|
||||
|
||||
it('creates user on user.created webhook', async () => {
|
||||
const payload = {
|
||||
type: 'user.created',
|
||||
data: {
|
||||
id: 'test_clerk_001',
|
||||
first_name: 'Marko',
|
||||
last_name: 'Markovic',
|
||||
email_addresses: [{ email_address: 'marko@test.com' }],
|
||||
image_url: 'https://example.com/avatar.jpg',
|
||||
},
|
||||
};
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
headers: signedHeaders(payload),
|
||||
payload,
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const [user] = await server.db.select().from(users).where(sql`clerk_id = 'test_clerk_001'`);
|
||||
expect(user).toBeDefined();
|
||||
expect(user.displayName).toBe('Marko Markovic');
|
||||
expect(user.email).toBe('marko@test.com');
|
||||
});
|
||||
|
||||
it('updates user on user.updated webhook', async () => {
|
||||
const payload = {
|
||||
type: 'user.updated',
|
||||
data: {
|
||||
id: 'test_clerk_001',
|
||||
first_name: 'Marko',
|
||||
last_name: 'Updated',
|
||||
email_addresses: [{ email_address: 'marko@test.com' }],
|
||||
image_url: null,
|
||||
},
|
||||
};
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
headers: signedHeaders(payload),
|
||||
payload,
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const [user] = await server.db.select().from(users).where(sql`clerk_id = 'test_clerk_001'`);
|
||||
expect(user.displayName).toBe('Marko Updated');
|
||||
});
|
||||
|
||||
it('deletes user on user.deleted webhook', async () => {
|
||||
const payload = {
|
||||
type: 'user.deleted',
|
||||
data: {
|
||||
id: 'test_clerk_001',
|
||||
},
|
||||
};
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
headers: signedHeaders(payload),
|
||||
payload,
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
const result = await server.db.select().from(users).where(sql`clerk_id = 'test_clerk_001'`);
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UserService.upsertFromClerk', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let userService: UserService;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
userService = new UserService(server.db);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'test_upsert_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('creates a new user when clerkId does not exist', async () => {
|
||||
const user = await userService.upsertFromClerk({
|
||||
clerkId: 'test_upsert_new',
|
||||
displayName: 'New User',
|
||||
email: 'new@test.com',
|
||||
avatarUrl: 'https://example.com/avatar.jpg',
|
||||
});
|
||||
|
||||
expect(user).toBeDefined();
|
||||
expect(user.clerkId).toBe('test_upsert_new');
|
||||
expect(user.displayName).toBe('New User');
|
||||
expect(user.email).toBe('new@test.com');
|
||||
expect(user.id).toBeTruthy();
|
||||
});
|
||||
|
||||
it('updates existing user when clerkId already exists', async () => {
|
||||
// First create
|
||||
await userService.upsertFromClerk({
|
||||
clerkId: 'test_upsert_existing',
|
||||
displayName: 'Original Name',
|
||||
email: 'original@test.com',
|
||||
});
|
||||
|
||||
// Then upsert with updated data
|
||||
const updated = await userService.upsertFromClerk({
|
||||
clerkId: 'test_upsert_existing',
|
||||
displayName: 'Updated Name',
|
||||
email: 'updated@test.com',
|
||||
avatarUrl: 'https://new-avatar.com/pic.jpg',
|
||||
});
|
||||
|
||||
expect(updated.displayName).toBe('Updated Name');
|
||||
expect(updated.email).toBe('updated@test.com');
|
||||
expect(updated.avatarUrl).toBe('https://new-avatar.com/pic.jpg');
|
||||
});
|
||||
|
||||
it('getByClerkId returns null for unknown clerkId', async () => {
|
||||
const result = await userService.getByClerkId('nonexistent_clerk_id');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
53
packages/team-server/tests/config.test.ts
Normal file
53
packages/team-server/tests/config.test.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
|
||||
// Guards the CORS_ORIGIN fail-closed contract on the TEAM server config
|
||||
// (packages/server/src/config.ts). The team server (index.ts) is the only
|
||||
// consumer of config.corsOrigin; the desktop/local server uses the separate
|
||||
// hardcoded ALLOWED_ORIGINS allowlist (local/cors-config.ts) and is unaffected.
|
||||
describe('loadConfig — CORS_ORIGIN', () => {
|
||||
const SAVED = {
|
||||
CORS_ORIGIN: process.env.CORS_ORIGIN,
|
||||
NODE_ENV: process.env.NODE_ENV,
|
||||
DATABASE_URL: process.env.DATABASE_URL,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.CORS_ORIGIN;
|
||||
delete process.env.NODE_ENV;
|
||||
// DATABASE_URL also fails closed in production; set it so we isolate the
|
||||
// CORS_ORIGIN behavior under test.
|
||||
process.env.DATABASE_URL = 'postgres://localhost:5434/waggle';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const [k, v] of Object.entries(SAVED)) {
|
||||
if (v === undefined) delete process.env[k];
|
||||
else process.env[k] = v;
|
||||
}
|
||||
});
|
||||
|
||||
it('defaults to the localhost dev origin when CORS_ORIGIN is unset (non-production)', () => {
|
||||
expect(loadConfig().corsOrigin).toEqual(['http://localhost:5173']);
|
||||
});
|
||||
|
||||
it('FAILS CLOSED in production when CORS_ORIGIN is unset (no silent localhost fallback)', () => {
|
||||
process.env.NODE_ENV = 'production';
|
||||
expect(() => loadConfig()).toThrow(/CORS_ORIGIN.*required in production/);
|
||||
});
|
||||
|
||||
it('parses a comma-separated list, trimming whitespace and dropping empties', () => {
|
||||
process.env.NODE_ENV = 'production';
|
||||
process.env.CORS_ORIGIN = 'https://app.example.com, https://admin.example.com ,';
|
||||
expect(loadConfig().corsOrigin).toEqual([
|
||||
'https://app.example.com',
|
||||
'https://admin.example.com',
|
||||
]);
|
||||
});
|
||||
|
||||
it('accepts a single explicit origin in production', () => {
|
||||
process.env.NODE_ENV = 'production';
|
||||
process.env.CORS_ORIGIN = 'https://app.example.com';
|
||||
expect(loadConfig().corsOrigin).toEqual(['https://app.example.com']);
|
||||
});
|
||||
});
|
||||
616
packages/team-server/tests/cron.test.ts
Normal file
616
packages/team-server/tests/cron.test.ts
Normal file
@@ -0,0 +1,616 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { Queue } from 'bullmq';
|
||||
import { buildServer } from '../src/index.js';
|
||||
import { users, teams, teamMembers, cronSchedules, agentJobs } from '../src/db/schema.js';
|
||||
import { sql, eq } from 'drizzle-orm';
|
||||
import { CronRunner } from '../src/scheduler/cron-runner.js';
|
||||
import { CronService } from '../src/services/cron-service.js';
|
||||
import { JobService } from '../src/services/job-service.js';
|
||||
|
||||
async function waitFor(
|
||||
predicate: () => Promise<boolean>,
|
||||
message: string,
|
||||
timeoutMs = 1_000,
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
if (await predicate()) return;
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
describe('Cron Scheduler (Task 3.16)', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let ownerId: string;
|
||||
let memberId: string;
|
||||
let attackerId: string;
|
||||
let teamSlug: string;
|
||||
let teamId: string;
|
||||
let attackerTeamSlug: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up leftover test data
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM cron_schedules WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'crontest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'crontest_%'`);
|
||||
|
||||
// Create test users
|
||||
const [owner] = await server.db.insert(users).values({
|
||||
clerkId: 'crontest_owner',
|
||||
displayName: 'Cron Owner',
|
||||
email: 'crontest_owner@test.com',
|
||||
}).returning();
|
||||
ownerId = owner.id;
|
||||
|
||||
const [member] = await server.db.insert(users).values({
|
||||
clerkId: 'crontest_member',
|
||||
displayName: 'Cron Member',
|
||||
email: 'crontest_member@test.com',
|
||||
}).returning();
|
||||
memberId = member.id;
|
||||
|
||||
const [attacker] = await server.db.insert(users).values({
|
||||
clerkId: 'crontest_attacker',
|
||||
displayName: 'Cron Attacker',
|
||||
email: 'crontest_attacker@test.com',
|
||||
}).returning();
|
||||
attackerId = attacker.id;
|
||||
|
||||
// Create team
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'Cron Test Team',
|
||||
slug: 'crontest-cron',
|
||||
ownerId,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
teamSlug = team.slug;
|
||||
|
||||
const [attackerTeam] = await server.db.insert(teams).values({
|
||||
name: 'Cron Attacker Team',
|
||||
slug: 'crontest-attacker',
|
||||
ownerId: attackerId,
|
||||
}).returning();
|
||||
attackerTeamSlug = attackerTeam.slug;
|
||||
|
||||
await server.db.insert(teamMembers).values([
|
||||
{ teamId, userId: ownerId, role: 'owner' },
|
||||
{ teamId, userId: memberId, role: 'member' },
|
||||
{ teamId: attackerTeam.id, userId: attackerId, role: 'owner' },
|
||||
]);
|
||||
|
||||
// Override auth handler for testing
|
||||
server._authHandler.fn = async function (request: FastifyRequest, reply: FastifyReply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM cron_schedules WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'crontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'crontest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'crontest_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('creates a cron schedule with computed next_run_at', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/cron`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
name: 'Daily Report',
|
||||
cronExpr: '0 9 * * *',
|
||||
jobType: 'task',
|
||||
jobConfig: { prompt: 'Generate daily report' },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.name).toBe('Daily Report');
|
||||
expect(body.cronExpr).toBe('0 9 * * *');
|
||||
expect(body.jobType).toBe('task');
|
||||
expect(body.enabled).toBe(true);
|
||||
expect(body.nextRunAt).toBeTruthy();
|
||||
expect(new Date(body.nextRunAt).getTime()).toBeGreaterThan(Date.now());
|
||||
expect(body.lastRunAt).toBeNull();
|
||||
});
|
||||
|
||||
it('lists schedules for team', async () => {
|
||||
// Create another schedule
|
||||
await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/cron`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: {
|
||||
name: 'Hourly Check',
|
||||
cronExpr: '0 * * * *',
|
||||
jobType: 'chat',
|
||||
},
|
||||
});
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/cron`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('returns the same not-found response for missing and foreign-team schedule ids without mutation', async () => {
|
||||
const createRes = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/cron`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
name: 'Victim Schedule',
|
||||
cronExpr: '15 * * * *',
|
||||
jobType: 'task',
|
||||
},
|
||||
});
|
||||
const schedule = JSON.parse(createRes.body);
|
||||
|
||||
const foreignRes = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${attackerTeamSlug}/cron/${schedule.id}`,
|
||||
headers: { 'x-test-user-id': attackerId },
|
||||
payload: { name: 'Hijacked Schedule', enabled: false },
|
||||
});
|
||||
const missingRes = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${attackerTeamSlug}/cron/00000000-0000-4000-8000-000000000001`,
|
||||
headers: { 'x-test-user-id': attackerId },
|
||||
payload: { enabled: false },
|
||||
});
|
||||
|
||||
expect(foreignRes.statusCode).toBe(404);
|
||||
expect(foreignRes.json()).toEqual({ error: 'Schedule not found' });
|
||||
expect(missingRes.statusCode).toBe(404);
|
||||
expect(missingRes.json()).toEqual(foreignRes.json());
|
||||
|
||||
const [persisted] = await server.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.id, schedule.id));
|
||||
expect(persisted.name).toBe('Victim Schedule');
|
||||
expect(persisted.enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('disables a schedule via PATCH', async () => {
|
||||
// Create a schedule to disable
|
||||
const createRes = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/cron`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
name: 'To Disable',
|
||||
cronExpr: '*/30 * * * *',
|
||||
jobType: 'task',
|
||||
},
|
||||
});
|
||||
const schedule = JSON.parse(createRes.body);
|
||||
expect(schedule.enabled).toBe(true);
|
||||
|
||||
const patchRes = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${teamSlug}/cron/${schedule.id}`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { enabled: false },
|
||||
});
|
||||
|
||||
expect(patchRes.statusCode).toBe(200);
|
||||
const updated = JSON.parse(patchRes.body);
|
||||
expect(updated.enabled).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['cron', 'shell'])('rejects unsupported scheduled job type %s before persistence', async (jobType) => {
|
||||
const name = `Unsupported ${jobType}`;
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/cron`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
name,
|
||||
cronExpr: '0 4 * * *',
|
||||
jobType,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
const schedules = await server.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.teamId, teamId));
|
||||
expect(schedules.some(schedule => schedule.name === name)).toBe(false);
|
||||
});
|
||||
|
||||
it('CronService refuses unsupported job types outside route validation', async () => {
|
||||
const cronService = new CronService(server.db);
|
||||
|
||||
await expect(cronService.create(teamId, ownerId, {
|
||||
name: 'Direct Unsafe Schedule',
|
||||
cronExpr: '0 5 * * *',
|
||||
jobType: 'shell',
|
||||
})).rejects.toThrow('Unsupported scheduled job type: shell');
|
||||
|
||||
const schedules = await server.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.teamId, teamId));
|
||||
expect(schedules.some(schedule => schedule.name === 'Direct Unsafe Schedule')).toBe(false);
|
||||
});
|
||||
|
||||
it('CronRunner.tick() picks up due schedule and queues job', async () => {
|
||||
// Snapshot job count before tick
|
||||
const jobsBefore = await server.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.teamId, teamId));
|
||||
const beforeCount = jobsBefore.length;
|
||||
|
||||
// Create a schedule with next_run_at in the past so it's immediately due
|
||||
const pastDate = new Date(Date.now() - 60_000);
|
||||
await server.db.insert(cronSchedules).values({
|
||||
teamId,
|
||||
createdBy: ownerId,
|
||||
name: 'Due Now',
|
||||
cronExpr: '* * * * *', // every minute
|
||||
jobType: 'task',
|
||||
jobConfig: { prompt: 'Cron runner test' },
|
||||
enabled: true,
|
||||
nextRunAt: pastDate,
|
||||
}).returning();
|
||||
|
||||
const runner = new CronRunner(server.db, server.jobService);
|
||||
const count = await runner.tick();
|
||||
|
||||
expect(count).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Verify our specific job was created
|
||||
const jobsAfter = await server.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.teamId, teamId));
|
||||
const cronJob = jobsAfter.find(j => (j.input as { prompt?: string }).prompt === 'Cron runner test');
|
||||
expect(cronJob).toBeTruthy();
|
||||
expect(cronJob!.jobType).toBe('task');
|
||||
expect(cronJob!.status).toBe('queued');
|
||||
expect(jobsAfter.length).toBeGreaterThan(beforeCount);
|
||||
});
|
||||
|
||||
it('updates last_run_at and next_run_at after tick', async () => {
|
||||
// Create a due schedule
|
||||
const pastDate = new Date(Date.now() - 120_000);
|
||||
const [schedule] = await server.db.insert(cronSchedules).values({
|
||||
teamId,
|
||||
createdBy: ownerId,
|
||||
name: 'Check After Tick',
|
||||
cronExpr: '*/5 * * * *', // every 5 minutes
|
||||
jobType: 'chat',
|
||||
jobConfig: {},
|
||||
enabled: true,
|
||||
nextRunAt: pastDate,
|
||||
}).returning();
|
||||
|
||||
const runner = new CronRunner(server.db, server.jobService);
|
||||
await runner.tick();
|
||||
|
||||
// Re-read the schedule
|
||||
const [updated] = await server.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.id, schedule.id));
|
||||
|
||||
expect(updated.lastRunAt).toBeTruthy();
|
||||
expect(new Date(updated.lastRunAt!).getTime()).toBeGreaterThan(pastDate.getTime());
|
||||
expect(updated.nextRunAt).toBeTruthy();
|
||||
expect(new Date(updated.nextRunAt!).getTime()).toBeGreaterThan(Date.now());
|
||||
});
|
||||
|
||||
it('runs due schedules through the Fastify lifecycle without a manual tick', async () => {
|
||||
const lifecycleConfig = { port: 0 };
|
||||
const lifecycleServer = await buildServer(lifecycleConfig);
|
||||
const marker = `lifecycle-${Date.now()}`;
|
||||
let scheduleId: string | undefined;
|
||||
|
||||
try {
|
||||
const [schedule] = await lifecycleServer.db.insert(cronSchedules).values({
|
||||
teamId,
|
||||
createdBy: ownerId,
|
||||
name: 'Lifecycle Due Schedule',
|
||||
cronExpr: '* * * * *',
|
||||
jobType: 'task',
|
||||
jobConfig: { marker, prompt: 'Lifecycle cron test' },
|
||||
enabled: true,
|
||||
nextRunAt: new Date(Date.now() - 60_000),
|
||||
}).returning();
|
||||
scheduleId = schedule.id;
|
||||
expect(schedule.lastRunAt).toBeNull();
|
||||
|
||||
await lifecycleServer.ready();
|
||||
await waitFor(async () => {
|
||||
const [persisted] = await lifecycleServer.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.id, schedule.id));
|
||||
return persisted?.lastRunAt !== null;
|
||||
}, 'Fastify lifecycle did not advance the due cron schedule');
|
||||
|
||||
const [advanced] = await lifecycleServer.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.id, schedule.id));
|
||||
expect(advanced.nextRunAt?.getTime()).toBeGreaterThan(Date.now());
|
||||
|
||||
const jobs = await lifecycleServer.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.teamId, teamId));
|
||||
expect(jobs.some(job => (job.input as { marker?: string }).marker === marker)).toBe(true);
|
||||
} finally {
|
||||
const jobs = await lifecycleServer.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.teamId, teamId));
|
||||
for (const job of jobs.filter(item => (item.input as { marker?: string }).marker === marker)) {
|
||||
await lifecycleServer.jobService.cancelJob(job.id);
|
||||
}
|
||||
if (scheduleId) {
|
||||
await lifecycleServer.db.delete(cronSchedules)
|
||||
.where(eq(cronSchedules.id, scheduleId));
|
||||
}
|
||||
await lifecycleServer.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('skips a legacy invalid cron expression before queueing and continues later schedules', async () => {
|
||||
const pastDate = new Date(Date.now() - 60_000);
|
||||
const invalidMarker = `invalid-cron-${Date.now()}`;
|
||||
const validMarker = `valid-after-invalid-${Date.now()}`;
|
||||
const [invalidSchedule] = await server.db.insert(cronSchedules).values({
|
||||
teamId,
|
||||
createdBy: ownerId,
|
||||
name: 'Legacy Invalid Cron',
|
||||
cronExpr: 'not a cron expression',
|
||||
jobType: 'task',
|
||||
jobConfig: { marker: invalidMarker },
|
||||
enabled: true,
|
||||
nextRunAt: pastDate,
|
||||
}).returning();
|
||||
const [validSchedule] = await server.db.insert(cronSchedules).values({
|
||||
teamId,
|
||||
createdBy: ownerId,
|
||||
name: 'Valid After Invalid Cron',
|
||||
cronExpr: '* * * * *',
|
||||
jobType: 'task',
|
||||
jobConfig: { marker: validMarker },
|
||||
enabled: true,
|
||||
nextRunAt: pastDate,
|
||||
}).returning();
|
||||
const errors: unknown[] = [];
|
||||
const runner = new CronRunner(server.db, server.jobService, error => errors.push(error));
|
||||
let validJob: typeof agentJobs.$inferSelect | undefined;
|
||||
|
||||
try {
|
||||
await expect(runner.tick()).resolves.toBe(1);
|
||||
const jobs = await server.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.teamId, teamId));
|
||||
expect(jobs.some(job => (job.input as { marker?: string }).marker === invalidMarker)).toBe(false);
|
||||
validJob = jobs.find(job => (job.input as { marker?: string }).marker === validMarker);
|
||||
expect(validJob?.status).toBe('queued');
|
||||
expect(errors).toHaveLength(1);
|
||||
|
||||
const [persistedInvalid] = await server.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.id, invalidSchedule.id));
|
||||
expect(persistedInvalid.lastRunAt).toBeNull();
|
||||
expect(persistedInvalid.nextRunAt?.getTime()).toBe(pastDate.getTime());
|
||||
} finally {
|
||||
if (validJob) await server.jobService.cancelJob(validJob.id);
|
||||
await server.db.delete(cronSchedules).where(eq(cronSchedules.id, invalidSchedule.id));
|
||||
await server.db.delete(cronSchedules).where(eq(cronSchedules.id, validSchedule.id));
|
||||
}
|
||||
});
|
||||
|
||||
it('deduplicates one due occurrence across concurrent runners', async () => {
|
||||
const marker = `concurrent-occurrence-${Date.now()}`;
|
||||
const [schedule] = await server.db.insert(cronSchedules).values({
|
||||
teamId,
|
||||
createdBy: ownerId,
|
||||
name: 'Concurrent Occurrence',
|
||||
cronExpr: '* * * * *',
|
||||
jobType: 'task',
|
||||
jobConfig: { marker },
|
||||
enabled: true,
|
||||
nextRunAt: new Date(Date.now() - 60_000),
|
||||
}).returning();
|
||||
|
||||
const originalCreate = server.jobService.createJob.bind(server.jobService);
|
||||
let arrivals = 0;
|
||||
let release!: () => void;
|
||||
const bothSelected = new Promise<void>(resolve => { release = resolve; });
|
||||
const createSpy = vi.spyOn(server.jobService, 'createJob').mockImplementation(async (...args) => {
|
||||
arrivals++;
|
||||
if (arrivals === 2) release();
|
||||
await bothSelected;
|
||||
return originalCreate(...args);
|
||||
});
|
||||
let jobs: Array<typeof agentJobs.$inferSelect> = [];
|
||||
|
||||
try {
|
||||
const first = new CronRunner(server.db, server.jobService);
|
||||
const second = new CronRunner(server.db, server.jobService);
|
||||
const counts = await Promise.all([first.tick(), second.tick()]);
|
||||
|
||||
jobs = (await server.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.teamId, teamId)))
|
||||
.filter(job => (job.input as { marker?: string }).marker === marker);
|
||||
expect(jobs).toHaveLength(1);
|
||||
expect(counts[0] + counts[1]).toBe(1);
|
||||
} finally {
|
||||
createSpy.mockRestore();
|
||||
for (const job of jobs) await server.jobService.cancelJob(job.id);
|
||||
await server.db.delete(cronSchedules).where(eq(cronSchedules.id, schedule.id));
|
||||
}
|
||||
});
|
||||
|
||||
it('reuses the same occurrence job after a post-enqueue schedule-update failure', async () => {
|
||||
const marker = `retry-occurrence-${Date.now()}`;
|
||||
const [schedule] = await server.db.insert(cronSchedules).values({
|
||||
teamId,
|
||||
createdBy: ownerId,
|
||||
name: 'Retry Occurrence',
|
||||
cronExpr: '* * * * *',
|
||||
jobType: 'task',
|
||||
jobConfig: { marker },
|
||||
enabled: true,
|
||||
nextRunAt: new Date(Date.now() - 60_000),
|
||||
}).returning();
|
||||
const errors: unknown[] = [];
|
||||
const runner = new CronRunner(server.db, server.jobService, error => errors.push(error));
|
||||
const updateSpy = vi.spyOn(server.db, 'update').mockImplementationOnce(() => {
|
||||
throw new Error('simulated schedule update failure');
|
||||
});
|
||||
let jobs: Array<typeof agentJobs.$inferSelect> = [];
|
||||
|
||||
try {
|
||||
try {
|
||||
expect(await runner.tick()).toBe(0);
|
||||
expect(errors).toHaveLength(1);
|
||||
} finally {
|
||||
updateSpy.mockRestore();
|
||||
}
|
||||
|
||||
expect(await runner.tick()).toBe(1);
|
||||
jobs = (await server.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.teamId, teamId)))
|
||||
.filter(job => (job.input as { marker?: string }).marker === marker);
|
||||
expect(jobs).toHaveLength(1);
|
||||
} finally {
|
||||
for (const job of jobs) await server.jobService.cancelJob(job.id);
|
||||
await server.db.delete(cronSchedules).where(eq(cronSchedules.id, schedule.id));
|
||||
}
|
||||
});
|
||||
|
||||
it('queues the persisted canonical payload when an occurrence retry input differs', async () => {
|
||||
const queueName = `cron-canonical-${Date.now()}`;
|
||||
const redisUrl = new URL(process.env.REDIS_URL ?? 'redis://localhost:6381');
|
||||
const jobService = new JobService(server.db, redisUrl.href, queueName);
|
||||
const queue = new Queue(queueName, {
|
||||
connection: {
|
||||
host: redisUrl.hostname,
|
||||
port: parseInt(redisUrl.port || '6379', 10),
|
||||
},
|
||||
});
|
||||
const jobId = randomUUID();
|
||||
|
||||
try {
|
||||
await jobService.createJob(teamId, ownerId, 'task', { marker: 'canonical' }, jobId);
|
||||
const firstQueueJob = await queue.getJob(jobId);
|
||||
expect(firstQueueJob).toBeTruthy();
|
||||
await firstQueueJob!.remove();
|
||||
|
||||
await jobService.createJob(teamId, ownerId, 'task', { marker: 'conflicting-retry' }, jobId);
|
||||
const [persisted] = await server.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.id, jobId));
|
||||
const retriedQueueJob = await queue.getJob(jobId);
|
||||
|
||||
expect(persisted.input).toEqual({ marker: 'canonical' });
|
||||
expect(retriedQueueJob?.data.input).toEqual(persisted.input);
|
||||
} finally {
|
||||
const queued = await queue.getJob(jobId);
|
||||
if (queued) await queued.remove();
|
||||
await server.db.delete(agentJobs).where(eq(agentJobs.id, jobId));
|
||||
await queue.close();
|
||||
await jobService.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('skips an unsafe legacy schedule while queueing an allowed due schedule', async () => {
|
||||
const pastDate = new Date(Date.now() - 60_000);
|
||||
const [unsafeSchedule, validSchedule] = await server.db.insert(cronSchedules).values([
|
||||
{
|
||||
teamId,
|
||||
createdBy: ownerId,
|
||||
name: 'Legacy Recursive Cron',
|
||||
cronExpr: '* * * * *',
|
||||
jobType: 'cron',
|
||||
jobConfig: { marker: 'blocked-recursive-cron' },
|
||||
enabled: true,
|
||||
nextRunAt: pastDate,
|
||||
},
|
||||
{
|
||||
teamId,
|
||||
createdBy: ownerId,
|
||||
name: 'Allowed Due Chat',
|
||||
cronExpr: '* * * * *',
|
||||
jobType: 'chat',
|
||||
jobConfig: { marker: 'allowed-due-chat', message: 'Scheduled read-only check' },
|
||||
enabled: true,
|
||||
nextRunAt: pastDate,
|
||||
},
|
||||
]).returning();
|
||||
|
||||
const runner = new CronRunner(server.db, server.jobService);
|
||||
let unsafeJob: typeof agentJobs.$inferSelect | undefined;
|
||||
let validJob: typeof agentJobs.$inferSelect | undefined;
|
||||
|
||||
try {
|
||||
const count = await runner.tick();
|
||||
const jobs = await server.db.select().from(agentJobs)
|
||||
.where(eq(agentJobs.teamId, teamId));
|
||||
unsafeJob = jobs.find(job => (job.input as { marker?: string }).marker === 'blocked-recursive-cron');
|
||||
validJob = jobs.find(job => (job.input as { marker?: string }).marker === 'allowed-due-chat');
|
||||
|
||||
expect(count).toBe(1);
|
||||
expect(unsafeJob).toBeUndefined();
|
||||
expect(validJob?.jobType).toBe('chat');
|
||||
|
||||
const [persistedUnsafe] = await server.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.id, unsafeSchedule.id));
|
||||
const [persistedValid] = await server.db.select().from(cronSchedules)
|
||||
.where(eq(cronSchedules.id, validSchedule.id));
|
||||
expect(persistedUnsafe.lastRunAt).toBeNull();
|
||||
expect(persistedUnsafe.nextRunAt?.getTime()).toBe(pastDate.getTime());
|
||||
expect(persistedValid.lastRunAt).toBeTruthy();
|
||||
expect(persistedValid.nextRunAt!.getTime()).toBeGreaterThan(Date.now());
|
||||
} finally {
|
||||
if (unsafeJob) await server.jobService.cancelJob(unsafeJob.id);
|
||||
if (validJob) await server.jobService.cancelJob(validJob.id);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects invalid cron expression', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/cron`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
name: 'Bad Cron',
|
||||
cronExpr: 'not a cron',
|
||||
jobType: 'task',
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('non-member gets 403', async () => {
|
||||
// Create an outsider
|
||||
const [outsider] = await server.db.insert(users).values({
|
||||
clerkId: 'crontest_outsider',
|
||||
displayName: 'Cron Outsider',
|
||||
email: 'crontest_outsider@test.com',
|
||||
}).returning();
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/cron`,
|
||||
headers: { 'x-test-user-id': outsider.id },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
});
|
||||
170
packages/team-server/tests/daemons/hive-mind.test.ts
Normal file
170
packages/team-server/tests/daemons/hive-mind.test.ts
Normal file
@@ -0,0 +1,170 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import { users, teams, teamMembers, teamResources, agentJobs, tasks, messages } from '../../src/db/schema.js';
|
||||
import { sql, eq } from 'drizzle-orm';
|
||||
import { HiveMindAgent } from '../../src/daemons/hive-mind.js';
|
||||
|
||||
describe('Hive Mind Agent (Task 3.20)', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let ownerId: string;
|
||||
let memberId: string;
|
||||
let teamId: string;
|
||||
let hiveMind: HiveMindAgent;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up leftover test data
|
||||
await server.db.execute(sql`DELETE FROM messages WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM tasks WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_resources WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'hivetest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'hive_%'`);
|
||||
|
||||
// Create test users
|
||||
const [owner] = await server.db.insert(users).values({
|
||||
clerkId: 'hive_owner',
|
||||
displayName: 'Hive Owner',
|
||||
email: 'hive_owner@test.com',
|
||||
}).returning();
|
||||
ownerId = owner.id;
|
||||
|
||||
const [member] = await server.db.insert(users).values({
|
||||
clerkId: 'hive_member',
|
||||
displayName: 'Hive Member',
|
||||
email: 'hive_member@test.com',
|
||||
}).returning();
|
||||
memberId = member.id;
|
||||
|
||||
// Create team
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'Hive Test Team',
|
||||
slug: 'hivetest-team',
|
||||
ownerId,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
|
||||
await server.db.insert(teamMembers).values([
|
||||
{ teamId, userId: ownerId, role: 'owner' },
|
||||
{ teamId, userId: memberId, role: 'member' },
|
||||
]);
|
||||
|
||||
// Seed data: completed jobs
|
||||
await server.db.insert(agentJobs).values(
|
||||
Array.from({ length: 5 }, (_, i) => ({
|
||||
teamId,
|
||||
userId: ownerId,
|
||||
jobType: 'chat',
|
||||
status: 'completed',
|
||||
input: { prompt: `job ${i}` },
|
||||
completedAt: new Date(),
|
||||
})),
|
||||
);
|
||||
|
||||
// Seed data: tasks with similar titles by different users (duplicate work)
|
||||
await server.db.insert(tasks).values([
|
||||
{ teamId, title: 'Setup CI/CD pipeline for backend', status: 'done', createdBy: ownerId },
|
||||
{ teamId, title: 'Setup CI/CD pipeline for frontend', status: 'done', createdBy: memberId },
|
||||
{ teamId, title: 'Write unit tests', status: 'done', createdBy: ownerId },
|
||||
]);
|
||||
|
||||
// Seed data: team resources with ratings
|
||||
await server.db.insert(teamResources).values([
|
||||
{
|
||||
teamId,
|
||||
resourceType: 'prompt_template',
|
||||
name: 'Best Code Review Prompt',
|
||||
description: 'A highly rated code review template',
|
||||
config: {},
|
||||
sharedBy: ownerId,
|
||||
rating: 4.5,
|
||||
},
|
||||
{
|
||||
teamId,
|
||||
resourceType: 'skill',
|
||||
name: 'Low Rated Skill',
|
||||
description: 'Not very useful',
|
||||
config: {},
|
||||
sharedBy: memberId,
|
||||
rating: 1.0,
|
||||
},
|
||||
]);
|
||||
|
||||
hiveMind = new HiveMindAgent(server.db);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM messages WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM tasks WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_resources WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'hivetest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'hivetest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'hive_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('generates weekly digest with metrics', async () => {
|
||||
const { digest, messageId } = await hiveMind.generateWeeklyDigest(teamId);
|
||||
|
||||
expect(digest).toBeTruthy();
|
||||
expect(digest.metrics.jobsCompleted).toBe(5);
|
||||
expect(digest.metrics.tasksCompleted).toBe(3);
|
||||
expect(digest.metrics.resourcesShared).toBe(2);
|
||||
expect(digest.period.from).toBeInstanceOf(Date);
|
||||
expect(digest.period.to).toBeInstanceOf(Date);
|
||||
expect(messageId).toBeTruthy();
|
||||
});
|
||||
|
||||
it('detects duplicate work across team members', async () => {
|
||||
const { digest } = await hiveMind.generateWeeklyDigest(teamId);
|
||||
|
||||
// "Setup CI/CD pipeline" tasks by different users should be detected
|
||||
expect(digest.duplicateWork.length).toBeGreaterThan(0);
|
||||
const duplicate = digest.duplicateWork[0];
|
||||
expect(duplicate.users.length).toBe(2);
|
||||
expect(duplicate.titles.length).toBe(2);
|
||||
});
|
||||
|
||||
it('identifies best practices from high-rated resources', async () => {
|
||||
const { digest } = await hiveMind.generateWeeklyDigest(teamId);
|
||||
|
||||
// Only the high-rated resource (4.5 >= 3.0) should appear
|
||||
expect(digest.bestPractices.length).toBe(1);
|
||||
expect(digest.bestPractices[0].name).toBe('Best Code Review Prompt');
|
||||
expect(digest.bestPractices[0].rating).toBe(4.5);
|
||||
});
|
||||
|
||||
it('generates recommendations based on findings', async () => {
|
||||
const { digest } = await hiveMind.generateWeeklyDigest(teamId);
|
||||
|
||||
// Should have duplicate work recommendation
|
||||
expect(digest.recommendations.length).toBeGreaterThan(0);
|
||||
expect(digest.recommendations.some(r => r.includes('duplicate'))).toBe(true);
|
||||
// Should have best practices recommendation
|
||||
expect(digest.recommendations.some(r => r.includes('highly-rated'))).toBe(true);
|
||||
});
|
||||
|
||||
it('broadcasts digest as a waggle dance message', async () => {
|
||||
const { messageId } = await hiveMind.generateWeeklyDigest(teamId);
|
||||
|
||||
// Verify the message was stored
|
||||
const [msg] = await server.db.select().from(messages)
|
||||
.where(eq(messages.id, messageId));
|
||||
|
||||
expect(msg).toBeTruthy();
|
||||
expect(msg.type).toBe('broadcast');
|
||||
expect(msg.subtype).toBe('discovery');
|
||||
const digestContent = msg.content as { type: string; digest: unknown };
|
||||
expect(digestContent.type).toBe('weekly_digest');
|
||||
expect(digestContent.digest).toBeTruthy();
|
||||
});
|
||||
});
|
||||
223
packages/team-server/tests/daemons/scout.test.ts
Normal file
223
packages/team-server/tests/daemons/scout.test.ts
Normal file
@@ -0,0 +1,223 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import { users, teams, teamMembers, teamResources, agents, scoutFindings } from '../../src/db/schema.js';
|
||||
import { sql, eq } from 'drizzle-orm';
|
||||
import { ScoutAgent } from '../../src/daemons/scout.js';
|
||||
|
||||
describe('Scout Agent (Task 3.18)', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let userId: string;
|
||||
let secondUserId: string;
|
||||
let teamId: string;
|
||||
let scout: ScoutAgent;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up leftover test data
|
||||
await server.db.execute(sql`DELETE FROM scout_findings WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'scout_%')`);
|
||||
await server.db.execute(sql`DELETE FROM agents WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'scout_%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_resources WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'scouttest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'scouttest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'scouttest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'scouttest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'scouttest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'scouttest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'scout_%'`);
|
||||
|
||||
// Create test user
|
||||
const [user] = await server.db.insert(users).values({
|
||||
clerkId: 'scout_user1',
|
||||
displayName: 'Scout User',
|
||||
email: 'scout_user1@test.com',
|
||||
}).returning();
|
||||
userId = user.id;
|
||||
|
||||
const [secondUser] = await server.db.insert(users).values({
|
||||
clerkId: 'scout_user2',
|
||||
displayName: 'Scout User 2',
|
||||
email: 'scout_user2@test.com',
|
||||
}).returning();
|
||||
secondUserId = secondUser.id;
|
||||
|
||||
// Create team
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'Scout Test Team',
|
||||
slug: 'scouttest-team',
|
||||
ownerId: userId,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
|
||||
// Add membership with interests
|
||||
await server.db.insert(teamMembers).values({
|
||||
teamId,
|
||||
userId,
|
||||
role: 'owner',
|
||||
interests: ['python', 'data-science'],
|
||||
});
|
||||
|
||||
// Create an agent with tools for the user
|
||||
await server.db.insert(agents).values({
|
||||
userId,
|
||||
teamId,
|
||||
name: 'TestAgent',
|
||||
tools: ['web_search', 'code_review'],
|
||||
});
|
||||
|
||||
// Create team resources
|
||||
await server.db.insert(teamResources).values([
|
||||
{
|
||||
teamId,
|
||||
resourceType: 'skill',
|
||||
name: 'Python Data Analyzer',
|
||||
description: 'A skill for analyzing data with Python',
|
||||
config: {},
|
||||
sharedBy: userId,
|
||||
},
|
||||
{
|
||||
teamId,
|
||||
resourceType: 'prompt_template',
|
||||
name: 'Code Review Template',
|
||||
description: 'Template for code reviews',
|
||||
config: {},
|
||||
sharedBy: userId,
|
||||
},
|
||||
]);
|
||||
|
||||
scout = new ScoutAgent(server.db);
|
||||
|
||||
// Override auth handler
|
||||
server._authHandler.fn = async function (request: FastifyRequest, reply: FastifyReply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM scout_findings WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'scout_%')`);
|
||||
await server.db.execute(sql`DELETE FROM agents WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'scout_%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_resources WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'scouttest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'scouttest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'scouttest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'scouttest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'scouttest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'scouttest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'scout_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('scan creates findings from team resources', async () => {
|
||||
const findings = await scout.scan(userId, teamId);
|
||||
expect(findings.length).toBeGreaterThanOrEqual(2);
|
||||
expect(findings.every((f) => f.status === 'new')).toBe(true);
|
||||
expect(findings.some((f) => f.title.includes('Python Data Analyzer'))).toBe(true);
|
||||
expect(findings.some((f) => f.title.includes('Code Review Template'))).toBe(true);
|
||||
});
|
||||
|
||||
it('relevance scoring boosts based on user interests', async () => {
|
||||
// The Python Data Analyzer should be boosted because user has 'python' interest
|
||||
const findings = await scout.listFindings(userId);
|
||||
const pythonFinding = findings.find((f) => f.title.includes('Python'));
|
||||
const templateFinding = findings.find((f) => f.title.includes('Code Review'));
|
||||
|
||||
expect(pythonFinding).toBeTruthy();
|
||||
expect(templateFinding).toBeTruthy();
|
||||
// Python finding should have higher score (base 0.5 + 0.3 interest boost)
|
||||
expect(pythonFinding!.relevanceScore).toBeGreaterThan(templateFinding!.relevanceScore);
|
||||
});
|
||||
|
||||
it('adopt updates status', async () => {
|
||||
const findings = await scout.listFindings(userId);
|
||||
const finding = findings[0];
|
||||
|
||||
const updated = await scout.adopt(finding.id, userId);
|
||||
expect(updated).toBeTruthy();
|
||||
expect(updated!.status).toBe('adopted');
|
||||
});
|
||||
|
||||
it('dismiss updates status', async () => {
|
||||
const findings = await scout.listFindings(userId);
|
||||
const newFinding = findings.find((f) => f.status === 'new');
|
||||
expect(newFinding).toBeTruthy();
|
||||
|
||||
const updated = await scout.dismiss(newFinding!.id, userId);
|
||||
expect(updated).toBeTruthy();
|
||||
expect(updated!.status).toBe('dismissed');
|
||||
});
|
||||
|
||||
it('dismissed finding not resurfaced in future scans', async () => {
|
||||
// Clear all non-dismissed findings
|
||||
const allFindings = await scout.listFindings(userId);
|
||||
const dismissed = allFindings.filter((f) => f.status === 'dismissed');
|
||||
expect(dismissed.length).toBeGreaterThan(0);
|
||||
|
||||
// Run scan again — dismissed titles should not reappear as new
|
||||
const newFindings = await scout.scan(userId, teamId);
|
||||
const dismissedTitles = dismissed.map((f) => f.title);
|
||||
const resurfaced = newFindings.filter((f) => dismissedTitles.includes(f.title));
|
||||
expect(resurfaced.length).toBe(0);
|
||||
});
|
||||
|
||||
it('GET /api/scout/findings returns findings for user', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/scout/findings',
|
||||
headers: { 'x-test-user-id': userId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it.each(['adopted', 'dismissed'] as const)(
|
||||
'does not let one user mark another user\'s finding as %s',
|
||||
async (status) => {
|
||||
const [victimFinding] = await server.db.insert(scoutFindings).values({
|
||||
userId: secondUserId,
|
||||
teamId,
|
||||
source: 'team',
|
||||
category: 'practice',
|
||||
title: `Victim finding ${status}`,
|
||||
summary: 'belongs to another user',
|
||||
relevanceScore: 0.8,
|
||||
url: null,
|
||||
status: 'new',
|
||||
}).returning();
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/scout/findings/${victimFinding.id}`,
|
||||
headers: { 'x-test-user-id': userId },
|
||||
payload: { status },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(response.json()).toEqual({ error: 'Finding not found' });
|
||||
const [unchanged] = await server.db.select().from(scoutFindings)
|
||||
.where(eq(scoutFindings.id, victimFinding.id));
|
||||
expect(unchanged.status).toBe('new');
|
||||
expect(unchanged.userId).toBe(secondUserId);
|
||||
},
|
||||
);
|
||||
|
||||
it('PATCH /api/scout/findings/:id rejects invalid status', async () => {
|
||||
const findings = await scout.listFindings(userId);
|
||||
const finding = findings[0];
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/scout/findings/${finding.id}`,
|
||||
headers: { 'x-test-user-id': userId },
|
||||
payload: { status: 'invalid' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
130
packages/team-server/tests/daemons/subconscious.test.ts
Normal file
130
packages/team-server/tests/daemons/subconscious.test.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import { users, teams, teamMembers, agentJobs, agentAuditLog } from '../../src/db/schema.js';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { SubconsciousAgent } from '../../src/daemons/subconscious.js';
|
||||
|
||||
describe('Subconscious Agent (Task 3.19)', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let userId: string;
|
||||
let teamId: string;
|
||||
let subconscious: SubconsciousAgent;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up leftover test data
|
||||
await server.db.execute(sql`DELETE FROM agent_audit_log WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'subcon_%')`);
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'subcon_%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'subcontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'subcontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'subcontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'subcontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'subcontest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'subcon_%'`);
|
||||
|
||||
// Create test user
|
||||
const [user] = await server.db.insert(users).values({
|
||||
clerkId: 'subcon_user1',
|
||||
displayName: 'Subconscious User',
|
||||
email: 'subcon_user1@test.com',
|
||||
}).returning();
|
||||
userId = user.id;
|
||||
|
||||
// Create team
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'Subconscious Test Team',
|
||||
slug: 'subcontest-team',
|
||||
ownerId: userId,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
|
||||
await server.db.insert(teamMembers).values({
|
||||
teamId,
|
||||
userId,
|
||||
role: 'owner',
|
||||
});
|
||||
|
||||
subconscious = new SubconsciousAgent(server.db);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM agent_audit_log WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'subcon_%')`);
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'subcon_%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'subcontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'subcontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'subcontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'subcontest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'subcontest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'subcon_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('shouldReflect returns false when under threshold', async () => {
|
||||
// No completed jobs yet
|
||||
const result = await subconscious.shouldReflect(userId);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('shouldReflect returns true after N completed jobs', async () => {
|
||||
// Insert 10 completed jobs (SUBCONSCIOUS_INTERACTION_THRESHOLD = 10)
|
||||
const jobValues = Array.from({ length: 10 }, (_, i) => ({
|
||||
teamId,
|
||||
userId,
|
||||
jobType: 'chat',
|
||||
status: 'completed',
|
||||
input: { prompt: `test ${i}` },
|
||||
completedAt: new Date(),
|
||||
}));
|
||||
await server.db.insert(agentJobs).values(jobValues);
|
||||
|
||||
const result = await subconscious.shouldReflect(userId);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('reflect creates audit entry', async () => {
|
||||
const { auditEntry, insights } = await subconscious.reflect(userId);
|
||||
|
||||
expect(auditEntry).toBeTruthy();
|
||||
expect(auditEntry.agentName).toBe('subconscious');
|
||||
expect(auditEntry.actionType).toBe('subconscious_reflection');
|
||||
expect(auditEntry.description).toContain('Reflected on');
|
||||
expect(Array.isArray(insights)).toBe(true);
|
||||
});
|
||||
|
||||
it('detects repeated job types pattern', async () => {
|
||||
// Insert 5 more jobs of same type to trigger pattern detection
|
||||
const repeatedJobs = Array.from({ length: 5 }, (_, i) => ({
|
||||
teamId,
|
||||
userId,
|
||||
jobType: 'task',
|
||||
status: 'completed',
|
||||
input: { prompt: `repeated ${i}` },
|
||||
completedAt: new Date(),
|
||||
}));
|
||||
await server.db.insert(agentJobs).values(repeatedJobs);
|
||||
|
||||
const { insights } = await subconscious.reflect(userId);
|
||||
|
||||
// Should find a prompt_change insight for the repeated 'chat' type (10 jobs)
|
||||
const promptInsight = insights.find(i => i.type === 'prompt_change');
|
||||
expect(promptInsight).toBeTruthy();
|
||||
expect(promptInsight!.description).toContain('executed');
|
||||
expect(promptInsight!.description).toContain('times recently');
|
||||
});
|
||||
|
||||
it('prompt change insight requires approval in audit entry', async () => {
|
||||
// The previous reflect should have created an audit entry with requiresApproval
|
||||
const entries = await server.db.select().from(agentAuditLog)
|
||||
.where(sql`${agentAuditLog.userId} = ${userId} AND ${agentAuditLog.actionType} = 'subconscious_reflection'`);
|
||||
|
||||
// Find one that has insights with prompt_change
|
||||
const withApproval = entries.find(e => {
|
||||
const state = e.afterState as { insights?: Array<{ type: string }> } | null;
|
||||
return state?.insights?.some((i) => i.type === 'prompt_change');
|
||||
});
|
||||
|
||||
expect(withApproval).toBeTruthy();
|
||||
expect(withApproval!.requiresApproval).toBe(true);
|
||||
});
|
||||
});
|
||||
93
packages/team-server/tests/db/schema.test.ts
Normal file
93
packages/team-server/tests/db/schema.test.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { createDb, type Db } from '../../src/db/connection.js';
|
||||
import { users, teams, teamMembers, tasks, messages, agents, agentGroups } from '../../src/db/schema.js';
|
||||
import { sql } from 'drizzle-orm';
|
||||
|
||||
const SUFFIX = `_schema_${Date.now()}`;
|
||||
|
||||
describe('PostgreSQL schema', () => {
|
||||
let db: Db;
|
||||
let testUserId: string;
|
||||
let testTeamId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
db = createDb(process.env.DATABASE_URL ?? 'postgres://waggle:waggle_dev@localhost:5434/waggle');
|
||||
|
||||
// Clean up any leftovers from previous runs
|
||||
await db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE '%_schema_%')`);
|
||||
await db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE '%_schema_%')`);
|
||||
await db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE '%_schema_%')`);
|
||||
await db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE '%_schema_%')`);
|
||||
await db.execute(sql`DELETE FROM teams WHERE slug LIKE '%_schema_%'`);
|
||||
await db.execute(sql`DELETE FROM users WHERE clerk_id LIKE '%_schema_%'`);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
// Clean up test data created by these tests
|
||||
if (testTeamId) {
|
||||
await db.execute(sql`DELETE FROM team_members WHERE team_id = ${testTeamId}`);
|
||||
await db.execute(sql`DELETE FROM team_capability_requests WHERE team_id = ${testTeamId}`);
|
||||
await db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id = ${testTeamId}`);
|
||||
await db.execute(sql`DELETE FROM team_capability_policies WHERE team_id = ${testTeamId}`);
|
||||
await db.execute(sql`DELETE FROM teams WHERE id = ${testTeamId}`);
|
||||
}
|
||||
if (testUserId) {
|
||||
await db.execute(sql`DELETE FROM users WHERE id = ${testUserId}`);
|
||||
}
|
||||
});
|
||||
|
||||
it('creates a user', async () => {
|
||||
const [user] = await db.insert(users).values({
|
||||
clerkId: `clerk${SUFFIX}`,
|
||||
displayName: 'Schema Test User',
|
||||
email: `schematest${SUFFIX}@test.com`,
|
||||
}).returning();
|
||||
testUserId = user.id;
|
||||
expect(user.id).toBeDefined();
|
||||
expect(user.displayName).toBe('Schema Test User');
|
||||
});
|
||||
|
||||
it('creates a team with owner', async () => {
|
||||
// Depends on previous test having created user
|
||||
expect(testUserId).toBeTruthy();
|
||||
|
||||
const [team] = await db.insert(teams).values({
|
||||
name: 'Marketing',
|
||||
slug: `marketing${SUFFIX}`,
|
||||
ownerId: testUserId,
|
||||
}).returning();
|
||||
testTeamId = team.id;
|
||||
expect(team.slug).toBe(`marketing${SUFFIX}`);
|
||||
|
||||
await db.insert(teamMembers).values({
|
||||
teamId: team.id,
|
||||
userId: testUserId,
|
||||
role: 'owner',
|
||||
});
|
||||
});
|
||||
|
||||
it('creates all 16 tables', async () => {
|
||||
const result = await db.execute(sql`
|
||||
SELECT table_name FROM information_schema.tables
|
||||
WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
|
||||
ORDER BY table_name
|
||||
`);
|
||||
const tableNames = (result as Array<{ table_name: string }>).map((r) => r.table_name);
|
||||
expect(tableNames).toContain('users');
|
||||
expect(tableNames).toContain('teams');
|
||||
expect(tableNames).toContain('team_members');
|
||||
expect(tableNames).toContain('agents');
|
||||
expect(tableNames).toContain('agent_groups');
|
||||
expect(tableNames).toContain('tasks');
|
||||
expect(tableNames).toContain('messages');
|
||||
expect(tableNames).toContain('team_entities');
|
||||
expect(tableNames).toContain('team_relations');
|
||||
expect(tableNames).toContain('team_resources');
|
||||
expect(tableNames).toContain('agent_jobs');
|
||||
expect(tableNames).toContain('cron_schedules');
|
||||
expect(tableNames).toContain('scout_findings');
|
||||
expect(tableNames).toContain('proactive_patterns');
|
||||
expect(tableNames).toContain('suggestions_log');
|
||||
expect(tableNames).toContain('agent_audit_log');
|
||||
});
|
||||
});
|
||||
139
packages/team-server/tests/e2e/team-server.spec.ts
Normal file
139
packages/team-server/tests/e2e/team-server.spec.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Team Server E2E — tests the multi-user team server running on Docker
|
||||
* (Postgres + Redis + LiteLLM).
|
||||
*
|
||||
* Requires: docker-compose up (postgres:5434, redis:6381, litellm:4000)
|
||||
* Team server running on port 3100.
|
||||
*/
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const TEAM = 'http://127.0.0.1:3100';
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
try {
|
||||
const res = await request.get(`${TEAM}/health`, { timeout: 1_000 });
|
||||
test.skip(!res.ok(), 'Optional team server is not running on 127.0.0.1:3100');
|
||||
} catch {
|
||||
test.skip(true, 'Optional team server is not running on 127.0.0.1:3100');
|
||||
}
|
||||
});
|
||||
|
||||
// ── 1. Server Health ──────────────────────────────────────────────────
|
||||
|
||||
test.describe('1. Team Server Health', () => {
|
||||
test('health endpoint responds', async ({ request }) => {
|
||||
const res = await request.get(`${TEAM}/health`);
|
||||
expect(res.ok()).toBeTruthy();
|
||||
const data = await res.json();
|
||||
expect(data.status).toBe('ok');
|
||||
});
|
||||
});
|
||||
|
||||
// ── 2. Team CRUD ──────────────────────────────────────────────────────
|
||||
|
||||
test.describe('2. Team Management', () => {
|
||||
let teamSlug: string;
|
||||
|
||||
test('can create a team', async ({ request }) => {
|
||||
const name = `TestTeam-${Date.now()}`;
|
||||
teamSlug = name.toLowerCase().replace(/[^a-z0-9]/g, '-');
|
||||
const res = await request.post(`${TEAM}/api/teams`, {
|
||||
data: { name, slug: teamSlug },
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
// May need auth — accept 200, 201, or 401
|
||||
expect([200, 201, 401, 403]).toContain(res.status());
|
||||
});
|
||||
|
||||
test('can list teams', async ({ request }) => {
|
||||
const res = await request.get(`${TEAM}/api/teams`);
|
||||
expect([200, 401, 403]).toContain(res.status());
|
||||
if (res.ok()) {
|
||||
const data = await res.json();
|
||||
expect(Array.isArray(data) || Array.isArray(data.teams)).toBeTruthy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ── 3. Agent Routes ───────────────────────────────────────────────────
|
||||
|
||||
test.describe('3. Agent & Model Routes', () => {
|
||||
test('agents list', async ({ request }) => {
|
||||
const res = await request.get(`${TEAM}/api/agents`);
|
||||
expect([200, 401]).toContain(res.status());
|
||||
});
|
||||
|
||||
test('workflows list', async ({ request }) => {
|
||||
const res = await request.get(`${TEAM}/api/workflows`);
|
||||
expect([200, 401, 404]).toContain(res.status());
|
||||
});
|
||||
});
|
||||
|
||||
// ── 4. Database Connection ────────────────────────────────────────────
|
||||
|
||||
test.describe('4. Database', () => {
|
||||
test('postgres is reachable from server', async ({ request }) => {
|
||||
// The server started successfully which means DB connected.
|
||||
// Verify by hitting an endpoint that requires DB.
|
||||
const res = await request.get(`${TEAM}/api/teams`);
|
||||
// If 500, DB connection failed. 200 or 401 means DB is fine.
|
||||
expect(res.status()).not.toBe(500);
|
||||
});
|
||||
});
|
||||
|
||||
// ── 5. WebSocket Gateway ──────────────────────────────────────────────
|
||||
|
||||
test.describe('5. WebSocket', () => {
|
||||
test('ws endpoint exists', async ({ request }) => {
|
||||
// HTTP GET to /ws should return upgrade required or similar
|
||||
const res = await request.get(`${TEAM}/ws`);
|
||||
// WebSocket endpoints typically return 400 or 426 on plain HTTP
|
||||
expect([400, 404, 426]).toContain(res.status());
|
||||
});
|
||||
});
|
||||
|
||||
// ── 6. Cron & Jobs ────────────────────────────────────────────────────
|
||||
|
||||
test.describe('6. Background Services', () => {
|
||||
test('cron status endpoint', async ({ request }) => {
|
||||
const res = await request.get(`${TEAM}/api/cron`);
|
||||
expect([200, 401, 404]).toContain(res.status());
|
||||
});
|
||||
});
|
||||
|
||||
// ── 7. Knowledge & Resources ──────────────────────────────────────────
|
||||
|
||||
test.describe('7. Knowledge Routes', () => {
|
||||
test('skills endpoint', async ({ request }) => {
|
||||
const res = await request.get(`${TEAM}/api/skills`);
|
||||
expect([200, 401, 404]).toContain(res.status());
|
||||
});
|
||||
});
|
||||
|
||||
// ── 8. Concurrent Requests ────────────────────────────────────────────
|
||||
|
||||
test.describe('8. Concurrency', () => {
|
||||
test('10 concurrent health checks all succeed', async ({ request }) => {
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 10 }, () => request.get(`${TEAM}/health`))
|
||||
);
|
||||
for (const res of results) {
|
||||
expect(res.ok()).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
test('server handles rapid API calls without crashing', async ({ request }) => {
|
||||
const endpoints = ['/health', '/api/teams', '/api/agents', '/api/workflows', '/api/cron'];
|
||||
const results = await Promise.all(
|
||||
endpoints.map(ep => request.get(`${TEAM}${ep}`))
|
||||
);
|
||||
// No 500s — server survived the burst
|
||||
for (const res of results) {
|
||||
expect(res.status()).toBeLessThan(500);
|
||||
}
|
||||
|
||||
// Health still ok after burst
|
||||
const health = await request.get(`${TEAM}/health`);
|
||||
expect(health.ok()).toBeTruthy();
|
||||
});
|
||||
});
|
||||
35
packages/team-server/tests/entrypoint.test.ts
Normal file
35
packages/team-server/tests/entrypoint.test.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { isDirectModule } from '../src/index.js';
|
||||
|
||||
const REPO_ROOT = fileURLToPath(new URL('../../../', import.meta.url));
|
||||
|
||||
describe('team server entrypoint detection', () => {
|
||||
it('is left out of the community-edition package build with the rest of team mode (ADR-0003)', () => {
|
||||
const rootPackage = JSON.parse(readFileSync(resolve(REPO_ROOT, 'package.json'), 'utf8')) as {
|
||||
scripts: Record<string, string>;
|
||||
};
|
||||
const build = rootPackage.scripts['build:packages'];
|
||||
|
||||
expect(build).toContain('cd ../server && npx tsc --build');
|
||||
for (const postponed of ['../team-server', '../worker', '../waggle-dance']) {
|
||||
expect(build).not.toContain(postponed);
|
||||
}
|
||||
});
|
||||
|
||||
it('recognizes the compiled dist entrypoint by URL identity', () => {
|
||||
const distPath = resolve(REPO_ROOT, 'packages/team-server/dist/index.js');
|
||||
|
||||
expect(isDirectModule(distPath, pathToFileURL(distPath).href)).toBe(true);
|
||||
});
|
||||
|
||||
it('does not start when imported by another process entrypoint', () => {
|
||||
const distPath = resolve(REPO_ROOT, 'packages/team-server/dist/index.js');
|
||||
const importerUrl = pathToFileURL(resolve(REPO_ROOT, 'packages/team-server/dist/consumer.js')).href;
|
||||
|
||||
expect(isDirectModule(distPath, importerUrl)).toBe(false);
|
||||
expect(isDirectModule(undefined, importerUrl)).toBe(false);
|
||||
});
|
||||
});
|
||||
292
packages/team-server/tests/integration/m3-full-stack.test.ts
Normal file
292
packages/team-server/tests/integration/m3-full-stack.test.ts
Normal file
@@ -0,0 +1,292 @@
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import {
|
||||
users, teams, teamMembers, tasks, messages,
|
||||
teamEntities, teamResources, agentAuditLog,
|
||||
} from '../../src/db/schema.js';
|
||||
import { sql } from 'drizzle-orm';
|
||||
|
||||
const SIGNING_KEY = Buffer.from('waggle-m3-full-stack-test-secret');
|
||||
const SIGNING_SECRET = `whsec_${SIGNING_KEY.toString('base64')}`;
|
||||
|
||||
function signedHeaders(payload: object) {
|
||||
const id = 'msg_waggle_m3_full_stack';
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
const signature = createHmac('sha256', SIGNING_KEY)
|
||||
.update(`${id}.${timestamp}.${JSON.stringify(payload)}`)
|
||||
.digest('base64');
|
||||
|
||||
return {
|
||||
'svix-id': id,
|
||||
'svix-timestamp': String(timestamp),
|
||||
'svix-signature': `v1,${signature}`,
|
||||
};
|
||||
}
|
||||
|
||||
describe('M3 Full Stack Integration', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let ownerId: string;
|
||||
let memberId: string;
|
||||
let teamId: string;
|
||||
let originalSigningSecret: string | undefined;
|
||||
const teamSlug = 'integ-team';
|
||||
|
||||
beforeAll(async () => {
|
||||
originalSigningSecret = process.env.CLERK_WEBHOOK_SIGNING_SECRET;
|
||||
process.env.CLERK_WEBHOOK_SIGNING_SECRET = SIGNING_SECRET;
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up leftover test data from previous runs (reverse dependency order)
|
||||
await server.db.execute(sql`DELETE FROM agent_audit_log WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'integ_%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_resources WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_relations WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_entities WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM messages WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM tasks WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM cron_schedules WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug = 'integ-team'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'integ_%'`);
|
||||
|
||||
// Override auth handler for testing
|
||||
server._authHandler.fn = async function (request: FastifyRequest, reply: FastifyReply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
// Clean up all test data
|
||||
await server.db.execute(sql`DELETE FROM agent_audit_log WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'integ_%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_resources WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_relations WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_entities WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM messages WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM tasks WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM cron_schedules WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug = 'integ-team')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug = 'integ-team'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'integ_%'`);
|
||||
} finally {
|
||||
try {
|
||||
await server?.close();
|
||||
} finally {
|
||||
if (originalSigningSecret === undefined) {
|
||||
delete process.env.CLERK_WEBHOOK_SIGNING_SECRET;
|
||||
} else {
|
||||
process.env.CLERK_WEBHOOK_SIGNING_SECRET = originalSigningSecret;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('Step 1: Creates users via webhook', async () => {
|
||||
// Create owner
|
||||
const ownerEvent = {
|
||||
type: 'user.created',
|
||||
data: {
|
||||
id: 'integ_owner',
|
||||
first_name: 'Owner',
|
||||
last_name: 'User',
|
||||
email_addresses: [{ email_address: 'integ_owner@test.com' }],
|
||||
},
|
||||
};
|
||||
let res = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
headers: signedHeaders(ownerEvent),
|
||||
payload: ownerEvent,
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
// Create member
|
||||
const memberEvent = {
|
||||
type: 'user.created',
|
||||
data: {
|
||||
id: 'integ_member',
|
||||
first_name: 'Member',
|
||||
last_name: 'User',
|
||||
email_addresses: [{ email_address: 'integ_member@test.com' }],
|
||||
},
|
||||
};
|
||||
res = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
headers: signedHeaders(memberEvent),
|
||||
payload: memberEvent,
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
// Get user IDs
|
||||
const [owner] = await server.db.select().from(users).where(sql`clerk_id = 'integ_owner'`);
|
||||
const [member] = await server.db.select().from(users).where(sql`clerk_id = 'integ_member'`);
|
||||
expect(owner).toBeDefined();
|
||||
expect(member).toBeDefined();
|
||||
ownerId = owner.id;
|
||||
memberId = member.id;
|
||||
});
|
||||
|
||||
it('Step 2: Creates team and invites member', async () => {
|
||||
let res = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/teams',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { name: 'Integration Team', slug: teamSlug },
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
teamId = JSON.parse(res.body).id;
|
||||
|
||||
// Add member
|
||||
res = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/members`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { email: 'integ_member@test.com', role: 'member' },
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
});
|
||||
|
||||
it('Step 3: Creates task on team board', async () => {
|
||||
const res = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/tasks`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { title: 'Research competitor pricing', priority: 'high' },
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.title).toBe('Research competitor pricing');
|
||||
expect(body.priority).toBe('high');
|
||||
expect(body.status).toBe('open');
|
||||
});
|
||||
|
||||
it('Step 4: Sends Waggle Dance message', async () => {
|
||||
const res = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
type: 'request',
|
||||
subtype: 'knowledge_check',
|
||||
content: { topic: 'competitor pricing' },
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.type).toBe('request');
|
||||
expect(body.subtype).toBe('knowledge_check');
|
||||
});
|
||||
|
||||
it('Step 5: Shares knowledge entity to team graph', async () => {
|
||||
const res = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { entityType: 'competitor', name: 'Acme Corp', properties: { pricing: '$99/mo' } },
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.entityType).toBe('competitor');
|
||||
expect(body.name).toBe('Acme Corp');
|
||||
});
|
||||
|
||||
it('Step 6: Shares team resource', async () => {
|
||||
const res = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/resources`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
resourceType: 'model_recipe',
|
||||
name: 'Fast Research Config',
|
||||
config: { model: 'claude-haiku-4-5', temperature: 0.3 },
|
||||
},
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.resourceType).toBe('model_recipe');
|
||||
expect(body.name).toBe('Fast Research Config');
|
||||
});
|
||||
|
||||
it('Step 7: Creates audit trail entry', async () => {
|
||||
const { AuditService } = await import('../../src/services/audit-service.js');
|
||||
const auditService = new AuditService(server.db);
|
||||
const entry = await auditService.log({
|
||||
userId: ownerId,
|
||||
teamId,
|
||||
agentName: 'memory-weaver',
|
||||
actionType: 'consolidation',
|
||||
description: 'Consolidated meeting notes',
|
||||
});
|
||||
expect(entry.agentName).toBe('memory-weaver');
|
||||
|
||||
// Verify via admin API
|
||||
// First promote owner to admin role (owner already has admin+ perms)
|
||||
const res = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/admin/teams/${teamSlug}/audit`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('Step 8: Member cannot access admin audit endpoint', async () => {
|
||||
const res = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/admin/teams/${teamSlug}/audit`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('Step 9: Lists tasks, messages, entities for the team', async () => {
|
||||
// Tasks
|
||||
const tasksRes = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/tasks`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
expect(tasksRes.statusCode).toBe(200);
|
||||
expect(JSON.parse(tasksRes.body).length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Messages
|
||||
const msgsRes = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
expect(msgsRes.statusCode).toBe(200);
|
||||
expect(JSON.parse(msgsRes.body).length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Entities
|
||||
const entRes = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
expect(entRes.statusCode).toBe(200);
|
||||
expect(JSON.parse(entRes.body).length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('Step 10: Health check passes', async () => {
|
||||
const res = await server.inject({ method: 'GET', url: '/health' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).status).toBe('ok');
|
||||
});
|
||||
});
|
||||
220
packages/team-server/tests/proactive.test.ts
Normal file
220
packages/team-server/tests/proactive.test.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { buildServer } from '../src/index.js';
|
||||
import { users, proactivePatterns, suggestionsLog } from '../src/db/schema.js';
|
||||
import { sql, eq } from 'drizzle-orm';
|
||||
import { ProactiveService } from '../src/services/proactive-service.js';
|
||||
|
||||
describe('Proactive Engine (Task 3.17)', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let userId: string;
|
||||
let secondUserId: string;
|
||||
let proactiveService: ProactiveService;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up leftover test data
|
||||
await server.db.execute(sql`DELETE FROM suggestions_log WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'protest_%')`);
|
||||
await server.db.execute(sql`DELETE FROM proactive_patterns WHERE name LIKE 'test_%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'protest_%'`);
|
||||
// Also clean any seeded patterns for a clean slate
|
||||
await server.db.execute(sql`DELETE FROM suggestions_log`);
|
||||
await server.db.execute(sql`DELETE FROM proactive_patterns`);
|
||||
|
||||
// Create test users
|
||||
const [user] = await server.db.insert(users).values({
|
||||
clerkId: 'protest_user1',
|
||||
displayName: 'Proactive User',
|
||||
email: 'protest_user1@test.com',
|
||||
}).returning();
|
||||
userId = user.id;
|
||||
|
||||
const [user2] = await server.db.insert(users).values({
|
||||
clerkId: 'protest_user2',
|
||||
displayName: 'Proactive User 2',
|
||||
email: 'protest_user2@test.com',
|
||||
}).returning();
|
||||
secondUserId = user2.id;
|
||||
|
||||
proactiveService = new ProactiveService(server.db);
|
||||
|
||||
// Seed patterns
|
||||
await proactiveService.ensurePatternsSeeded();
|
||||
|
||||
// Override auth handler
|
||||
server._authHandler.fn = async function (request: FastifyRequest, reply: FastifyReply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM suggestions_log WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'protest_%')`);
|
||||
await server.db.execute(sql`DELETE FROM proactive_patterns`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'protest_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('seeds built-in patterns', async () => {
|
||||
const patterns = await server.db.select().from(proactivePatterns);
|
||||
expect(patterns.length).toBe(5);
|
||||
const names = patterns.map(p => p.name);
|
||||
expect(names).toContain('recurring_task');
|
||||
expect(names).toContain('data_report');
|
||||
expect(names).toContain('relevant_to_others');
|
||||
expect(names).toContain('expensive_model');
|
||||
expect(names).toContain('manual_repetition');
|
||||
});
|
||||
|
||||
it('does not re-seed if patterns exist', async () => {
|
||||
await proactiveService.ensurePatternsSeeded();
|
||||
const patterns = await server.db.select().from(proactivePatterns);
|
||||
expect(patterns.length).toBe(5); // still 5, not 10
|
||||
});
|
||||
|
||||
it('pattern triggers create suggestion when context matches', async () => {
|
||||
const result = await proactiveService.evaluate(userId, {
|
||||
repeatCount: 5, // triggers 'recurring_task' (cron) pattern
|
||||
});
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result!.status).toBe('pending');
|
||||
expect(result!.pattern.suggestionType).toBe('cron');
|
||||
});
|
||||
|
||||
it('max 1 suggestion per interaction (second evaluate returns null)', async () => {
|
||||
// User already has a pending suggestion from previous test
|
||||
const result = await proactiveService.evaluate(userId, {
|
||||
hasData: true, // would trigger 'data_report' (dashboard) pattern
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('dismissed pattern not re-suggested', async () => {
|
||||
// Clear all pending suggestions for secondUserId so we start fresh
|
||||
await server.db.execute(sql`DELETE FROM suggestions_log WHERE user_id = ${secondUserId}`);
|
||||
|
||||
// First, trigger a suggestion for secondUserId
|
||||
const suggestion = await proactiveService.evaluate(secondUserId, {
|
||||
repeatCount: 4, // triggers cron pattern
|
||||
});
|
||||
expect(suggestion).toBeTruthy();
|
||||
|
||||
// Dismiss it
|
||||
await proactiveService.updateStatus(suggestion!.id, secondUserId, 'dismissed');
|
||||
|
||||
// Clear pending count so the MAX check doesn't block us
|
||||
// (dismissed doesn't count as pending, so evaluate should proceed)
|
||||
|
||||
// Try to trigger the same pattern again
|
||||
const result2 = await proactiveService.evaluate(secondUserId, {
|
||||
repeatCount: 10,
|
||||
});
|
||||
|
||||
// Should be null because the cron pattern was dismissed
|
||||
// It might match a different pattern though, so check specifically
|
||||
if (result2) {
|
||||
expect(result2.pattern.suggestionType).not.toBe('cron');
|
||||
}
|
||||
});
|
||||
|
||||
it('accept/dismiss/snooze updates status via API', async () => {
|
||||
// Clear suggestions for userId
|
||||
await server.db.execute(sql`DELETE FROM suggestions_log WHERE user_id = ${userId}`);
|
||||
|
||||
// Create a new suggestion
|
||||
const suggestion = await proactiveService.evaluate(userId, {
|
||||
expensiveModel: true, // triggers 'upgrade' pattern
|
||||
});
|
||||
expect(suggestion).toBeTruthy();
|
||||
|
||||
// Accept via API
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/suggestions/${suggestion!.id}`,
|
||||
headers: { 'x-test-user-id': userId },
|
||||
payload: { status: 'accepted' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.status).toBe('accepted');
|
||||
});
|
||||
|
||||
it('does not let one user update another user\'s suggestion', async () => {
|
||||
const patterns = await server.db.select().from(proactivePatterns);
|
||||
const [victimSuggestion] = await server.db.insert(suggestionsLog).values({
|
||||
userId: secondUserId,
|
||||
patternId: patterns[0].id,
|
||||
context: { owner: 'victim' },
|
||||
status: 'pending',
|
||||
}).returning();
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/suggestions/${victimSuggestion.id}`,
|
||||
headers: { 'x-test-user-id': userId },
|
||||
payload: { status: 'accepted' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(response.json()).toEqual({ error: 'Suggestion not found' });
|
||||
const [unchanged] = await server.db.select().from(suggestionsLog)
|
||||
.where(eq(suggestionsLog.id, victimSuggestion.id));
|
||||
expect(unchanged.status).toBe('pending');
|
||||
expect(unchanged.userId).toBe(secondUserId);
|
||||
});
|
||||
|
||||
it('list pending returns only pending suggestions via API', async () => {
|
||||
// Clear and create fresh data
|
||||
await server.db.execute(sql`DELETE FROM suggestions_log WHERE user_id = ${userId}`);
|
||||
|
||||
// Create a pending suggestion directly
|
||||
const patterns = await server.db.select().from(proactivePatterns);
|
||||
const pattern = patterns[0];
|
||||
|
||||
await server.db.insert(suggestionsLog).values([
|
||||
{ userId, patternId: pattern.id, context: { test: 1 }, status: 'pending' },
|
||||
{ userId, patternId: pattern.id, context: { test: 2 }, status: 'accepted' },
|
||||
{ userId, patternId: pattern.id, context: { test: 3 }, status: 'dismissed' },
|
||||
]);
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/suggestions',
|
||||
headers: { 'x-test-user-id': userId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
// Only pending ones should be returned
|
||||
expect((body as Array<{ status: string }>).every((s) => s.status === 'pending')).toBe(true);
|
||||
expect(body.length).toBe(1);
|
||||
});
|
||||
|
||||
it('rejects invalid status in PATCH', async () => {
|
||||
const patterns = await server.db.select().from(proactivePatterns);
|
||||
const [suggestion] = await server.db.insert(suggestionsLog).values({
|
||||
userId,
|
||||
patternId: patterns[0].id,
|
||||
context: {},
|
||||
status: 'pending',
|
||||
}).returning();
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/suggestions/${suggestion.id}`,
|
||||
headers: { 'x-test-user-id': userId },
|
||||
payload: { status: 'invalid' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
581
packages/team-server/tests/routes/agents.test.ts
Normal file
581
packages/team-server/tests/routes/agents.test.ts
Normal file
@@ -0,0 +1,581 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import { users, agents, agentGroups, agentGroupMembers, agentJobs, teams, teamMembers } from '../../src/db/schema.js';
|
||||
import { sql, eq } from 'drizzle-orm';
|
||||
|
||||
describe('Agent API', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let user1Id: string;
|
||||
let user2Id: string;
|
||||
let teamId: string;
|
||||
let team2Id: string;
|
||||
let agent1Id: string;
|
||||
let agent2Id: string;
|
||||
let foreignAgentId: string;
|
||||
let group1Id: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up leftover test data
|
||||
await server.db.execute(sql`DELETE FROM agent_group_members WHERE group_id IN (SELECT id FROM agent_groups WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'agtest_%'))`);
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'agtest_%')`);
|
||||
await server.db.execute(sql`DELETE FROM agent_groups WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'agtest_%')`);
|
||||
await server.db.execute(sql`DELETE FROM agents WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'agtest_%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'agtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'agtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'agtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'agtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'agtest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'agtest_%'`);
|
||||
|
||||
// Create test users
|
||||
const [u1] = await server.db.insert(users).values({
|
||||
clerkId: 'agtest_user1',
|
||||
displayName: 'Agent User 1',
|
||||
email: 'agentuser1@test.com',
|
||||
}).returning();
|
||||
user1Id = u1.id;
|
||||
|
||||
const [u2] = await server.db.insert(users).values({
|
||||
clerkId: 'agtest_user2',
|
||||
displayName: 'Agent User 2',
|
||||
email: 'agentuser2@test.com',
|
||||
}).returning();
|
||||
user2Id = u2.id;
|
||||
|
||||
// Create a team for job tests
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'Agent Test Team',
|
||||
slug: 'agtest-team',
|
||||
ownerId: user1Id,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
|
||||
await server.db.insert(teamMembers).values({ teamId, userId: user1Id, role: 'owner' });
|
||||
|
||||
const [team2] = await server.db.insert(teams).values({
|
||||
name: 'Agent Test Team 2',
|
||||
slug: 'agtest-team-2',
|
||||
ownerId: user2Id,
|
||||
}).returning();
|
||||
team2Id = team2.id;
|
||||
|
||||
await server.db.insert(teamMembers).values({ teamId: team2Id, userId: user2Id, role: 'owner' });
|
||||
|
||||
// Override auth handler for tests
|
||||
server._authHandler.fn = async function (request, reply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM agent_group_members WHERE group_id IN (SELECT id FROM agent_groups WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'agtest_%'))`);
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'agtest_%')`);
|
||||
await server.db.execute(sql`DELETE FROM agent_groups WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'agtest_%')`);
|
||||
await server.db.execute(sql`DELETE FROM agents WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'agtest_%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'agtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'agtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'agtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'agtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'agtest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'agtest_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('creates an agent with custom model, tools, and system prompt', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/agents',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
name: 'Research Agent',
|
||||
role: 'researcher',
|
||||
systemPrompt: 'You are a research agent.',
|
||||
model: 'claude-sonnet-4-20250514',
|
||||
tools: ['web_search', 'read_file'],
|
||||
config: { maxTokens: 4096 },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.name).toBe('Research Agent');
|
||||
expect(body.role).toBe('researcher');
|
||||
expect(body.systemPrompt).toBe('You are a research agent.');
|
||||
expect(body.model).toBe('claude-sonnet-4-20250514');
|
||||
expect(body.tools).toEqual(['web_search', 'read_file']);
|
||||
expect(body.config).toEqual({ maxTokens: 4096 });
|
||||
expect(body.userId).toBe(user1Id);
|
||||
agent1Id = body.id;
|
||||
});
|
||||
|
||||
it('creates a second agent for user1', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/agents',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
name: 'Coding Agent',
|
||||
model: 'claude-haiku-4-5',
|
||||
tools: ['execute_code'],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
agent2Id = JSON.parse(response.body).id;
|
||||
});
|
||||
|
||||
it('lists agents returns only the user\'s agents', async () => {
|
||||
// Create an agent for user2
|
||||
const foreignAgentResponse = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/agents',
|
||||
headers: { 'x-test-user-id': user2Id },
|
||||
payload: { name: 'User2 Agent' },
|
||||
});
|
||||
expect(foreignAgentResponse.statusCode).toBe(201);
|
||||
foreignAgentId = JSON.parse(foreignAgentResponse.body).id;
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/agents',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.length).toBe(2);
|
||||
expect(body.every((a: { userId: string }) => a.userId === user1Id)).toBe(true);
|
||||
});
|
||||
|
||||
it('updates agent model and config', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/agents/${agent1Id}`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
model: 'claude-haiku-4-5',
|
||||
config: { maxTokens: 2048, temperature: 0.7 },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.model).toBe('claude-haiku-4-5');
|
||||
expect(body.config).toEqual({ maxTokens: 2048, temperature: 0.7 });
|
||||
});
|
||||
|
||||
it('user cannot update another user\'s agent', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/agents/${agent1Id}`,
|
||||
headers: { 'x-test-user-id': user2Id },
|
||||
payload: { model: 'hacked-model' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('user cannot delete another user\'s agent', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/agents/${agent1Id}`,
|
||||
headers: { 'x-test-user-id': user2Id },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('creates an agent group with parallel strategy and 2 members', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/agent-groups',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
name: 'Research Squad',
|
||||
description: 'Parallel research team',
|
||||
strategy: 'parallel',
|
||||
members: [
|
||||
{ agentId: agent1Id, roleInGroup: 'worker', executionOrder: 0 },
|
||||
{ agentId: agent2Id, roleInGroup: 'worker', executionOrder: 0 },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.name).toBe('Research Squad');
|
||||
expect(body.strategy).toBe('parallel');
|
||||
expect(body.members).toHaveLength(2);
|
||||
group1Id = body.id;
|
||||
});
|
||||
|
||||
it('rejects foreign and missing agents identically when creating a group', async () => {
|
||||
const payload = {
|
||||
name: 'Cross-tenant group',
|
||||
strategy: 'parallel',
|
||||
members: [
|
||||
{ agentId: agent1Id, roleInGroup: 'worker', executionOrder: 0 },
|
||||
{ agentId: foreignAgentId, roleInGroup: 'worker', executionOrder: 1 },
|
||||
],
|
||||
};
|
||||
const foreignResponse = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/agent-groups',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload,
|
||||
});
|
||||
const missingResponse = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/agent-groups',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
...payload,
|
||||
members: [
|
||||
payload.members[0],
|
||||
{ ...payload.members[1], agentId: '00000000-0000-4000-8000-000000000001' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(foreignResponse.statusCode).toBe(404);
|
||||
expect(missingResponse.statusCode).toBe(404);
|
||||
expect(JSON.parse(foreignResponse.body)).toEqual({ error: 'Agent not found' });
|
||||
expect(missingResponse.body).toBe(foreignResponse.body);
|
||||
|
||||
const groups = await server.db
|
||||
.select()
|
||||
.from(agentGroups)
|
||||
.where(eq(agentGroups.userId, user1Id));
|
||||
expect(groups.some((group) => group.name === payload.name)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects foreign replacement members without altering the owned group', async () => {
|
||||
const foreignResponse = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/agent-groups/${group1Id}`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
members: [
|
||||
{ agentId: agent1Id, roleInGroup: 'worker', executionOrder: 0 },
|
||||
{ agentId: foreignAgentId, roleInGroup: 'worker', executionOrder: 1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
const missingResponse = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/agent-groups/${group1Id}`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
members: [
|
||||
{ agentId: agent1Id, roleInGroup: 'worker', executionOrder: 0 },
|
||||
{
|
||||
agentId: '00000000-0000-4000-8000-000000000001',
|
||||
roleInGroup: 'worker',
|
||||
executionOrder: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(foreignResponse.statusCode).toBe(404);
|
||||
expect(missingResponse.statusCode).toBe(404);
|
||||
expect(JSON.parse(foreignResponse.body)).toEqual({ error: 'Agent not found' });
|
||||
expect(missingResponse.body).toBe(foreignResponse.body);
|
||||
|
||||
const groupResponse = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/agent-groups/${group1Id}`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
});
|
||||
expect(groupResponse.statusCode).toBe(200);
|
||||
const group = JSON.parse(groupResponse.body);
|
||||
expect(group.members.map((member: { agentId: string }) => member.agentId).sort())
|
||||
.toEqual([agent1Id, agent2Id].sort());
|
||||
});
|
||||
|
||||
it('replaces group membership when every agent belongs to the caller', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/agent-groups/${group1Id}`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
members: [
|
||||
{ agentId: agent1Id, roleInGroup: 'lead', executionOrder: 0 },
|
||||
{ agentId: agent2Id, roleInGroup: 'worker', executionOrder: 1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const group = JSON.parse(response.body);
|
||||
expect(group.members.map((member: { agentId: string }) => member.agentId).sort())
|
||||
.toEqual([agent1Id, agent2Id].sort());
|
||||
});
|
||||
|
||||
it('creates a group with coordinator strategy and a lead agent', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/agent-groups',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
name: 'Coordinated Team',
|
||||
strategy: 'coordinator',
|
||||
members: [
|
||||
{ agentId: agent1Id, roleInGroup: 'lead', executionOrder: 0 },
|
||||
{ agentId: agent2Id, roleInGroup: 'worker', executionOrder: 1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.strategy).toBe('coordinator');
|
||||
const lead = body.members.find((m: { roleInGroup: string; agentId: string }) => m.roleInGroup === 'lead');
|
||||
expect(lead).toBeDefined();
|
||||
expect(lead.agentId).toBe(agent1Id);
|
||||
});
|
||||
|
||||
it('gets group with members', async () => {
|
||||
// List groups to get an ID
|
||||
const listResponse = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/agent-groups',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
});
|
||||
|
||||
expect(listResponse.statusCode).toBe(200);
|
||||
const groups = JSON.parse(listResponse.body);
|
||||
expect(groups.length).toBeGreaterThanOrEqual(2);
|
||||
|
||||
const groupId = groups[0].id;
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/agent-groups/${groupId}`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.id).toBe(groupId);
|
||||
expect(body.members).toBeDefined();
|
||||
expect(Array.isArray(body.members)).toBe(true);
|
||||
});
|
||||
|
||||
it('executes group run — queues a job and returns 202 with jobId', async () => {
|
||||
const listResponse = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/agent-groups',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
});
|
||||
const groups = JSON.parse(listResponse.body);
|
||||
const groupId = groups[0].id;
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/agent-groups/${groupId}/run`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
task: 'Research the latest AI papers',
|
||||
teamId,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(202);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.jobId).toBeDefined();
|
||||
expect(typeof body.jobId).toBe('string');
|
||||
|
||||
// Verify the job was created in the database
|
||||
const [job] = await server.db
|
||||
.select()
|
||||
.from(agentJobs)
|
||||
.where(eq(agentJobs.id, body.jobId))
|
||||
.limit(1);
|
||||
expect(job).toBeDefined();
|
||||
expect(job.status).toBe('queued');
|
||||
expect(job.jobType).toBe('group');
|
||||
expect(job.userId).toBe(user1Id);
|
||||
});
|
||||
|
||||
it('rejects an owned group run attributed to a foreign team', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/agent-groups/${group1Id}/run`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: { task: 'Cross-tenant run', teamId: team2Id },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(JSON.parse(response.body)).toEqual({ error: 'Team not found' });
|
||||
});
|
||||
|
||||
it('rejects generic job submission for a foreign team', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/jobs',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: { jobType: 'chat', teamId: team2Id, input: { message: 'Cross-tenant job' } },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(JSON.parse(response.body)).toEqual({ error: 'Team not found' });
|
||||
});
|
||||
|
||||
it('rejects a generic group job that references another user\'s group', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/jobs',
|
||||
headers: { 'x-test-user-id': user2Id },
|
||||
payload: {
|
||||
jobType: 'group',
|
||||
teamId: team2Id,
|
||||
input: { groupId: group1Id, taskInput: { task: 'Run foreign group' } },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(JSON.parse(response.body)).toEqual({ error: 'Agent group not found' });
|
||||
});
|
||||
|
||||
it('hides job status from users outside the job team while preserving member access', async () => {
|
||||
const createResponse = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/jobs',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: { jobType: 'chat', teamId, input: { message: 'Private job' } },
|
||||
});
|
||||
expect(createResponse.statusCode).toBe(202);
|
||||
const { jobId } = JSON.parse(createResponse.body);
|
||||
|
||||
const foreignResponse = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/jobs/${jobId}`,
|
||||
headers: { 'x-test-user-id': user2Id },
|
||||
});
|
||||
expect(foreignResponse.statusCode).toBe(404);
|
||||
expect(JSON.parse(foreignResponse.body)).toEqual({ error: 'Job not found' });
|
||||
|
||||
const memberResponse = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/jobs/${jobId}`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
});
|
||||
expect(memberResponse.statusCode).toBe(200);
|
||||
expect(JSON.parse(memberResponse.body).id).toBe(jobId);
|
||||
});
|
||||
|
||||
it('prevents users outside the job team from cancelling it', async () => {
|
||||
const createResponse = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/jobs',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: { jobType: 'chat', teamId, input: { message: 'Do not cancel' } },
|
||||
});
|
||||
expect(createResponse.statusCode).toBe(202);
|
||||
const { jobId } = JSON.parse(createResponse.body);
|
||||
|
||||
const foreignResponse = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/jobs/${jobId}/cancel`,
|
||||
headers: { 'x-test-user-id': user2Id },
|
||||
});
|
||||
expect(foreignResponse.statusCode).toBe(404);
|
||||
expect(JSON.parse(foreignResponse.body)).toEqual({ error: 'Job not found' });
|
||||
|
||||
const [unchanged] = await server.db
|
||||
.select()
|
||||
.from(agentJobs)
|
||||
.where(eq(agentJobs.id, jobId))
|
||||
.limit(1);
|
||||
expect(unchanged.status).toBe('queued');
|
||||
|
||||
const memberResponse = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/jobs/${jobId}/cancel`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
});
|
||||
expect(memberResponse.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('fails closed when a legacy group contains a foreign-owned agent', async () => {
|
||||
const [legacyGroup] = await server.db.insert(agentGroups).values({
|
||||
userId: user1Id,
|
||||
name: 'Legacy compromised group',
|
||||
strategy: 'parallel',
|
||||
}).returning();
|
||||
await server.db.insert(agentGroupMembers).values({
|
||||
groupId: legacyGroup.id,
|
||||
agentId: foreignAgentId,
|
||||
roleInGroup: 'worker',
|
||||
executionOrder: 0,
|
||||
});
|
||||
|
||||
const getResponse = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/agent-groups/${legacyGroup.id}`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
});
|
||||
const patchResponse = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/agent-groups/${legacyGroup.id}`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: { name: 'Preserved compromise' },
|
||||
});
|
||||
const runResponse = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/agent-groups/${legacyGroup.id}/run`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: { task: 'Run foreign configuration', teamId },
|
||||
});
|
||||
const jobResponse = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/jobs',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
payload: {
|
||||
jobType: 'group',
|
||||
teamId,
|
||||
input: { groupId: legacyGroup.id, taskInput: { task: 'Run foreign configuration' } },
|
||||
},
|
||||
});
|
||||
|
||||
for (const response of [getResponse, patchResponse, runResponse, jobResponse]) {
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(JSON.parse(response.body)).toEqual({ error: 'Agent group not found' });
|
||||
}
|
||||
|
||||
const [unchanged] = await server.db
|
||||
.select()
|
||||
.from(agentGroups)
|
||||
.where(eq(agentGroups.id, legacyGroup.id))
|
||||
.limit(1);
|
||||
expect(unchanged.name).toBe('Legacy compromised group');
|
||||
});
|
||||
|
||||
it('deletes an agent', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/agents/${agent2Id}`,
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
|
||||
// Verify it's gone
|
||||
const listResponse = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/agents',
|
||||
headers: { 'x-test-user-id': user1Id },
|
||||
});
|
||||
const remaining = JSON.parse(listResponse.body);
|
||||
const ids = remaining.map((a: { id: string }) => a.id);
|
||||
expect(ids).not.toContain(agent2Id);
|
||||
});
|
||||
});
|
||||
261
packages/team-server/tests/routes/analytics.test.ts
Normal file
261
packages/team-server/tests/routes/analytics.test.ts
Normal file
@@ -0,0 +1,261 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import { users, teams, teamMembers, agentAuditLog, agentJobs, teamCapabilityRequests } from '../../src/db/schema.js';
|
||||
import { sql } from 'drizzle-orm';
|
||||
|
||||
describe('Analytics API', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let ownerId: string;
|
||||
let memberId: string;
|
||||
let teamId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up any leftover test data
|
||||
await server.db.execute(sql`DELETE FROM agent_audit_log WHERE agent_name = 'analytics-test'`);
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE job_type = 'analytics-test'`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE justification = 'analytics-test'`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug = 'test-analytics')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug = 'test-analytics')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug = 'test-analytics'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'antest_%'`);
|
||||
|
||||
// Create test users
|
||||
const [owner] = await server.db.insert(users).values({
|
||||
clerkId: 'antest_owner',
|
||||
displayName: 'Analytics Owner',
|
||||
email: 'analytics-owner@test.com',
|
||||
}).returning();
|
||||
ownerId = owner.id;
|
||||
|
||||
const [member] = await server.db.insert(users).values({
|
||||
clerkId: 'antest_member',
|
||||
displayName: 'Analytics Member',
|
||||
email: 'analytics-member@test.com',
|
||||
}).returning();
|
||||
memberId = member.id;
|
||||
|
||||
// Create team
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'Analytics Test Team',
|
||||
slug: 'test-analytics',
|
||||
ownerId,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
|
||||
// Add members
|
||||
await server.db.insert(teamMembers).values([
|
||||
{ teamId, userId: ownerId, role: 'owner' },
|
||||
{ teamId, userId: memberId, role: 'member' },
|
||||
]);
|
||||
|
||||
// Override auth handler for tests
|
||||
server._authHandler.fn = async function (request, reply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM agent_audit_log WHERE agent_name = 'analytics-test'`);
|
||||
await server.db.execute(sql`DELETE FROM agent_jobs WHERE job_type = 'analytics-test'`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE justification = 'analytics-test'`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug = 'test-analytics')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug = 'test-analytics')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug = 'test-analytics'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'antest_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('GET /api/admin/teams/:slug/analytics returns correct shape with zeroes for empty data', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/admin/teams/test-analytics/analytics',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
|
||||
// Verify top-level shape
|
||||
expect(body).toHaveProperty('activeUsers');
|
||||
expect(body).toHaveProperty('tokenUsage');
|
||||
expect(body).toHaveProperty('topTools');
|
||||
expect(body).toHaveProperty('topCommands');
|
||||
expect(body).toHaveProperty('capabilityGaps');
|
||||
expect(body).toHaveProperty('performanceTrends');
|
||||
|
||||
// activeUsers shape
|
||||
expect(body.activeUsers).toHaveProperty('daily');
|
||||
expect(body.activeUsers).toHaveProperty('weekly');
|
||||
expect(body.activeUsers).toHaveProperty('monthly');
|
||||
expect(typeof body.activeUsers.daily).toBe('number');
|
||||
expect(typeof body.activeUsers.weekly).toBe('number');
|
||||
expect(typeof body.activeUsers.monthly).toBe('number');
|
||||
|
||||
// tokenUsage shape
|
||||
expect(typeof body.tokenUsage.total).toBe('number');
|
||||
expect(Array.isArray(body.tokenUsage.byUser)).toBe(true);
|
||||
|
||||
// topTools and topCommands are arrays
|
||||
expect(Array.isArray(body.topTools)).toBe(true);
|
||||
expect(Array.isArray(body.topCommands)).toBe(true);
|
||||
expect(Array.isArray(body.capabilityGaps)).toBe(true);
|
||||
|
||||
// performanceTrends shape
|
||||
expect(typeof body.performanceTrends.correctionRate).toBe('number');
|
||||
expect(typeof body.performanceTrends.correctionTrend).toBe('number');
|
||||
expect(typeof body.performanceTrends.avgResponseTime).toBe('number');
|
||||
|
||||
// With no activity, everything should be zeroes
|
||||
expect(body.activeUsers.daily).toBe(0);
|
||||
expect(body.activeUsers.weekly).toBe(0);
|
||||
expect(body.activeUsers.monthly).toBe(0);
|
||||
expect(body.tokenUsage.total).toBe(0);
|
||||
expect(body.topTools).toHaveLength(0);
|
||||
expect(body.topCommands).toHaveLength(0);
|
||||
expect(body.capabilityGaps).toHaveLength(0);
|
||||
expect(body.performanceTrends.correctionRate).toBe(0);
|
||||
expect(body.performanceTrends.avgResponseTime).toBe(0);
|
||||
});
|
||||
|
||||
it('returns 401 without auth header', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/admin/teams/test-analytics/analytics',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('returns 403 for non-admin member', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/admin/teams/test-analytics/analytics',
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('returns 404 for non-existent team', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/admin/teams/nonexistent-team/analytics',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('returns data when audit log entries exist', async () => {
|
||||
// Insert some audit log entries
|
||||
await server.db.insert(agentAuditLog).values([
|
||||
{
|
||||
userId: ownerId,
|
||||
teamId,
|
||||
agentName: 'analytics-test',
|
||||
actionType: 'web_search',
|
||||
description: 'test search 1',
|
||||
},
|
||||
{
|
||||
userId: ownerId,
|
||||
teamId,
|
||||
agentName: 'analytics-test',
|
||||
actionType: 'web_search',
|
||||
description: 'test search 2',
|
||||
},
|
||||
{
|
||||
userId: ownerId,
|
||||
teamId,
|
||||
agentName: 'analytics-test',
|
||||
actionType: 'save_memory',
|
||||
description: 'test memory save',
|
||||
},
|
||||
{
|
||||
userId: ownerId,
|
||||
teamId,
|
||||
agentName: 'analytics-test',
|
||||
actionType: 'command:/research',
|
||||
description: 'test command',
|
||||
},
|
||||
]);
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/admin/teams/test-analytics/analytics',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
|
||||
// Should detect the active user
|
||||
expect(body.activeUsers.daily).toBeGreaterThanOrEqual(1);
|
||||
expect(body.activeUsers.weekly).toBeGreaterThanOrEqual(1);
|
||||
expect(body.activeUsers.monthly).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Should show top tools
|
||||
expect(body.topTools.length).toBeGreaterThanOrEqual(1);
|
||||
const webSearch = body.topTools.find((t: { name: string }) => t.name === 'web_search');
|
||||
expect(webSearch).toBeDefined();
|
||||
expect(webSearch.invocations).toBeGreaterThanOrEqual(2);
|
||||
|
||||
// Should show top commands
|
||||
expect(body.topCommands.length).toBeGreaterThanOrEqual(1);
|
||||
const research = body.topCommands.find((c: { name: string }) => c.name === '/research');
|
||||
expect(research).toBeDefined();
|
||||
expect(research.count).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('returns capability gaps from pending requests', async () => {
|
||||
// Insert a pending capability request
|
||||
await server.db.insert(teamCapabilityRequests).values({
|
||||
teamId,
|
||||
requestedBy: memberId,
|
||||
capabilityName: 'email_send',
|
||||
capabilityType: 'tool',
|
||||
justification: 'analytics-test',
|
||||
status: 'pending',
|
||||
});
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/admin/teams/test-analytics/analytics',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
|
||||
expect(body.capabilityGaps.length).toBeGreaterThanOrEqual(1);
|
||||
const emailGap = body.capabilityGaps.find((g: { tool: string }) => g.tool === 'email_send');
|
||||
expect(emailGap).toBeDefined();
|
||||
expect(emailGap.requestCount).toBeGreaterThanOrEqual(1);
|
||||
expect(emailGap.suggestion).toContain('email_send');
|
||||
});
|
||||
|
||||
it('includes byUser token estimates in tokenUsage', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/admin/teams/test-analytics/analytics',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
|
||||
// byUser should include team members
|
||||
expect(body.tokenUsage.byUser.length).toBeGreaterThanOrEqual(1);
|
||||
const ownerEntry = body.tokenUsage.byUser.find((u: { userId: string }) => u.userId === ownerId);
|
||||
expect(ownerEntry).toBeDefined();
|
||||
expect(ownerEntry.name).toBe('Analytics Owner');
|
||||
expect(typeof ownerEntry.tokens).toBe('number');
|
||||
expect(typeof ownerEntry.cost).toBe('number');
|
||||
});
|
||||
});
|
||||
191
packages/team-server/tests/routes/capability-governance.test.ts
Normal file
191
packages/team-server/tests/routes/capability-governance.test.ts
Normal file
@@ -0,0 +1,191 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { and, eq, sql } from 'drizzle-orm';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import {
|
||||
messages,
|
||||
teamCapabilityOverrides,
|
||||
teamCapabilityRequests,
|
||||
teamMembers,
|
||||
teams,
|
||||
users,
|
||||
} from '../../src/db/schema.js';
|
||||
|
||||
const SLUG_PREFIX = 'cap-bind-';
|
||||
const MISSING_ID = '00000000-0000-4000-8000-000000000000';
|
||||
|
||||
describe('Capability Governance Routes', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let attackerAdminId: string;
|
||||
let victimOwnerId: string;
|
||||
let attackerTeamId: string;
|
||||
let victimTeamId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
await server.db.execute(sql`DELETE FROM messages WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'}`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'cap_bind_%'`);
|
||||
|
||||
const [attackerAdmin, victimOwner] = await server.db.insert(users).values([
|
||||
{
|
||||
clerkId: 'cap_bind_attacker_admin',
|
||||
displayName: 'Capability Attacker Admin',
|
||||
email: 'cap-bind-attacker@test.invalid',
|
||||
},
|
||||
{
|
||||
clerkId: 'cap_bind_victim_owner',
|
||||
displayName: 'Capability Victim Owner',
|
||||
email: 'cap-bind-victim@test.invalid',
|
||||
},
|
||||
]).returning();
|
||||
attackerAdminId = attackerAdmin.id;
|
||||
victimOwnerId = victimOwner.id;
|
||||
|
||||
const [attackerTeam, victimTeam] = await server.db.insert(teams).values([
|
||||
{ name: 'Capability Attacker Team', slug: `${SLUG_PREFIX}attacker`, ownerId: attackerAdminId },
|
||||
{ name: 'Capability Victim Team', slug: `${SLUG_PREFIX}victim`, ownerId: victimOwnerId },
|
||||
]).returning();
|
||||
attackerTeamId = attackerTeam.id;
|
||||
victimTeamId = victimTeam.id;
|
||||
|
||||
await server.db.insert(teamMembers).values([
|
||||
{ teamId: attackerTeamId, userId: attackerAdminId, role: 'admin' },
|
||||
{ teamId: victimTeamId, userId: victimOwnerId, role: 'owner' },
|
||||
]);
|
||||
|
||||
server._authHandler.fn = async function (request, reply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM messages WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'}`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'cap_bind_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('does not let an authorized admin delete another team\'s override by ID', async () => {
|
||||
const [victimOverride] = await server.db.insert(teamCapabilityOverrides).values({
|
||||
teamId: victimTeamId,
|
||||
capabilityName: 'victim-secret-tool',
|
||||
capabilityType: 'mcp',
|
||||
decision: 'blocked',
|
||||
decidedBy: victimOwnerId,
|
||||
}).returning();
|
||||
|
||||
const foreign = await server.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/teams/${SLUG_PREFIX}attacker/capability-overrides/${victimOverride.id}`,
|
||||
headers: { 'x-test-user-id': attackerAdminId },
|
||||
});
|
||||
const missing = await server.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/teams/${SLUG_PREFIX}attacker/capability-overrides/${MISSING_ID}`,
|
||||
headers: { 'x-test-user-id': attackerAdminId },
|
||||
});
|
||||
|
||||
expect({ statusCode: foreign.statusCode, body: foreign.body }).toEqual({
|
||||
statusCode: missing.statusCode,
|
||||
body: missing.body,
|
||||
});
|
||||
const [stored] = await server.db.select().from(teamCapabilityOverrides).where(and(
|
||||
eq(teamCapabilityOverrides.id, victimOverride.id),
|
||||
eq(teamCapabilityOverrides.teamId, victimTeamId),
|
||||
));
|
||||
expect(stored).toBeDefined();
|
||||
});
|
||||
|
||||
it('still lets a same-team admin delete an override', async () => {
|
||||
const [ownOverride] = await server.db.insert(teamCapabilityOverrides).values({
|
||||
teamId: attackerTeamId,
|
||||
capabilityName: 'attacker-team-tool',
|
||||
capabilityType: 'mcp',
|
||||
decision: 'blocked',
|
||||
decidedBy: attackerAdminId,
|
||||
}).returning();
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/teams/${SLUG_PREFIX}attacker/capability-overrides/${ownOverride.id}`,
|
||||
headers: { 'x-test-user-id': attackerAdminId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
const [stored] = await server.db.select().from(teamCapabilityOverrides).where(eq(teamCapabilityOverrides.id, ownOverride.id));
|
||||
expect(stored).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not let an authorized admin decide another team\'s request by ID', async () => {
|
||||
const [victimRequest] = await server.db.insert(teamCapabilityRequests).values({
|
||||
teamId: victimTeamId,
|
||||
requestedBy: victimOwnerId,
|
||||
capabilityName: 'victim-requested-tool',
|
||||
capabilityType: 'mcp',
|
||||
justification: 'Victim-only request',
|
||||
}).returning();
|
||||
|
||||
const foreign = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${SLUG_PREFIX}attacker/capability-requests/${victimRequest.id}`,
|
||||
headers: { 'x-test-user-id': attackerAdminId },
|
||||
payload: { status: 'rejected', reason: 'cross-team decision attempt' },
|
||||
});
|
||||
const missing = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${SLUG_PREFIX}attacker/capability-requests/${MISSING_ID}`,
|
||||
headers: { 'x-test-user-id': attackerAdminId },
|
||||
payload: { status: 'rejected', reason: 'missing request' },
|
||||
});
|
||||
|
||||
expect({ statusCode: foreign.statusCode, body: foreign.body }).toEqual({
|
||||
statusCode: missing.statusCode,
|
||||
body: missing.body,
|
||||
});
|
||||
const [stored] = await server.db.select().from(teamCapabilityRequests).where(and(
|
||||
eq(teamCapabilityRequests.id, victimRequest.id),
|
||||
eq(teamCapabilityRequests.teamId, victimTeamId),
|
||||
));
|
||||
expect(stored?.status).toBe('pending');
|
||||
expect(stored?.decidedBy).toBeNull();
|
||||
});
|
||||
|
||||
it('still lets a same-team admin decide a pending request', async () => {
|
||||
const [ownRequest] = await server.db.insert(teamCapabilityRequests).values({
|
||||
teamId: attackerTeamId,
|
||||
requestedBy: attackerAdminId,
|
||||
capabilityName: 'attacker-requested-tool',
|
||||
capabilityType: 'mcp',
|
||||
justification: 'Same-team request',
|
||||
}).returning();
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${SLUG_PREFIX}attacker/capability-requests/${ownRequest.id}`,
|
||||
headers: { 'x-test-user-id': attackerAdminId },
|
||||
payload: { status: 'rejected', reason: 'same-team decision' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toMatchObject({
|
||||
id: ownRequest.id,
|
||||
teamId: attackerTeamId,
|
||||
status: 'rejected',
|
||||
decidedBy: attackerAdminId,
|
||||
});
|
||||
});
|
||||
});
|
||||
366
packages/team-server/tests/routes/knowledge.test.ts
Normal file
366
packages/team-server/tests/routes/knowledge.test.ts
Normal file
@@ -0,0 +1,366 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import { users, teams, teamMembers, teamEntities, teamRelations } from '../../src/db/schema.js';
|
||||
import { eq, or, sql } from 'drizzle-orm';
|
||||
|
||||
describe('Team Knowledge Graph API', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let ownerId: string;
|
||||
let memberId: string;
|
||||
let outsiderId: string;
|
||||
let teamSlug: string;
|
||||
let teamId: string;
|
||||
let foreignEntityId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up any leftover test data
|
||||
await server.db.execute(sql`DELETE FROM team_relations WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_entities WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'kgtest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'kgtest_%'`);
|
||||
|
||||
// Create test users
|
||||
const [owner] = await server.db.insert(users).values({
|
||||
clerkId: 'kgtest_owner',
|
||||
displayName: 'KG Owner',
|
||||
email: 'kgtest_owner@test.com',
|
||||
}).returning();
|
||||
ownerId = owner.id;
|
||||
|
||||
const [member] = await server.db.insert(users).values({
|
||||
clerkId: 'kgtest_member',
|
||||
displayName: 'KG Member',
|
||||
email: 'kgtest_member@test.com',
|
||||
}).returning();
|
||||
memberId = member.id;
|
||||
|
||||
const [outsider] = await server.db.insert(users).values({
|
||||
clerkId: 'kgtest_outsider',
|
||||
displayName: 'KG Outsider',
|
||||
email: 'kgtest_outsider@test.com',
|
||||
}).returning();
|
||||
outsiderId = outsider.id;
|
||||
|
||||
// Create a team with owner + member
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'KG Test Team',
|
||||
slug: 'kgtest-knowledge',
|
||||
ownerId,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
teamSlug = team.slug;
|
||||
|
||||
await server.db.insert(teamMembers).values([
|
||||
{ teamId, userId: ownerId, role: 'owner' },
|
||||
{ teamId, userId: memberId, role: 'member' },
|
||||
]);
|
||||
|
||||
const [foreignTeam] = await server.db.insert(teams).values({
|
||||
name: 'Foreign KG Team',
|
||||
slug: 'kgtest-foreign-knowledge',
|
||||
ownerId: outsiderId,
|
||||
}).returning();
|
||||
await server.db.insert(teamMembers).values({
|
||||
teamId: foreignTeam.id,
|
||||
userId: outsiderId,
|
||||
role: 'owner',
|
||||
});
|
||||
const [foreignEntity] = await server.db.insert(teamEntities).values({
|
||||
teamId: foreignTeam.id,
|
||||
entityType: 'secret',
|
||||
name: 'Foreign Entity',
|
||||
properties: { confidential: true },
|
||||
sharedBy: outsiderId,
|
||||
}).returning();
|
||||
foreignEntityId = foreignEntity.id;
|
||||
|
||||
// Override auth handler
|
||||
server._authHandler.fn = async function (request, reply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM team_relations WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_entities WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'kgtest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'kgtest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'kgtest_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('creates an entity with properties and valid_from/valid_to', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
entityType: 'concept',
|
||||
name: 'Machine Learning',
|
||||
properties: { domain: 'AI', level: 'advanced' },
|
||||
validFrom: '2026-01-01T00:00:00.000Z',
|
||||
validTo: '2027-01-01T00:00:00.000Z',
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.entityType).toBe('concept');
|
||||
expect(body.name).toBe('Machine Learning');
|
||||
expect(body.properties).toEqual({ domain: 'AI', level: 'advanced' });
|
||||
expect(body.sharedBy).toBe(ownerId);
|
||||
expect(body.teamId).toBe(teamId);
|
||||
expect(body.validFrom).toBeTruthy();
|
||||
expect(body.validTo).toBeTruthy();
|
||||
});
|
||||
|
||||
it('searches entities by type', async () => {
|
||||
// Create entities of different types
|
||||
await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { entityType: 'person', name: 'Alice' },
|
||||
});
|
||||
await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { entityType: 'person', name: 'Bob' },
|
||||
});
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/entities?type=person`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.length).toBeGreaterThanOrEqual(2);
|
||||
expect(body.every((e: { entityType: string }) => e.entityType === 'person')).toBe(true);
|
||||
});
|
||||
|
||||
it('searches entities by name (ILIKE)', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/entities?search=machine`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.length).toBeGreaterThanOrEqual(1);
|
||||
expect(body.some((e: { name: string }) => e.name === 'Machine Learning')).toBe(true);
|
||||
});
|
||||
|
||||
it('creates a relation with confidence score', async () => {
|
||||
// Create two entities to relate
|
||||
const res1 = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { entityType: 'tool', name: 'TensorFlow' },
|
||||
});
|
||||
const entity1 = JSON.parse(res1.body);
|
||||
|
||||
const res2 = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { entityType: 'concept', name: 'Deep Learning' },
|
||||
});
|
||||
const entity2 = JSON.parse(res2.body);
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/relations`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
sourceId: entity1.id,
|
||||
targetId: entity2.id,
|
||||
relationType: 'implements',
|
||||
confidence: 0.95,
|
||||
properties: { since: '2015' },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.sourceId).toBe(entity1.id);
|
||||
expect(body.targetId).toBe(entity2.id);
|
||||
expect(body.relationType).toBe('implements');
|
||||
expect(body.confidence).toBeCloseTo(0.95);
|
||||
expect(body.teamId).toBe(teamId);
|
||||
});
|
||||
|
||||
it('rejects relations when either endpoint belongs to another team', async () => {
|
||||
const localRes = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { entityType: 'concept', name: 'Local Endpoint' },
|
||||
});
|
||||
const localEntity = localRes.json();
|
||||
|
||||
const foreignSource = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/relations`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
sourceId: foreignEntityId,
|
||||
targetId: localEntity.id,
|
||||
relationType: 'references',
|
||||
},
|
||||
});
|
||||
const foreignTarget = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/relations`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
sourceId: localEntity.id,
|
||||
targetId: foreignEntityId,
|
||||
relationType: 'references',
|
||||
},
|
||||
});
|
||||
|
||||
expect(foreignSource.statusCode).toBe(404);
|
||||
expect(foreignSource.json()).toEqual({ error: 'Entity not found' });
|
||||
expect(foreignTarget.statusCode).toBe(404);
|
||||
expect(foreignTarget.json()).toEqual({ error: 'Entity not found' });
|
||||
|
||||
const leaked = await server.db.select().from(teamRelations).where(or(
|
||||
eq(teamRelations.sourceId, foreignEntityId),
|
||||
eq(teamRelations.targetId, foreignEntityId),
|
||||
));
|
||||
expect(leaked).toEqual([]);
|
||||
});
|
||||
|
||||
it('graph traversal returns connected entities up to depth N', async () => {
|
||||
// Create a chain: A -> B -> C
|
||||
const resA = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { entityType: 'node', name: 'Node-A' },
|
||||
});
|
||||
const nodeA = JSON.parse(resA.body);
|
||||
|
||||
const resB = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { entityType: 'node', name: 'Node-B' },
|
||||
});
|
||||
const nodeB = JSON.parse(resB.body);
|
||||
|
||||
const resC = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { entityType: 'node', name: 'Node-C' },
|
||||
});
|
||||
const nodeC = JSON.parse(resC.body);
|
||||
|
||||
// A -> B
|
||||
await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/relations`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { sourceId: nodeA.id, targetId: nodeB.id, relationType: 'links_to' },
|
||||
});
|
||||
|
||||
// B -> C
|
||||
await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/relations`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { sourceId: nodeB.id, targetId: nodeC.id, relationType: 'links_to' },
|
||||
});
|
||||
|
||||
// Depth 1: should find A and B only
|
||||
const res1 = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/graph?startId=${nodeA.id}&depth=1`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
expect(res1.statusCode).toBe(200);
|
||||
const graph1 = JSON.parse(res1.body);
|
||||
const entityIds1 = graph1.entities.map((e: { id: string }) => e.id);
|
||||
expect(entityIds1).toContain(nodeA.id);
|
||||
expect(entityIds1).toContain(nodeB.id);
|
||||
expect(entityIds1).not.toContain(nodeC.id);
|
||||
|
||||
// Depth 2: should find A, B, and C
|
||||
const res2 = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/graph?startId=${nodeA.id}&depth=2`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
expect(res2.statusCode).toBe(200);
|
||||
const graph2 = JSON.parse(res2.body);
|
||||
const entityIds2 = graph2.entities.map((e: { id: string }) => e.id);
|
||||
expect(entityIds2).toContain(nodeA.id);
|
||||
expect(entityIds2).toContain(nodeB.id);
|
||||
expect(entityIds2).toContain(nodeC.id);
|
||||
expect(graph2.relations.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('does not return a foreign-team graph start entity', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/graph?startId=${foreignEntityId}&depth=1`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(response.json()).toEqual({ error: 'Entity not found' });
|
||||
expect(response.body).not.toContain('Foreign Entity');
|
||||
expect(response.body).not.toContain('confidential');
|
||||
});
|
||||
|
||||
it('shared_by tracks who contributed', async () => {
|
||||
// Owner creates entity
|
||||
const res1 = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { entityType: 'doc', name: 'Owner Doc' },
|
||||
});
|
||||
expect(JSON.parse(res1.body).sharedBy).toBe(ownerId);
|
||||
|
||||
// Member creates entity
|
||||
const res2 = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: { entityType: 'doc', name: 'Member Doc' },
|
||||
});
|
||||
expect(JSON.parse(res2.body).sharedBy).toBe(memberId);
|
||||
});
|
||||
|
||||
it('non-member gets 403', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/entities`,
|
||||
headers: { 'x-test-user-id': outsiderId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
});
|
||||
392
packages/team-server/tests/routes/messages.test.ts
Normal file
392
packages/team-server/tests/routes/messages.test.ts
Normal file
@@ -0,0 +1,392 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import { users, teams, teamMembers, teamEntities, tasks, messages } from '../../src/db/schema.js';
|
||||
import { sql } from 'drizzle-orm';
|
||||
|
||||
describe('Waggle Dance Messages API', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let ownerId: string;
|
||||
let memberId: string;
|
||||
let outsiderId: string;
|
||||
let teamSlug: string;
|
||||
let teamId: string;
|
||||
|
||||
const SLUG_PREFIX = 'msgtest-';
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up any leftover test data (order matters for FK constraints)
|
||||
await server.db.execute(sql`DELETE FROM messages WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_entities WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM tasks WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'}`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'msgtest_%'`);
|
||||
|
||||
// Create test users
|
||||
const [owner] = await server.db.insert(users).values({
|
||||
clerkId: 'msgtest_owner',
|
||||
displayName: 'Msg Owner',
|
||||
email: 'msgtest_owner@test.com',
|
||||
}).returning();
|
||||
ownerId = owner.id;
|
||||
|
||||
const [member] = await server.db.insert(users).values({
|
||||
clerkId: 'msgtest_member',
|
||||
displayName: 'Msg Member',
|
||||
email: 'msgtest_member@test.com',
|
||||
}).returning();
|
||||
memberId = member.id;
|
||||
|
||||
const [outsider] = await server.db.insert(users).values({
|
||||
clerkId: 'msgtest_outsider',
|
||||
displayName: 'Msg Outsider',
|
||||
email: 'msgtest_outsider@test.com',
|
||||
}).returning();
|
||||
outsiderId = outsider.id;
|
||||
|
||||
// Create a team with owner + member
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'Msg Test Team',
|
||||
slug: `${SLUG_PREFIX}waggle`,
|
||||
ownerId,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
teamSlug = team.slug;
|
||||
|
||||
await server.db.insert(teamMembers).values([
|
||||
{ teamId, userId: ownerId, role: 'owner' },
|
||||
{ teamId, userId: memberId, role: 'member' },
|
||||
]);
|
||||
|
||||
// Seed some team_entities and tasks for hive-check tests
|
||||
await server.db.insert(teamEntities).values([
|
||||
{ teamId, entityType: 'concept', name: 'Machine Learning', properties: { domain: 'AI' }, sharedBy: ownerId },
|
||||
{ teamId, entityType: 'tool', name: 'TensorFlow', properties: { lang: 'python' }, sharedBy: memberId },
|
||||
{ teamId, entityType: 'concept', name: 'Database Design', properties: { domain: 'engineering' }, sharedBy: ownerId },
|
||||
]);
|
||||
|
||||
await server.db.insert(tasks).values([
|
||||
{ teamId, title: 'Implement ML pipeline', description: 'Build a machine learning pipeline', status: 'open', createdBy: ownerId },
|
||||
{ teamId, title: 'Fix login bug', description: 'Login page crashes on mobile', status: 'done', createdBy: memberId },
|
||||
]);
|
||||
|
||||
// Override auth handler
|
||||
server._authHandler.fn = async function (request, reply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM messages WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_entities WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM tasks WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'})`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE ${SLUG_PREFIX + '%'}`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'msgtest_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('sends a broadcast message and returns 201', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
type: 'broadcast',
|
||||
subtype: 'discovery',
|
||||
content: { topic: 'New skill available', details: 'web-scraper v2' },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.type).toBe('broadcast');
|
||||
expect(body.subtype).toBe('discovery');
|
||||
expect(body.content).toEqual({ topic: 'New skill available', details: 'web-scraper v2' });
|
||||
expect(body.senderId).toBe(ownerId);
|
||||
expect(body.teamId).toBe(teamId);
|
||||
expect(body.id).toBeDefined();
|
||||
});
|
||||
|
||||
it('sends a request message with valid type-subtype combo', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: {
|
||||
type: 'request',
|
||||
subtype: 'knowledge_check',
|
||||
content: { query: 'Who knows about React?' },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.type).toBe('request');
|
||||
expect(body.subtype).toBe('knowledge_check');
|
||||
});
|
||||
|
||||
it('rejects invalid type-subtype combination with 400', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
type: 'request',
|
||||
subtype: 'discovery', // discovery is a broadcast subtype, not request
|
||||
content: { query: 'test' },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.error).toContain('Invalid type-subtype combination');
|
||||
});
|
||||
|
||||
it('stores routing field when provided', async () => {
|
||||
const routing = [
|
||||
{ userId: memberId, reason: 'Expert in ML' },
|
||||
];
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
type: 'broadcast',
|
||||
subtype: 'routed_share',
|
||||
content: { data: 'ML model results' },
|
||||
routing,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.routing).toEqual(routing);
|
||||
});
|
||||
|
||||
it('stores referenceId when provided', async () => {
|
||||
// First create a message to reference
|
||||
const firstRes = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: {
|
||||
type: 'request',
|
||||
subtype: 'task_delegation',
|
||||
content: { task: 'Review PR #42' },
|
||||
},
|
||||
});
|
||||
const firstMsg = JSON.parse(firstRes.body);
|
||||
|
||||
// Send a response referencing the first message
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
type: 'response',
|
||||
subtype: 'task_claim',
|
||||
content: { accepted: true },
|
||||
referenceId: firstMsg.id,
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.referenceId).toBe(firstMsg.id);
|
||||
});
|
||||
|
||||
it('lists messages for the team', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('filters messages by type', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/messages?type=broadcast`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.every((m: { type: string }) => m.type === 'broadcast')).toBe(true);
|
||||
expect(body.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('filters messages by subtype', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/messages?subtype=discovery`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.every((m: { subtype: string }) => m.subtype === 'discovery')).toBe(true);
|
||||
});
|
||||
|
||||
it('publishes message to Redis channel on send', async () => {
|
||||
// Subscribe to the team channel before sending
|
||||
const receivedMessages: string[] = [];
|
||||
await server.redisSub.subscribe(`team:${teamId}:waggle`);
|
||||
server.redisSub.on('message', (_channel: string, message: string) => {
|
||||
receivedMessages.push(message);
|
||||
});
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
type: 'broadcast',
|
||||
subtype: 'skill_share',
|
||||
content: { skill: 'data-analysis', version: '1.0' },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
|
||||
// Give Redis a moment to deliver
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
|
||||
expect(receivedMessages.length).toBeGreaterThanOrEqual(1);
|
||||
const published = JSON.parse(receivedMessages[receivedMessages.length - 1]);
|
||||
expect(published.subtype).toBe('skill_share');
|
||||
expect(published.content).toEqual({ skill: 'data-analysis', version: '1.0' });
|
||||
|
||||
// Cleanup subscription
|
||||
await server.redisSub.unsubscribe(`team:${teamId}:waggle`);
|
||||
server.redisSub.removeAllListeners('message');
|
||||
});
|
||||
|
||||
it('non-member gets 403 when sending messages', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': outsiderId },
|
||||
payload: {
|
||||
type: 'broadcast',
|
||||
subtype: 'discovery',
|
||||
content: { test: true },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('non-member gets 403 when listing messages', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/messages`,
|
||||
headers: { 'x-test-user-id': outsiderId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
describe('hive-check', () => {
|
||||
it('finds matching entities by topic', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages/hive-check`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { topic: 'Machine Learning' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.entities.length).toBeGreaterThanOrEqual(1);
|
||||
expect(body.entities.some((e: { name: string }) => e.name === 'Machine Learning')).toBe(true);
|
||||
});
|
||||
|
||||
it('finds matching tasks by topic', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages/hive-check`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: { topic: 'ML pipeline' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.relatedTasks.length).toBeGreaterThanOrEqual(1);
|
||||
expect(body.relatedTasks.some((t: { title: string }) => t.title.includes('ML pipeline'))).toBe(true);
|
||||
});
|
||||
|
||||
it('finds matching broadcast messages', async () => {
|
||||
// We already sent broadcast messages earlier in the test suite
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages/hive-check`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { topic: 'anything' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.relatedMessages).toBeDefined();
|
||||
expect(Array.isArray(body.relatedMessages)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns empty results for non-matching topic', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages/hive-check`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { topic: 'xyzzy_nonexistent_topic_12345' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.entities).toHaveLength(0);
|
||||
expect(body.relatedTasks).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('non-member gets 403 on hive-check', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages/hive-check`,
|
||||
headers: { 'x-test-user-id': outsiderId },
|
||||
payload: { topic: 'test' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('validates hive-check input', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/messages/hive-check`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {}, // missing topic
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
});
|
||||
263
packages/team-server/tests/routes/resources.test.ts
Normal file
263
packages/team-server/tests/routes/resources.test.ts
Normal file
@@ -0,0 +1,263 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import { users, teams, teamMembers, teamResources } from '../../src/db/schema.js';
|
||||
import { eq, sql } from 'drizzle-orm';
|
||||
|
||||
describe('Team Resources API', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let ownerId: string;
|
||||
let memberId: string;
|
||||
let outsiderId: string;
|
||||
let teamSlug: string;
|
||||
let teamId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up any leftover test data
|
||||
await server.db.execute(sql`DELETE FROM team_resources WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'restest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'restest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'restest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'restest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'restest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'restest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'restest_%'`);
|
||||
|
||||
// Create test users
|
||||
const [owner] = await server.db.insert(users).values({
|
||||
clerkId: 'restest_owner',
|
||||
displayName: 'Res Owner',
|
||||
email: 'restest_owner@test.com',
|
||||
}).returning();
|
||||
ownerId = owner.id;
|
||||
|
||||
const [member] = await server.db.insert(users).values({
|
||||
clerkId: 'restest_member',
|
||||
displayName: 'Res Member',
|
||||
email: 'restest_member@test.com',
|
||||
}).returning();
|
||||
memberId = member.id;
|
||||
|
||||
const [outsider] = await server.db.insert(users).values({
|
||||
clerkId: 'restest_outsider',
|
||||
displayName: 'Res Outsider',
|
||||
email: 'restest_outsider@test.com',
|
||||
}).returning();
|
||||
outsiderId = outsider.id;
|
||||
|
||||
// Create a team with owner + member
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'Res Test Team',
|
||||
slug: 'restest-resources',
|
||||
ownerId,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
teamSlug = team.slug;
|
||||
|
||||
await server.db.insert(teamMembers).values([
|
||||
{ teamId, userId: ownerId, role: 'owner' },
|
||||
{ teamId, userId: memberId, role: 'member' },
|
||||
]);
|
||||
|
||||
// Override auth handler
|
||||
server._authHandler.fn = async function (request, reply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM team_resources WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'restest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'restest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'restest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'restest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'restest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'restest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'restest_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('shares a model_recipe resource', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/resources`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
resourceType: 'model_recipe',
|
||||
name: 'GPT-4 Coding Recipe',
|
||||
description: 'Optimized for code generation',
|
||||
config: { model: 'gpt-4', temperature: 0.2 },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.resourceType).toBe('model_recipe');
|
||||
expect(body.name).toBe('GPT-4 Coding Recipe');
|
||||
expect(body.description).toBe('Optimized for code generation');
|
||||
expect(body.config).toEqual({ model: 'gpt-4', temperature: 0.2 });
|
||||
expect(body.sharedBy).toBe(ownerId);
|
||||
expect(body.rating).toBe(0);
|
||||
expect(body.useCount).toBe(0);
|
||||
});
|
||||
|
||||
it('shares a skill resource', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/resources`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: {
|
||||
resourceType: 'skill',
|
||||
name: 'Code Review Skill',
|
||||
description: 'Automated code review with best practices',
|
||||
config: { language: 'typescript', rules: ['no-any', 'strict-null'] },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.resourceType).toBe('skill');
|
||||
expect(body.name).toBe('Code Review Skill');
|
||||
expect(body.sharedBy).toBe(memberId);
|
||||
});
|
||||
|
||||
it('rates a resource and updates running average', async () => {
|
||||
// Create a resource first
|
||||
const createRes = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/resources`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
resourceType: 'prompt_template',
|
||||
name: 'Summarizer Prompt',
|
||||
config: { template: 'Summarize: {{input}}' },
|
||||
},
|
||||
});
|
||||
const resource = JSON.parse(createRes.body);
|
||||
|
||||
// First rating: should be the rating itself (useCount was 0)
|
||||
const rate1 = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${teamSlug}/resources/${resource.id}`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { rating: 4 },
|
||||
});
|
||||
expect(rate1.statusCode).toBe(200);
|
||||
const body1 = JSON.parse(rate1.body);
|
||||
// After first rate: rating was set to 4 (useCount was 0), then useCount incremented to 1
|
||||
expect(body1.useCount).toBe(1);
|
||||
|
||||
// Second rating: running average = (4 * 1 + 2) / 2 = 3
|
||||
const rate2 = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${teamSlug}/resources/${resource.id}`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: { rating: 2 },
|
||||
});
|
||||
expect(rate2.statusCode).toBe(200);
|
||||
const body2 = JSON.parse(rate2.body);
|
||||
expect(body2.useCount).toBe(2);
|
||||
// rating = (4 * 1 + 2) / 2 = 3
|
||||
expect(body2.rating).toBeCloseTo(3, 1);
|
||||
});
|
||||
|
||||
it('increments use_count on rate', async () => {
|
||||
const createRes = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/resources`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: {
|
||||
resourceType: 'tool_config',
|
||||
name: 'Linter Config',
|
||||
config: { tool: 'eslint', extends: 'recommended' },
|
||||
},
|
||||
});
|
||||
const resource = JSON.parse(createRes.body);
|
||||
expect(resource.useCount).toBe(0);
|
||||
|
||||
// Rate it
|
||||
const rateRes = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${teamSlug}/resources/${resource.id}`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: { rating: 5 },
|
||||
});
|
||||
const rated = JSON.parse(rateRes.body);
|
||||
expect(rated.useCount).toBe(1);
|
||||
|
||||
// Rate again
|
||||
const rateRes2 = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${teamSlug}/resources/${resource.id}`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { rating: 3 },
|
||||
});
|
||||
const rated2 = JSON.parse(rateRes2.body);
|
||||
expect(rated2.useCount).toBe(2);
|
||||
});
|
||||
|
||||
it('does not rate a resource owned by another team through this team route', async () => {
|
||||
const [foreignTeam] = await server.db.insert(teams).values({
|
||||
name: 'Foreign Resource Team',
|
||||
slug: 'restest-foreign-resources',
|
||||
ownerId: outsiderId,
|
||||
}).returning();
|
||||
await server.db.insert(teamMembers).values({
|
||||
teamId: foreignTeam.id,
|
||||
userId: outsiderId,
|
||||
role: 'owner',
|
||||
});
|
||||
const [foreignResource] = await server.db.insert(teamResources).values({
|
||||
teamId: foreignTeam.id,
|
||||
resourceType: 'model_recipe',
|
||||
name: 'Foreign Recipe',
|
||||
config: { model: 'private-model' },
|
||||
sharedBy: outsiderId,
|
||||
rating: 1,
|
||||
useCount: 1,
|
||||
}).returning();
|
||||
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${teamSlug}/resources/${foreignResource.id}`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { rating: 5 },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(response.json()).toEqual({ error: 'Resource not found' });
|
||||
|
||||
const [unchanged] = await server.db.select().from(teamResources)
|
||||
.where(eq(teamResources.id, foreignResource.id));
|
||||
expect(unchanged.rating).toBe(1);
|
||||
expect(unchanged.useCount).toBe(1);
|
||||
});
|
||||
|
||||
it('filters resources by resource_type', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/resources?type=skill`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.length).toBeGreaterThanOrEqual(1);
|
||||
expect(body.every((r: { resourceType: string }) => r.resourceType === 'skill')).toBe(true);
|
||||
});
|
||||
|
||||
it('non-member gets 403', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/resources`,
|
||||
headers: { 'x-test-user-id': outsiderId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
});
|
||||
210
packages/team-server/tests/routes/tasks.test.ts
Normal file
210
packages/team-server/tests/routes/tasks.test.ts
Normal file
@@ -0,0 +1,210 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import { users, teams, teamMembers, tasks } from '../../src/db/schema.js';
|
||||
import { sql } from 'drizzle-orm';
|
||||
|
||||
describe('Task Board API', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let ownerId: string;
|
||||
let memberId: string;
|
||||
let outsiderId: string;
|
||||
let teamSlug: string;
|
||||
let teamId: string;
|
||||
let createdTaskId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up any leftover test data
|
||||
await server.db.execute(sql`DELETE FROM tasks WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'tstest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'tstest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'tstest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'tstest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'tstest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'tstest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'tstest_%'`);
|
||||
|
||||
// Create test users
|
||||
const [owner] = await server.db.insert(users).values({
|
||||
clerkId: 'tstest_owner',
|
||||
displayName: 'Task Owner',
|
||||
email: 'tstest_owner@test.com',
|
||||
}).returning();
|
||||
ownerId = owner.id;
|
||||
|
||||
const [member] = await server.db.insert(users).values({
|
||||
clerkId: 'tstest_member',
|
||||
displayName: 'Task Member',
|
||||
email: 'tstest_member@test.com',
|
||||
}).returning();
|
||||
memberId = member.id;
|
||||
|
||||
const [outsider] = await server.db.insert(users).values({
|
||||
clerkId: 'tstest_outsider',
|
||||
displayName: 'Task Outsider',
|
||||
email: 'tstest_outsider@test.com',
|
||||
}).returning();
|
||||
outsiderId = outsider.id;
|
||||
|
||||
// Create a team with owner + member
|
||||
const [team] = await server.db.insert(teams).values({
|
||||
name: 'Task Test Team',
|
||||
slug: 'tstest-tasks',
|
||||
ownerId,
|
||||
}).returning();
|
||||
teamId = team.id;
|
||||
teamSlug = team.slug;
|
||||
|
||||
await server.db.insert(teamMembers).values([
|
||||
{ teamId, userId: ownerId, role: 'owner' },
|
||||
{ teamId, userId: memberId, role: 'member' },
|
||||
]);
|
||||
|
||||
// Override auth handler
|
||||
server._authHandler.fn = async function (request, reply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await server.db.execute(sql`DELETE FROM tasks WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'tstest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'tstest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'tstest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'tstest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'tstest-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'tstest-%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'tstest_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('creates a task on team board', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/tasks`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { title: 'Research competitors', description: 'Analyze top 5 competitors', priority: 'high' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.title).toBe('Research competitors');
|
||||
expect(body.description).toBe('Analyze top 5 competitors');
|
||||
expect(body.priority).toBe('high');
|
||||
expect(body.status).toBe('open');
|
||||
expect(body.createdBy).toBe(ownerId);
|
||||
expect(body.teamId).toBe(teamId);
|
||||
createdTaskId = body.id;
|
||||
});
|
||||
|
||||
it('lists tasks on team board', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/tasks`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
expect(body.length).toBeGreaterThanOrEqual(1);
|
||||
expect(body.some((t: { id: string }) => t.id === createdTaskId)).toBe(true);
|
||||
});
|
||||
|
||||
it('lists tasks with status filter', async () => {
|
||||
// Create a second task and mark it done
|
||||
const createRes = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/tasks`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { title: 'Done task' },
|
||||
});
|
||||
const doneTask = JSON.parse(createRes.body);
|
||||
|
||||
await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${teamSlug}/tasks/${doneTask.id}`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { status: 'done' },
|
||||
});
|
||||
|
||||
// Filter by status=open
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/tasks?status=open`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.every((t: { status: string }) => t.status === 'open')).toBe(true);
|
||||
expect(body.some((t: { id: string }) => t.id === doneTask.id)).toBe(false);
|
||||
});
|
||||
|
||||
it('claims a task — sets assignedTo and status to claimed', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/tasks/${createdTaskId}/claim`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.assignedTo).toBe(memberId);
|
||||
expect(body.status).toBe('claimed');
|
||||
});
|
||||
|
||||
it('completes a task — status changes to done', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/${teamSlug}/tasks/${createdTaskId}`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: { status: 'done' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.status).toBe('done');
|
||||
});
|
||||
|
||||
it('creates a subtask with parentTaskId', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: `/api/teams/${teamSlug}/tasks`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { title: 'Sub-research item', parentTaskId: createdTaskId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.parentTaskId).toBe(createdTaskId);
|
||||
expect(body.priority).toBe('normal');
|
||||
});
|
||||
|
||||
it('non-team-member gets 403', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/tasks`,
|
||||
headers: { 'x-test-user-id': outsiderId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('gets a single task by id', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: `/api/teams/${teamSlug}/tasks/${createdTaskId}`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.id).toBe(createdTaskId);
|
||||
expect(body.title).toBe('Research competitors');
|
||||
});
|
||||
});
|
||||
304
packages/team-server/tests/routes/teams.test.ts
Normal file
304
packages/team-server/tests/routes/teams.test.ts
Normal file
@@ -0,0 +1,304 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { buildServer } from '../../src/index.js';
|
||||
import { users, teams, teamMembers } from '../../src/db/schema.js';
|
||||
import { sql } from 'drizzle-orm';
|
||||
|
||||
describe('Team API', () => {
|
||||
let server: Awaited<ReturnType<typeof buildServer>>;
|
||||
let ownerId: string;
|
||||
let memberId: string;
|
||||
let adminId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await buildServer();
|
||||
|
||||
// Clean up any leftover test data (use unique prefix to avoid collision with auth tests)
|
||||
// Narrow to 'test-team%' — previously 'test-%' collided with analytics.test.ts's
|
||||
// 'test-analytics' slug when files ran in parallel and wiped it mid-run, causing
|
||||
// spurious 403s because the analytics team's owner was no longer a member.
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'test-team%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'test-team%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'test-team%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'test-team%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'test-team%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'tmtest_%'`);
|
||||
|
||||
// Create test users directly in DB (clerk IDs use 'tmtest_' prefix to avoid auth test cleanup)
|
||||
const [owner] = await server.db.insert(users).values({
|
||||
clerkId: 'tmtest_owner',
|
||||
displayName: 'Team Owner',
|
||||
email: 'teamowner@test.com',
|
||||
}).returning();
|
||||
ownerId = owner.id;
|
||||
|
||||
const [member] = await server.db.insert(users).values({
|
||||
clerkId: 'tmtest_member',
|
||||
displayName: 'Team Member',
|
||||
email: 'teammember@test.com',
|
||||
}).returning();
|
||||
memberId = member.id;
|
||||
|
||||
const [admin] = await server.db.insert(users).values({
|
||||
clerkId: 'tmtest_admin',
|
||||
displayName: 'Team Admin',
|
||||
email: 'teamadmin@test.com',
|
||||
}).returning();
|
||||
adminId = admin.id;
|
||||
|
||||
// Override auth handler to use x-test-user-id header (via indirection object)
|
||||
server._authHandler.fn = async function (request, reply) {
|
||||
const testUserId = request.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
return reply.code(401).send({ error: 'Missing x-test-user-id header' });
|
||||
}
|
||||
request.userId = testUserId;
|
||||
request.clerkId = 'test';
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
// Narrow to 'test-team%' — previously 'test-%' collided with analytics.test.ts's
|
||||
// 'test-analytics' slug when files ran in parallel and wiped it mid-run, causing
|
||||
// spurious 403s because the analytics team's owner was no longer a member.
|
||||
await server.db.execute(sql`DELETE FROM team_members WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'test-team%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'test-team%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'test-team%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'test-team%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'test-team%'`);
|
||||
await server.db.execute(sql`DELETE FROM users WHERE clerk_id LIKE 'tmtest_%'`);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('creates a team and auto-adds owner as member with role owner', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/teams',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { name: 'Test Team', slug: 'test-team-crud' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.name).toBe('Test Team');
|
||||
expect(body.slug).toBe('test-team-crud');
|
||||
expect(body.ownerId).toBe(ownerId);
|
||||
|
||||
// Verify owner membership
|
||||
const [membership] = await server.db
|
||||
.select()
|
||||
.from(teamMembers)
|
||||
.where(sql`team_id = ${body.id} AND user_id = ${ownerId}`);
|
||||
expect(membership).toBeDefined();
|
||||
expect(membership.role).toBe('owner');
|
||||
});
|
||||
|
||||
it('returns 409 on duplicate slug', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/teams',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { name: 'Another Team', slug: 'test-team-crud' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
});
|
||||
|
||||
it('lists only teams the user belongs to', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/teams',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(Array.isArray(body)).toBe(true);
|
||||
const slugs = body.map((t: { slug: string }) => t.slug);
|
||||
expect(slugs).toContain('test-team-crud');
|
||||
});
|
||||
|
||||
it('non-member gets empty list', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/teams',
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
// memberId is not a member of any team with test- slug yet
|
||||
const testTeams = body.filter((t: { slug: string }) => t.slug.startsWith('test-'));
|
||||
expect(testTeams).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('gets team by slug with members', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/teams/test-team-crud',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.slug).toBe('test-team-crud');
|
||||
expect(body.members).toBeDefined();
|
||||
expect(body.members.length).toBeGreaterThanOrEqual(1);
|
||||
expect(body.members[0].displayName).toBe('Team Owner');
|
||||
});
|
||||
|
||||
it('non-member gets 403 when accessing team', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/teams/test-team-crud',
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('adds a member via invite (admin+)', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/teams/test-team-crud/members',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { email: 'teammember@test.com', role: 'member' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.userId).toBe(memberId);
|
||||
expect(body.role).toBe('member');
|
||||
});
|
||||
|
||||
it('returns 409 when inviting existing member', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/teams/test-team-crud/members',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { email: 'teammember@test.com', role: 'member' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
});
|
||||
|
||||
it('adds an admin member', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'POST',
|
||||
url: '/api/teams/test-team-crud/members',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
payload: { email: 'teamadmin@test.com', role: 'admin' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.role).toBe('admin');
|
||||
});
|
||||
|
||||
it('member can update own roleDescription and interests', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/test-team-crud/members/${memberId}`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: {
|
||||
roleDescription: 'Frontend developer',
|
||||
interests: ['React', 'TypeScript'],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.roleDescription).toBe('Frontend developer');
|
||||
expect(body.interests).toEqual(['React', 'TypeScript']);
|
||||
});
|
||||
|
||||
it('member cannot change own role', async () => {
|
||||
// Attempting to change role requires admin, but member is only 'member'
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/test-team-crud/members/${memberId}`,
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: { role: 'admin' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('admin can update team name', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/teams/test-team-crud',
|
||||
headers: { 'x-test-user-id': adminId },
|
||||
payload: { name: 'Updated Team Name' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.name).toBe('Updated Team Name');
|
||||
});
|
||||
|
||||
it('member cannot update team name', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/teams/test-team-crud',
|
||||
headers: { 'x-test-user-id': memberId },
|
||||
payload: { name: 'Should Fail' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('cannot remove the team owner', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/teams/test-team-crud/members/${ownerId}`,
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('admin can remove a member', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/teams/test-team-crud/members/${memberId}`,
|
||||
headers: { 'x-test-user-id': adminId },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
|
||||
// Verify member is gone
|
||||
const checkResponse = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/teams/test-team-crud',
|
||||
headers: { 'x-test-user-id': ownerId },
|
||||
});
|
||||
const body = JSON.parse(checkResponse.body);
|
||||
const memberIds = body.members.map((m: { userId: string }) => m.userId);
|
||||
expect(memberIds).not.toContain(memberId);
|
||||
});
|
||||
|
||||
it('does not let an admin demote the team owner', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'PATCH',
|
||||
url: `/api/teams/test-team-crud/members/${ownerId}`,
|
||||
headers: { 'x-test-user-id': adminId },
|
||||
payload: { role: 'member' },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
expect(response.json()).toEqual({ error: 'Cannot change the team owner role' });
|
||||
|
||||
const [membership] = await server.db.select().from(teamMembers)
|
||||
.where(sql`team_id = (SELECT id FROM teams WHERE slug = 'test-team-crud') AND user_id = ${ownerId}`);
|
||||
expect(membership.role).toBe('owner');
|
||||
});
|
||||
|
||||
it('returns 401 without auth header', async () => {
|
||||
const response = await server.inject({
|
||||
method: 'GET',
|
||||
url: '/api/teams',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
173
packages/team-server/tests/routes/webhooks.test.ts
Normal file
173
packages/team-server/tests/routes/webhooks.test.ts
Normal file
@@ -0,0 +1,173 @@
|
||||
import { createHmac } from 'node:crypto';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { webhookRoutes } from '../../src/routes/webhooks.js';
|
||||
|
||||
const SIGNING_KEY = Buffer.from('waggle-clerk-webhook-test-secret');
|
||||
const SIGNING_SECRET = `whsec_${SIGNING_KEY.toString('base64')}`;
|
||||
|
||||
const createEvent = {
|
||||
type: 'user.created',
|
||||
data: {
|
||||
id: 'clerk_webhook_user',
|
||||
first_name: 'Ada',
|
||||
last_name: 'Lovelace',
|
||||
email_addresses: [{ email_address: 'ada@example.com' }],
|
||||
image_url: 'https://example.com/ada.png',
|
||||
},
|
||||
};
|
||||
|
||||
function signedHeaders(payload: object, timestamp = Math.floor(Date.now() / 1000)) {
|
||||
const id = 'msg_waggle_clerk_test';
|
||||
const body = JSON.stringify(payload);
|
||||
const signature = createHmac('sha256', SIGNING_KEY)
|
||||
.update(`${id}.${timestamp}.${body}`)
|
||||
.digest('base64');
|
||||
|
||||
return {
|
||||
'svix-id': id,
|
||||
'svix-timestamp': String(timestamp),
|
||||
'svix-signature': `v1,${signature}`,
|
||||
};
|
||||
}
|
||||
|
||||
function createDbDouble() {
|
||||
const onConflictDoNothing = vi.fn().mockResolvedValue(undefined);
|
||||
const values = vi.fn(() => ({ onConflictDoNothing }));
|
||||
const insert = vi.fn(() => ({ values }));
|
||||
|
||||
const updateWhere = vi.fn().mockResolvedValue(undefined);
|
||||
const set = vi.fn(() => ({ where: updateWhere }));
|
||||
const update = vi.fn(() => ({ set }));
|
||||
|
||||
const deleteWhere = vi.fn().mockResolvedValue(undefined);
|
||||
const deleteFrom = vi.fn(() => ({ where: deleteWhere }));
|
||||
|
||||
return {
|
||||
db: { insert, update, delete: deleteFrom },
|
||||
mutations: { insert, values, update, deleteFrom },
|
||||
};
|
||||
}
|
||||
|
||||
describe('Clerk webhook authenticity', () => {
|
||||
let app: FastifyInstance;
|
||||
let mutations: ReturnType<typeof createDbDouble>['mutations'];
|
||||
let originalSigningSecret: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
originalSigningSecret = process.env.CLERK_WEBHOOK_SIGNING_SECRET;
|
||||
process.env.CLERK_WEBHOOK_SIGNING_SECRET = SIGNING_SECRET;
|
||||
|
||||
const dbDouble = createDbDouble();
|
||||
mutations = dbDouble.mutations;
|
||||
app = Fastify();
|
||||
app.decorate('db', dbDouble.db as never);
|
||||
await app.register(webhookRoutes);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
if (originalSigningSecret === undefined) {
|
||||
delete process.env.CLERK_WEBHOOK_SIGNING_SECRET;
|
||||
} else {
|
||||
process.env.CLERK_WEBHOOK_SIGNING_SECRET = originalSigningSecret;
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['user.created', createEvent.data],
|
||||
['user.updated', createEvent.data],
|
||||
['user.deleted', { id: createEvent.data.id }],
|
||||
])('rejects an unsigned %s event before any database mutation', async (type, data) => {
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
payload: { type, data },
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json()).toEqual({ error: 'Invalid webhook signature' });
|
||||
expect(mutations.insert).not.toHaveBeenCalled();
|
||||
expect(mutations.update).not.toHaveBeenCalled();
|
||||
expect(mutations.deleteFrom).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an otherwise signed event when its timestamp is stale', async () => {
|
||||
const staleTimestamp = Math.floor(Date.now() / 1000) - 301;
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
headers: signedHeaders(createEvent, staleTimestamp),
|
||||
payload: createEvent,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(mutations.insert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a signature that was generated for a different body', async () => {
|
||||
const tamperedEvent = {
|
||||
...createEvent,
|
||||
data: { ...createEvent.data, email_addresses: [{ email_address: 'attacker@example.com' }] },
|
||||
};
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
headers: signedHeaders(createEvent),
|
||||
payload: tamperedEvent,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(mutations.insert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails closed when the Clerk webhook signing secret is not configured', async () => {
|
||||
delete process.env.CLERK_WEBHOOK_SIGNING_SECRET;
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
headers: signedHeaders(createEvent),
|
||||
payload: createEvent,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(mutations.insert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves a correctly signed user.created event and its field mapping', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
headers: signedHeaders(createEvent),
|
||||
payload: createEvent,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toEqual({ received: true });
|
||||
expect(mutations.values).toHaveBeenCalledWith({
|
||||
clerkId: 'clerk_webhook_user',
|
||||
displayName: 'Ada Lovelace',
|
||||
email: 'ada@example.com',
|
||||
avatarUrl: 'https://example.com/ada.png',
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves correctly signed user.updated and user.deleted events', async () => {
|
||||
const updateEvent = { ...createEvent, type: 'user.updated' };
|
||||
const deleteEvent = { type: 'user.deleted', data: { id: createEvent.data.id } };
|
||||
|
||||
for (const event of [updateEvent, deleteEvent]) {
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/webhooks/clerk',
|
||||
headers: signedHeaders(event),
|
||||
payload: event,
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
}
|
||||
|
||||
expect(mutations.update).toHaveBeenCalledOnce();
|
||||
expect(mutations.deleteFrom).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
19
packages/team-server/tests/server.test.ts
Normal file
19
packages/team-server/tests/server.test.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { describe, it, expect, afterAll } from 'vitest';
|
||||
import { buildServer } from '../src/index.js';
|
||||
|
||||
describe('Fastify server', () => {
|
||||
const serverPromise = buildServer();
|
||||
|
||||
afterAll(async () => {
|
||||
const server = await serverPromise;
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('responds to health check', async () => {
|
||||
const server = await serverPromise;
|
||||
const response = await server.inject({ method: 'GET', url: '/health' });
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.status).toBe('ok');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
resolvePermission,
|
||||
filterByPermissions,
|
||||
getDefaultPolicies,
|
||||
riskExceedsThreshold,
|
||||
type EffectivePermissions,
|
||||
} from '../../src/services/team-capability-governance.js';
|
||||
|
||||
function makePerms(overrides?: Partial<EffectivePermissions>): EffectivePermissions {
|
||||
return {
|
||||
role: 'member',
|
||||
allowedSources: ['native', 'skill'],
|
||||
blockedTools: ['bash', 'delete_skill'],
|
||||
approvalThreshold: 'medium',
|
||||
overrides: new Map(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('riskExceedsThreshold', () => {
|
||||
it('high exceeds medium', () => {
|
||||
expect(riskExceedsThreshold('high', 'medium')).toBe(true);
|
||||
});
|
||||
|
||||
it('medium does not exceed medium', () => {
|
||||
expect(riskExceedsThreshold('medium', 'medium')).toBe(false);
|
||||
});
|
||||
|
||||
it('low does not exceed medium', () => {
|
||||
expect(riskExceedsThreshold('low', 'medium')).toBe(false);
|
||||
});
|
||||
|
||||
it('nothing exceeds none threshold', () => {
|
||||
expect(riskExceedsThreshold('high', 'none')).toBe(false);
|
||||
expect(riskExceedsThreshold('medium', 'none')).toBe(false);
|
||||
expect(riskExceedsThreshold('low', 'none')).toBe(false);
|
||||
});
|
||||
|
||||
it('medium exceeds low', () => {
|
||||
expect(riskExceedsThreshold('medium', 'low')).toBe(true);
|
||||
});
|
||||
|
||||
// P7/D15 A2b regression: 'critical' was omitted from the local risk map, so
|
||||
// `?? 0` sorted it BELOW 'low' and a critical capability slipped past a 'low'
|
||||
// approval threshold. Now ranked on the canonical scale.
|
||||
it('critical exceeds every lower threshold', () => {
|
||||
expect(riskExceedsThreshold('critical', 'low')).toBe(true);
|
||||
expect(riskExceedsThreshold('critical', 'medium')).toBe(true);
|
||||
expect(riskExceedsThreshold('critical', 'high')).toBe(true);
|
||||
});
|
||||
|
||||
it('critical does not exceed critical', () => {
|
||||
expect(riskExceedsThreshold('critical', 'critical')).toBe(false);
|
||||
});
|
||||
|
||||
it('nothing exceeds the none threshold, including critical', () => {
|
||||
expect(riskExceedsThreshold('critical', 'none')).toBe(false);
|
||||
});
|
||||
|
||||
it('low does not exceed low', () => {
|
||||
expect(riskExceedsThreshold('low', 'low')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolvePermission', () => {
|
||||
it('override approved returns allowed immediately', () => {
|
||||
const perms = makePerms({
|
||||
overrides: new Map([['dangerous_tool', 'approved']]),
|
||||
});
|
||||
// Even if source not in allowedSources, override wins
|
||||
expect(resolvePermission(perms, 'dangerous_tool', 'plugin', 'high')).toBe('allowed');
|
||||
});
|
||||
|
||||
it('override blocked returns blocked immediately', () => {
|
||||
const perms = makePerms({
|
||||
overrides: new Map([['some_skill', 'blocked']]),
|
||||
});
|
||||
// Even if source is allowed and tool not blocked, override wins
|
||||
expect(resolvePermission(perms, 'some_skill', 'native', 'low')).toBe('blocked');
|
||||
});
|
||||
|
||||
it('source not allowed returns source_not_allowed', () => {
|
||||
const perms = makePerms({ allowedSources: ['native'] });
|
||||
expect(resolvePermission(perms, 'some_plugin', 'plugin', 'low')).toBe('source_not_allowed');
|
||||
});
|
||||
|
||||
it('blocked tool returns blocked', () => {
|
||||
const perms = makePerms();
|
||||
expect(resolvePermission(perms, 'bash', 'native', 'low')).toBe('blocked');
|
||||
});
|
||||
|
||||
it('risk exceeds threshold returns needs_approval', () => {
|
||||
const perms = makePerms({ approvalThreshold: 'medium' });
|
||||
expect(resolvePermission(perms, 'safe_tool', 'native', 'high')).toBe('needs_approval');
|
||||
});
|
||||
|
||||
it('risk within threshold returns allowed', () => {
|
||||
const perms = makePerms({ approvalThreshold: 'medium' });
|
||||
expect(resolvePermission(perms, 'safe_tool', 'native', 'low')).toBe('allowed');
|
||||
});
|
||||
|
||||
it('threshold none means everything allowed (no approval needed)', () => {
|
||||
const perms = makePerms({ approvalThreshold: 'none' });
|
||||
expect(resolvePermission(perms, 'safe_tool', 'native', 'high')).toBe('allowed');
|
||||
});
|
||||
|
||||
it('blocked tool takes priority over source check', () => {
|
||||
const perms = makePerms({
|
||||
allowedSources: ['native'],
|
||||
blockedTools: ['bash'],
|
||||
});
|
||||
// bash is native (allowed source) but blocked tool — should be blocked
|
||||
expect(resolvePermission(perms, 'bash', 'native', 'low')).toBe('blocked');
|
||||
});
|
||||
|
||||
it('defaults risk to low when not provided', () => {
|
||||
const perms = makePerms({ approvalThreshold: 'low' });
|
||||
// low does not exceed low, so allowed
|
||||
expect(resolvePermission(perms, 'safe_tool', 'native')).toBe('allowed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('filterByPermissions', () => {
|
||||
it('removes blocked capabilities', () => {
|
||||
const perms = makePerms();
|
||||
const caps = [
|
||||
{ name: 'bash', type: 'native' },
|
||||
{ name: 'safe_tool', type: 'native', risk: 'low' },
|
||||
];
|
||||
const results = filterByPermissions(perms, caps);
|
||||
expect(results).toHaveLength(2);
|
||||
expect(results[0].result).toBe('blocked');
|
||||
expect(results[1].result).toBe('allowed');
|
||||
});
|
||||
|
||||
it('keeps approved overrides even if source not in policy', () => {
|
||||
const perms = makePerms({
|
||||
allowedSources: ['native'],
|
||||
overrides: new Map([['my_plugin', 'approved']]),
|
||||
});
|
||||
const caps = [{ name: 'my_plugin', type: 'plugin', risk: 'high' }];
|
||||
const results = filterByPermissions(perms, caps);
|
||||
expect(results[0].result).toBe('allowed');
|
||||
});
|
||||
|
||||
it('blocks override-blocked even if policy would allow', () => {
|
||||
const perms = makePerms({
|
||||
allowedSources: ['native', 'skill'],
|
||||
blockedTools: [],
|
||||
overrides: new Map([['good_skill', 'blocked']]),
|
||||
});
|
||||
const caps = [{ name: 'good_skill', type: 'skill', risk: 'low' }];
|
||||
const results = filterByPermissions(perms, caps);
|
||||
expect(results[0].result).toBe('blocked');
|
||||
});
|
||||
|
||||
it('marks source_not_allowed for unknown sources', () => {
|
||||
const perms = makePerms({ allowedSources: ['native'] });
|
||||
const caps = [{ name: 'mcp_tool', type: 'mcp' }];
|
||||
const results = filterByPermissions(perms, caps);
|
||||
expect(results[0].result).toBe('source_not_allowed');
|
||||
});
|
||||
|
||||
it('marks needs_approval when risk exceeds threshold', () => {
|
||||
const perms = makePerms({ approvalThreshold: 'low' });
|
||||
const caps = [{ name: 'risky_skill', type: 'skill', risk: 'medium' }];
|
||||
const results = filterByPermissions(perms, caps);
|
||||
expect(results[0].result).toBe('needs_approval');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDefaultPolicies', () => {
|
||||
it('returns 3 role policies', () => {
|
||||
const policies = getDefaultPolicies();
|
||||
expect(policies).toHaveLength(3);
|
||||
const roles = policies.map((p) => p.role);
|
||||
expect(roles).toContain('owner');
|
||||
expect(roles).toContain('admin');
|
||||
expect(roles).toContain('member');
|
||||
});
|
||||
|
||||
it('owner has all sources and no blocks', () => {
|
||||
const owner = getDefaultPolicies().find((p) => p.role === 'owner')!;
|
||||
expect(owner.allowedSources).toEqual(['native', 'skill', 'plugin', 'mcp']);
|
||||
expect(owner.blockedTools).toEqual([]);
|
||||
expect(owner.approvalThreshold).toBe('none');
|
||||
});
|
||||
|
||||
it('admin has all sources and no blocks', () => {
|
||||
const admin = getDefaultPolicies().find((p) => p.role === 'admin')!;
|
||||
expect(admin.allowedSources).toEqual(['native', 'skill', 'plugin', 'mcp']);
|
||||
expect(admin.blockedTools).toEqual([]);
|
||||
expect(admin.approvalThreshold).toBe('none');
|
||||
});
|
||||
|
||||
it('member has restricted sources and blocked tools', () => {
|
||||
const member = getDefaultPolicies().find((p) => p.role === 'member')!;
|
||||
expect(member.allowedSources).toEqual(['native', 'skill']);
|
||||
expect(member.blockedTools).toEqual(['bash', 'delete_skill']);
|
||||
expect(member.approvalThreshold).toBe('medium');
|
||||
});
|
||||
});
|
||||
574
packages/team-server/tests/ws/gateway.test.ts
Normal file
574
packages/team-server/tests/ws/gateway.test.ts
Normal file
@@ -0,0 +1,574 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import type { WebSocket } from 'ws';
|
||||
import type { Task, SuggestionEntry } from '@waggle/shared';
|
||||
import type { AuthenticateFn } from '../../src/plugins/auth.js';
|
||||
import { ConnectionManager } from '../../src/ws/connection-manager.js';
|
||||
import { connectionManager, setWsTokenVerifier } from '../../src/ws/gateway.js';
|
||||
|
||||
/** A minimal mock WebSocket exposing the surface ConnectionManager touches. */
|
||||
interface MockWebSocket {
|
||||
readyState: number;
|
||||
OPEN: number;
|
||||
send: Mock;
|
||||
}
|
||||
|
||||
/** Build a mock WebSocket whose `send` is a vitest mock the tests can assert on. */
|
||||
function mockWs(readyState = 1): MockWebSocket {
|
||||
return { readyState, OPEN: 1, send: vi.fn() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Cast a mock WebSocket to the real `ws.WebSocket` type at ConnectionManager
|
||||
* boundaries. The real type has a large surface; ConnectionManager only reads
|
||||
* `readyState`/`OPEN` and calls `send`, so the minimal mock is sound here.
|
||||
*/
|
||||
function asWs(ws: MockWebSocket): WebSocket {
|
||||
return ws as unknown as WebSocket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a structurally valid JWT with a given payload.
|
||||
* Header: {"alg":"HS256","typ":"JWT"}, signature: fake.
|
||||
* This is NOT cryptographically signed — it's for testing JWT structure validation.
|
||||
*/
|
||||
function makeTestJwt(payload: Record<string, unknown>): string {
|
||||
const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' }))
|
||||
.toString('base64url');
|
||||
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
|
||||
const signature = Buffer.from('test-signature').toString('base64url');
|
||||
return `${header}.${body}.${signature}`;
|
||||
}
|
||||
|
||||
// ─── ConnectionManager unit tests ───────────────────────────────────────────
|
||||
|
||||
describe('ConnectionManager', () => {
|
||||
it('tracks connections by team and user', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const ws = mockWs();
|
||||
|
||||
cm.add('team1', 'user1', asWs(ws));
|
||||
expect(cm.getConnectedUsers('team1')).toEqual(['user1']);
|
||||
|
||||
cm.remove('team1', 'user1');
|
||||
expect(cm.getConnectedUsers('team1')).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns empty array for unknown team', () => {
|
||||
const cm = new ConnectionManager();
|
||||
expect(cm.getConnectedUsers('nonexistent')).toEqual([]);
|
||||
});
|
||||
|
||||
it('removes team entry when last user disconnects', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const ws = mockWs();
|
||||
|
||||
cm.add('team1', 'user1', asWs(ws));
|
||||
expect(cm.getTeamCount()).toBe(1);
|
||||
|
||||
cm.remove('team1', 'user1');
|
||||
expect(cm.getTeamCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('tracks multiple users in same team', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const ws1 = mockWs();
|
||||
const ws2 = mockWs();
|
||||
|
||||
cm.add('team1', 'user1', asWs(ws1));
|
||||
cm.add('team1', 'user2', asWs(ws2));
|
||||
expect(cm.getConnectedUsers('team1')).toEqual(['user1', 'user2']);
|
||||
});
|
||||
|
||||
it('tracks users across multiple teams', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const ws1 = mockWs();
|
||||
const ws2 = mockWs();
|
||||
|
||||
cm.add('team1', 'user1', asWs(ws1));
|
||||
cm.add('team2', 'user2', asWs(ws2));
|
||||
expect(cm.getConnectedUsers('team1')).toEqual(['user1']);
|
||||
expect(cm.getConnectedUsers('team2')).toEqual(['user2']);
|
||||
expect(cm.getTeamCount()).toBe(2);
|
||||
});
|
||||
|
||||
it('broadcasts to all team members', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const ws1 = mockWs();
|
||||
const ws2 = mockWs();
|
||||
|
||||
cm.add('team1', 'user1', asWs(ws1));
|
||||
cm.add('team1', 'user2', asWs(ws2));
|
||||
|
||||
cm.broadcast('team1', { type: 'task_update', task: {} as unknown as Task });
|
||||
expect(ws1.send).toHaveBeenCalledOnce();
|
||||
expect(ws2.send).toHaveBeenCalledOnce();
|
||||
|
||||
const sentData = JSON.parse(ws1.send.mock.calls[0][0] as string);
|
||||
expect(sentData.type).toBe('task_update');
|
||||
});
|
||||
|
||||
it('excludes user from broadcast', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const ws1 = mockWs();
|
||||
const ws2 = mockWs();
|
||||
|
||||
cm.add('team1', 'user1', asWs(ws1));
|
||||
cm.add('team1', 'user2', asWs(ws2));
|
||||
|
||||
cm.broadcast('team1', { type: 'task_update', task: {} as unknown as Task }, 'user1');
|
||||
expect(ws1.send).not.toHaveBeenCalled();
|
||||
expect(ws2.send).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('skips sockets that are not OPEN', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const wsOpen = mockWs(1);
|
||||
const wsClosed = mockWs(3); // readyState 3 = CLOSED
|
||||
|
||||
cm.add('team1', 'user1', asWs(wsOpen));
|
||||
cm.add('team1', 'user2', asWs(wsClosed));
|
||||
|
||||
cm.broadcast('team1', { type: 'task_update', task: {} as unknown as Task });
|
||||
expect(wsOpen.send).toHaveBeenCalledOnce();
|
||||
expect(wsClosed.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends to specific user', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const ws1 = mockWs();
|
||||
const ws2 = mockWs();
|
||||
|
||||
cm.add('team1', 'user1', asWs(ws1));
|
||||
cm.add('team1', 'user2', asWs(ws2));
|
||||
|
||||
cm.sendTo('team1', 'user1', { type: 'suggestion', suggestion: {} as unknown as SuggestionEntry });
|
||||
expect(ws1.send).toHaveBeenCalledOnce();
|
||||
expect(ws2.send).not.toHaveBeenCalled();
|
||||
|
||||
const sentData = JSON.parse(ws1.send.mock.calls[0][0] as string);
|
||||
expect(sentData.type).toBe('suggestion');
|
||||
});
|
||||
|
||||
it('sendTo does nothing for nonexistent user', () => {
|
||||
const cm = new ConnectionManager();
|
||||
// Should not throw
|
||||
cm.sendTo('team1', 'nobody', { type: 'task_update', task: {} as unknown as Task });
|
||||
});
|
||||
|
||||
it('sendTo does nothing for closed socket', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const wsClosed = mockWs(3);
|
||||
|
||||
cm.add('team1', 'user1', asWs(wsClosed));
|
||||
cm.sendTo('team1', 'user1', { type: 'task_update', task: {} as unknown as Task });
|
||||
expect(wsClosed.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('broadcast does nothing for nonexistent team', () => {
|
||||
const cm = new ConnectionManager();
|
||||
// Should not throw
|
||||
cm.broadcast('nonexistent', { type: 'task_update', task: {} as unknown as Task });
|
||||
});
|
||||
|
||||
it('replaces connection when same user re-adds', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const ws1 = mockWs();
|
||||
const ws2 = mockWs();
|
||||
|
||||
cm.add('team1', 'user1', asWs(ws1));
|
||||
cm.add('team1', 'user1', asWs(ws2)); // replace
|
||||
|
||||
cm.broadcast('team1', { type: 'task_update', task: {} as unknown as Task });
|
||||
expect(ws1.send).not.toHaveBeenCalled();
|
||||
expect(ws2.send).toHaveBeenCalledOnce();
|
||||
expect(cm.getConnectedUsers('team1')).toEqual(['user1']);
|
||||
});
|
||||
|
||||
// ── 11F-6: WebSocket lifecycle tests ──────────────────────────────────
|
||||
|
||||
it('multiple clients with one disconnect: broadcast still reaches remaining 2', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const ws1 = mockWs();
|
||||
const ws2 = mockWs();
|
||||
const ws3 = mockWs();
|
||||
|
||||
// Register 3 clients in a team
|
||||
cm.add('team1', 'user1', asWs(ws1));
|
||||
cm.add('team1', 'user2', asWs(ws2));
|
||||
cm.add('team1', 'user3', asWs(ws3));
|
||||
expect(cm.getConnectedUsers('team1')).toEqual(['user1', 'user2', 'user3']);
|
||||
|
||||
// Disconnect user2
|
||||
cm.remove('team1', 'user2');
|
||||
expect(cm.getConnectedUsers('team1')).toEqual(['user1', 'user3']);
|
||||
|
||||
// Broadcast — should reach user1 and user3 only
|
||||
cm.broadcast('team1', { type: 'task_update', task: {} as unknown as Task });
|
||||
expect(ws1.send).toHaveBeenCalledOnce();
|
||||
expect(ws2.send).not.toHaveBeenCalled();
|
||||
expect(ws3.send).toHaveBeenCalledOnce();
|
||||
|
||||
// Team is still tracked (not removed since 2 users remain)
|
||||
expect(cm.getTeamCount()).toBe(1);
|
||||
});
|
||||
|
||||
it('reconnection with same userId: no duplicate entries, clean replacement', () => {
|
||||
const cm = new ConnectionManager();
|
||||
const wsOriginal = mockWs();
|
||||
const wsReconnect = mockWs();
|
||||
|
||||
// Initial connection
|
||||
cm.add('team1', 'user1', asWs(wsOriginal));
|
||||
expect(cm.getConnectedUsers('team1')).toEqual(['user1']);
|
||||
|
||||
// Simulate disconnect
|
||||
cm.remove('team1', 'user1');
|
||||
expect(cm.getConnectedUsers('team1')).toEqual([]);
|
||||
// Team entry should be cleaned up since last user left
|
||||
expect(cm.getTeamCount()).toBe(0);
|
||||
|
||||
// Reconnect with same userId
|
||||
cm.add('team1', 'user1', asWs(wsReconnect));
|
||||
expect(cm.getConnectedUsers('team1')).toEqual(['user1']);
|
||||
expect(cm.getTeamCount()).toBe(1);
|
||||
|
||||
// Broadcast should only reach the reconnected socket
|
||||
cm.broadcast('team1', { type: 'task_update', task: {} as unknown as Task });
|
||||
expect(wsOriginal.send).not.toHaveBeenCalled();
|
||||
expect(wsReconnect.send).toHaveBeenCalledOnce();
|
||||
|
||||
// No duplicate user entries
|
||||
expect(cm.getConnectedUsers('team1')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── WebSocket Gateway integration tests ────────────────────────────────────
|
||||
// These require PostgreSQL + Redis running (ports 5434 / 6381)
|
||||
|
||||
describe('WebSocket Gateway (integration)', () => {
|
||||
let server: Awaited<ReturnType<typeof import('../../src/index.js').buildServer>>;
|
||||
let address: string;
|
||||
let userId: string;
|
||||
let outsiderUserId: string;
|
||||
let clerkId: string;
|
||||
let teamSlug: string;
|
||||
let teamId: string;
|
||||
/** A structurally valid JWT whose sub matches our test user's clerkId */
|
||||
let validJwt: string;
|
||||
let outsiderJwt: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
const { buildServer } = await import('../../src/index.js');
|
||||
const { sql: drizzleSql } = await import('drizzle-orm');
|
||||
server = await buildServer();
|
||||
|
||||
// Override auth to bypass Clerk for REST routes
|
||||
const testAuthHandler: AuthenticateFn = async (req, reply) => {
|
||||
const testUserId = req.headers['x-test-user-id'] as string;
|
||||
if (!testUserId) {
|
||||
await reply.code(401).send({ error: 'Missing test user' });
|
||||
return;
|
||||
}
|
||||
req.userId = testUserId;
|
||||
req.clerkId = 'test';
|
||||
};
|
||||
server._authHandler.fn = testAuthHandler;
|
||||
|
||||
// Clean up leftover data from previous runs
|
||||
const { users, teams, teamMembers } = await import('../../src/db/schema.js');
|
||||
await server.db.execute(drizzleSql`DELETE FROM team_members WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'wstest_%')`);
|
||||
await server.db.execute(drizzleSql`DELETE FROM messages WHERE sender_id IN (SELECT id FROM users WHERE clerk_id LIKE 'wstest_%')`);
|
||||
await server.db.execute(drizzleSql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'ws-test-team-%')`);
|
||||
await server.db.execute(drizzleSql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'ws-test-team-%')`);
|
||||
await server.db.execute(drizzleSql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'ws-test-team-%')`);
|
||||
await server.db.execute(drizzleSql`DELETE FROM teams WHERE slug LIKE 'ws-test-team-%'`);
|
||||
await server.db.execute(drizzleSql`DELETE FROM users WHERE clerk_id LIKE 'wstest_%'`);
|
||||
|
||||
// Create test user and team with unique IDs
|
||||
const suffix = Date.now();
|
||||
clerkId = `wstest_user_${suffix}`;
|
||||
const [user] = await server.db
|
||||
.insert(users)
|
||||
.values({
|
||||
clerkId,
|
||||
displayName: 'WS User',
|
||||
email: `wsuser_${suffix}@test.com`,
|
||||
})
|
||||
.returning();
|
||||
userId = user.id;
|
||||
|
||||
const outsiderClerkId = `wstest_outsider_${suffix}`;
|
||||
const [outsider] = await server.db
|
||||
.insert(users)
|
||||
.values({
|
||||
clerkId: outsiderClerkId,
|
||||
displayName: 'WS Outsider',
|
||||
email: `wsoutsider_${suffix}@test.com`,
|
||||
})
|
||||
.returning();
|
||||
outsiderUserId = outsider.id;
|
||||
|
||||
// Build a valid test JWT with the user's clerkId as `sub`
|
||||
validJwt = makeTestJwt({ sub: clerkId, iat: Math.floor(Date.now() / 1000) });
|
||||
outsiderJwt = makeTestJwt({ sub: outsiderClerkId, iat: Math.floor(Date.now() / 1000) });
|
||||
|
||||
// Override the WS token verifier so tests don't need a real Clerk secret key.
|
||||
// The verifier accepts any structurally valid JWT and returns its decoded `sub`.
|
||||
setWsTokenVerifier(async (token: string) => {
|
||||
const parts = token.split('.');
|
||||
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString());
|
||||
if (typeof payload.sub !== 'string') throw new Error('Missing sub');
|
||||
return { sub: payload.sub };
|
||||
});
|
||||
|
||||
teamSlug = `ws-test-team-${suffix}`;
|
||||
const [team] = await server.db
|
||||
.insert(teams)
|
||||
.values({ name: 'WS Team', slug: teamSlug, ownerId: userId })
|
||||
.returning();
|
||||
teamId = team.id;
|
||||
|
||||
await server.db
|
||||
.insert(teamMembers)
|
||||
.values({ teamId: team.id, userId, role: 'owner' });
|
||||
|
||||
// Start listening on a random port
|
||||
await server.listen({ port: 0, host: '127.0.0.1' });
|
||||
const addr = server.server.address();
|
||||
address = typeof addr === 'string' ? addr : `127.0.0.1:${addr?.port}`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
// Clear the WS token verifier override
|
||||
setWsTokenVerifier(null);
|
||||
|
||||
if (!server) return;
|
||||
const { sql } = await import('drizzle-orm');
|
||||
await server.db.execute(
|
||||
sql`DELETE FROM team_members WHERE user_id IN (SELECT id FROM users WHERE clerk_id LIKE 'wstest_%')`,
|
||||
);
|
||||
await server.db.execute(
|
||||
sql`DELETE FROM messages WHERE sender_id IN (SELECT id FROM users WHERE clerk_id LIKE 'wstest_%')`,
|
||||
);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_requests WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'ws-test-team-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_overrides WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'ws-test-team-%')`);
|
||||
await server.db.execute(sql`DELETE FROM team_capability_policies WHERE team_id IN (SELECT id FROM teams WHERE slug LIKE 'ws-test-team-%')`);
|
||||
await server.db.execute(sql`DELETE FROM teams WHERE slug LIKE 'ws-test-team-%'`);
|
||||
await server.db.execute(
|
||||
sql`DELETE FROM users WHERE clerk_id LIKE 'wstest_%'`,
|
||||
);
|
||||
await server.close();
|
||||
});
|
||||
|
||||
function connectWs(): Promise<{ ws: import('ws').WebSocket; messages: Record<string, unknown>[] }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Dynamic import to avoid issues if ws isn't available at parse time
|
||||
import('ws').then(({ default: WS }) => {
|
||||
const ws = new WS(`ws://${address}/ws`);
|
||||
const msgs: Record<string, unknown>[] = [];
|
||||
ws.on('message', (data: Buffer) => msgs.push(JSON.parse(data.toString())));
|
||||
ws.on('open', () => resolve({ ws, messages: msgs }));
|
||||
ws.on('error', reject);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function wait(ms: number) {
|
||||
return new Promise((r) => setTimeout(r, ms));
|
||||
}
|
||||
|
||||
/** Wait until messages array has at least `count` entries, or timeout. */
|
||||
async function waitForMessages(messages: Record<string, unknown>[], count: number, timeoutMs = 3000) {
|
||||
const start = Date.now();
|
||||
while (messages.length < count && Date.now() - start < timeoutMs) {
|
||||
await wait(50);
|
||||
}
|
||||
}
|
||||
|
||||
it('connects and authenticates via WebSocket', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: validJwt }));
|
||||
await waitForMessages(messages, 1);
|
||||
|
||||
expect(messages).toHaveLength(1);
|
||||
expect(messages[0]).toEqual({ type: 'authenticated', userId });
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('rejects join_team before authentication', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
ws.send(JSON.stringify({ type: 'join_team', teamSlug }));
|
||||
await waitForMessages(messages, 1);
|
||||
|
||||
expect(messages[0]).toEqual({ type: 'error', message: 'Not authenticated' });
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('joins team room after authentication', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: validJwt }));
|
||||
await waitForMessages(messages, 1);
|
||||
|
||||
ws.send(JSON.stringify({ type: 'join_team', teamSlug }));
|
||||
await waitForMessages(messages, 2);
|
||||
|
||||
expect(messages[1]).toEqual({ type: 'joined_team', teamSlug });
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('rejects an authenticated non-member joining an existing team', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: outsiderJwt }));
|
||||
await waitForMessages(messages, 1);
|
||||
expect(messages[0]).toEqual({ type: 'authenticated', userId: outsiderUserId });
|
||||
|
||||
ws.send(JSON.stringify({ type: 'join_team', teamSlug }));
|
||||
await waitForMessages(messages, 2);
|
||||
|
||||
expect(messages[1]).toEqual({ type: 'error', message: 'Team not found' });
|
||||
expect(connectionManager.getConnectedUsers(teamId)).not.toContain(outsiderUserId);
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('clears the joined team when a socket authenticates as a different user', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: validJwt }));
|
||||
await waitForMessages(messages, 1);
|
||||
ws.send(JSON.stringify({ type: 'join_team', teamSlug }));
|
||||
await waitForMessages(messages, 2);
|
||||
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: outsiderJwt }));
|
||||
await waitForMessages(messages, 3);
|
||||
|
||||
expect(messages[2]).toEqual({ type: 'authenticated', userId: outsiderUserId });
|
||||
expect(connectionManager.getConnectedUsers(teamId)).not.toContain(userId);
|
||||
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'send_message',
|
||||
teamSlug,
|
||||
messageType: 'broadcast',
|
||||
subtype: 'discovery',
|
||||
content: { text: 'reauthenticated outsider' },
|
||||
}),
|
||||
);
|
||||
await waitForMessages(messages, 4);
|
||||
expect(messages[3]).toEqual({ type: 'error', message: 'Not in a team' });
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('returns error for nonexistent team', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: validJwt }));
|
||||
await waitForMessages(messages, 1);
|
||||
|
||||
ws.send(JSON.stringify({ type: 'join_team', teamSlug: 'does-not-exist' }));
|
||||
await waitForMessages(messages, 2);
|
||||
|
||||
expect(messages[1]).toEqual({ type: 'error', message: 'Team not found' });
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('rejects send_message before joining team', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: validJwt }));
|
||||
await waitForMessages(messages, 1);
|
||||
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'send_message',
|
||||
teamSlug,
|
||||
messageType: 'broadcast',
|
||||
subtype: 'discovery',
|
||||
content: { text: 'hello' },
|
||||
}),
|
||||
);
|
||||
await waitForMessages(messages, 2);
|
||||
|
||||
expect(messages[1]).toEqual({ type: 'error', message: 'Not in a team' });
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('handles invalid JSON gracefully', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
ws.send('this is not json');
|
||||
await wait(200);
|
||||
|
||||
expect(messages[0]).toEqual({ type: 'error', message: 'Invalid message' });
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
// ─── JWT auth security tests ──────────────────────────────────────────────
|
||||
|
||||
it('rejects plain userId string as token (not a JWT)', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
// Sending a raw userId (UUID) should be rejected — it's not a JWT
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: userId }));
|
||||
await waitForMessages(messages, 1);
|
||||
|
||||
expect(messages[0]).toEqual({
|
||||
type: 'error',
|
||||
message: 'Invalid token: must be a valid JWT',
|
||||
});
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('rejects random non-JWT string as token', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: 'not-a-jwt-token' }));
|
||||
await waitForMessages(messages, 1);
|
||||
|
||||
expect(messages[0]).toEqual({
|
||||
type: 'error',
|
||||
message: 'Invalid token: must be a valid JWT',
|
||||
});
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('rejects JWT with nonexistent user (unknown clerkId)', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
const fakeJwt = makeTestJwt({ sub: 'clerk_user_does_not_exist', iat: Math.floor(Date.now() / 1000) });
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: fakeJwt }));
|
||||
await waitForMessages(messages, 1);
|
||||
|
||||
expect(messages[0]).toEqual({
|
||||
type: 'error',
|
||||
message: 'User not found',
|
||||
});
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('authenticates with valid JWT and maps clerkId to internal userId', async () => {
|
||||
const { ws, messages } = await connectWs();
|
||||
|
||||
ws.send(JSON.stringify({ type: 'authenticate', token: validJwt }));
|
||||
await waitForMessages(messages, 1);
|
||||
|
||||
expect(messages[0]).toEqual({ type: 'authenticated', userId });
|
||||
|
||||
ws.close();
|
||||
});
|
||||
});
|
||||
24
packages/team-server/tsconfig.json
Normal file
24
packages/team-server/tsconfig.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"composite": true
|
||||
},
|
||||
"references": [
|
||||
{ "path": "../shared" }
|
||||
],
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["node_modules", "dist", "tests"]
|
||||
}
|
||||
Reference in New Issue
Block a user