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
mcp-write.test.ts29.4 KB · 900 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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
/**
 * Block K1 — MCP write surface tests.
 *
 * Covers the 10 new tools added in src/lib/mcp-tools.ts:
 *   create_issue / comment_issue / close_issue / reopen_issue
 *   create_pr    / get_pr        / list_prs    / comment_pr
 *   merge_pr     / close_pr
 *
 * Each tool gets at minimum:
 *   - Happy-ish path: authenticated owner returns the spec-described shape
 *   - Auth gate    : ctx.userId === null → McpError(-32602 INVALID_PARAMS)
 *   - Write-access : authed but no write access → McpError(-32601 NOT_FOUND)
 *
 * We stub the `../db` module (same pattern as repo-access.test.ts and
 * import-verify.test.ts) so these tests never touch Neon. The fake `db`
 * dispatches on the table passed to `.from(...)` / `.insert(...)` to
 * decide which canned shape to return. Mutations are recorded in the
 * `_inserted` / `_updated` arrays so the assertions can verify the audit
 * + DB-write path was actually exercised.
 *
 * We also stub `./notify` to avoid the email-fanout path (which would
 * also try to hit the DB), and `./gate` + `./branch-protection` +
 * `./merge-resolver` for the merge_pr happy path so we don't shell out
 * to git.
 */

import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";
import {
  ERR_INVALID_PARAMS,
  ERR_METHOD_NOT_FOUND,
  McpError,
} from "../lib/mcp";

// Capture the REAL modules BEFORE any mock.module() call below so we can
// restore them in afterAll. `mock.module()` is process-global in Bun and
// otherwise bleeds into every test file that runs after this one in the
// same `bun test` invocation, silently breaking every test that imports
// (directly or transitively) any of the modules we stub.
const _real_db = await import("../db");
const _real_notify = await import("../lib/notify");
const _real_gate = await import("../lib/gate");
const _real_branchProtection = await import("../lib/branch-protection");
const _real_mergeResolver = await import("../lib/merge-resolver");
const _real_aiReview = await import("../lib/ai-review");
const _real_closeKeywords = await import("../lib/close-keywords");
const _real_sse = await import("../lib/sse");

// ---------------------------------------------------------------------------
// Module stubs
// ---------------------------------------------------------------------------

/** Per-test override hooks. Reset in beforeEach. */
let _nextRepoRow: any = null;
let _nextCollabRow: any = null;
let _nextIssueRow: any = null;
let _nextPrRow: any = null;
let _nextAiCommentRows: any[] = [];
let _nextProtectionRule: any = null;

const _inserted: { table: string; values: any; returned: any }[] = [];
const _updated: { table: string; set: any }[] = [];

let _lastSelectFrom: any = null;
let _lastInsertTable: any = null;
let _lastUpdateTable: any = null;
let _lastInsertValues: any = null;

const tableName = (t: any): string => {
  if (!t || typeof t !== "object") return "?";
  // Drizzle pgTable objects expose a Symbol-keyed name. We probe `_` /
  // common keys to identify the table without importing the schema.
  if ("isPrivate" in t) return "repositories";
  if ("acceptedAt" in t || "invitedAt" in t) return "repo_collaborators";
  if ("issueId" in t && "body" in t) return "issue_comments";
  if ("pullRequestId" in t) return "pr_comments";
  if (
    "baseBranch" in t ||
    "headBranch" in t ||
    "mergedAt" in t ||
    "isDraft" in t
  )
    return "pull_requests";
  if ("state" in t && "closedAt" in t && "title" in t && !("baseBranch" in t))
    return "issues";
  if ("username" in t && "passwordHash" in t) return "users";
  if ("kind" in t) return "notifications";
  if ("action" in t && "userId" in t) return "audit_log";
  return "?";
};

