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
spec-git.ts8.9 KB · 312 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
/**
 * spec-git — apply a batch of AI-proposed file edits to a new branch in a bare
 * git repo using plumbing only (no working tree, no `git add`, no `git commit`).
 *
 * Pattern cribbed from `src/lib/demo-seed.ts` (`writeInitialCommit`): transient
 * GIT_INDEX_FILE, hash-object → update-index → write-tree → commit-tree →
 * update-ref. Extended here to:
 *   - seed the index from a base tree (`read-tree`) so unrelated paths survive,
 *   - support delete edits via `update-index --remove`,
 *   - fail if the target branch already exists,
 *   - validate each edit path as defense in depth (reject `..`, absolute, empty).
 *
 * Never throws. Always cleans up the temp index in a `finally`.
 */
import { unlink } from "fs/promises";

export type FileEdit =
  | { action: "create"; path: string; content: string }
  | { action: "edit"; path: string; content: string }
  | { action: "delete"; path: string };

export type ApplyEditsResult =
  | {
      ok: true;
      branchName: string;
      commitSha: string;
      filesChanged: string[];
    }
  | { ok: false; error: string };

interface GitResult {
  stdout: string;
  stderr: string;
  exitCode: number;
}

/**
 * Run a git subprocess safely. Never throws — errors surface via exitCode=-1.
 */
async function runGit(
  args: string[],
  cwd: string,
  opts?: { stdin?: string | Uint8Array; env?: Record<string, string> }
): Promise<GitResult> {
  try {
    const proc = Bun.spawn(["git", ...args], {
      cwd,
      stdout: "pipe",
      stderr: "pipe",
      stdin: opts?.stdin !== undefined ? "pipe" : undefined,
      env: { ...process.env, ...(opts?.env || {}) },
    });
    if (opts?.stdin !== undefined && proc.stdin) {
      const bytes =
        typeof opts.stdin === "string"
          ? new TextEncoder().encode(opts.stdin)
          : opts.stdin;
      (proc.stdin as any).write(bytes);
      (proc.stdin as any).end();
    }
    const [stdout, stderr] = await Promise.all([
      new Response(proc.stdout).text(),
      new Response(proc.stderr).text(),
    ]);
    const exitCode = await proc.exited;
    return { stdout: stdout.trim(), stderr, exitCode };
  } catch (err: any) {
    return { stdout: "", stderr: String(err?.message || err), exitCode: -1 };
  }
}

/**
 * Reject paths that could escape the repo tree. Caller may have already
 * validated — this is defense in depth.
 */
function validatePath(p: string): string | null {
  if (typeof p !== "string") return "path must be a string";
  if (p.length === 0) return "path is empty";
  if (p.startsWith("/")) return `path is absolute: ${p}`;
  // Reject any `..` segment.
  const segments = p.split("/");
  for (const seg of segments) {
    if (seg === "..") return `path contains '..' segment: ${p}`;
    if (seg === "") return `path has empty segment: ${p}`;
  }
  return null;
}

const SHA_RE = /^[0-9a-f]{40}$/;

