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
commit.ts10.2 KB · 319 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
/**
 * `gluecron commit` — wrap `git commit` with an AI-drafted message.
 *
 * Flow:
 *   1. If `-m` is provided, just shell out to git commit verbatim.
 *   2. Otherwise:
 *        a. Stage all if `-a` was passed.
 *        b. Read `git diff --cached`.
 *        c. POST to `/api/v2/ai/commit-message`.
 *        d. Print the proposed subject + body and prompt
 *           [y]es / [e]dit / [n]o.
 *        e. yes  → git commit -m <subject> -m <body>
 *           edit → drop into $EDITOR with the message pre-filled,
 *                  then `git commit -F <tmp>` after the editor exits.
 *           no   → abort.
 *
 * The CLI is dependency-free Bun; we shell out to `git` via Bun.spawnSync.
 * All exported helpers are pure functions so the test suite can exercise
 * them without a real git repository.
 */

import { spawnSync } from "node:child_process";
import { writeFileSync, mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

export interface CommitMessage {
  subject: string;
  body: string;
}

export interface CommitConfig {
  host: string;
  token?: string;
}

// ──────────────────────────── arg parsing ────────────────────────────

export interface CommitArgs {
  stageAll: boolean;
  message?: string;
  bodyExtra?: string;
  style: "conventional" | "plain";
  yes: boolean; // --yes / -y → skip the prompt
}

export function parseCommitArgs(argv: string[]): CommitArgs {
  const args: CommitArgs = {
    stageAll: false,
    style: "conventional",
    yes: false,
  };
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i];
    if (a === "-a" || a === "--all") {
      args.stageAll = true;
    } else if (a === "-m" || a === "--message") {
      args.message = argv[++i];
    } else if (a === "-y" || a === "--yes") {
      args.yes = true;
    } else if (a === "--plain") {
      args.style = "plain";
    } else if (a === "--conventional") {
      args.style = "conventional";
    }
  }
  return args;
}

// ──────────────────────────── git wrappers ────────────────────────────

function git(
  argv: string[],
  opts: { input?: string; cwd?: string } = {}
): { stdout: string; stderr: string; exitCode: number } {
  const r = spawnSync("git", argv, {
    cwd: opts.cwd ?? process.cwd(),
    input: opts.input,
    encoding: "utf8",
    stdio: ["pipe", "pipe", "pipe"],
  });
  return {
    stdout: r.stdout || "",
    stderr: r.stderr || "",
    exitCode: r.status ?? 1,
  };
}

export function readStagedDiff(stageAll: boolean): string {
  // -a in `git commit` stages tracked changes before committing. We
  // emulate that by passing `--cached` after a `git add -u` (tracked
  // only — `git add -A` would sweep up untracked, which is NOT what
  // `git commit -a` does).
  if (stageAll) {
    git(["add", "-u"]);
  }
  const r = git(["diff", "--cached"]);
  if (r.exitCode !== 0) return "";
  return r.stdout;
}

// ──────────────────────────── API call ────────────────────────────

export async function requestCommitMessage(
  cfg: CommitConfig,
  diff: string,
  style: "conventional" | "plain",
  fetchImpl: typeof fetch = fetch
): Promise<CommitMessage> {
  const url = cfg.host.replace(/\/+$/, "") + "/api/v2/ai/commit-message";
  const headers: Record<string, string> = {
    "content-type": "application/json",
    accept: "application/json",
  };
  if (cfg.token) headers.authorization = `Bearer ${cfg.token}`;

  const res = await fetchImpl(url, {
    method: "POST",
    headers,
    body: JSON.stringify({ diff, style }),
  });
  const text = await res.text();
  let json: { subject?: string; body?: string; error?: string };
  try {
    json = JSON.parse(text);
  } catch {
    throw new Error(`Server returned non-JSON [${res.status}]: ${text.slice(0, 200)}`);
  }
  if (!res.ok) {
    throw new Error(json?.error || `Server returned ${res.status}`);
  }
  return {
    subject: typeof json.subject === "string" ? json.subject : "",
    body: typeof json.body === "string" ? json.body : "",
  };
}

// ──────────────────────────── prompt + editor ────────────────────────────

export function formatProposedMessage(m: CommitMessage): string {
  let out = `\nProposed commit message:\n\n  ${m.subject}\n`;
  if (m.body.trim()) {
    out += "\n";
    for (const line of m.body.split("\n")) {
      out += `  ${line}\n`;
    }
  }
  return out;
}

async function readChar(prompt: string): Promise<string> {
  process.stdout.write(prompt);
  return new Promise((resolve) => {
    const onData = (chunk: Buffer | string) => {
      process.stdin.removeListener("data", onData);
      process.stdin.pause();
      resolve(String(chunk).trim().toLowerCase());
    };
    process.stdin.resume();
    process.stdin.once("data", onData);
  });
}

