git-colabor 0.1.8 → 0.1.10

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 (4) hide show
  1. package/README.md +2 -3
  2. package/dist/cli.cjs +1094 -870
  3. package/dist/index.cjs +408 -179
  4. package/package.json +1 -1
package/dist/cli.cjs CHANGED
@@ -1,195 +1,109 @@
1
1
  'use strict';
2
2
 
3
- var fs = require('fs');
3
+ var os = require('os');
4
4
  var path = require('path');
5
5
  var promises = require('fs/promises');
6
6
  var crypto = require('crypto');
7
- var os = require('os');
8
7
  var child_process = require('child_process');
8
+ var fs = require('fs');
9
9
 
10
- // src/cli/index.ts
11
-
12
- // src/core/errors.ts
13
- var EXIT_CODES = {
14
- RUNTIME: 1,
15
- USAGE: 2,
16
- NOT_A_REPO: 3,
17
- SECRET_UNAVAILABLE: 4,
18
- NOT_FOUND: 5};
19
- var AppError = class extends Error {
20
- code;
21
- exitCode;
22
- hints;
23
- constructor(init) {
24
- super(init.message);
25
- this.name = "AppError";
26
- this.code = init.code;
27
- this.exitCode = init.exitCode ?? EXIT_CODES.RUNTIME;
28
- this.hints = init.hints;
29
- }
30
- toPayload() {
31
- return { code: this.code, message: this.message, hints: this.hints, exitCode: this.exitCode };
32
- }
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __esm = (fn, res) => function __init() {
13
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
33
14
  };
34
- var Errors = {
35
- notARepo: (cwd) => new AppError({
36
- code: "NOT_A_REPO",
37
- message: cwd ? `not a git repository: ${cwd}` : "not a git repository",
38
- exitCode: EXIT_CODES.NOT_A_REPO
39
- }),
40
- authorNotFound: (key) => new AppError({
41
- code: "AUTHOR_NOT_FOUND",
42
- message: `Author with initials "${key}" not found in identities`,
43
- exitCode: EXIT_CODES.NOT_FOUND,
44
- hints: [`Add it with: git colabor coauthor add ${key} "Full Name" email@example.com`]
45
- }),
46
- duplicateKey: (key) => new AppError({
47
- code: "DUPLICATE_KEY",
48
- message: `Key "${key}" already exists`,
49
- exitCode: EXIT_CODES.NOT_FOUND,
50
- hints: []
51
- }),
52
- invalidEmail: (email) => new AppError({ code: "INVALID_EMAIL", message: `Invalid email: ${email}`, exitCode: EXIT_CODES.USAGE }),
53
- usage: (message, hints) => new AppError({ code: "USAGE", message, exitCode: EXIT_CODES.USAGE, hints }),
54
- secretUnavailable: (message, hints) => new AppError({ code: "SECRET_UNAVAILABLE", message, exitCode: EXIT_CODES.SECRET_UNAVAILABLE, hints })
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
55
18
  };
19
+
20
+ // src/core/errors.ts
56
21
  function toErrorPayload(e) {
57
22
  if (e instanceof AppError) return e.toPayload();
58
23
  const message = e instanceof Error ? e.message : String(e);
59
24
  return { code: "INTERNAL", message, exitCode: EXIT_CODES.RUNTIME };
60
25
  }
61
-
62
- // src/cli/json.ts
63
- function ok(data, warnings) {
64
- return warnings && warnings.length > 0 ? { ok: true, data, warnings } : { ok: true, data };
65
- }
66
- function failFromError(e) {
67
- return { ok: false, error: toErrorPayload(e), data: null };
68
- }
69
- function emit(result, opts) {
70
- if (opts.json) {
71
- process.stdout.write(JSON.stringify(result) + "\n");
72
- } else if (opts.human) {
73
- const txt = opts.human(result);
74
- if (txt) {
75
- const stream = result.ok ? process.stdout : process.stderr;
76
- stream.write(txt.endsWith("\n") ? txt : `${txt}
77
- `);
78
- }
79
- }
80
- process.exit(result.ok ? 0 : result.error.exitCode);
81
- }
82
-
83
- // src/cli/parse-args.ts
84
- function parseGlobals(argv) {
85
- const flags = { json: false, noColor: false, help: false, version: false };
86
- const rest = [];
87
- for (let i = 0; i < argv.length; i++) {
88
- const tok = argv[i];
89
- if (!tok) continue;
90
- if (tok === "--") {
91
- rest.push(...argv.slice(i + 1));
92
- break;
93
- }
94
- if (tok === "-C") {
95
- flags.cwd = argv[++i];
96
- continue;
97
- }
98
- if (tok.startsWith("-C") && tok.length > 2) {
99
- flags.cwd = tok.slice(2);
100
- continue;
101
- }
102
- if (tok === "--log-level") {
103
- flags.logLevel = argv[++i];
104
- continue;
105
- }
106
- if (tok.startsWith("--log-level=")) {
107
- flags.logLevel = tok.slice("--log-level=".length);
108
- continue;
109
- }
110
- if (tok === "--json") {
111
- flags.json = true;
112
- continue;
113
- }
114
- if (tok === "--no-color") {
115
- flags.noColor = true;
116
- continue;
117
- }
118
- if (tok === "-h" || tok === "--help") {
119
- flags.help = true;
120
- continue;
121
- }
122
- if (tok === "-v" || tok === "--version") {
123
- flags.version = true;
124
- continue;
125
- }
126
- rest.push(tok);
127
- }
128
- return { flags, rest };
129
- }
130
- function parseCommandArgs(tokens, spec = {}) {
131
- const positionals = [];
132
- const values = {};
133
- const bools = /* @__PURE__ */ new Set();
134
- const valueFlags = new Set(spec.valueFlags ?? []);
135
- const boolFlags = new Set(spec.boolFlags ?? []);
136
- for (let i = 0; i < tokens.length; i++) {
137
- const tok = tokens[i];
138
- if (!tok) continue;
139
- if (tok === "--") {
140
- positionals.push(...tokens.slice(i + 1));
141
- break;
142
- }
143
- if (tok.startsWith("--") && tok.includes("=")) {
144
- const eq = tok.indexOf("=");
145
- const k = tok.slice(0, eq);
146
- const v = tok.slice(eq + 1);
147
- if (valueFlags.has(k)) values[k] = v;
148
- else bools.add(k);
149
- continue;
150
- }
151
- if (valueFlags.has(tok)) {
152
- const v = tokens[++i];
153
- if (v !== void 0) values[tok] = v;
154
- continue;
155
- }
156
- if (boolFlags.has(tok)) {
157
- bools.add(tok);
158
- continue;
159
- }
160
- if (tok.startsWith("-")) {
161
- bools.add(tok);
162
- continue;
163
- }
164
- positionals.push(tok);
26
+ var EXIT_CODES, AppError, Errors;
27
+ var init_errors = __esm({
28
+ "src/core/errors.ts"() {
29
+ EXIT_CODES = {
30
+ OK: 0,
31
+ RUNTIME: 1,
32
+ USAGE: 2,
33
+ NOT_A_REPO: 3,
34
+ SECRET_UNAVAILABLE: 4,
35
+ NOT_FOUND: 5,
36
+ CONFLICT_BLOCKED: 6
37
+ };
38
+ AppError = class extends Error {
39
+ code;
40
+ exitCode;
41
+ hints;
42
+ constructor(init) {
43
+ super(init.message);
44
+ this.name = "AppError";
45
+ this.code = init.code;
46
+ this.exitCode = init.exitCode ?? EXIT_CODES.RUNTIME;
47
+ this.hints = init.hints;
48
+ }
49
+ toPayload() {
50
+ return { code: this.code, message: this.message, hints: this.hints, exitCode: this.exitCode };
51
+ }
52
+ };
53
+ Errors = {
54
+ notARepo: (cwd) => new AppError({
55
+ code: "NOT_A_REPO",
56
+ message: cwd ? `not a git repository: ${cwd}` : "not a git repository",
57
+ exitCode: EXIT_CODES.NOT_A_REPO
58
+ }),
59
+ authorNotFound: (key) => new AppError({
60
+ code: "AUTHOR_NOT_FOUND",
61
+ message: `Author with initials "${key}" not found in identities`,
62
+ exitCode: EXIT_CODES.NOT_FOUND,
63
+ hints: [`Add it with: git colabor coauthor add ${key} "Full Name" email@example.com`]
64
+ }),
65
+ duplicateKey: (key) => new AppError({
66
+ code: "DUPLICATE_KEY",
67
+ message: `Key "${key}" already exists`,
68
+ exitCode: EXIT_CODES.NOT_FOUND,
69
+ hints: []
70
+ }),
71
+ invalidEmail: (email) => new AppError({ code: "INVALID_EMAIL", message: `Invalid email: ${email}`, exitCode: EXIT_CODES.USAGE }),
72
+ usage: (message, hints) => new AppError({ code: "USAGE", message, exitCode: EXIT_CODES.USAGE, hints }),
73
+ secretUnavailable: (message, hints) => new AppError({ code: "SECRET_UNAVAILABLE", message, exitCode: EXIT_CODES.SECRET_UNAVAILABLE, hints })
74
+ };
165
75
  }
166
- return { positionals, values, bools };
167
- }
76
+ });
168
77
 
169
78
  // src/core/authors/types.ts
170
- var CO_AUTHOR_TRAILER = "Co-authored-by:";
171
- var Author = class {
172
- constructor(key, name, email) {
173
- this.key = key;
174
- this.name = name;
175
- this.email = email;
176
- }
177
- key;
178
- name;
179
- email;
180
- /** `NAME <EMAIL>` */
181
- toString() {
182
- return `${this.name} <${this.email}>`;
183
- }
184
- /** `Co-authored-by: NAME <EMAIL>` */
185
- format() {
186
- return `${CO_AUTHOR_TRAILER} ${this.toString()}`;
187
- }
188
- };
189
79
  function genKey(name, email) {
190
80
  const initials = name.toLowerCase().split(/\s+/).filter(Boolean).map((w) => w[0] ?? "").join("");
191
81
  return `${initials}${email.slice(0, 2)}`;
192
82
  }
83
+ var CO_AUTHOR_TRAILER, Author;
84
+ var init_types = __esm({
85
+ "src/core/authors/types.ts"() {
86
+ CO_AUTHOR_TRAILER = "Co-authored-by:";
87
+ Author = class {
88
+ constructor(key, name, email) {
89
+ this.key = key;
90
+ this.name = name;
91
+ this.email = email;
92
+ }
93
+ key;
94
+ name;
95
+ email;
96
+ /** `NAME <EMAIL>` */
97
+ toString() {
98
+ return `${this.name} <${this.email}>`;
99
+ }
100
+ /** `Co-authored-by: NAME <EMAIL>` */
101
+ format() {
102
+ return `${CO_AUTHOR_TRAILER} ${this.toString()}`;
103
+ }
104
+ };
105
+ }
106
+ });
193
107
  function dataDir() {
194
108
  if (process.platform === "win32") {
195
109
  return path.join(process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"), "git-colabor");
@@ -202,6 +116,10 @@ function mapPath() {
202
116
  function auditLogPath() {
203
117
  return process.env.GIT_COLABOR_AUDIT_FILE ?? path.join(dataDir(), "audit.log");
204
118
  }
119
+ var init_paths = __esm({
120
+ "src/core/paths.ts"() {
121
+ }
122
+ });
205
123
  async function atomicWriteJson(path$1, data, mode) {
206
124
  await promises.mkdir(path.dirname(path$1), { recursive: true });
207
125
  const tmp = `${path$1}.${crypto.randomBytes(4).toString("hex")}.tmp`;
@@ -212,27 +130,75 @@ async function atomicWriteJson(path$1, data, mode) {
212
130
  }
213
131
  await promises.rename(tmp, path$1);
214
132
  }
133
+ var init_io = __esm({
134
+ "src/core/io.ts"() {
135
+ }
136
+ });
215
137
 
216
138
  // src/core/identity/map.ts
217
- function genId() {
218
- return "id_" + crypto.randomBytes(4).toString("hex");
139
+ var map_exports = {};
140
+ __export(map_exports, {
141
+ addIdentity: () => addIdentity,
142
+ findIdentity: () => findIdentity,
143
+ getIdentity: () => getIdentity,
144
+ getKeyBinding: () => getKeyBinding,
145
+ hideIdentityEmail: () => hideIdentityEmail,
146
+ identityId: () => identityId,
147
+ listHiddenEmails: () => listHiddenEmails,
148
+ listIdentities: () => listIdentities,
149
+ readMap: () => readMap,
150
+ removeIdentity: () => removeIdentity,
151
+ setDefault: () => setDefault,
152
+ setKeyBinding: () => setKeyBinding,
153
+ setPushKey: () => setPushKey,
154
+ setSignKey: () => setSignKey,
155
+ unhideIdentityEmail: () => unhideIdentityEmail,
156
+ updateIdentity: () => updateIdentity,
157
+ writeMap: () => writeMap
158
+ });
159
+ function identityId(name, email) {
160
+ return "id_" + crypto.createHash("sha256").update(`${name}
161
+ ${email}`).digest("hex").slice(0, 12);
219
162
  }
220
163
  async function readMap() {
221
164
  try {
222
165
  const txt = await promises.readFile(mapPath(), "utf8");
223
166
  const parsed = JSON.parse(txt);
224
167
  const identities = { ...parsed.identities };
168
+ const keyBindings = { ...parsed.keyBindings ?? {} };
225
169
  for (const id of Object.keys(identities)) {
226
170
  const row = identities[id];
171
+ if (row.sshKeyPath && row.sshKeyFingerprint && !keyBindings[id]?.pushKey) {
172
+ const ref = { path: row.sshKeyPath, fingerprint: row.sshKeyFingerprint };
173
+ if (row.sshKeyEncrypted) ref.encrypted = true;
174
+ const existing = keyBindings[id] ?? {};
175
+ keyBindings[id] = { ...existing, pushKey: ref };
176
+ }
177
+ if (row.gpgKey && !keyBindings[id]?.signKey) {
178
+ const existing = keyBindings[id] ?? {};
179
+ keyBindings[id] = { ...existing, signKey: { format: "openpgp", key: row.gpgKey } };
180
+ }
181
+ delete row.sshKeyPath;
182
+ delete row.sshKeyFingerprint;
183
+ delete row.sshKeyEncrypted;
184
+ delete row.gpgKey;
227
185
  delete row.passphraseCommand;
228
- if (row.scope === "user" || row.scope === "vscode") row.scope = "machine";
186
+ delete row.disabled;
187
+ delete row.remoteKeys;
188
+ const legacyScope = row.scope;
189
+ if (legacyScope === "user" || legacyScope === "vscode") row.scope = "machine";
229
190
  }
230
- return {
191
+ const migrated = {
231
192
  schemaVersion: 1,
232
193
  identities,
194
+ keyBindings,
233
195
  defaultIdentity: parsed.defaultIdentity,
234
196
  hidden: parsed.hidden
235
197
  };
198
+ if (JSON.stringify(parsed) !== JSON.stringify(migrated)) {
199
+ await writeMap(migrated);
200
+ }
201
+ return migrated;
236
202
  } catch {
237
203
  return { schemaVersion: 1, identities: {} };
238
204
  }
@@ -246,11 +212,17 @@ async function getIdentity(id) {
246
212
  if (!found) throw Errors.usage(`identity "${id}" not found`);
247
213
  return found;
248
214
  }
215
+ async function findIdentity(name, email) {
216
+ const map = await readMap();
217
+ return Object.values(map.identities).find(
218
+ (i) => i.email.toLowerCase() === email.toLowerCase() && i.name.trim() === name.trim()
219
+ );
220
+ }
249
221
  async function addIdentity(input) {
250
222
  const map = await readMap();
251
- const id = input.id ?? genId();
252
- if (map.identities[id]) throw Errors.usage(`identity "${id}" already exists`);
223
+ const id = input.id ?? identityId(input.name, input.email);
253
224
  const identity = { ...input, id, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
225
+ if (map.identities[id]) return map.identities[id];
254
226
  map.identities[id] = identity;
255
227
  if (map.hidden?.[identity.email.toLowerCase()]) delete map.hidden[identity.email.toLowerCase()];
256
228
  await writeMap(map);
@@ -260,15 +232,27 @@ async function updateIdentity(id, patch) {
260
232
  const map = await readMap();
261
233
  const identity = map.identities[id];
262
234
  if (!identity) throw Errors.usage(`identity "${id}" not found`);
263
- const next = { ...identity, ...patch };
264
- if (patch.sshKeyPath === void 0 && Object.keys(patch).includes("sshKeyPath")) {
265
- delete next.sshKeyPath;
266
- delete next.sshKeyFingerprint;
267
- delete next.sshKeyEncrypted;
268
- }
269
- map.identities[id] = next;
235
+ map.identities[id] = { ...identity, ...patch };
236
+ await writeMap(map);
237
+ return map.identities[id];
238
+ }
239
+ async function getKeyBinding(id) {
240
+ const map = await readMap();
241
+ return map.keyBindings?.[id] ?? {};
242
+ }
243
+ async function setKeyBinding(id, binding) {
244
+ const map = await readMap();
245
+ if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
246
+ map.keyBindings = { ...map.keyBindings, [id]: binding };
270
247
  await writeMap(map);
271
- return next;
248
+ }
249
+ async function setPushKey(id, ref) {
250
+ const b = await getKeyBinding(id);
251
+ await setKeyBinding(id, { ...b, pushKey: ref });
252
+ }
253
+ async function setSignKey(id, ref) {
254
+ const b = await getKeyBinding(id);
255
+ await setKeyBinding(id, { ...b, signKey: ref });
272
256
  }
273
257
  async function hideIdentityEmail(email) {
274
258
  const map = await readMap();
@@ -291,6 +275,7 @@ async function removeIdentity(id) {
291
275
  const map = await readMap();
292
276
  if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
293
277
  delete map.identities[id];
278
+ if (map.keyBindings?.[id]) delete map.keyBindings[id];
294
279
  if (map.defaultIdentity === id) delete map.defaultIdentity;
295
280
  await writeMap(map);
296
281
  }
@@ -304,18 +289,13 @@ async function listIdentities() {
304
289
  const map = await readMap();
305
290
  return { identities: Object.values(map.identities), defaultIdentity: map.defaultIdentity };
306
291
  }
307
- var GitError = class extends Error {
308
- cmd;
309
- exitCode;
310
- stderr;
311
- constructor(cmd, exitCode, stderr) {
312
- super(`git ${cmd} failed (exit ${exitCode})${stderr ? ": " + stderr.trim() : ""}`);
313
- this.name = "GitError";
314
- this.cmd = cmd;
315
- this.exitCode = exitCode;
316
- this.stderr = stderr;
292
+ var init_map = __esm({
293
+ "src/core/identity/map.ts"() {
294
+ init_errors();
295
+ init_paths();
296
+ init_io();
317
297
  }
318
- };
298
+ });
319
299
  function run(args, opts) {
320
300
  return new Promise((resolve4, reject) => {
321
301
  const child = child_process.spawn("git", args, {
@@ -368,8 +348,36 @@ async function runBin(cmd, args, opts = {}) {
368
348
  else child.stdin.end();
369
349
  });
370
350
  }
351
+ var GitError;
352
+ var init_exec = __esm({
353
+ "src/core/git/exec.ts"() {
354
+ GitError = class extends Error {
355
+ cmd;
356
+ exitCode;
357
+ stderr;
358
+ constructor(cmd, exitCode, stderr) {
359
+ super(`git ${cmd} failed (exit ${exitCode})${stderr ? ": " + stderr.trim() : ""}`);
360
+ this.name = "GitError";
361
+ this.cmd = cmd;
362
+ this.exitCode = exitCode;
363
+ this.stderr = stderr;
364
+ }
365
+ };
366
+ }
367
+ });
371
368
 
372
369
  // src/core/git/config.ts
370
+ var config_exports = {};
371
+ __export(config_exports, {
372
+ addConfigValue: () => addConfigValue,
373
+ getAllConfig: () => getAllConfig,
374
+ getConfig: () => getConfig,
375
+ getEffectiveConfig: () => getEffectiveConfig,
376
+ removeSection: () => removeSection,
377
+ setConfig: () => setConfig,
378
+ unsetAllConfig: () => unsetAllConfig,
379
+ unsetConfig: () => unsetConfig
380
+ });
373
381
  function scopeArgs(scope) {
374
382
  return scope ? [`--${scope}`] : [];
375
383
  }
@@ -404,6 +412,14 @@ async function unsetConfig(key, scope, cwd) {
404
412
  async function unsetAllConfig(key, scope, cwd) {
405
413
  await gitRaw(["config", ...scopeArgs(scope), "--unset-all", key], { cwd });
406
414
  }
415
+ async function removeSection(section, scope, cwd) {
416
+ await gitRaw(["config", ...scopeArgs(scope), "--remove-section", section], { cwd });
417
+ }
418
+ var init_config = __esm({
419
+ "src/core/git/config.ts"() {
420
+ init_exec();
421
+ }
422
+ });
407
423
  async function insideWorkTree(cwd) {
408
424
  const r = await gitRaw(["rev-parse", "--is-inside-work-tree"], { cwd });
409
425
  return r.exitCode === 0 && r.stdout.trim() === "true";
@@ -416,6 +432,11 @@ async function gitDir(cwd) {
416
432
  const r = await git(["rev-parse", "--git-dir"], { cwd });
417
433
  return path.resolve(cwd ?? process.cwd(), r.stdout.trim());
418
434
  }
435
+ var init_rev = __esm({
436
+ "src/core/git/rev.ts"() {
437
+ init_exec();
438
+ }
439
+ });
419
440
  function formatMessage(txt, authors) {
420
441
  const stripRe = new RegExp(`(\r
421
442
  |\r|
@@ -431,8 +452,21 @@ function printTrailers(authors) {
431
452
  if (authors.length === 0) return "";
432
453
  return os.EOL + os.EOL + authors.map((a) => a.format()).join(os.EOL);
433
454
  }
455
+ var init_formatter = __esm({
456
+ "src/core/message/formatter.ts"() {
457
+ init_types();
458
+ }
459
+ });
434
460
 
435
461
  // src/core/message/template.ts
462
+ var template_exports = {};
463
+ __export(template_exports, {
464
+ clearTemplate: () => clearTemplate,
465
+ ensureCommitTemplate: () => ensureCommitTemplate,
466
+ gitMessagePath: () => gitMessagePath,
467
+ resolveTemplatePath: () => resolveTemplatePath,
468
+ writeCoAuthorsToTemplate: () => writeCoAuthorsToTemplate
469
+ });
436
470
  function gitMessagePath() {
437
471
  return path.join(os.homedir(), ".gitmessage");
438
472
  }
@@ -475,302 +509,50 @@ async function writeCoAuthorsToTemplate(authors, cwd) {
475
509
  async function clearTemplate(cwd) {
476
510
  await applyToTemplate([], cwd);
477
511
  }
478
-
479
- // src/core/coauthors/state.ts
480
- var KEY = "colabor.selected";
481
- var LINE_RE = /^(.*)\s<([^>]+)>$/;
482
- async function getSelected(cwd) {
483
- const raw = (await getAllConfig(KEY, "local", cwd)).split(/\r?\n/).filter(Boolean);
484
- if (raw.length === 0) return [];
485
- const out = [];
486
- for (const line of raw) {
487
- const m = line.match(LINE_RE);
488
- if (!m) continue;
489
- out.push(new Author(m[2].split("@")[0] || "co", m[1].trim(), m[2].trim()));
512
+ var init_template = __esm({
513
+ "src/core/message/template.ts"() {
514
+ init_config();
515
+ init_rev();
516
+ init_formatter();
490
517
  }
491
- return out;
492
- }
493
- async function setSelected(authors, cwd) {
494
- await unsetAllConfig(KEY, "local", cwd);
495
- for (const a of authors) await addConfigValue(KEY, a.toString(), "local", cwd);
496
- await ensureCommitTemplate(cwd);
497
- await writeCoAuthorsToTemplate(authors, cwd);
498
- }
499
-
500
- // src/core/git/shortlog.ts
501
- var SHORTLOG_LINE = /^\s*\d+\t(.+)\s<(.+)>$/;
502
- async function repoAuthors(filter, cwd) {
503
- const args = ["shortlog", "-seni", "HEAD"];
504
- if (filter) args.splice(1, 0, `--author=${filter}`);
505
- const r = await gitRaw(args, { cwd });
506
- if (r.exitCode !== 0) return [];
507
- const out = [];
508
- for (const line of r.stdout.split(/\r?\n/)) {
509
- const m = line.match(SHORTLOG_LINE);
510
- if (!m) continue;
511
- const name = m[1].trim();
512
- const email = m[2].trim();
513
- out.push(new Author(genKey(name, email), name, email));
518
+ });
519
+ async function fingerprintOfFile(path) {
520
+ const r = await runBin("ssh-keygen", ["-lf", path]);
521
+ if (r.exitCode !== 0) {
522
+ throw new AppError({
523
+ code: "KEY_READ_FAILED",
524
+ message: `cannot read key fingerprint: ${r.stderr.trim() || "ssh-keygen failed"}`
525
+ });
514
526
  }
515
- return out;
516
- }
517
- async function requireRepo(cwd) {
518
- if (!await insideWorkTree(cwd)) throw Errors.notARepo(cwd);
519
- }
520
- async function identityAuthors() {
521
- const { identities } = await listIdentities();
522
- return identities.map((i) => ({
523
- id: i.id,
524
- author: new Author(genKey(i.name, i.email), i.name, i.email)
525
- }));
527
+ const m = r.stdout.match(FP_RE);
528
+ if (!m) throw new AppError({ code: "KEY_READ_FAILED", message: `unparseable ssh-keygen output: ${r.stdout}` });
529
+ return m[0];
526
530
  }
527
- async function resolveCoAuthor(arg) {
528
- const all = await identityAuthors();
529
- const lower = arg.toLowerCase();
530
- const found = all.find(({ id, author }) => author.email.toLowerCase() === lower || id === arg);
531
- if (!found) throw Errors.authorNotFound(arg);
532
- return found.author;
531
+ async function isEncrypted(path) {
532
+ const r = await runBin("ssh-keygen", ["-y", "-P", "", "-f", path]);
533
+ return r.exitCode !== 0;
533
534
  }
534
- var globalCoAuthorsPath = () => path.join(dataDir(), "global-coauthors.json");
535
- async function readGlobal() {
535
+ async function keyUsable(path) {
536
536
  try {
537
- const txt = await promises.readFile(globalCoAuthorsPath(), "utf8");
538
- const arr = JSON.parse(txt);
539
- return arr.map((a) => new Author(genKey(a.name, a.email), a.name, a.email));
537
+ await fingerprintOfFile(path);
538
+ return true;
540
539
  } catch {
541
- return [];
540
+ return false;
542
541
  }
543
542
  }
544
- async function writeGlobal(authors) {
545
- await promises.mkdir(dataDir(), { recursive: true });
546
- await promises.writeFile(globalCoAuthorsPath(), JSON.stringify(authors.map((a) => ({ name: a.name, email: a.email })), null, 2) + "\n", "utf8");
543
+ async function importKey(sourcePath) {
544
+ const fingerprint = await fingerprintOfFile(sourcePath);
545
+ const encrypted = await isEncrypted(sourcePath);
546
+ return { path: path.resolve(sourcePath), fingerprint, encrypted };
547
547
  }
548
- async function setOneshot(authors, cwd) {
549
- await unsetConfig("colabor.oneshot", "local", cwd);
550
- for (const a of authors) {
551
- await setConfig("colabor.oneshot", a.toString(), "local", cwd);
548
+ var FP_RE;
549
+ var init_keys = __esm({
550
+ "src/core/identity/keys.ts"() {
551
+ init_exec();
552
+ init_errors();
553
+ FP_RE = /SHA256:[A-Za-z0-9+/=]+/;
552
554
  }
553
- }
554
- async function getOneshot(cwd) {
555
- const raw = await getAllConfig("colabor.oneshot", "local", cwd);
556
- if (!raw) return [];
557
- return raw.split(/\r?\n/).filter(Boolean).map((line) => {
558
- const m = line.match(/^(.*)\s<(.+)>$/);
559
- return m ? new Author(genKey(m[1], m[2]), m[1], m[2]) : null;
560
- }).filter((a) => !!a);
561
- }
562
- async function add(args, opts, cwd) {
563
- const emailOrId = args[0];
564
- if (!emailOrId) throw Errors.usage("git colabor coauthor add <email|id> [--always] [--global]");
565
- const author = await resolveCoAuthor(emailOrId);
566
- if (opts.global) {
567
- const globals = await readGlobal();
568
- if (!globals.some((a) => a.email.toLowerCase() === author.email.toLowerCase())) {
569
- globals.push(author);
570
- await writeGlobal(globals);
571
- }
572
- return ok({ added: { name: author.name, email: author.email }, mode: "global" });
573
- }
574
- await requireRepo(cwd);
575
- if (opts.always) {
576
- const current = await getSelected(cwd);
577
- if (!current.some((a) => a.email.toLowerCase() === author.email.toLowerCase())) {
578
- current.push(author);
579
- await setSelected(current, cwd);
580
- }
581
- return ok({ added: { name: author.name, email: author.email }, mode: "always" });
582
- }
583
- const oneshot = await getOneshot(cwd);
584
- if (!oneshot.some((a) => a.email.toLowerCase() === author.email.toLowerCase())) {
585
- oneshot.push(author);
586
- await setOneshot(oneshot, cwd);
587
- }
588
- return ok({ added: { name: author.name, email: author.email }, mode: "oneshot" });
589
- }
590
- async function rm(args, cwd) {
591
- const emailOrId = args[0];
592
- if (!emailOrId) throw Errors.usage("git colabor coauthor rm <email|id>");
593
- const target = await resolveCoAuthor(emailOrId);
594
- const lower = target.email.toLowerCase();
595
- const removedFrom = [];
596
- const globals = await readGlobal();
597
- const newGlobals = globals.filter((a) => a.email.toLowerCase() !== lower);
598
- if (newGlobals.length !== globals.length) {
599
- await writeGlobal(newGlobals);
600
- removedFrom.push("global");
601
- }
602
- try {
603
- await requireRepo(cwd);
604
- const selected = await getSelected(cwd);
605
- const newSelected = selected.filter((a) => a.email.toLowerCase() !== lower);
606
- if (newSelected.length !== selected.length) {
607
- await setSelected(newSelected, cwd);
608
- removedFrom.push("repo");
609
- }
610
- const oneshot = await getOneshot(cwd);
611
- const newOneshot = oneshot.filter((a) => a.email.toLowerCase() !== lower);
612
- if (newOneshot.length !== oneshot.length) {
613
- await setOneshot(newOneshot, cwd);
614
- removedFrom.push("oneshot");
615
- }
616
- } catch {
617
- }
618
- return ok({ removed: { name: target.name, email: target.email }, from: removedFrom });
619
- }
620
- async function ls(args, cwd) {
621
- const filter = args[0]?.toLowerCase();
622
- const all = await identityAuthors();
623
- const available = (filter ? all.filter(({ author }) => author.name.toLowerCase().includes(filter) || author.email.toLowerCase().includes(filter)) : all).map(({ author }) => ({ name: author.name, email: author.email }));
624
- const selected = [];
625
- for (const a of await readGlobal()) {
626
- selected.push({ name: a.name, email: a.email, mode: "global" });
627
- }
628
- try {
629
- for (const a of await getSelected(cwd)) {
630
- if (!selected.some((s) => s.email === a.email)) {
631
- selected.push({ name: a.name, email: a.email, mode: "repo" });
632
- }
633
- }
634
- for (const a of await getOneshot(cwd)) {
635
- if (!selected.some((s) => s.email === a.email)) {
636
- selected.push({ name: a.name, email: a.email, mode: "oneshot" });
637
- }
638
- }
639
- } catch {
640
- }
641
- return ok({ available, selected });
642
- }
643
- async function print(_opts, cwd) {
644
- const active = [
645
- ...await readGlobal(),
646
- ...await getSelected(cwd).catch(() => []),
647
- ...await getOneshot(cwd).catch(() => [])
648
- ];
649
- const seen = /* @__PURE__ */ new Set();
650
- const deduped = active.filter((a) => {
651
- const k = a.email.toLowerCase();
652
- if (seen.has(k)) return false;
653
- seen.add(k);
654
- return true;
655
- });
656
- return ok({ text: printTrailers(deduped) });
657
- }
658
- async function suggest(args, cwd) {
659
- await requireRepo(cwd);
660
- const candidates = await repoAuthors(args[0], cwd);
661
- if (candidates.length === 0) {
662
- return ok({ candidates: [], added: [] }, [{ code: "none", message: "no contributors found" }]);
663
- }
664
- return ok({ candidates: candidates.map((a) => ({ key: a.key, name: a.name, email: a.email })), added: [] });
665
- }
666
-
667
- // src/core/git/committers.ts
668
- async function historyCommitters(cwd) {
669
- const r = await gitRaw(["log", "--format=%cn%x1f%ce"], { cwd });
670
- if (r.exitCode !== 0) return [];
671
- const counts = /* @__PURE__ */ new Map();
672
- for (const line of r.stdout.split("\n")) {
673
- const sep = line.indexOf("");
674
- if (sep < 0) continue;
675
- const name = line.slice(0, sep).trim();
676
- const email = line.slice(sep + 1).trim();
677
- if (!name || !email) continue;
678
- const key = email.toLowerCase();
679
- const cur = counts.get(key);
680
- if (cur) cur.count++;
681
- else counts.set(key, { name, email, count: 1 });
682
- }
683
- return [...counts.values()].sort((a, b) => b.count - a.count).map(({ name, email }) => ({ name, email }));
684
- }
685
- var FP_RE = /SHA256:[A-Za-z0-9+/=]+/;
686
- async function fingerprintOfFile(path) {
687
- const r = await runBin("ssh-keygen", ["-lf", path]);
688
- if (r.exitCode !== 0) {
689
- throw new AppError({
690
- code: "KEY_READ_FAILED",
691
- message: `cannot read key fingerprint: ${r.stderr.trim() || "ssh-keygen failed"}`
692
- });
693
- }
694
- const m = r.stdout.match(FP_RE);
695
- if (!m) throw new AppError({ code: "KEY_READ_FAILED", message: `unparseable ssh-keygen output: ${r.stdout}` });
696
- return m[0];
697
- }
698
- async function isEncrypted(path) {
699
- const r = await runBin("ssh-keygen", ["-y", "-P", "", "-f", path]);
700
- return r.exitCode !== 0;
701
- }
702
- async function keyUsable(path) {
703
- try {
704
- await fingerprintOfFile(path);
705
- return true;
706
- } catch {
707
- return false;
708
- }
709
- }
710
- async function importKey(sourcePath) {
711
- const fingerprint = await fingerprintOfFile(sourcePath);
712
- const encrypted = await isEncrypted(sourcePath);
713
- return { path: path.resolve(sourcePath), fingerprint, encrypted };
714
- }
715
- async function statePath(cwd) {
716
- return path.join(await gitDir(cwd), "colabor", "state.json");
717
- }
718
- async function readState(cwd) {
719
- try {
720
- const p = await statePath(cwd);
721
- const txt = await promises.readFile(p, "utf8");
722
- return JSON.parse(txt);
723
- } catch {
724
- return { schemaVersion: 1 };
725
- }
726
- }
727
- async function writeState(state, cwd) {
728
- const p = await statePath(cwd);
729
- await atomicWriteJson(p, state, 384);
730
- }
731
- async function readCurrentIdentityConfig(cwd) {
732
- const [userName, userEmail, sshCommand, commitTemplate, commitGpgsign, gpgFormat, signingKey] = await Promise.all([
733
- getConfig("user.name", "local", cwd),
734
- getConfig("user.email", "local", cwd),
735
- getConfig("core.sshCommand", "local", cwd),
736
- getConfig("commit.template", "local", cwd),
737
- getConfig("commit.gpgsign", "local", cwd),
738
- getConfig("gpg.format", "local", cwd),
739
- getConfig("user.signingKey", "local", cwd)
740
- ]);
741
- return { userName, userEmail, sshCommand, commitTemplate, commitGpgsign, gpgFormat, signingKey };
742
- }
743
- async function captureBackupIfFirstTouch(cwd) {
744
- const managed = await getConfig("colabor.managed", "local", cwd);
745
- const state = await readState(cwd);
746
- if (managed === "true" || state.backups) return state;
747
- state.backups = await readCurrentIdentityConfig(cwd);
748
- await writeState(state, cwd);
749
- return state;
750
- }
751
- function isStale(heldBy, staleMinutes) {
752
- const ageMs = Date.now() - new Date(heldBy.since).getTime();
753
- return ageMs > staleMinutes * 6e4;
754
- }
755
- async function detectConflict(session, cwd, staleMinutes = Infinity) {
756
- const st = await readState(cwd);
757
- const hb = st.heldBy;
758
- if (!hb || hb.session === session) return null;
759
- if (isStale(hb, staleMinutes)) return null;
760
- return { heldBy: hb };
761
- }
762
- function cliSessionId() {
763
- return `cli:${process.pid}@${os.hostname()}`;
764
- }
765
- function nowHeldBy(session, source) {
766
- return {
767
- session,
768
- since: (/* @__PURE__ */ new Date()).toISOString(),
769
- host: os.hostname(),
770
- osUser: os.userInfo().username,
771
- source
772
- };
773
- }
555
+ });
774
556
  async function appendAudit(input) {
775
557
  const entry = {
776
558
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -810,6 +592,11 @@ async function readAudit(opts = {}) {
810
592
  return [];
811
593
  }
812
594
  }
595
+ var init_audit = __esm({
596
+ "src/core/logging/audit.ts"() {
597
+ init_paths();
598
+ }
599
+ });
813
600
  function runInherit(cmdArgs, env, stdinNull = false) {
814
601
  return new Promise((resolve4) => {
815
602
  const [cmd, ...args] = cmdArgs;
@@ -941,9 +728,17 @@ async function verifyKey(opts) {
941
728
  );
942
729
  return verify === 0;
943
730
  }
731
+ var init_agent = __esm({
732
+ "src/core/identity/agent.ts"() {
733
+ }
734
+ });
944
735
 
945
736
  // src/core/identity/gpg.ts
946
- var UNUSABLE = /* @__PURE__ */ new Set(["i", "d", "r", "e", "n"]);
737
+ var gpg_exports = {};
738
+ __export(gpg_exports, {
739
+ listSigningKeys: () => listSigningKeys,
740
+ parseSecretKeys: () => parseSecretKeys
741
+ });
947
742
  function unescape(s) {
948
743
  return s.replace(/\\x([0-9a-fA-F]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
949
744
  }
@@ -1007,6 +802,15 @@ async function listSigningKeys(cwd, query) {
1007
802
  }
1008
803
  return r.exitCode === 0 ? parseSecretKeys(r.stdout) : [];
1009
804
  }
805
+ var UNUSABLE;
806
+ var init_gpg = __esm({
807
+ "src/core/identity/gpg.ts"() {
808
+ init_config();
809
+ init_exec();
810
+ init_errors();
811
+ UNUSABLE = /* @__PURE__ */ new Set(["i", "d", "r", "e", "n"]);
812
+ }
813
+ });
1010
814
  async function safeTopLevel(cwd) {
1011
815
  try {
1012
816
  return await topLevel(cwd);
@@ -1046,9 +850,12 @@ async function signingKeyPath(sshKeyPath, fingerprint) {
1046
850
  return sshKeyPath;
1047
851
  }
1048
852
  async function signingConfigFor(identity) {
1049
- if (identity.gpgKey) return { format: "openpgp", key: identity.gpgKey };
1050
- if (identity.sshKeyPath && await keyUsable(identity.sshKeyPath)) {
1051
- return { format: "ssh", key: await signingKeyPath(identity.sshKeyPath, identity.sshKeyFingerprint) };
853
+ const binding = await getKeyBinding(identity.id);
854
+ if (binding.signKey) {
855
+ return binding.signKey.format === "openpgp" ? { format: "openpgp", key: binding.signKey.key } : { format: "ssh", key: await signingKeyPath(binding.signKey.path, binding.signKey.fingerprint) };
856
+ }
857
+ if (binding.pushKey && await keyUsable(binding.pushKey.path)) {
858
+ return { format: "ssh", key: await signingKeyPath(binding.pushKey.path, binding.pushKey.fingerprint) };
1052
859
  }
1053
860
  return void 0;
1054
861
  }
@@ -1065,12 +872,10 @@ async function writeIdentitySigning(identity, cwd, askpassScriptPath) {
1065
872
  }
1066
873
  return cfg;
1067
874
  }
1068
- async function disableSigning(cwd, managed = true) {
1069
- if (managed) {
1070
- await unsetConfig("gpg.format", "local", cwd);
1071
- await unsetConfig("user.signingKey", "local", cwd);
1072
- await unsetConfig("gpg.ssh.program", "local", cwd);
1073
- }
875
+ async function disableSigning(cwd, _managed = true) {
876
+ await unsetConfig("gpg.format", "local", cwd);
877
+ await unsetConfig("user.signingKey", "local", cwd);
878
+ await unsetConfig("gpg.ssh.program", "local", cwd);
1074
879
  await unsetConfig("commit.gpgsign", "local", cwd);
1075
880
  if ((await getEffectiveConfig("commit.gpgsign", cwd, "bool"))?.value === "true") {
1076
881
  await setConfig("commit.gpgsign", "false", "local", cwd);
@@ -1078,11 +883,8 @@ async function disableSigning(cwd, managed = true) {
1078
883
  }
1079
884
  async function setCommitSigning(opts) {
1080
885
  if (!await insideWorkTree(opts.cwd)) throw Errors.notARepo(opts.cwd);
1081
- const state = await readState(opts.cwd);
1082
886
  if (!opts.on) {
1083
- await disableSigning(opts.cwd, state.signing === true);
1084
- state.signing = false;
1085
- await writeState(state, opts.cwd);
887
+ await disableSigning(opts.cwd, false);
1086
888
  await appendAudit({ action: "identity.sign", source: opts.source, identity: opts.id, repo: await safeTopLevel(opts.cwd), result: "ok", message: "signing off" });
1087
889
  return { signing: false };
1088
890
  }
@@ -1090,21 +892,19 @@ async function setCommitSigning(opts) {
1090
892
  const identity = await getIdentity(opts.id);
1091
893
  const cfg = await writeIdentitySigning(identity, opts.cwd, opts.askpassScriptPath);
1092
894
  if (!cfg) throw Errors.usage(`identity "${identity.name}" has no usable SSH or GPG key to sign with`);
1093
- state.signing = true;
1094
- await writeState(state, opts.cwd);
1095
895
  await appendAudit({
1096
896
  action: "identity.sign",
1097
897
  source: opts.source,
1098
898
  identity: opts.id,
1099
899
  identityName: identity.name,
1100
- fingerprint: cfg.format === "ssh" ? identity.sshKeyFingerprint : cfg.key,
900
+ fingerprint: cfg.key,
1101
901
  repo: await safeTopLevel(opts.cwd),
1102
902
  result: "ok",
1103
903
  message: `signing on (${cfg.format})`
1104
904
  });
1105
905
  return { signing: true, format: cfg.format, key: cfg.key };
1106
906
  }
1107
- async function signingStatus(cwd, managed) {
907
+ async function signingStatus(cwd) {
1108
908
  const [sign2, format, key] = await Promise.all([
1109
909
  getEffectiveConfig("commit.gpgsign", cwd, "bool"),
1110
910
  getEffectiveConfig("gpg.format", cwd),
@@ -1116,198 +916,655 @@ async function signingStatus(cwd, managed) {
1116
916
  format: format?.value || "openpgp",
1117
917
  scope: sign2?.scope ?? null,
1118
918
  origin: sign2?.origin ?? null,
1119
- managed
919
+ managed: sign2?.scope === "local"
1120
920
  };
1121
921
  if (status2.enabled && status2.format === "openpgp" && status2.key) {
1122
922
  const emails = (await listSigningKeys(cwd, status2.key).catch(() => [])).flatMap((k) => k.emails);
1123
923
  if (emails.length > 0) status2.keyEmails = emails;
1124
924
  }
1125
- return status2;
1126
- }
1127
- function discoverSessionBridges() {
925
+ return status2;
926
+ }
927
+ var init_sign = __esm({
928
+ "src/core/identity/sign.ts"() {
929
+ init_config();
930
+ init_rev();
931
+ init_map();
932
+ init_keys();
933
+ init_agent();
934
+ init_audit();
935
+ init_errors();
936
+ init_paths();
937
+ init_apply();
938
+ init_gpg();
939
+ }
940
+ });
941
+ function discoverSessionBridges() {
942
+ try {
943
+ const dir = dataDir();
944
+ const sessions = fs.readdirSync(dir).filter((f) => /^session-.*\.json$/.test(f)).map((f) => ({ f, mtime: fs.statSync(path.join(dir, f)).mtimeMs })).sort((a, b) => b.mtime - a.mtime);
945
+ const out = [];
946
+ for (const s of sessions) {
947
+ try {
948
+ const parsed = JSON.parse(fs.readFileSync(path.join(dir, s.f), "utf8"));
949
+ if (parsed.socketPath && parsed.token) out.push({ socketPath: parsed.socketPath, token: parsed.token });
950
+ } catch {
951
+ }
952
+ }
953
+ return out;
954
+ } catch {
955
+ return [];
956
+ }
957
+ }
958
+ function discoverSessionBridge() {
959
+ return discoverSessionBridges()[0];
960
+ }
961
+ var init_session_bridge = __esm({
962
+ "src/core/secrets/session-bridge.ts"() {
963
+ init_paths();
964
+ }
965
+ });
966
+
967
+ // src/core/identity/apply.ts
968
+ var apply_exports = {};
969
+ __export(apply_exports, {
970
+ applyIdentity: () => applyIdentity,
971
+ applyResolvedIdentity: () => applyResolvedIdentity,
972
+ ensureAskpassWrapper: () => ensureAskpassWrapper
973
+ });
974
+ async function safeTopLevel2(cwd) {
975
+ try {
976
+ return await topLevel(cwd);
977
+ } catch {
978
+ return void 0;
979
+ }
980
+ }
981
+ async function applyResolvedIdentity(args) {
982
+ const { name, email, sshCommand, identity, opts } = args;
983
+ await setConfig("user.name", name, "local", opts.cwd);
984
+ await setConfig("user.email", email, "local", opts.cwd);
985
+ if (sshCommand) {
986
+ await setConfig("core.sshCommand", sshCommand, "local", opts.cwd);
987
+ } else if (identity) {
988
+ await unsetConfig("core.sshCommand", "local", opts.cwd);
989
+ const gpgsign = await getConfig("commit.gpgsign", "local", opts.cwd);
990
+ if (gpgsign === "true") await disableSigning(opts.cwd);
991
+ }
992
+ const binding = identity ? await getKeyBinding(identity.id) : void 0;
993
+ let agent;
994
+ if (binding?.pushKey) {
995
+ agent = { inAgent: await keyInAgent(binding.pushKey.fingerprint) };
996
+ }
997
+ await appendAudit({
998
+ action: "identity.use",
999
+ source: opts.source,
1000
+ identity: identity?.id,
1001
+ identityName: identity?.name ?? name,
1002
+ fingerprint: binding?.pushKey?.fingerprint,
1003
+ repo: await safeTopLevel2(opts.cwd)
1004
+ });
1005
+ return { name, email, sshCommand, keyApplied: !!sshCommand, agent };
1006
+ }
1007
+ async function ensureAskpassWrapper(askpassScriptPath) {
1008
+ const wrapperPath = path.join(dataDir(), "askpass-wrapper.sh");
1009
+ const content = `#!/bin/sh
1010
+ exec "${process.execPath}" "${askpassScriptPath}" "$@"
1011
+ `;
1012
+ try {
1013
+ const existing = await promises.readFile(wrapperPath, "utf8");
1014
+ if (existing === content) return wrapperPath;
1015
+ } catch {
1016
+ }
1017
+ await promises.writeFile(wrapperPath, content, { mode: 448 });
1018
+ await promises.chmod(wrapperPath, 448);
1019
+ return wrapperPath;
1020
+ }
1021
+ async function applyIdentity(id, opts) {
1022
+ const identity = await getIdentity(id);
1023
+ const binding = await getKeyBinding(id);
1024
+ const push = binding.pushKey;
1025
+ let sshCommand;
1026
+ let keyMissing = false;
1027
+ const keyDegraded = false;
1028
+ if (push) {
1029
+ if (await keyUsable(push.path)) {
1030
+ const fp = await fingerprintOfFile(push.path).catch(() => void 0);
1031
+ if (fp && fp !== push.fingerprint) {
1032
+ await setPushKey(id, { ...push, fingerprint: fp });
1033
+ push.fingerprint = fp;
1034
+ }
1035
+ const bare2 = `ssh -i ${push.path} -o IdentitiesOnly=yes`;
1036
+ const bridge = opts.socketPath && opts.token || discoverSessionBridge();
1037
+ if (opts.askpassScriptPath && bridge) {
1038
+ const wrapper = await ensureAskpassWrapper(opts.askpassScriptPath);
1039
+ sshCommand = `SSH_ASKPASS="${wrapper}" SSH_ASKPASS_REQUIRE=force DISPLAY=:0 ${bare2}`;
1040
+ } else {
1041
+ sshCommand = bare2;
1042
+ }
1043
+ } else {
1044
+ keyMissing = true;
1045
+ }
1046
+ }
1047
+ const result = await applyResolvedIdentity({
1048
+ name: opts.asName ?? identity.name,
1049
+ email: opts.asEmail ?? identity.email,
1050
+ sshCommand,
1051
+ identity,
1052
+ opts
1053
+ });
1054
+ result.keyMissing = keyMissing;
1055
+ result.keyDegraded = keyDegraded;
1056
+ if (identity) {
1057
+ const gpgsign = await getConfig("commit.gpgsign", "local", opts.cwd);
1058
+ if (gpgsign === "true") {
1059
+ const okSign = await writeIdentitySigning(identity, opts.cwd, opts.askpassScriptPath);
1060
+ if (!okSign) await disableSigning(opts.cwd);
1061
+ }
1062
+ }
1063
+ return { identity, result };
1064
+ }
1065
+ var init_apply = __esm({
1066
+ "src/core/identity/apply.ts"() {
1067
+ init_config();
1068
+ init_paths();
1069
+ init_rev();
1070
+ init_audit();
1071
+ init_agent();
1072
+ init_map();
1073
+ init_keys();
1074
+ init_sign();
1075
+ init_session_bridge();
1076
+ init_config();
1077
+ }
1078
+ });
1079
+
1080
+ // src/core/identity/configClear.ts
1081
+ var configClear_exports = {};
1082
+ __export(configClear_exports, {
1083
+ clearIdentityConfigLayer: () => clearIdentityConfigLayer
1084
+ });
1085
+ function signingKeyOwned(configured, keys) {
1086
+ const value = configured.trim();
1087
+ if (!value) return false;
1088
+ if (keys.sshPaths.some((p) => bare(p) === bare(value))) return true;
1089
+ if (keys.gpgFingerprint) {
1090
+ const hex = (k) => /^(0x)?[0-9a-f]{8,}!?$/i.test(k) ? k.replace(/^0x/i, "").replace(/!$/, "").toUpperCase() : void 0;
1091
+ const a = hex(value);
1092
+ const b = hex(keys.gpgFingerprint);
1093
+ if (a && b && (a.endsWith(b) || b.endsWith(a))) return true;
1094
+ }
1095
+ return false;
1096
+ }
1097
+ async function clearIdentityConfigLayer(identity, opts = {}) {
1098
+ const forceKeys = opts.forceKeys === true;
1099
+ const sshPaths = [
1100
+ ...identity.pushKeyPath ? [identity.pushKeyPath] : [],
1101
+ ...identity.signKey?.format === "ssh" ? [identity.signKey.path] : []
1102
+ ];
1103
+ const gpgFingerprint = identity.signKey?.format === "openpgp" ? identity.signKey.key : void 0;
1104
+ const [n, e, ssh, signKey, sshProgram] = await Promise.all([
1105
+ getConfig("user.name", "local", opts.cwd),
1106
+ getConfig("user.email", "local", opts.cwd),
1107
+ getConfig("core.sshCommand", "local", opts.cwd),
1108
+ getConfig("user.signingKey", "local", opts.cwd),
1109
+ getConfig("gpg.ssh.program", "local", opts.cwd)
1110
+ ]);
1111
+ const eq = (a, b) => !!a && a.trim() === b.trim();
1112
+ const result = { identityLayer: false, sshCommand: false, signing: false };
1113
+ if (eq(n, identity.name)) {
1114
+ await unsetConfig("user.name", "local", opts.cwd);
1115
+ result.identityLayer = true;
1116
+ }
1117
+ if (eq(e, identity.email)) {
1118
+ await unsetConfig("user.email", "local", opts.cwd);
1119
+ result.identityLayer = true;
1120
+ }
1121
+ if (ssh && (forceKeys || sshPaths.some((p) => sshCommandUses(ssh, p)))) {
1122
+ await unsetConfig("core.sshCommand", "local", opts.cwd);
1123
+ result.sshCommand = true;
1124
+ }
1125
+ const wrapperIsOurs = !!sshProgram && sshProgram.includes("git-colabor");
1126
+ if (signKey && (forceKeys || signingKeyOwned(signKey, { sshPaths, gpgFingerprint }))) {
1127
+ await unsetConfig("user.signingKey", "local", opts.cwd);
1128
+ result.signing = true;
1129
+ }
1130
+ if (result.signing || wrapperIsOurs || forceKeys) {
1131
+ await unsetConfig("gpg.format", "local", opts.cwd);
1132
+ await unsetConfig("gpg.ssh.program", "local", opts.cwd);
1133
+ await unsetConfig("commit.gpgsign", "local", opts.cwd);
1134
+ }
1135
+ return result;
1136
+ }
1137
+ var bare, sshCommandUses;
1138
+ var init_configClear = __esm({
1139
+ "src/core/identity/configClear.ts"() {
1140
+ init_config();
1141
+ bare = (p) => p.trim().replace(/\.pub$/, "");
1142
+ sshCommandUses = (command, keyPath) => command.includes(bare(keyPath));
1143
+ }
1144
+ });
1145
+
1146
+ // src/cli/index.ts
1147
+ init_errors();
1148
+
1149
+ // src/cli/json.ts
1150
+ init_errors();
1151
+ function ok(data, warnings) {
1152
+ return warnings && warnings.length > 0 ? { ok: true, data, warnings } : { ok: true, data };
1153
+ }
1154
+ function failFromError(e) {
1155
+ return { ok: false, error: toErrorPayload(e), data: null };
1156
+ }
1157
+ function emit(result, opts) {
1158
+ if (opts.json) {
1159
+ process.stdout.write(JSON.stringify(result) + "\n");
1160
+ } else if (opts.human) {
1161
+ const txt = opts.human(result);
1162
+ if (txt) {
1163
+ const stream = result.ok ? process.stdout : process.stderr;
1164
+ stream.write(txt.endsWith("\n") ? txt : `${txt}
1165
+ `);
1166
+ }
1167
+ }
1168
+ process.exit(result.ok ? 0 : result.error.exitCode);
1169
+ }
1170
+
1171
+ // src/cli/parse-args.ts
1172
+ function parseGlobals(argv) {
1173
+ const flags = { json: false, noColor: false, help: false, version: false };
1174
+ const rest = [];
1175
+ for (let i = 0; i < argv.length; i++) {
1176
+ const tok = argv[i];
1177
+ if (!tok) continue;
1178
+ if (tok === "--") {
1179
+ rest.push(...argv.slice(i + 1));
1180
+ break;
1181
+ }
1182
+ if (tok === "-C") {
1183
+ flags.cwd = argv[++i];
1184
+ continue;
1185
+ }
1186
+ if (tok.startsWith("-C") && tok.length > 2) {
1187
+ flags.cwd = tok.slice(2);
1188
+ continue;
1189
+ }
1190
+ if (tok === "--log-level") {
1191
+ flags.logLevel = argv[++i];
1192
+ continue;
1193
+ }
1194
+ if (tok.startsWith("--log-level=")) {
1195
+ flags.logLevel = tok.slice("--log-level=".length);
1196
+ continue;
1197
+ }
1198
+ if (tok === "--json") {
1199
+ flags.json = true;
1200
+ continue;
1201
+ }
1202
+ if (tok === "--no-color") {
1203
+ flags.noColor = true;
1204
+ continue;
1205
+ }
1206
+ if (tok === "-h" || tok === "--help") {
1207
+ flags.help = true;
1208
+ continue;
1209
+ }
1210
+ if (tok === "-v" || tok === "--version") {
1211
+ flags.version = true;
1212
+ continue;
1213
+ }
1214
+ rest.push(tok);
1215
+ }
1216
+ return { flags, rest };
1217
+ }
1218
+ function parseCommandArgs(tokens, spec = {}) {
1219
+ const positionals = [];
1220
+ const values = {};
1221
+ const bools = /* @__PURE__ */ new Set();
1222
+ const valueFlags = new Set(spec.valueFlags ?? []);
1223
+ const boolFlags = new Set(spec.boolFlags ?? []);
1224
+ for (let i = 0; i < tokens.length; i++) {
1225
+ const tok = tokens[i];
1226
+ if (!tok) continue;
1227
+ if (tok === "--") {
1228
+ positionals.push(...tokens.slice(i + 1));
1229
+ break;
1230
+ }
1231
+ if (tok.startsWith("--") && tok.includes("=")) {
1232
+ const eq = tok.indexOf("=");
1233
+ const k = tok.slice(0, eq);
1234
+ const v = tok.slice(eq + 1);
1235
+ if (valueFlags.has(k)) values[k] = v;
1236
+ else bools.add(k);
1237
+ continue;
1238
+ }
1239
+ if (valueFlags.has(tok)) {
1240
+ const v = tokens[++i];
1241
+ if (v !== void 0) values[tok] = v;
1242
+ continue;
1243
+ }
1244
+ if (boolFlags.has(tok)) {
1245
+ bools.add(tok);
1246
+ continue;
1247
+ }
1248
+ if (tok.startsWith("-")) {
1249
+ bools.add(tok);
1250
+ continue;
1251
+ }
1252
+ positionals.push(tok);
1253
+ }
1254
+ return { positionals, values, bools };
1255
+ }
1256
+
1257
+ // src/cli/coauthor.ts
1258
+ init_types();
1259
+ init_map();
1260
+
1261
+ // src/core/coauthors/state.ts
1262
+ init_config();
1263
+ init_types();
1264
+ init_template();
1265
+ var KEY = "colabor.selected";
1266
+ var LINE_RE = /^(.*)\s<([^>]+)>$/;
1267
+ async function getSelected(cwd) {
1268
+ const raw = (await getAllConfig(KEY, "local", cwd)).split(/\r?\n/).filter(Boolean);
1269
+ if (raw.length === 0) return [];
1270
+ const out = [];
1271
+ for (const line of raw) {
1272
+ const m = line.match(LINE_RE);
1273
+ if (!m) continue;
1274
+ out.push(new Author(m[2].split("@")[0] || "co", m[1].trim(), m[2].trim()));
1275
+ }
1276
+ return out;
1277
+ }
1278
+ async function setSelected(authors, cwd) {
1279
+ await unsetAllConfig(KEY, "local", cwd);
1280
+ for (const a of authors) await addConfigValue(KEY, a.toString(), "local", cwd);
1281
+ await ensureCommitTemplate(cwd);
1282
+ await writeCoAuthorsToTemplate(authors, cwd);
1283
+ }
1284
+
1285
+ // src/cli/coauthor.ts
1286
+ init_formatter();
1287
+
1288
+ // src/core/git/shortlog.ts
1289
+ init_exec();
1290
+ init_types();
1291
+ var SHORTLOG_LINE = /^\s*\d+\t(.+)\s<(.+)>$/;
1292
+ async function repoAuthors(filter, cwd) {
1293
+ const args = ["shortlog", "-seni", "HEAD"];
1294
+ if (filter) args.splice(1, 0, `--author=${filter}`);
1295
+ const r = await gitRaw(args, { cwd });
1296
+ if (r.exitCode !== 0) return [];
1297
+ const out = [];
1298
+ for (const line of r.stdout.split(/\r?\n/)) {
1299
+ const m = line.match(SHORTLOG_LINE);
1300
+ if (!m) continue;
1301
+ const name = m[1].trim();
1302
+ const email = m[2].trim();
1303
+ out.push(new Author(genKey(name, email), name, email));
1304
+ }
1305
+ return out;
1306
+ }
1307
+
1308
+ // src/cli/coauthor.ts
1309
+ init_rev();
1310
+ init_config();
1311
+ init_paths();
1312
+ init_errors();
1313
+ async function requireRepo(cwd) {
1314
+ if (!await insideWorkTree(cwd)) throw Errors.notARepo(cwd);
1315
+ }
1316
+ async function identityAuthors() {
1317
+ const { identities } = await listIdentities();
1318
+ return identities.map((i) => ({
1319
+ id: i.id,
1320
+ author: new Author(genKey(i.name, i.email), i.name, i.email)
1321
+ }));
1322
+ }
1323
+ async function resolveCoAuthor(arg) {
1324
+ const all = await identityAuthors();
1325
+ const lower = arg.toLowerCase();
1326
+ const found = all.find(({ id, author }) => author.email.toLowerCase() === lower || id === arg);
1327
+ if (!found) throw Errors.authorNotFound(arg);
1328
+ return found.author;
1329
+ }
1330
+ var globalCoAuthorsPath = () => path.join(dataDir(), "global-coauthors.json");
1331
+ async function readGlobal() {
1332
+ try {
1333
+ const txt = await promises.readFile(globalCoAuthorsPath(), "utf8");
1334
+ const arr = JSON.parse(txt);
1335
+ return arr.map((a) => new Author(genKey(a.name, a.email), a.name, a.email));
1336
+ } catch {
1337
+ return [];
1338
+ }
1339
+ }
1340
+ async function writeGlobal(authors) {
1341
+ await promises.mkdir(dataDir(), { recursive: true });
1342
+ await promises.writeFile(globalCoAuthorsPath(), JSON.stringify(authors.map((a) => ({ name: a.name, email: a.email })), null, 2) + "\n", "utf8");
1343
+ }
1344
+ async function setOneshot(authors, cwd) {
1345
+ await unsetConfig("colabor.oneshot", "local", cwd);
1346
+ for (const a of authors) {
1347
+ await setConfig("colabor.oneshot", a.toString(), "local", cwd);
1348
+ }
1349
+ }
1350
+ async function getOneshot(cwd) {
1351
+ const raw = await getAllConfig("colabor.oneshot", "local", cwd);
1352
+ if (!raw) return [];
1353
+ return raw.split(/\r?\n/).filter(Boolean).map((line) => {
1354
+ const m = line.match(/^(.*)\s<(.+)>$/);
1355
+ return m ? new Author(genKey(m[1], m[2]), m[1], m[2]) : null;
1356
+ }).filter((a) => !!a);
1357
+ }
1358
+ async function add(args, opts, cwd) {
1359
+ const emailOrId = args[0];
1360
+ if (!emailOrId) throw Errors.usage("git colabor coauthor add <email|id> [--always] [--global]");
1361
+ const author = await resolveCoAuthor(emailOrId);
1362
+ if (opts.global) {
1363
+ const globals = await readGlobal();
1364
+ if (!globals.some((a) => a.email.toLowerCase() === author.email.toLowerCase())) {
1365
+ globals.push(author);
1366
+ await writeGlobal(globals);
1367
+ }
1368
+ return ok({ added: { name: author.name, email: author.email }, mode: "global" });
1369
+ }
1370
+ await requireRepo(cwd);
1371
+ if (opts.always) {
1372
+ const current = await getSelected(cwd);
1373
+ if (!current.some((a) => a.email.toLowerCase() === author.email.toLowerCase())) {
1374
+ current.push(author);
1375
+ await setSelected(current, cwd);
1376
+ }
1377
+ return ok({ added: { name: author.name, email: author.email }, mode: "always" });
1378
+ }
1379
+ const oneshot = await getOneshot(cwd);
1380
+ if (!oneshot.some((a) => a.email.toLowerCase() === author.email.toLowerCase())) {
1381
+ oneshot.push(author);
1382
+ await setOneshot(oneshot, cwd);
1383
+ }
1384
+ return ok({ added: { name: author.name, email: author.email }, mode: "oneshot" });
1385
+ }
1386
+ async function rm(args, cwd) {
1387
+ const emailOrId = args[0];
1388
+ if (!emailOrId) throw Errors.usage("git colabor coauthor rm <email|id>");
1389
+ const target = await resolveCoAuthor(emailOrId);
1390
+ const lower = target.email.toLowerCase();
1391
+ const removedFrom = [];
1392
+ const globals = await readGlobal();
1393
+ const newGlobals = globals.filter((a) => a.email.toLowerCase() !== lower);
1394
+ if (newGlobals.length !== globals.length) {
1395
+ await writeGlobal(newGlobals);
1396
+ removedFrom.push("global");
1397
+ }
1128
1398
  try {
1129
- const dir = dataDir();
1130
- const sessions = fs.readdirSync(dir).filter((f) => /^session-.*\.json$/.test(f)).map((f) => ({ f, mtime: fs.statSync(path.join(dir, f)).mtimeMs })).sort((a, b) => b.mtime - a.mtime);
1131
- const out = [];
1132
- for (const s of sessions) {
1133
- try {
1134
- const parsed = JSON.parse(fs.readFileSync(path.join(dir, s.f), "utf8"));
1135
- if (parsed.socketPath && parsed.token) out.push({ socketPath: parsed.socketPath, token: parsed.token });
1136
- } catch {
1137
- }
1399
+ await requireRepo(cwd);
1400
+ const selected = await getSelected(cwd);
1401
+ const newSelected = selected.filter((a) => a.email.toLowerCase() !== lower);
1402
+ if (newSelected.length !== selected.length) {
1403
+ await setSelected(newSelected, cwd);
1404
+ removedFrom.push("repo");
1405
+ }
1406
+ const oneshot = await getOneshot(cwd);
1407
+ const newOneshot = oneshot.filter((a) => a.email.toLowerCase() !== lower);
1408
+ if (newOneshot.length !== oneshot.length) {
1409
+ await setOneshot(newOneshot, cwd);
1410
+ removedFrom.push("oneshot");
1138
1411
  }
1139
- return out;
1140
1412
  } catch {
1141
- return [];
1142
1413
  }
1414
+ return ok({ removed: { name: target.name, email: target.email }, from: removedFrom });
1143
1415
  }
1144
- function discoverSessionBridge() {
1145
- return discoverSessionBridges()[0];
1146
- }
1147
-
1148
- // src/core/identity/apply.ts
1149
- async function safeTopLevel2(cwd) {
1416
+ async function ls(args, cwd) {
1417
+ const filter = args[0]?.toLowerCase();
1418
+ const all = await identityAuthors();
1419
+ const available = (filter ? all.filter(({ author }) => author.name.toLowerCase().includes(filter) || author.email.toLowerCase().includes(filter)) : all).map(({ author }) => ({ name: author.name, email: author.email }));
1420
+ const selected = [];
1421
+ for (const a of await readGlobal()) {
1422
+ selected.push({ name: a.name, email: a.email, mode: "global" });
1423
+ }
1150
1424
  try {
1151
- return await topLevel(cwd);
1425
+ for (const a of await getSelected(cwd)) {
1426
+ if (!selected.some((s) => s.email === a.email)) {
1427
+ selected.push({ name: a.name, email: a.email, mode: "repo" });
1428
+ }
1429
+ }
1430
+ for (const a of await getOneshot(cwd)) {
1431
+ if (!selected.some((s) => s.email === a.email)) {
1432
+ selected.push({ name: a.name, email: a.email, mode: "oneshot" });
1433
+ }
1434
+ }
1152
1435
  } catch {
1153
- return void 0;
1154
1436
  }
1437
+ return ok({ available, selected });
1155
1438
  }
1156
- async function applyResolvedIdentity(args) {
1157
- const { name, email, sshCommand, identity, opts } = args;
1158
- const session = opts.session ?? (opts.source === "cli" ? cliSessionId() : "ext:unknown");
1159
- const conflict = await detectConflict(session, opts.cwd, opts.staleMinutes);
1160
- if (conflict && opts.noOverride) {
1161
- throw new AppError({
1162
- code: "CONFLICT_BLOCKED",
1163
- message: `repo is held by ${conflict.heldBy.session} (since ${conflict.heldBy.since})`,
1164
- exitCode: 6,
1165
- hints: ["re-run without --no-override to take over"]
1166
- });
1167
- }
1168
- await captureBackupIfFirstTouch(opts.cwd);
1169
- await setConfig("user.name", name, "local", opts.cwd);
1170
- await setConfig("user.email", email, "local", opts.cwd);
1171
- if (sshCommand) {
1172
- await setConfig("core.sshCommand", sshCommand, "local", opts.cwd);
1173
- } else if (identity && !identity.sshKeyPath) {
1174
- await unsetConfig("core.sshCommand", "local", opts.cwd);
1175
- }
1176
- await setConfig("colabor.managed", "true", "local", opts.cwd);
1177
- await setConfig("colabor.managed-by", opts.source, "local", opts.cwd);
1178
- const state = await readState(opts.cwd);
1179
- state.activeIdentity = identity?.id;
1180
- state.heldBy = nowHeldBy(session, opts.source);
1181
- if (state.signing === true && identity && !await writeIdentitySigning(identity, opts.cwd, opts.askpassScriptPath)) {
1182
- state.signing = false;
1183
- await disableSigning(opts.cwd);
1184
- }
1185
- await writeState(state, opts.cwd);
1186
- let agent;
1187
- if (identity?.sshKeyFingerprint) {
1188
- agent = { inAgent: await keyInAgent(identity.sshKeyFingerprint) };
1189
- }
1190
- await appendAudit({
1191
- action: "identity.use",
1192
- source: opts.source,
1193
- identity: identity?.id,
1194
- identityName: identity?.name ?? name,
1195
- fingerprint: identity?.sshKeyFingerprint,
1196
- repo: await safeTopLevel2(opts.cwd),
1197
- result: conflict ? "warn" : "ok",
1198
- message: conflict ? `overrode ${conflict.heldBy.session}` : void 0
1439
+ async function print(_opts, cwd) {
1440
+ const active = [
1441
+ ...await readGlobal(),
1442
+ ...await getSelected(cwd).catch(() => []),
1443
+ ...await getOneshot(cwd).catch(() => [])
1444
+ ];
1445
+ const seen = /* @__PURE__ */ new Set();
1446
+ const deduped = active.filter((a) => {
1447
+ const k = a.email.toLowerCase();
1448
+ if (seen.has(k)) return false;
1449
+ seen.add(k);
1450
+ return true;
1199
1451
  });
1200
- return { name, email, sshCommand, conflict, agent };
1452
+ return ok({ text: printTrailers(deduped) });
1201
1453
  }
1202
- async function ensureAskpassWrapper(askpassScriptPath) {
1203
- const wrapperPath = path.join(dataDir(), "askpass-wrapper.sh");
1204
- const content = `#!/bin/sh
1205
- exec "${process.execPath}" "${askpassScriptPath}" "$@"
1206
- `;
1207
- try {
1208
- const existing = await promises.readFile(wrapperPath, "utf8");
1209
- if (existing === content) return wrapperPath;
1210
- } catch {
1454
+ async function suggest(args, cwd) {
1455
+ await requireRepo(cwd);
1456
+ const candidates = await repoAuthors(args[0], cwd);
1457
+ if (candidates.length === 0) {
1458
+ return ok({ candidates: [], added: [] }, [{ code: "none", message: "no contributors found" }]);
1211
1459
  }
1212
- await promises.writeFile(wrapperPath, content, { mode: 448 });
1213
- await promises.chmod(wrapperPath, 448);
1214
- return wrapperPath;
1460
+ return ok({ candidates: candidates.map((a) => ({ key: a.key, name: a.name, email: a.email })), added: [] });
1215
1461
  }
1216
- async function applyIdentity(id, opts) {
1217
- let identity = await getIdentity(id);
1218
- let sshCommand;
1219
- let bridgeUsed = false;
1220
- let keyMissing = false;
1221
- if (identity.sshKeyPath) {
1222
- let imp;
1223
- try {
1224
- imp = await importKey(identity.sshKeyPath);
1225
- } catch {
1226
- imp = void 0;
1227
- }
1228
- if (imp) {
1229
- if (imp.fingerprint !== identity.sshKeyFingerprint || imp.encrypted !== !!identity.sshKeyEncrypted) {
1230
- await updateIdentity(id, { sshKeyFingerprint: imp.fingerprint, sshKeyEncrypted: imp.encrypted });
1231
- identity = { ...identity, sshKeyFingerprint: imp.fingerprint, sshKeyEncrypted: imp.encrypted };
1232
- }
1233
- const bare = `ssh -i ${identity.sshKeyPath} -o IdentitiesOnly=yes`;
1234
- const bridge = opts.socketPath && opts.token || discoverSessionBridge();
1235
- if (opts.askpassScriptPath && bridge) {
1236
- const wrapper = await ensureAskpassWrapper(opts.askpassScriptPath);
1237
- sshCommand = `SSH_ASKPASS="${wrapper}" SSH_ASKPASS_REQUIRE=force DISPLAY=:0 ${bare}`;
1238
- bridgeUsed = true;
1239
- } else {
1240
- sshCommand = bare;
1241
- }
1242
- } else {
1243
- keyMissing = true;
1244
- }
1462
+ init_errors();
1463
+ init_map();
1464
+
1465
+ // src/core/git/committers.ts
1466
+ init_exec();
1467
+ async function historyCommitters(cwd) {
1468
+ const r = await gitRaw(["log", "--format=%cn%x1f%ce"], { cwd });
1469
+ if (r.exitCode !== 0) return [];
1470
+ const counts = /* @__PURE__ */ new Map();
1471
+ for (const line of r.stdout.split("\n")) {
1472
+ const sep = line.indexOf("");
1473
+ if (sep < 0) continue;
1474
+ const name = line.slice(0, sep).trim();
1475
+ const email = line.slice(sep + 1).trim();
1476
+ if (!name || !email) continue;
1477
+ const key = email.toLowerCase();
1478
+ const cur = counts.get(key);
1479
+ if (cur) cur.count++;
1480
+ else counts.set(key, { name, email, count: 1 });
1245
1481
  }
1246
- const result = await applyResolvedIdentity({
1247
- name: opts.asName ?? identity.name,
1248
- email: opts.asEmail ?? identity.email,
1249
- sshCommand,
1250
- identity: keyMissing ? { ...identity, sshKeyPath: void 0 } : identity,
1251
- opts
1252
- });
1253
- result.keyMissing = keyMissing;
1254
- result.bridgeUsed = bridgeUsed;
1255
- return { identity, result };
1482
+ return [...counts.values()].sort((a, b) => b.count - a.count).map(({ name, email }) => ({ name, email }));
1256
1483
  }
1257
1484
 
1258
- // src/core/identity/revert.ts
1259
- async function safeTopLevel3(cwd) {
1485
+ // src/cli/identity.ts
1486
+ init_keys();
1487
+ init_apply();
1488
+ init_sign();
1489
+
1490
+ // src/core/identity/logout.ts
1491
+ init_rev();
1492
+ init_map();
1493
+
1494
+ // src/core/identity/resolve.ts
1495
+ init_config();
1496
+ init_map();
1497
+ init_keys();
1498
+ var norm = (s) => s.trim().toLowerCase();
1499
+ function keyPathFromSshCommand(cmd) {
1500
+ if (!cmd) return void 0;
1501
+ const m = cmd.match(/(?:^|\s)-i\s+(\S+)/);
1502
+ return m?.[1];
1503
+ }
1504
+ async function fpOf(path) {
1260
1505
  try {
1261
- return await topLevel(cwd);
1506
+ return await fingerprintOfFile(path);
1262
1507
  } catch {
1263
1508
  return void 0;
1264
1509
  }
1265
1510
  }
1266
- async function restoreKey(key, value, cwd) {
1267
- if (value === void 0) await unsetConfig(key, "local", cwd);
1268
- else await setConfig(key, value, "local", cwd);
1269
- }
1270
- async function revertRepo(opts) {
1271
- const state = await readState(opts.cwd);
1272
- const backups = state.backups;
1273
- const managed = await getConfig("colabor.managed", "local", opts.cwd);
1274
- if (backups) {
1275
- await restoreKey("user.name", backups.userName, opts.cwd);
1276
- await restoreKey("user.email", backups.userEmail, opts.cwd);
1277
- await restoreKey("core.sshCommand", backups.sshCommand, opts.cwd);
1278
- await restoreKey("commit.template", backups.commitTemplate, opts.cwd);
1279
- await restoreKey("commit.gpgsign", backups.commitGpgsign, opts.cwd);
1280
- await restoreKey("gpg.format", backups.gpgFormat, opts.cwd);
1281
- await restoreKey("user.signingKey", backups.signingKey, opts.cwd);
1282
- }
1283
- if (state.activeIdentity) {
1284
- try {
1285
- const id = await getIdentity(state.activeIdentity);
1286
- if (id.sshKeyPath) await removeKey(id.sshKeyPath);
1287
- } catch {
1511
+ async function resolveActive(cwd, opts = {}) {
1512
+ const [n, e] = await Promise.all([
1513
+ getEffectiveConfig("user.name", cwd),
1514
+ getEffectiveConfig("user.email", cwd)
1515
+ ]);
1516
+ if (!n?.value || !e?.value) return void 0;
1517
+ const name = n.value;
1518
+ const email = e.value;
1519
+ const { identities } = await listIdentities();
1520
+ const byEmail = identities.filter((i) => norm(i.email) === norm(email));
1521
+ let match = byEmail.find((i) => norm(i.name) === norm(name));
1522
+ let enrolled = false;
1523
+ if (!match) {
1524
+ if (!opts.enroll) return void 0;
1525
+ match = await addIdentity({ name, email, scope: "machine", fromConfig: true });
1526
+ enrolled = true;
1527
+ }
1528
+ const sshCmd = await getEffectiveConfig("core.sshCommand", cwd);
1529
+ const cfgPushPath = keyPathFromSshCommand(sshCmd?.value);
1530
+ if (cfgPushPath) {
1531
+ const fp = await fpOf(cfgPushPath);
1532
+ const binding = await getKeyBinding(match.id);
1533
+ if (!binding.pushKey || binding.pushKey.path !== cfgPushPath || fp && binding.pushKey.fingerprint !== fp) {
1534
+ const ref = { path: cfgPushPath, fingerprint: fp ?? binding.pushKey?.fingerprint ?? "" };
1535
+ await setPushKey(match.id, ref);
1288
1536
  }
1289
1537
  }
1290
- await unsetConfig("colabor.managed", "local", opts.cwd);
1291
- await unsetConfig("colabor.managed-by", "local", opts.cwd);
1292
- await unsetAllConfig("colabor.selected", "local", opts.cwd);
1293
- await clearTemplate(opts.cwd).catch(() => {
1294
- });
1295
- state.activeIdentity = void 0;
1296
- state.backups = void 0;
1297
- state.heldBy = void 0;
1298
- await writeState(state, opts.cwd);
1299
- await appendAudit({
1300
- action: "identity.revert",
1301
- source: opts.source,
1302
- repo: await safeTopLevel3(opts.cwd),
1303
- result: managed === "true" ? "ok" : "warn",
1304
- message: managed === "true" ? void 0 : "repo was not managed"
1305
- });
1306
- return { restored: backups, hadBackup: !!backups };
1538
+ const signKeyCfg = await getEffectiveConfig("user.signingKey", cwd);
1539
+ const gpgFormat = await getEffectiveConfig("gpg.format", cwd);
1540
+ if (signKeyCfg?.value) {
1541
+ const binding = await getKeyBinding(match.id);
1542
+ const cur = binding.signKey;
1543
+ if (gpgFormat?.value === "openpgp") {
1544
+ if (!cur || cur.format !== "openpgp" || cur.key !== signKeyCfg.value) {
1545
+ await setSignKey(match.id, { format: "openpgp", key: signKeyCfg.value });
1546
+ }
1547
+ } else {
1548
+ const path = signKeyCfg.value.replace(/\.pub$/, "");
1549
+ if (!cur || cur.format !== "ssh" || cur.path !== path) {
1550
+ const fp = await fpOf(path);
1551
+ if (fp) await setSignKey(match.id, { format: "ssh", path, fingerprint: fp });
1552
+ }
1553
+ }
1554
+ }
1555
+ const finalBinding = await getKeyBinding(match.id);
1556
+ return {
1557
+ identity: match,
1558
+ enrolled,
1559
+ keyPref: { push: !!finalBinding.pushKey, sign: !!finalBinding.signKey }
1560
+ };
1307
1561
  }
1308
1562
 
1309
1563
  // src/core/identity/logout.ts
1310
- async function safeTopLevel4(cwd) {
1564
+ init_agent();
1565
+ init_audit();
1566
+ init_errors();
1567
+ async function safeTopLevel3(cwd) {
1311
1568
  try {
1312
1569
  return await topLevel(cwd);
1313
1570
  } catch {
@@ -1315,38 +1572,83 @@ async function safeTopLevel4(cwd) {
1315
1572
  }
1316
1573
  }
1317
1574
  async function logoutIdentity(opts) {
1318
- const state = await readState(opts.cwd);
1319
- let id = opts.id ?? state.activeIdentity;
1575
+ const resolved = await resolveActive(opts.cwd);
1576
+ let id = opts.id ?? resolved?.identity.id;
1320
1577
  if (!id) {
1321
1578
  const { identities } = await listIdentities();
1322
1579
  if (identities.length === 1) id = identities[0].id;
1323
1580
  else throw Errors.usage("no active identity \u2014 specify one: git colabor identity logout <id>");
1324
1581
  }
1325
1582
  const identity = await getIdentity(id);
1326
- const agentRemoved = identity.sshKeyPath ? await removeKey(identity.sshKeyPath) : false;
1327
- if (state.activeIdentity === identity.id) {
1328
- state.activeIdentity = void 0;
1329
- state.heldBy = void 0;
1330
- if (state.signing === true) {
1331
- state.signing = false;
1332
- await disableSigning(opts.cwd);
1333
- }
1334
- await writeState(state, opts.cwd);
1583
+ const binding = await getKeyBinding(id);
1584
+ const agentRemoved = binding.pushKey ? await removeKey(binding.pushKey.path) : false;
1585
+ const { clearIdentityConfigLayer: clearIdentityConfigLayer2 } = await Promise.resolve().then(() => (init_configClear(), configClear_exports));
1586
+ const cleared = await clearIdentityConfigLayer2(
1587
+ {
1588
+ name: identity.name,
1589
+ email: identity.email,
1590
+ pushKeyPath: binding.pushKey?.path,
1591
+ signKey: binding.signKey
1592
+ },
1593
+ { cwd: opts.cwd, forceKeys: resolved?.identity.id === id }
1594
+ );
1595
+ const clearedAnything = cleared.identityLayer || cleared.sshCommand || cleared.signing;
1596
+ if (cleared.identityLayer) {
1597
+ const { unsetAllConfig: unsetAllConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
1598
+ const { clearTemplate: clearTemplate2 } = await Promise.resolve().then(() => (init_template(), template_exports));
1599
+ await unsetAllConfig2("colabor.selected", "local", opts.cwd);
1600
+ await clearTemplate2(opts.cwd).catch(() => {
1601
+ });
1335
1602
  }
1336
1603
  await appendAudit({
1337
1604
  action: "identity.logout",
1338
1605
  source: opts.source,
1339
1606
  identity: identity.id,
1340
1607
  identityName: identity.name,
1341
- fingerprint: identity.sshKeyFingerprint,
1342
- repo: await safeTopLevel4(opts.cwd)
1608
+ fingerprint: binding.pushKey?.fingerprint,
1609
+ repo: await safeTopLevel3(opts.cwd),
1610
+ message: clearedAnything ? `cleared ${[cleared.identityLayer ? "config" : null, cleared.sshCommand ? "ssh key" : null, cleared.signing ? "sign key" : null].filter(Boolean).join(" + ")} + agent` : "agent only"
1343
1611
  });
1344
1612
  return {
1345
- identity: { id: identity.id, name: identity.name, fingerprint: identity.sshKeyFingerprint },
1346
- agentRemoved
1613
+ identity: { id: identity.id, name: identity.name, fingerprint: binding.pushKey?.fingerprint },
1614
+ agentRemoved,
1615
+ cleared: {
1616
+ agent: agentRemoved,
1617
+ config: cleared.identityLayer,
1618
+ sshCommand: cleared.sshCommand,
1619
+ signing: cleared.signing
1620
+ }
1347
1621
  };
1348
1622
  }
1349
1623
 
1624
+ // src/cli/identity.ts
1625
+ init_audit();
1626
+ init_agent();
1627
+ init_rev();
1628
+
1629
+ // src/core/repo/status.ts
1630
+ init_config();
1631
+ init_rev();
1632
+ init_map();
1633
+ init_types();
1634
+
1635
+ // src/core/repo/state.ts
1636
+ init_rev();
1637
+ init_config();
1638
+ init_io();
1639
+ async function statePath(cwd) {
1640
+ return path.join(await gitDir(cwd), "colabor", "state.json");
1641
+ }
1642
+ async function readState(cwd) {
1643
+ try {
1644
+ const p = await statePath(cwd);
1645
+ const txt = await promises.readFile(p, "utf8");
1646
+ return JSON.parse(txt);
1647
+ } catch {
1648
+ return { schemaVersion: 1 };
1649
+ }
1650
+ }
1651
+
1350
1652
  // src/core/repo/status.ts
1351
1653
  async function repoStatus(cwd) {
1352
1654
  const inRepo = cwd ? await insideWorkTree(cwd) : false;
@@ -1387,47 +1689,50 @@ function toBrief(a) {
1387
1689
  }
1388
1690
 
1389
1691
  // src/cli/identity.ts
1390
- var USE_SPEC = { valueFlags: ["--source", "--as-name", "--as-email", "--stale-minutes"], boolFlags: ["--no-override"] };
1692
+ init_paths();
1693
+ var USE_SPEC = { valueFlags: ["--source", "--as-name", "--as-email"], boolFlags: [] };
1391
1694
  var ADD_SPEC = {
1392
1695
  valueFlags: ["--name", "--email", "--key", "--host", "--source"],
1393
- boolFlags: ["--default", "--no-encrypt"]
1696
+ boolFlags: ["--default"]
1394
1697
  };
1395
1698
  var AUDIT_SPEC = { valueFlags: ["--repo", "--since", "--tail"] };
1396
1699
  var APPLY_SPEC = { valueFlags: ["--name", "--email", "--ssh-command", "--source"] };
1397
- var SET_SPEC = { valueFlags: ["--name", "--email", "--key", "--scope", "--gpg-key"], boolFlags: ["--no-key", "--no-gpg-key"] };
1700
+ var SET_SPEC = {
1701
+ valueFlags: ["--name", "--email", "--key", "--gpg-key", "--sign-key", "--scope"],
1702
+ boolFlags: ["--no-key", "--no-gpg-key", "--no-sign-key"]
1703
+ };
1398
1704
  var SIGN_SPEC = { valueFlags: [], boolFlags: ["--off"] };
1399
1705
  var AGENT_SPEC = { valueFlags: [], boolFlags: ["--remove", "--verify"] };
1400
- function identityToJson(i, defaultId, agentPrints) {
1706
+ function identityToJson(i, defaultId, agentPrints, binding) {
1707
+ const push = binding?.pushKey;
1708
+ const sign2 = binding?.signKey;
1401
1709
  return {
1402
1710
  id: i.id,
1403
1711
  name: i.name,
1404
1712
  email: i.email,
1405
- sshKeyFingerprint: i.sshKeyFingerprint,
1406
1713
  host: i.host,
1407
1714
  // reference mode: a key counts only while the referenced file is still there
1408
- hasKey: !!i.sshKeyPath && fs.existsSync(i.sshKeyPath),
1409
- sshKeyPath: i.sshKeyPath,
1410
- keyEncrypted: !!i.sshKeyEncrypted,
1411
- /** key fingerprint currently held by ssh-agent (live check, one listAgent per call) */
1412
- inAgent: !!i.sshKeyFingerprint && (agentPrints?.has(i.sshKeyFingerprint) ?? false),
1715
+ hasKey: !!push && fs.existsSync(push.path),
1716
+ sshKeyPath: push?.path,
1717
+ sshKeyFingerprint: push?.fingerprint,
1718
+ keyEncrypted: !!push?.encrypted,
1719
+ /** key fingerprint currently held by ssh-agent (live check) */
1720
+ inAgent: !!push?.fingerprint && (agentPrints?.has(push.fingerprint) ?? false),
1721
+ signKey: sign2 ? sign2.format === "openpgp" ? { format: sign2.format, key: sign2.key } : {
1722
+ format: sign2.format,
1723
+ path: sign2.path,
1724
+ fingerprint: sign2.fingerprint,
1725
+ ...sign2.encrypted ? { encrypted: true } : {}
1726
+ } : null,
1413
1727
  imported: !!i.imported,
1414
- disabled: !!i.disabled,
1728
+ fromConfig: !!i.fromConfig,
1415
1729
  scope: i.scope ?? (i.imported ? "project" : "machine"),
1416
- remoteKeys: i.remoteKeys,
1417
- gpgKey: i.gpgKey,
1418
1730
  isDefault: i.id === defaultId
1419
1731
  };
1420
1732
  }
1421
1733
  function asSource(v) {
1422
1734
  return v === "ext" ? "ext" : "cli";
1423
1735
  }
1424
- async function safeTopLevel5(cwd) {
1425
- try {
1426
- return await topLevel(cwd);
1427
- } catch {
1428
- return void 0;
1429
- }
1430
- }
1431
1736
  async function dispatch(command, tokens, ctx) {
1432
1737
  switch (command) {
1433
1738
  case void 0:
@@ -1445,14 +1750,12 @@ async function dispatch(command, tokens, ctx) {
1445
1750
  return sign(parseCommandArgs(tokens, SIGN_SPEC), ctx);
1446
1751
  case "gpg-keys":
1447
1752
  return gpgKeys(ctx);
1448
- case "disable":
1449
- return disable(parseCommandArgs(tokens), ctx);
1450
1753
  case "unhide":
1451
1754
  return unhide(parseCommandArgs(tokens));
1452
1755
  case "hidden":
1453
1756
  return hiddenLs();
1454
1757
  case "rm":
1455
- return rm2(parseCommandArgs(tokens), ctx);
1758
+ return rm2(parseCommandArgs(tokens));
1456
1759
  case "logout":
1457
1760
  return logout(parseCommandArgs(tokens), ctx);
1458
1761
  case "agent":
@@ -1463,8 +1766,6 @@ async function dispatch(command, tokens, ctx) {
1463
1766
  return audit(parseCommandArgs(tokens, AUDIT_SPEC));
1464
1767
  case "doctor":
1465
1768
  return doctor(ctx);
1466
- case "revert":
1467
- return revert(ctx);
1468
1769
  case "status":
1469
1770
  return status(ctx);
1470
1771
  case "_apply":
@@ -1474,11 +1775,12 @@ async function dispatch(command, tokens, ctx) {
1474
1775
  }
1475
1776
  }
1476
1777
  async function ls2() {
1778
+ const map = await readMap();
1477
1779
  const { identities, defaultIdentity } = await listIdentities();
1478
1780
  const prints = await agentFingerprints();
1479
1781
  const hidden = new Set(await listHiddenEmails());
1480
1782
  const visible = identities.filter((i) => !hidden.has(i.email.toLowerCase()));
1481
- return ok({ identities: visible.map((i) => identityToJson(i, defaultIdentity, prints)), defaultIdentity });
1783
+ return ok({ identities: visible.map((i) => identityToJson(i, defaultIdentity, prints, map.keyBindings?.[i.id])), defaultIdentity });
1482
1784
  }
1483
1785
  async function hideIdentityCmd(p) {
1484
1786
  const email = p.positionals[0];
@@ -1495,101 +1797,77 @@ async function agentKey(p, ctx) {
1495
1797
  const id = p.positionals[0];
1496
1798
  if (!id) throw Errors.usage("git colabor identity agent <id> [--remove | --verify]");
1497
1799
  const identity = await getIdentity(id);
1498
- if (!identity.sshKeyPath || !identity.sshKeyFingerprint) {
1499
- throw Errors.usage(`identity "${id}" has no SSH key`);
1500
- }
1800
+ const binding = await getKeyBinding(id);
1801
+ if (!binding.pushKey) throw Errors.usage(`identity "${id}" has no SSH push key`);
1802
+ const { path: keyPath, fingerprint } = binding.pushKey;
1501
1803
  const remove = p.bools.has("--remove");
1502
1804
  const verify = p.bools.has("--verify");
1503
1805
  if (remove && verify) throw Errors.usage("--remove and --verify are mutually exclusive");
1504
1806
  if (remove) {
1505
- const removed = await removeKey(identity.sshKeyPath);
1807
+ const removed = await removeKey(keyPath);
1506
1808
  await appendAudit({
1507
1809
  action: "key.remove",
1508
1810
  source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
1509
1811
  identity: id,
1510
1812
  identityName: identity.name,
1511
- fingerprint: identity.sshKeyFingerprint
1813
+ fingerprint
1512
1814
  });
1513
- return ok({ removed, inAgent: await keyInAgent(identity.sshKeyFingerprint) }, removed ? [] : [
1815
+ return ok({ removed, inAgent: await keyInAgent(fingerprint) }, removed ? [] : [
1514
1816
  { code: "not-in-agent", message: "key was not loaded in ssh-agent" }
1515
1817
  ]);
1516
1818
  }
1517
- const askpassScriptPath = ctx.askpassScriptPath ? await ensureAskpassWrapper(ctx.askpassScriptPath) : void 0;
1819
+ const askpassScriptPath = ctx.askpassScriptPath ? await (await Promise.resolve().then(() => (init_apply(), apply_exports))).ensureAskpassWrapper(ctx.askpassScriptPath) : void 0;
1518
1820
  if (verify) {
1519
- const verified = await verifyKey({
1520
- keyPath: identity.sshKeyPath,
1521
- fingerprint: identity.sshKeyFingerprint,
1522
- askpassScriptPath,
1523
- socketPath: ctx.socketPath,
1524
- token: ctx.token
1525
- });
1526
- return ok({ verified, inAgent: await keyInAgent(identity.sshKeyFingerprint) });
1821
+ const verified = await verifyKey({ keyPath, fingerprint, askpassScriptPath, socketPath: ctx.socketPath, token: ctx.token });
1822
+ return ok({ verified, inAgent: await keyInAgent(fingerprint) });
1527
1823
  }
1528
- const loaded = await loadKey({
1529
- keyPath: identity.sshKeyPath,
1530
- fingerprint: identity.sshKeyFingerprint,
1531
- askpassScriptPath,
1532
- socketPath: ctx.socketPath,
1533
- token: ctx.token,
1534
- useAppleKeychain: true
1535
- });
1824
+ const loaded = await loadKey({ keyPath, fingerprint, askpassScriptPath, socketPath: ctx.socketPath, token: ctx.token, useAppleKeychain: true });
1536
1825
  if (loaded.loaded) {
1537
1826
  await appendAudit({
1538
1827
  action: "key.load",
1539
1828
  source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
1540
1829
  identity: id,
1541
1830
  identityName: identity.name,
1542
- fingerprint: identity.sshKeyFingerprint,
1831
+ fingerprint,
1543
1832
  message: `via ${loaded.via}`
1544
1833
  });
1545
1834
  }
1546
1835
  return ok(
1547
- // inAgent is a live re-check: keygen-verify (agent-less host) reports
1548
- // loaded=true even though no agent holds the key
1549
- { loaded: loaded.loaded, via: loaded.via, inAgent: await keyInAgent(identity.sshKeyFingerprint), message: loaded.message },
1836
+ { loaded: loaded.loaded, via: loaded.via, inAgent: await keyInAgent(fingerprint), message: loaded.message },
1550
1837
  loaded.loaded ? [] : [{ code: "key-not-loaded", message: loaded.message ?? `via ${loaded.via}` }]
1551
1838
  );
1552
1839
  }
1553
1840
  async function use(p, ctx) {
1554
1841
  const id = p.positionals[0];
1555
1842
  if (!id) throw Errors.usage("git colabor identity use <id>");
1556
- const staleRaw = p.values["--stale-minutes"];
1557
- if (staleRaw !== void 0 && !Number.isFinite(Number(staleRaw))) {
1558
- throw Errors.usage(`--stale-minutes must be a number, got "${staleRaw}"`);
1559
- }
1560
- const current = await getIdentity(id);
1561
- if (current.disabled) await updateIdentity(id, { disabled: void 0 });
1562
1843
  const { identity, result } = await applyIdentity(id, {
1563
1844
  source: asSource(p.values["--source"]),
1564
1845
  cwd: ctx.cwd,
1565
1846
  asName: p.values["--as-name"],
1566
1847
  asEmail: p.values["--as-email"],
1567
- noOverride: p.bools.has("--no-override"),
1568
- staleMinutes: staleRaw ? Number(staleRaw) : void 0,
1569
1848
  askpassScriptPath: ctx.askpassScriptPath,
1570
1849
  socketPath: ctx.socketPath,
1571
1850
  token: ctx.token
1572
1851
  });
1573
1852
  const warnings = [];
1574
- if (result.conflict) warnings.push({ code: "conflict", message: `overrode ${result.conflict.heldBy.session}` });
1575
1853
  if (result.keyMissing) {
1576
1854
  warnings.push({
1577
1855
  code: "key-missing",
1578
- message: `key file missing or unreadable: ${identity.sshKeyPath} \u2014 applied without a key (no core.sshCommand)`
1856
+ message: `push key file missing or unreadable \u2014 applied without a key (no core.sshCommand)`
1579
1857
  });
1580
1858
  }
1581
- if (identity.sshKeyEncrypted && result.agent && !result.agent.inAgent && !result.bridgeUsed) {
1859
+ if (result.keyDegraded) {
1582
1860
  warnings.push({
1583
- code: "agent-reminder",
1584
- message: `key not in ssh-agent \u2014 run \`ssh-add ${identity.sshKeyPath}\` to cache it, or each push will prompt for the passphrase`
1861
+ code: "key-degraded",
1862
+ message: `passphrase unavailable \u2014 identity applied WITHOUT the push/sign key; retry via the extension or ssh-add`
1585
1863
  });
1586
1864
  }
1865
+ const map = await readMap();
1587
1866
  return ok(
1588
1867
  {
1589
- identity: identityToJson(identity),
1868
+ identity: identityToJson(identity, void 0, void 0, map.keyBindings?.[identity.id]),
1590
1869
  applied: { userName: result.name, userEmail: result.email, sshCommand: result.sshCommand ?? null },
1591
- agent: result.agent ?? null,
1592
- conflict: result.conflict
1870
+ keyApplied: result.keyApplied
1593
1871
  },
1594
1872
  warnings
1595
1873
  );
@@ -1601,41 +1879,26 @@ async function add2(p) {
1601
1879
  throw Errors.usage("git colabor identity add --name <n> --email <e> [--key <path>] [--host <h>] [--default]");
1602
1880
  }
1603
1881
  const warnings = [];
1604
- let sshKeyFingerprint;
1605
- let sshKeyPath;
1606
- let sshKeyEncrypted;
1607
1882
  let encrypted = null;
1608
1883
  const keySource = p.values["--key"];
1609
1884
  if (keySource) {
1610
1885
  if (!fs.existsSync(keySource)) throw Errors.usage(`key file not found: ${keySource}`);
1611
1886
  const imp = await importKey(keySource);
1612
- sshKeyFingerprint = imp.fingerprint;
1613
- sshKeyPath = imp.path;
1614
1887
  encrypted = imp.encrypted;
1615
- sshKeyEncrypted = imp.encrypted;
1616
1888
  if (imp.encrypted) {
1617
- warnings.push({
1618
- code: "encrypted-key",
1619
- message: "key is encrypted; it loads via the extension askpass session or an ssh-agent"
1620
- });
1889
+ warnings.push({ code: "encrypted-key", message: "key is encrypted; it loads via the extension askpass session or an ssh-agent" });
1621
1890
  } else {
1622
- warnings.push({
1623
- code: "unencrypted-key",
1624
- message: "key is UNENCRYPTED \u2014 anyone who reads the key file can use it. Consider encrypting it."
1625
- });
1891
+ warnings.push({ code: "unencrypted-key", message: "key is UNENCRYPTED \u2014 anyone who reads the key file can use it. Consider encrypting it." });
1626
1892
  }
1627
1893
  }
1628
- const identity = await addIdentity({
1629
- name,
1630
- email,
1631
- sshKeyFingerprint,
1632
- sshKeyPath,
1633
- sshKeyEncrypted,
1634
- host: p.values["--host"]
1635
- });
1894
+ const identity = await addIdentity({ name, email, host: p.values["--host"] });
1895
+ if (keySource) {
1896
+ const imp = await importKey(keySource);
1897
+ await setPushKey(identity.id, { path: imp.path, fingerprint: imp.fingerprint, ...imp.encrypted ? { encrypted: true } : {} });
1898
+ }
1636
1899
  if (p.bools.has("--default")) await setDefault(identity.id);
1637
- await appendAudit({ action: "key.load", source: "cli", identity: identity.id, identityName: name, fingerprint: sshKeyFingerprint });
1638
- return ok({ identity: identityToJson(identity), encrypted }, warnings);
1900
+ const map = await readMap();
1901
+ return ok({ identity: identityToJson(identity, void 0, void 0, map.keyBindings?.[identity.id]), encrypted }, warnings);
1639
1902
  }
1640
1903
  async function importFromHistory(ctx) {
1641
1904
  if (!await insideWorkTree(ctx.cwd)) throw Errors.notARepo(ctx.cwd);
@@ -1647,12 +1910,7 @@ async function importFromHistory(ctx) {
1647
1910
  for (const c of committers) {
1648
1911
  const id = c.email.toLowerCase();
1649
1912
  if (known.has(id) || hidden.has(id)) continue;
1650
- const identity = await addIdentity({
1651
- name: c.name,
1652
- email: c.email,
1653
- imported: true,
1654
- scope: "project"
1655
- });
1913
+ const identity = await addIdentity({ name: c.name, email: c.email, imported: true, scope: "project" });
1656
1914
  known.add(id);
1657
1915
  added.push(identity);
1658
1916
  }
@@ -1664,9 +1922,9 @@ async function importFromHistory(ctx) {
1664
1922
  });
1665
1923
  }
1666
1924
  const warnings = committers.length === 0 ? [{ code: "empty", message: "no commits found in history" }] : [];
1667
- return ok({ added: added.map((i) => identityToJson(i)), skipped: committers.length - added.length }, warnings);
1925
+ return ok({ added, skipped: committers.length - added.length }, warnings);
1668
1926
  }
1669
- async function rm2(p, ctx) {
1927
+ async function rm2(p) {
1670
1928
  const id = p.positionals[0];
1671
1929
  if (!id) throw Errors.usage("git colabor identity rm <id>");
1672
1930
  let email;
@@ -1677,10 +1935,6 @@ async function rm2(p, ctx) {
1677
1935
  wasImported = !!identity.imported;
1678
1936
  } catch {
1679
1937
  }
1680
- try {
1681
- await logoutIdentity({ source: "cli", cwd: ctx.cwd, id });
1682
- } catch {
1683
- }
1684
1938
  await removeIdentity(id);
1685
1939
  if (wasImported && email) await hideIdentityEmail(email);
1686
1940
  return ok({ removed: id, hidden: wasImported ? (email ?? "").toLowerCase() : void 0 });
@@ -1689,63 +1943,76 @@ async function setIdentity(p, ctx) {
1689
1943
  const id = p.positionals[0];
1690
1944
  if (!id) {
1691
1945
  throw Errors.usage(
1692
- "git colabor identity set <id> --name <n> | --email <e> | --key <path> | --no-key | --gpg-key <key> | --no-gpg-key"
1946
+ "git colabor identity set <id> --name <n> | --email <e> | --key <path> | --no-key | --gpg-key <k> | --no-gpg-key | --sign-key <path> | --no-sign-key | --scope <s>"
1693
1947
  );
1694
1948
  }
1695
1949
  await getIdentity(id);
1696
- const patch = {};
1697
1950
  const warnings = [];
1951
+ const { updateIdentity: updateIdentity2 } = await Promise.resolve().then(() => (init_map(), map_exports));
1952
+ const patch = {};
1698
1953
  if (p.values["--name"]) patch.name = p.values["--name"];
1699
1954
  if (p.values["--email"]) patch.email = p.values["--email"];
1700
- if (p.bools.has("--no-key")) patch.sshKeyPath = void 0;
1955
+ if (p.values["--scope"]) {
1956
+ const s = p.values["--scope"];
1957
+ if (s !== "machine" && s !== "project") throw Errors.usage(`--scope must be machine|project, got "${s}"`);
1958
+ patch.scope = s;
1959
+ }
1960
+ let keyTouched = false;
1961
+ if (p.bools.has("--no-key")) {
1962
+ await setPushKey(id, void 0);
1963
+ keyTouched = true;
1964
+ }
1701
1965
  if (p.values["--key"]) {
1702
1966
  const keySource = p.values["--key"];
1703
1967
  if (!fs.existsSync(keySource)) throw Errors.usage(`key file not found: ${keySource}`);
1704
1968
  const imp = await importKey(keySource);
1705
- patch.sshKeyPath = imp.path;
1706
- patch.sshKeyFingerprint = imp.fingerprint;
1707
- patch.sshKeyEncrypted = imp.encrypted;
1969
+ await setPushKey(id, { path: imp.path, fingerprint: imp.fingerprint, ...imp.encrypted ? { encrypted: true } : {} });
1970
+ keyTouched = true;
1708
1971
  if (imp.encrypted) {
1709
- warnings.push({
1710
- code: "encrypted-key",
1711
- message: "key is encrypted; it loads via the extension askpass session or an ssh-agent"
1712
- });
1972
+ warnings.push({ code: "encrypted-key", message: "key is encrypted; it loads via the extension askpass session or an ssh-agent" });
1713
1973
  }
1714
1974
  }
1715
- if (p.values["--scope"]) {
1716
- const s = p.values["--scope"];
1717
- if (s !== "machine" && s !== "project") {
1718
- throw Errors.usage(`--scope must be machine|project, got "${s}"`);
1719
- }
1720
- patch.scope = s;
1975
+ if (p.bools.has("--no-gpg-key") || p.bools.has("--no-sign-key")) {
1976
+ await setSignKey(id, void 0);
1977
+ keyTouched = true;
1721
1978
  }
1722
- if (p.bools.has("--no-gpg-key")) patch.gpgKey = void 0;
1723
1979
  if (p.values["--gpg-key"]) {
1724
- const [key, ...more] = await listSigningKeys(ctx.cwd, p.values["--gpg-key"]);
1980
+ const { listSigningKeys: listSigningKeys2 } = await Promise.resolve().then(() => (init_gpg(), gpg_exports));
1981
+ const [key, ...more] = await listSigningKeys2(ctx.cwd, p.values["--gpg-key"]);
1725
1982
  if (!key) throw Errors.usage(`no usable secret GPG signing key matches "${p.values["--gpg-key"]}"`);
1726
1983
  if (more.length > 0) throw Errors.usage(`"${p.values["--gpg-key"]}" matches several GPG keys \u2014 pass a fingerprint`);
1727
- patch.gpgKey = key.fingerprint;
1984
+ await setSignKey(id, { format: "openpgp", key: key.fingerprint });
1985
+ keyTouched = true;
1986
+ }
1987
+ if (p.values["--sign-key"]) {
1988
+ const signSource = p.values["--sign-key"];
1989
+ if (!fs.existsSync(signSource)) throw Errors.usage(`key file not found: ${signSource}`);
1990
+ const imp = await importKey(signSource);
1991
+ await setSignKey(id, { format: "ssh", path: imp.path, fingerprint: imp.fingerprint, ...imp.encrypted ? { encrypted: true } : {} });
1992
+ keyTouched = true;
1993
+ if (imp.encrypted) {
1994
+ warnings.push({ code: "encrypted-key", message: "sign key is encrypted; it signs via the extension askpass session or an ssh-agent" });
1995
+ }
1728
1996
  }
1729
- if (Object.keys(patch).length === 0) {
1730
- throw Errors.usage("identity set needs at least one of --name / --email / --key / --no-key / --gpg-key / --no-gpg-key");
1997
+ if (Object.keys(patch).length === 0 && !keyTouched) {
1998
+ throw Errors.usage(
1999
+ "identity set needs at least one of --name / --email / --key / --no-key / --gpg-key / --no-gpg-key / --sign-key / --no-sign-key / --scope"
2000
+ );
1731
2001
  }
1732
- const next = await updateIdentity(id, patch);
2002
+ const next = Object.keys(patch).length > 0 ? await updateIdentity2(id, patch) : await getIdentity(id);
1733
2003
  await appendAudit({
1734
2004
  action: "identity.set",
1735
2005
  source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
1736
2006
  identity: id,
1737
2007
  identityName: next.name,
1738
- fingerprint: next.sshKeyFingerprint,
1739
- message: `set ${Object.keys(patch).join(", ")}`
2008
+ message: `set ${[...Object.keys(patch), ...keyTouched ? ["key"] : []].join(", ")}`
1740
2009
  });
1741
- return ok({ identity: identityToJson(next) }, warnings);
2010
+ const map = await readMap();
2011
+ return ok({ identity: identityToJson(next, void 0, void 0, map.keyBindings?.[id]) }, warnings);
1742
2012
  }
1743
2013
  async function logout(p, ctx) {
1744
2014
  const r = await logoutIdentity({ source: "cli", cwd: ctx.cwd, id: p.positionals[0] });
1745
- return ok({
1746
- identity: r.identity,
1747
- cleared: { agent: r.agentRemoved }
1748
- });
2015
+ return ok({ identity: r.identity, cleared: r.cleared });
1749
2016
  }
1750
2017
  async function audit(p) {
1751
2018
  const entries = await readAudit({
@@ -1769,50 +2036,12 @@ async function sign(p, ctx) {
1769
2036
  const id = p.positionals[0];
1770
2037
  const on = !p.bools.has("--off");
1771
2038
  if (!id && on) throw Errors.usage("git colabor identity sign <id> | identity sign [id] --off");
1772
- const r = await setCommitSigning({
1773
- source: "cli",
1774
- cwd: ctx.cwd,
1775
- id,
1776
- on,
1777
- askpassScriptPath: ctx.askpassScriptPath
1778
- });
2039
+ const r = await setCommitSigning({ source: "cli", cwd: ctx.cwd, id, on, askpassScriptPath: ctx.askpassScriptPath });
1779
2040
  return ok(r);
1780
2041
  }
1781
2042
  async function gpgKeys(ctx) {
1782
- return ok({ keys: await listSigningKeys(ctx.cwd) });
1783
- }
1784
- async function disable(p, ctx) {
1785
- const id = p.positionals[0];
1786
- if (!id) throw Errors.usage("git colabor identity disable <id>");
1787
- const identity = await getIdentity(id);
1788
- await updateIdentity(id, { disabled: true });
1789
- let deactivated = false;
1790
- if (ctx.cwd) {
1791
- const state = await readState(ctx.cwd);
1792
- if (state.activeIdentity === id) {
1793
- state.activeIdentity = void 0;
1794
- state.heldBy = void 0;
1795
- if (state.signing === true) {
1796
- state.signing = false;
1797
- await disableSigning(ctx.cwd);
1798
- }
1799
- await writeState(state, ctx.cwd);
1800
- deactivated = true;
1801
- }
1802
- }
1803
- await appendAudit({
1804
- action: "identity.disable",
1805
- source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
1806
- identity: id,
1807
- identityName: identity.name,
1808
- repo: deactivated ? await safeTopLevel5(ctx.cwd) : void 0,
1809
- message: deactivated ? "deactivated in repo" : "disabled"
1810
- });
1811
- return ok({ disabled: id, deactivated });
1812
- }
1813
- async function revert(ctx) {
1814
- const r = await revertRepo({ source: "cli", cwd: ctx.cwd });
1815
- return ok({ restored: r.restored ?? null, hadBackup: r.hadBackup });
2043
+ const { listSigningKeys: listSigningKeys2 } = await Promise.resolve().then(() => (init_gpg(), gpg_exports));
2044
+ return ok({ keys: await listSigningKeys2(ctx.cwd) });
1816
2045
  }
1817
2046
  async function hiddenApply(p, ctx) {
1818
2047
  const name = p.values["--name"];
@@ -1825,27 +2054,29 @@ async function hiddenApply(p, ctx) {
1825
2054
  opts: { source: asSource(p.values["--source"]), cwd: ctx.cwd }
1826
2055
  });
1827
2056
  return ok({
1828
- applied: { userName: result.name, userEmail: result.email, sshCommand: result.sshCommand ?? null },
1829
- conflict: result.conflict
2057
+ applied: { userName: result.name, userEmail: result.email, sshCommand: result.sshCommand ?? null }
1830
2058
  });
1831
2059
  }
1832
2060
  async function status(ctx) {
2061
+ const map = await readMap();
1833
2062
  const { identities, defaultIdentity } = await listIdentities();
1834
2063
  const rs = await repoStatus(ctx.cwd);
1835
- const active = rs.activeIdentityId ? identities.find((i) => i.id === rs.activeIdentityId) : void 0;
1836
- const st = ctx.cwd ? await readState(ctx.cwd) : void 0;
1837
2064
  const prints = await agentFingerprints();
2065
+ const resolved = rs.inRepo ? await resolveActive(ctx.cwd, { enroll: true }) : void 0;
2066
+ const active = resolved?.identity;
2067
+ const activeId = active?.id;
1838
2068
  const hidden = new Set(await listHiddenEmails());
1839
- const rows = identities.filter((i) => i.id === rs.activeIdentityId || !hidden.has(i.email.toLowerCase())).map((i) => ({ ...identityToJson(i, defaultIdentity, prints), active: i.id === rs.activeIdentityId }));
2069
+ const rows = identities.filter((i) => i.id === activeId || !hidden.has(i.email.toLowerCase())).map((i) => ({
2070
+ ...identityToJson(i, defaultIdentity, prints, map.keyBindings?.[i.id]),
2071
+ active: i.id === activeId
2072
+ }));
1840
2073
  return ok({
1841
2074
  repo: rs.repo,
1842
2075
  inRepo: rs.inRepo,
1843
- managed: rs.managed,
1844
- managedBy: rs.managedBy,
1845
- heldBy: rs.heldBy,
1846
2076
  // what `git commit` will actually do here, and which scope decides it
1847
- signing: await signingStatus(ctx.cwd, st?.signing === true),
1848
- activeIdentity: active ? identityToJson(active, defaultIdentity, prints) : null,
2077
+ signing: await signingStatus(ctx.cwd),
2078
+ activeIdentity: active ? identityToJson(active, defaultIdentity, prints, map.keyBindings?.[active.id]) : null,
2079
+ enrolled: resolved?.enrolled ?? false,
1849
2080
  identities: rows,
1850
2081
  selected: rs.selected,
1851
2082
  available: rs.available
@@ -1878,10 +2109,8 @@ async function doctor(ctx) {
1878
2109
  const inRepo = ctx.cwd ? await insideWorkTree(ctx.cwd) : false;
1879
2110
  check("inside git repo", () => inRepo, ctx.cwd);
1880
2111
  if (inRepo && ctx.cwd) {
1881
- const managed = await getConfig("colabor.managed", "local", ctx.cwd);
1882
- check("repo managed", () => managed === "true", `colabor.managed=${managed ?? "unset"}`);
1883
- const st = await readState(ctx.cwd);
1884
- check("active identity", () => !!st.activeIdentity, st.activeIdentity ?? "(none)");
2112
+ const resolved = await resolveActive(ctx.cwd);
2113
+ check("active identity", () => !!resolved, resolved?.identity.name ?? "(none \u2014 config has no match)");
1885
2114
  }
1886
2115
  return ok({ diagnostics: diags });
1887
2116
  }
@@ -1919,7 +2148,6 @@ function topHelp() {
1919
2148
  " git colabor identity disable <id> (deactivate on key/passphrase failure)",
1920
2149
  " git colabor identity rm <id>",
1921
2150
  " git colabor identity logout [id]",
1922
- " git colabor identity revert",
1923
2151
  " git colabor identity status",
1924
2152
  " git colabor identity audit [--repo <p>] [--tail N]",
1925
2153
  " git colabor identity doctor",
@@ -2092,10 +2320,6 @@ ${data.added.map((i) => ` ${i.name} <${i.email}>`).join("\n")}`;
2092
2320
  const data = d;
2093
2321
  return `Logged out "${data.identity.name}" (agent: ${data.cleared.agent ? "removed" : "n/a"}; the key file itself is never touched)`;
2094
2322
  }
2095
- if (command === "revert") {
2096
- const data = d;
2097
- return data.hadBackup ? "Reverted repo identity to pre-tool state." : "Repo was not managed; nothing to revert.";
2098
- }
2099
2323
  if (command === "audit") {
2100
2324
  const entries = d.entries ?? [];
2101
2325
  if (entries.length === 0) return "(no audit entries)";