const _selectChain: any = {
  from: (t: any) => {
    _lastSelectFrom = t;
    return _selectChain;
  },
  innerJoin: () => _selectChain,
  leftJoin: () => _selectChain,
  rightJoin: () => _selectChain,
  where: () => _selectChain,
  orderBy: () => _selectChain,
  groupBy: () => _selectChain,
  limit: async () => {
    const name = tableName(_lastSelectFrom);
    if (name === "repositories") {
      return _nextRepoRow ? [_nextRepoRow] : [];
    }
    if (name === "repo_collaborators") {
      return _nextCollabRow ? [_nextCollabRow] : [];
    }
    if (name === "issues") {
      return _nextIssueRow ? [_nextIssueRow] : [];
    }
    if (name === "pull_requests") {
      return _nextPrRow ? [_nextPrRow] : [];
    }
    if (name === "pr_comments") {
      return _nextAiCommentRows;
    }
    if (name === "users") {
      // Only echo a username when the test explicitly set one via
      // `_nextRepoRow.username`. Returning a default row breaks every
      // downstream test that expects an empty result for nonexistent
      // users (graphql, api-v2, etc.).
      return _nextRepoRow?.username ? [{ username: _nextRepoRow.username }] : [];
    }
    return [];
  },
  // For pr-comments AI-approval lookup, the route doesn't `.limit(1)` — it
  // awaits the chain directly. We expose `.then` so `await chain` yields
  // the rows.
  then: (resolve: (v: any) => void) => {
    const name = tableName(_lastSelectFrom);
    if (name === "pr_comments") return resolve(_nextAiCommentRows);
    if (name === "pull_requests") return resolve(_nextPrRow ? [_nextPrRow] : []);
    return resolve([]);
  },
};

const _insertChain = (table: any) => {
  _lastInsertTable = table;
  return {
    values: (vals: any) => {
      _lastInsertValues = vals;
      return {
        returning: async () => {
          const name = tableName(table);
          let returned: any;
          if (name === "issues") {
            returned = {
              id: "iss-id-1",
              number: 42,
              repositoryId: vals.repositoryId,
              authorId: vals.authorId,
              title: vals.title,
              body: vals.body,
              state: "open",
              createdAt: new Date(),
              updatedAt: new Date(),
              closedAt: null,
            };
          } else if (name === "issue_comments") {
            returned = {
              id: "ic-id-1",
              issueId: vals.issueId,
              authorId: vals.authorId,
              body: vals.body,
              createdAt: new Date(),
              updatedAt: new Date(),
            };
          } else if (name === "pull_requests") {
            returned = {
              id: "pr-id-1",
              number: 7,
              repositoryId: vals.repositoryId,
              authorId: vals.authorId,
              title: vals.title,
              body: vals.body,
              state: "open",
              baseBranch: vals.baseBranch,
              headBranch: vals.headBranch,
              isDraft: vals.isDraft ?? false,
              mergeStrategy: "merge",
              milestoneId: null,
              mergedAt: null,
              mergedBy: null,
              createdAt: new Date(),
              updatedAt: new Date(),
              closedAt: null,
            };
          } else if (name === "pr_comments") {
            returned = {
              id: "pc-id-1",
              pullRequestId: vals.pullRequestId,
              authorId: vals.authorId,
              body: vals.body,
              isAiReview: vals.isAiReview ?? false,
              filePath: null,
              lineNumber: null,
              createdAt: new Date(),
              updatedAt: new Date(),
            };
          } else {
            returned = vals;
          }
          _inserted.push({ table: name, values: vals, returned });
          return [returned];
        },
        // Allow `await db.insert(...).values(...)` (no `.returning()`),
        // used by notify/audit + auto-close-issues path.
        then: (resolve: (v: any) => void) => {
          _inserted.push({ table: tableName(table), values: vals, returned: null });
          resolve(undefined);
        },
      };
    },
  };
};

const _updateChain = (table: any) => {
  _lastUpdateTable = table;
  return {
    set: (vals: any) => {
      _updated.push({ table: tableName(table), set: vals });
      return {
        where: () => ({
          then: (resolve: (v: any) => void) => resolve(undefined),
        }),
      };
    },
  };
};

