Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
agent-multiplayer.ts12.1 KB · 408 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/**
 * Agent multiplayer v1 — sessions, leases, budgets.
 *
 * Goal: when 10-100 AI agents push to the same repo, they don't step on
 * each other. Each agent gets a stable session with:
 *   - a token (`agt_<hex>`) used as Bearer credentials,
 *   - a `branch_namespace` prefix the git plumbing enforces on every
 *     ref update,
 *   - a daily spend budget (cents) that callers consult via
 *     `chargeAgent()` before billing an action.
 *
 * Coordination on shared targets (issues, PRs, file paths, branches)
 * flows through `agent_leases` — a soft mutex with a TTL. The active
 * lease is enforced by a partial UNIQUE index on
 * (target_type, target_id) WHERE status='active'; conflicting INSERTs
 * raise a 23505 we translate to `null`.
 *
 * All helpers swallow DB errors and return null/false, matching the
 * graceful-degradation pattern used elsewhere on this codebase. Pure
 * format helpers (token generation, namespace normalisation) work
 * without a DB so unit tests can exercise them in isolation.
 */

import { and, eq, lt, sql } from "drizzle-orm";
import { db } from "../db";
import { agentSessions, agentLeases } from "../db/schema";
import type { AgentSession, AgentLease } from "../db/schema";

/** Plaintext token prefix — distinct from PAT (`glc_`) and OAuth (`glct_`). */
export const AGENT_TOKEN_PREFIX = "agt_";

/** Default lease duration when callers don't supply one. */
export const DEFAULT_LEASE_DURATION_MS = 5 * 60 * 1000;

/** Recognised target_type values. Keep in sync with the migration comment. */
export const LEASE_TARGET_TYPES = [
  "issue",
  "pr",
  "file_path",
  "branch",
] as const;
export type LeaseTargetType = (typeof LEASE_TARGET_TYPES)[number];

// ---------------------------------------------------------------------------
// Pure helpers (no DB)
// ---------------------------------------------------------------------------

/** 32-byte hex token, `agt_`-prefixed. Mirrors the PAT generator shape. */
export function generateAgentToken(): string {
  const bytes = crypto.getRandomValues(new Uint8Array(32));
  return (
    AGENT_TOKEN_PREFIX +
    Array.from(bytes)
      .map((b) => b.toString(16).padStart(2, "0"))
      .join("")
  );
}

