git-colabor 0.1.10 → 0.1.11

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
@@ -6,6 +6,7 @@ var promises = require('fs/promises');
6
6
  var crypto = require('crypto');
7
7
  var child_process = require('child_process');
8
8
  var fs = require('fs');
9
+ var readline = require('readline');
9
10
 
10
11
  var __defProp = Object.defineProperty;
11
12
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -139,129 +140,204 @@ var init_io = __esm({
139
140
  var map_exports = {};
140
141
  __export(map_exports, {
141
142
  addIdentity: () => addIdentity,
143
+ clearStandingDown: () => clearStandingDown,
144
+ findByIdentityEmail: () => findByIdentityEmail,
142
145
  findIdentity: () => findIdentity,
143
146
  getIdentity: () => getIdentity,
144
147
  getKeyBinding: () => getKeyBinding,
145
148
  hideIdentityEmail: () => hideIdentityEmail,
146
- identityId: () => identityId,
149
+ idOf: () => idOf,
150
+ isStandingDown: () => isStandingDown,
147
151
  listHiddenEmails: () => listHiddenEmails,
148
152
  listIdentities: () => listIdentities,
153
+ markStandingDown: () => markStandingDown,
149
154
  readMap: () => readMap,
150
155
  removeIdentity: () => removeIdentity,
151
156
  setDefault: () => setDefault,
152
157
  setKeyBinding: () => setKeyBinding,
153
158
  setPushKey: () => setPushKey,
159
+ setSignCommits: () => setSignCommits,
154
160
  setSignKey: () => setSignKey,
155
161
  unhideIdentityEmail: () => unhideIdentityEmail,
156
162
  updateIdentity: () => updateIdentity,
157
163
  writeMap: () => writeMap
158
164
  });
159
- function identityId(name, email) {
160
- return "id_" + crypto.createHash("sha256").update(`${name}
161
- ${email}`).digest("hex").slice(0, 12);
165
+ function parseAuthorRef(ref) {
166
+ const m = ref.match(/^(.*) <([^<>]+)>$/);
167
+ return m ? { name: m[1], email: m[2] } : void 0;
168
+ }
169
+ function resolveRow(map, ref) {
170
+ const author = parseAuthorRef(ref);
171
+ if (author) {
172
+ const hit = map.identities.find((i) => norm(i.name) === norm(author.name) && norm(i.email) === norm(author.email));
173
+ if (hit) return hit;
174
+ }
175
+ const byAlias = map.identities.find((i) => i.alias !== void 0 && i.alias.toLowerCase() === ref.trim().toLowerCase());
176
+ if (byAlias) return byAlias;
177
+ if (/^\d+$/.test(ref.trim())) {
178
+ const row = map.identities[Number(ref.trim()) - 1];
179
+ if (row) return row;
180
+ throw Errors.usage(
181
+ `identity index ${ref.trim()} out of range \u2014 the list has ${map.identities.length} entries (see \`git colabor identity ls\`)`
182
+ );
183
+ }
184
+ if (!author) {
185
+ const byEmail = map.identities.filter((i) => norm(i.email) === norm(ref));
186
+ if (byEmail.length === 1) return byEmail[0];
187
+ if (byEmail.length > 1) {
188
+ const list = byEmail.map((i) => `"${idOf(i.name, i.email)}"`).join(", ");
189
+ throw Errors.usage(`email "${ref}" matches several identities \u2014 use the full form: ${list}`);
190
+ }
191
+ }
192
+ throw Errors.usage(`identity "${ref}" not found`);
193
+ }
194
+ function foldRow(rows, raw) {
195
+ let keyBindings = raw.keyBindings;
196
+ if (raw.sshKeyPath && raw.sshKeyFingerprint && !keyBindings?.pushKey) {
197
+ const ref = { path: raw.sshKeyPath, fingerprint: raw.sshKeyFingerprint };
198
+ if (raw.sshKeyEncrypted) ref.encrypted = true;
199
+ keyBindings = { ...keyBindings, pushKey: ref };
200
+ }
201
+ if (raw.gpgKey && !keyBindings?.signKey) {
202
+ keyBindings = { ...keyBindings, signKey: { format: "openpgp", key: raw.gpgKey } };
203
+ }
204
+ const scope = raw.scope === "user" || raw.scope === "vscode" ? "machine" : raw.scope ?? (raw.imported ? "project" : "machine");
205
+ const row = {
206
+ name: raw.name,
207
+ email: raw.email,
208
+ createdAt: raw.createdAt,
209
+ ...raw.host !== void 0 ? { host: raw.host } : {},
210
+ ...raw.alias !== void 0 && raw.alias !== "" ? { alias: raw.alias } : {},
211
+ ...scope !== void 0 ? { scope } : {},
212
+ ...raw.fromConfig !== void 0 ? { fromConfig: raw.fromConfig } : {},
213
+ ...keyBindings ? { keyBindings } : {}
214
+ };
215
+ const dup = rows.find((i) => norm(i.name) === norm(row.name) && norm(i.email) === norm(row.email));
216
+ if (dup) {
217
+ dup.keyBindings = { ...row.keyBindings ?? {}, ...dup.keyBindings ?? {} };
218
+ return;
219
+ }
220
+ rows.push(row);
162
221
  }
163
222
  async function readMap() {
164
223
  try {
165
224
  const txt = await promises.readFile(mapPath(), "utf8");
166
225
  const parsed = JSON.parse(txt);
167
- const identities = { ...parsed.identities };
168
- const keyBindings = { ...parsed.keyBindings ?? {} };
169
- for (const id of Object.keys(identities)) {
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 } };
226
+ const raws = Array.isArray(parsed.identities) ? parsed.identities : Object.entries(parsed.identities ?? {}).map(([k, row]) => ({
227
+ ...row,
228
+ keyBindings: row.keyBindings ?? parsed.keyBindings?.[k]
229
+ }));
230
+ const identities = [];
231
+ for (const raw of raws) foldRow(identities, raw);
232
+ let defaultIdentity;
233
+ if (parsed.defaultIdentity) {
234
+ try {
235
+ defaultIdentity = refOf(resolveRow({ schemaVersion: 2, identities }, parsed.defaultIdentity));
236
+ } catch {
237
+ defaultIdentity = void 0;
180
238
  }
181
- delete row.sshKeyPath;
182
- delete row.sshKeyFingerprint;
183
- delete row.sshKeyEncrypted;
184
- delete row.gpgKey;
185
- delete row.passphraseCommand;
186
- delete row.disabled;
187
- delete row.remoteKeys;
188
- const legacyScope = row.scope;
189
- if (legacyScope === "user" || legacyScope === "vscode") row.scope = "machine";
190
239
  }
191
240
  const migrated = {
192
- schemaVersion: 1,
241
+ schemaVersion: 2,
242
+ // any v1 shape on disk folds into the v2 list above
193
243
  identities,
194
- keyBindings,
195
- defaultIdentity: parsed.defaultIdentity,
196
- hidden: parsed.hidden
244
+ ...defaultIdentity ? { defaultIdentity } : {},
245
+ ...parsed.hidden ? { hidden: parsed.hidden } : {},
246
+ ...parsed.standingDown ? { standingDown: parsed.standingDown } : {}
197
247
  };
198
248
  if (JSON.stringify(parsed) !== JSON.stringify(migrated)) {
199
249
  await writeMap(migrated);
200
250
  }
201
251
  return migrated;
202
252
  } catch {
203
- return { schemaVersion: 1, identities: {} };
253
+ return { schemaVersion: 2, identities: [] };
204
254
  }
205
255
  }
206
256
  async function writeMap(map) {
207
257
  await atomicWriteJson(mapPath(), map, 384);
208
258
  }
209
- async function getIdentity(id) {
210
- const map = await readMap();
211
- const found = map.identities[id];
212
- if (!found) throw Errors.usage(`identity "${id}" not found`);
213
- return found;
259
+ async function getIdentity(ref) {
260
+ return resolveRow(await readMap(), ref);
261
+ }
262
+ async function findByIdentityEmail(email) {
263
+ const { identities } = await readMap();
264
+ return identities.filter((i) => norm(i.email) === norm(email));
214
265
  }
215
266
  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
- );
267
+ const { identities } = await readMap();
268
+ return identities.find((i) => norm(i.email) === norm(email) && norm(i.name) === norm(name));
220
269
  }
221
270
  async function addIdentity(input) {
222
271
  const map = await readMap();
223
- const id = input.id ?? identityId(input.name, input.email);
224
- const identity = { ...input, id, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
225
- if (map.identities[id]) return map.identities[id];
226
- map.identities[id] = identity;
227
- if (map.hidden?.[identity.email.toLowerCase()]) delete map.hidden[identity.email.toLowerCase()];
272
+ const dup = map.identities.find((i) => norm(i.name) === norm(input.name) && norm(i.email) === norm(input.email));
273
+ if (dup) return dup;
274
+ const identity = { ...input, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
275
+ map.identities.push(identity);
276
+ const hiddenKey = norm(input.email);
277
+ if (map.hidden?.[hiddenKey]) delete map.hidden[hiddenKey];
228
278
  await writeMap(map);
229
279
  return identity;
230
280
  }
231
- async function updateIdentity(id, patch) {
281
+ async function updateIdentity(ref, patch, opts = {}) {
232
282
  const map = await readMap();
233
- const identity = map.identities[id];
234
- if (!identity) throw Errors.usage(`identity "${id}" not found`);
235
- map.identities[id] = { ...identity, ...patch };
283
+ const row = resolveRow(map, ref);
284
+ const before = refOf(row);
285
+ Object.assign(row, patch);
286
+ if (opts?.clearAlias) delete row.alias;
287
+ const after = refOf(row);
288
+ const aliasClash = patch.alias && map.identities.find((i) => i !== row && i.alias === patch.alias);
289
+ if (aliasClash) throw Errors.usage(`alias "${patch.alias}" already belongs to ${idOf(aliasClash.name, aliasClash.email)}`);
290
+ const clash = map.identities.find((i) => i !== row && refOf(i) === after);
291
+ if (clash) throw Errors.usage(`"${idOf(row.name, row.email)}" already exists`);
292
+ if (map.defaultIdentity === before) map.defaultIdentity = after;
236
293
  await writeMap(map);
237
- return map.identities[id];
294
+ return row;
238
295
  }
239
- async function getKeyBinding(id) {
240
- const map = await readMap();
241
- return map.keyBindings?.[id] ?? {};
296
+ async function getKeyBinding(ref) {
297
+ return (await getIdentity(ref)).keyBindings ?? {};
242
298
  }
243
- async function setKeyBinding(id, binding) {
299
+ async function setKeyBinding(ref, binding) {
244
300
  const map = await readMap();
245
- if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
246
- map.keyBindings = { ...map.keyBindings, [id]: binding };
301
+ resolveRow(map, ref).keyBindings = binding;
247
302
  await writeMap(map);
248
303
  }
249
- async function setPushKey(id, ref) {
250
- const b = await getKeyBinding(id);
251
- await setKeyBinding(id, { ...b, pushKey: ref });
304
+ async function setPushKey(ref, ref_) {
305
+ const b = await getKeyBinding(ref);
306
+ await setKeyBinding(ref, { ...b, pushKey: ref_ });
307
+ }
308
+ async function setSignKey(ref, key) {
309
+ const b = await getKeyBinding(ref);
310
+ await setKeyBinding(ref, { ...b, signKey: key });
252
311
  }
253
- async function setSignKey(id, ref) {
254
- const b = await getKeyBinding(id);
255
- await setKeyBinding(id, { ...b, signKey: ref });
312
+ async function setSignCommits(ref, on) {
313
+ const b = await getKeyBinding(ref);
314
+ await setKeyBinding(ref, { ...b, signCommits: on ? true : void 0 });
256
315
  }
257
316
  async function hideIdentityEmail(email) {
258
317
  const map = await readMap();
259
- map.hidden = { ...map.hidden, [email.toLowerCase()]: true };
318
+ map.hidden = { ...map.hidden, [norm(email)]: true };
260
319
  await writeMap(map);
261
320
  }
321
+ async function markStandingDown(root) {
322
+ const map = await readMap();
323
+ const roots = new Set(map.standingDown ?? []);
324
+ roots.add(root);
325
+ map.standingDown = [...roots];
326
+ await writeMap(map);
327
+ }
328
+ async function clearStandingDown(root) {
329
+ const map = await readMap();
330
+ if (!map.standingDown?.includes(root)) return;
331
+ map.standingDown = map.standingDown.filter((r) => r !== root);
332
+ await writeMap(map);
333
+ }
334
+ async function isStandingDown(root) {
335
+ const map = await readMap();
336
+ return (map.standingDown ?? []).includes(root);
337
+ }
262
338
  async function unhideIdentityEmail(email) {
263
339
  const map = await readMap();
264
- const key = email.toLowerCase();
340
+ const key = norm(email);
265
341
  if (!map.hidden?.[key]) return false;
266
342
  delete map.hidden[key];
267
343
  await writeMap(map);
@@ -271,29 +347,31 @@ async function listHiddenEmails() {
271
347
  const map = await readMap();
272
348
  return Object.keys(map.hidden ?? {});
273
349
  }
274
- async function removeIdentity(id) {
350
+ async function removeIdentity(ref) {
275
351
  const map = await readMap();
276
- if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
277
- delete map.identities[id];
278
- if (map.keyBindings?.[id]) delete map.keyBindings[id];
279
- if (map.defaultIdentity === id) delete map.defaultIdentity;
352
+ const row = resolveRow(map, ref);
353
+ map.identities = map.identities.filter((i) => i !== row);
354
+ if (map.defaultIdentity === refOf(row)) delete map.defaultIdentity;
280
355
  await writeMap(map);
281
356
  }
282
- async function setDefault(id) {
357
+ async function setDefault(ref) {
283
358
  const map = await readMap();
284
- if (!map.identities[id]) throw Errors.usage(`identity "${id}" not found`);
285
- map.defaultIdentity = id;
359
+ map.defaultIdentity = refOf(resolveRow(map, ref));
286
360
  await writeMap(map);
287
361
  }
288
362
  async function listIdentities() {
289
363
  const map = await readMap();
290
- return { identities: Object.values(map.identities), defaultIdentity: map.defaultIdentity };
364
+ return { identities: map.identities, ...map.defaultIdentity ? { defaultIdentity: map.defaultIdentity } : {} };
291
365
  }
366
+ var norm, refOf, idOf;
292
367
  var init_map = __esm({
293
368
  "src/core/identity/map.ts"() {
294
369
  init_errors();
295
370
  init_paths();
296
371
  init_io();
372
+ norm = (s) => s.trim().toLowerCase();
373
+ refOf = (i) => `${norm(i.name)} <${norm(i.email)}>`;
374
+ idOf = (name, email) => `${name.trim()} <${email.trim()}>`;
297
375
  }
298
376
  });
299
377
  function run(args, opts) {
@@ -420,6 +498,16 @@ var init_config = __esm({
420
498
  init_exec();
421
499
  }
422
500
  });
501
+
502
+ // src/core/git/rev.ts
503
+ var rev_exports = {};
504
+ __export(rev_exports, {
505
+ gitDir: () => gitDir,
506
+ headSha: () => headSha,
507
+ insideWorkTree: () => insideWorkTree,
508
+ isRepo: () => isRepo,
509
+ topLevel: () => topLevel
510
+ });
423
511
  async function insideWorkTree(cwd) {
424
512
  const r = await gitRaw(["rev-parse", "--is-inside-work-tree"], { cwd });
425
513
  return r.exitCode === 0 && r.stdout.trim() === "true";
@@ -432,6 +520,15 @@ async function gitDir(cwd) {
432
520
  const r = await git(["rev-parse", "--git-dir"], { cwd });
433
521
  return path.resolve(cwd ?? process.cwd(), r.stdout.trim());
434
522
  }
523
+ async function isRepo(cwd) {
524
+ return insideWorkTree(cwd);
525
+ }
526
+ async function headSha(cwd) {
527
+ const r = await gitRaw(["rev-parse", "HEAD"], { cwd });
528
+ if (r.exitCode !== 0) return void 0;
529
+ const sha = r.stdout.trim();
530
+ return sha.length > 0 ? sha : void 0;
531
+ }
435
532
  var init_rev = __esm({
436
533
  "src/core/git/rev.ts"() {
437
534
  init_exec();
@@ -850,7 +947,7 @@ async function signingKeyPath(sshKeyPath, fingerprint) {
850
947
  return sshKeyPath;
851
948
  }
852
949
  async function signingConfigFor(identity) {
853
- const binding = await getKeyBinding(identity.id);
950
+ const binding = await getKeyBinding(idOf(identity.name, identity.email));
854
951
  if (binding.signKey) {
855
952
  return binding.signKey.format === "openpgp" ? { format: "openpgp", key: binding.signKey.key } : { format: "ssh", key: await signingKeyPath(binding.signKey.path, binding.signKey.fingerprint) };
856
953
  }
@@ -859,32 +956,33 @@ async function signingConfigFor(identity) {
859
956
  }
860
957
  return void 0;
861
958
  }
862
- async function writeIdentitySigning(identity, cwd, askpassScriptPath) {
959
+ async function writeIdentitySigning(identity, cwd, askpassScriptPath, scope = "local") {
863
960
  const cfg = await signingConfigFor(identity);
864
961
  if (!cfg) return void 0;
865
- await setConfig("commit.gpgsign", "true", "local", cwd);
866
- await setConfig("gpg.format", cfg.format, "local", cwd);
867
- await setConfig("user.signingKey", cfg.key, "local", cwd);
962
+ await setConfig("commit.gpgsign", "true", scope, cwd);
963
+ await setConfig("gpg.format", cfg.format, scope, cwd);
964
+ await setConfig("user.signingKey", cfg.key, scope, cwd);
868
965
  if (cfg.format === "ssh" && askpassScriptPath) {
869
- await setConfig("gpg.ssh.program", await ensureSignWrapper(askpassScriptPath), "local", cwd);
966
+ await setConfig("gpg.ssh.program", await ensureSignWrapper(askpassScriptPath), scope, cwd);
870
967
  } else if (cfg.format === "openpgp") {
871
- await unsetConfig("gpg.ssh.program", "local", cwd);
968
+ await unsetConfig("gpg.ssh.program", scope, cwd);
872
969
  }
873
970
  return cfg;
874
971
  }
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);
879
- await unsetConfig("commit.gpgsign", "local", cwd);
972
+ async function disableSigning(cwd, scope = "local") {
973
+ await unsetConfig("gpg.format", scope, cwd);
974
+ await unsetConfig("user.signingKey", scope, cwd);
975
+ await unsetConfig("gpg.ssh.program", scope, cwd);
976
+ await unsetConfig("commit.gpgsign", scope, cwd);
880
977
  if ((await getEffectiveConfig("commit.gpgsign", cwd, "bool"))?.value === "true") {
881
- await setConfig("commit.gpgsign", "false", "local", cwd);
978
+ await setConfig("commit.gpgsign", "false", scope, cwd);
882
979
  }
883
980
  }
884
981
  async function setCommitSigning(opts) {
885
982
  if (!await insideWorkTree(opts.cwd)) throw Errors.notARepo(opts.cwd);
886
983
  if (!opts.on) {
887
- await disableSigning(opts.cwd, false);
984
+ await disableSigning(opts.cwd);
985
+ if (opts.id) await setSignCommits(opts.id, false);
888
986
  await appendAudit({ action: "identity.sign", source: opts.source, identity: opts.id, repo: await safeTopLevel(opts.cwd), result: "ok", message: "signing off" });
889
987
  return { signing: false };
890
988
  }
@@ -892,6 +990,7 @@ async function setCommitSigning(opts) {
892
990
  const identity = await getIdentity(opts.id);
893
991
  const cfg = await writeIdentitySigning(identity, opts.cwd, opts.askpassScriptPath);
894
992
  if (!cfg) throw Errors.usage(`identity "${identity.name}" has no usable SSH or GPG key to sign with`);
993
+ await setSignCommits(opts.id, true);
895
994
  await appendAudit({
896
995
  action: "identity.sign",
897
996
  source: opts.source,
@@ -938,6 +1037,15 @@ var init_sign = __esm({
938
1037
  init_gpg();
939
1038
  }
940
1039
  });
1040
+ function pidIsAlive(pid) {
1041
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return false;
1042
+ try {
1043
+ process.kill(pid, 0);
1044
+ return true;
1045
+ } catch (e) {
1046
+ return e.code === "EPERM";
1047
+ }
1048
+ }
941
1049
  function discoverSessionBridges() {
942
1050
  try {
943
1051
  const dir = dataDir();
@@ -946,7 +1054,23 @@ function discoverSessionBridges() {
946
1054
  for (const s of sessions) {
947
1055
  try {
948
1056
  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 });
1057
+ if (!parsed.socketPath || !parsed.token) continue;
1058
+ const ourSock = /^askpass-[\w.-]+\.sock$/.test(path.basename(parsed.socketPath)) && path.join(dir, path.basename(parsed.socketPath)) === parsed.socketPath;
1059
+ const stale = parsed.pid !== void 0 && !pidIsAlive(parsed.pid) || !ourSock || !fs.existsSync(parsed.socketPath);
1060
+ if (stale) {
1061
+ if (ourSock && fs.existsSync(parsed.socketPath)) {
1062
+ try {
1063
+ fs.rmSync(parsed.socketPath);
1064
+ } catch {
1065
+ }
1066
+ }
1067
+ try {
1068
+ fs.unlinkSync(path.join(dir, s.f));
1069
+ } catch {
1070
+ }
1071
+ continue;
1072
+ }
1073
+ out.push({ socketPath: parsed.socketPath, token: parsed.token });
950
1074
  } catch {
951
1075
  }
952
1076
  }
@@ -980,24 +1104,29 @@ async function safeTopLevel2(cwd) {
980
1104
  }
981
1105
  async function applyResolvedIdentity(args) {
982
1106
  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);
1107
+ const scope = opts.configScope === "global" ? "global" : "local";
1108
+ await setConfig("user.name", name, scope, opts.cwd);
1109
+ await setConfig("user.email", email, scope, opts.cwd);
985
1110
  if (sshCommand) {
986
- await setConfig("core.sshCommand", sshCommand, "local", opts.cwd);
1111
+ await setConfig("core.sshCommand", sshCommand, scope, opts.cwd);
987
1112
  } 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);
1113
+ await unsetConfig("core.sshCommand", scope, opts.cwd);
1114
+ const eff = await getEffectiveConfig("commit.gpgsign", opts.cwd, "bool");
1115
+ if (eff?.value === "true") await disableSigning(opts.cwd, scope);
991
1116
  }
992
- const binding = identity ? await getKeyBinding(identity.id) : void 0;
1117
+ const binding = identity ? await getKeyBinding(idOf(identity.name, identity.email)) : void 0;
993
1118
  let agent;
994
1119
  if (binding?.pushKey) {
995
1120
  agent = { inAgent: await keyInAgent(binding.pushKey.fingerprint) };
996
1121
  }
1122
+ if (scope === "local") {
1123
+ const tl = await safeTopLevel2(opts.cwd);
1124
+ if (tl) await clearStandingDown(tl);
1125
+ }
997
1126
  await appendAudit({
998
1127
  action: "identity.use",
999
1128
  source: opts.source,
1000
- identity: identity?.id,
1129
+ identity: identity ? idOf(identity.name, identity.email) : void 0,
1001
1130
  identityName: identity?.name ?? name,
1002
1131
  fingerprint: binding?.pushKey?.fingerprint,
1003
1132
  repo: await safeTopLevel2(opts.cwd)
@@ -1054,10 +1183,11 @@ async function applyIdentity(id, opts) {
1054
1183
  result.keyMissing = keyMissing;
1055
1184
  result.keyDegraded = keyDegraded;
1056
1185
  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);
1186
+ const scope = opts.configScope === "global" ? "global" : "local";
1187
+ const gpgsign = await getConfig("commit.gpgsign", scope, opts.cwd);
1188
+ if (gpgsign === "true" || binding.signCommits) {
1189
+ const okSign = await writeIdentitySigning(identity, opts.cwd, opts.askpassScriptPath, scope);
1190
+ if (!okSign && gpgsign === "true") await disableSigning(opts.cwd, scope);
1061
1191
  }
1062
1192
  }
1063
1193
  return { identity, result };
@@ -1096,41 +1226,43 @@ function signingKeyOwned(configured, keys) {
1096
1226
  }
1097
1227
  async function clearIdentityConfigLayer(identity, opts = {}) {
1098
1228
  const forceKeys = opts.forceKeys === true;
1229
+ const scope = opts.scope === "global" ? "global" : "local";
1099
1230
  const sshPaths = [
1100
1231
  ...identity.pushKeyPath ? [identity.pushKeyPath] : [],
1101
1232
  ...identity.signKey?.format === "ssh" ? [identity.signKey.path] : []
1102
1233
  ];
1103
1234
  const gpgFingerprint = identity.signKey?.format === "openpgp" ? identity.signKey.key : void 0;
1104
1235
  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)
1236
+ getConfig("user.name", scope, opts.cwd),
1237
+ getConfig("user.email", scope, opts.cwd),
1238
+ getConfig("core.sshCommand", scope, opts.cwd),
1239
+ getConfig("user.signingKey", scope, opts.cwd),
1240
+ getConfig("gpg.ssh.program", scope, opts.cwd)
1110
1241
  ]);
1111
1242
  const eq = (a, b) => !!a && a.trim() === b.trim();
1112
1243
  const result = { identityLayer: false, sshCommand: false, signing: false };
1113
- if (eq(n, identity.name)) {
1114
- await unsetConfig("user.name", "local", opts.cwd);
1244
+ const emailIsThis = eq(e, identity.email);
1245
+ if (emailIsThis || eq(n, identity.name)) {
1246
+ await unsetConfig("user.name", scope, opts.cwd);
1115
1247
  result.identityLayer = true;
1116
1248
  }
1117
- if (eq(e, identity.email)) {
1118
- await unsetConfig("user.email", "local", opts.cwd);
1249
+ if (emailIsThis) {
1250
+ await unsetConfig("user.email", scope, opts.cwd);
1119
1251
  result.identityLayer = true;
1120
1252
  }
1121
1253
  if (ssh && (forceKeys || sshPaths.some((p) => sshCommandUses(ssh, p)))) {
1122
- await unsetConfig("core.sshCommand", "local", opts.cwd);
1254
+ await unsetConfig("core.sshCommand", scope, opts.cwd);
1123
1255
  result.sshCommand = true;
1124
1256
  }
1125
1257
  const wrapperIsOurs = !!sshProgram && sshProgram.includes("git-colabor");
1126
1258
  if (signKey && (forceKeys || signingKeyOwned(signKey, { sshPaths, gpgFingerprint }))) {
1127
- await unsetConfig("user.signingKey", "local", opts.cwd);
1259
+ await unsetConfig("user.signingKey", scope, opts.cwd);
1128
1260
  result.signing = true;
1129
1261
  }
1130
1262
  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);
1263
+ await unsetConfig("gpg.format", scope, opts.cwd);
1264
+ await unsetConfig("gpg.ssh.program", scope, opts.cwd);
1265
+ await unsetConfig("commit.gpgsign", scope, opts.cwd);
1134
1266
  }
1135
1267
  return result;
1136
1268
  }
@@ -1289,18 +1421,34 @@ init_formatter();
1289
1421
  init_exec();
1290
1422
  init_types();
1291
1423
  var SHORTLOG_LINE = /^\s*\d+\t(.+)\s<(.+)>$/;
1424
+ var AUTHOR_LINE = /^(.*)\s<([^<>]+)>$/;
1292
1425
  async function repoAuthors(filter, cwd) {
1293
1426
  const args = ["shortlog", "-seni", "HEAD"];
1294
1427
  if (filter) args.splice(1, 0, `--author=${filter}`);
1295
- const r = await gitRaw(args, { cwd });
1296
- if (r.exitCode !== 0) return [];
1297
1428
  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();
1429
+ const seen = /* @__PURE__ */ new Set();
1430
+ const add3 = (name, email) => {
1431
+ if (!name || !email) return;
1432
+ const key = email.toLowerCase();
1433
+ if (seen.has(key)) return;
1434
+ seen.add(key);
1303
1435
  out.push(new Author(genKey(name, email), name, email));
1436
+ };
1437
+ const r = await gitRaw(args, { cwd });
1438
+ if (r.exitCode === 0) {
1439
+ for (const line of r.stdout.split(/\r?\n/)) {
1440
+ const m = line.match(SHORTLOG_LINE);
1441
+ if (m) add3(m[1].trim(), m[2].trim());
1442
+ }
1443
+ }
1444
+ const t = await gitRaw(["log", "--format=%(trailers:key=Co-authored-by,valueonly)"], { cwd });
1445
+ if (t.exitCode === 0) {
1446
+ for (const line of t.stdout.split(/\r?\n/)) {
1447
+ const m = line.match(AUTHOR_LINE);
1448
+ if (!m) continue;
1449
+ if (filter && !`${m[1]} <${m[2]}>`.toLowerCase().includes(filter.toLowerCase())) continue;
1450
+ add3(m[1].trim(), m[2].trim());
1451
+ }
1304
1452
  }
1305
1453
  return out;
1306
1454
  }
@@ -1316,7 +1464,7 @@ async function requireRepo(cwd) {
1316
1464
  async function identityAuthors() {
1317
1465
  const { identities } = await listIdentities();
1318
1466
  return identities.map((i) => ({
1319
- id: i.id,
1467
+ id: `${i.name} <${i.email}>`,
1320
1468
  author: new Author(genKey(i.name, i.email), i.name, i.email)
1321
1469
  }));
1322
1470
  }
@@ -1464,27 +1612,42 @@ init_map();
1464
1612
 
1465
1613
  // src/core/git/committers.ts
1466
1614
  init_exec();
1615
+ var AUTHOR_LINE2 = /^(.*)\s<([^<>]+)>$/;
1616
+ function bump(counts, name, email) {
1617
+ const key = email.toLowerCase();
1618
+ const cur = counts.get(key);
1619
+ if (cur) cur.count++;
1620
+ else counts.set(key, { name, email, count: 1 });
1621
+ }
1467
1622
  async function historyCommitters(cwd) {
1468
- const r = await gitRaw(["log", "--format=%cn%x1f%ce"], { cwd });
1469
- if (r.exitCode !== 0) return [];
1470
1623
  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 });
1624
+ const r = await gitRaw(["log", "--format=%cn%x1f%ce"], { cwd });
1625
+ if (r.exitCode === 0) {
1626
+ for (const line of r.stdout.split("\n")) {
1627
+ const sep = line.indexOf("");
1628
+ if (sep < 0) continue;
1629
+ const name = line.slice(0, sep).trim();
1630
+ const email = line.slice(sep + 1).trim();
1631
+ if (!name || !email) continue;
1632
+ bump(counts, name, email);
1633
+ }
1634
+ }
1635
+ const t = await gitRaw(["log", "--format=%(trailers:key=Co-authored-by,valueonly)"], { cwd });
1636
+ if (t.exitCode === 0) {
1637
+ for (const line of t.stdout.split("\n")) {
1638
+ const m = line.match(AUTHOR_LINE2);
1639
+ if (!m) continue;
1640
+ bump(counts, m[1].trim(), m[2].trim());
1641
+ }
1481
1642
  }
1482
1643
  return [...counts.values()].sort((a, b) => b.count - a.count).map(({ name, email }) => ({ name, email }));
1483
1644
  }
1484
1645
 
1485
1646
  // src/cli/identity.ts
1647
+ init_config();
1486
1648
  init_keys();
1487
1649
  init_apply();
1650
+ init_map();
1488
1651
  init_sign();
1489
1652
 
1490
1653
  // src/core/identity/logout.ts
@@ -1495,7 +1658,7 @@ init_map();
1495
1658
  init_config();
1496
1659
  init_map();
1497
1660
  init_keys();
1498
- var norm = (s) => s.trim().toLowerCase();
1661
+ var norm2 = (s) => s.trim().toLowerCase();
1499
1662
  function keyPathFromSshCommand(cmd) {
1500
1663
  if (!cmd) return void 0;
1501
1664
  const m = cmd.match(/(?:^|\s)-i\s+(\S+)/);
@@ -1517,8 +1680,9 @@ async function resolveActive(cwd, opts = {}) {
1517
1680
  const name = n.value;
1518
1681
  const email = e.value;
1519
1682
  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));
1683
+ let match = identities.find(
1684
+ (i) => norm2(i.email) === norm2(email) && norm2(i.name) === norm2(name)
1685
+ );
1522
1686
  let enrolled = false;
1523
1687
  if (!match) {
1524
1688
  if (!opts.enroll) return void 0;
@@ -1529,30 +1693,30 @@ async function resolveActive(cwd, opts = {}) {
1529
1693
  const cfgPushPath = keyPathFromSshCommand(sshCmd?.value);
1530
1694
  if (cfgPushPath) {
1531
1695
  const fp = await fpOf(cfgPushPath);
1532
- const binding = await getKeyBinding(match.id);
1696
+ const binding = await getKeyBinding(idOf(match.name, match.email));
1533
1697
  if (!binding.pushKey || binding.pushKey.path !== cfgPushPath || fp && binding.pushKey.fingerprint !== fp) {
1534
1698
  const ref = { path: cfgPushPath, fingerprint: fp ?? binding.pushKey?.fingerprint ?? "" };
1535
- await setPushKey(match.id, ref);
1699
+ await setPushKey(idOf(match.name, match.email), ref);
1536
1700
  }
1537
1701
  }
1538
1702
  const signKeyCfg = await getEffectiveConfig("user.signingKey", cwd);
1539
1703
  const gpgFormat = await getEffectiveConfig("gpg.format", cwd);
1540
1704
  if (signKeyCfg?.value) {
1541
- const binding = await getKeyBinding(match.id);
1705
+ const binding = await getKeyBinding(idOf(match.name, match.email));
1542
1706
  const cur = binding.signKey;
1543
1707
  if (gpgFormat?.value === "openpgp") {
1544
1708
  if (!cur || cur.format !== "openpgp" || cur.key !== signKeyCfg.value) {
1545
- await setSignKey(match.id, { format: "openpgp", key: signKeyCfg.value });
1709
+ await setSignKey(idOf(match.name, match.email), { format: "openpgp", key: signKeyCfg.value });
1546
1710
  }
1547
1711
  } else {
1548
1712
  const path = signKeyCfg.value.replace(/\.pub$/, "");
1549
1713
  if (!cur || cur.format !== "ssh" || cur.path !== path) {
1550
1714
  const fp = await fpOf(path);
1551
- if (fp) await setSignKey(match.id, { format: "ssh", path, fingerprint: fp });
1715
+ if (fp) await setSignKey(idOf(match.name, match.email), { format: "ssh", path, fingerprint: fp });
1552
1716
  }
1553
1717
  }
1554
1718
  }
1555
- const finalBinding = await getKeyBinding(match.id);
1719
+ const finalBinding = await getKeyBinding(idOf(match.name, match.email));
1556
1720
  return {
1557
1721
  identity: match,
1558
1722
  enrolled,
@@ -1573,26 +1737,28 @@ async function safeTopLevel3(cwd) {
1573
1737
  }
1574
1738
  async function logoutIdentity(opts) {
1575
1739
  const resolved = await resolveActive(opts.cwd);
1576
- let id = opts.id ?? resolved?.identity.id;
1740
+ let id = opts.id ?? (resolved ? idOf(resolved.identity.name, resolved.identity.email) : void 0);
1577
1741
  if (!id) {
1578
1742
  const { identities } = await listIdentities();
1579
- if (identities.length === 1) id = identities[0].id;
1743
+ if (identities.length === 1) id = idOf(identities[0].name, identities[0].email);
1580
1744
  else throw Errors.usage("no active identity \u2014 specify one: git colabor identity logout <id>");
1581
1745
  }
1582
1746
  const identity = await getIdentity(id);
1583
1747
  const binding = await getKeyBinding(id);
1584
- const agentRemoved = binding.pushKey ? await removeKey(binding.pushKey.path) : false;
1748
+ const agentRemoved = opts.removeAgentKey === false ? false : binding.pushKey ? await removeKey(binding.pushKey.path) : false;
1585
1749
  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;
1750
+ const layer = {
1751
+ name: identity.name,
1752
+ email: identity.email,
1753
+ pushKeyPath: binding.pushKey?.path,
1754
+ signKey: binding.signKey
1755
+ };
1756
+ const cleared = await clearIdentityConfigLayer2(layer, {
1757
+ cwd: opts.cwd,
1758
+ forceKeys: !!(resolved && idOf(resolved.identity.name, resolved.identity.email) === id)
1759
+ });
1760
+ const globalCleared = await clearIdentityConfigLayer2(layer, { scope: "global" });
1761
+ const clearedAnything = cleared.identityLayer || cleared.sshCommand || cleared.signing || globalCleared.identityLayer || globalCleared.sshCommand || globalCleared.signing;
1596
1762
  if (cleared.identityLayer) {
1597
1763
  const { unsetAllConfig: unsetAllConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
1598
1764
  const { clearTemplate: clearTemplate2 } = await Promise.resolve().then(() => (init_template(), template_exports));
@@ -1600,17 +1766,21 @@ async function logoutIdentity(opts) {
1600
1766
  await clearTemplate2(opts.cwd).catch(() => {
1601
1767
  });
1602
1768
  }
1769
+ if (cleared.identityLayer || cleared.sshCommand || cleared.signing) {
1770
+ const tl = await safeTopLevel3(opts.cwd);
1771
+ if (tl) await markStandingDown(tl);
1772
+ }
1603
1773
  await appendAudit({
1604
1774
  action: "identity.logout",
1605
1775
  source: opts.source,
1606
- identity: identity.id,
1776
+ identity: id,
1607
1777
  identityName: identity.name,
1608
1778
  fingerprint: binding.pushKey?.fingerprint,
1609
1779
  repo: await safeTopLevel3(opts.cwd),
1610
1780
  message: clearedAnything ? `cleared ${[cleared.identityLayer ? "config" : null, cleared.sshCommand ? "ssh key" : null, cleared.signing ? "sign key" : null].filter(Boolean).join(" + ")} + agent` : "agent only"
1611
1781
  });
1612
1782
  return {
1613
- identity: { id: identity.id, name: identity.name, fingerprint: binding.pushKey?.fingerprint },
1783
+ identity: { id, name: identity.name, fingerprint: binding.pushKey?.fingerprint },
1614
1784
  agentRemoved,
1615
1785
  cleared: {
1616
1786
  agent: agentRemoved,
@@ -1675,7 +1845,10 @@ async function repoStatus(cwd) {
1675
1845
  const available = identityMap.identities.filter((i) => !selectedEmails.has(i.email)).map((i) => ({ key: genKey(i.name, i.email), name: i.name, email: i.email }));
1676
1846
  return {
1677
1847
  inRepo: true,
1678
- repo: cwd,
1848
+ // canonical repo root (topLevel resolves symlinks, e.g. /var →
1849
+ // /private/var on macOS) — the standing-down store and every per-repo
1850
+ // comparison key off this exact form
1851
+ repo: await topLevel(cwd),
1679
1852
  managed: managed === "true",
1680
1853
  managedBy: managedBy ?? null,
1681
1854
  activeIdentityId: state.activeIdentity ?? null,
@@ -1690,7 +1863,7 @@ function toBrief(a) {
1690
1863
 
1691
1864
  // src/cli/identity.ts
1692
1865
  init_paths();
1693
- var USE_SPEC = { valueFlags: ["--source", "--as-name", "--as-email"], boolFlags: [] };
1866
+ var USE_SPEC = { valueFlags: ["--source", "--as-name", "--as-email", "--config-scope"], boolFlags: [] };
1694
1867
  var ADD_SPEC = {
1695
1868
  valueFlags: ["--name", "--email", "--key", "--host", "--source"],
1696
1869
  boolFlags: ["--default"]
@@ -1698,18 +1871,22 @@ var ADD_SPEC = {
1698
1871
  var AUDIT_SPEC = { valueFlags: ["--repo", "--since", "--tail"] };
1699
1872
  var APPLY_SPEC = { valueFlags: ["--name", "--email", "--ssh-command", "--source"] };
1700
1873
  var SET_SPEC = {
1701
- valueFlags: ["--name", "--email", "--key", "--gpg-key", "--sign-key", "--scope"],
1702
- boolFlags: ["--no-key", "--no-gpg-key", "--no-sign-key"]
1874
+ valueFlags: ["--name", "--email", "--key", "--gpg-key", "--sign-key", "--scope", "--alias"],
1875
+ boolFlags: ["--no-key", "--no-gpg-key", "--no-sign-key", "--sign-commits", "--no-sign-commits", "--no-alias"]
1703
1876
  };
1704
1877
  var SIGN_SPEC = { valueFlags: [], boolFlags: ["--off"] };
1878
+ var LOGOUT_SPEC = { valueFlags: [], boolFlags: ["--no-agent"] };
1879
+ var UNSET_SPEC = { valueFlags: ["--scope"], boolFlags: [] };
1705
1880
  var AGENT_SPEC = { valueFlags: [], boolFlags: ["--remove", "--verify"] };
1706
1881
  function identityToJson(i, defaultId, agentPrints, binding) {
1707
1882
  const push = binding?.pushKey;
1708
1883
  const sign2 = binding?.signKey;
1709
1884
  return {
1710
- id: i.id,
1885
+ id: idOf(i.name, i.email),
1886
+ // derived ref — never stored
1711
1887
  name: i.name,
1712
1888
  email: i.email,
1889
+ alias: i.alias ?? null,
1713
1890
  host: i.host,
1714
1891
  // reference mode: a key counts only while the referenced file is still there
1715
1892
  hasKey: !!push && fs.existsSync(push.path),
@@ -1724,12 +1901,14 @@ function identityToJson(i, defaultId, agentPrints, binding) {
1724
1901
  fingerprint: sign2.fingerprint,
1725
1902
  ...sign2.encrypted ? { encrypted: true } : {}
1726
1903
  } : null,
1727
- imported: !!i.imported,
1728
1904
  fromConfig: !!i.fromConfig,
1729
- scope: i.scope ?? (i.imported ? "project" : "machine"),
1730
- isDefault: i.id === defaultId
1905
+ scope: i.scope ?? "machine",
1906
+ isDefault: !!defaultId && ckey(i) === defaultId.toLowerCase(),
1907
+ /** the user turned commit signing on for this identity */
1908
+ signCommits: !!binding?.signCommits
1731
1909
  };
1732
1910
  }
1911
+ var ckey = (i) => `${i.name.trim().toLowerCase()} <${i.email.trim().toLowerCase()}>`;
1733
1912
  function asSource(v) {
1734
1913
  return v === "ext" ? "ext" : "cli";
1735
1914
  }
@@ -1757,7 +1936,9 @@ async function dispatch(command, tokens, ctx) {
1757
1936
  case "rm":
1758
1937
  return rm2(parseCommandArgs(tokens));
1759
1938
  case "logout":
1760
- return logout(parseCommandArgs(tokens), ctx);
1939
+ return logout(parseCommandArgs(tokens, LOGOUT_SPEC), ctx);
1940
+ case "unset-config":
1941
+ return unsetConfigForIdentity(parseCommandArgs(tokens, UNSET_SPEC), ctx);
1761
1942
  case "agent":
1762
1943
  return agentKey(parseCommandArgs(tokens, AGENT_SPEC), ctx);
1763
1944
  case "hide":
@@ -1775,12 +1956,11 @@ async function dispatch(command, tokens, ctx) {
1775
1956
  }
1776
1957
  }
1777
1958
  async function ls2() {
1778
- const map = await readMap();
1779
1959
  const { identities, defaultIdentity } = await listIdentities();
1780
1960
  const prints = await agentFingerprints();
1781
1961
  const hidden = new Set(await listHiddenEmails());
1782
1962
  const visible = identities.filter((i) => !hidden.has(i.email.toLowerCase()));
1783
- return ok({ identities: visible.map((i) => identityToJson(i, defaultIdentity, prints, map.keyBindings?.[i.id])), defaultIdentity });
1963
+ return ok({ identities: visible.map((i) => identityToJson(i, defaultIdentity, prints, i.keyBindings)), defaultIdentity });
1784
1964
  }
1785
1965
  async function hideIdentityCmd(p) {
1786
1966
  const email = p.positionals[0];
@@ -1795,10 +1975,10 @@ async function hideIdentityCmd(p) {
1795
1975
  }
1796
1976
  async function agentKey(p, ctx) {
1797
1977
  const id = p.positionals[0];
1798
- if (!id) throw Errors.usage("git colabor identity agent <id> [--remove | --verify]");
1978
+ if (!id) throw Errors.usage("git colabor identity agent <email> [--remove | --verify]");
1799
1979
  const identity = await getIdentity(id);
1800
1980
  const binding = await getKeyBinding(id);
1801
- if (!binding.pushKey) throw Errors.usage(`identity "${id}" has no SSH push key`);
1981
+ if (!binding.pushKey) throw Errors.usage(`identity "${id}" (email) has no SSH push key`);
1802
1982
  const { path: keyPath, fingerprint } = binding.pushKey;
1803
1983
  const remove = p.bools.has("--remove");
1804
1984
  const verify = p.bools.has("--verify");
@@ -1837,9 +2017,37 @@ async function agentKey(p, ctx) {
1837
2017
  loaded.loaded ? [] : [{ code: "key-not-loaded", message: loaded.message ?? `via ${loaded.via}` }]
1838
2018
  );
1839
2019
  }
2020
+ async function resolveRefOrPrompt(ref, ctx) {
2021
+ try {
2022
+ await getIdentity(ref);
2023
+ return ref;
2024
+ } catch (e) {
2025
+ const byEmail = await findByIdentityEmail(ref);
2026
+ const canPrompt = !ctx.flags.json && process.stdin.isTTY && process.stdout.isTTY;
2027
+ if (byEmail.length > 1 && canPrompt) {
2028
+ const lines = byEmail.map((x, i) => ` ${i + 1}. ${idOf(x.name, x.email)}${x.alias ? ` (${x.alias})` : ""}`);
2029
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2030
+ const answer = await new Promise(
2031
+ (done) => rl.question(`email "${ref}" matches ${byEmail.length} identities:
2032
+ ${lines.join("\n")}
2033
+ pick one [1-${byEmail.length}]: `, (a) => done(a))
2034
+ ).finally(() => rl.close());
2035
+ const n = Number((answer ?? "").trim());
2036
+ if (Number.isInteger(n) && n >= 1 && n <= byEmail.length) {
2037
+ return idOf(byEmail[n - 1].name, byEmail[n - 1].email);
2038
+ }
2039
+ }
2040
+ throw e;
2041
+ }
2042
+ }
1840
2043
  async function use(p, ctx) {
1841
- const id = p.positionals[0];
1842
- if (!id) throw Errors.usage("git colabor identity use <id>");
2044
+ const rawRef = p.positionals[0];
2045
+ if (!rawRef) throw Errors.usage("git colabor identity use <ref>");
2046
+ const id = await resolveRefOrPrompt(rawRef, ctx);
2047
+ const scopeVal = p.values["--config-scope"];
2048
+ if (scopeVal !== void 0 && scopeVal !== "local" && scopeVal !== "global") {
2049
+ throw Errors.usage(`--config-scope must be local|global, got "${scopeVal}"`);
2050
+ }
1843
2051
  const { identity, result } = await applyIdentity(id, {
1844
2052
  source: asSource(p.values["--source"]),
1845
2053
  cwd: ctx.cwd,
@@ -1847,7 +2055,8 @@ async function use(p, ctx) {
1847
2055
  asEmail: p.values["--as-email"],
1848
2056
  askpassScriptPath: ctx.askpassScriptPath,
1849
2057
  socketPath: ctx.socketPath,
1850
- token: ctx.token
2058
+ token: ctx.token,
2059
+ configScope: scopeVal === "global" ? "global" : "local"
1851
2060
  });
1852
2061
  const warnings = [];
1853
2062
  if (result.keyMissing) {
@@ -1862,12 +2071,17 @@ async function use(p, ctx) {
1862
2071
  message: `passphrase unavailable \u2014 identity applied WITHOUT the push/sign key; retry via the extension or ssh-add`
1863
2072
  });
1864
2073
  }
1865
- const map = await readMap();
1866
2074
  return ok(
1867
2075
  {
1868
- identity: identityToJson(identity, void 0, void 0, map.keyBindings?.[identity.id]),
1869
- applied: { userName: result.name, userEmail: result.email, sshCommand: result.sshCommand ?? null },
1870
- keyApplied: result.keyApplied
2076
+ identity: identityToJson(identity, void 0, void 0, identity.keyBindings),
2077
+ applied: {
2078
+ userName: result.name,
2079
+ userEmail: result.email,
2080
+ sshCommand: result.sshCommand ?? null,
2081
+ configScope: scopeVal === "global" ? "global" : "local"
2082
+ },
2083
+ keyApplied: result.keyApplied,
2084
+ agent: result.agent ?? null
1871
2085
  },
1872
2086
  warnings
1873
2087
  );
@@ -1894,11 +2108,10 @@ async function add2(p) {
1894
2108
  const identity = await addIdentity({ name, email, host: p.values["--host"] });
1895
2109
  if (keySource) {
1896
2110
  const imp = await importKey(keySource);
1897
- await setPushKey(identity.id, { path: imp.path, fingerprint: imp.fingerprint, ...imp.encrypted ? { encrypted: true } : {} });
2111
+ await setPushKey(idOf(identity.name, identity.email), { path: imp.path, fingerprint: imp.fingerprint, ...imp.encrypted ? { encrypted: true } : {} });
1898
2112
  }
1899
- if (p.bools.has("--default")) await setDefault(identity.id);
1900
- const map = await readMap();
1901
- return ok({ identity: identityToJson(identity, void 0, void 0, map.keyBindings?.[identity.id]), encrypted }, warnings);
2113
+ if (p.bools.has("--default")) await setDefault(idOf(identity.name, identity.email));
2114
+ return ok({ identity: identityToJson(identity, void 0, void 0, identity.keyBindings), encrypted }, warnings);
1902
2115
  }
1903
2116
  async function importFromHistory(ctx) {
1904
2117
  if (!await insideWorkTree(ctx.cwd)) throw Errors.notARepo(ctx.cwd);
@@ -1910,7 +2123,7 @@ async function importFromHistory(ctx) {
1910
2123
  for (const c of committers) {
1911
2124
  const id = c.email.toLowerCase();
1912
2125
  if (known.has(id) || hidden.has(id)) continue;
1913
- const identity = await addIdentity({ name: c.name, email: c.email, imported: true, scope: "project" });
2126
+ const identity = await addIdentity({ name: c.name, email: c.email, scope: "project" });
1914
2127
  known.add(id);
1915
2128
  added.push(identity);
1916
2129
  }
@@ -1932,7 +2145,7 @@ async function rm2(p) {
1932
2145
  try {
1933
2146
  const identity = await getIdentity(id);
1934
2147
  email = identity.email;
1935
- wasImported = !!identity.imported;
2148
+ wasImported = identity.scope === "project";
1936
2149
  } catch {
1937
2150
  }
1938
2151
  await removeIdentity(id);
@@ -1943,7 +2156,7 @@ async function setIdentity(p, ctx) {
1943
2156
  const id = p.positionals[0];
1944
2157
  if (!id) {
1945
2158
  throw Errors.usage(
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>"
2159
+ "git colabor identity set <ref> --name <n> | --email <e> | --alias <a> | --no-alias | --key <path> | --no-key | --gpg-key <k> | --no-gpg-key | --sign-key <path> | --no-sign-key | --sign-commits | --no-sign-commits | --scope <s>"
1947
2160
  );
1948
2161
  }
1949
2162
  await getIdentity(id);
@@ -1984,6 +2197,19 @@ async function setIdentity(p, ctx) {
1984
2197
  await setSignKey(id, { format: "openpgp", key: key.fingerprint });
1985
2198
  keyTouched = true;
1986
2199
  }
2200
+ const aliasVal = p.values["--alias"];
2201
+ if (aliasVal !== void 0) {
2202
+ if (!/^[A-Za-z0-9._@-]+$/.test(aliasVal)) {
2203
+ throw Errors.usage(`alias must be letters/digits/dot/dash/underscore/@, got "${aliasVal}"`);
2204
+ }
2205
+ if (/^\d+$/.test(aliasVal)) {
2206
+ throw Errors.usage(`alias cannot be a bare number ("${aliasVal}") \u2014 it would shadow the 1-based list index ref`);
2207
+ }
2208
+ if (aliasVal.includes(" <") || aliasVal.includes(">")) {
2209
+ throw Errors.usage(`alias cannot contain angle brackets ("${aliasVal}") \u2014 it would shadow the "Name <email>" ref form`);
2210
+ }
2211
+ patch.alias = aliasVal;
2212
+ }
1987
2213
  if (p.values["--sign-key"]) {
1988
2214
  const signSource = p.values["--sign-key"];
1989
2215
  if (!fs.existsSync(signSource)) throw Errors.usage(`key file not found: ${signSource}`);
@@ -1994,12 +2220,22 @@ async function setIdentity(p, ctx) {
1994
2220
  warnings.push({ code: "encrypted-key", message: "sign key is encrypted; it signs via the extension askpass session or an ssh-agent" });
1995
2221
  }
1996
2222
  }
2223
+ if (p.bools.has("--sign-commits")) {
2224
+ await setSignCommits(id, true);
2225
+ keyTouched = true;
2226
+ }
2227
+ if (p.bools.has("--no-sign-commits")) {
2228
+ await setSignCommits(id, false);
2229
+ keyTouched = true;
2230
+ }
2231
+ const clearAlias = p.bools.has("--no-alias");
2232
+ if (clearAlias) keyTouched = true;
1997
2233
  if (Object.keys(patch).length === 0 && !keyTouched) {
1998
2234
  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"
2235
+ "identity set needs at least one of --name / --email / --alias / --no-alias / --key / --no-key / --gpg-key / --no-gpg-key / --sign-key / --no-sign-key / --sign-commits / --no-sign-commits / --scope"
2000
2236
  );
2001
2237
  }
2002
- const next = Object.keys(patch).length > 0 ? await updateIdentity2(id, patch) : await getIdentity(id);
2238
+ const next = Object.keys(patch).length > 0 || clearAlias ? await updateIdentity2(id, patch, { clearAlias }) : await getIdentity(id);
2003
2239
  await appendAudit({
2004
2240
  action: "identity.set",
2005
2241
  source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
@@ -2007,13 +2243,45 @@ async function setIdentity(p, ctx) {
2007
2243
  identityName: next.name,
2008
2244
  message: `set ${[...Object.keys(patch), ...keyTouched ? ["key"] : []].join(", ")}`
2009
2245
  });
2010
- const map = await readMap();
2011
- return ok({ identity: identityToJson(next, void 0, void 0, map.keyBindings?.[id]) }, warnings);
2246
+ return ok({ identity: identityToJson(next, void 0, void 0, next.keyBindings) }, warnings);
2012
2247
  }
2013
2248
  async function logout(p, ctx) {
2014
- const r = await logoutIdentity({ source: "cli", cwd: ctx.cwd, id: p.positionals[0] });
2249
+ const r = await logoutIdentity({
2250
+ source: "cli",
2251
+ cwd: ctx.cwd,
2252
+ id: p.positionals[0],
2253
+ removeAgentKey: !p.bools.has("--no-agent")
2254
+ });
2015
2255
  return ok({ identity: r.identity, cleared: r.cleared });
2016
2256
  }
2257
+ async function unsetConfigForIdentity(p, ctx) {
2258
+ const id = p.positionals[0];
2259
+ if (!id) throw Errors.usage("git colabor identity unset-config <email> [--scope local|global]");
2260
+ const scope = p.values["--scope"];
2261
+ if (scope !== void 0 && scope !== "local" && scope !== "global") {
2262
+ throw Errors.usage(`--scope must be local|global, got "${scope}"`);
2263
+ }
2264
+ const identity = await getIdentity(id);
2265
+ const binding = await getKeyBinding(id);
2266
+ const { clearIdentityConfigLayer: clearIdentityConfigLayer2 } = await Promise.resolve().then(() => (init_configClear(), configClear_exports));
2267
+ const cleared = await clearIdentityConfigLayer2(
2268
+ { name: identity.name, email: identity.email, pushKeyPath: binding.pushKey?.path, signKey: binding.signKey },
2269
+ { cwd: ctx.cwd, scope: scope === "global" ? "global" : "local" }
2270
+ );
2271
+ if (scope !== "global" && (cleared.identityLayer || cleared.sshCommand || cleared.signing)) {
2272
+ const tl = await (await Promise.resolve().then(() => (init_rev(), rev_exports))).topLevel(ctx.cwd).catch(() => void 0);
2273
+ if (tl) await markStandingDown(tl);
2274
+ }
2275
+ await appendAudit({
2276
+ action: "identity.logout",
2277
+ source: process.env.GIT_COLABOR_SOURCE === "ext" ? "ext" : "cli",
2278
+ identity: id,
2279
+ identityName: identity.name,
2280
+ repo: await (await Promise.resolve().then(() => (init_rev(), rev_exports))).topLevel(ctx.cwd).catch(() => void 0),
2281
+ message: `unset-config ${scope ?? "local"}: ${[cleared.identityLayer ? "identity" : null, cleared.sshCommand ? "ssh key" : null, cleared.signing ? "sign key" : null].filter(Boolean).join(" + ") || "nothing matched"}`
2282
+ });
2283
+ return ok({ identity: { id, name: identity.name }, cleared: { ...cleared, scope: scope ?? "local" } });
2284
+ }
2017
2285
  async function audit(p) {
2018
2286
  const entries = await readAudit({
2019
2287
  repo: p.values["--repo"],
@@ -2058,26 +2326,47 @@ async function hiddenApply(p, ctx) {
2058
2326
  });
2059
2327
  }
2060
2328
  async function status(ctx) {
2061
- const map = await readMap();
2062
- const { identities, defaultIdentity } = await listIdentities();
2063
2329
  const rs = await repoStatus(ctx.cwd);
2330
+ const scopeIdentity = async (scope) => {
2331
+ const [n, e] = await Promise.all([getConfig("user.name", scope, ctx.cwd), getConfig("user.email", scope, ctx.cwd)]);
2332
+ if (!n || !e) return null;
2333
+ const norm3 = (s) => s.trim().toLowerCase();
2334
+ const match = Object.values((await readMap()).identities).find(
2335
+ (i) => norm3(i.email) === norm3(e) && norm3(i.name) === norm3(n)
2336
+ );
2337
+ if (match) return { name: n, email: e, id: idOf(match.name, match.email) };
2338
+ if ((await listHiddenEmails()).includes(e.toLowerCase())) return { name: n, email: e, id: "" };
2339
+ const added = await addIdentity({ name: n, email: e, scope: "machine", fromConfig: true });
2340
+ return { name: n, email: e, id: idOf(added.name, added.email) };
2341
+ };
2342
+ const configIdentities = {
2343
+ repo: rs.inRepo ? await scopeIdentity("local") : null,
2344
+ global: await scopeIdentity("global")
2345
+ };
2346
+ const { identities, defaultIdentity } = await listIdentities();
2064
2347
  const prints = await agentFingerprints();
2065
2348
  const resolved = rs.inRepo ? await resolveActive(ctx.cwd, { enroll: true }) : void 0;
2066
2349
  const active = resolved?.identity;
2067
- const activeId = active?.id;
2350
+ const activeId = active ? ckey(active) : void 0;
2068
2351
  const hidden = new Set(await listHiddenEmails());
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
2352
+ const rows = identities.filter((i) => ckey(i) === activeId || !hidden.has(i.email.toLowerCase())).map((i) => ({
2353
+ ...identityToJson(i, defaultIdentity, prints, i.keyBindings),
2354
+ active: ckey(i) === activeId
2072
2355
  }));
2073
2356
  return ok({
2074
2357
  repo: rs.repo,
2075
2358
  inRepo: rs.inRepo,
2076
2359
  // what `git commit` will actually do here, and which scope decides it
2077
2360
  signing: await signingStatus(ctx.cwd),
2078
- activeIdentity: active ? identityToJson(active, defaultIdentity, prints, map.keyBindings?.[active.id]) : null,
2361
+ activeIdentity: active ? identityToJson(active, defaultIdentity, prints, active.keyBindings) : null,
2079
2362
  enrolled: resolved?.enrolled ?? false,
2080
2363
  identities: rows,
2364
+ // which identity each git-config SCOPE names (repo-local / global) —
2365
+ // drives the "found in repo config" / "found in git global config" rows
2366
+ configIdentities,
2367
+ // the user stripped this repo's config and auto-apply stands down here
2368
+ // until an explicit local use (see map.ts standingDown)
2369
+ standingDown: rs.repo ? await isStandingDown(rs.repo) : false,
2081
2370
  selected: rs.selected,
2082
2371
  available: rs.available
2083
2372
  });
@@ -2268,7 +2557,7 @@ function identityHuman(command, d) {
2268
2557
  const identities = d.identities ?? [];
2269
2558
  if (identities.length === 0) return "No identities. Add one: git colabor identity add --name <n> --email <e>";
2270
2559
  return identities.map(
2271
- (i) => `${i.isDefault ? "* " : " "}${i.id} ${i.name} <${i.email}>${i.hasKey ? ` [key ${i.sshKeyFingerprint ?? ""}${i.inAgent ? " \xB7 in agent" : ""}]` : ""}`
2560
+ (i, idx) => `${idx + 1}. ${i.isDefault ? "* " : " "}${i.name} <${i.email}>${i.alias ? ` [${i.alias}]` : ""}${i.hasKey ? ` [key ${i.sshKeyFingerprint ?? ""}${i.inAgent ? " \xB7 in agent" : ""}]` : ""}`
2272
2561
  ).join("\n");
2273
2562
  }
2274
2563
  if (command === "use") {
@@ -2294,12 +2583,12 @@ function identityHuman(command, d) {
2294
2583
  }
2295
2584
  if (command === "add") {
2296
2585
  const data = d;
2297
- return `Added identity "${data.identity.name}" <${data.identity.email}> (${data.identity.id})${data.identity.hasKey ? ` key=${data.identity.sshKeyFingerprint ?? ""}` : ""}`;
2586
+ return `Added identity "${data.identity.name}" <${data.identity.email}>${data.identity.hasKey ? ` key=${data.identity.sshKeyFingerprint ?? ""}` : ""}`;
2298
2587
  }
2299
2588
  if (command === "rm") return `Removed identity ${d.removed}`;
2300
2589
  if (command === "set") {
2301
2590
  const data = d;
2302
- return `Updated identity "${data.identity.name}" <${data.identity.email}> (${data.identity.id})${data.identity.hasKey ? ` key=${data.identity.sshKeyFingerprint ?? ""}` : ""}`;
2591
+ return `Updated identity "${data.identity.name}" <${data.identity.email}>${data.identity.hasKey ? ` key=${data.identity.sshKeyFingerprint ?? ""}` : ""}`;
2303
2592
  }
2304
2593
  if (command === "sign") {
2305
2594
  const data = d;