@myrialabs/clopen 0.4.40 → 0.4.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +6 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +50 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/index.ts +18 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
  20. package/backend/database/migrations/082_create_git_identities.ts +122 -0
  21. package/backend/database/migrations/index.ts +28 -0
  22. package/backend/database/queries/file-share-queries.ts +163 -0
  23. package/backend/database/queries/git-identity-queries.ts +290 -0
  24. package/backend/database/queries/index.ts +8 -4
  25. package/backend/database/queries/profile-queries.ts +5 -3
  26. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  27. package/backend/database/queries/push-subscription-queries.ts +99 -0
  28. package/backend/database/queries/skill-queries.ts +96 -18
  29. package/backend/engine/adapters/claude/environment.ts +11 -1
  30. package/backend/engine/adapters/claude/stream.ts +3 -2
  31. package/backend/engine/adapters/cline/stream.ts +3 -3
  32. package/backend/engine/adapters/codex/stream.ts +38 -6
  33. package/backend/engine/adapters/copilot/stream.ts +3 -3
  34. package/backend/engine/adapters/cursor/stream.ts +25 -3
  35. package/backend/engine/adapters/opencode/server.ts +26 -2
  36. package/backend/engine/adapters/opencode/stream.ts +8 -7
  37. package/backend/engine/adapters/pi/stream.ts +2 -2
  38. package/backend/engine/adapters/qwen/stream.ts +5 -3
  39. package/backend/engine/artifact-sync.ts +26 -20
  40. package/backend/engine/docs/artifacts.md +81 -22
  41. package/backend/engine/docs/quick-reference.md +2 -1
  42. package/backend/engine/resolve-model.test.ts +108 -0
  43. package/backend/engine/resolve-model.ts +53 -10
  44. package/backend/engine/structured-helpers.ts +22 -0
  45. package/backend/engine/types.ts +10 -0
  46. package/backend/files/file-shares.ts +369 -0
  47. package/backend/files/path-browsing.ts +27 -21
  48. package/backend/git/git-executor.ts +28 -2
  49. package/backend/git/git-service.ts +59 -40
  50. package/backend/git/identity/cli.test.ts +58 -0
  51. package/backend/git/identity/cli.ts +201 -0
  52. package/backend/git/identity/credential-helper.test.ts +242 -0
  53. package/backend/git/identity/env.test.ts +214 -0
  54. package/backend/git/identity/env.ts +193 -0
  55. package/backend/git/identity/import-local.test.ts +199 -0
  56. package/backend/git/identity/import-local.ts +141 -0
  57. package/backend/git/identity/index.ts +78 -0
  58. package/backend/git/identity/keys.ts +183 -0
  59. package/backend/git/identity/resolve.ts +140 -0
  60. package/backend/git/identity/scope-config.test.ts +145 -0
  61. package/backend/git/identity/scope-config.ts +175 -0
  62. package/backend/git/identity/service.ts +297 -0
  63. package/backend/http/files-shared.test.ts +505 -0
  64. package/backend/http/files-shared.ts +351 -0
  65. package/backend/http/push.ts +150 -0
  66. package/backend/index.ts +24 -0
  67. package/backend/instructions/index.ts +1 -1
  68. package/backend/instructions/sync.ts +30 -6
  69. package/backend/memory/compose.ts +2 -2
  70. package/backend/memory/consolidate.ts +2 -2
  71. package/backend/memory/extract/episodic.ts +2 -2
  72. package/backend/memory/judge.ts +2 -2
  73. package/backend/preview/browser/browser-console-manager.ts +214 -34
  74. package/backend/preview/browser/browser-pool.ts +526 -123
  75. package/backend/preview/browser/browser-preview-service.ts +192 -8
  76. package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
  77. package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
  78. package/backend/preview/browser/browser-tab-manager.ts +291 -65
  79. package/backend/preview/browser/capture-profile.ts +15 -1
  80. package/backend/preview/browser/types.ts +26 -1
  81. package/backend/profiles/service.ts +7 -6
  82. package/backend/push/sender.ts +172 -0
  83. package/backend/push/tags.ts +25 -0
  84. package/backend/push/vapid-keys.ts +77 -0
  85. package/backend/push/webpush-crypto.test.ts +200 -0
  86. package/backend/push/webpush-crypto.ts +231 -0
  87. package/backend/skills/detect.ts +28 -0
  88. package/backend/skills/index.ts +22 -4
  89. package/backend/skills/invoke.test.ts +114 -0
  90. package/backend/skills/invoke.ts +222 -0
  91. package/backend/skills/service.ts +194 -44
  92. package/backend/skills/spec.ts +35 -0
  93. package/backend/skills/sync.ts +85 -55
  94. package/backend/subagents/detect.ts +2 -3
  95. package/backend/subagents/sync.ts +15 -8
  96. package/backend/terminal/ptykit.ts +24 -0
  97. package/backend/work/pull-requests.ts +2 -2
  98. package/backend/ws/chat/stream.ts +100 -8
  99. package/backend/ws/files/index.ts +4 -0
  100. package/backend/ws/files/share.ts +95 -0
  101. package/backend/ws/git/branch-name.ts +2 -2
  102. package/backend/ws/git/branch.ts +17 -6
  103. package/backend/ws/git/commit-message.ts +2 -2
  104. package/backend/ws/git/commit.ts +6 -5
  105. package/backend/ws/git/conflict.ts +3 -2
  106. package/backend/ws/git/identity-context.ts +91 -0
  107. package/backend/ws/git/identity.ts +200 -0
  108. package/backend/ws/git/index.ts +3 -1
  109. package/backend/ws/git/remote.ts +57 -11
  110. package/backend/ws/index.ts +3 -4
  111. package/backend/ws/preview/browser/data.ts +60 -0
  112. package/backend/ws/preview/browser/interact.ts +6 -0
  113. package/backend/ws/preview/browser/tab-info.ts +9 -1
  114. package/backend/ws/preview/browser/tab.ts +64 -8
  115. package/backend/ws/preview/index.ts +21 -0
  116. package/backend/ws/profiles/crud.ts +2 -3
  117. package/backend/ws/skills/catalog.ts +5 -1
  118. package/backend/ws/skills/crud.ts +128 -22
  119. package/backend/ws/skills/index.ts +4 -1
  120. package/backend/ws/user/crud.ts +12 -3
  121. package/bin/clopen.ts +9 -0
  122. package/dist/assets/{index-D4igjF6e.js → index-BynqyvF4.js} +1 -1
  123. package/dist/assets/{index-DONNwiXm.js → index-DLoJsmNQ.js} +1 -1
  124. package/dist/assets/{main-BrfXH1bL.js → main-CUyZAmqt.js} +601 -592
  125. package/dist/assets/main-DVCW3cfr.css +1 -0
  126. package/dist/index.html +7 -2
  127. package/dist/sw.js +112 -0
  128. package/package.json +2 -2
  129. package/shared/constants/engine-tools.ts +31 -6
  130. package/shared/constants/notification-messages.ts +142 -0
  131. package/shared/types/git-identity.ts +112 -0
  132. package/shared/types/unified/stream.ts +7 -0
  133. package/backend/commands/detect.ts +0 -25
  134. package/backend/commands/index.ts +0 -9
  135. package/backend/commands/service.ts +0 -178
  136. package/backend/commands/store.ts +0 -45
  137. package/backend/commands/sync.ts +0 -94
  138. package/backend/database/queries/command-queries.ts +0 -82
  139. package/backend/ws/commands/crud.ts +0 -157
  140. package/backend/ws/commands/index.ts +0 -8
  141. package/dist/assets/main-CT1PygsW.css +0 -1
