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
voice-to-pr.ts17.8 KB · 561 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
/**
 * Voice-to-PR — phone-first dictation pipeline.
 *
 * The `/voice` route captures a browser Web Speech API transcript and posts
 * it here. This module turns that transcript into one of three outcomes:
 *
 *   1. `interpretVoiceTranscript` — sends the transcript to Claude with a
 *      tight classification prompt. Returns a discriminated union telling
 *      the route whether to treat the utterance as a *spec*, an *issue*,
 *      or "unclear" (ambiguous → user picks). The model also returns a
 *      polished title + body markdown so the eventual spec/issue isn't
 *      just raw dictation noise.
 *
 *   2. `shipAsSpec` — writes a `.gluecron/specs/voice-<slug>.md` file to
 *      the repo's default branch with `status: ready`. The autopilot loop
 *      (`autopilot-spec-to-pr.ts`) picks it up on the next tick and runs
 *      the full spec-to-PR pipeline against it. This is intentionally a
 *      thin wrapper around `createOrUpdateFileOnBranch` + the spec
 *      front-matter format — it reuses the existing flow rather than
 *      duplicating any of `runSpecToPr`.
 *
 *   3. `createIssueFromVoice` — inserts a row directly into the `issues`
 *      table mirroring `src/routes/issues.tsx`. Kept here so the route
 *      handler stays tiny and so the unit tests can exercise the flow
 *      without going through the HTTP layer.
 *
 * Hard contract:
 *   - No function throws. Every failure path returns
 *     `{ok:false, error:string}`.
 *   - When `ANTHROPIC_API_KEY` is missing, `interpretVoiceTranscript`
 *     returns a deterministic best-effort fallback so the demo still
 *     works on machines without an API key.
 *   - The shared layout / locked files are never touched here.
 */

import { and, eq } from "drizzle-orm";
import { db } from "../db";
import { issues, repositories, users } from "../db/schema";
import { createOrUpdateFileOnBranch } from "../git/repository";
import { config } from "./config";
import { serialiseSpec } from "./spec-to-pr";

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

export type VoiceIntent = "spec" | "issue" | "unclear";

export interface VoiceInterpretation {
  kind: VoiceIntent;
  title: string;
  body_markdown: string;
  /** Optional hint surfaced by the model (e.g. "the dashboard repo"). */
  target_repo_id_hint?: string;
}

export interface InterpretArgs {
  transcript: string;
  /** Optional list of the user's repos so the model can suggest one. */
  knownRepos?: Array<{ id: string; fullName: string }>;
  /** Test-only injection. */
  client?: { call: (prompt: string) => Promise<string> };
}

export type InterpretResult =
  | { ok: true; suggestion: VoiceInterpretation }
  | { ok: false; error: string };

export interface ShipSpecArgs {
  repositoryId: string;
  transcript: string;
  userId: string;
  /** Override the deterministic slug — only used in tests. */
  slugOverride?: string;
  /** Pre-computed interpretation; lets the route reuse a single Claude call. */
  interpretation?: VoiceInterpretation;
}

export type ShipSpecResult =
  | {
      ok: true;
      specPath: string;
      commitSha: string;
      branch: string;
    }
  | { ok: false; error: string };

export interface CreateIssueArgs {
  repositoryId: string;
  transcript: string;
  userId: string;
  interpretation?: VoiceInterpretation;
}

export type CreateIssueResult =
  | {
      ok: true;
      issueNumber: number;
      ownerName: string;
      repoName: string;
    }
  | { ok: false; error: string };

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/**
 * Derive a stable, URL-safe slug for the voice spec filename. Capped at 40
 * chars so the resulting path stays short.
 */
export function voiceSlug(text: string): string {
  const base = (text || "")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 40);
  return base || "voice-note";
}

/** Heuristic fallback used when the Claude API key is missing. */
function classifyHeuristically(transcript: string): VoiceInterpretation {
  const t = transcript.trim();
  const lower = t.toLowerCase();
  const looksLikeBug =
    /(bug|broken|crash|error|doesn'?t work|not working|regression|fails?)/i.test(
      lower
    );
  const looksLikeFeature =
    /(add|build|implement|create|wire up|ship|introduce|support)/i.test(lower);
  const kind: VoiceIntent = looksLikeBug
    ? "issue"
    : looksLikeFeature
      ? "spec"
      : "unclear";
  // First clause becomes the title; cap at 80 chars.
  const firstClause =
    t.split(/[.!?\n]/)[0]?.trim() || t.slice(0, 80) || "Voice note";
  const title = firstClause.length > 80 ? `${firstClause.slice(0, 77)}...` : firstClause;
  return {
    kind,
    title: title.replace(/^[a-z]/, (c) => c.toUpperCase()),
    body_markdown: t,
  };
}