const _fakeDb = {
  db: {
    select: () => _selectChain,
    insert: (t: any) => _insertChain(t),
    update: (t: any) => _updateChain(t),
    delete: () => ({ where: () => Promise.resolve() }),
  },
  getDb: () => _fakeDb.db,
  // NOTE: `isNeonUrl` is intentionally NOT overridden. The real export
  // is a pure substring helper that downstream tests (db-driver.test.ts)
  // exercise directly — overriding it here used to bleed `() => false`
  // into every test in the run.
};
// Mock ONLY `../db`. Bun's `mock.module()` is process-global AND it
// poisons every downstream test file that imports the same module —
// overrides applied here persist past `afterAll` because ESM caches
// the resolved module in each test file at load time. So we keep the
// stub surface minimal: only the modules that would touch external
// resources (real DB, real git subprocess, real Anthropic API) get
// inert overrides. Everything else runs the real implementation,
// which behaves correctly when the underlying DB returns nothing.
//
// For modules that DO need their behaviour neutered (gate runner,
// merge-resolver, ai-review's API call), we install spy-style stubs
// inside `beforeEach` and remove them in `afterAll` so they don't
// leak across files.
const _notifyCalls: any[] = [];
const _auditCalls: any[] = [];
mock.module("../db", () => ({ ..._real_db, ..._fakeDb }));
mock.module("../lib/notify", () => ({
  ..._real_notify,
  notify: async (userId: string, opts: any) => {
    _notifyCalls.push({ userId, ...opts });
  },
  notifyMany: async () => {},
  audit: async (opts: any) => {
    _auditCalls.push(opts);
  },
}));
// `runAllGateChecks` shells out to git + the gate runner; replace with
// a permissive no-op. Other gate exports stay real.
mock.module("../lib/gate", () => ({
  ..._real_gate,
  runAllGateChecks: async () => ({ checks: [] }),
}));
// `mergeWithAutoResolve` shells out to git; replace with a success no-op.
mock.module("../lib/merge-resolver", () => ({
  ..._real_mergeResolver,
  mergeWithAutoResolve: async () => ({ success: true, resolvedFiles: [] }),
}));
// `triggerAiReview` calls Anthropic; replace with a no-op. Crucially,
// `AI_REVIEW_MARKER` (used by auto-merge.ts elsewhere) stays the real
// const.
mock.module("../lib/ai-review", () => ({
  ..._real_aiReview,
  isAiReviewEnabled: () => false,
  triggerAiReview: async () => {},
}));
// NOTE: `../lib/branch-protection`, `../lib/close-keywords`, and
// `../lib/sse` are intentionally NOT mocked here. The real modules
// are pure (close-keywords) or fail-safe when the DB is the inert
// stub (branch-protection's `matchProtection` returns null when no
// rows come back, which is the K1 happy-path expectation anyway).
// Mocking these previously broke K2's auto-merge.test.ts and the
// sse + close-keywords + branch-protection test files.

// We stub Bun.spawn globally so any git subprocess (e.g. resolveRef,
// `git update-ref` in merge_pr) returns a deterministic happy exit. We
// intentionally do NOT mock `../git/repository` so the rest of the
// library's static imports keep resolving correctly.
const _realBunSpawn = (globalThis as any).Bun?.spawn;
function stubBunSpawnSuccess() {
  (globalThis as any).Bun.spawn = () => ({
    exited: Promise.resolve(0),
    stdout: new ReadableStream({
      start(c) {
        c.enqueue(new TextEncoder().encode("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef\n"));
        c.close();
      },
    }),
    stderr: new ReadableStream({
      start(c) {
        c.close();
      },
    }),
  });
}
function restoreBunSpawn() {
  if (_realBunSpawn) (globalThis as any).Bun.spawn = _realBunSpawn;
}
// Bun.spawn stub is NOT installed globally — the previous global install
// bled into every downstream test file in the run and broke any test
// whose code path eventually shelled out to `git`. The merge-PR happy
// path test below installs + restores it inside the test body instead.

afterAll(() => {
  restoreBunSpawn();
  // Reset every per-test row hook so any downstream test file whose
  // code path runs `db.select()...limit(1)` against our stub sees an
  // empty result (the no-rows branch) rather than inheriting the
  // PUBLIC_REPO_ROW that K1's beforeEach last installed.
  _nextRepoRow = null;
  _nextCollabRow = null;
  _nextIssueRow = null;
  _nextPrRow = null;
  _nextAiCommentRows = [];
  _nextProtectionRule = null;
  // Best-effort restoration: re-register the real modules. Note that
  // downstream test files' static imports are already cached against
  // whatever was active at their load time, so this is mostly a hygiene
  // measure for files using dynamic imports.
  mock.module("../db", () => _real_db);
  mock.module("../lib/notify", () => _real_notify);
  mock.module("../lib/gate", () => _real_gate);
  mock.module("../lib/merge-resolver", () => _real_mergeResolver);
  mock.module("../lib/ai-review", () => _real_aiReview);
});

// ---------------------------------------------------------------------------
// Test fixtures
// ---------------------------------------------------------------------------

