yadflow 4.7.0 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/README.md +43 -4
  3. package/bin/commands.mjs +5 -1
  4. package/bin/yad.mjs +169 -22
  5. package/cli/agent-guard.mjs +511 -0
  6. package/cli/agent-guide.mjs +83 -0
  7. package/cli/agent-rules.mjs +388 -0
  8. package/cli/argv-flags.mjs +7 -0
  9. package/cli/build.mjs +1 -1
  10. package/cli/ci-check.mjs +492 -0
  11. package/cli/docs.mjs +1 -1
  12. package/cli/doctor.mjs +148 -7
  13. package/cli/epic-state.mjs +3 -3
  14. package/cli/errors.mjs +1 -0
  15. package/cli/guide.mjs +549 -0
  16. package/cli/hook.mjs +32 -3
  17. package/cli/lib.mjs +46 -0
  18. package/cli/lifecycle/defaults/2.json +124 -0
  19. package/cli/lifecycle/lifecycle.schema.json +5 -2
  20. package/cli/lifecycle.mjs +16 -3
  21. package/cli/machine.mjs +141 -0
  22. package/cli/manifest.mjs +75 -0
  23. package/cli/marked-block.mjs +48 -0
  24. package/cli/members.mjs +19 -5
  25. package/cli/migrate.mjs +17 -19
  26. package/cli/next.mjs +1 -1
  27. package/cli/openpr.mjs +46 -6
  28. package/cli/plan.mjs +326 -22
  29. package/cli/preview.mjs +253 -0
  30. package/cli/protection.mjs +50 -0
  31. package/cli/reconcile.mjs +187 -26
  32. package/cli/repo.mjs +64 -3
  33. package/cli/report.mjs +62 -14
  34. package/cli/review.mjs +4 -0
  35. package/cli/setup.mjs +244 -25
  36. package/cli/signing.mjs +377 -0
  37. package/cli/story-frames.mjs +296 -0
  38. package/cli/test-agents-file.mjs +993 -0
  39. package/cli/test-ci-check.mjs +616 -0
  40. package/cli/test-guide.mjs +1267 -0
  41. package/cli/test-machine.mjs +140 -0
  42. package/cli/test-node.mjs +129 -0
  43. package/cli/test-preview.mjs +511 -0
  44. package/cli/test-setup-agent.mjs +352 -0
  45. package/cli/test-signing.mjs +524 -0
  46. package/cli/test-story-frames.mjs +339 -0
  47. package/cli/toolbox.mjs +35 -1
  48. package/cli/update-commit.mjs +313 -11
  49. package/cli/workspace.mjs +37 -12
  50. package/package.json +6 -4
  51. package/skills/sdlc/config.yaml +4 -4
  52. package/skills/sdlc/module-help.csv +1 -0
  53. package/skills/yad-change/SKILL.md +3 -2
  54. package/skills/yad-checks/SKILL.md +29 -9
  55. package/skills/yad-checks/references/check-gates.md +9 -4
  56. package/skills/yad-checks/templates/checks/package-manager.sh +1 -1
  57. package/skills/yad-checks/templates/github/yad-checks.yml +1 -1
  58. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +1 -1
  59. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +1 -1
  60. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +1 -1
  61. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +1 -1
  62. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +1 -1
  63. package/skills/yad-checks/templates/hooks/agent-guard.mjs +116 -0
  64. package/skills/yad-commit/SKILL.md +4 -3
  65. package/skills/yad-connect-design/SKILL.md +7 -4
  66. package/skills/yad-connect-design/references/design-context.md +23 -0
  67. package/skills/yad-connect-design/references/design-registry.md +3 -3
  68. package/skills/yad-connect-repos/SKILL.md +13 -3
  69. package/skills/yad-connect-repos/references/code-context.md +2 -1
  70. package/skills/yad-connect-repos/references/repos-registry.md +2 -1
  71. package/skills/yad-docs-overview/references/pipeline-model.md +2 -2
  72. package/skills/yad-engineer-review/SKILL.md +25 -7
  73. package/skills/yad-engineer-review/references/ship-and-record.md +7 -4
  74. package/skills/yad-epic/SKILL.md +2 -1
  75. package/skills/yad-epic/references/state-schema.md +7 -1
  76. package/skills/yad-guide/SKILL.md +192 -0
  77. package/skills/yad-implement/SKILL.md +14 -0
  78. package/skills/yad-open-pr/SKILL.md +5 -2
  79. package/skills/yad-pair-review/SKILL.md +19 -5
  80. package/skills/yad-pr-template/templates/github/pull_request_template.md +1 -0
  81. package/skills/yad-pr-template/templates/gitlab/merge_request_templates/Default.md +1 -0
  82. package/skills/yad-product-bridge/SKILL.md +32 -13
  83. package/skills/yad-product-bridge/references/bridge.md +6 -3
  84. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +2 -2
  85. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +1 -1
  86. package/skills/yad-report/SKILL.md +15 -0
  87. package/skills/yad-review-companion/SKILL.md +9 -4
  88. package/skills/yad-review-gate/SKILL.md +13 -9
  89. package/skills/yad-review-gate/references/gating.md +1 -1
  90. package/skills/yad-run/SKILL.md +10 -6
  91. package/skills/yad-run/references/run-loop.md +2 -1
  92. package/skills/yad-spec/SKILL.md +21 -0
  93. package/skills/yad-stories/SKILL.md +22 -0
  94. package/skills/yad-stories/references/story-schema.md +1 -0
  95. package/skills/yad-sync-repos/SKILL.md +2 -1
  96. package/skills/yad-ui/SKILL.md +7 -2
