yadflow 4.10.0 → 4.12.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 (120) hide show
  1. package/CHANGELOG.md +152 -0
  2. package/README.md +14 -3
  3. package/bin/commands.mjs +7 -1
  4. package/bin/yad.mjs +163 -16
  5. package/cli/agent-guard-worker.mjs +13 -0
  6. package/cli/agent-guard.mjs +1053 -57
  7. package/cli/agent-rules.mjs +59 -3
  8. package/cli/argv-flags.mjs +2 -2
  9. package/cli/brain/vendor/LICENSE-graphology-library.txt +21 -0
  10. package/cli/brain/vendor/LICENSE-graphology.txt +21 -0
  11. package/cli/brain/vendor/LICENSE-sigma.txt +12 -0
  12. package/cli/brain/vendor/graphology-library.min.js +2 -0
  13. package/cli/brain/vendor/graphology.umd.min.js +2 -0
  14. package/cli/brain/vendor/sigma.min.js +1369 -0
  15. package/cli/brain/view/app.js +382 -0
  16. package/cli/brain/view/index.html +63 -0
  17. package/cli/brain/view/live.css +228 -0
  18. package/cli/brain/view/live.html +110 -0
  19. package/cli/brain/view/live.js +884 -0
  20. package/cli/brain/view/style.css +141 -0
  21. package/cli/brain-about.mjs +206 -0
  22. package/cli/brain-activity.mjs +285 -0
  23. package/cli/brain-skills.mjs +118 -0
  24. package/cli/brain-vendor.mjs +71 -0
  25. package/cli/brain-view.mjs +345 -0
  26. package/cli/brain.mjs +810 -0
  27. package/cli/brand-cmd.mjs +326 -0
  28. package/cli/brand.mjs +327 -0
  29. package/cli/ci-check.mjs +3 -3
  30. package/cli/doctor.mjs +145 -14
  31. package/cli/epic-state.mjs +93 -1
  32. package/cli/epic.mjs +15 -3
  33. package/cli/errors.mjs +2 -1
  34. package/cli/find-product.mjs +69 -15
  35. package/cli/foundation-publish.mjs +256 -0
  36. package/cli/gate.mjs +29 -3
  37. package/cli/git-read.mjs +38 -0
  38. package/cli/guard-stream.mjs +409 -0
  39. package/cli/guide.mjs +26 -3
  40. package/cli/hook.mjs +59 -9
  41. package/cli/issues-act.mjs +57 -13
  42. package/cli/issues-write.mjs +19 -6
  43. package/cli/issues.mjs +69 -24
  44. package/cli/lib.mjs +37 -2
  45. package/cli/local-page.mjs +138 -0
  46. package/cli/local-setup-record.mjs +71 -0
  47. package/cli/local-setup-steps.mjs +186 -0
  48. package/cli/local-setup.mjs +611 -0
  49. package/cli/machine.mjs +1 -1
  50. package/cli/manifest.mjs +55 -0
  51. package/cli/map/view/app.js +712 -0
  52. package/cli/map/view/index.html +50 -0
  53. package/cli/map/view/style.css +142 -0
  54. package/cli/map-view.mjs +190 -0
  55. package/cli/map.mjs +637 -0
  56. package/cli/members.mjs +9 -15
  57. package/cli/next.mjs +1 -1
  58. package/cli/openpr.mjs +2 -2
  59. package/cli/plain-text.mjs +22 -0
  60. package/cli/plan.mjs +310 -36
  61. package/cli/platform.mjs +5 -5
  62. package/cli/product-index.mjs +1 -1
  63. package/cli/protection.mjs +32 -0
  64. package/cli/reconcile.mjs +61 -13
  65. package/cli/report.mjs +9 -3
  66. package/cli/reports-dir.mjs +393 -0
  67. package/cli/reports.mjs +65 -0
  68. package/cli/run-checks.mjs +5 -2
  69. package/cli/scan.mjs +4 -6
  70. package/cli/secret-text.mjs +66 -0
  71. package/cli/setup.mjs +54 -8
  72. package/cli/standup.mjs +94 -72
  73. package/cli/status.mjs +6 -5
  74. package/cli/test-agents-file.mjs +614 -8
  75. package/cli/test-brain-activity.mjs +753 -0
  76. package/cli/test-brain-view.mjs +381 -0
  77. package/cli/test-brain.mjs +795 -0
  78. package/cli/test-brand.mjs +558 -0
  79. package/cli/test-guide.mjs +438 -0
  80. package/cli/test-local-setup.mjs +1188 -0
  81. package/cli/test-machine.mjs +59 -0
  82. package/cli/test-map.mjs +615 -0
  83. package/cli/test-reports.mjs +382 -0
  84. package/cli/test-run-checks.mjs +4 -0
  85. package/cli/test-worktree.mjs +24 -3
  86. package/cli/toolbox-connect.mjs +21 -6
  87. package/cli/toolbox.mjs +74 -5
  88. package/cli/update-commit.mjs +118 -9
  89. package/cli/usage.mjs +17 -7
  90. package/cli/workspace.mjs +11 -2
  91. package/package.json +8 -4
  92. package/skills/sdlc/module-help.csv +1 -0
  93. package/skills/yad-architecture/SKILL.md +22 -4
  94. package/skills/yad-brand/SKILL.md +69 -0
  95. package/skills/yad-change/SKILL.md +3 -1
  96. package/skills/yad-change/references/triage.md +2 -0
  97. package/skills/yad-checks/SKILL.md +2 -0
  98. package/skills/yad-checks/references/check-gates.md +8 -5
  99. package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
  100. package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
  101. package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
  102. package/skills/yad-checks/templates/github/yad-checks.yml +3 -2
  103. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +3 -2
  104. package/skills/yad-checks/templates/hooks/local-setup-notice.mjs +96 -0
  105. package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
  106. package/skills/yad-connect-repos/SKILL.md +14 -0
  107. package/skills/yad-discovery/SKILL.md +11 -0
  108. package/skills/yad-discovery/references/foundation-schema.md +11 -0
  109. package/skills/yad-docs/templates/app/package-lock.json +18 -10
  110. package/skills/yad-docs/templates/app/package.json +6 -1
  111. package/skills/yad-epic/SKILL.md +3 -0
  112. package/skills/yad-epic/references/state-schema.md +35 -1
  113. package/skills/yad-guide/SKILL.md +10 -7
  114. package/skills/yad-implement/SKILL.md +76 -15
  115. package/skills/yad-issues/SKILL.md +2 -1
  116. package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
  117. package/skills/yad-pr-template/templates/checks/pr-title.sh +8 -4
  118. package/skills/yad-spec/SKILL.md +19 -0
  119. package/skills/yad-stories/SKILL.md +22 -4
  120. package/skills/yad-stories/references/story-schema.md +1 -1