/**
 * Sanitise the model's response into a `VoiceInterpretation`. Anything that
 * doesn't conform falls back to "unclear" so the UI shows the picker.
 */
export function normaliseInterpretation(
  raw: unknown,
  fallbackBody: string
): VoiceInterpretation {
  if (!raw || typeof raw !== "object") {
    return classifyHeuristically(fallbackBody);
  }
  const r = raw as Record<string, unknown>;
  const kindRaw = typeof r.kind === "string" ? r.kind.toLowerCase() : "";
  const kind: VoiceIntent =
    kindRaw === "spec" || kindRaw === "issue" || kindRaw === "unclear"
      ? (kindRaw as VoiceIntent)
      : "unclear";
  const title =
    typeof r.title === "string" && r.title.trim()
      ? r.title.trim().slice(0, 120)
      : classifyHeuristically(fallbackBody).title;
  const body =
    typeof r.body_markdown === "string" && r.body_markdown.trim()
      ? r.body_markdown.trim()
      : fallbackBody.trim();
  const hint =
    typeof r.target_repo_id_hint === "string" && r.target_repo_id_hint.trim()
      ? r.target_repo_id_hint.trim().slice(0, 200)
      : undefined;
  return { kind, title, body_markdown: body, target_repo_id_hint: hint };
}

/**
 * Build the prompt sent to Claude. Kept in its own function so the test
 * harness can assert on its contents if needed.
 */
export function buildInterpretPrompt(
  transcript: string,
  knownRepos: Array<{ id: string; fullName: string }>
): string {
  const repoBlock =
    knownRepos.length > 0
      ? `\n\nThe user's available repositories (id — name):\n${knownRepos
          .slice(0, 25)
          .map((r) => `- ${r.id}${r.fullName}`)
          .join("\n")}`
      : "";
  return `You are classifying a phone-dictated note from a developer. They have just spoken into the Gluecron "voice-to-PR" feature and we need to decide what to do with their utterance.

The transcript:
"""
${transcript.trim().slice(0, 4000)}
"""${repoBlock}

Decide which of the following best fits:
  - "spec"   : the user is describing a feature or change they want built. The autopilot will turn this into a draft PR via spec-to-PR.
  - "issue"  : the user is reporting a bug, a question, or an observation that should be filed for discussion, not implemented immediately.
  - "unclear": you can't confidently decide — let the user pick.

Polish the transcript into:
  - A short imperative "title" (under 80 chars).
  - A "body_markdown" expanding the request as a proper feature spec or bug report. Keep it faithful to what was said; do NOT invent acceptance criteria the user didn't mention. Format with short paragraphs or bullet lists where helpful.

Respond ONLY with JSON in this exact shape:
{
  "kind": "spec" | "issue" | "unclear",
  "title": "...",
  "body_markdown": "...",
  "target_repo_id_hint": "<repo-id from the list above, or omit>"
}`;
}

// ---------------------------------------------------------------------------
// interpretVoiceTranscript
// ---------------------------------------------------------------------------

/**
 * Classify and polish a voice transcript. Never throws.
 *
 * Test injection: pass `client.call(prompt)` to swap out the real Claude
 * call with a stub returning a JSON string.
 */