const OWNER_ID = "11111111-1111-1111-1111-111111111111";
const REPO_ID = "22222222-2222-2222-2222-222222222222";
const OTHER_USER_ID = "33333333-3333-3333-3333-333333333333";

const PUBLIC_REPO_ROW = {
  id: REPO_ID,
  ownerId: OWNER_ID,
  isPrivate: false,
  defaultBranch: "main",
  username: "alice",
};

const ownerCtx = { userId: OWNER_ID };
const anonCtx = { userId: null };
const otherCtx = { userId: OTHER_USER_ID };

function resetState() {
  _nextRepoRow = PUBLIC_REPO_ROW;
  _nextCollabRow = null; // No collaborator rows → public repo non-owner = read
  _nextIssueRow = null;
  _nextPrRow = null;
  _nextAiCommentRows = [];
  _nextProtectionRule = null;
  _inserted.length = 0;
  _updated.length = 0;
  _notifyCalls.length = 0;
  _auditCalls.length = 0;
}

beforeEach(() => {
  resetState();
});

async function getTools() {
  const m = await import("../lib/mcp-tools");
  return m.__test;
}

// ---------------------------------------------------------------------------
// gluecron_create_issue
// ---------------------------------------------------------------------------

describe("gluecron_create_issue", () => {
  it("owner can create an issue (happy path)", async () => {
    const T = await getTools();
    const result = (await T.createIssue.run(
      { owner: "alice", repo: "demo", title: "Hello", body: "World" },
      ownerCtx
    )) as { number: number; url: string };
    expect(result.number).toBe(42);
    expect(result.url).toBe("/alice/demo/issues/42");
    expect(_inserted.find((r) => r.table === "issues")).toBeTruthy();
    expect(_auditCalls.some((a) => a.action === "issue.created")).toBe(true);
  });

  it("anonymous → -32602 INVALID_PARAMS", async () => {
    const T = await getTools();
    let caught: McpError | null = null;
    try {
      await T.createIssue.run(
        { owner: "alice", repo: "demo", title: "x" },
        anonCtx
      );
    } catch (err) {
      if (err instanceof McpError) caught = err;
    }
    expect(caught?.code).toBe(ERR_INVALID_PARAMS);
    expect(caught?.message).toMatch(/authentication required/);
  });

  it("authed-but-no-write → -32601 METHOD_NOT_FOUND", async () => {
    const T = await getTools();
    // Public repo, other user, no collab row → only "read"
    let caught: McpError | null = null;
    try {
      await T.createIssue.run(
        { owner: "alice", repo: "demo", title: "x" },
        otherCtx
      );
    } catch (err) {
      if (err instanceof McpError) caught = err;
    }
    expect(caught?.code).toBe(ERR_METHOD_NOT_FOUND);
    expect(caught?.message).toMatch(/no write access/);
  });
});

// ---------------------------------------------------------------------------
// gluecron_comment_issue
// ---------------------------------------------------------------------------

describe("gluecron_comment_issue", () => {
  it("owner can comment on an issue", async () => {
    const T = await getTools();
    _nextIssueRow = {
      id: "iss-id-1",
      number: 42,
      repositoryId: REPO_ID,
      authorId: OWNER_ID,
      state: "open",
    };
    const result = (await T.commentIssue.run(
      { owner: "alice", repo: "demo", number: 42, body: "thanks!" },
      ownerCtx
    )) as { commentId: string };
    expect(result.commentId).toBe("ic-id-1");
    expect(_inserted.find((r) => r.table === "issue_comments")).toBeTruthy();
  });

  it("anonymous → -32602", async () => {
    const T = await getTools();
    expect(
      T.commentIssue.run(
        { owner: "alice", repo: "demo", number: 1, body: "x" },
        anonCtx
      )
    ).rejects.toMatchObject({ code: ERR_INVALID_PARAMS });
  });

  it("other user (read-only) → -32601", async () => {
    const T = await getTools();
    expect(
      T.commentIssue.run(
        { owner: "alice", repo: "demo", number: 1, body: "x" },
        otherCtx
      )
    ).rejects.toMatchObject({ code: ERR_METHOD_NOT_FOUND });
  });
});

// ---------------------------------------------------------------------------
// gluecron_close_issue
// ---------------------------------------------------------------------------