/** SHA-256 hex of the plaintext token — what we persist. */
export async function hashAgentToken(token: string): Promise<string> {
  const data = new TextEncoder().encode(token);
  const digest = await crypto.subtle.digest("SHA-256", data);
  return Array.from(new Uint8Array(digest))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

/**
 * Detect the agent token shape. Used by middleware to short-circuit
 * before hitting the DB on regular PAT/OAuth tokens.
 */
export function isAgentToken(token: string): boolean {
  return /^agt_[0-9a-f]{64}$/.test(token);
}

/**
 * Normalise a caller-supplied branch namespace to a canonical
 * `agents/<name>/` form. We keep it lower-case, strip leading
 * `refs/heads/`, and force a trailing slash so `startsWith()` checks
 * elsewhere are unambiguous.
 */
export function normaliseBranchNamespace(name: string, raw?: string): string {
  let ns = (raw ?? `agents/${name}`).trim();
  if (ns.startsWith("refs/heads/")) ns = ns.slice("refs/heads/".length);
  ns = ns.replace(/^\/+|\/+$/g, ""); // strip surrounding slashes
  if (!ns) ns = `agents/${name}`;
  return ns + "/";
}

/**
 * Check whether a fully-qualified ref (e.g. `refs/heads/agents/claude-1/foo`)
 * sits inside the agent's allowed namespace. The caller is expected to pass
 * a fully-qualified ref OR a short branch name — both work.
 */
export function refIsInNamespace(ref: string, namespace: string): boolean {
  const short = ref.startsWith("refs/heads/")
    ? ref.slice("refs/heads/".length)
    : ref;
  return short.startsWith(namespace);
}

// ---------------------------------------------------------------------------
// Session lifecycle
// ---------------------------------------------------------------------------

export interface CreateAgentSessionInput {
  ownerUserId: string;
  name: string;
  repositoryId?: string | null;
  branchNamespace?: string;
  budgetCentsPerDay?: number;
}

export interface CreateAgentSessionResult {
  session: AgentSession;
  /** Plaintext token — returned exactly once, never persisted. */
  token: string;
}

/**
 * Mint a new agent session. Returns the plaintext token alongside the
 * stored row so the caller can hand it to the agent. The token is only
 * recoverable here; we persist only its SHA-256 hash.
 */
export async function createAgentSession(
  input: CreateAgentSessionInput
): Promise<CreateAgentSessionResult | null> {
  const name = input.name.trim();
  if (!name) return null;

  const token = generateAgentToken();
  const tokenHash = await hashAgentToken(token);
  const branchNamespace = normaliseBranchNamespace(name, input.branchNamespace);
  const budget =
    typeof input.budgetCentsPerDay === "number" && input.budgetCentsPerDay >= 0
      ? Math.floor(input.budgetCentsPerDay)
      : 500;

  try {
    const [row] = await db
      .insert(agentSessions)
      .values({
        name,
        ownerUserId: input.ownerUserId,
        repositoryId: input.repositoryId ?? null,
        tokenHash,
        branchNamespace,
        budgetCentsPerDay: budget,
        spentCentsToday: 0,
      })
      .returning();
    if (!row) return null;
    return { session: row, token };
  } catch {
    return null;
  }
}

/**
 * Look up a session by plaintext token. Returns null if the token is
 * malformed, unknown, or the DB call throws. Side-effect: bumps
 * `last_active_at` on a hit (fire-and-forget).
 */
export async function authenticateAgent(
  token: string
): Promise<AgentSession | null> {
  if (!isAgentToken(token)) return null;
  try {
    const tokenHash = await hashAgentToken(token);
    const [row] = await db
      .select()
      .from(agentSessions)
      .where(eq(agentSessions.tokenHash, tokenHash))
      .limit(1);
    if (!row) return null;
    // Fire-and-forget — never block the request on the activity bump.
    db.update(agentSessions)
      .set({ lastActiveAt: new Date() })
      .where(eq(agentSessions.id, row.id))
      .catch(() => undefined);
    return row;
  } catch {
    return null;
  }
}

export async function listAgentSessionsForOwner(
  ownerUserId: string
): Promise<AgentSession[]> {
  try {
    return await db
      .select()
      .from(agentSessions)
      .where(eq(agentSessions.ownerUserId, ownerUserId));
  } catch {
    return [];
  }
}

export async function revokeAgentSession(
  sessionId: string,
  ownerUserId: string
): Promise<boolean> {
  try {
    const result = await db
      .delete(agentSessions)
      .where(
        and(
          eq(agentSessions.id, sessionId),
          eq(agentSessions.ownerUserId, ownerUserId)
        )
      )
      .returning({ id: agentSessions.id });
    return result.length > 0;
  } catch {
    return false;
  }
}

// ---------------------------------------------------------------------------
// Leases
// ---------------------------------------------------------------------------

/**
 * Try to grab an exclusive lease on a target. Returns the lease row on
 * success, null when another agent already holds an active lease. The
 * uniqueness invariant is enforced by a partial UNIQUE index, so this
 * is race-safe even under concurrent INSERTs — the loser hits a 23505
 * we translate to null.
 *
 * Before INSERT we sweep any expired-but-still-active rows for this
 * target, flipping their status to 'expired' so a stale holder doesn't
 * block a fresh request.
 */
export async function acquireLease(
  agentSessionId: string,
  targetType: string,
  targetId: string,
  durationMs: number = DEFAULT_LEASE_DURATION_MS
): Promise<AgentLease | null> {
  if (!agentSessionId || !targetType || !targetId) return null;
  const now = new Date();
  const expiresAt = new Date(now.getTime() + Math.max(1, durationMs));

  try {
    // Expire stale leases on this target so the unique index doesn't
    // wrongly block a new acquire.
    await db
      .update(agentLeases)
      .set({ status: "expired" })
      .where(
        and(
          eq(agentLeases.targetType, targetType),
          eq(agentLeases.targetId, targetId),
          eq(agentLeases.status, "active"),
          lt(agentLeases.expiresAt, now)
        )
      );

    const [row] = await db
      .insert(agentLeases)
      .values({
        agentSessionId,
        targetType,
        targetId,
        acquiredAt: now,
        expiresAt,
        status: "active",
      })
      .returning();
    return row ?? null;
  } catch {
    // 23505 unique violation (another active lease) or any other DB error
    // — treat as "couldn't acquire". The caller should fall back.
    return null;
  }
}

export async function releaseLease(leaseId: string): Promise<boolean> {
  if (!leaseId) return false;
  try {
    const result = await db
      .update(agentLeases)
      .set({ status: "released" })
      .where(
        and(eq(agentLeases.id, leaseId), eq(agentLeases.status, "active"))
      )
      .returning({ id: agentLeases.id });
    return result.length > 0;
  } catch {
    return false;
  }
}

export async function listLeasesForAgent(
  agentSessionId: string
): Promise<AgentLease[]> {
  try {
    return await db
      .select()
      .from(agentLeases)
      .where(eq(agentLeases.agentSessionId, agentSessionId));
  } catch {
    return [];
  }
}

/**
 * Mark every active lease whose `expires_at` has passed as 'expired'.
 * Safe to call from the autopilot ticker.
 */
export async function expireStaleLeases(now: Date = new Date()): Promise<number> {
  try {
    const result = await db
      .update(agentLeases)
      .set({ status: "expired" })
      .where(
        and(eq(agentLeases.status, "active"), lt(agentLeases.expiresAt, now))
      )
      .returning({ id: agentLeases.id });
    return result.length;
  } catch {
    return 0;
  }
}

// ---------------------------------------------------------------------------
// Budgets
// ---------------------------------------------------------------------------

/**
 * Atomically attempt to charge `cents` against an agent's daily budget.
 * Returns true when the charge was recorded, false when the agent is
 * over budget (caller should refuse the request).
 *
 * We use a single UPDATE with a WHERE clause that includes the budget
 * predicate, so we never race against a parallel charger: either the
 * row update succeeds (we landed under cap) or it doesn't (over).
 */
export async function chargeAgent(
  agentSessionId: string,
  cents: number
): Promise<boolean> {
  if (!agentSessionId) return false;
  const amount = Math.max(0, Math.floor(cents));
  if (amount === 0) return true; // free actions still pass.

  try {
    const result = await db
      .update(agentSessions)
      .set({
        spentCentsToday: sql`${agentSessions.spentCentsToday} + ${amount}`,
      })
      .where(
        and(
          eq(agentSessions.id, agentSessionId),
          // spent + amount must still fit under cap.
          sql`${agentSessions.spentCentsToday} + ${amount} <= ${agentSessions.budgetCentsPerDay}`
        )
      )
      .returning({ id: agentSessions.id });
    return result.length > 0;
  } catch {
    return false;
  }
}

/** Convenience getter — returns 0 spent / 0 cap when the session is missing. */
export async function getAgentUsage(agentSessionId: string): Promise<{
  spent: number;
  cap: number;
  remaining: number;
}> {
  try {
    const [row] = await db
      .select({
        spent: agentSessions.spentCentsToday,
        cap: agentSessions.budgetCentsPerDay,
      })
      .from(agentSessions)
      .where(eq(agentSessions.id, agentSessionId))
      .limit(1);
    if (!row) return { spent: 0, cap: 0, remaining: 0 };
    return {
      spent: row.spent,
      cap: row.cap,
      remaining: Math.max(0, row.cap - row.spent),
    };
  } catch {
    return { spent: 0, cap: 0, remaining: 0 };
  }
}

/**
 * Reset every agent's `spent_cents_today` to 0. Designed to run at the
 * UTC day boundary from the autopilot.
 */
export async function resetDailyBudgets(): Promise<number> {
  try {
    const result = await db
      .update(agentSessions)
      .set({ spentCentsToday: 0 })
      .returning({ id: agentSessions.id });
    return result.length;
  } catch {
    return 0;
  }
}