Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix: cli datetime and slug uniqueness
Gus799bd52f0b1b
diff --git a/src/shared/src/logger.ts b/src/shared/src/logger.tsindex dc4b09da0..eec318591 100644--- a/src/shared/src/logger.ts+++ b/src/shared/src/logger.ts@@ -11,16 +11,19 @@ const LEVELS: Record<LogLevel, number> = {export interface LoggerOptions {service: stringlevel?: LogLevel+ pretty?: boolean}export class Logger {private readonly service: stringprivate readonly level: number+ private readonly pretty: booleanprivate readonly fields: Record<string, unknown>constructor(opts: LoggerOptions, fields?: Record<string, unknown>) {this.service = opts.servicethis.level = LEVELS[opts.level ?? "info"]+ this.pretty = opts.pretty ?? falsethis.fields = fields ?? {}}@@ -43,7 +46,7 @@ export class Logger {child(fields: Record<string, unknown>): Logger {const merged = { ...this.fields, ...fields }const child = new Logger(- { service: this.service, level: this.levelName() },+ { service: this.service, level: this.levelName(), pretty: this.pretty },merged,)return child@@ -78,7 +81,19 @@ export class Logger {}}- const line = JSON.stringify(entry)+ let line: string+ if (this.pretty) {+ const ts = (entry.ts as string).replace("T", " ").replace("Z", "")+ const lvl = (entry.level as string).toUpperCase().padEnd(5)+ const pairs = Object.entries(entry)+ .filter(([k]) => k !== "level" && k !== "msg" && k !== "service" && k !== "ts")+ .map(([k, v]) => `${k}=${typeof v === "object" ? JSON.stringify(v) : v}`)+ .join(" ")+ line = `${ts} ${lvl} [${entry.service}] ${entry.msg}${pairs ? " " + pairs : ""}`+ } else {+ line = JSON.stringify(entry)+ }+if (level === "error") {console.error(line)} else {diff --git a/src/web/src/app/api/workspaces/route.test.ts b/src/web/src/app/api/workspaces/route.test.tsindex e491e6465..3651fc90a 100644--- a/src/web/src/app/api/workspaces/route.test.ts+++ b/src/web/src/app/api/workspaces/route.test.ts@@ -116,8 +116,32 @@ describe("POST /api/workspaces", () => {expect(await res.json()).toEqual({ error: "slug is required" });});- it("returns 409 on duplicate slug", async () => {- mockCreateWorkspace.mockRejectedValue(new Error("UNIQUE constraint failed: workspaces.slug"));+ it("retries with suffixed slug on duplicate and returns 201", async () => {+ const uniqueError = new Error("UNIQUE constraint failed: workspaces.slug");+ mockCreateWorkspace+ .mockRejectedValueOnce(uniqueError)+ .mockResolvedValueOnce({ id: "w-retry", name: "Dup", slug: "dup-abcd" });+ mockCreateMember.mockResolvedValue({});++ const req = new NextRequest("http://localhost/api/workspaces", {+ method: "POST",+ body: JSON.stringify({ name: "Dup", slug: "dup" }),+ headers: { "Content-Type": "application/json" },+ });+ const res = await POST(req, {} as any);++ expect(res.status).toBe(201);+ expect(mockCreateWorkspace).toHaveBeenCalledTimes(2);+ // First call uses original slug+ expect(mockCreateWorkspace.mock.calls[0][1].slug).toBe("dup");+ // Second call uses a suffixed slug+ expect(mockCreateWorkspace.mock.calls[1][1].slug).toMatch(/^dup-.+/);+ });++ it("returns 409 after all slug retries exhausted", async () => {+ const uniqueError = new Error("UNIQUE constraint failed: workspaces.slug");+ // 1 initial + 9 retries = 10 rejections+ mockCreateWorkspace.mockRejectedValue(uniqueError);const req = new NextRequest("http://localhost/api/workspaces", {method: "POST",@@ -128,13 +152,60 @@ describe("POST /api/workspaces", () => {expect(res.status).toBe(409);expect(await res.json()).toEqual({ error: "workspace slug already exists" });+ // 1 initial + 9 retries+ expect(mockCreateWorkspace).toHaveBeenCalledTimes(10);+ });++ it("retries with escalating suffix lengths", async () => {+ const uniqueError = new Error("UNIQUE constraint failed: workspaces.slug");+ // Fail 7 times (1 original + 3 nanoid(4) + 3 nanoid(8)), succeed on 8th+ const rejections = Array.from({ length: 7 }, () => uniqueError);+ mockCreateWorkspace+ .mockRejectedValueOnce(rejections[0])+ .mockRejectedValueOnce(rejections[1])+ .mockRejectedValueOnce(rejections[2])+ .mockRejectedValueOnce(rejections[3])+ .mockRejectedValueOnce(rejections[4])+ .mockRejectedValueOnce(rejections[5])+ .mockRejectedValueOnce(rejections[6])+ .mockResolvedValueOnce({ id: "w-long", name: "Dup", slug: "dup-longsuffix123456" });+ mockCreateMember.mockResolvedValue({});++ const req = new NextRequest("http://localhost/api/workspaces", {+ method: "POST",+ body: JSON.stringify({ name: "Dup", slug: "dup" }),+ headers: { "Content-Type": "application/json" },+ });+ const res = await POST(req, {} as any);++ expect(res.status).toBe(201);+ expect(mockCreateWorkspace).toHaveBeenCalledTimes(8);+ // Verify suffix length escalation+ const slugs = mockCreateWorkspace.mock.calls.map((c: any) => c[1].slug as string);+ expect(slugs[0]).toBe("dup"); // original+ // nanoid(4) attempts: suffix part should be 4 chars+ for (let i = 1; i <= 3; i++) {+ const suffix = slugs[i].replace("dup-", "");+ expect(suffix).toHaveLength(4);+ }+ // nanoid(8) attempts: suffix part should be 8 chars+ for (let i = 4; i <= 6; i++) {+ const suffix = slugs[i].replace("dup-", "");+ expect(suffix).toHaveLength(8);+ }+ // 8th call succeeds with nanoid(16) suffix+ const lastSuffix = slugs[7].replace("dup-", "");+ expect(lastSuffix).toHaveLength(16);});- it("returns 409 on duplicate slug wrapped with cause", async () => {+ it("retries on duplicate slug wrapped with cause", async () => {const cause = new Error("UNIQUE constraint failed: workspaces.slug");const wrapped = new Error("Failed query: INSERT INTO ...");(wrapped as any).cause = cause;- mockCreateWorkspace.mockRejectedValue(wrapped);+ mockCreateWorkspace+ .mockRejectedValueOnce(wrapped)+ .mockResolvedValueOnce({ id: "w-retry2", name: "Dup", slug: "dup-xyz" });+ mockCreateMember.mockResolvedValue({});const req = new NextRequest("http://localhost/api/workspaces", {method: "POST",@@ -143,7 +214,7 @@ describe("POST /api/workspaces", () => {});const res = await POST(req, {} as any);- expect(res.status).toBe(409);- expect(await res.json()).toEqual({ error: "workspace slug already exists" });+ expect(res.status).toBe(201);+ expect(mockCreateWorkspace).toHaveBeenCalledTimes(2);});});diff --git a/src/web/src/app/api/workspaces/route.ts b/src/web/src/app/api/workspaces/route.tsindex ea7249432..ed2029025 100644--- a/src/web/src/app/api/workspaces/route.ts+++ b/src/web/src/app/api/workspaces/route.ts@@ -1,6 +1,7 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare"import { createDb, queries, isUniqueConstraintError } from "@alook/shared"+import { nanoid } from "nanoid"import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError } from "@/lib/middleware/helpers";import { workspaceToResponse } from "@/lib/api/responses";@@ -34,18 +35,24 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("slug is required", 400);}- try {- const ws = await queries.workspace.createWorkspace(db, { name, slug });- await queries.member.createMember(db, {- workspaceId: ws.id,- userId: ctx.userId,- role: "owner",- });- return writeJSON(workspaceToResponse(ws), 201);- } catch (err: unknown) {- if (isUniqueConstraintError(err)) {- return writeError("workspace slug already exists", 409);+ const suffixLengths = [4, 4, 4, 8, 8, 8, 16, 16, 16];+ let candidateSlug = slug;++ for (let attempt = 0; ; attempt++) {+ try {+ const ws = await queries.workspace.createWorkspace(db, { name, slug: candidateSlug });+ await queries.member.createMember(db, {+ workspaceId: ws.id,+ userId: ctx.userId,+ role: "owner",+ });+ return writeJSON(workspaceToResponse(ws), 201);+ } catch (err: unknown) {+ if (!isUniqueConstraintError(err)) throw err;+ if (attempt >= suffixLengths.length) {+ return writeError("workspace slug already exists", 409);+ }+ candidateSlug = `${slug}-${nanoid(suffixLengths[attempt])}`;}- throw err;}});diff --git a/src/web/src/instrumentation.ts b/src/web/src/instrumentation.tsnew file mode 100644index 000000000..35eed1afa--- /dev/null+++ b/src/web/src/instrumentation.ts@@ -0,0 +1,44 @@+const SUPPRESSED_WARNINGS = [+ "[Better Auth]:",+]++export function register() {+ if (process.env.NODE_ENV !== "development") return++ // Patch stdout.write to prepend timestamps to Next.js dev request logs.+ // Use Function constructor to access process.stdout without the Edge bundler+ // statically detecting the Node.js API reference.+ try {+ const getStdout = new Function("return process.stdout") as () => typeof process.stdout+ const stdout = getStdout()+ if (typeof stdout?.write === "function") {+ const origWrite = stdout.write.bind(stdout)+ const REQUEST_LOG_RE = /^ +(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) /++ function timestamp(): string {+ return new Date().toISOString().replace("T", " ").replace("Z", "")+ }++ stdout.write = (+ chunk: Uint8Array | string,+ ...rest: unknown[]+ ): boolean => {+ const str = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString()+ if (REQUEST_LOG_RE.test(str)) {+ return (origWrite as Function)(`${timestamp()}${str}`, ...rest)+ }+ return (origWrite as Function)(chunk, ...rest)+ }+ }+ } catch {+ // Edge Runtime — no process.stdout, skip patching+ }++ // Suppress noisy third-party warnings in dev+ const origWarn = console.warn+ console.warn = (...args: unknown[]) => {+ const first = typeof args[0] === "string" ? args[0] : ""+ if (SUPPRESSED_WARNINGS.some((s) => first.includes(s))) return+ origWarn(...args)+ }+}diff --git a/src/web/src/lib/logger.test.ts b/src/web/src/lib/logger.test.tsindex 2141f0ddb..edf773f89 100644--- a/src/web/src/lib/logger.test.ts+++ b/src/web/src/lib/logger.test.ts@@ -70,6 +70,37 @@ describe("Logger", () => {expect(serialized.message).toBe("bad input");});+ it("pretty mode outputs human-readable line with datetime", () => {+ const logger = new Logger({ service: "web", pretty: true });+ logger.info("hello");++ const line = logSpy.mock.calls[0][0] as string;+ expect(line.startsWith("{")).toBe(false);+ expect(line).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/);+ expect(line).toContain("INFO");+ expect(line).toContain("[web]");+ expect(line).toContain("hello");+ });++ it("pretty mode includes context fields as key=value pairs", () => {+ const logger = new Logger({ service: "web", pretty: true });+ logger.info("request", { method: "GET", status: 200 });++ const line = logSpy.mock.calls[0][0] as string;+ expect(line).toContain("method=GET");+ expect(line).toContain("status=200");+ });++ it("pretty mode errors go to console.error", () => {+ const logger = new Logger({ service: "web", pretty: true });+ logger.error("boom");++ expect(errorSpy).toHaveBeenCalledTimes(1);+ const line = errorSpy.mock.calls[0][0] as string;+ expect(line).toContain("ERROR");+ expect(line).toContain("boom");+ });+it("silent level suppresses all output", () => {const logger = new Logger({ service: "web", level: "silent" });logger.debug("nope");diff --git a/src/web/src/lib/logger.ts b/src/web/src/lib/logger.tsindex 77dcf3517..61b145026 100644--- a/src/web/src/lib/logger.ts+++ b/src/web/src/lib/logger.ts@@ -6,4 +6,5 @@ export { Logger, createLogger }export const log = createLogger({service: "web",level: (process.env.ALOOK_LOG_LEVEL as "debug" | "info" | "warn" | "error" | "silent") || "info",+ pretty: process.env.NODE_ENV === "development",})diff --git a/src/web/src/test/e2e/workspace.test.ts b/src/web/src/test/e2e/workspace.test.tsindex 3e5cebdf9..fd66a113b 100644--- a/src/web/src/test/e2e/workspace.test.ts+++ b/src/web/src/test/e2e/workspace.test.ts@@ -40,13 +40,18 @@ describe("workspace", () => {workspaceId = data.id as string})- it("POST /api/workspaces rejects duplicate slug", async () => {+ it("POST /api/workspaces auto-suffixes duplicate slug", async () => {const res = await sessionRequest("/api/workspaces", cookie, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: "Dup Workspace", slug }),})- expect(res.status).toBe(409)+ expect(res.status).toBe(201)+ const data = await res.json() as Record<string, unknown>+ expect(data.name).toBe("Dup Workspace")+ // Slug should start with the original slug but have a suffix+ expect(data.slug).not.toBe(slug)+ expect((data.slug as string).startsWith(`${slug}-`)).toBe(true)})it("GET /api/workspaces lists user's workspaces", async () => {