describe("gluecron_close_issue", () => {
  it("owner can close an open issue", async () => {
    const T = await getTools();
    _nextIssueRow = {
      id: "iss-1",
      number: 5,
      repositoryId: REPO_ID,
      authorId: OWNER_ID,
      state: "open",
    };
    const result = (await T.closeIssue.run(
      { owner: "alice", repo: "demo", number: 5 },
      ownerCtx
    )) as { state: string };
    expect(result.state).toBe("closed");
    expect(_updated.find((u) => u.table === "issues")).toBeTruthy();
  });

  it("anonymous → -32602", async () => {
    const T = await getTools();
    expect(
      T.closeIssue.run({ owner: "alice", repo: "demo", number: 5 }, anonCtx)
    ).rejects.toMatchObject({ code: ERR_INVALID_PARAMS });
  });

  it("other user → -32601", async () => {
    const T = await getTools();
    expect(
      T.closeIssue.run({ owner: "alice", repo: "demo", number: 5 }, otherCtx)
    ).rejects.toMatchObject({ code: ERR_METHOD_NOT_FOUND });
  });
});

// ---------------------------------------------------------------------------
// gluecron_reopen_issue
// ---------------------------------------------------------------------------

describe("gluecron_reopen_issue", () => {
  it("owner can reopen a closed issue", async () => {
    const T = await getTools();
    _nextIssueRow = {
      id: "iss-1",
      number: 5,
      repositoryId: REPO_ID,
      authorId: OWNER_ID,
      state: "closed",
      closedAt: new Date(),
    };
    const result = (await T.reopenIssue.run(
      { owner: "alice", repo: "demo", number: 5 },
      ownerCtx
    )) as { state: string };
    expect(result.state).toBe("open");
    expect(_updated.find((u) => u.table === "issues")).toBeTruthy();
  });

  it("anonymous → -32602", async () => {
    const T = await getTools();
    expect(
      T.reopenIssue.run({ owner: "alice", repo: "demo", number: 5 }, anonCtx)
    ).rejects.toMatchObject({ code: ERR_INVALID_PARAMS });
  });

  it("other user → -32601", async () => {
    const T = await getTools();
    expect(
      T.reopenIssue.run({ owner: "alice", repo: "demo", number: 5 }, otherCtx)
    ).rejects.toMatchObject({ code: ERR_METHOD_NOT_FOUND });
  });
});

// ---------------------------------------------------------------------------
// gluecron_create_pr
// ---------------------------------------------------------------------------

describe("gluecron_create_pr", () => {
  it("owner can open a PR (base defaults to repo default branch)", async () => {
    const T = await getTools();
    const result = (await T.createPr.run(
      {
        owner: "alice",
        repo: "demo",
        title: "Feature X",
        head_branch: "feat/x",
      },
      ownerCtx
    )) as { number: number; url: string };
    expect(result.number).toBe(7);
    expect(result.url).toBe("/alice/demo/pulls/7");
    const ins = _inserted.find((r) => r.table === "pull_requests");
    expect(ins).toBeTruthy();
    expect(ins?.values.baseBranch).toBe("main");
    expect(ins?.values.headBranch).toBe("feat/x");
  });

  it("rejects when base === head", async () => {
    const T = await getTools();
    let caught: McpError | null = null;
    try {
      await T.createPr.run(
        {
          owner: "alice",
          repo: "demo",
          title: "x",
          head_branch: "main",
          base_branch: "main",
        },
        ownerCtx
      );
    } catch (err) {
      if (err instanceof McpError) caught = err;
    }
    expect(caught?.code).toBe(ERR_INVALID_PARAMS);
  });

  it("anonymous → -32602", async () => {
    const T = await getTools();
    expect(
      T.createPr.run(
        { owner: "alice", repo: "demo", title: "x", head_branch: "feat" },
        anonCtx
      )
    ).rejects.toMatchObject({ code: ERR_INVALID_PARAMS });
  });

  it("other user → -32601", async () => {
    const T = await getTools();
    expect(
      T.createPr.run(
        { owner: "alice", repo: "demo", title: "x", head_branch: "feat" },
        otherCtx
      )
    ).rejects.toMatchObject({ code: ERR_METHOD_NOT_FOUND });
  });
});

// ---------------------------------------------------------------------------
// gluecron_get_pr
// ---------------------------------------------------------------------------

