git-colabor 0.1.0 → 0.1.4

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.
package/dist/cli.cjs CHANGED
@@ -2,11 +2,10 @@
2
2
 
3
3
  var fs = require('fs');
4
4
  var path = require('path');
5
- var promises = require('readline/promises');
6
- var promises$1 = require('fs/promises');
5
+ var promises = require('fs/promises');
6
+ var crypto = require('crypto');
7
7
  var os = require('os');
8
8
  var child_process = require('child_process');
9
- var crypto = require('crypto');
10
9
 
11
10
  // src/cli/index.ts
12
11
 
@@ -40,15 +39,15 @@ var Errors = {
40
39
  }),
41
40
  authorNotFound: (key) => new AppError({
42
41
  code: "AUTHOR_NOT_FOUND",
43
- message: `Author with initials "${key}" not found in .git-coauthors`,
42
+ message: `Author with initials "${key}" not found in identities`,
44
43
  exitCode: EXIT_CODES.NOT_FOUND,
45
44
  hints: [`Add it with: git colabor coauthor add ${key} "Full Name" email@example.com`]
46
45
  }),
47
46
  duplicateKey: (key) => new AppError({
48
47
  code: "DUPLICATE_KEY",
49
- message: `Key "${key}" already exists in .git-coauthors`,
48
+ message: `Key "${key}" already exists`,
50
49
  exitCode: EXIT_CODES.NOT_FOUND,
51
- hints: ["Edit .git-coauthors directly to change an existing entry."]
50
+ hints: []
52
51
  }),
53
52
  invalidEmail: (email) => new AppError({ code: "INVALID_EMAIL", message: `Invalid email: ${email}`, exitCode: EXIT_CODES.USAGE }),
54
53
  usage: (message, hints) => new AppError({ code: "USAGE", message, exitCode: EXIT_CODES.USAGE, hints }),
@@ -167,17 +166,6 @@ function parseCommandArgs(tokens, spec = {}) {
167
166
  return { positionals, values, bools };
168
167
  }
169
168
 
170
- // src/cli/render.ts
171
- function authorToJson(a) {
172
- return { key: a.key, name: a.name, email: a.email };
173
- }
174
- function renderAuthors(authors) {
175
- if (authors.length === 0) return "(none)";
176
- const keyW = Math.max(2, ...authors.map((a) => a.key.length));
177
- const nameW = Math.max(4, ...authors.map((a) => a.name.length));
178
- return authors.map((a) => `${a.key.padEnd(keyW)} ${a.name.padEnd(nameW)} ${a.email}`).join("\n");
179
- }
180
-
181
169
  // src/core/authors/types.ts
182
170
  var CO_AUTHOR_TRAILER = "Co-authored-by:";