export function editInEditor(m: CommitMessage): CommitMessage {
  const editor = process.env.EDITOR || process.env.VISUAL || "vi";
  const dir = mkdtempSync(join(tmpdir(), "gluecron-commit-"));
  const file = join(dir, "COMMIT_EDITMSG");
  const seed =
    m.subject +
    (m.body.trim() ? `\n\n${m.body}\n` : "\n") +
    "\n# Edit the commit message above. Lines starting with '#' are ignored.\n";
  writeFileSync(file, seed, "utf8");
  // Bun has no synchronous spawn with TTY inheritance — node:child_process
  // gives it to us cleanly. We block until the editor returns.
  spawnSync(editor, [file], { stdio: "inherit" });
  const raw = readFileSync(file, "utf8");
  const lines = raw
    .split("\n")
    .filter((l) => !l.startsWith("#"))
    .join("\n")
    .trim();
  if (!lines) return m;
  const subject = (lines.split("\n")[0] || "").trim();
  const body = lines.split("\n").slice(1).join("\n").trim();
  return { subject, body };
}

// ──────────────────────────── main command ────────────────────────────

export interface CommitDeps {
  out: (msg: string) => void;
  readChar?: (prompt: string) => Promise<string>;
  fetchImpl?: typeof fetch;
  editorEdit?: (m: CommitMessage) => CommitMessage;
  // Test-only override — lets us bypass the network without a fake fetch.
  generate?: (diff: string, style: "conventional" | "plain") => Promise<CommitMessage>;
}

/**
 * Run `gluecron commit`. Returns the exit code.
 *
 * Pulled out from the dispatcher so the CLI test suite can drive it
 * with synthetic deps and assert on behaviour without spawning git or
 * hitting the network.
 */
export async function runCommit(
  argv: string[],
  cfg: CommitConfig,
  deps: CommitDeps
): Promise<number> {
  const args = parseCommitArgs(argv);

  // Fast path: -m provided → straight pass-through to git.
  if (args.message) {
    const gitArgs = ["commit"];
    if (args.stageAll) gitArgs.push("-a");
    gitArgs.push("-m", args.message);
    if (args.bodyExtra) gitArgs.push("-m", args.bodyExtra);
    const r = spawnSync("git", gitArgs, { stdio: "inherit" });
    return r.status ?? 1;
  }

  // Pull the staged diff (after auto-adding tracked changes if -a).
  const diff = readStagedDiff(args.stageAll);
  if (!diff.trim()) {
    deps.out(
      "error: nothing to commit. Stage changes with `git add` (or pass -a)."
    );
    return 1;
  }

  // Ask the API for a message — or use the supplied generator (tests).
  let proposed: CommitMessage;
  try {
    proposed = deps.generate
      ? await deps.generate(diff, args.style)
      : await requestCommitMessage(cfg, diff, args.style, deps.fetchImpl);
  } catch (err) {
    deps.out(`error: ${(err as Error).message}`);
    return 1;
  }

  if (!proposed.subject.trim()) {
    deps.out("error: AI returned an empty subject. Try again or pass -m.");
    return 1;
  }

  deps.out(formatProposedMessage(proposed));

  // Skip prompt when --yes was passed (CI / scripted commits).
  let choice: string;
  if (args.yes) {
    choice = "y";
  } else {
    const rc = deps.readChar ?? readChar;
    choice = await rc("Commit with this message? [y/e/n]: ");
  }

  if (choice === "n" || choice === "no") {
    deps.out("Aborted.");
    return 1;
  }

  let final = proposed;
  if (choice === "e" || choice === "edit") {
    final = (deps.editorEdit ?? editInEditor)(proposed);
    if (!final.subject.trim()) {
      deps.out("Aborted — empty subject after edit.");
      return 1;
    }
  }

  // Commit. We use two `-m` arguments so git formats the body the usual
  // way (separated by a blank line from the subject).
  const commitArgs = ["commit", "-m", final.subject];
  if (final.body.trim()) {
    commitArgs.push("-m", final.body);
  }
  const r = spawnSync("git", commitArgs, { stdio: "inherit" });
  return r.status ?? 1;
}

// ──────────────────────────── `gluecron ai commit-msg` ────────────────────────────
//
// Used by the prepare-commit-msg hook. Reads diff from stdin (or runs
// `git diff --cached`), asks the API for a message, prints just
// `<subject>\n\n<body>` on stdout. No prompts, no edit flow.

export interface AiCommitMsgDeps {
  out: (msg: string) => void;
  fetchImpl?: typeof fetch;
  generate?: (diff: string, style: "conventional" | "plain") => Promise<CommitMessage>;
  // Allow tests to supply an explicit diff (so we don't have to mock stdin).
  diff?: string;
}

export async function runAiCommitMsg(
  cfg: CommitConfig,
  deps: AiCommitMsgDeps
): Promise<number> {
  const diff = deps.diff ?? readStagedDiff(false);
  if (!diff.trim()) {
    return 1; // hook will fall back to git's default empty message.
  }
  try {
    const msg = deps.generate
      ? await deps.generate(diff, "conventional")
      : await requestCommitMessage(cfg, diff, "conventional", deps.fetchImpl);
    if (!msg.subject.trim()) return 1;
    if (msg.body.trim()) {
      deps.out(`${msg.subject}\n\n${msg.body}`);
    } else {
      deps.out(msg.subject);
    }
    return 0;
  } catch {
    return 1;
  }
}