export async function applyEditsToNewBranch(args: {
  repoDiskPath: string;
  baseRef: string;
  edits: FileEdit[];
  branchName: string;
  commitMessage: string;
  authorName: string;
  authorEmail: string;
}): Promise<ApplyEditsResult> {
  const {
    repoDiskPath,
    baseRef,
    edits,
    branchName,
    commitMessage,
    authorName,
    authorEmail,
  } = args;

  // 0. Empty edits → refuse (don't manufacture empty commits).
  if (!Array.isArray(edits) || edits.length === 0) {
    return { ok: false, error: "no edits supplied" };
  }

  // 0b. Validate every path up front.
  for (const edit of edits) {
    const bad = validatePath(edit.path);
    if (bad) return { ok: false, error: bad };
  }

  // 0c. Basic branch-name sanity.
  if (!branchName || branchName.includes(" ") || branchName.startsWith("-")) {
    return { ok: false, error: `invalid branch name: ${branchName}` };
  }

  // 0d. Basic commit-message presence.
  if (!commitMessage || !commitMessage.trim()) {
    return { ok: false, error: "commit message is empty" };
  }

  // 1. Confirm repo path exists by probing `git rev-parse --git-dir`.
  const probe = await runGit(["rev-parse", "--git-dir"], repoDiskPath);
  if (probe.exitCode !== 0) {
    return {
      ok: false,
      error: `repo path invalid: ${probe.stderr.trim() || "rev-parse failed"}`,
    };
  }

  // 2. Refuse if target branch already exists.
  const existing = await runGit(
    ["rev-parse", "--verify", `refs/heads/${branchName}`],
    repoDiskPath
  );
  if (existing.exitCode === 0) {
    return { ok: false, error: "branch already exists" };
  }

  // 3. Resolve base commit sha and base tree sha.
  const baseSha = await runGit(["rev-parse", baseRef], repoDiskPath);
  if (baseSha.exitCode !== 0 || !SHA_RE.test(baseSha.stdout)) {
    return {
      ok: false,
      error: `base ref not found: ${baseRef}`,
    };
  }
  const baseTree = await runGit(
    ["rev-parse", `${baseRef}^{tree}`],
    repoDiskPath
  );
  if (baseTree.exitCode !== 0 || !SHA_RE.test(baseTree.stdout)) {
    return {
      ok: false,
      error: `could not resolve base tree for ${baseRef}`,
    };
  }

  // 4. Allocate a transient index file. Keep it inside the repo dir so it
  //    lives on the same filesystem as the object store.
  const tmpIndex = `${repoDiskPath}/index.spec-git.${process.pid}.${Date.now()}.${Math.random()
    .toString(36)
    .slice(2)}`;
  const baseEnv: Record<string, string> = {
    GIT_INDEX_FILE: tmpIndex,
    GIT_AUTHOR_NAME: authorName,
    GIT_AUTHOR_EMAIL: authorEmail,
    GIT_COMMITTER_NAME: authorName,
    GIT_COMMITTER_EMAIL: authorEmail,
  };

  try {
    // 5. Seed the transient index from the base tree.
    const readTree = await runGit(
      ["read-tree", baseTree.stdout],
      repoDiskPath,
      { env: baseEnv }
    );
    if (readTree.exitCode !== 0) {
      return {
        ok: false,
        error: `read-tree failed: ${readTree.stderr.trim()}`,
      };
    }

    // 6. Apply each edit to the transient index.
    const filesChanged: string[] = [];
    for (const edit of edits) {
      if (edit.action === "delete") {
        const rm = await runGit(
          ["update-index", "--remove", edit.path],
          repoDiskPath,
          { env: baseEnv }
        );
        if (rm.exitCode !== 0) {
          return {
            ok: false,
            error: `update-index --remove failed for ${edit.path}: ${rm.stderr.trim()}`,
          };
        }
        filesChanged.push(edit.path);
        continue;
      }

      // create or edit — both hash the content and add to the index.
      const hashed = await runGit(
        ["hash-object", "-w", "--stdin"],
        repoDiskPath,
        { stdin: edit.content }
      );
      if (hashed.exitCode !== 0 || !SHA_RE.test(hashed.stdout)) {
        return {
          ok: false,
          error: `hash-object failed for ${edit.path}: ${hashed.stderr.trim()}`,
        };
      }
      const blobSha = hashed.stdout;
      const add = await runGit(
        [
          "update-index",
          "--add",
          "--cacheinfo",
          `100644,${blobSha},${edit.path}`,
        ],
        repoDiskPath,
        { env: baseEnv }
      );
      if (add.exitCode !== 0) {
        return {
          ok: false,
          error: `update-index --add failed for ${edit.path}: ${add.stderr.trim()}`,
        };
      }
      filesChanged.push(edit.path);
    }

    // 7. write-tree → new tree sha.
    const wt = await runGit(["write-tree"], repoDiskPath, { env: baseEnv });
    if (wt.exitCode !== 0 || !SHA_RE.test(wt.stdout)) {
      return {
        ok: false,
        error: `write-tree failed: ${wt.stderr.trim()}`,
      };
    }
    const newTreeSha = wt.stdout;

    // 8. If the new tree equals the base tree, nothing actually changed —
    //    don't create an empty commit.
    if (newTreeSha === baseTree.stdout) {
      return { ok: false, error: "no changes produced (tree identical)" };
    }

    // 9. commit-tree with the base commit as parent.
    const commit = await runGit(
      [
        "commit-tree",
        newTreeSha,
        "-p",
        baseSha.stdout,
        "-m",
        commitMessage,
      ],
      repoDiskPath,
      { env: baseEnv }
    );
    if (commit.exitCode !== 0 || !SHA_RE.test(commit.stdout)) {
      return {
        ok: false,
        error: `commit-tree failed: ${commit.stderr.trim()}`,
      };
    }
    const commitSha = commit.stdout;

    // 10. update-ref — create the new branch atomically. The `""` old-value
    //     argument tells git to only create if the ref doesn't yet exist.
    const upd = await runGit(
      ["update-ref", `refs/heads/${branchName}`, commitSha, ""],
      repoDiskPath
    );
    if (upd.exitCode !== 0) {
      return {
        ok: false,
        error: `update-ref failed: ${upd.stderr.trim()}`,
      };
    }

    return {
      ok: true,
      branchName,
      commitSha,
      filesChanged,
    };
  } catch (err: any) {
    return { ok: false, error: String(err?.message || err) };
  } finally {
    // Always remove the transient index file, success or failure.
    try {
      await unlink(tmpIndex);
    } catch {
      /* ignore — file may never have been created */
    }
  }
}