183
171
  var Author = class {
@@ -202,6 +190,120 @@ function genKey(name, email) {
202
190
  const initials = name.toLowerCase().split(/\s+/).filter(Boolean).map((w) => w[0] ?? "").join("");
203
191
  return `${initials}${email.slice(0, 2)}`;
204
192
  }
193
+ function dataDir() {
194
+ if (process.platform === "win32") {
195
+ return path.join(process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"), "git-colabor");
196
+ }
197
+ return path.join(process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"), "git-colabor");
198
+ }
199
+ function mapPath() {
200
+ return process.env.GIT_COLABOR_MAP ?? path.join(dataDir(), "identities.json");
201
+ }
202
+ function auditLogPath() {
203
+ return process.env.GIT_COLABOR_AUDIT_FILE ?? path.join(dataDir(), "audit.log");
204
+ }
205
+ async function atomicWriteJson(path$1, data, mode) {
206
+ await promises.mkdir(path.dirname(path$1), { recursive: true });
207
+ const tmp = `${path$1}.${crypto.randomBytes(4).toString("hex")}.tmp`;
208
+ await promises.writeFile(tmp, JSON.stringify(data, null, 2) + "\n", "utf8");
209
+ {
210
+ await promises.chmod(tmp, mode).catch(() => {
211
+ });
212
+ }
213
+ await promises.rename(tmp, path$1);
214
+ }
215
+
216
+ // src/core/identity/map.ts
217
+ function genId() {
218
+ return "id_" + crypto.randomBytes(4).toString("hex");
219
+ }
220
+ async function readMap() {
221
+ try {
222
+ const txt = await promises.readFile(mapPath(), "utf8");
223
+ const parsed = JSON.parse(txt);
224
+ const identities = { ...parsed.identities };
225
+ for (const id of Object.keys(identities)) {
226
+ const row = identities[id];
227
+ delete row.passphraseCommand;
228
+ if (row.scope === "user" || row.scope === "vscode") row.scope = "machine";
229
+ }
230
+ return {
231
+ schemaVersion: 1,
232
+ identities,
233
+ defaultIdentity: parsed.defaultIdentity,
234
+ hidden: parsed.hidden
235
+ };
236
+ } catch {
237
+ return { schemaVersion: 1, identities: {} };
238
+ }
239
+ }
240
+ async function writeMap(map) {
241
+ await atomicWriteJson(mapPath(), map, 384);
242
+ }
243
+ async function getIdentity(id) {
244
+ const map = await readMap();
245
+ const found = map.identities[id];
246
+ if (!found) throw Errors.usage(`identity "${id}" not found`);
247
+ return found;
248
+ }
249
+ async function addIdentity(input) {
250
+ const map = await readMap();
251
+ const id = input.id ?? genId();
252
+ if (map.identities[id]) throw Errors.usage(`identity "${id}" already exists`);
253
+ const identity = { ...input, id, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
254
+ map.identities[id] = identity;
255
+ if (map.hidden?.[identity.email.toLowerCase()]) delete map.hidden[identity.email.toLowerCase()];
256
+ await writeMap(map);
257
+ return identity;
258
+ }
259
+ async function updateIdentity(id, patch) {
260
+ const map = await readMap();
261
+ const identity = map.identities[id];
262
+ 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;
270
+ await writeMap(map);
271
+ return next;
272
+ }
273
+ async function hideIdentityEmail(email) {
274
+ const map = await readMap();
275
+ map.hidden = { ...map.hidden, [email.toLowerCase()]: true };
276
+ await writeMap(map);
277
+ }
278
+ async function unhideIdentityEmail(email) {
279
+ const map = await readMap();
280
+ const key = email.toLowerCase();
281
+ if (!map.hidden?.[key]) return false;
282
+ delete map.hidden[key];
283
+ await writeMap(map);
284
+ return true;
285
+ }
286
+ async function listHiddenEmails() {
287
+ const map = await readMap();
288
+ return Object.keys(map.hidden ?? {});
289
+ }
290
+ async function removeIdentity(id) {
291
+ const map = await readMap();
292
+ if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
293
+ delete map.identities[id];
294
+ if (map.defaultIdentity === id) delete map.defaultIdentity;
295
+ await writeMap(map);
296
+ }
297
+ async function setDefault(id) {
298
+ const map = await readMap();
299
+ if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
300
+ map.defaultIdentity = id;
301
+ await writeMap(map);
302
+ }
303
+ async function listIdentities() {
304
+ const map = await readMap();
305
+ return { identities: Object.values(map.identities), defaultIdentity: map.defaultIdentity };
306
+ }
205
307
  var GitError = class extends Error {
206
308
  cmd;
207
309
  exitCode;
@@ -267,86 +369,6 @@ async function runBin(cmd, args, opts = {}) {
267
369
  });
268
370
  }
269
371
 
270
- // src/core/git/rev.ts
271
- async function insideWorkTree(cwd) {
272
- const r = await gitRaw(["rev-parse", "--is-inside-work-tree"], { cwd });
273
- return r.exitCode === 0 && r.stdout.trim() === "true";
274
- }
275
- async function topLevel(cwd) {
276
- const r = await git(["rev-parse", "--show-toplevel"], { cwd });
277
- return r.stdout.trim();
278
- }
279
- async function gitDir(cwd) {
280
- const r = await git(["rev-parse", "--git-dir"], { cwd });
281
- return path.resolve(cwd ?? process.cwd(), r.stdout.trim());
282
- }
283
-
284
- // src/core/authors/store.ts
285
- var COAUTHORS_FILENAME = ".git-coauthors";
286
- var EMAIL_RE = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|((\w+\.)+[a-zA-Z]{2,}))$/;
287
- function validateEmail(email) {
288
- return EMAIL_RE.test(email);
289
- }
290
- function homeCoAuthorsPath() {
291
- return path.join(os.homedir(), COAUTHORS_FILENAME);
292
- }
293
- async function coAuthorsPath(cwd) {
294
- const envPath = process.env.GIT_COLABOR_COAUTHORS_PATH;
295
- if (envPath) return path.resolve(envPath);
296
- try {
297
- const root = await topLevel(cwd);
298
- const local = path.join(root, COAUTHORS_FILENAME);
299
- if (fs.existsSync(local)) return local;
300
- } catch {
301
- }
302
- return homeCoAuthorsPath();
303
- }
304
- async function readAuthors(cwd) {
305
- const p = await coAuthorsPath(cwd);
306
- const txt = await promises$1.readFile(p, "utf8");
307
- const parsed = JSON.parse(txt);
308
- if (!parsed || typeof parsed !== "object" || !parsed.coauthors) {
309
- throw Errors.usage(`Invalid .git-coauthors at ${p}: missing "coauthors" object`);
310
- }
311
- return { coauthors: parsed.coauthors };
312
- }
313
- async function writeAuthors(schema, cwd) {
314
- const p = await coAuthorsPath(cwd);
315
- await promises$1.mkdir(path.dirname(p), { recursive: true });
316
- await promises$1.writeFile(p, JSON.stringify(schema, null, 2) + "\n", "utf8");
317
- }
318
- function schemaToAuthors(schema) {
319
- return Object.entries(schema.coauthors).map(([key, v]) => new Author(key, v.name, v.email));
320
- }
321
- async function listAuthors(filter, cwd) {
322
- let schema;
323
- try {
324
- schema = await readAuthors(cwd);
325
- } catch {
326
- return [];
327
- }
328
- const all = schemaToAuthors(schema);
329
- if (!filter) return all;
330
- const f = filter.toLowerCase();
331
- return all.filter(
332
- (a) => a.key.toLowerCase().includes(f) || a.name.toLowerCase().includes(f) || a.email.toLowerCase().includes(f)
333
- );
334
- }
335
- async function addCoAuthor(author, cwd) {
336
- if (!validateEmail(author.email)) throw Errors.invalidEmail(author.email);
337
- let schema;
338
- try {
339
- schema = await readAuthors(cwd);
340
- } catch {
341
- schema = { coauthors: {} };
342
- }
343
- if (Object.prototype.hasOwnProperty.call(schema.coauthors, author.key)) {
344
- throw Errors.duplicateKey(author.key);
345
- }
346
- schema.coauthors[author.key] = { name: author.name, email: author.email };
347
- await writeAuthors(schema, cwd);
348
- }
349
-
350
372
  // src/core/git/config.ts
351
373
  function scopeArgs(scope) {
352
374
  return scope ? [`--${scope}`] : [];
@@ -373,6 +395,18 @@ async function unsetConfig(key, scope, cwd) {
373
395
  async function unsetAllConfig(key, scope, cwd) {
374
396
  await gitRaw(["config", ...scopeArgs(scope), "--unset-all", key], { cwd });
375
397
  }
398
+ async function insideWorkTree(cwd) {
399
+ const r = await gitRaw(["rev-parse", "--is-inside-work-tree"], { cwd });
400
+ return r.exitCode === 0 && r.stdout.trim() === "true";
401
+ }
402
+ async function topLevel(cwd) {
403
+ const r = await git(["rev-parse", "--show-toplevel"], { cwd });
404
+ return r.stdout.trim();
405
+ }
406
+ async function gitDir(cwd) {
407
+ const r = await git(["rev-parse", "--git-dir"], { cwd });
408
+ return path.resolve(cwd ?? process.cwd(), r.stdout.trim());
409
+ }
376
410
  function formatMessage(txt, authors) {
377
411
  const stripRe = new RegExp(`(\r
378
412
  |\r|
@@ -404,14 +438,14 @@ async function ensureCommitTemplate(cwd) {
404
438
  }
405
439
  async function readMsg(p) {
406
440
  try {
407
- return await promises$1.readFile(p, "utf8");
441
+ return await promises.readFile(p, "utf8");
408
442
  } catch {
409
443
  return "";
410
444
  }
411
445
  }
412
446
  async function writeMsg(p, txt) {
413
- await promises$1.mkdir(path.dirname(p), { recursive: true });
414
- await promises$1.writeFile(p, txt, "utf8");
447
+ await promises.mkdir(path.dirname(p), { recursive: true });
448
+ await promises.writeFile(p, txt, "utf8");
415
449
  }
416
450
  async function applyToTemplate(authors, cwd) {
417
451
  const [localTpl, firstTpl] = await Promise.all([
@@ -439,15 +473,11 @@ var LINE_RE = /^(.*)\s<([^>]+)>$/;
439
473
  async function getSelected(cwd) {
440
474
  const raw = (await getAllConfig(KEY, "local", cwd)).split(/\r?\n/).filter(Boolean);
441
475
  if (raw.length === 0) return [];
442
- const all = await listAuthors(void 0, cwd);
443
476
  const out = [];
444
477
  for (const line of raw) {
445
478
  const m = line.match(LINE_RE);
446
479
  if (!m) continue;
447
- const name = m[1].trim();
448
- const email = m[2].trim();
449
- const found = all.find((a) => a.email === email);
450
- out.push(found ?? new Author(email.split("@")[0] || "co", name, email));
480
+ out.push(new Author(m[2].split("@")[0] || "co", m[1].trim(), m[2].trim()));
451
481
  }
452
482
  return out;
453
483
  }
@@ -457,14 +487,9 @@ async function setSelected(authors, cwd) {
457
487
  await ensureCommitTemplate(cwd);
458
488
  await writeCoAuthorsToTemplate(authors, cwd);
459
489
  }
460
- async function clearSelected(cwd) {
461
- await unsetAllConfig(KEY, "local", cwd);
462
- await ensureCommitTemplate(cwd);
463
- await clearTemplate(cwd);
464
- }
465
490
 
466
491
  // src/core/git/shortlog.ts
467
- var SHORTLOG_LINE = /^\d+\t(.+)\s<(.+)>$/;
492
+ var SHORTLOG_LINE = /^\s*\d+\t(.+)\s<(.+)>$/;
468
493
  async function repoAuthors(filter, cwd) {
469
494
  const args = ["shortlog", "-seni", "HEAD"];
470
495
  if (filter) args.splice(1, 0, `--author=${filter}`);
@@ -480,180 +505,173 @@ async function repoAuthors(filter, cwd) {
480
505
  }
481
506
  return out;
482
507
  }
483
-
484
- // src/cli/coauthor.ts
485
508
  async function requireRepo(cwd) {
486
509
  if (!await insideWorkTree(cwd)) throw Errors.notARepo(cwd);
487
510
  }
488
- async function prompt(question) {
489
- const rl = promises.createInterface({ input: process.stdin, output: process.stderr });
511
+ async function identityAuthors() {
512
+ const { identities } = await listIdentities();
513
+ return identities.map((i) => ({
514
+ id: i.id,
515
+ author: new Author(genKey(i.name, i.email), i.name, i.email)
516
+ }));
517
+ }
518
+ async function resolveCoAuthor(arg) {
519
+ const all = await identityAuthors();
520
+ const lower = arg.toLowerCase();
521
+ const found = all.find(({ id, author }) => author.email.toLowerCase() === lower || id === arg);
522
+ if (!found) throw Errors.authorNotFound(arg);
523
+ return found.author;
524
+ }
525
+ var globalCoAuthorsPath = () => path.join(dataDir(), "global-coauthors.json");
526
+ async function readGlobal() {
490
527
  try {
491
- return (await rl.question(question)).trim();
492
- } finally {
493
- rl.close();
494
- }
495
- }
496
- async function ls(args, cwd) {
497
- const authors = await listAuthors(args[0], cwd);
498
- return ok(authors.map(authorToJson));
499
- }
500
- async function use(args, cwd) {
501
- await requireRepo(cwd);
502
- if (args.length === 0) {
503
- const selected2 = await getSelected(cwd);
504
- const data = { selected: selected2.map(authorToJson) };
505
- return selected2.length === 0 ? ok(data, [{ code: "empty", message: "no co-authors selected" }]) : ok(data);
506
- }
507
- const all = await listAuthors(void 0, cwd);
508
- const selected = [];
509
- for (const k of args) {
510
- const found = all.find((a) => a.key === k);
511
- if (!found) throw Errors.authorNotFound(k);
512
- selected.push(found);
513
- }
514
- await setSelected(selected, cwd);
515
- return ok({ selected: selected.map(authorToJson) });
516
- }
517
- async function solo(cwd) {
518
- await requireRepo(cwd);
519
- await clearSelected(cwd);
520
- return ok({ selected: [] });
521
- }
522
- async function print(opts, cwd) {
523
- const selected = await getSelected(cwd);
524
- const text = opts.initials ? selected.map((a) => a.key).join(",") : printTrailers(selected);
525
- return ok({ text });
526
- }
527
- async function add(args, cwd) {
528
- const [key, name, email] = args;
529
- if (!key || !name || !email) {
530
- throw Errors.usage('git colabor coauthor add <initials> "Name" <email>');
528
+ const txt = await promises.readFile(globalCoAuthorsPath(), "utf8");
529
+ const arr = JSON.parse(txt);
530
+ return arr.map((a) => new Author(genKey(a.name, a.email), a.name, a.email));
531
+ } catch {
532
+ return [];
531
533
  }
532
- if (!validateEmail(email)) throw Errors.invalidEmail(email);
533
- const author = new Author(key, name, email);
534
- await addCoAuthor(author, cwd);
535
- return ok({ author: authorToJson(author) });
536
534
  }
537
- async function suggest(args, cwd) {
538
- await requireRepo(cwd);
539
- const candidates = await repoAuthors(args[0], cwd);
540
- if (candidates.length === 0) {
541
- return ok({ candidates: [], added: [] }, [
542
- { code: "none", message: "no contributors found" }
543
- ]);
535
+ async function writeGlobal(authors) {
536
+ await promises.mkdir(dataDir(), { recursive: true });
537
+ await promises.writeFile(globalCoAuthorsPath(), JSON.stringify(authors.map((a) => ({ name: a.name, email: a.email })), null, 2) + "\n", "utf8");
538
+ }
539
+ async function setOneshot(authors, cwd) {
540
+ await unsetConfig("colabor.oneshot", "local", cwd);
541
+ for (const a of authors) {
542
+ await setConfig("colabor.oneshot", a.toString(), "local", cwd);
543
+ }
544
+ }
545
+ async function getOneshot(cwd) {
546
+ const raw = await getAllConfig("colabor.oneshot", "local", cwd);
547
+ if (!raw) return [];
548
+ return raw.split(/\r?\n/).filter(Boolean).map((line) => {
549
+ const m = line.match(/^(.*)\s<(.+)>$/);
550
+ return m ? new Author(genKey(m[1], m[2]), m[1], m[2]) : null;
551
+ }).filter((a) => !!a);
552
+ }
553
+ async function add(args, opts, cwd) {
554
+ const emailOrId = args[0];
555
+ if (!emailOrId) throw Errors.usage("git colabor coauthor add <email|id> [--always] [--global]");
556
+ const author = await resolveCoAuthor(emailOrId);
557
+ if (opts.global) {
558
+ const globals = await readGlobal();
559
+ if (!globals.some((a) => a.email.toLowerCase() === author.email.toLowerCase())) {
560
+ globals.push(author);
561
+ await writeGlobal(globals);
562
+ }
563
+ return ok({ added: { name: author.name, email: author.email }, mode: "global" });
544
564
  }
545
- return ok({ candidates: candidates.map(authorToJson), added: [] });
546
- }
547
- async function suggestInteractive(args, cwd) {
548
565
  await requireRepo(cwd);
549
- const candidates = await repoAuthors(args[0], cwd);
550
- if (candidates.length === 0) {
551
- process.stderr.write("No contributors found.\n");
552
- return ok({ added: [] });
553
- }
554
- process.stderr.write(
555
- candidates.map((a, i) => `[${i}] ${a.name} <${a.email}>`).join("\n") + "\n"
556
- );
557
- const answer = await prompt("Add which? (comma-separated numbers, blank to skip) ");
558
- const added = [];
559
- for (const part of answer.split(",")) {
560
- const idx = Number(part.trim());
561
- if (Number.isInteger(idx) && idx >= 0 && idx < candidates.length) {
562
- added.push(candidates[idx]);
566
+ if (opts.always) {
567
+ const current = await getSelected(cwd);
568
+ if (!current.some((a) => a.email.toLowerCase() === author.email.toLowerCase())) {
569
+ current.push(author);
570
+ await setSelected(current, cwd);
563
571
  }
572
+ return ok({ added: { name: author.name, email: author.email }, mode: "always" });
573
+ }
574
+ const oneshot = await getOneshot(cwd);
575
+ if (!oneshot.some((a) => a.email.toLowerCase() === author.email.toLowerCase())) {
576
+ oneshot.push(author);
577
+ await setOneshot(oneshot, cwd);
578
+ }
579
+ return ok({ added: { name: author.name, email: author.email }, mode: "oneshot" });
580
+ }
581
+ async function rm(args, cwd) {
582
+ const emailOrId = args[0];
583
+ if (!emailOrId) throw Errors.usage("git colabor coauthor rm <email|id>");
584
+ const target = await resolveCoAuthor(emailOrId);
585
+ const lower = target.email.toLowerCase();
586
+ const removedFrom = [];
587
+ const globals = await readGlobal();
588
+ const newGlobals = globals.filter((a) => a.email.toLowerCase() !== lower);
589
+ if (newGlobals.length !== globals.length) {
590
+ await writeGlobal(newGlobals);
591
+ removedFrom.push("global");
564
592
  }
565
- for (const a of added) {
566
- try {
567
- await addCoAuthor(a, cwd);
568
- } catch (e) {
569
- if (!(e instanceof AppError && e.code === "DUPLICATE_KEY")) throw e;
593
+ try {
594
+ await requireRepo(cwd);
595
+ const selected = await getSelected(cwd);
596
+ const newSelected = selected.filter((a) => a.email.toLowerCase() !== lower);
597
+ if (newSelected.length !== selected.length) {
598
+ await setSelected(newSelected, cwd);
599
+ removedFrom.push("repo");
570
600
  }
601
+ const oneshot = await getOneshot(cwd);
602
+ const newOneshot = oneshot.filter((a) => a.email.toLowerCase() !== lower);
603
+ if (newOneshot.length !== oneshot.length) {
604
+ await setOneshot(newOneshot, cwd);
605
+ removedFrom.push("oneshot");
606
+ }
607
+ } catch {
571
608
  }
572
- return ok({ added: added.map(authorToJson) });
573
- }
574
- function dataDir() {
575
- if (process.platform === "win32") {
576
- return path.join(process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"), "git-colabor");
577
- }
578
- return path.join(process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"), "git-colabor");
609
+ return ok({ removed: { name: target.name, email: target.email }, from: removedFrom });
579
610
  }
580
- function mapPath() {
581
- return process.env.GIT_COLABOR_MAP ?? path.join(dataDir(), "identities.json");
582
- }
583
- function keysDir() {
584
- return path.join(dataDir(), "keys");
585
- }
586
- function auditLogPath() {
587
- return process.env.GIT_COLABOR_AUDIT_FILE ?? path.join(dataDir(), "audit.log");
588
- }
589
- function keyFileName(fingerprint) {
590
- return fingerprint.replace(/[^A-Za-z0-9]+/g, "_") + ".key";
591
- }
592
- function keyFilePath(fingerprint) {
593
- return path.join(keysDir(), keyFileName(fingerprint));
594
- }
595
- async function atomicWriteJson(path$1, data, mode) {
596
- await promises$1.mkdir(path.dirname(path$1), { recursive: true });
597
- const tmp = `${path$1}.${crypto.randomBytes(4).toString("hex")}.tmp`;
598
- await promises$1.writeFile(tmp, JSON.stringify(data, null, 2) + "\n", "utf8");
599
- {
600
- await promises$1.chmod(tmp, mode).catch(() => {
601
- });
611
+ async function ls(args, cwd) {
612
+ const filter = args[0]?.toLowerCase();
613
+ const all = await identityAuthors();
614
+ 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 }));
615
+ const selected = [];
616
+ for (const a of await readGlobal()) {
617
+ selected.push({ name: a.name, email: a.email, mode: "global" });
602
618
  }
603
- await promises$1.rename(tmp, path$1);
604
- }
605
-
606
- // src/core/identity/map.ts
607
- function genId() {
608
- return "id_" + crypto.randomBytes(4).toString("hex");
609
- }
610
- async function readMap() {
611
619
  try {
612
- const txt = await promises$1.readFile(mapPath(), "utf8");
613
- const parsed = JSON.parse(txt);
614
- return {
615
- schemaVersion: 1,
616
- identities: parsed.identities ?? {},
617
- defaultIdentity: parsed.defaultIdentity
618
- };
620
+ for (const a of await getSelected(cwd)) {
621
+ if (!selected.some((s) => s.email === a.email)) {
622
+ selected.push({ name: a.name, email: a.email, mode: "repo" });
623
+ }
624
+ }
625
+ for (const a of await getOneshot(cwd)) {
626
+ if (!selected.some((s) => s.email === a.email)) {
627
+ selected.push({ name: a.name, email: a.email, mode: "oneshot" });
628
+ }
629
+ }
619
630
  } catch {
620
- return { schemaVersion: 1, identities: {} };
621
631
  }
632
+ return ok({ available, selected });
633
+ }
634
+ async function print(_opts, cwd) {
635
+ const active = [
636
+ ...await readGlobal(),
637
+ ...await getSelected(cwd).catch(() => []),
638
+ ...await getOneshot(cwd).catch(() => [])
639
+ ];
640
+ const seen = /* @__PURE__ */ new Set();
641
+ const deduped = active.filter((a) => {
642
+ const k = a.email.toLowerCase();
643
+ if (seen.has(k)) return false;
644
+ seen.add(k);
645
+ return true;
646
+ });
647
+ return ok({ text: printTrailers(deduped) });
622
648
  }
623
- async function writeMap(map) {
624
- await atomicWriteJson(mapPath(), map, 384);
625
- }
626
- async function getIdentity(id) {
627
- const map = await readMap();
628
- const found = map.identities[id];
629
- if (!found) throw Errors.usage(`identity "${id}" not found`);
630
- return found;
631
- }
632
- async function addIdentity(input) {
633
- const map = await readMap();
634
- const id = input.id ?? genId();
635
- if (map.identities[id]) throw Errors.usage(`identity "${id}" already exists`);
636
- const identity = { ...input, id, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
637
- map.identities[id] = identity;
638
- await writeMap(map);
639
- return identity;
640
- }
641
- async function removeIdentity(id) {
642
- const map = await readMap();
643
- if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
644
- delete map.identities[id];
645
- if (map.defaultIdentity === id) delete map.defaultIdentity;
646
- await writeMap(map);
647
- }
648
- async function setDefault(id) {
649
- const map = await readMap();
650
- if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
651
- map.defaultIdentity = id;
652
- await writeMap(map);
649
+ async function suggest(args, cwd) {
650
+ await requireRepo(cwd);
651
+ const candidates = await repoAuthors(args[0], cwd);
652
+ if (candidates.length === 0) {
653
+ return ok({ candidates: [], added: [] }, [{ code: "none", message: "no contributors found" }]);
654
+ }
655
+ return ok({ candidates: candidates.map((a) => ({ key: a.key, name: a.name, email: a.email })), added: [] });
653
656
  }
654
- async function listIdentities() {
655
- const map = await readMap();
656
- return { identities: Object.values(map.identities), defaultIdentity: map.defaultIdentity };
657
+
658
+ // src/core/git/committers.ts
659
+ async function historyCommitters(cwd) {
660
+ const r = await gitRaw(["log", "--format=%cn%x1f%ce"], { cwd });
661
+ if (r.exitCode !== 0) return [];
662
+ const counts = /* @__PURE__ */ new Map();
663
+ for (const line of r.stdout.split("\n")) {
664
+ const sep = line.indexOf("");
665
+ if (sep < 0) continue;
666
+ const name = line.slice(0, sep).trim();
667
+ const email = line.slice(sep + 1).trim();
668
+ if (!name || !email) continue;
669
+ const key = email.toLowerCase();
670
+ const cur = counts.get(key);
671
+ if (cur) cur.count++;
672
+ else counts.set(key, { name, email, count: 1 });
673
+ }
674
+ return [...counts.values()].sort((a, b) => b.count - a.count).map(({ name, email }) => ({ name, email }));
657
675
  }
658
676
  var FP_RE = /SHA256:[A-Za-z0-9+/=]+/;
659
677
  async function fingerprintOfFile(path) {
@@ -672,34 +690,18 @@ async function isEncrypted(path) {
672
690
  const r = await runBin("ssh-keygen", ["-y", "-P", "", "-f", path]);
673
691
  return r.exitCode !== 0;
674
692
  }
675
- async function restrictKeyPerms(path) {
676
- if (process.platform === "win32") {
677
- const user = process.env.USERNAME ?? process.env.USER ?? "";
678
- if (user) {
679
- await runBin("icacls", [path, "/inheritance:r", "/grant:r", `${user}:(R,W)`]).catch(() => {
680
- });
681
- }
682
- return;
693
+ async function keyUsable(path) {
694
+ try {
695
+ await fingerprintOfFile(path);
696
+ return true;
697
+ } catch {
698
+ return false;
683
699
  }
684
- await promises$1.chmod(path, 384).catch(() => {
685
- });
686
- }
687
- async function materializeKey(privateKeyPem) {
688
- await promises$1.mkdir(keysDir(), { recursive: true });
689
- const tmp = path.join(keysDir(), `.import.${crypto.randomBytes(4).toString("hex")}`);
690
- await promises$1.writeFile(tmp, privateKeyPem.endsWith("\n") ? privateKeyPem : privateKeyPem + "\n", "utf8");
691
- await restrictKeyPerms(tmp);
692
- const fingerprint = await fingerprintOfFile(tmp);
693
- const dest = keyFilePath(fingerprint);
694
- await promises$1.rename(tmp, dest);
695
- await restrictKeyPerms(dest);
696
- return { path: dest, fingerprint };
697
700
  }
698
701
  async function importKey(sourcePath) {
699
- const pem = await promises$1.readFile(sourcePath, "utf8");
700
- const { path, fingerprint } = await materializeKey(pem);
701
- const encrypted = await isEncrypted(path);
702
- return { path, fingerprint, encrypted };
702
+ const fingerprint = await fingerprintOfFile(sourcePath);
703
+ const encrypted = await isEncrypted(sourcePath);
704
+ return { path: path.resolve(sourcePath), fingerprint, encrypted };
703
705
  }
704
706
  async function statePath(cwd) {
705
707
  return path.join(await gitDir(cwd), "colabor", "state.json");
@@ -707,7 +709,7 @@ async function statePath(cwd) {
707
709
  async function readState(cwd) {
708
710
  try {
709
711
  const p = await statePath(cwd);
710
- const txt = await promises$1.readFile(p, "utf8");
712
+ const txt = await promises.readFile(p, "utf8");
711
713
  return JSON.parse(txt);
712
714
  } catch {
713
715
  return { schemaVersion: 1 };
@@ -718,13 +720,16 @@ async function writeState(state, cwd) {
718
720
  await atomicWriteJson(p, state, 384);
719
721
  }
720
722
  async function readCurrentIdentityConfig(cwd) {
721
- const [userName, userEmail, sshCommand, commitTemplate] = await Promise.all([
723
+ const [userName, userEmail, sshCommand, commitTemplate, commitGpgsign, gpgFormat, signingKey] = await Promise.all([
722
724
  getConfig("user.name", "local", cwd),
723
725
  getConfig("user.email", "local", cwd),
724
726
  getConfig("core.sshCommand", "local", cwd),
725
- getConfig("commit.template", "local", cwd)
727
+ getConfig("commit.template", "local", cwd),
728
+ getConfig("commit.gpgsign", "local", cwd),
729
+ getConfig("gpg.format", "local", cwd),
730
+ getConfig("user.signingKey", "local", cwd)
726
731
  ]);
727
- return { userName, userEmail, sshCommand, commitTemplate };
732
+ return { userName, userEmail, sshCommand, commitTemplate, commitGpgsign, gpgFormat, signingKey };
728
733
  }
729
734
  async function captureBackupIfFirstTouch(cwd) {
730
735
  const managed = await getConfig("colabor.managed", "local", cwd);
@@ -774,16 +779,16 @@ async function appendAudit(input) {
774
779
  };
775
780
  const file = auditLogPath();
776
781
  try {
777
- await promises$1.mkdir(path.dirname(file), { recursive: true });
778
- await promises$1.appendFile(file, JSON.stringify(entry) + "\n", "utf8");
779
- await promises$1.chmod(file, 384).catch(() => {
782
+ await promises.mkdir(path.dirname(file), { recursive: true });
783
+ await promises.appendFile(file, JSON.stringify(entry) + "\n", "utf8");
784
+ await promises.chmod(file, 384).catch(() => {
780
785
  });
781
786
  } catch {
782
787
  }
783
788
  }
784
789
  async function readAudit(opts = {}) {
785
790
  try {
786
- const txt = await promises$1.readFile(auditLogPath(), "utf8");
791
+ const txt = await promises.readFile(auditLogPath(), "utf8");
787
792
  let entries = txt.split(/\r?\n/).filter(Boolean).map((l) => JSON.parse(l));
788
793
  if (opts.repo) entries = entries.filter((e) => e.repo === opts.repo);
789
794
  if (opts.since) {
@@ -801,10 +806,27 @@ function runInherit(cmdArgs, env, stdinNull = false) {
801
806
  const [cmd, ...args] = cmdArgs;
802
807
  const child = child_process.spawn(cmd, args, {
803
808
  env: env ?? process.env,
804
- stdio: [stdinNull ? "ignore" : "inherit", "inherit", "pipe"]
809
+ stdio: [stdinNull ? "ignore" : "inherit", "inherit", "pipe"],
810
+ detached: false
811
+ // keep setsid children in our process group so the kill timer can reach them
812
+ });
813
+ const killTimer = setTimeout(() => {
814
+ child.kill("SIGKILL");
815
+ if (child.pid) {
816
+ try {
817
+ process.kill(-child.pid, "SIGKILL");
818
+ } catch {
819
+ }
820
+ }
821
+ }, 1e4);
822
+ child.on("error", () => {
823
+ clearTimeout(killTimer);
824
+ resolve4(127);
825
+ });
826
+ child.on("close", (c) => {
827
+ clearTimeout(killTimer);
828
+ resolve4(c ?? 127);
805
829
  });
806
- child.on("error", () => resolve4(127));
807
- child.on("close", (c) => resolve4(c ?? 127));
808
830
  });
809
831
  }
810
832
  function hasBin(bin) {
@@ -833,11 +855,11 @@ async function loadKey(opts) {
833
855
  if (!fs.existsSync(opts.keyPath)) return { loaded: false, via: "none", message: "key file missing" };
834
856
  let code = await runInherit(["ssh-add", opts.keyPath], void 0, !process.stdin.isTTY);
835
857
  if (code === 0) return { loaded: true, via: "plain" };
836
- if (await supportsAppleKeychain()) {
858
+ if (opts.useAppleKeychain && await supportsAppleKeychain()) {
837
859
  code = await runInherit(["ssh-add", "--apple-use-keychain", opts.keyPath]);
838
860
  if (code === 0) return { loaded: true, via: "apple-keychain" };
839
861
  }
840
- const haveSource = opts.socketPath && opts.token || opts.passphraseCommand;
862
+ const haveSource = opts.socketPath && opts.token;
841
863
  if (opts.askpassScriptPath && haveSource) {
842
864
  const env = { ...process.env };
843
865
  env.SSH_ASKPASS = opts.askpassScriptPath;
@@ -845,12 +867,18 @@ async function loadKey(opts) {
845
867
  env.DISPLAY = env.DISPLAY ?? ":0";
846
868
  if (opts.socketPath) env.GIT_COLABOR_ASKPASS_SOCK = opts.socketPath;
847
869
  if (opts.token) env.GIT_COLABOR_ASKPASS_TOKEN = opts.token;
848
- if (opts.passphraseCommand) env.GIT_COLABOR_PASSPHRASE_COMMAND = opts.passphraseCommand;
849
870
  env.GIT_COLABOR_FINGERPRINT = opts.fingerprint;
850
871
  const useSetsid = process.platform !== "win32" && hasBin("setsid");
851
872
  code = await runInherit(useSetsid ? ["setsid", "ssh-add", opts.keyPath] : ["ssh-add", opts.keyPath], env, true);
852
873
  if (code === 0) return { loaded: true, via: "askpass" };
853
- return { loaded: false, via: "askpass", message: `ssh-add exited ${code}` };
874
+ if (await verifyKey(opts)) {
875
+ return {
876
+ loaded: true,
877
+ via: "keygen-verify",
878
+ message: "passphrase verified (no ssh-agent \u2014 the key unlocks at ssh time via SSH_ASKPASS)"
879
+ };
880
+ }
881
+ return { loaded: false, via: "askpass", message: "passphrase rejected" };
854
882
  }
855
883
  if (process.stdin.isTTY) {
856
884
  code = await runInherit(["ssh-add", opts.keyPath]);
@@ -862,12 +890,48 @@ async function loadKey(opts) {
862
890
  async function listAgent() {
863
891
  return runBinQuiet("ssh-add", ["-l"]);
864
892
  }
893
+ async function agentFingerprints() {
894
+ const out = await listAgent();
895
+ const prints = /* @__PURE__ */ new Set();
896
+ for (const line of out.split("\n")) {
897
+ const tok = line.trim().split(/\s+/)[1];
898
+ if (tok?.startsWith("SHA256:")) prints.add(tok);
899
+ }
900
+ return prints;
901
+ }
902
+ async function keyInAgent(fingerprint) {
903
+ return (await agentFingerprints()).has(fingerprint);
904
+ }
865
905
  async function removeKey(keyPath) {
866
906
  const code = await runInherit(["ssh-add", "-d", keyPath], void 0, true);
867
907
  return code === 0;
868
908
  }
869
-
870
- // src/core/identity/apply.ts
909
+ async function verifyKey(opts) {
910
+ if (!opts.askpassScriptPath || !(opts.socketPath && opts.token)) return false;
911
+ const env = { ...process.env };
912
+ env.SSH_ASKPASS = opts.askpassScriptPath;
913
+ env.SSH_ASKPASS_REQUIRE = "force";
914
+ env.DISPLAY = env.DISPLAY ?? ":0";
915
+ env.GIT_COLABOR_ASKPASS_SOCK = opts.socketPath;
916
+ env.GIT_COLABOR_ASKPASS_TOKEN = opts.token;
917
+ env.GIT_COLABOR_FINGERPRINT = opts.fingerprint;
918
+ const verifyQuiet = (args) => new Promise((resolve4) => {
919
+ const child = child_process.spawn("ssh-keygen", args, { env, stdio: ["ignore", "pipe", "pipe"] });
920
+ const killTimer = setTimeout(() => child.kill("SIGKILL"), 1e4);
921
+ child.on("error", () => {
922
+ clearTimeout(killTimer);
923
+ resolve4(127);
924
+ });
925
+ child.on("close", (c) => {
926
+ clearTimeout(killTimer);
927
+ resolve4(c ?? 127);
928
+ });
929
+ });
930
+ const verify = await verifyQuiet(["-y", "-P", "", "-f", opts.keyPath]).then(
931
+ (c) => c === 0 ? Promise.resolve(0) : verifyQuiet(["-y", "-f", opts.keyPath])
932
+ );
933
+ return verify === 0;
934
+ }
871
935
  async function safeTopLevel(cwd) {
872
936
  try {
873
937
  return await topLevel(cwd);
@@ -875,6 +939,102 @@ async function safeTopLevel(cwd) {
875
939
  return void 0;
876
940
  }
877
941
  }
942
+ async function ensureSignWrapper(askpassScriptPath) {
943
+ const wrapperPath = path.join(dataDir(), "sign-wrapper.sh");
944
+ const askpass = askpassScriptPath ? await ensureAskpassWrapper(askpassScriptPath) : path.join(dataDir(), "askpass-wrapper.sh");
945
+ const content = [
946
+ "#!/bin/sh",
947
+ "# extract -f <key> so the askpass helper can fingerprint it even when",
948
+ '# the prompt carries no key path (bare "Enter passphrase:" on some OpenSSH)',
949
+ "signkey=",
950
+ "prev=",
951
+ 'for a in "$@"; do',
952
+ ' if [ "$prev" = "-f" ]; then signkey="$a"; break; fi',
953
+ ' prev="$a"',
954
+ "done",
955
+ `SSH_ASKPASS="${askpass}" SSH_ASKPASS_REQUIRE=force DISPLAY=:0 GIT_COLABOR_SIGNING_KEY="$signkey" exec ssh-keygen "$@"`,
956
+ ""
957
+ ].join("\n");
958
+ if (fs.existsSync(wrapperPath)) {
959
+ const existing = await promises.readFile(wrapperPath, "utf8");
960
+ if (existing === content) return wrapperPath;
961
+ }
962
+ await promises.writeFile(wrapperPath, content, { mode: 448 });
963
+ await promises.chmod(wrapperPath, 448);
964
+ return wrapperPath;
965
+ }
966
+ async function signingKeyPath(sshKeyPath, fingerprint) {
967
+ if (fingerprint && await keyInAgent(fingerprint)) {
968
+ const pub = `${sshKeyPath}.pub`;
969
+ if (fs.existsSync(pub)) return pub;
970
+ }
971
+ return sshKeyPath;
972
+ }
973
+ async function setCommitSigning(opts) {
974
+ if (!await insideWorkTree(opts.cwd)) throw Errors.notARepo(opts.cwd);
975
+ const state = await readState(opts.cwd);
976
+ if (!opts.on) {
977
+ state.signing = false;
978
+ await writeState(state, opts.cwd);
979
+ await unsetConfig("commit.gpgsign", "local", opts.cwd);
980
+ await unsetConfig("gpg.format", "local", opts.cwd);
981
+ await unsetConfig("user.signingKey", "local", opts.cwd);
982
+ await unsetConfig("gpg.ssh.program", "local", opts.cwd);
983
+ await appendAudit({ action: "identity.sign", source: opts.source, identity: opts.id, repo: await safeTopLevel(opts.cwd), result: "ok", message: "signing off" });
984
+ return { signing: false };
985
+ }
986
+ const identity = await getIdentity(opts.id);
987
+ if (!identity.sshKeyPath || !await keyUsable(identity.sshKeyPath)) {
988
+ throw Errors.usage(`identity "${identity.name}" has no usable key to sign with`);
989
+ }
990
+ state.signing = true;
991
+ await writeState(state, opts.cwd);
992
+ await setConfig("commit.gpgsign", "true", "local", opts.cwd);
993
+ await setConfig("gpg.format", "ssh", "local", opts.cwd);
994
+ await setConfig("user.signingKey", await signingKeyPath(identity.sshKeyPath, identity.sshKeyFingerprint), "local", opts.cwd);
995
+ if (opts.askpassScriptPath) {
996
+ const signWrapper = await ensureSignWrapper(opts.askpassScriptPath);
997
+ await setConfig("gpg.ssh.program", signWrapper, "local", opts.cwd);
998
+ }
999
+ await appendAudit({
1000
+ action: "identity.sign",
1001
+ source: opts.source,
1002
+ identity: opts.id,
1003
+ identityName: identity.name,
1004
+ fingerprint: identity.sshKeyFingerprint,
1005
+ repo: await safeTopLevel(opts.cwd),
1006
+ result: "ok",
1007
+ message: "signing on"
1008
+ });
1009
+ return { signing: true, key: identity.sshKeyPath };
1010
+ }
1011
+ function discoverSessionBridges() {
1012
+ try {
1013
+ const dir = dataDir();
1014
+ 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);
1015
+ const out = [];
1016
+ for (const s of sessions) {
1017
+ try {
1018
+ const parsed = JSON.parse(fs.readFileSync(path.join(dir, s.f), "utf8"));
1019
+ if (parsed.socketPath && parsed.token) out.push({ socketPath: parsed.socketPath, token: parsed.token });
1020
+ } catch {
1021
+ }
1022
+ }
1023
+ return out;
1024
+ } catch {
1025
+ return [];
1026
+ }
1027
+ }
1028
+ function discoverSessionBridge() {
1029
+ return discoverSessionBridges()[0];
1030
+ }
1031
+ async function safeTopLevel2(cwd) {
1032
+ try {
1033
+ return await topLevel(cwd);
1034
+ } catch {
1035
+ return void 0;
1036
+ }
1037
+ }
878
1038
  async function applyResolvedIdentity(args) {
879
1039
  const { name, email, sshCommand, identity, opts } = args;
880
1040
  const session = opts.session ?? (opts.source === "cli" ? cliSessionId() : "ext:unknown");
@@ -896,16 +1056,20 @@ async function applyResolvedIdentity(args) {
896
1056
  const state = await readState(opts.cwd);
897
1057
  state.activeIdentity = identity?.id;
898
1058
  state.heldBy = nowHeldBy(session, opts.source);
1059
+ if (state.signing === true && identity?.sshKeyPath && sshCommand) {
1060
+ await setConfig("commit.gpgsign", "true", "local", opts.cwd);
1061
+ await setConfig("gpg.format", "ssh", "local", opts.cwd);
1062
+ const pub = `${identity.sshKeyPath}.pub`;
1063
+ const viaAgent = !!identity.sshKeyFingerprint && await keyInAgent(identity.sshKeyFingerprint) && fs.existsSync(pub);
1064
+ await setConfig("user.signingKey", viaAgent ? pub : identity.sshKeyPath, "local", opts.cwd);
1065
+ if (opts.askpassScriptPath) {
1066
+ await setConfig("gpg.ssh.program", await ensureSignWrapper(opts.askpassScriptPath), "local", opts.cwd);
1067
+ }
1068
+ }
899
1069
  await writeState(state, opts.cwd);
900
- let keyLoaded;
901
- if (identity?.sshKeyPath && identity.sshKeyFingerprint) {
902
- keyLoaded = await loadKey({
903
- keyPath: identity.sshKeyPath,
904
- fingerprint: identity.sshKeyFingerprint,
905
- askpassScriptPath: opts.askpassScriptPath,
906
- socketPath: opts.socketPath,
907
- token: opts.token,
908
- passphraseCommand: identity.passphraseCommand});
1070
+ let agent;
1071
+ if (identity?.sshKeyFingerprint) {
1072
+ agent = { inAgent: await keyInAgent(identity.sshKeyFingerprint) };
909
1073
  }
910
1074
  await appendAudit({
911
1075
  action: "identity.use",
@@ -913,27 +1077,70 @@ async function applyResolvedIdentity(args) {
913
1077
  identity: identity?.id,
914
1078
  identityName: identity?.name ?? name,
915
1079
  fingerprint: identity?.sshKeyFingerprint,
916
- repo: await safeTopLevel(opts.cwd),
1080
+ repo: await safeTopLevel2(opts.cwd),
917
1081
  result: conflict ? "warn" : "ok",
918
1082
  message: conflict ? `overrode ${conflict.heldBy.session}` : void 0
919
1083
  });
920
- return { name, email, sshCommand, conflict, keyLoaded };
1084
+ return { name, email, sshCommand, conflict, agent };
1085
+ }
1086
+ async function ensureAskpassWrapper(askpassScriptPath) {
1087
+ const wrapperPath = path.join(dataDir(), "askpass-wrapper.sh");
1088
+ const content = `#!/bin/sh
1089
+ exec "${process.execPath}" "${askpassScriptPath}" "$@"
1090
+ `;
1091
+ try {
1092
+ const existing = await promises.readFile(wrapperPath, "utf8");
1093
+ if (existing === content) return wrapperPath;
1094
+ } catch {
1095
+ }
1096
+ await promises.writeFile(wrapperPath, content, { mode: 448 });
1097
+ await promises.chmod(wrapperPath, 448);
1098
+ return wrapperPath;
921
1099
  }
922
1100
  async function applyIdentity(id, opts) {
923
- const identity = await getIdentity(id);
924
- const sshCommand = identity.sshKeyPath ? `ssh -i ${identity.sshKeyPath} -o IdentitiesOnly=yes` : void 0;
1101
+ let identity = await getIdentity(id);
1102
+ let sshCommand;
1103
+ let bridgeUsed = false;
1104
+ let keyMissing = false;
1105
+ if (identity.sshKeyPath) {
1106
+ let imp;
1107
+ try {
1108
+ imp = await importKey(identity.sshKeyPath);
1109
+ } catch {
1110
+ imp = void 0;
1111
+ }
1112
+ if (imp) {
1113
+ if (imp.fingerprint !== identity.sshKeyFingerprint || imp.encrypted !== !!identity.sshKeyEncrypted) {
1114
+ await updateIdentity(id, { sshKeyFingerprint: imp.fingerprint, sshKeyEncrypted: imp.encrypted });
1115
+ identity = { ...identity, sshKeyFingerprint: imp.fingerprint, sshKeyEncrypted: imp.encrypted };
1116
+ }
1117
+ const bare = `ssh -i ${identity.sshKeyPath} -o IdentitiesOnly=yes`;
1118
+ const bridge = opts.socketPath && opts.token || discoverSessionBridge();
1119
+ if (opts.askpassScriptPath && bridge) {
1120
+ const wrapper = await ensureAskpassWrapper(opts.askpassScriptPath);
1121
+ sshCommand = `SSH_ASKPASS="${wrapper}" SSH_ASKPASS_REQUIRE=force DISPLAY=:0 ${bare}`;
1122
+ bridgeUsed = true;
1123
+ } else {
1124
+ sshCommand = bare;
1125
+ }
1126
+ } else {
1127
+ keyMissing = true;
1128
+ }
1129
+ }
925
1130
  const result = await applyResolvedIdentity({
926
1131
  name: opts.asName ?? identity.name,
927
1132
  email: opts.asEmail ?? identity.email,
928
1133
  sshCommand,
929
- identity,
1134
+ identity: keyMissing ? { ...identity, sshKeyPath: void 0 } : identity,
930
1135
  opts
931
1136
  });
1137
+ result.keyMissing = keyMissing;
1138
+ result.bridgeUsed = bridgeUsed;
932
1139
  return { identity, result };
933
1140
  }
934
1141
 
935
1142
  // src/core/identity/revert.ts
936
- async function safeTopLevel2(cwd) {
1143
+ async function safeTopLevel3(cwd) {
937
1144
  try {
938
1145
  return await topLevel(cwd);
939
1146
  } catch {
@@ -953,6 +1160,9 @@ async function revertRepo(opts) {
953
1160
  await restoreKey("user.email", backups.userEmail, opts.cwd);
954
1161
  await restoreKey("core.sshCommand", backups.sshCommand, opts.cwd);
955
1162
  await restoreKey("commit.template", backups.commitTemplate, opts.cwd);
1163
+ await restoreKey("commit.gpgsign", backups.commitGpgsign, opts.cwd);
1164
+ await restoreKey("gpg.format", backups.gpgFormat, opts.cwd);
1165
+ await restoreKey("user.signingKey", backups.signingKey, opts.cwd);
956
1166
  }
957
1167
  if (state.activeIdentity) {
958
1168
  try {
@@ -973,31 +1183,21 @@ async function revertRepo(opts) {
973
1183
  await appendAudit({
974
1184
  action: "identity.revert",
975
1185
  source: opts.source,
976
- repo: await safeTopLevel2(opts.cwd),
1186
+ repo: await safeTopLevel3(opts.cwd),
977
1187
  result: managed === "true" ? "ok" : "warn",
978
1188
  message: managed === "true" ? void 0 : "repo was not managed"
979
1189
  });
980
1190
  return { restored: backups, hadBackup: !!backups };
981
1191
  }
982
- async function safeTopLevel3(cwd) {
1192
+
1193
+ // src/core/identity/logout.ts
1194
+ async function safeTopLevel4(cwd) {
983
1195
  try {
984
1196
  return await topLevel(cwd);
985
1197
  } catch {
986
1198
  return void 0;
987
1199
  }
988
1200
  }
989
- async function shred(path) {
990
- if (process.platform !== "win32") {
991
- const r = child_process.spawnSync("shred", ["-u", path]);
992
- if (r.status === 0) return true;
993
- }
994
- try {
995
- await promises$1.unlink(path);
996
- return true;
997
- } catch {
998
- return false;
999
- }
1000
- }
1001
1201
  async function logoutIdentity(opts) {
1002
1202
  const state = await readState(opts.cwd);
1003
1203
  let id = opts.id ?? state.activeIdentity;
@@ -1007,15 +1207,17 @@ async function logoutIdentity(opts) {
1007
1207
  else throw Errors.usage("no active identity \u2014 specify one: git colabor identity logout <id>");
1008
1208
  }
1009
1209
  const identity = await getIdentity(id);
1010
- let agentRemoved = false;
1011
- let keyfileShredded = false;
1012
- if (identity.sshKeyPath) {
1013
- agentRemoved = await removeKey(identity.sshKeyPath);
1014
- keyfileShredded = await shred(identity.sshKeyPath);
1015
- }
1210
+ const agentRemoved = identity.sshKeyPath ? await removeKey(identity.sshKeyPath) : false;
1016
1211
  if (state.activeIdentity === identity.id) {
1017
1212
  state.activeIdentity = void 0;
1018
1213
  state.heldBy = void 0;
1214
+ if (state.signing === true) {
1215
+ state.signing = false;
1216
+ await unsetConfig("commit.gpgsign", "local", opts.cwd);
1217
+ await unsetConfig("gpg.format", "local", opts.cwd);
1218
+ await unsetConfig("user.signingKey", "local", opts.cwd);
1219
+ await unsetConfig("gpg.ssh.program", "local", opts.cwd);
1220
+ }
1019
1221
  await writeState(state, opts.cwd);
1020
1222
  }
1021
1223
  await appendAudit({
@@ -1024,12 +1226,11 @@ async function logoutIdentity(opts) {
1024
1226
  identity: identity.id,
1025
1227
  identityName: identity.name,
1026
1228
  fingerprint: identity.sshKeyFingerprint,
1027
- repo: await safeTopLevel3(opts.cwd)
1229
+ repo: await safeTopLevel4(opts.cwd)
1028
1230
  });
1029
1231
  return {
1030
1232
  identity: { id: identity.id, name: identity.name, fingerprint: identity.sshKeyFingerprint },
1031
- agentRemoved,
1032
- keyfileShredded
1233
+ agentRemoved
1033
1234
  };
1034
1235
  }
1035
1236
 
@@ -1048,15 +1249,15 @@ async function repoStatus(cwd) {
1048
1249
  available: []
1049
1250
  };
1050
1251
  }
1051
- const [managed, managedBy, state, selected] = await Promise.all([
1252
+ const [managed, managedBy, state, selected, identityMap] = await Promise.all([
1052
1253
  getConfig("colabor.managed", "local", cwd),
1053
1254
  getConfig("colabor.managed-by", "local", cwd),
1054
1255
  readState(cwd),
1055
- getSelected(cwd)
1256
+ getSelected(cwd),
1257
+ listIdentities()
1056
1258
  ]);
1057
- const allAuthors = await listAuthors(void 0, cwd);
1058
1259
  const selectedEmails = new Set(selected.map((a) => a.email));
1059
- const available = allAuthors.filter((a) => !selectedEmails.has(a.email)).map(toBrief);
1260
+ const available = identityMap.identities.filter((i) => !selectedEmails.has(i.email)).map((i) => ({ key: genKey(i.name, i.email), name: i.name, email: i.email }));
1060
1261
  return {
1061
1262
  inRepo: true,
1062
1263
  repo: cwd,
@@ -1075,38 +1276,73 @@ function toBrief(a) {
1075
1276
  // src/cli/identity.ts
1076
1277
  var USE_SPEC = { valueFlags: ["--source", "--as-name", "--as-email"], boolFlags: ["--no-override"] };
1077
1278
  var ADD_SPEC = {
1078
- valueFlags: ["--name", "--email", "--key", "--passphrase-command", "--host", "--source"],
1279
+ valueFlags: ["--name", "--email", "--key", "--host", "--source"],
1079
1280
  boolFlags: ["--default", "--no-encrypt"]
1080
1281
  };
1081
1282
  var AUDIT_SPEC = { valueFlags: ["--repo", "--since", "--tail"] };
1082
1283
  var APPLY_SPEC = { valueFlags: ["--name", "--email", "--ssh-command", "--source"] };
1083
- function identityToJson(i, defaultId) {
1284
+ var SET_SPEC = { valueFlags: ["--name", "--email", "--key", "--scope"], boolFlags: ["--no-key"] };
1285
+ var SIGN_SPEC = { valueFlags: [], boolFlags: ["--off"] };
1286
+ var AGENT_SPEC = { valueFlags: [], boolFlags: ["--remove", "--verify"] };
1287
+ function identityToJson(i, defaultId, agentPrints) {
1084
1288
  return {
1085
1289
  id: i.id,
1086
1290
  name: i.name,
1087
1291
  email: i.email,
1088
1292
  sshKeyFingerprint: i.sshKeyFingerprint,
1089
1293
  host: i.host,
1090
- hasKey: !!i.sshKeyPath,
1294
+ // reference mode: a key counts only while the referenced file is still there
1295
+ hasKey: !!i.sshKeyPath && fs.existsSync(i.sshKeyPath),
1296
+ sshKeyPath: i.sshKeyPath,
1297
+ keyEncrypted: !!i.sshKeyEncrypted,
1298
+ /** key fingerprint currently held by ssh-agent (live check, one listAgent per call) */
1299
+ inAgent: !!i.sshKeyFingerprint && (agentPrints?.has(i.sshKeyFingerprint) ?? false),
1300
+ imported: !!i.imported,
1301
+ disabled: !!i.disabled,
1302
+ scope: i.scope ?? (i.imported ? "project" : "machine"),
1303
+ remoteKeys: i.remoteKeys,
1091
1304
  isDefault: i.id === defaultId
1092
1305
  };
1093
1306
  }
1094
1307
  function asSource(v) {
1095
1308
  return v === "ext" ? "ext" : "cli";
1096
1309
  }
1310
+ async function safeTopLevel5(cwd) {
1311
+ try {
1312
+ return await topLevel(cwd);
1313
+ } catch {
1314
+ return void 0;
1315
+ }
1316
+ }
1097
1317
  async function dispatch(command, tokens, ctx) {
1098
1318
  switch (command) {
1099
1319
  case void 0:
1100
1320
  case "ls":
1101
1321
  return ls2();
1102
1322
  case "use":
1103
- return use2(parseCommandArgs(tokens, USE_SPEC), ctx);
1323
+ return use(parseCommandArgs(tokens, USE_SPEC), ctx);
1104
1324
  case "add":
1105
1325
  return add2(parseCommandArgs(tokens, ADD_SPEC));
1326
+ case "import":
1327
+ return importFromHistory(ctx);
1328
+ case "set":
1329
+ return setIdentity(parseCommandArgs(tokens, SET_SPEC));
1330
+ case "sign":
1331
+ return sign(parseCommandArgs(tokens, SIGN_SPEC), ctx);
1332
+ case "disable":
1333
+ return disable(parseCommandArgs(tokens), ctx);
1334
+ case "unhide":
1335
+ return unhide(parseCommandArgs(tokens));
1336
+ case "hidden":
1337
+ return hiddenLs();
1106
1338
  case "rm":
1107
- return rm(parseCommandArgs(tokens), ctx);
1339
+ return rm2(parseCommandArgs(tokens), ctx);
1108
1340
  case "logout":
1109
1341
  return logout(parseCommandArgs(tokens), ctx);
1342
+ case "agent":
1343
+ return agentKey(parseCommandArgs(tokens, AGENT_SPEC), ctx);
1344
+ case "hide":
1345
+ return hideIdentityCmd(parseCommandArgs(tokens));
1110
1346
  case "audit":
1111
1347
  return audit(parseCommandArgs(tokens, AUDIT_SPEC));
1112
1348
  case "doctor":
@@ -1123,11 +1359,86 @@ async function dispatch(command, tokens, ctx) {
1123
1359
  }
1124
1360
  async function ls2() {
1125
1361
  const { identities, defaultIdentity } = await listIdentities();
1126
- return ok({ identities: identities.map((i) => identityToJson(i, defaultIdentity)), defaultIdentity });
1362
+ const prints = await agentFingerprints();
1363
+ const hidden = new Set(await listHiddenEmails());
1364
+ const visible = identities.filter((i) => !hidden.has(i.email.toLowerCase()));
1365
+ return ok({ identities: visible.map((i) => identityToJson(i, defaultIdentity, prints)), defaultIdentity });
1366
+ }
1367
+ async function hideIdentityCmd(p) {
1368
+ const email = p.positionals[0];
1369
+ if (!email) throw Errors.usage("git colabor identity hide <email>");
1370
+ await hideIdentityEmail(email);
1371
+ await appendAudit({
1372
+ action: "identity.hide",
1373
+ source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
1374
+ message: email.toLowerCase()
1375
+ });
1376
+ return ok({ hidden: email.toLowerCase() });
1377
+ }
1378
+ async function agentKey(p, ctx) {
1379
+ const id = p.positionals[0];
1380
+ if (!id) throw Errors.usage("git colabor identity agent <id> [--remove | --verify]");
1381
+ const identity = await getIdentity(id);
1382
+ if (!identity.sshKeyPath || !identity.sshKeyFingerprint) {
1383
+ throw Errors.usage(`identity "${id}" has no SSH key`);
1384
+ }
1385
+ const remove = p.bools.has("--remove");
1386
+ const verify = p.bools.has("--verify");
1387
+ if (remove && verify) throw Errors.usage("--remove and --verify are mutually exclusive");
1388
+ if (remove) {
1389
+ const removed = await removeKey(identity.sshKeyPath);
1390
+ await appendAudit({
1391
+ action: "key.remove",
1392
+ source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
1393
+ identity: id,
1394
+ identityName: identity.name,
1395
+ fingerprint: identity.sshKeyFingerprint
1396
+ });
1397
+ return ok({ removed, inAgent: await keyInAgent(identity.sshKeyFingerprint) }, removed ? [] : [
1398
+ { code: "not-in-agent", message: "key was not loaded in ssh-agent" }
1399
+ ]);
1400
+ }
1401
+ const askpassScriptPath = ctx.askpassScriptPath ? await ensureAskpassWrapper(ctx.askpassScriptPath) : void 0;
1402
+ if (verify) {
1403
+ const verified = await verifyKey({
1404
+ keyPath: identity.sshKeyPath,
1405
+ fingerprint: identity.sshKeyFingerprint,
1406
+ askpassScriptPath,
1407
+ socketPath: ctx.socketPath,
1408
+ token: ctx.token
1409
+ });
1410
+ return ok({ verified, inAgent: await keyInAgent(identity.sshKeyFingerprint) });
1411
+ }
1412
+ const loaded = await loadKey({
1413
+ keyPath: identity.sshKeyPath,
1414
+ fingerprint: identity.sshKeyFingerprint,
1415
+ askpassScriptPath,
1416
+ socketPath: ctx.socketPath,
1417
+ token: ctx.token,
1418
+ useAppleKeychain: true
1419
+ });
1420
+ if (loaded.loaded) {
1421
+ await appendAudit({
1422
+ action: "key.load",
1423
+ source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
1424
+ identity: id,
1425
+ identityName: identity.name,
1426
+ fingerprint: identity.sshKeyFingerprint,
1427
+ message: `via ${loaded.via}`
1428
+ });
1429
+ }
1430
+ return ok(
1431
+ // inAgent is a live re-check: keygen-verify (agent-less host) reports
1432
+ // loaded=true even though no agent holds the key
1433
+ { loaded: loaded.loaded, via: loaded.via, inAgent: await keyInAgent(identity.sshKeyFingerprint), message: loaded.message },
1434
+ loaded.loaded ? [] : [{ code: "key-not-loaded", message: loaded.message ?? `via ${loaded.via}` }]
1435
+ );
1127
1436
  }
1128
- async function use2(p, ctx) {
1437
+ async function use(p, ctx) {
1129
1438
  const id = p.positionals[0];
1130
1439
  if (!id) throw Errors.usage("git colabor identity use <id>");
1440
+ const current = await getIdentity(id);
1441
+ if (current.disabled) await updateIdentity(id, { disabled: void 0 });
1131
1442
  const { identity, result } = await applyIdentity(id, {
1132
1443
  source: asSource(p.values["--source"]),
1133
1444
  cwd: ctx.cwd,
@@ -1140,14 +1451,23 @@ async function use2(p, ctx) {
1140
1451
  });
1141
1452
  const warnings = [];
1142
1453
  if (result.conflict) warnings.push({ code: "conflict", message: `overrode ${result.conflict.heldBy.session}` });
1143
- if (result.keyLoaded && !result.keyLoaded.loaded) {
1144
- warnings.push({ code: "key-not-loaded", message: `key not loaded into agent: ${result.keyLoaded.message ?? result.keyLoaded.via}` });
1454
+ if (result.keyMissing) {
1455
+ warnings.push({
1456
+ code: "key-missing",
1457
+ message: `key file missing or unreadable: ${identity.sshKeyPath} \u2014 applied without a key (no core.sshCommand)`
1458
+ });
1459
+ }
1460
+ if (identity.sshKeyEncrypted && result.agent && !result.agent.inAgent && !result.bridgeUsed) {
1461
+ warnings.push({
1462
+ code: "agent-reminder",
1463
+ message: `key not in ssh-agent \u2014 run \`ssh-add ${identity.sshKeyPath}\` to cache it, or each push will prompt for the passphrase`
1464
+ });
1145
1465
  }
1146
1466
  return ok(
1147
1467
  {
1148
1468
  identity: identityToJson(identity),
1149
1469
  applied: { userName: result.name, userEmail: result.email, sshCommand: result.sshCommand ?? null },
1150
- keyLoaded: result.keyLoaded ?? null,
1470
+ agent: result.agent ?? null,
1151
1471
  conflict: result.conflict
1152
1472
  },
1153
1473
  warnings
@@ -1157,11 +1477,12 @@ async function add2(p) {
1157
1477
  const name = p.values["--name"];
1158
1478
  const email = p.values["--email"];
1159
1479
  if (!name || !email) {
1160
- throw Errors.usage("git colabor identity add --name <n> --email <e> [--key <path>] [--passphrase-command <cmd>] [--host <h>] [--default]");
1480
+ throw Errors.usage("git colabor identity add --name <n> --email <e> [--key <path>] [--host <h>] [--default]");
1161
1481
  }
1162
1482
  const warnings = [];
1163
1483
  let sshKeyFingerprint;
1164
1484
  let sshKeyPath;
1485
+ let sshKeyEncrypted;
1165
1486
  let encrypted = null;
1166
1487
  const keySource = p.values["--key"];
1167
1488
  if (keySource) {
@@ -1170,12 +1491,13 @@ async function add2(p) {
1170
1491
  sshKeyFingerprint = imp.fingerprint;
1171
1492
  sshKeyPath = imp.path;
1172
1493
  encrypted = imp.encrypted;
1173
- if (imp.encrypted && !p.values["--passphrase-command"]) {
1494
+ sshKeyEncrypted = imp.encrypted;
1495
+ if (imp.encrypted) {
1174
1496
  warnings.push({
1175
1497
  code: "encrypted-key",
1176
- message: "key is encrypted; provide --passphrase-command or run via the extension to load it at use time"
1498
+ message: "key is encrypted; it loads via the extension askpass session or an ssh-agent"
1177
1499
  });
1178
- } else if (!imp.encrypted) {
1500
+ } else {
1179
1501
  warnings.push({
1180
1502
  code: "unencrypted-key",
1181
1503
  message: "key is UNENCRYPTED \u2014 anyone who reads the key file can use it. Consider encrypting it."
@@ -1187,28 +1509,110 @@ async function add2(p) {
1187
1509
  email,
1188
1510
  sshKeyFingerprint,
1189
1511
  sshKeyPath,
1190
- passphraseCommand: p.values["--passphrase-command"],
1512
+ sshKeyEncrypted,
1191
1513
  host: p.values["--host"]
1192
1514
  });
1193
1515
  if (p.bools.has("--default")) await setDefault(identity.id);
1194
1516
  await appendAudit({ action: "key.load", source: "cli", identity: identity.id, identityName: name, fingerprint: sshKeyFingerprint });
1195
1517
  return ok({ identity: identityToJson(identity), encrypted }, warnings);
1196
1518
  }
1197
- async function rm(p, ctx) {
1519
+ async function importFromHistory(ctx) {
1520
+ if (!await insideWorkTree(ctx.cwd)) throw Errors.notARepo(ctx.cwd);
1521
+ const committers = await historyCommitters(ctx.cwd);
1522
+ const map = await readMap();
1523
+ const known = new Set(Object.values(map.identities).map((i) => i.email.toLowerCase()));
1524
+ const hidden = new Set(Object.keys(map.hidden ?? {}));
1525
+ const added = [];
1526
+ for (const c of committers) {
1527
+ const id = c.email.toLowerCase();
1528
+ if (known.has(id) || hidden.has(id)) continue;
1529
+ const identity = await addIdentity({
1530
+ name: c.name,
1531
+ email: c.email,
1532
+ imported: true,
1533
+ scope: "project"
1534
+ });
1535
+ known.add(id);
1536
+ added.push(identity);
1537
+ }
1538
+ if (added.length > 0) {
1539
+ await appendAudit({
1540
+ action: "identity.import",
1541
+ source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
1542
+ message: `imported ${added.length} committer(s) from history`
1543
+ });
1544
+ }
1545
+ const warnings = committers.length === 0 ? [{ code: "empty", message: "no commits found in history" }] : [];
1546
+ return ok({ added: added.map((i) => identityToJson(i)), skipped: committers.length - added.length }, warnings);
1547
+ }
1548
+ async function rm2(p, ctx) {
1198
1549
  const id = p.positionals[0];
1199
1550
  if (!id) throw Errors.usage("git colabor identity rm <id>");
1551
+ let email;
1552
+ let wasImported = false;
1553
+ try {
1554
+ const identity = await getIdentity(id);
1555
+ email = identity.email;
1556
+ wasImported = !!identity.imported;
1557
+ } catch {
1558
+ }
1200
1559
  try {
1201
1560
  await logoutIdentity({ source: "cli", cwd: ctx.cwd, id });
1202
1561
  } catch {
1203
1562
  }
1204
1563
  await removeIdentity(id);
1205
- return ok({ removed: id });
1564
+ if (wasImported && email) await hideIdentityEmail(email);
1565
+ return ok({ removed: id, hidden: wasImported ? (email ?? "").toLowerCase() : void 0 });
1566
+ }
1567
+ async function setIdentity(p) {
1568
+ const id = p.positionals[0];
1569
+ if (!id) throw Errors.usage("git colabor identity set <id> --name <n> | --email <e> | --key <path> | --no-key");
1570
+ await getIdentity(id);
1571
+ const patch = {};
1572
+ const warnings = [];
1573
+ if (p.values["--name"]) patch.name = p.values["--name"];
1574
+ if (p.values["--email"]) patch.email = p.values["--email"];
1575
+ if (p.bools.has("--no-key")) patch.sshKeyPath = void 0;
1576
+ if (p.values["--key"]) {
1577
+ const keySource = p.values["--key"];
1578
+ if (!fs.existsSync(keySource)) throw Errors.usage(`key file not found: ${keySource}`);
1579
+ const imp = await importKey(keySource);
1580
+ patch.sshKeyPath = imp.path;
1581
+ patch.sshKeyFingerprint = imp.fingerprint;
1582
+ patch.sshKeyEncrypted = imp.encrypted;
1583
+ if (imp.encrypted) {
1584
+ warnings.push({
1585
+ code: "encrypted-key",
1586
+ message: "key is encrypted; it loads via the extension askpass session or an ssh-agent"
1587
+ });
1588
+ }
1589
+ }
1590
+ if (p.values["--scope"]) {
1591
+ const s = p.values["--scope"];
1592
+ if (s !== "machine" && s !== "project") {
1593
+ throw Errors.usage(`--scope must be machine|project, got "${s}"`);
1594
+ }
1595
+ patch.scope = s;
1596
+ }
1597
+ if (Object.keys(patch).length === 0) {
1598
+ throw Errors.usage("identity set needs at least one of --name / --email / --key / --no-key");
1599
+ }
1600
+ const next = await updateIdentity(id, patch);
1601
+ await appendAudit({
1602
+ action: "identity.set",
1603
+ source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
1604
+ identity: id,
1605
+ identityName: next.name,
1606
+ fingerprint: next.sshKeyFingerprint,
1607
+ message: `set ${Object.keys(patch).join(", ")}`
1608
+ });
1609
+ return ok({ identity: identityToJson(next) }, warnings);
1206
1610
  }
1207
1611
  async function logout(p, ctx) {
1208
1612
  const r = await logoutIdentity({ source: "cli", cwd: ctx.cwd, id: p.positionals[0] });
1209
1613
  return ok({
1210
1614
  identity: r.identity,
1211
- cleared: { agent: r.agentRemoved, keyfile: r.keyfileShredded }
1615
+ cleared: { agent: r.agentRemoved }
1212
1616
  });
1213
1617
  }
1214
1618
  async function audit(p) {
@@ -1219,6 +1623,60 @@ async function audit(p) {
1219
1623
  });
1220
1624
  return ok({ entries });
1221
1625
  }
1626
+ async function unhide(p) {
1627
+ const email = p.positionals[0];
1628
+ if (!email) throw Errors.usage("git colabor identity unhide <email>");
1629
+ const removed = await unhideIdentityEmail(email);
1630
+ if (!removed) throw Errors.usage(`"${email}" is not hidden`);
1631
+ return ok({ unhid: email.toLowerCase() });
1632
+ }
1633
+ async function hiddenLs() {
1634
+ return ok({ hidden: await listHiddenEmails() });
1635
+ }
1636
+ async function sign(p, ctx) {
1637
+ const id = p.positionals[0];
1638
+ if (!id) throw Errors.usage("git colabor identity sign <id> [--off]");
1639
+ const r = await setCommitSigning({
1640
+ source: "cli",
1641
+ cwd: ctx.cwd,
1642
+ id,
1643
+ on: !p.bools.has("--off"),
1644
+ askpassScriptPath: ctx.askpassScriptPath
1645
+ });
1646
+ return ok(r);
1647
+ }
1648
+ async function disable(p, ctx) {
1649
+ const id = p.positionals[0];
1650
+ if (!id) throw Errors.usage("git colabor identity disable <id>");
1651
+ const identity = await getIdentity(id);
1652
+ await updateIdentity(id, { disabled: true });
1653
+ let deactivated = false;
1654
+ if (ctx.cwd) {
1655
+ const state = await readState(ctx.cwd);
1656
+ if (state.activeIdentity === id) {
1657
+ state.activeIdentity = void 0;
1658
+ state.heldBy = void 0;
1659
+ if (state.signing === true) {
1660
+ state.signing = false;
1661
+ await unsetConfig("commit.gpgsign", "local", ctx.cwd);
1662
+ await unsetConfig("gpg.format", "local", ctx.cwd);
1663
+ await unsetConfig("user.signingKey", "local", ctx.cwd);
1664
+ await unsetConfig("gpg.ssh.program", "local", ctx.cwd);
1665
+ }
1666
+ await writeState(state, ctx.cwd);
1667
+ deactivated = true;
1668
+ }
1669
+ }
1670
+ await appendAudit({
1671
+ action: "identity.disable",
1672
+ source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
1673
+ identity: id,
1674
+ identityName: identity.name,
1675
+ repo: deactivated ? await safeTopLevel5(ctx.cwd) : void 0,
1676
+ message: deactivated ? "deactivated in repo" : "disabled"
1677
+ });
1678
+ return ok({ disabled: id, deactivated });
1679
+ }
1222
1680
  async function revert(ctx) {
1223
1681
  const r = await revertRepo({ source: "cli", cwd: ctx.cwd });
1224
1682
  return ok({ restored: r.restored ?? null, hadBackup: r.hadBackup });
@@ -1242,14 +1700,20 @@ async function status(ctx) {
1242
1700
  const { identities, defaultIdentity } = await listIdentities();
1243
1701
  const rs = await repoStatus(ctx.cwd);
1244
1702
  const active = rs.activeIdentityId ? identities.find((i) => i.id === rs.activeIdentityId) : void 0;
1703
+ const st = ctx.cwd ? await readState(ctx.cwd) : void 0;
1704
+ const signingKey = await getConfig("user.signingKey", "local", ctx.cwd);
1705
+ const prints = await agentFingerprints();
1706
+ const hidden = new Set(await listHiddenEmails());
1707
+ 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 }));
1245
1708
  return ok({
1246
1709
  repo: rs.repo,
1247
1710
  inRepo: rs.inRepo,
1248
1711
  managed: rs.managed,
1249
1712
  managedBy: rs.managedBy,
1250
1713
  heldBy: rs.heldBy,
1251
- activeIdentity: active ? identityToJson(active, defaultIdentity) : null,
1252
- identities: identities.map((i) => ({ ...identityToJson(i, defaultIdentity), active: i.id === rs.activeIdentityId })),
1714
+ signing: { enabled: st?.signing === true, key: signingKey ?? null },
1715
+ activeIdentity: active ? identityToJson(active, defaultIdentity, prints) : null,
1716
+ identities: rows,
1253
1717
  selected: rs.selected,
1254
1718
  available: rs.available
1255
1719
  });
@@ -1274,12 +1738,6 @@ async function doctor(ctx) {
1274
1738
  } catch {
1275
1739
  check("identity map", () => true, `${mapPath()} (will be created on first add)`);
1276
1740
  }
1277
- try {
1278
- fs.accessSync(keysDir(), fs.constants.W_OK);
1279
- check("keys dir", () => true, keysDir());
1280
- } catch {
1281
- check("keys dir", () => true, `${keysDir()} (will be created on first import)`);
1282
- }
1283
1741
  check("audit log", () => true, auditLogPath());
1284
1742
  check("askpass bundle", () => !!ctx.askpassScriptPath && fs.existsSync(ctx.askpassScriptPath), ctx.askpassScriptPath);
1285
1743
  const agentOut = await listAgent();
@@ -1310,15 +1768,20 @@ function topHelp() {
1310
1768
  "git colabor \u2014 co-author + identity + SSH key management",
1311
1769
  "",
1312
1770
  "Usage:",
1313
- " git colabor coauthor ls [filter]",
1314
- " git colabor coauthor use <initials...>",
1315
- " git colabor coauthor solo",
1316
- " git colabor coauthor print [-i]",
1317
- ' git colabor coauthor add <initials> "Name" <email>',
1771
+ " git colabor coauthor add <email|id> [--always] [--global]",
1772
+ " default: next commit only \xB7 --always: this repo \xB7 --global: all repos",
1773
+ " git colabor coauthor rm <email|id> (remove from all scopes)",
1774
+ " git colabor coauthor ls [filter] (available + active co-authors)",
1775
+ " git colabor coauthor print (trailer blob for commit message)",
1318
1776
  " git colabor coauthor suggest [filter]",
1319
1777
  " git colabor identity ls",
1320
1778
  " git colabor identity use <id> [--as-name <n> --as-email <e>]",
1321
- " git colabor identity add --name <n> --email <e> [--key <path>] [--passphrase-command <cmd>]",
1779
+ " git colabor identity agent <id> [--remove | --verify] (load/unload the key in ssh-agent)",
1780
+ " git colabor identity add --name <n> --email <e> [--key <path>]",
1781
+ " git colabor identity import (add all history committers as identities)",
1782
+ " git colabor identity set <id> --name <n> | --email <e> | --key <path> | --no-key",
1783
+ " git colabor identity sign <id> [--off] (opt-in SSH commit signing)",
1784
+ " git colabor identity disable <id> (deactivate on key/passphrase failure)",
1322
1785
  " git colabor identity rm <id>",
1323
1786
  " git colabor identity logout [id]",
1324
1787
  " git colabor identity revert",
@@ -1367,28 +1830,27 @@ async function main(argv = process.argv.slice(2)) {
1367
1830
  }
1368
1831
  async function dispatchCoauthor(command, tokens, flags, cwd) {
1369
1832
  switch (command) {
1370
- case void 0:
1371
- case "ls": {
1372
- const p = parseCommandArgs(tokens);
1373
- return ls(p.positionals, cwd);
1833
+ case "add": {
1834
+ const p = parseCommandArgs(tokens, { boolFlags: ["--always", "--global"] });
1835
+ return add(p.positionals, {
1836
+ always: p.bools.has("--always"),
1837
+ global: p.bools.has("--global")
1838
+ }, cwd);
1374
1839
  }
1375
- case "use": {
1840
+ case "rm": {
1376
1841
  const p = parseCommandArgs(tokens);
1377
- return use(p.positionals, cwd);
1378
- }
1379
- case "solo":
1380
- return solo(cwd);
1381
- case "print": {
1382
- const p = parseCommandArgs(tokens, { boolFlags: ["-i", "--initials"] });
1383
- return print({ initials: p.bools.has("-i") || p.bools.has("--initials") }, cwd);
1842
+ return rm(p.positionals, cwd);
1384
1843
  }
1385
- case "add": {
1844
+ case void 0:
1845
+ case "ls": {
1386
1846
  const p = parseCommandArgs(tokens);
1387
- return add(p.positionals, cwd);
1847
+ return ls(p.positionals, cwd);
1388
1848
  }
1849
+ case "print":
1850
+ return print({ }, cwd);
1389
1851
  case "suggest": {
1390
1852
  const p = parseCommandArgs(tokens);
1391
- return flags.json ? suggest(p.positionals, cwd) : suggestInteractive(p.positionals, cwd);
1853
+ return suggest(p.positionals, cwd);
1392
1854
  }
1393
1855
  default:
1394
1856
  throw Errors.usage(`unknown coauthor command "${command}"`);
@@ -1407,20 +1869,34 @@ function humanFor(r, subgroup, command) {
1407
1869
  }
1408
1870
  function coauthorHuman(command, d) {
1409
1871
  if (command === "print") return String(d.text ?? "");
1410
- if (command === void 0 || command === "ls") {
1411
- return renderAuthors(d ?? []);
1872
+ if (command === "add") {
1873
+ const data = d;
1874
+ const modeLabel = data.mode === "global" ? "all repos" : data.mode === "always" ? "this repo" : "next commit";
1875
+ return `Co-author ${data.added.name} <${data.added.email}> \u2192 ${modeLabel}`;
1412
1876
  }
1413
- if (command === "use") {
1414
- const sel = d.selected ?? [];
1415
- return sel.length ? `Co-authoring with:
1416
- ${renderAuthors(sel)}` : "No co-authors selected.";
1877
+ if (command === "rm") {
1878
+ const data = d;
1879
+ return data.from.length ? `Removed ${data.removed.name} from: ${data.from.join(", ")}` : `${data.removed.name} was not active in any scope`;
1880
+ }
1881
+ if (command === void 0 || command === "ls") {
1882
+ const data = d;
1883
+ const lines = [];
1884
+ if (data.selected.length > 0) {
1885
+ lines.push("Active co-authors:");
1886
+ for (const s of data.selected) lines.push(` \u25CF ${s.name} <${s.email}> (${s.mode})`);
1887
+ }
1888
+ lines.push(`Available (${data.available.length}):`);
1889
+ const selectedEmails = new Set(data.selected.map((s) => s.email.toLowerCase()));
1890
+ for (const a of data.available) {
1891
+ if (selectedEmails.has(a.email.toLowerCase())) continue;
1892
+ lines.push(` \u25CB ${a.name} <${a.email}>`);
1893
+ }
1894
+ return lines.join("\n");
1417
1895
  }
1418
- if (command === "solo") return "Cleared co-authors.";
1419
- if (command === "add") return `${d.author.name} added to .git-coauthors`;
1420
1896
  if (command === "suggest") {
1421
- const added = d.added ?? [];
1422
- return added.length ? `Added ${added.length} co-author(s):
1423
- ${renderAuthors(added)}` : "No co-authors added.";
1897
+ const candidates = d.candidates ?? [];
1898
+ return candidates.length ? `Found ${candidates.length} contributor(s):
1899
+ ${candidates.map((a) => ` ${a.name} <${a.email}>`).join("\n")}` : "No contributors found.";
1424
1900
  }
1425
1901
  return JSON.stringify(d, null, 2);
1426
1902
  }
@@ -1429,7 +1905,7 @@ function identityHuman(command, d) {
1429
1905
  const identities = d.identities ?? [];
1430
1906
  if (identities.length === 0) return "No identities. Add one: git colabor identity add --name <n> --email <e>";
1431
1907
  return identities.map(
1432
- (i) => `${i.isDefault ? "* " : " "}${i.id} ${i.name} <${i.email}>${i.hasKey ? ` [key ${i.sshKeyFingerprint ?? ""}]` : ""}`
1908
+ (i) => `${i.isDefault ? "* " : " "}${i.id} ${i.name} <${i.email}>${i.hasKey ? ` [key ${i.sshKeyFingerprint ?? ""}${i.inAgent ? " \xB7 in agent" : ""}]` : ""}`
1433
1909
  ).join("\n");
1434
1910
  }
1435
1911
  if (command === "use") {
@@ -1440,16 +1916,41 @@ function identityHuman(command, d) {
1440
1916
  ` user.email = ${data.applied.userEmail}`
1441
1917
  ];
1442
1918
  if (data.applied.sshCommand) lines.push(` core.sshCommand = ${data.applied.sshCommand}`);
1919
+ if (data.identity.hasKey) lines.push(` key in ssh-agent = ${data.agent?.inAgent ? "yes" : "no (load: git colabor identity agent <id>)"}`);
1443
1920
  return lines.join("\n");
1444
1921
  }
1922
+ if (command === "agent") {
1923
+ const data = d;
1924
+ if (data.removed !== void 0) {
1925
+ return data.removed ? "Key removed from ssh-agent." : "Key was not in ssh-agent.";
1926
+ }
1927
+ if (data.verified !== void 0) {
1928
+ return data.verified ? "Passphrase verified (no agent write)." : "Passphrase rejected.";
1929
+ }
1930
+ return data.inAgent ? "Key loaded into ssh-agent." : `Key not loaded${data.message ? `: ${data.message}` : ""}`;
1931
+ }
1445
1932
  if (command === "add") {
1446
1933
  const data = d;
1447
1934
  return `Added identity "${data.identity.name}" <${data.identity.email}> (${data.identity.id})${data.identity.hasKey ? ` key=${data.identity.sshKeyFingerprint ?? ""}` : ""}`;
1448
1935
  }
1449
1936
  if (command === "rm") return `Removed identity ${d.removed}`;
1937
+ if (command === "set") {
1938
+ const data = d;
1939
+ return `Updated identity "${data.identity.name}" <${data.identity.email}> (${data.identity.id})${data.identity.hasKey ? ` key=${data.identity.sshKeyFingerprint ?? ""}` : ""}`;
1940
+ }
1941
+ if (command === "sign") {
1942
+ const data = d;
1943
+ return data.signing ? `SSH commit signing ON (${data.key}).` : "SSH commit signing OFF.";
1944
+ }
1945
+ if (command === "import") {
1946
+ const data = d;
1947
+ if (data.added.length === 0) return `No new committers (skipped ${data.skipped} already-known).`;
1948
+ return `Imported ${data.added.length} identity(s) from history (skipped ${data.skipped}):
1949
+ ${data.added.map((i) => ` ${i.name} <${i.email}>`).join("\n")}`;
1950
+ }
1450
1951
  if (command === "logout") {
1451
1952
  const data = d;
1452
- return `Logged out "${data.identity.name}" (agent:${data.cleared.agent ? "removed" : "n/a"}, keyfile:${data.cleared.keyfile ? "shredded" : "n/a"})`;
1953
+ return `Logged out "${data.identity.name}" (agent: ${data.cleared.agent ? "removed" : "n/a"}; the key file itself is never touched)`;
1453
1954
  }
1454
1955
  if (command === "revert") {
1455
1956
  const data = d;