export async function interpretVoiceTranscript(
  args: InterpretArgs
): Promise<InterpretResult> {
  const transcript =
    typeof args.transcript === "string" ? args.transcript.trim() : "";
  if (!transcript) return { ok: false, error: "transcript is empty" };

  // Graceful degrade — no key, no model, but still a usable response.
  if (!args.client && !config.anthropicApiKey) {
    return { ok: true, suggestion: classifyHeuristically(transcript) };
  }

  const prompt = buildInterpretPrompt(transcript, args.knownRepos || []);

  // Test injection path.
  if (args.client) {
    try {
      const text = await args.client.call(prompt);
      const parsed = safeParseJson(text);
      return {
        ok: true,
        suggestion: normaliseInterpretation(parsed, transcript),
      };
    } catch (err) {
      return {
        ok: false,
        error: err instanceof Error ? err.message : "client.call threw",
      };
    }
  }

  // Real Claude call. Dynamic import keeps the SDK out of the test bundle
  // and means a missing dep never crashes the route.
  try {
    const { getAnthropic, MODEL_SONNET, extractText } = await import(
      "./ai-client"
    );
    const client = getAnthropic();
    const msg = await client.messages.create({
      model: MODEL_SONNET,
      max_tokens: 1024,
      messages: [{ role: "user", content: prompt }],
    });
    try {
      const { recordAiCost, extractUsage } = await import(
        "./ai-cost-tracker"
      );
      const usage = extractUsage(msg);
      await recordAiCost({
        model: MODEL_SONNET,
        inputTokens: usage.input,
        outputTokens: usage.output,
        category: "voice",
        sourceKind: "voice_transcript",
      });
    } catch {
      /* swallow — best-effort */
    }
    const text = extractText(msg);
    const parsed = safeParseJson(text);
    return {
      ok: true,
      suggestion: normaliseInterpretation(parsed, transcript),
    };
  } catch (err) {
    // Fall back to the heuristic so the demo doesn't dead-end on a 429.
    const fallback = classifyHeuristically(transcript);
    if (process.env.DEBUG_VOICE === "1") {
      console.warn(
        "[voice] Claude call failed, using heuristic:",
        err instanceof Error ? err.message : err
      );
    }
    return { ok: true, suggestion: fallback };
  }
}

function safeParseJson(text: string): unknown {
  if (!text) return null;
  // Try a fenced block first.
  const fenced = text.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
  const candidate = fenced ? fenced[1] : null;
  if (candidate) {
    try {
      return JSON.parse(candidate);
    } catch {
      /* fall through */
    }
  }
  const braced = text.match(/\{[\s\S]*\}/);
  if (braced) {
    try {
      return JSON.parse(braced[0]);
    } catch {
      return null;
    }
  }
  return null;
}

// ---------------------------------------------------------------------------
// shipAsSpec
// ---------------------------------------------------------------------------

/**
 * Resolve repo + owner + author rows for a given repository / user combo.
 * Returns null on any miss so callers can return a clean error.
 */
async function resolveRepoAndAuthor(
  repositoryId: string,
  userId: string
): Promise<
  | {
      ownerName: string;
      repoName: string;
      defaultBranch: string;
      authorName: string;
      authorEmail: string;
    }
  | null
> {
  try {
    const [row] = await db
      .select({
        repoName: repositories.name,
        defaultBranch: repositories.defaultBranch,
        ownerName: users.username,
      })
      .from(repositories)
      .leftJoin(users, eq(users.id, repositories.ownerId))
      .where(eq(repositories.id, repositoryId))
      .limit(1);
    if (!row || !row.ownerName) return null;

    const [authorRow] = await db
      .select({ username: users.username, email: users.email })
      .from(users)
      .where(eq(users.id, userId))
      .limit(1);
    if (!authorRow) return null;

    return {
      ownerName: row.ownerName,
      repoName: row.repoName,
      defaultBranch: row.defaultBranch || "main",
      authorName: authorRow.username,
      authorEmail:
        authorRow.email || `${authorRow.username}@users.noreply.gluecron`,
    };
  } catch {
    return null;
  }
}

/**
 * Commit a `.gluecron/specs/voice-<slug>.md` spec to the repo's default
 * branch with `status: ready`. The autopilot picks it up on the next tick.
 */
export async function shipAsSpec(
  args: ShipSpecArgs
): Promise<ShipSpecResult> {
  const transcript =
    typeof args.transcript === "string" ? args.transcript.trim() : "";
  if (!transcript) return { ok: false, error: "transcript is empty" };
  if (!args.repositoryId) return { ok: false, error: "repository_id required" };
  if (!args.userId) return { ok: false, error: "userId required" };

  const resolved = await resolveRepoAndAuthor(args.repositoryId, args.userId);
  if (!resolved) return { ok: false, error: "repo or user not found" };

  // Use the supplied interpretation when present, otherwise fall back to
  // the heuristic so we always have a polished title.
  const interp =
    args.interpretation || classifyHeuristically(transcript);
  const slug =
    args.slugOverride && args.slugOverride.trim()
      ? voiceSlug(args.slugOverride)
      : voiceSlug(interp.title || transcript);
  // Stamp the filename with a short timestamp so back-to-back voice notes
  // with the same slug don't collide on the autopilot dedup.
  const specPath = `.gluecron/specs/voice-${slug}-${Date.now().toString(36)}.md`;

  const fm: Record<string, string> = {
    title: interp.title || "Voice spec",
    status: "ready",
    source: "voice-to-pr",
  };
  const body = `# ${interp.title || "Voice spec"}\n\n${interp.body_markdown || transcript}\n\n---\n\n_Captured via Gluecron voice-to-PR._\n`;
  const content = serialiseSpec(fm, body);
  const bytes = new TextEncoder().encode(content);

  const res = await createOrUpdateFileOnBranch({
    owner: resolved.ownerName,
    name: resolved.repoName,
    branch: resolved.defaultBranch,
    filePath: specPath,
    bytes,
    message: `voice: ${interp.title || "captured spec"}`,
    authorName: resolved.authorName,
    authorEmail: resolved.authorEmail,
  });
  if ("error" in res) {
    return { ok: false, error: `git write failed: ${res.error}` };
  }
  return {
    ok: true,
    specPath,
    commitSha: res.commitSha,
    branch: resolved.defaultBranch,
  };
}