describe("gluecron_get_pr", () => {
  it("returns full detail for an authed reader", async () => {
    const T = await getTools();
    _nextPrRow = {
      id: "pr-1",
      number: 7,
      repositoryId: REPO_ID,
      authorId: OWNER_ID,
      title: "Feature",
      body: "Body",
      state: "open",
      baseBranch: "main",
      headBranch: "feat/x",
      isDraft: false,
      createdAt: new Date(),
      updatedAt: new Date(),
      mergedAt: null,
      closedAt: null,
    };
    const r = (await T.getPr.run(
      { owner: "alice", repo: "demo", number: 7 },
      ownerCtx
    )) as any;
    expect(r.number).toBe(7);
    expect(r.state).toBe("open");
    expect(r.baseBranch).toBe("main");
    expect(r.headBranch).toBe("feat/x");
    expect(r.url).toBe("/alice/demo/pulls/7");
  });

  it("anonymous → -32602 (write surface requires auth)", async () => {
    const T = await getTools();
    expect(
      T.getPr.run({ owner: "alice", repo: "demo", number: 1 }, anonCtx)
    ).rejects.toMatchObject({ code: ERR_INVALID_PARAMS });
  });

  it("private repo + non-collaborator → -32601 (privacy)", async () => {
    const T = await getTools();
    _nextRepoRow = { ...PUBLIC_REPO_ROW, isPrivate: true };
    expect(
      T.getPr.run({ owner: "alice", repo: "demo", number: 1 }, otherCtx)
    ).rejects.toMatchObject({ code: ERR_METHOD_NOT_FOUND });
  });
});

// ---------------------------------------------------------------------------
// gluecron_list_prs
// ---------------------------------------------------------------------------

describe("gluecron_list_prs", () => {
  it("rejects an unknown state value", async () => {
    const T = await getTools();
    expect(
      T.listPrs.run(
        { owner: "alice", repo: "demo", state: "garbage" },
        ownerCtx
      )
    ).rejects.toMatchObject({ code: ERR_INVALID_PARAMS });
  });

  it("anonymous → -32602", async () => {
    const T = await getTools();
    expect(
      T.listPrs.run({ owner: "alice", repo: "demo" }, anonCtx)
    ).rejects.toMatchObject({ code: ERR_INVALID_PARAMS });
  });

  it("private repo + non-collaborator → -32601", async () => {
    const T = await getTools();
    _nextRepoRow = { ...PUBLIC_REPO_ROW, isPrivate: true };
    expect(
      T.listPrs.run({ owner: "alice", repo: "demo" }, otherCtx)
    ).rejects.toMatchObject({ code: ERR_METHOD_NOT_FOUND });
  });

  it("authed reader gets a 0-row list when none exist", async () => {
    const T = await getTools();
    const r = (await T.listPrs.run(
      { owner: "alice", repo: "demo" },
      ownerCtx
    )) as { total: number; prs: any[] };
    // The fake DB returns [] for the listPrs path because the chain only
    // returns canned rows on `.limit(1)` of repositories. The unbounded
    // PR list shape comes back empty — which is the explicit "no PRs"
    // happy path we want to assert.
    expect(typeof r.total).toBe("number");
    expect(Array.isArray(r.prs)).toBe(true);
  });
});

// ---------------------------------------------------------------------------
// gluecron_comment_pr
// ---------------------------------------------------------------------------

describe("gluecron_comment_pr", () => {
  it("owner can comment on a PR", async () => {
    const T = await getTools();
    _nextPrRow = {
      id: "pr-1",
      number: 7,
      repositoryId: REPO_ID,
      authorId: OWNER_ID,
      state: "open",
      baseBranch: "main",
      headBranch: "feat/x",
      isDraft: false,
    };
    const result = (await T.commentPr.run(
      { owner: "alice", repo: "demo", number: 7, body: "LGTM" },
      ownerCtx
    )) as { commentId: string };
    expect(result.commentId).toBe("pc-id-1");
    expect(_inserted.find((r) => r.table === "pr_comments")).toBeTruthy();
  });

  it("anonymous → -32602", async () => {
    const T = await getTools();
    expect(
      T.commentPr.run(
        { owner: "alice", repo: "demo", number: 1, body: "x" },
        anonCtx
      )
    ).rejects.toMatchObject({ code: ERR_INVALID_PARAMS });
  });

  it("other user → -32601", async () => {
    const T = await getTools();
    expect(
      T.commentPr.run(
        { owner: "alice", repo: "demo", number: 1, body: "x" },
        otherCtx
      )
    ).rejects.toMatchObject({ code: ERR_METHOD_NOT_FOUND });
  });
});