@@ -0,0 +1,138 @@
1
+ // A page served to this machine only, or written as one self-contained file (E177, shared since E181).
2
+ //
3
+ // `yad brain view` (E177) and `yad map` (E181) both draw a page in the person's browser. The rules that keep
4
+ // that page safe live here, once:
5
+ // - the server binds 127.0.0.1 on a random port; every request needs the one-time key (`?t=`), compared in
6
+ // constant time; the Host header must be the address printed (no DNS rebinding); GET and HEAD only; a
7
+ // fixed route table, so no request path ever reaches the filesystem; strict headers (CSP, no-store,
8
+ // no-referrer, no framing);
9
+ // - the self-contained file holds every script and style inline, allowed by their hashes and nothing else,
10
+ // with the data in a `<script type="application/json">` that no name can close;
11
+ // - a file the person names is written by a temp file and a rename, never through a link, and a warning
12
+ // says when it sits in a git work tree that does not ignore it.
13
+ import fs from 'node:fs';
14
+ import http from 'node:http';
15
+ import path from 'node:path';
16
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
17
+ import { spawnSync } from 'node:child_process';
18
+ import { writePlain } from './brain.mjs';
19
+
20
+ export const CSP = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
21
+ export const BASE_HEADERS = Object.freeze({
22
+ 'Content-Security-Policy': CSP,
23
+ 'X-Content-Type-Options': 'nosniff',
24
+ 'Cache-Control': 'no-store',
25
+ 'Referrer-Policy': 'no-referrer',
26
+ 'Cross-Origin-Resource-Policy': 'same-origin',
27
+ 'Cross-Origin-Opener-Policy': 'same-origin',
28
+ 'X-Frame-Options': 'DENY',
29
+ });
30
+ export const TYPES = Object.freeze({ html: 'text/html; charset=utf-8', js: 'text/javascript; charset=utf-8', css: 'text/css; charset=utf-8', json: 'application/json; charset=utf-8' });
31
+
32
+ // Is `given` the token? A length check first: `timingSafeEqual` throws on buffers of different lengths.
33
+ export function tokenMatches(given, token) {
34
+ if (typeof given !== 'string') return false;
35
+ const a = Buffer.from(given);
36
+ const b = Buffer.from(token);
37
+ return a.length === b.length && timingSafeEqual(a, b);
38
+ }
39
+
40
+ // Start a locked-down page server: { url, token, port, host, server, close() }.
41
+ // routes(token) → Map(pathname → () => { type, body, status? }) — a request path is only ever a KEY.
42
+ // stream optional { path, attach(req, res, headers), close() } — a one-way event stream (SSE).
43
+ export function startPageServer({ routes, stream = null, host = '127.0.0.1', port = 0, failText = 'the page could not read its files' }) {
44
+ const token = randomBytes(24).toString('hex');
45
+ const table = routes(token);
46
+ let expectedHost = null;
47
+ const server = http.createServer((req, res) => {
48
+ const send = (status, type, body, extra = {}) => {
49
+ res.writeHead(status, { ...BASE_HEADERS, 'Content-Type': type, ...extra });
50
+ res.end(req.method === 'HEAD' ? undefined : body);
51
+ };
52
+ const text = (status, msg, extra) => send(status, 'text/plain; charset=utf-8', `${msg}\n`, extra);
53
+ if (req.method !== 'GET' && req.method !== 'HEAD') return text(405, 'method not allowed', { Allow: 'GET, HEAD' });
54
+ if (req.headers.host !== expectedHost) return text(403, 'forbidden');
55
+ let url;
56
+ try { url = new URL(req.url, `http://${expectedHost}`); } catch { return text(400, 'bad request'); }
57
+ if (!tokenMatches(url.searchParams.get('t'), token)) return text(403, 'forbidden');
58
+ if (stream && url.pathname === (stream.path || '/events') && req.method === 'GET') return stream.attach(req, res, BASE_HEADERS);
59
+ const route = table.get(url.pathname);
60
+ if (!route) return text(404, 'not found');
61
+ try {
62
+ const r = route();
63
+ return send(r.status || 200, r.type, r.body);
64
+ } catch {
65
+ return text(500, failText);
66
+ }
67
+ });
68
+ return new Promise((resolve, reject) => {
69
+ server.once('error', reject);
70
+ server.listen(port, host, () => {
71
+ const a = server.address();
72
+ expectedHost = `${host}:${a.port}`;
73
+ resolve({
74
+ url: `http://${expectedHost}/?t=${token}`, token, port: a.port, host, server,
75
+ close: () => new Promise((done) => { stream?.close(); server.closeAllConnections?.(); server.close(() => done()); }),
76
+ });
77
+ });
78
+ });
79
+ }
80
+
81
+ // JSON that can sit inside a <script> element: nothing in it can end the element or start a comment.
82
+ export const scriptSafeJSON = (value) => JSON.stringify(value)
83
+ .replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026')
84
+ .replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
85
+ const sha256b64 = (s) => createHash('sha256').update(s, 'utf8').digest('base64');
86
+
87
+ export const SERVED_START = '<!--SERVED:start-->';
88
+ export const SERVED_END = '<!--SERVED:end-->';
89
+
90
+ // One HTML file with everything inline, and a CSP that allows exactly the inline blocks it holds (by hash)
91
+ // and no network at all. `shell` is the served page: its `<script src>` tags sit between the SERVED markers
92
+ // and are cut out by them (never by matching HTML with a pattern), its stylesheet link becomes a <style>, and
93
+ // `<!--SCRIPTS-->` becomes the data block followed by each script.
94
+ export function inlineSnapshot({ shell, scripts, css, dataId, data }) {
95
+ // A script's own text must not hold `</script`, or the file would end it early: checked here, so a future
96
+ // file that holds one fails loudly instead of breaking the page.
97
+ for (const s of scripts) if (/<\/script/i.test(s)) throw new Error('an inline script holds </script');
98
+ const csp = [
99
+ "default-src 'none'",
100
+ `script-src ${scripts.map((s) => `'sha256-${sha256b64(s)}'`).join(' ')}`,
101
+ `style-src 'sha256-${sha256b64(css)}'`,
102
+ "img-src data:", "font-src data:", "base-uri 'none'", "form-action 'none'",
103
+ ].join('; ');
104
+ // The key placeholder goes before anything is spliced in: the data's own names may hold the same text.
105
+ const page = shell.replaceAll('__TOKEN__', '');
106
+ const from = page.indexOf(SERVED_START);
107
+ const to = page.indexOf(SERVED_END);
108
+ if (from < 0 || to < from) throw new Error(`the page has no ${SERVED_START} … ${SERVED_END} block`);
109
+ const body = (page.slice(0, from) + page.slice(to + SERVED_END.length))
110
+ .replace(/<link rel="stylesheet"[^>]*>/, () => `<style>${css}</style>`)
111
+ .replace('<!--SCRIPTS-->', () => [
112
+ `<script type="application/json" id="${dataId}">${scriptSafeJSON(data)}</script>`,
113
+ ...scripts.map((s) => `<script>${s}</script>`),
114
+ ].join('\n'));
115
+ return body
116
+ .replace(/<meta http-equiv="Content-Security-Policy"[^>]*>/, () => `<meta http-equiv="Content-Security-Policy" content="${csp}">`);
117
+ }
118
+
119
+ // Write `data` to the path the person named, by a temp file and a rename, refusing a link at the target (a
120
+ // rename replaces a link, but a person who put one there means the file it points at). → null | problem
121
+ export function writeOwnFile(file, data) {
122
+ let st = null;
123
+ try { st = fs.lstatSync(file); } catch { /* new file */ }
124
+ if (st && !st.isFile()) return `${file} is not a plain file (a link or a folder) — name another path`;
125
+ const dir = path.dirname(file);
126
+ if (!fs.existsSync(dir)) return `the folder ${dir} does not exist`;
127
+ writePlain(dir, path.basename(file), data);
128
+ return null;
129
+ }
130
+
131
+ // Is `file` inside a git work tree, and NOT ignored there? Then committing it is one `git add .` away.
132
+ export function trackedRisk(file, runner = spawnSync) {
133
+ const dir = path.dirname(file);
134
+ const inTree = runner('git', ['-C', dir, 'rev-parse', '--is-inside-work-tree'], { encoding: 'utf8' });
135
+ if (inTree.status !== 0 || String(inTree.stdout).trim() !== 'true') return false;
136
+ const ignored = runner('git', ['-C', dir, 'check-ignore', '-q', '--', path.basename(file)], { encoding: 'utf8' });
137
+ return ignored.status === 1;
138
+ }
@@ -0,0 +1,71 @@
1
+ // E185 part 2 — what THIS machine did with the local setup script: the steps the person did or said no to.
2
+ //
3
+ // <git-common-dir>/yad/local-setup-done.json { steps: { <id>: { hash, state: 'done'|'skipped', at, reason? } } }
4
+ //
5
+ // Inside git's own folder, so it is never committed, and every worktree of one clone shares it (the same folder
6
+ // `yad capture` keeps its state in). It holds only this person's answers: deleting it asks the questions again.
7
+ //
8
+ // An answer is tied to the step's hash (stepHash: what the step runs and how it is checked). When a step's
9
+ // commands change, the old answer no longer counts, and the person is asked again.
10
+ //
11
+ // One record per clone, keyed by step id: two worktrees on branches whose script differs share it, so an answer
12
+ // given in one replaces the other's, and that step reads as changed there until it is answered again.
13
+
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { isPlainObject, run, writeJSON } from './lib.mjs';
17
+ import { err } from './errors.mjs';
18
+
19
+ export const RECORD_STATES = Object.freeze(['done', 'skipped']);
20
+ const RECORD_NAME = path.join('yad', 'local-setup-done.json');
21
+
22
+ // The record's path for the clone `root` is in, or null when `root` is not in a git clone.
23
+ export function localSetupRecordPath(root) {
24
+ const r = run('git', ['-C', root, 'rev-parse', '--path-format=absolute', '--git-common-dir']);
25
+ return r.ok && r.stdout ? path.join(r.stdout, RECORD_NAME) : null;
26
+ }
27
+
28
+ const sound = (e) => isPlainObject(e) && typeof e.hash === 'string' && RECORD_STATES.includes(e.state);
29
+
30
+ // For showing: `{ path, entries, error }`. A file that cannot be read counts as empty (it only remembers answers),
31
+ // and `error` says why. An entry of the wrong shape is left out.
32
+ export function readLocalSetupRecord(root) {
33
+ const file = localSetupRecordPath(root);
34
+ if (!file) return { path: null, entries: {}, error: null };
35
+ let text;
36
+ try { text = fs.readFileSync(file, 'utf8'); } catch (e) { return { path: file, entries: {}, error: e.code === 'ENOENT' ? null : 'cannot be read' }; }
37
+ let doc;
38
+ try { doc = JSON.parse(text); } catch { return { path: file, entries: {}, error: 'does not parse' }; }
39
+ if (!isPlainObject(doc) || (doc.steps !== undefined && !isPlainObject(doc.steps))) return { path: file, entries: {}, error: 'is not the shape yad writes' };
40
+ // A null prototype: a `__proto__` key in the file is an id like any other, never this object's prototype.
41
+ const entries = Object.create(null);
42
+ for (const [id, e] of Object.entries(doc.steps ?? {})) if (sound(e)) entries[id] = e;
43
+ return { path: file, entries, error: null };
44
+ }
45
+
46
+ // The answer that counts for a step: its entry, only when made for the step as it is now.
47
+ export const answerFor = (entries, step) => {
48
+ const e = Object.hasOwn(entries, step.id) ? entries[step.id] : null;
49
+ return e && e.hash === step.hash ? e : null;
50
+ };
51
+
52
+ // Record answers: `answers` is a list of { id, hash, state, reason? }. Read strictly first — a file that does not
53
+ // parse is refused, never replaced, so no answer already there is lost. Every other key and entry is kept.
54
+ export function writeLocalSetupAnswers(root, answers, { now = new Date() } = {}) {
55
+ const file = localSetupRecordPath(root);
56
+ if (!file) throw new Error(`${root} is not in a git clone, so this machine's local setup answers have nowhere to go`);
57
+ let doc = {};
58
+ if (fs.existsSync(file)) {
59
+ try { doc = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { doc = null; }
60
+ if (!isPlainObject(doc) || (doc.steps !== undefined && !isPlainObject(doc.steps))) {
61
+ throw err('YAD-STATE-001', `${file} is not the record yad writes, so it was not changed`, 'delete it: it only remembers which local setup steps this machine did or skipped, and `yad local-setup` asks again');
62
+ }
63
+ }
64
+ const steps = { ...(doc.steps ?? {}) };
65
+ const at = now.toISOString();
66
+ for (const a of answers) {
67
+ steps[a.id] = { hash: a.hash, state: a.state, at, ...(a.state === 'skipped' ? { reason: a.reason } : {}) };
68
+ }
69
+ writeJSON(file, { ...doc, steps });
70
+ return file;
71
+ }
@@ -0,0 +1,186 @@
1
+ // E185 — the steps yadflow itself puts in a Product's local setup script (`.sdlc/local-setup.json`).
2
+ //
3
+ // The script is what a team member's agent follows on that person's own machine: after setup or join, and again
4
+ // after every update. Each step says what to run, why (`purpose`), and what it changes for the person (`impact`),
5
+ // so the person decides each one. This module builds yadflow's part, `yadflow[]`; the team's part, `team[]`, is
6
+ // written by `yad local-setup add` and never touched here.
7
+ //
8
+ // THE SAME ON EVERY MACHINE. The file is committed, so every step is built from what the Product records (its
9
+ // platform, its ledger, the team's toolbox choices) and from this release, never from what one machine has or
10
+ // lacks. Whether a step is already done on a machine is its `check`, run on that machine.
11
+ //
12
+ // CHECKS yad RUNS. A yadflow step's check is one of BUILTIN_CHECKS, worked out inside yad without running any
13
+ // program the file names. A team step's check is a shell command from a committed file: yad shows it and never
14
+ // runs it, so nobody who can merge to the Product can run a command on every member's machine.
15
+
16
+ import crypto from 'node:crypto';
17
+ import path from 'node:path';
18
+ import { readJSON, run, has } from './lib.mjs';
19
+ import { VERSION, isVerifiedLedger, productConfigPath } from './manifest.mjs';
20
+ import { cliFor, hostFromGitUrl, plainHost } from './platform.mjs';
21
+ import { TOOLBOX, compare, parseVersion, loadChoices, toolUse, toolStatus } from './toolbox.mjs';
22
+ import { detectInstalled } from './detect.mjs';
23
+ import { gitHookState } from './plan.mjs';
24
+ import { signingDoctorLine } from './signing.mjs';
25
+
26
+ // Bumped when the shipped steps change in a way a reader of the file should know about.
27
+ // 2: a shipped tool's step runs its `yad toolbox connect` recipe (E185 review 1).
28
+ export const LOCAL_SETUP_CATALOGUE_VERSION = 2;
29
+ // The file's own format.
30
+ export const LOCAL_SETUP_VERSION = 1;
31
+ export const LOCAL_SETUP_FILE = '.sdlc/local-setup.json';
32
+ export const LOCAL_SETUP_DOC = 'LOCAL-SETUP.md';
33
+ export const STEP_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
34
+ export const WHEN = Object.freeze(['required', 'optional']);
35
+ export const BUILTIN_CHECKS = Object.freeze(['cli-version', 'platform-login', 'ledger-hook', 'commit-signing', 'tool']);
36
+
37
+ // One-off machine steps a release needs (a new hook to install, a tool to upgrade). `since` is the release that
38
+ // added the step. Add an entry here, in the step shape below, whenever a release asks something of each machine
39
+ // that the derived steps do not already cover.
40
+ export const RELEASE_STEPS = Object.freeze([]);
41
+
42
+ // The content hash: what the step RUNS and how it is checked — never its wording. A machine that did a step is
43
+ // asked again only when this changes, so fixing a typo in a purpose does not re-ask the whole team.
44
+ export function stepHash(step) {
45
+ const body = JSON.stringify({ commands: step.commands ?? [], check: step.check ?? null, when: step.when ?? 'optional' });
46
+ return crypto.createHash('sha256').update(body).digest('hex').slice(0, 16);
47
+ }
48
+
49
+ const step = (s) => ({ source: 'yadflow', vetted: true, verify: null, since: null, ...s });
50
+
51
+ // The CLI version the script asks for: this release, or the one the file already asks for when that is newer. An
52
+ // older yad rewriting the file (any member's `yad check --fix`) must never lower it, or the members who are behind
53
+ // would stop being told to upgrade.
54
+ // Only a plain release number (`4.12.0`, `5.0.0-next.3`) is ever taken from the file: it goes into the command.
55
+ export const PLAIN_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?$/;
56
+ // The first release that writes this file (E185). No yad below it ever did, so a file asking for less was edited
57
+ // by hand: it is never taken as yad's own (a lowered version would send new machines to an old release).
58
+ export const LOCAL_SETUP_SINCE = '4.12.0-0';
59
+ export const fileCliMin = (doc) => {
60
+ const step = Array.isArray(doc?.yadflow) ? doc.yadflow.find((s) => s && typeof s === 'object' && s.id === 'yadflow-cli') : null;
61
+ const min = step?.check?.min;
62
+ if (typeof min !== 'string' || !PLAIN_VERSION.test(min)) return null;
63
+ return compare(parseVersion(min), parseVersion(LOCAL_SETUP_SINCE)) >= 0 ? min : null;
64
+ };
65
+ export function cliMinimum(current) {
66
+ const have = parseVersion(VERSION);
67
+ const was = typeof current === 'string' && PLAIN_VERSION.test(current) ? parseVersion(current) : null;
68
+ return was && have && compare(was, have) > 0 ? current : VERSION;
69
+ }
70
+
71
+ // yadflow's steps for this Product, in the order a person would do them. `cliMin` is the version the CLI step asks
72
+ // for (cliMinimum).
73
+ export function yadflowSteps(root, { cliMin = VERSION } = {}) {
74
+ const config = readJSON(productConfigPath(root), {}) || {};
75
+ const steps = [];
76
+
77
+ steps.push(step({
78
+ id: 'yadflow-cli', title: `Install the yadflow CLI, version ${cliMin} or later`, when: 'required',
79
+ purpose: 'yad is the command every step of this project runs. The project was last set up or updated with this version, and an older yad on your machine can misread its files.',
80
+ impact: 'Replaces the yad command on your machine for every project that uses it. Nothing in any repo changes.',
81
+ commands: [`npm install -g yadflow@${cliMin}`],
82
+ check: { builtin: 'cli-version', min: cliMin },
83
+ verify: 'yad --version',
84
+ }));
85
+
86
+ const cli = typeof config.platform === 'string' ? cliFor(config.platform) : null;
87
+ if (cli) {
88
+ steps.push(step({
89
+ id: 'platform-login', title: `Sign in to ${config.platform === 'gitlab' ? 'GitLab' : 'GitHub'} with ${cli}`, when: 'required',
90
+ purpose: `yad opens pull requests, reads reviews and approvals through ${cli}. Without a login those steps stop.`,
91
+ impact: `Stores a login for ${cli} on your machine. It is yours alone: you type it, never the agent.`,
92
+ commands: [`${cli} auth login`],
93
+ check: { builtin: 'platform-login' },
94
+ verify: `${cli} auth status`,
95
+ person: true,
96
+ }));
97
+ }
98
+
99
+ if (isVerifiedLedger(config)) {
100
+ steps.push(step({
101
+ id: 'ledger-hook', title: 'Install the pre-commit ledger guard in your clone', when: 'required',
102
+ purpose: 'With a verified ledger, approvals and gate files are written by CI only. The hook stops a commit that edits them by hand, before CI refuses it.',
103
+ impact: 'Adds a git hook to your clone of the Product. It runs on each commit there and only refuses ledger edits. Other repos are not touched.',
104
+ commands: ['yad check --fix'],
105
+ check: { builtin: 'ledger-hook' },
106
+ verify: 'yad doctor',
107
+ }));
108
+ steps.push(step({
109
+ id: 'commit-signing', title: 'Sign your commits', when: 'required',
110
+ purpose: 'The verified-commits check refuses commits that are not signed by a known person.',
111
+ impact: 'Changes your git settings so every commit you make is signed. A signing key is a secret: you make it and add it to your account yourself.',
112
+ commands: ['yad signing check'],
113
+ check: { builtin: 'commit-signing' },
114
+ verify: 'yad signing check',
115
+ person: true,
116
+ }));
117
+ }
118
+
119
+ // The tools this team uses (the toolbox choices, E86). None is required: each says what happens without it.
120
+ const choices = loadChoices(root);
121
+ for (const tool of [...TOOLBOX, ...choices.custom]) {
122
+ if (!toolUse(tool, choices).used) continue;
123
+ const own = tool.tier === 'project';
124
+ // A shipped tool has a recipe (E165): `yad toolbox connect` gives the agent its exact, pinned steps and the
125
+ // one question to ask. A team's own tool has no recipe: its install commands are the team's.
126
+ const commands = own ? (tool.install ?? []).map((i) => i.command) : [`yad toolbox connect ${tool.id} --json`];
127
+ steps.push(step({
128
+ id: `tool-${tool.id}`, title: `Install ${tool.name}`, when: 'optional',
129
+ purpose: `Your team uses ${tool.name}: it ${tool.role}.`,
130
+ impact: `Without it: ${tool.fallback}.`,
131
+ commands: commands.length ? commands : [tool.manual ? `set it up by hand: ${tool.manual}` : `see ${tool.source ?? 'its own instructions'}`],
132
+ check: { builtin: 'tool', tool: tool.id },
133
+ verify: 'yad toolbox check',
134
+ // A team's own tool is the team's to vet (E88), even though yad builds the step from it.
135
+ vetted: !own,
136
+ }));
137
+ }
138
+
139
+ for (const s of RELEASE_STEPS) steps.push(step(s));
140
+ return steps;
141
+ }
142
+
143
+ // ---- the built-in checks --------------------------------------------------------------------------
144
+ // Each answers `{ ok, why }` for this machine. They run no program a file names: only git, the platform CLI's
145
+ // own `auth status`, and yad's own detection.
146
+
147
+ export function runBuiltinCheck(check, root, { items = null } = {}) {
148
+ const kind = check?.builtin;
149
+ if (kind === 'cli-version') {
150
+ const have = parseVersion(VERSION);
151
+ const need = parseVersion(check.min);
152
+ const ok = !!(have && need) && compare(have, need) >= 0;
153
+ return { ok, why: ok ? `yad ${VERSION} is installed` : `yad ${VERSION} is older than ${check.min}` };
154
+ }
155
+ if (kind === 'platform-login') {
156
+ const config = readJSON(productConfigPath(root), {}) || {};
157
+ const cli = cliFor(config.platform);
158
+ if (!cli) return { ok: true, why: 'this Product uses no platform' };
159
+ if (!has(cli)) return { ok: false, why: `${cli} is not installed` };
160
+ const host = plainHost(hostFromGitUrl(config.git_url) || hostFromGitUrl(run('git', ['remote', 'get-url', 'origin'], { cwd: root }).stdout));
161
+ // Scoped to the Product's host: an unscoped `auth status` fails when ANY saved login is stale (doctor.mjs).
162
+ if (!host) return { ok: false, why: 'the Product\'s host is not known, so the login was not checked' };
163
+ const ok = run(cli, ['auth', 'status', '--hostname', host]).ok;
164
+ return { ok, why: ok ? `${cli} is signed in to ${host}` : `${cli} is not signed in to ${host}` };
165
+ }
166
+ if (kind === 'ledger-hook') {
167
+ const st = gitHookState(root);
168
+ if (!st.applies) return { ok: true, why: 'this Product does not use the hook' };
169
+ return { ok: st.state === 'ok', why: st.state === 'ok' ? 'the hook is installed' : `the hook is ${st.state}` };
170
+ }
171
+ if (kind === 'commit-signing') {
172
+ const line = signingDoctorLine(root);
173
+ return { ok: line.status === 'ok', why: line.message };
174
+ }
175
+ if (kind === 'tool') {
176
+ const choices = loadChoices(root);
177
+ const tool = [...TOOLBOX, ...choices.custom].find((t) => t.id === check.tool);
178
+ if (!tool) return { ok: false, why: `${check.tool} is not a tool this yadflow knows` };
179
+ const st = toolStatus(tool, items ?? detectInstalled(root).items);
180
+ const ok = st.state === 'installed' || st.state === 'available';
181
+ return { ok, why: ok ? `${tool.name} is here (${st.found.join(', ')})` : `${tool.name} is ${st.state}` };
182
+ }
183
+ return { ok: false, why: 'not a check yad knows' };
184
+ }
185
+
186
+ export const localSetupPath = (root) => path.join(root, LOCAL_SETUP_FILE);