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
|
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";
export type VoiceIntent = "spec" | "issue" | "unclear";
export interface VoiceInterpretation {
kind: VoiceIntent;
title: string;
body_markdown: string;
target_repo_id_hint?: string;
}
export interface InterpretArgs {
transcript: string;
knownRepos?: Array<{ id: string; fullName: string }>;
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;
slugOverride?: string;
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 };
export function voiceSlug(text: string): string {
const base = (text || "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 40);
return base || "voice-note";
}
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";
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,
};
}
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 };
}
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>"
}`;
}
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" };
if (!args.client && !config.anthropicApiKey) {
return { ok: true, suggestion: classifyHeuristically(transcript) };
}
const prompt = buildInterpretPrompt(transcript, args.knownRepos || []);
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",
};
}
}
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 {
}
const text = extractText(msg);
const parsed = safeParseJson(text);
return {
ok: true,
suggestion: normaliseInterpretation(parsed, transcript),
};
} catch (err) {
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;
const fenced = text.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
const candidate = fenced ? fenced[1] : null;
if (candidate) {
try {
return JSON.parse(candidate);
} catch {
}
}
const braced = text.match(/\{[\s\S]*\}/);
if (braced) {
try {
return JSON.parse(braced[0]);
} catch {
return null;
}
}
return null;
}
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;
}
}
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" };
const interp =
args.interpretation || classifyHeuristically(transcript);
const slug =
args.slugOverride && args.slugOverride.trim()
? voiceSlug(args.slugOverride)
: voiceSlug(interp.title || transcript);
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,
};
}
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" };
try {
await db
.update(repositories)
.set({ issueCount: (repoRow.issueCount || 0) + 1 })
.where(eq(repositories.id, repoRow.id));
} catch {
}
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)}`,
};
}
}
export const __voiceTest = {
classifyHeuristically,
safeParseJson,
resolveRepoAndAuthor,
};
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 [];
}
}
|