// ---------------------------------------------------------------------------
// createIssueFromVoice
// ---------------------------------------------------------------------------

/**
 * Insert an issue row mirroring `src/routes/issues.tsx`. The route handler
 * wires up the AI triage trigger separately so this function stays
 * dependency-light + easy to test.
 */
export async function createIssueFromVoice(
  args: CreateIssueArgs
): Promise<CreateIssueResult> {
  const transcript =
    typeof args.transcript === "string" ? args.transcript.trim() : "";
  if (!transcript) return { ok: false, error: "transcript is empty" };
  if (!args.repositoryId) return { ok: false, error: "repository_id required" };
  if (!args.userId) return { ok: false, error: "userId required" };

  let repoRow:
    | {
        id: string;
        name: string;
        issueCount: number;
        ownerName: string | null;
      }
    | undefined;
  try {
    const [row] = await db
      .select({
        id: repositories.id,
        name: repositories.name,
        issueCount: repositories.issueCount,
        ownerName: users.username,
      })
      .from(repositories)
      .leftJoin(users, eq(users.id, repositories.ownerId))
      .where(eq(repositories.id, args.repositoryId))
      .limit(1);
    repoRow = row;
  } catch {
    return { ok: false, error: "db lookup failed" };
  }
  if (!repoRow || !repoRow.ownerName) {
    return { ok: false, error: "repo not found" };
  }

  const interp = args.interpretation || classifyHeuristically(transcript);
  const title = (interp.title || transcript.slice(0, 80)).slice(0, 200);
  const body = `${interp.body_markdown || transcript}\n\n---\n\n_Captured via Gluecron voice-to-PR._`;

  try {
    const [issue] = await db
      .insert(issues)
      .values({
        repositoryId: repoRow.id,
        authorId: args.userId,
        title,
        body,
      })
      .returning();
    if (!issue) return { ok: false, error: "issue insert returned no row" };
    // Best-effort counter update; mirrors src/routes/issues.tsx.
    try {
      await db
        .update(repositories)
        .set({ issueCount: (repoRow.issueCount || 0) + 1 })
        .where(eq(repositories.id, repoRow.id));
    } catch {
      /* non-fatal */
    }
    return {
      ok: true,
      issueNumber: issue.number,
      ownerName: repoRow.ownerName,
      repoName: repoRow.name,
    };
  } catch (err) {
    return {
      ok: false,
      error: `issue insert failed: ${err instanceof Error ? err.message : String(err)}`,
    };
  }
}

// ---------------------------------------------------------------------------
// Test-only exports
// ---------------------------------------------------------------------------

export const __voiceTest = {
  classifyHeuristically,
  safeParseJson,
  resolveRepoAndAuthor,
};

/** True if access to the user's repo list should fan out (used by the route). */
export async function listUserRepos(
  userId: string
): Promise<Array<{ id: string; fullName: string }>> {
  try {
    const rows = await db
      .select({
        id: repositories.id,
        name: repositories.name,
        ownerName: users.username,
      })
      .from(repositories)
      .leftJoin(users, eq(users.id, repositories.ownerId))
      .where(
        and(
          eq(repositories.ownerId, userId),
          eq(repositories.isArchived, false)
        )
      )
      .limit(100);
    return rows
      .filter((r) => r.ownerName)
      .map((r) => ({ id: r.id, fullName: `${r.ownerName}/${r.name}` }));
  } catch {
    return [];
  }
}