@@ -3,7 +3,7 @@
3
3
  * High-level git operations built on top of executor and parser
4
4
  */
5
5
 
6
- import { execGit, isGitRepo, getGitRoot, type GitExecResult } from './git-executor';
6
+ import { execGit, isGitRepo, getGitRoot, type GitExecResult, type GitIdentityEnv } from './git-executor';
7
7
  import { resolveBinary } from '../utils/cli';
8
8
  import { getCleanSpawnEnv } from '../utils/env';
9
9
  import {
@@ -241,9 +241,18 @@ export class GitService {
241
241
  // Commit
242
242
  // ============================================
243
243
 
244
- async commit(cwd: string, message: string): Promise<string> {
244
+ /**
245
+ * Create a commit.
246
+ *
247
+ * `identityEnv` carries who is committing (see `backend/git/identity`). It is
248
+ * threaded explicitly through the operations that create a git object or talk
249
+ * to a remote, rather than resolved inside `execGit`, because resolving it
250
+ * reads the database and the read-only commands run constantly. Anything
251
+ * added here that writes an object or authenticates needs the same parameter.
252
+ */
253
+ async commit(cwd: string, message: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
245
254
  assertSafeGitCommitMessage(message);
246
- const result = await execGit(['commit', '-m', message], cwd);
255
+ const result = await execGit(['commit', '-m', message], cwd, { env: identityEnv });
247
256
  if (result.exitCode !== 0) {
248
257
  throw new Error(`git commit failed: ${result.stderr}`);
249
258
  }
@@ -252,7 +261,7 @@ export class GitService {
252
261
  return hashResult.stdout.trim();
253
262
  }
254
263
 
255
- async amendCommit(cwd: string, message?: string): Promise<string> {
264
+ async amendCommit(cwd: string, message?: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
256
265
  const args = ['commit', '--amend'];
257
266
  if (message) {
258
267
  assertSafeGitCommitMessage(message);
@@ -260,7 +269,7 @@ export class GitService {
260
269
  } else {
261
270
  args.push('--no-edit');
262
271
  }
263
- const result = await execGit(args, cwd);
272
+ const result = await execGit(args, cwd, { env: identityEnv });
264
273
  if (result.exitCode !== 0) {
265
274
  // Unborn HEAD — git says "You have nothing to amend", which reads like a
266
275
  // failure rather than "commit normally instead".
@@ -535,10 +544,10 @@ export class GitService {
535
544
  }
536
545
  }
537
546
 
538
- async deleteRemoteBranch(cwd: string, remote: string, branch: string): Promise<void> {
547
+ async deleteRemoteBranch(cwd: string, remote: string, branch: string, identityEnv: GitIdentityEnv = {}): Promise<void> {
539
548
  assertSafeGitRevish(remote, 'remote name');
540
549
  assertSafeGitRevish(branch, 'branch name');
541
- const result = await execGit(['push', remote, '--delete', branch], cwd);
550
+ const result = await execGit(['push', remote, '--delete', branch], cwd, { env: identityEnv });
542
551
  if (result.exitCode !== 0) {
543
552
  throw new Error(`git push --delete failed: ${result.stderr}`);
544
553
  }
@@ -555,7 +564,8 @@ export class GitService {
555
564
  async mergeBranch(
556
565
  cwd: string,
557
566
  branchName: string,
558
- options: { noFastForward?: boolean; squash?: boolean; ffOnly?: boolean } | boolean = false
567
+ options: { noFastForward?: boolean; squash?: boolean; ffOnly?: boolean } | boolean = false,
568
+ identityEnv: GitIdentityEnv = {}
559
569
  ): Promise<{ success: boolean; message: string }> {
560
570
  assertSafeGitRevish(branchName, 'merge branch');
561
571
  const opts = typeof options === 'boolean' ? { noFastForward: options } : options;
@@ -564,7 +574,7 @@ export class GitService {
564
574
  else if (opts.ffOnly) args.push('--ff-only');
565
575
  else if (opts.noFastForward) args.push('--no-ff');
566
576
  args.push(branchName);
567
- const result = await execGit(args, cwd, 120000);
577
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
568
578
  return {
569
579
  success: result.exitCode === 0,
570
580
  message: result.exitCode === 0 ? result.stdout : result.stderr
@@ -627,10 +637,10 @@ export class GitService {
627
637
  return parseRemotes(result.stdout);
628
638
  }
629
639
 
630
- async fetch(cwd: string, remote = 'origin'): Promise<string> {
640
+ async fetch(cwd: string, remote = 'origin', identityEnv: GitIdentityEnv = {}): Promise<string> {
631
641
  assertSafeGitRemoteName(remote);
632
642
  // Use explicit refspec to ensure all branches are fetched regardless of clone config
633
- const result = await execGit(['fetch', remote, `+refs/heads/*:refs/remotes/${remote}/*`, '--prune'], cwd, 60000);
643
+ const result = await execGit(['fetch', remote, `+refs/heads/*:refs/remotes/${remote}/*`, '--prune'], cwd, { timeout: 60000, env: identityEnv });
634
644
  if (result.exitCode !== 0) {
635
645
  throw new Error(`git fetch failed: ${result.stderr}`);
636
646
  }
@@ -645,7 +655,7 @@ export class GitService {
645
655
  * differently-named branch, which is the normal state of a fork PR under
646
656
  * review. A tracked branch pulls from its own upstream.
647
657
  */
648
- async pull(cwd: string, remote = 'origin', branch?: string, rebase = false): Promise<{ success: boolean; message: string }> {
658
+ async pull(cwd: string, remote = 'origin', branch?: string, rebase = false, identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
649
659
  const args = ['pull'];
650
660
  if (rebase) args.push('--rebase');
651
661
 
@@ -659,7 +669,9 @@ export class GitService {
659
669
  }
660
670
  }
661
671
 
662
- const result = await execGit(args, cwd, 60000);
672
+ // A pull can create a merge commit, so it needs both halves of the
673
+ // identity: the credential to fetch, the name to author the merge.
674
+ const result = await execGit(args, cwd, { timeout: 60000, env: identityEnv });
663
675
  return {
664
676
  success: result.exitCode === 0,
665
677
  message: result.exitCode === 0 ? result.stdout : result.stderr
@@ -794,7 +806,8 @@ export class GitService {
794
806
  remote = 'origin',
795
807
  branch?: string,
796
808
  force = false,
797
- options: { useUpstream?: boolean } = {}
809
+ options: { useUpstream?: boolean } = {},
810
+ identityEnv: GitIdentityEnv = {}
798
811
  ): Promise<{ success: boolean; message: string }> {
799
812
  const { useUpstream = true } = options;
800
813
  const target = await this.getPushTarget(cwd, branch);
@@ -802,7 +815,7 @@ export class GitService {
802
815
  if (useUpstream && target.hasUpstream) {
803
816
  const args = ['push'];
804
817
  if (force) args.push('--force-with-lease');
805
- return this.describePushResult(cwd, await execGit(args, cwd, 60000));
818
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
806
819
  }
807
820
 
808
821
  assertSafeGitRemoteName(remote);
@@ -815,7 +828,7 @@ export class GitService {
815
828
  // Only safe here: the branch tracks nothing, so there is no upstream to
816
829
  // overwrite and recording one is the point of a first push.
817
830
  args.push('-u');
818
- return this.describePushResult(cwd, await execGit(args, cwd, 60000));
831
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
819
832
  }
820
833
 
821
834
  /** Point a branch at a different upstream — the way back from a wrong push. */
@@ -857,7 +870,8 @@ export class GitService {
857
870
  cwd: string,
858
871
  mode: 'with-tags' | 'all-tags' | 'force-lease' | 'force',
859
872
  remote = 'origin',
860
- branch?: string
873
+ branch?: string,
874
+ identityEnv: GitIdentityEnv = {}
861
875
  ): Promise<{ success: boolean; message: string }> {
862
876
  // `--tags` is about the tag namespace, not this branch, so it always needs
863
877
  // an explicit remote.
@@ -865,7 +879,7 @@ export class GitService {
865
879
  assertSafeGitRemoteName(remote);
866
880
  return this.describePushResult(
867
881
  cwd,
868
- await execGit(['push', remote, '--tags'], cwd, 60000)
882
+ await execGit(['push', remote, '--tags'], cwd, { timeout: 60000, env: identityEnv })
869
883
  );
870
884
  }
871
885
 
@@ -879,7 +893,7 @@ export class GitService {
879
893
  // Same rule as `push`: a tracked branch goes where git says it goes.
880
894
  const target = await this.getPushTarget(cwd, branch);
881
895
  if (target.hasUpstream) {
882
- return this.describePushResult(cwd, await execGit(['push', flag], cwd, 60000));
896
+ return this.describePushResult(cwd, await execGit(['push', flag], cwd, { timeout: 60000, env: identityEnv }));
883
897
  }
884
898
 
885
899
  assertSafeGitRemoteName(remote);
@@ -889,12 +903,12 @@ export class GitService {
889
903
  args.push(branch);
890
904
  }
891
905
  args.push(flag, '-u');
892
- return this.describePushResult(cwd, await execGit(args, cwd, 60000));
906
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
893
907
  }
894
908
 
895
909
  /** Fetch every configured remote and prune deleted remote-tracking refs. */
896
- async fetchAll(cwd: string): Promise<string> {
897
- const result = await execGit(['fetch', '--all', '--prune', '--tags'], cwd, 60000);
910
+ async fetchAll(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
911
+ const result = await execGit(['fetch', '--all', '--prune', '--tags'], cwd, { timeout: 60000, env: identityEnv });
898
912
  if (result.exitCode !== 0) {
899
913
  throw new Error(`git fetch --all failed: ${result.stderr}`);
900
914
  }
@@ -950,7 +964,7 @@ export class GitService {
950
964
  return parseStashList(result.stdout);
951
965
  }
952
966
 
953
- async stashSave(cwd: string, message?: string, stagedOnly = false): Promise<void> {
967
+ async stashSave(cwd: string, message?: string, stagedOnly = false, identityEnv: GitIdentityEnv = {}): Promise<void> {
954
968
  const args = ['stash', 'push'];
955
969
  // `--staged` stashes exactly the index (works at hunk level, so partially
956
970
  // staged files are handled precisely). Requires Git >= 2.35.
@@ -959,7 +973,7 @@ export class GitService {
959
973
  assertSafeGitCommitMessage(message);
960
974
  args.push('-m', message);
961
975
  }
962
- const result = await execGit(args, cwd);
976
+ const result = await execGit(args, cwd, { env: identityEnv });
963
977
  if (result.exitCode !== 0) {
964
978
  // Git < 2.35 doesn't know `--staged`; surface an actionable message
965
979
  // instead of the raw "unknown option" / "usage:" noise.
@@ -1073,7 +1087,7 @@ export class GitService {
1073
1087
  return tags;
1074
1088
  }
1075
1089
 
1076
- async createTag(cwd: string, name: string, message?: string, commitHash?: string): Promise<void> {
1090
+ async createTag(cwd: string, name: string, message?: string, commitHash?: string, identityEnv: GitIdentityEnv = {}): Promise<void> {
1077
1091
  assertSafeGitRevish(name, 'tag name');
1078
1092
  const args = ['tag'];
1079
1093
  if (message) {
@@ -1086,7 +1100,7 @@ export class GitService {
1086
1100
  assertSafeGitRevish(commitHash, 'tag target');
1087
1101
  args.push(commitHash);
1088
1102
  }
1089
- const result = await execGit(args, cwd);
1103
+ const result = await execGit(args, cwd, { env: identityEnv });
1090
1104
  if (result.exitCode !== 0) {
1091
1105
  throw new Error(`git tag failed: ${result.stderr}`);
1092
1106
  }
@@ -1100,10 +1114,10 @@ export class GitService {
1100
1114
  }
1101
1115
  }
1102
1116
 
1103
- async pushTag(cwd: string, name: string, remote = 'origin'): Promise<{ success: boolean; message: string }> {
1117
+ async pushTag(cwd: string, name: string, remote = 'origin', identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1104
1118
  assertSafeGitRemoteName(remote);
1105
1119
  assertSafeGitRevish(name, 'tag name');
1106
- const result = await execGit(['push', remote, name], cwd, 60000);
1120
+ const result = await execGit(['push', remote, name], cwd, { timeout: 60000, env: identityEnv });
1107
1121
  return {
1108
1122
  success: result.exitCode === 0,
1109
1123
  message: result.exitCode === 0 ? (result.stderr || result.stdout) : result.stderr
@@ -1422,7 +1436,7 @@ export class GitService {
1422
1436
  * on failure, because the common failures here are instructions rather than
1423
1437
  * errors — "nothing to commit, use --skip" is something the user must read.
1424
1438
  */
1425
- async continueOperation(cwd: string): Promise<{ success: boolean; message: string }> {
1439
+ async continueOperation(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1426
1440
  const operation = await this.detectGitOperation(cwd);
1427
1441
  const unmerged = await this.getUnmergedPaths(cwd);
1428
1442
  if (unmerged.length > 0) {
@@ -1449,7 +1463,7 @@ export class GitService {
1449
1463
  throw new Error('There is no operation to continue.');
1450
1464
  }
1451
1465
 
1452
- const result = await execGit(args, cwd, 120000);
1466
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
1453
1467
  return {
1454
1468
  success: result.exitCode === 0,
1455
1469
  message: (result.exitCode === 0 ? result.stdout : result.stderr).trim()
@@ -1457,7 +1471,7 @@ export class GitService {
1457
1471
  }
1458
1472
 
1459
1473
  /** Drop the commit git is currently stuck on and move to the next one. */
1460
- async skipOperation(cwd: string): Promise<{ success: boolean; message: string }> {
1474
+ async skipOperation(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1461
1475
  const operation = await this.detectGitOperation(cwd);
1462
1476
  let args: string[];
1463
1477
  switch (operation) {
@@ -1474,7 +1488,7 @@ export class GitService {
1474
1488
  throw new Error('This operation cannot be skipped.');
1475
1489
  }
1476
1490
 
1477
- const result = await execGit(args, cwd, 120000);
1491
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
1478
1492
  return {
1479
1493
  success: result.exitCode === 0,
1480
1494
  message: (result.exitCode === 0 ? result.stdout : result.stderr).trim()
@@ -1531,14 +1545,15 @@ export class GitService {
1531
1545
  async rebaseOnto(
1532
1546
  cwd: string,
1533
1547
  upstream: string,
1534
- autostash = true
1548
+ autostash = true,
1549
+ identityEnv: GitIdentityEnv = {}
1535
1550
  ): Promise<{ success: boolean; hasConflicts: boolean; message: string }> {
1536
1551
  assertSafeGitRevish(upstream, 'rebase upstream');
1537
1552
  const args = ['rebase'];
1538
1553
  if (autostash) args.push('--autostash');
1539
1554
  args.push(upstream);
1540
1555
 
1541
- const result = await execGit(args, cwd, 120000);
1556
+ const result = await execGit(args, cwd, { timeout: 120000, env: identityEnv });
1542
1557
  const combined = `${result.stdout}\n${result.stderr}`;
1543
1558
  const hasConflicts = /CONFLICT \(/.test(combined) || /could not apply/i.test(combined);
1544
1559
  if (result.exitCode !== 0 && !hasConflicts) {
@@ -1644,9 +1659,9 @@ export class GitService {
1644
1659
  }
1645
1660
 
1646
1661
  /** Create a new commit that reverses a previous one (default: HEAD). */
1647
- async revertCommit(cwd: string, ref = 'HEAD'): Promise<{ success: boolean; message: string }> {
1662
+ async revertCommit(cwd: string, ref = 'HEAD', identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1648
1663
  assertSafeGitRevish(ref, 'revert ref');
1649
- const result = await execGit(['revert', '--no-edit', ref], cwd);
1664
+ const result = await execGit(['revert', '--no-edit', ref], cwd, { env: identityEnv });
1650
1665
  if (result.exitCode !== 0 && !(await this.hasCommits(cwd))) {
1651
1666
  // Unborn HEAD — git only reports `bad revision 'HEAD'`.
1652
1667
  return { success: false, message: 'This repository has no commits yet, so there is nothing to revert.' };
@@ -1658,14 +1673,14 @@ export class GitService {
1658
1673
  }
1659
1674
 
1660
1675
  /** Cherry-pick one or more commits onto the current branch (`git cherry-pick <hash>...`). */
1661
- async cherryPick(cwd: string, refs: string[]): Promise<{ success: boolean; message: string }> {
1676
+ async cherryPick(cwd: string, refs: string[], identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1662
1677
  if (refs.length === 0) {
1663
1678
  return { success: false, message: 'No commits provided' };
1664
1679
  }
1665
1680
  for (const ref of refs) {
1666
1681
  assertSafeGitRevish(ref, 'cherry-pick ref');
1667
1682
  }
1668
- const result = await execGit(['cherry-pick', ...refs], cwd);
1683
+ const result = await execGit(['cherry-pick', ...refs], cwd, { env: identityEnv });
1669
1684
  return {
1670
1685
  success: result.exitCode === 0,
1671
1686
  message: result.exitCode === 0 ? (result.stdout || result.stderr || 'Cherry-pick succeeded') : result.stderr
@@ -1705,17 +1720,21 @@ export class GitService {
1705
1720
  */
1706
1721
  async npmVersion(
1707
1722
  cwd: string,
1708
- bump: 'patch' | 'minor' | 'major'
1723
+ bump: 'patch' | 'minor' | 'major',
1724
+ identityEnv: GitIdentityEnv = {}
1709
1725
  ): Promise<{ success: boolean; version: string; message: string }> {
1710
1726
  const npmPath = resolveBinary('npm');
1711
1727
  if (!npmPath) {
1712
1728
  throw new Error('npm binary not found on PATH');
1713
1729
  }
1730
+ // npm runs git itself for the bump commit and tag, so the identity has to
1731
+ // travel in the environment — there is no `execGit` call here to attach it
1732
+ // to, and this is precisely why the mechanism is environment-based.
1714
1733
  const proc = Bun.spawn([npmPath, 'version', bump], {
1715
1734
  cwd,
1716
1735
  stdout: 'pipe',
1717
1736
  stderr: 'pipe',
1718
- env: { ...getCleanSpawnEnv() }
1737
+ env: { ...getCleanSpawnEnv(), ...identityEnv }
1719
1738
  });
1720
1739
  const [stdout, stderr] = await Promise.all([
1721
1740
  new Response(proc.stdout).text(),
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The helper's input parsing, which authentication depends on.
3
+ *
4
+ * Git speaks a line protocol on stdin and reads the answer on stdout, so a
5
+ * mis-parse does not fail loudly — it produces a helper that silently answers
6
+ * nothing, and a push that asks for a password nobody typed.
7
+ */
8
+
9
+ import { describe, expect, test } from 'bun:test';
10
+ import { identityIdFrom, parseCredentialRequest } from './cli';
11
+
12
+ describe('parseCredentialRequest', () => {
13
+ test('reads the key=value lines git sends', () => {
14
+ expect(
15
+ parseCredentialRequest('protocol=https\nhost=github.com\npath=owner/repo.git\n\n')
16
+ ).toEqual({
17
+ protocol: 'https',
18
+ host: 'github.com',
19
+ path: 'owner/repo.git'
20
+ });
21
+ });
22
+
23
+ test('keeps a value containing "=" intact', () => {
24
+ // Only the FIRST `=` separates; a token or query string would otherwise
25
+ // arrive truncated at its first equals sign.
26
+ expect(parseCredentialRequest('password=abc=def=ghi\n')).toEqual({
27
+ password: 'abc=def=ghi'
28
+ });
29
+ });
30
+
31
+ test('ignores blank lines and malformed rows rather than failing', () => {
32
+ expect(parseCredentialRequest('\nhost=github.com\n\n=novalue\ngarbage\n')).toEqual({
33
+ host: 'github.com'
34
+ });
35
+ });
36
+
37
+ test('an empty value is a value, not a missing key', () => {
38
+ expect(parseCredentialRequest('username=\n')).toEqual({ username: '' });
39
+ });
40
+
41
+ test('empty input yields no fields', () => {
42
+ expect(parseCredentialRequest('')).toEqual({});
43
+ });
44
+ });
45
+
46
+ describe('identityIdFrom', () => {
47
+ test('finds the flag among git-appended arguments', () => {
48
+ // Git appends the operation after our own arguments.
49
+ expect(identityIdFrom(['--identity=abc-123', 'get'])).toBe('abc-123');
50
+ expect(identityIdFrom(['get', '--identity=abc-123'])).toBe('abc-123');
51
+ });
52
+
53
+ test('a missing or empty flag yields null, so the helper declines', () => {
54
+ expect(identityIdFrom(['get'])).toBeNull();
55
+ expect(identityIdFrom(['--identity=', 'get'])).toBeNull();
56
+ expect(identityIdFrom([])).toBeNull();
57
+ });
58
+ });
@@ -0,0 +1,201 @@
1
+ /**
2
+ * The two helper subcommands git invokes: `git-credential` and `git-askpass`.
3
+ *
4
+ * Both exist for one reason: A SECRET MUST NOT TRAVEL THROUGH ARGV OR THE
5
+ * ENVIRONMENT. `ps` shows another user on the same machine every argument of
6
+ * every running process, and the alternatives git offers all leak:
7
+ * `http.extraheader` puts the token in the command line, `credential.helper
8
+ * store` writes it to a plaintext file, and a token embedded in a remote URL
9
+ * persists in `.git/config`. A helper receives its question on stdin and
10
+ * answers on stdout, which no other process can read.
11
+ *
12
+ * ── STDOUT IS THE PROTOCOL ──
13
+ * Git parses this process's stdout. Anything else written there — a debug line,
14
+ * a warning, a stray `console.log` from a module loaded on the way in — is read
15
+ * as part of the answer and corrupts it. So the first thing either entry point
16
+ * does is move `console.log` to stderr. That is not tidiness; it is what keeps
17
+ * an unrelated log statement from breaking authentication.
18
+ *
19
+ * These run in a SHORT-LIVED SEPARATE PROCESS. Git spawns them, they answer,
20
+ * they exit. They open the database directly and start no server.
21
+ */
22
+
23
+ /**
24
+ * Silence routine logging for the rest of this process.
25
+ *
26
+ * `debug.log` writes through `console.log`, which is stdout — the protocol
27
+ * channel. Redirecting it to stderr protects the protocol but then prints
28
+ * "Connected to database" into the middle of the user's `git push` output,
29
+ * which is noise they can neither act on nor turn off. So routine logs are
30
+ * dropped entirely; a genuine helper failure still goes to stderr through
31
+ * `console.error`, which git shows and which is worth showing.
32
+ */
33
+ function protectStdout(): void {
34
+ const drop = () => {};
35
+ console.log = drop;
36
+ console.info = drop;
37
+ console.debug = drop;
38
+ }
39
+
40
+ /** `--identity=<id>` out of the helper's own arguments. */
41
+ export function identityIdFrom(argv: string[]): string | null {
42
+ for (const arg of argv) {
43
+ if (arg.startsWith('--identity=')) {
44
+ const value = arg.slice('--identity='.length).trim();
45
+ if (value) return value;
46
+ }
47
+ }
48
+ return null;
49
+ }
50
+
51
+ /**
52
+ * Open the existing database, without migrating or seeding it.
53
+ *
54
+ * `initializeDatabase()` would run migrations and seeders — the right thing for
55
+ * a server starting up, the wrong thing for a helper git spawned mid-push. It
56
+ * would race the running server's schema and could apply a migration from a
57
+ * process nobody is watching. A helper only ever reads one row.
58
+ */
59
+ async function connectReadOnly(): Promise<void> {
60
+ const { connectExistingDatabase } = await import('$backend/database');
61
+ await connectExistingDatabase();
62
+ }
63
+
64
+ /** Read stdin to the end. Empty string when nothing is piped. */
65
+ async function readStdin(): Promise<string> {
66
+ try {
67
+ return await new Response(Bun.stdin.stream()).text();
68
+ } catch {
69
+ return '';
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Parse git's credential description: `key=value` lines, blank line terminated.
75
+ *
76
+ * Unknown keys are kept — git adds fields over time, and one we do not
77
+ * recognise is not a reason to fail an authentication.
78
+ */
79
+ export function parseCredentialRequest(input: string): Record<string, string> {
80
+ const fields: Record<string, string> = {};
81
+ for (const line of input.split('\n')) {
82
+ const trimmed = line.trim();
83
+ if (!trimmed) continue;
84
+ const eq = trimmed.indexOf('=');
85
+ if (eq <= 0) continue;
86
+ fields[trimmed.slice(0, eq)] = trimmed.slice(eq + 1);
87
+ }
88
+ return fields;
89
+ }
90
+
91
+ /**
92
+ * Answer a `git credential` request.
93
+ *
94
+ * Only `get` produces output. `store` and `erase` are accepted and ignored on
95
+ * purpose: the credential lives in Clopen's database, and letting git overwrite
96
+ * or delete it would put git's cache in charge of a user's stored account.
97
+ * Exiting 0 without output tells git "no opinion", which is the correct answer
98
+ * for a read-only helper.
99
+ */
100
+ async function runCredentialHelper(argv: string[]): Promise<number> {
101
+ const operation = argv.find((a) => !a.startsWith('--')) ?? 'get';
102
+ if (operation !== 'get') return 0;
103
+
104
+ const identityId = identityIdFrom(argv);
105
+ if (!identityId) return 0;
106
+
107
+ const request = parseCredentialRequest(await readStdin());
108
+
109
+ // Imported here, after stdout is protected, and lazily so `store`/`erase`
110
+ // never pay for opening the database.
111
+ await connectReadOnly();
112
+ const { gitIdentityQueries, integrationAccountQueries, parseHosts } = await import(
113
+ '$backend/database/queries'
114
+ );
115
+
116
+ const row = gitIdentityQueries.getById(identityId);
117
+ if (!row) return 0;
118
+
119
+ // The host git is asking about must be one this identity claims. Without the
120
+ // check, a repository whose remote was changed to another host would be
121
+ // handed this account's token.
122
+ const host = (request.host ?? '').toLowerCase().split(':')[0] ?? '';
123
+ if (host && !parseHosts(row.hosts).includes(host)) return 0;
124
+
125
+ let token: string | null = null;
126
+ if (row.auth_method === 'https-token') {
127
+ token = row.https_token;
128
+ } else if (row.auth_method === 'https-account' && row.integration_account_id) {
129
+ // Borrowed from a connected integration account, so rotating the token in
130
+ // one place is enough.
131
+ const account = integrationAccountQueries.getById(row.integration_account_id);
132
+ if (account) {
133
+ const credentials = integrationAccountQueries.credentialsOf(account);
134
+ token = credentials.token ?? credentials.apiKey ?? null;
135
+ }
136
+ }
137
+ if (!token) return 0;
138
+
139
+ // GitHub and friends accept any non-empty username alongside a token, but it
140
+ // must not be blank, so fall back to the conventional placeholder.
141
+ const username = row.https_username || request.username || 'x-access-token';
142
+ process.stdout.write(`username=${username}\npassword=${token}\n`);
143
+ return 0;
144
+ }
145
+
146
+ /**
147
+ * Answer `ssh`'s passphrase prompt.
148
+ *
149
+ * `ssh` calls SSH_ASKPASS with the prompt text as an argument and reads the
150
+ * answer from stdout. Only passphrase prompts are answered: a host-key
151
+ * confirmation ("Are you sure you want to continue connecting?") reaching this
152
+ * helper must not be auto-accepted, because that is the check that detects a
153
+ * man-in-the-middle.
154
+ */
155
+ async function runAskpass(argv: string[]): Promise<number> {
156
+ const identityId = identityIdFrom(argv);
157
+ if (!identityId) return 1;
158
+
159
+ const prompt = argv.filter((a) => !a.startsWith('--') && a !== 'git-askpass').join(' ');
160
+ if (prompt && !/passphrase|password/i.test(prompt)) {
161
+ // Declining leaves ssh to fail the way it would without us, which is the
162
+ // safe outcome for anything that is not a passphrase question.
163
+ return 1;
164
+ }
165
+
166
+ await connectReadOnly();
167
+ const { gitIdentityQueries } = await import('$backend/database/queries');
168
+
169
+ const row = gitIdentityQueries.getById(identityId);
170
+ if (!row?.ssh_passphrase) return 1;
171
+
172
+ process.stdout.write(`${row.ssh_passphrase}\n`);
173
+ return 0;
174
+ }
175
+
176
+ /** The subcommands this module owns. */
177
+ export const GIT_HELPER_COMMANDS = ['git-credential', 'git-askpass'] as const;
178
+
179
+ /**
180
+ * Handle a helper subcommand if this invocation is one.
181
+ *
182
+ * Returns the exit code to use, or `null` when the arguments are not a helper
183
+ * call and the CLI should carry on to its normal startup.
184
+ */
185
+ export async function runGitHelper(argv: string[]): Promise<number | null> {
186
+ const command = argv[0];
187
+ if (command !== 'git-credential' && command !== 'git-askpass') return null;
188
+
189
+ protectStdout();
190
+
191
+ try {
192
+ return command === 'git-credential'
193
+ ? await runCredentialHelper(argv.slice(1))
194
+ : await runAskpass(argv.slice(1));
195
+ } catch (error) {
196
+ // Never print the failure to stdout, and never expose the reason to git —
197
+ // an empty answer means "no credential", which is what a failure is.
198
+ console.error('[clopen] git helper failed:', error);
199
+ return command === 'git-credential' ? 0 : 1;
200
+ }
201
+ }