// ---------------------------------------------------------------------------
// gluecron_merge_pr
// ---------------------------------------------------------------------------

describe("gluecron_merge_pr", () => {
  it("owner can merge a clean open PR (no protection, no conflicts)", async () => {
    const T = await getTools();
    _nextPrRow = {
      id: "pr-1",
      number: 7,
      repositoryId: REPO_ID,
      authorId: OWNER_ID,
      title: "Feature",
      body: "",
      state: "open",
      baseBranch: "main",
      headBranch: "feat/x",
      isDraft: false,
    };
    stubBunSpawnSuccess();
    try {
      const r = (await T.mergePr.run(
        { owner: "alice", repo: "demo", number: 7 },
        ownerCtx
      )) as { merged: boolean; sha?: string; reason?: string };
      expect(r.merged).toBe(true);
      expect(typeof r.sha).toBe("string");
      expect(_updated.some((u) => u.table === "pull_requests")).toBe(true);
    } finally {
      restoreBunSpawn();
    }
  });

  it("draft PR → merged=false with human-readable reason", async () => {
    const T = await getTools();
    _nextPrRow = {
      id: "pr-1",
      number: 7,
      repositoryId: REPO_ID,
      authorId: OWNER_ID,
      state: "open",
      baseBranch: "main",
      headBranch: "feat/x",
      isDraft: true,
    };
    const r = (await T.mergePr.run(
      { owner: "alice", repo: "demo", number: 7 },
      ownerCtx
    )) as { merged: boolean; reason?: string };
    expect(r.merged).toBe(false);
    expect(r.reason).toMatch(/draft/i);
  });

  it("anonymous → -32602", async () => {
    const T = await getTools();
    expect(
      T.mergePr.run({ owner: "alice", repo: "demo", number: 1 }, anonCtx)
    ).rejects.toMatchObject({ code: ERR_INVALID_PARAMS });
  });

  it("other user → -32601", async () => {
    const T = await getTools();
    expect(
      T.mergePr.run({ owner: "alice", repo: "demo", number: 1 }, otherCtx)
    ).rejects.toMatchObject({ code: ERR_METHOD_NOT_FOUND });
  });
});

// ---------------------------------------------------------------------------
// gluecron_close_pr
// ---------------------------------------------------------------------------

describe("gluecron_close_pr", () => {
  it("owner can close an open PR", async () => {
    const T = await getTools();
    _nextPrRow = {
      id: "pr-1",
      number: 7,
      repositoryId: REPO_ID,
      authorId: OWNER_ID,
      state: "open",
      baseBranch: "main",
      headBranch: "feat/x",
      isDraft: false,
    };
    const r = (await T.closePr.run(
      { owner: "alice", repo: "demo", number: 7 },
      ownerCtx
    )) as { state: string };
    expect(r.state).toBe("closed");
    expect(_updated.some((u) => u.table === "pull_requests")).toBe(true);
  });

  it("anonymous → -32602", async () => {
    const T = await getTools();
    expect(
      T.closePr.run({ owner: "alice", repo: "demo", number: 1 }, anonCtx)
    ).rejects.toMatchObject({ code: ERR_INVALID_PARAMS });
  });

  it("other user → -32601", async () => {
    const T = await getTools();
    expect(
      T.closePr.run({ owner: "alice", repo: "demo", number: 1 }, otherCtx)
    ).rejects.toMatchObject({ code: ERR_METHOD_NOT_FOUND });
  });
});

// ---------------------------------------------------------------------------
// Default registry contains the new tools
// ---------------------------------------------------------------------------

describe("defaultTools — registry shape", () => {
  it("includes all 10 K1 write-surface tools", async () => {
    const { defaultTools } = await import("../lib/mcp-tools");
    const tools = defaultTools();
    const expected = [
      "gluecron_create_issue",
      "gluecron_comment_issue",
      "gluecron_close_issue",
      "gluecron_reopen_issue",
      "gluecron_create_pr",
      "gluecron_get_pr",
      "gluecron_list_prs",
      "gluecron_comment_pr",
      "gluecron_merge_pr",
      "gluecron_close_pr",
    ];
    for (const name of expected) {
      expect(tools[name]).toBeTruthy();
      expect(tools[name].tool.name).toBe(name);
      expect(tools[name].tool.inputSchema.type).toBe("object");
    }
  });
});