@@ -0,0 +1,377 @@
1
+ // `yad signing check` (E160a) — will this person's commits be signed, and will the platform mark them
2
+ // Verified? Read-only: it reads the git config in the folder it runs in, the key it names, and the account
3
+ // on the Product's platform (the key listed for SIGNING, and a verified email). Every finding is `ok`, `gap`
4
+ // (with the person's fix), `suggest`, or `unknown` (a read that failed: never counted as ok).
5
+ //
6
+ // Setting signing up is the person's (a key is a secret, and adding it to the account is a platform
7
+ // setting): the agent hands over the fix and runs this again to confirm by reading. SSH is taught first
8
+ // (one key, no extra program), GPG second.
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import { c, log, ok, warn, fail, info, hand, run, has, forTerminal } from './lib.mjs';
13
+ import { api, loggedIn, whyFailed, PAGE, PLATFORM_NAME } from './protection.mjs';
14
+ import { productIdentity } from './members.mjs';
15
+
16
+ const SSH_MIN_GIT = [2, 34];
17
+
18
+ // The public key a `user.signingkey` names for SSH, as `<type> <base64>`, or `{ problem }`. A `key::` value is
19
+ // the key itself; a path names the public key, or the private key with its `.pub` beside it.
20
+ export function sshPublicKey(signingkey, { home = os.homedir(), dir = process.cwd() } = {}) {
21
+ if (!signingkey) return { problem: 'no key is named (user.signingkey is not set)' };
22
+ if (signingkey.startsWith('key::')) return { key: keyText(signingkey.slice(5)) };
23
+ // The older form git still reads: the public key itself, with no `key::` in front.
24
+ if (keyText(signingkey)) return { key: keyText(signingkey) };
25
+ // A relative path is read from the repo's folder, as git reads it there.
26
+ const file = path.resolve(dir, signingkey.replace(/^~(?=$|[\\/])/, home));
27
+ if (!fs.existsSync(file)) return { problem: `${file} does not exist` };
28
+ const pub = file.endsWith('.pub') ? file : `${file}.pub`;
29
+ for (const f of [pub, file]) {
30
+ try {
31
+ const text = keyText(fs.readFileSync(f, 'utf8'));
32
+ if (text) return { key: text, file: f };
33
+ } catch { /* not readable: the next one */ }
34
+ }
35
+ return { problem: `no public key beside ${file} (make one: ssh-keygen -y -f ${file} > ${file}.pub)` };
36
+ }
37
+ // `<type> <base64>` from a public key line, or '' when the text is not one.
38
+ const keyText = (s) => {
39
+ const m = String(s || '').trim().match(/^((?:ssh|ecdsa|sk)-[\w@.-]+)\s+([A-Za-z0-9+/=]+)/);
40
+ return m ? `${m[1]} ${m[2]}` : '';
41
+ };
42
+
43
+ // The key ids (16 hex) and fingerprints in `gpg --with-colons` output: the key and its subkeys. With
44
+ // `signing`, only a key or subkey that can sign now: not expired, revoked, disabled or invalid (field 2: e,
45
+ // r, d, i; a disabled key is also `D` in field 12, printed on the primary only), with the sign capability
46
+ // (field 12: `s`, lower case: this key's own, not the whole key's), and its secret here (field 15 is `#` for
47
+ // a stub, whose secret is elsewhere; a card's serial number when the secret is on a smartcard). A primary that
48
+ // cannot be used makes its subkeys unusable too. With `live`, every key and subkey that is not expired,
49
+ // revoked, disabled or invalid (a platform's copy of a key, which signs nothing here). `keys` counts the
50
+ // primary keys (`sec`/`pub`) with a part that can sign now; `listed` counts every one.
51
+ // `parts` holds each part taken, as a Set of its id and fingerprint, with `sub` (a subkey), `created`
52
+ // (field 6), `primary` (which key it belongs to, counted in listing order) and `card` (a signing part whose
53
+ // secret is on a smartcard): gpg signs with ONE of them.
54
+ export function gpgIds(colons, { signing = false, live = false } = {}) {
55
+ const ids = new Set();
56
+ const parts = [];
57
+ const signers = new Set();
58
+ let listed = 0;
59
+ let primary = null;
60
+ let primaryDead = false;
61
+ let take = false;
62
+ for (const line of String(colons || '').split('\n')) {
63
+ const f = line.split(':');
64
+ if (['sec', 'ssb', 'pub', 'sub'].includes(f[0])) {
65
+ // gpg prints `D` on the primary only; reading it on every line costs nothing.
66
+ const dead = ['e', 'r', 'd', 'i'].includes(f[1]) || (f[11] || '').includes('D');
67
+ if (f[0] === 'sec' || f[0] === 'pub') { primary = ++listed; primaryDead = dead; }
68
+ // A subkey before any primary belongs to no key: skipped.
69
+ const signs = primary !== null && !dead && !primaryDead && (f[11] || '').includes('s') && f[14] !== '#';
70
+ if (signs) signers.add(primary);
71
+ take = primary !== null && (signing ? signs : !live || (!dead && !primaryDead));
72
+ if (take) parts.push(Object.assign(new Set(), { sub: f[0] === 'ssb' || f[0] === 'sub', created: Number(f[5]) || 0, primary, card: signs && !!f[14] && f[14] !== '+' }));
73
+ // (Field 6 is seconds today; GnuPG may switch it to an ISO date, read as 0: then the first subkey wins.)
74
+ if (take && /^[0-9A-F]{16}$/i.test(f[4] || '')) { ids.add(f[4].toUpperCase()); parts.at(-1).add(f[4].toUpperCase()); }
75
+ } else if (f[0] === 'fpr' && take && /^[0-9A-F]{40}$/i.test(f[9] || '')) { ids.add(f[9].toUpperCase()); parts.at(-1).add(f[9].toUpperCase()); }
76
+ }
77
+ return Object.assign(ids, { keys: signers.size, listed, parts: parts.filter((x) => x.size) });
78
+ }
79
+ // A long key id matches its fingerprint's last 16 digits.
80
+ const sameKey = (a, b) => a === b || (a.length === 40 && a.endsWith(b)) || (b.length === 40 && b.endsWith(a));
81
+
82
+ // git's version as [major, minor], or null.
83
+ const gitVersion = (gitRun) => {
84
+ const m = (gitRun('git', ['--version']).stdout || '').match(/(\d+)\.(\d+)/);
85
+ return m ? [Number(m[1]), Number(m[2])] : null;
86
+ };
87
+ const atLeast = (v, min) => !!v && (v[0] > min[0] || (v[0] === min[0] && v[1] >= min[1]));
88
+
89
+ // The check. `dir` is the folder whose git config counts; `root` the Product, when there is one (its platform
90
+ // and host). `runner` answers the platform CLIs (gh, glab); `gitRun` answers git, gpg and ssh-keygen; `haveTool`
91
+ // says whether a program is on PATH. All three are injectable for tests.
92
+ export function signingCheck(dir, { root = null, runner = run, gitRun = run, haveTool = has, env = process.env, home = os.homedir() } = {}) {
93
+ const findings = [];
94
+ const notes = [];
95
+ const add = (id, status, message, fix = null) => findings.push({ id, status, message, ...(fix ? { fix: { actor: 'person', ...fix } } : {}) });
96
+ const cfg = (key, bool = false) => {
97
+ const r = gitRun('git', ['config', ...(bool ? ['--bool'] : []), '--get', key], { cwd: dir, env });
98
+ return r.ok ? r.stdout : '';
99
+ };
100
+ const email = cfg('user.email');
101
+ const signingkey = cfg('user.signingkey');
102
+ const format = cfg('gpg.format') || 'openpgp';
103
+ const method = format === 'ssh' ? 'ssh' : format === 'openpgp' ? 'gpg' : format;
104
+ const sshSteps = [
105
+ 'Make a key (once): ssh-keygen -t ed25519 -C "<your email>" (press Enter for the default file).',
106
+ 'Tell git to sign with it: git config --global gpg.format ssh, then git config --global user.signingkey ~/.ssh/id_ed25519.pub',
107
+ 'Turn signing on: git config --global commit.gpgsign true',
108
+ 'Add the .pub file to your account as a SIGNING key (the platform\'s settings page, below), then run `yad signing check` again.',
109
+ ];
110
+
111
+ // --- this machine ---
112
+ if (cfg('commit.gpgsign', true) === 'true') add('gpgsign', 'ok', 'signing is on (commit.gpgsign)');
113
+ else add('gpgsign', 'gap', 'commits are not signed: commit.gpgsign is not true', { commands: ['git config --global commit.gpgsign true'], steps: ['If you have no signing key yet, make one first (SSH is the simplest):', ...sshSteps] });
114
+ if (method === 'x509') add('format', 'unknown', 'gpg.format is x509: yad does not check X.509 certificates — the platform\'s documentation says whether it verifies yours');
115
+ else if (method !== 'ssh' && method !== 'gpg') add('format', 'gap', `gpg.format is "${forTerminal(format)}", which git does not know`, { commands: ['git config --global gpg.format ssh'] });
116
+ else add('format', 'ok', `signing with ${method === 'ssh' ? 'an SSH key' : 'a GPG key'}${format === 'openpgp' && !cfg('gpg.format') ? ' (git\'s default)' : ''}`);
117
+ if (email) add('email', 'ok', `commits are made as ${forTerminal(email)}`);
118
+ else add('email', 'gap', 'user.email is not set, so the platform cannot tie a commit to your account', { commands: ['git config --global user.email "<an email verified on your account>"'] });
119
+
120
+ let localKey = null; // what to look for on the platform: { ssh } or { gpg: Set }
121
+ if (method === 'ssh') {
122
+ const v = gitVersion(gitRun);
123
+ if (atLeast(v, SSH_MIN_GIT)) add('git-version', 'ok', `git ${v.join('.')} can sign with SSH`);
124
+ else add('git-version', 'gap', `git ${v ? v.join('.') : '(unknown version)'} cannot sign with an SSH key: it needs 2.34 or later`, { steps: ['Install a newer git (https://git-scm.com/downloads), then run `yad signing check` again.'] });
125
+ const pub = sshPublicKey(signingkey, { home, dir });
126
+ const keyCommand = !signingkey && cfg('gpg.ssh.defaultKeyCommand');
127
+ if (keyCommand) add('key', 'unknown', `git asks gpg.ssh.defaultKeyCommand (${forTerminal(keyCommand)}) for the key each time: yad cannot tell which key it is`);
128
+ else if (!haveTool('ssh-keygen')) add('key', 'gap', 'ssh-keygen is not on PATH: git signs SSH commits with it', { steps: ['Install OpenSSH (it comes with git on Windows, and with macOS and Linux).'] });
129
+ else if (pub.problem) add('key', 'gap', `the SSH signing key: ${forTerminal(pub.problem)}`, { steps: sshSteps });
130
+ else { add('key', 'ok', `the SSH signing key is ${forTerminal(pub.file || 'given in user.signingkey')}`); localKey = { ssh: pub.key }; }
131
+ if (cfg('gpg.ssh.allowedSignersFile')) add('allowed-signers', 'ok', 'gpg.ssh.allowedSignersFile is set, so git can check signatures here too');
132
+ else {
133
+ add('allowed-signers', 'suggest', 'gpg.ssh.allowedSignersFile is not set: the platform still verifies your commits, but `git log --show-signature` (and yad\'s local check) here cannot', {
134
+ commands: ['echo "$(git config user.email) $(cat ~/.ssh/id_ed25519.pub)" >> ~/.ssh/allowed_signers', 'git config --global gpg.ssh.allowedSignersFile ~/.ssh/allowed_signers'],
135
+ });
136
+ }
137
+ } else if (method === 'gpg') {
138
+ const gpgSteps = [
139
+ 'Make a key (once): gpg --full-generate-key (an RSA 4096 or ed25519 key, with your account\'s email).',
140
+ 'Find its id: gpg --list-secret-keys --keyid-format=long (the part after the slash on the "sec" line).',
141
+ 'Tell git: git config --global user.signingkey <that id> (end it with "!" to sign with that exact part), then git config --global commit.gpgsign true',
142
+ 'Add it to your account: gpg --armor --export <that id>, pasted as a GPG key on the platform\'s settings page (below).',
143
+ ];
144
+ // By email, gpg matches any user id that CONTAINS it: `<email>` asks for that address exactly.
145
+ const target = signingkey || (email ? `<${email}>` : '');
146
+ if (!haveTool('gpg')) add('key', 'gap', 'gpg is not on PATH: git signs with it (or switch to an SSH key, which needs no extra program)', { steps: ['Install GnuPG (https://gnupg.org/download/), or use an SSH key:', ...sshSteps] });
147
+ else if (!target) add('key', 'gap', 'no key is named (user.signingkey is not set) and there is no email to find one by', { steps: gpgSteps });
148
+ else {
149
+ const r = gitRun('gpg', ['--with-colons', '--list-secret-keys', target], { env });
150
+ // A key named in user.signingkey that gpg does not have is most often a typo.
151
+ const noKeySteps = signingkey ? ['Check user.signingkey for a typo against the ids gpg lists (the "Find its id" step below).', ...gpgSteps] : gpgSteps;
152
+ const ids = r.ok ? gpgIds(r.stdout, { signing: true }) : Object.assign(new Set(), { keys: 0, listed: 0, parts: [] });
153
+ const { keys, listed } = ids;
154
+ // The part gpg signs with (GnuPG's finish_lookup): the one a key id ending in `!` names, and no other;
155
+ // else the newest signing subkey (the first listed, on a tie); the primary only when no subkey signs.
156
+ const bang = String(signingkey || '').endsWith('!');
157
+ const pinned = /^(?:0x)?([0-9A-F]{8}|[0-9A-F]{16}|[0-9A-F]{40})!$/i.exec(signingkey || '');
158
+ const all = ids.parts || [];
159
+ const subs = all.filter((part) => part.sub);
160
+ const newest = Math.max(0, ...subs.map((part) => part.created));
161
+ const pin = pinned?.[1].toUpperCase();
162
+ // A short id is the end of the long id and of the fingerprint; a fingerprint ends with the long id (gpg
163
+ // listed by that fingerprint, so a part with the same long id but another fingerprint is not here in practice).
164
+ const parts = pinned ? all.filter((part) => [...part].some((id) => id.endsWith(pin) || (pin.length === 40 && pin.endsWith(id))))
165
+ : subs.length ? [subs.find((part) => part.created === newest)] : all;
166
+ if (bang && !pinned && ids.size) add('key', 'unknown', `user.signingkey (${forTerminal(signingkey)}) ends in "!" but is not a key id, so yad cannot tell which part gpg signs with`);
167
+ else if (pinned && !parts.length && !listed) add('key', 'gap', `gpg has no secret key for ${forTerminal(target)}`, { steps: noKeySteps });
168
+ else if (pinned && !parts.length) add('key', 'gap', `the part user.signingkey names (${forTerminal(signingkey)}) cannot sign now (expired, revoked, without the sign capability, or its secret is not on this machine): gpg signs with that part only`, { steps: ['List the parts: gpg --list-secret-keys --keyid-format=long (the "ssb" lines with [S] are subkeys that sign)', 'Name one that signs: git config --global user.signingkey <its id>! (or drop the "!" to let gpg pick)'] });
169
+ // A pin to one part settles which key, even when the email finds several.
170
+ else if (keys > 1 && !(pinned && parts.length === 1)) add('key', 'gap', `gpg has ${keys} secret keys for ${forTerminal(target)}: git may sign with any of them`, { commands: ['git config --global user.signingkey <the key id to sign with>'], steps: ['List them: gpg --list-secret-keys --keyid-format=long'] });
171
+ else if (ids.size) {
172
+ add('key', 'ok', parts.some((part) => part.card) ? `the GPG key ${forTerminal(target)} can sign; the part gpg signs with is on a smartcard, so the card must be inserted` : `the GPG key ${forTerminal(target)} is on this machine and can sign`);
173
+ // Every id of the key gpg signs with (dead parts too), for the "not the part" message: never another
174
+ // key that only shares the email.
175
+ const owners = new Set(parts.map((part) => part.primary));
176
+ localKey = { gpg: parts, all: new Set(gpgIds(r.stdout).parts.filter((part) => owners.has(part.primary)).flatMap((part) => [...part])) };
177
+ }
178
+ else if (listed) add('key', 'gap', `the GPG key ${forTerminal(target)} cannot sign now (expired, revoked, without the sign capability, or its secret is not on this machine)`, { steps: gpgSteps });
179
+ else add('key', 'gap', `gpg has no secret key for ${forTerminal(target)}`, { steps: noKeySteps });
180
+ }
181
+ }
182
+
183
+ // --- the platform ---
184
+ const identity = root ? productIdentity(root) : null;
185
+ if (!identity?.platform) {
186
+ notes.push(root ? 'the Product names no platform: nothing on an account to check' : 'no Product here: only this machine is checked (run it from the Product, or a repo it registers, to check the account too)');
187
+ } else {
188
+ platformRows({ identity, method, localKey, email, runner, gitRun, haveTool, env, add });
189
+ }
190
+
191
+ const count = (s) => findings.filter((f) => f.status === s).length;
192
+ // Complete only when the account was read too: with no platform, half the question is open.
193
+ const summary = { gaps: count('gap'), suggestions: count('suggest'), unknown: count('unknown'), complete: count('unknown') === 0 && !!identity?.platform, accountChecked: !!identity?.platform };
194
+ return { method, platform: identity?.platform ?? null, host: identity?.host ?? null, findings, summary, ...(notes.length ? { notes } : {}) };
195
+ }
196
+
197
+ // The account's half: the key listed for SIGNING, and the commit email verified on it.
198
+ function platformRows({ identity, method, localKey, email, runner, gitRun, haveTool, env, add }) {
199
+ const { platform, host } = identity;
200
+ const name = PLATFORM_NAME[platform];
201
+ const cli = platform === 'github' ? 'gh' : 'glab';
202
+ const unknownBoth = (why, fix) => { add('platform-key', 'unknown', `${name}: ${why}`, fix); add('platform-email', 'unknown', `${name}: ${why}`, fix); };
203
+ if (env.YAD_PLATFORM_READ === '0') return unknownBoth('platform reads are off (YAD_PLATFORM_READ=0)');
204
+ if (!haveTool(cli)) return unknownBoth(`${cli} is not installed, so your account cannot be read`, { steps: [`Install ${cli}, log in, then run \`yad signing check\` again.`] });
205
+ if (!loggedIn(runner, cli, host, new Map())) {
206
+ return unknownBoth(`not logged in to ${host}, so your account cannot be read`, { commands: [platform === 'github' ? `gh auth login --hostname ${host}` : `glab auth login --hostname ${host}`] });
207
+ }
208
+ const read = (p) => api(runner, cli, host, p);
209
+ const scopeFix = (scope) => (platform === 'github'
210
+ ? { commands: [`gh auth refresh -h ${host} -s ${scope}`] }
211
+ : { steps: ['Log glab in with a token that has the read_user scope: glab auth login --hostname ' + host] });
212
+ const refused = (res) => res.status === 403 || res.status === 404 || res.status === 401;
213
+ // A refusal of the user's own list means the login lacks the scope (GitHub answers 404 for that); anything
214
+ // else (offline, an unreadable answer) is said as protection.mjs says it.
215
+ const notRead = (res, what, scope) => (refused(res)
216
+ ? `${name} would not list ${what} (HTTP ${res.status}): ${platform === 'github' ? `the login needs the ${scope} scope` : 'the token needs the read_user scope'}`
217
+ : whyFailed(res, { platform, host, what, plural: true }));
218
+ const keysPage = platform === 'github' ? `https://${host}/settings/keys` : `https://${host}/-/user_settings/${method === 'gpg' ? 'gpg_keys' : 'ssh_keys'}`;
219
+
220
+ // The key.
221
+ if (!localKey) add('platform-key', 'unknown', `${name}: the key on this machine could not be read, so it cannot be matched (fix the key above first)`);
222
+ else if (method === 'ssh') {
223
+ const path_ = platform === 'github' ? `user/ssh_signing_keys?per_page=${PAGE}` : `user/keys?per_page=${PAGE}`;
224
+ const res = read(path_);
225
+ if (!res.ok) add('platform-key', 'unknown', notRead(res, 'your SSH keys', 'read:ssh_signing_key'), refused(res) ? scopeFix('read:ssh_signing_key') : null);
226
+ else {
227
+ const list = Array.isArray(res.body) ? res.body : [];
228
+ const hit = list.find((k) => keyText(k?.key) === localKey.ssh);
229
+ const signing = platform === 'github' ? !!hit : !!hit && ['signing', 'auth_and_signing'].includes(hit.usage_type);
230
+ if (signing) add('platform-key', 'ok', `${name} lists your SSH key for signing`);
231
+ else if (!hit && list.length >= PAGE) add('platform-key', 'unknown', `${name}: your account has ${PAGE} or more keys and only the first ${PAGE} were read`);
232
+ else {
233
+ // GitHub keeps signing keys apart from authentication keys: say which it is, when the token can tell.
234
+ let only = !!hit;
235
+ if (platform === 'github') { const auth = read(`user/keys?per_page=${PAGE}`); only = auth.ok && Array.isArray(auth.body) && auth.body.some((k) => keyText(k?.key) === localKey.ssh); }
236
+ add('platform-key', 'gap', only ? `${name} has your SSH key for logging in only, not for signing` : `${name} does not list your SSH key for signing`, {
237
+ url: keysPage,
238
+ steps: [platform === 'github' ? `Open ${keysPage} → New SSH key → Key type: Signing Key → paste your .pub file.` : `Open ${keysPage} → add (or edit) the key → Usage type: Authentication & Signing (or Signing) → paste your .pub file.`, 'Then run `yad signing check` again.'],
239
+ });
240
+ }
241
+ }
242
+ } else if (method === 'gpg') {
243
+ const res = read(`user/gpg_keys?per_page=${PAGE}`);
244
+ if (!res.ok) add('platform-key', 'unknown', notRead(res, 'your GPG keys', 'read:gpg_key'), refused(res) ? scopeFix('read:gpg_key') : null);
245
+ else {
246
+ const list = Array.isArray(res.body) ? res.body : [];
247
+ // Every id the account lists, and those of copies still in force: an expired or revoked copy there
248
+ // marks new commits Unverified even when the key here was renewed.
249
+ let remote = new Set();
250
+ let live = new Set();
251
+ const unclear = new Set(); // an expiry date yad cannot read: neither in force nor out
252
+ let readable = true;
253
+ const now = Date.now();
254
+ // 'live', 'dead', or 'unclear' for one GitHub key or subkey.
255
+ const state = (k) => {
256
+ if (k?.revoked === true) return 'dead';
257
+ if (!k?.expires_at) return 'live';
258
+ const t = Date.parse(k.expires_at);
259
+ return Number.isNaN(t) ? 'unclear' : t <= now ? 'dead' : 'live';
260
+ };
261
+ if (platform === 'github') {
262
+ for (const k of list) {
263
+ const top = state(k);
264
+ for (const sub of [k, ...(Array.isArray(k?.subkeys) ? k.subkeys : [])]) {
265
+ if (typeof sub?.key_id !== 'string') continue;
266
+ const id = sub.key_id.toUpperCase();
267
+ const own = sub === k ? top : state(sub);
268
+ remote.add(id);
269
+ if (top === 'dead' || own === 'dead') continue;
270
+ if (top === 'unclear' || own === 'unclear') unclear.add(id);
271
+ else live.add(id);
272
+ }
273
+ }
274
+ } else if (haveTool('gpg')) {
275
+ // GitLab lists the armored key only: gpg reads its ids without importing it.
276
+ for (const k of list) {
277
+ if (typeof k?.key !== 'string') continue;
278
+ const out = gitRun('gpg', ['--with-colons', '--import-options', 'show-only', '--import'], { input: k.key, env }).stdout;
279
+ remote = new Set([...remote, ...gpgIds(out)]);
280
+ live = new Set([...live, ...gpgIds(out, { live: true })]);
281
+ }
282
+ } else readable = false;
283
+ // The part gpg signs with (see the key row) must be listed and in force, or commits show as Unverified.
284
+ const has = (set) => (part) => [...part].some((a) => [...set].some((b) => sameKey(a, b)));
285
+ const parts = localKey.gpg;
286
+ const reupload = { url: keysPage, steps: ['Export it again: gpg --armor --export <your key id>', `Open ${keysPage} → remove the old copy → New GPG key → paste it.`, 'Then run `yad signing check` again.'] };
287
+ if (parts.length && parts.every(has(live))) add('platform-key', 'ok', `${name} lists your GPG key`);
288
+ else if (parts.some((p) => has(remote)(p) && !has(live)(p) && !has(unclear)(p))) add('platform-key', 'gap', `${name} lists your GPG key, but its copy there has expired, was revoked or is not valid: new commits show as Unverified`, reupload);
289
+ else if (parts.some(has(unclear))) add('platform-key', 'unknown', `${name} lists your GPG key with an expiry date yad cannot read`);
290
+ else if (has(remote)(localKey.all)) add('platform-key', 'gap', `${name} lists your GPG key, but not the part gpg signs with (a subkey added after the upload?)`, reupload);
291
+ else if (!readable) add('platform-key', 'unknown', `${name} lists GPG keys yad cannot read without gpg`);
292
+ else if (list.length >= PAGE) add('platform-key', 'unknown', `${name}: your account has ${PAGE} or more GPG keys and only the first ${PAGE} were read`);
293
+ else add('platform-key', 'gap', `${name} does not list your GPG key`, { url: keysPage, steps: [`Export it: gpg --armor --export <your key id>`, `Open ${keysPage} → New GPG key → paste it.`, 'Then run `yad signing check` again.'] });
294
+ }
295
+ }
296
+
297
+ // The email.
298
+ if (!email) add('platform-email', 'unknown', `${name}: no commit email to look for (set user.email above)`);
299
+ else if (platform === 'github') {
300
+ const noreply = `users.noreply.${host === 'github.com' ? 'github.com' : host}`;
301
+ if (email.toLowerCase().endsWith(`@${noreply}`)) {
302
+ // A no-reply address is verified for the ONE account it names: `<id>+<login>@` or `<login>@`.
303
+ const u = read('user');
304
+ if (!u.ok) add('platform-email', 'unknown', notRead(u, 'your account', 'read:user'), refused(u) ? scopeFix('read:user') : null);
305
+ else if (!u.body?.login) add('platform-email', 'unknown', `${name} did not say which account this login is, so the no-reply address cannot be matched`);
306
+ else {
307
+ const local = email.slice(0, email.lastIndexOf('@')).toLowerCase();
308
+ const login = String(u.body.login).toLowerCase();
309
+ const { id } = u.body;
310
+ if (local === login || (id != null && local === `${id}+${login}`)) add('platform-email', 'ok', `${forTerminal(email)} is your ${name} no-reply address`);
311
+ // `<id>+<login>@` with no id in the answer: it may be this account's.
312
+ else if (id == null && local.endsWith(`+${login}`)) add('platform-email', 'unknown', `${name} did not give this account's id, so ${forTerminal(email)} cannot be matched`);
313
+ else add('platform-email', 'gap', `${forTerminal(email)} is a ${name} no-reply address, but not this account's (${forTerminal(u.body.login)})`, { url: `https://${host}/settings/emails`, steps: [`Use your own: git config --global user.email "${id != null ? `${id}+` : ''}${u.body.login}@${noreply}"`] });
314
+ }
315
+ } else {
316
+ const res = read(`user/emails?per_page=${PAGE}`);
317
+ if (!res.ok) add('platform-email', 'unknown', notRead(res, 'your email addresses', 'user:email'), refused(res) ? scopeFix('user:email') : null);
318
+ else {
319
+ const list = Array.isArray(res.body) ? res.body : [];
320
+ emailRow(add, name, email, list.filter((e) => e?.verified).map((e) => e.email), list.map((e) => e?.email), list.length >= PAGE, `https://${host}/settings/emails`);
321
+ }
322
+ }
323
+ } else {
324
+ const u = read('user');
325
+ const e = read(`user/emails?per_page=${PAGE}`);
326
+ if (!u.ok) add('platform-email', 'unknown', notRead(u, 'your account', 'read_user'), refused(u) ? scopeFix('read_user') : null);
327
+ else {
328
+ const others = e.ok && Array.isArray(e.body) ? e.body : [];
329
+ const confirmed = [u.body?.email, u.body?.commit_email, ...others.filter((x) => x?.confirmed_at).map((x) => x.email)];
330
+ const all = [...confirmed, ...others.map((x) => x?.email)];
331
+ if (!e.ok && !confirmed.some((x) => sameEmail(x, email))) add('platform-email', 'unknown', `${name}: your other email addresses could not be read — the token needs the read_user scope`, scopeFix('read_user'));
332
+ else emailRow(add, name, email, confirmed, all, others.length >= PAGE, `https://${host}/-/profile/emails`);
333
+ }
334
+ }
335
+ }
336
+ const sameEmail = (a, b) => typeof a === 'string' && typeof b === 'string' && a.toLowerCase() === b.toLowerCase();
337
+ function emailRow(add, name, email, verified, all, full, url) {
338
+ if (verified.some((x) => sameEmail(x, email))) return add('platform-email', 'ok', `${forTerminal(email)} is verified on your ${name} account`);
339
+ if (all.some((x) => sameEmail(x, email))) return add('platform-email', 'gap', `${forTerminal(email)} is on your ${name} account but not verified, so your commits are not marked Verified`, { url, steps: [`Open ${url} and verify it (the platform emails you a link).`] });
340
+ if (full) return add('platform-email', 'unknown', `${name}: only the first page of your email addresses was read`);
341
+ return add('platform-email', 'gap', `${forTerminal(email)} is not on your ${name} account, so your commits are not marked Verified`, { url, steps: [`Add it at ${url} and verify it, or set user.email to an address that is: git config --global user.email "<that address>"`] });
342
+ }
343
+
344
+ // The doctor line: this machine only (no network), so `yad doctor` stays quick.
345
+ export function signingDoctorLine(dir, { gitRun = run } = {}) {
346
+ const cfg = (key, bool = false) => { const r = gitRun('git', ['config', ...(bool ? ['--bool'] : []), '--get', key], { cwd: dir }); return r.ok ? r.stdout : ''; };
347
+ const hint = '`yad signing check` says what to set up';
348
+ if (cfg('commit.gpgsign', true) !== 'true') return { status: 'warn', message: 'commits made here are not signed', hint };
349
+ const format = cfg('gpg.format') || 'openpgp';
350
+ const method = { ssh: 'SSH', openpgp: 'GPG', x509: 'X.509' }[format];
351
+ if (!method) return { status: 'warn', message: `gpg.format is "${forTerminal(format)}", which git does not know`, hint };
352
+ if (method === 'SSH' && !cfg('user.signingkey') && !cfg('gpg.ssh.defaultKeyCommand')) return { status: 'warn', message: 'commits made here are set to be signed with SSH, but no key is named', hint };
353
+ return { status: 'ok', message: `commits made here are signed (${method})`, hint: '`yad signing check` also confirms your account lists the key' };
354
+ }
355
+
356
+ // `yad signing check [--json]`.
357
+ export function runSigningCheck(dir, { root = null, json = false } = {}) {
358
+ const r = signingCheck(dir, { root });
359
+ if (!json) {
360
+ log(c.bold('\nyad signing check'));
361
+ const mark = { ok: ok, gap: fail, suggest: warn, unknown: info };
362
+ for (const f of r.findings) {
363
+ mark[f.status](`${f.status === 'unknown' ? 'not known — ' : ''}${f.message}`);
364
+ for (const cmd of f.fix?.commands || []) hand(cmd);
365
+ for (const s of f.fix?.steps || []) log(c.dim(` ${s}`));
366
+ }
367
+ for (const n of r.notes || []) info(n);
368
+ const { gaps, unknown } = r.summary;
369
+ log('');
370
+ if (gaps) log(c.bold(`${gaps} thing(s) to set up: these are yours (a key is a secret, and the account is yours) — then run \`yad signing check\` again.`));
371
+ else if (unknown) log(c.bold(`${unknown} item(s) not read — not cleared.`));
372
+ else if (!r.summary.accountChecked) ok('this machine is set to sign your commits — your account was not checked (see the note above)');
373
+ else ok('your commits will be signed, and your account can verify them');
374
+ }
375
+ if (r.summary.gaps) process.exitCode = 1;
376
+ return r;
377
+ }