yadflow 4.10.0 → 4.11.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 (106) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +12 -3
  3. package/bin/commands.mjs +5 -1
  4. package/bin/yad.mjs +109 -15
  5. package/cli/agent-guard-worker.mjs +13 -0
  6. package/cli/agent-guard.mjs +1053 -57
  7. package/cli/agent-rules.mjs +34 -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 +344 -0
  26. package/cli/brain.mjs +810 -0
  27. package/cli/ci-check.mjs +3 -3
  28. package/cli/doctor.mjs +80 -13
  29. package/cli/epic-state.mjs +93 -1
  30. package/cli/epic.mjs +15 -3
  31. package/cli/errors.mjs +2 -1
  32. package/cli/find-product.mjs +69 -15
  33. package/cli/foundation-publish.mjs +256 -0
  34. package/cli/gate.mjs +29 -3
  35. package/cli/git-read.mjs +38 -0
  36. package/cli/guard-stream.mjs +409 -0
  37. package/cli/hook.mjs +59 -9
  38. package/cli/issues-act.mjs +57 -13
  39. package/cli/issues-write.mjs +19 -6
  40. package/cli/issues.mjs +62 -23
  41. package/cli/lib.mjs +37 -2
  42. package/cli/local-page.mjs +138 -0
  43. package/cli/machine.mjs +1 -1
  44. package/cli/manifest.mjs +50 -0
  45. package/cli/map/view/app.js +712 -0
  46. package/cli/map/view/index.html +50 -0
  47. package/cli/map/view/style.css +142 -0
  48. package/cli/map-view.mjs +186 -0
  49. package/cli/map.mjs +637 -0
  50. package/cli/members.mjs +9 -15
  51. package/cli/next.mjs +1 -1
  52. package/cli/openpr.mjs +2 -2
  53. package/cli/plan.mjs +125 -0
  54. package/cli/platform.mjs +5 -5
  55. package/cli/product-index.mjs +1 -1
  56. package/cli/protection.mjs +32 -0
  57. package/cli/reconcile.mjs +8 -2
  58. package/cli/report.mjs +9 -3
  59. package/cli/reports-dir.mjs +391 -0
  60. package/cli/reports.mjs +65 -0
  61. package/cli/run-checks.mjs +5 -2
  62. package/cli/scan.mjs +1 -1
  63. package/cli/setup.mjs +30 -5
  64. package/cli/standup.mjs +87 -71
  65. package/cli/status.mjs +6 -5
  66. package/cli/test-agents-file.mjs +614 -8
  67. package/cli/test-brain-activity.mjs +753 -0
  68. package/cli/test-brain-view.mjs +381 -0
  69. package/cli/test-brain.mjs +795 -0
  70. package/cli/test-guide.mjs +211 -0
  71. package/cli/test-machine.mjs +59 -0
  72. package/cli/test-map.mjs +615 -0
  73. package/cli/test-reports.mjs +382 -0
  74. package/cli/test-run-checks.mjs +4 -0
  75. package/cli/test-worktree.mjs +24 -3
  76. package/cli/toolbox-connect.mjs +21 -6
  77. package/cli/toolbox.mjs +59 -4
  78. package/cli/update-commit.mjs +101 -9
  79. package/cli/usage.mjs +8 -4
  80. package/package.json +8 -4
  81. package/skills/yad-architecture/SKILL.md +22 -4
  82. package/skills/yad-change/SKILL.md +3 -1
  83. package/skills/yad-change/references/triage.md +2 -0
  84. package/skills/yad-checks/SKILL.md +2 -0
  85. package/skills/yad-checks/references/check-gates.md +8 -5
  86. package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
  87. package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
  88. package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
  89. package/skills/yad-checks/templates/github/yad-checks.yml +3 -2
  90. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +3 -2
  91. package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
  92. package/skills/yad-connect-repos/SKILL.md +14 -0
  93. package/skills/yad-discovery/SKILL.md +11 -0
  94. package/skills/yad-discovery/references/foundation-schema.md +11 -0
  95. package/skills/yad-docs/templates/app/package-lock.json +18 -10
  96. package/skills/yad-docs/templates/app/package.json +6 -1
  97. package/skills/yad-epic/SKILL.md +3 -0
  98. package/skills/yad-epic/references/state-schema.md +35 -1
  99. package/skills/yad-guide/SKILL.md +4 -4
  100. package/skills/yad-implement/SKILL.md +76 -15
  101. package/skills/yad-issues/SKILL.md +2 -1
  102. package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
  103. package/skills/yad-pr-template/templates/checks/pr-title.sh +8 -4
  104. package/skills/yad-spec/SKILL.md +19 -0
  105. package/skills/yad-stories/SKILL.md +22 -4
  106. package/skills/yad-stories/references/story-schema.md +1 -1
package/cli/map.mjs ADDED
@@ -0,0 +1,637 @@
1
+ // `yad map` — the progress map's data (E181).
2
+ //
3
+ // One picture of how close the work is to Production: epics → stories → tasks → branches, flowing through
4
+ // each code repo's integration branch ("Development") into its Production branch. Read from the Product
5
+ // ledger in this checkout and from READ-ONLY git in each registered code repo; the only git command that
6
+ // changes anything is `git fetch origin`, and only with --fetch (it downloads, never uploads).
7
+ //
8
+ // Two halves, so the rules are tested without git:
9
+ // gatherMap(root, …) reads the ledger, the code repos and the members → raw facts
10
+ // mapModel(inputs, …) PURE: states, roll-ups, people and their roles, waiting, what moved, notes
11
+ //
12
+ // PEOPLE (the user's decisions, 2026-11-14): roles, never counts — owner, builder, reviewer, approver. One
13
+ // person, one badge: a name is matched to a member file (E131) the way `yad standup` matches it; a name that
14
+ // matches no member keeps its own badge, and one that matches more than one member says so. No emails
15
+ // (`shown`), no commit subjects, no machine paths. `--anonymous` names each person "Person A…" in a stable
16
+ // order, masks the capture-branch name and any branch part that is a person's name, and drops PR links.
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { spawnSync } from 'node:child_process';
20
+ import { createHash } from 'node:crypto';
21
+ import { readJSON } from './lib.mjs';
22
+ import { productConfigPath } from './manifest.mjs';
23
+ import { epicIds, epicRoot, loadLedger, readFrontmatter, FOUNDATION_EPIC } from './epic-state.mjs';
24
+ import { readShips } from './ledger.mjs';
25
+ import { readRegistry } from './workspace.mjs';
26
+ import { readOwners } from './owners.mjs';
27
+ import { readMembers, productIdentity } from './members.mjs';
28
+ import { gateWaits, whose } from './standup.mjs';
29
+ import { shown } from './protection.mjs';
30
+ import { readFilesAt, listTreeAt } from './git-read.mjs';
31
+
32
+ export const STATES = Object.freeze(['live', 'merged', 'active', 'planned', 'idle']);
33
+ export const PRODUCTION_GUESSES = Object.freeze(['Production', 'production', 'prod', 'release', 'main', 'master']);
34
+ export const DEFAULT_STALE_DAYS = 60;
35
+ export const DEFAULT_GROUPS = Object.freeze([{ id: 'other', label: 'Other branches' }]);
36
+ const HUES = 8;
37
+
38
+ // ---- small helpers -------------------------------------------------------------------------------
39
+
40
+ const clip = (s, n) => { s = String(s ?? '').replace(/\s+/g, ' ').trim(); return s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s; };
41
+ const pretty = (id) => id.replace(/^EP-/, '').replace(/-/g, ' ').replace(/\b\w/, (ch) => ch.toUpperCase());
42
+ const tally = (arr, key) => arr.reduce((a, x) => { const k = typeof key === 'function' ? key(x) : x[key]; a[k] = (a[k] || 0) + 1; return a; }, {});
43
+ const json = (t) => { try { return JSON.parse(t); } catch { return null; } };
44
+ export const compiles = (pattern) => { try { new RegExp(pattern, 'i'); return true; } catch { return false; } };
45
+ const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
46
+
47
+ function frontmatterText(md) {
48
+ const out = {};
49
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(md || '');
50
+ if (!m) return out;
51
+ for (const l of m[1].split(/\r?\n/)) {
52
+ const k = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(l);
53
+ if (!k) continue;
54
+ let v = k[2].trim();
55
+ if (/^\[.*\]$/.test(v)) v = v.slice(1, -1).split(',').map((x) => x.trim()).filter(Boolean);
56
+ else v = v.replace(/^"(.*)"$/, '$1');
57
+ out[k[1]] = v;
58
+ }
59
+ return out;
60
+ }
61
+ export function storyTitle(md) {
62
+ const body = String(md || '').replace(/^---[\s\S]*?\n---/, '');
63
+ const at = body.search(/^##\s+Story\b/m);
64
+ const rest = (at >= 0 ? body.slice(at) : body).split(/\r?\n/).filter((l) => l.trim() && !/^#/.test(l.trim()));
65
+ return clip(rest[0] || '', 220);
66
+ }
67
+ const heading = (md) => { const m = /^#\s+(.+)$/m.exec(String(md || '').replace(/^---[\s\S]*?\n---/, '')); return m ? m[1].trim() : null; };
68
+ const asList = (v) => (Array.isArray(v) ? v : v ? [v] : []).map((x) => String(x).trim()).filter(Boolean);
69
+
70
+ // ---- people --------------------------------------------------------------------------------------
71
+
72
+ // Two letters for a badge: the first letters of the first two words, else the first two letters.
73
+ export function initials(name) {
74
+ const words = String(name || '').replace(/[^\p{L}\p{N}\s._-]/gu, ' ').split(/[\s._-]+/).filter(Boolean);
75
+ if (!words.length) return '?';
76
+ const two = words.length > 1 ? words[0][0] + words[1][0] : words[0].slice(0, 2);
77
+ return two.toUpperCase();
78
+ }
79
+ // A stable colour slot for a person: the same key always gets the same hue.
80
+ export function hueOf(key) {
81
+ let h = 2166136261;
82
+ for (let i = 0; i < key.length; i++) { h ^= key.charCodeAt(i); h = Math.imul(h, 16777619); }
83
+ return (h >>> 0) % HUES;
84
+ }
85
+ // A short fingerprint for a key (never shown, never reversible to the text it came from in practice).
86
+ const hueKey = (text) => createHash('sha256').update(text, 'utf8').digest('hex').slice(0, 16);
87
+ // "Person A", "Person B", … "Person Z", "Person AA" …
88
+ export function personLetter(n) {
89
+ let s = '';
90
+ for (let i = n + 1; i > 0; i = Math.floor((i - 1) / 26)) s = String.fromCharCode(65 + ((i - 1) % 26)) + s;
91
+ return `Person ${s}`;
92
+ }
93
+
94
+ // What a person whose name holds an @ is shown as: an address is never shown.
95
+ const AT_NAME = 'a name with an @ in it';
96
+
97
+ // The resolver: a raw name from the record → one person key. Members first (E131); else the name itself,
98
+ // compared without case. A name with an @ is never shown.
99
+ export function makeResolver(members = []) {
100
+ const people = new Map(); // key -> { key, name, raws:Set, member: bool, ambiguous: [logins] | null }
101
+ const cache = new Map();
102
+ const resolve = (raw) => {
103
+ const r = String(raw ?? '').trim();
104
+ if (!r) return null;
105
+ if (cache.has(r.toLowerCase())) return cache.get(r.toLowerCase());
106
+ const hit = whose(members, { login: r, name: r });
107
+ let key, name, ambiguous = null;
108
+ if (hit.member) {
109
+ const login = hit.member.primary.login.toLowerCase();
110
+ key = login.includes('@') ? `m:@${hueKey(login)}` : `m:${login}`;
111
+ name = hit.member.names.find((n) => !n.includes('@')) || hit.member.primary.login;
112
+ } else {
113
+ // A raw value with an @ is an email: its key is a fingerprint, so the address never rides in the data.
114
+ key = r.includes('@') ? `n:@${hueKey(r.toLowerCase())}` : `n:${r.toLowerCase()}`;
115
+ name = r;
116
+ if (hit.ambiguous) ambiguous = hit.ambiguous.map((m) => (m.primary.login.includes('@') ? 'a login with an @ in it' : m.primary.login));
117
+ }
118
+ // Any @ (even a leading one, which `shown` lets through for a handle) means an address: it is never
119
+ // shown. This is stricter than `shown` on purpose — do not "fix" it to match.
120
+ if (!people.has(key)) people.set(key, { key, name: String(name).includes('@') ? AT_NAME : shown(name), raws: new Set(), member: !!hit.member, ambiguous });
121
+ people.get(key).raws.add(r);
122
+ cache.set(r.toLowerCase(), key);
123
+ return key;
124
+ };
125
+ return { resolve, people };
126
+ }
127
+
128
+ // ---- the pure model ------------------------------------------------------------------------------
129
+
130
+ // inputs (from gatherMap, or a test):
131
+ // product { name, branch, sha, behind, fetchedAt } staleDays groups [{id,label,pattern?}] members [...]
132
+ // epics [{ id, title, type, currentStep, createdAt, owner, parent, repos, steps:[{id,status}], onMain,
133
+ // sourceBranch?, stepOwners:{step:name}, approvals:[{step, approver}] }]
134
+ // stories [{ id, epic, title, status, owner, repos, build:{repo:{currentStep, steps:[{id,status}]}} }]
135
+ // tasks [{ story, epic, task, repo, branch, pr, mergeCommit, shippedAt, reviewers:[], builder?,
136
+ // reach: { found, prod, integ, via? } | null }]
137
+ // repos [{ name, available, integrationBranch, productionBranch, productionGuessed, waitingCommits,
138
+ // productionAhead, production:{date,author}|null, integration:{date,author}|null, fetchedAt }]
139
+ // branches [{ repo, name, sha, date, author, inProd, inInteg, ahead }]
140
+ // waits [{ epic, step, kind, owner (raw name) | null }]
141
+ // A branch name can hold an address (git allows `@`): each part of it that does is shown as `an-address`, in
142
+ // every map, named or not — before anything else reads the name, so ids and matches agree.
143
+ // Each masked part keeps a short fingerprint, so two address branches never share a name or an id.
144
+ export const noAddress = (name) => (typeof name === 'string' && name.includes('@') ? name.split('/').map((seg) => (seg.includes('@') ? `an-address-${hueKey(seg).slice(0, 6)}` : seg)).join('/') : name);
145
+ function withoutAddresses(inputs) {
146
+ const via = (r) => (r && r.via ? { ...r, via: { ...r.via, branch: noAddress(r.via.branch) } } : r);
147
+ return { ...inputs,
148
+ // The raw name is kept beside it only to find the epic, story and group; it never reaches the model.
149
+ branches: (inputs.branches || []).map((b) => ({ ...b, rawName: b.name, name: noAddress(b.name) })),
150
+ // A link holding an address (in its user part, say) is dropped, never shown.
151
+ tasks: (inputs.tasks || []).map((t) => ({ ...t, branch: noAddress(t.branch), reach: via(t.reach), pr: typeof t.pr === 'string' && t.pr.includes('@') ? null : t.pr })),
152
+ product: inputs.product ? { ...inputs.product, branch: noAddress(inputs.product.branch) } : inputs.product,
153
+ epics: (inputs.epics || []).map((e) => ({ ...e, ...(e.sourceBranch ? { sourceBranch: noAddress(e.sourceBranch) } : {}), ...(e.productBranches ? { productBranches: e.productBranches.map(noAddress) } : {}) })) };
154
+ }
155
+
156
+ export function mapModel(inputs, { anonymous = false, previous = null, now = Date.now() } = {}) {
157
+ inputs = withoutAddresses(inputs);
158
+ const staleDays = Number.isInteger(inputs.staleDays) && inputs.staleDays > 0 ? inputs.staleDays : DEFAULT_STALE_DAYS;
159
+ // A group whose pattern does not compile is left out (gatherMap says so) — never a catch-all by mistake.
160
+ const usable = (inputs.groups || []).filter((g) => !g.pattern || compiles(g.pattern));
161
+ const groups = (usable.length ? usable : DEFAULT_GROUPS).map((g) => {
162
+ const re = g.pattern ? new RegExp(g.pattern, 'i') : null;
163
+ return { id: String(g.id), label: String(g.label || g.id), re };
164
+ });
165
+ const { resolve, people } = makeResolver(inputs.members || []);
166
+ const roles = new Map(); // key -> Set(role)
167
+ const role = (key, r) => { if (!key) return; if (!roles.has(key)) roles.set(key, new Set()); roles.get(key).add(r); };
168
+
169
+ const epics = inputs.epics.map((e) => ({ ...e, label: pretty(e.id) }));
170
+ const epicIdsLong = epics.map((e) => e.id).sort((a, b) => b.length - a.length);
171
+ const repoBy = new Map(inputs.repos.map((r) => [r.name, r]));
172
+
173
+ // Tasks: where each shipped task's merge reached.
174
+ const tasks = inputs.tasks.map((t) => {
175
+ const repo = repoBy.get(t.repo);
176
+ const out = { id: `${t.story}-${t.task}-${t.repo}`, story: t.story, epic: t.epic, task: t.task, repo: t.repo, branch: t.branch || null,
177
+ pr: /^https?:\/\//.test(t.pr || '') ? t.pr : null, shippedAt: t.shippedAt || null, verified: true, note: null, via: null,
178
+ roles: { builder: resolve(t.builder), reviewers: [...new Set(asList(t.reviewers).map(resolve).filter(Boolean))] } };
179
+ role(out.roles.builder, 'builder');
180
+ for (const k of out.roles.reviewers) role(k, 'reviewer');
181
+ if (!repo) { out.state = 'merged'; out.verified = false; out.note = `${t.repo} is not a registered repo`; return out; }
182
+ if (!repo.available) { out.state = 'merged'; out.verified = false; out.note = `${t.repo} is not on this machine, so Production could not be checked`; return out; }
183
+ const r = t.reach;
184
+ if (!r || !r.found) { out.state = 'merged'; out.verified = false; out.note = 'Its merge commit is not in the local copy yet (try --fetch)'; return out; }
185
+ if (r.prod) out.state = 'live';
186
+ else if (r.via) { out.state = 'live'; out.via = r.via.branch; out.note = `Reached ${repo.productionBranch} on ${String(r.via.date).slice(0, 10)} through its own branch “${r.via.branch}”, not through ${repo.integrationBranch}.`; }
187
+ else if (r.integ) out.state = 'merged';
188
+ else { out.state = 'merged'; out.verified = false; out.note = `Merge commit found, but not on ${repo.integrationBranch} or ${repo.productionBranch || 'a Production branch'}`; }
189
+ return out;
190
+ });
191
+
192
+ // Branches: merged into Production, else into Development, else active or idle by age.
193
+ const taskBranch = new Set(tasks.map((t) => `${t.repo}:${t.branch}`));
194
+ const branches = inputs.branches.map((b) => {
195
+ const ageDays = Math.max(0, Math.floor((now - Date.parse(b.date)) / 864e5));
196
+ const state = b.inProd ? 'live' : b.inInteg ? 'merged' : ageDays > staleDays ? 'idle' : 'active';
197
+ const raw = b.rawName ?? b.name; // the epic, story and group are read from the name as it was
198
+ const epic = epicIdsLong.find((id) => new RegExp(`(?:^|[^A-Za-z0-9])${reEsc(id)}(?![A-Za-z0-9])`).test(raw)) || null;
199
+ const sm = epic ? new RegExp(`${reEsc(epic)}-(S\\d+)`).exec(raw) : null;
200
+ const group = epic ? null : (groups.find((g) => !g.re || g.re.test(raw)) || groups[groups.length - 1]).id;
201
+ const author = resolve(b.author);
202
+ role(author, 'builder');
203
+ return { id: `${b.repo}:${b.name}`, repo: b.repo, name: b.name, sha: String(b.sha || '').slice(0, 10), date: b.date, state, ageDays, epic,
204
+ story: sm ? `${epic}-${sm[1]}` : null, group, ahead: state === 'live' || state === 'merged' ? 0 : (Number.isInteger(b.ahead) ? b.ahead : null),
205
+ roles: { builder: author }, task: taskBranch.has(`${b.repo}:${b.name}`) };
206
+ });
207
+
208
+ // Stories.
209
+ const started = (s) => Object.values(s.build || {}).some((b) => (b.steps || []).some((x) => ['done', 'in_progress', 'in_review'].includes(x.status)));
210
+ const stories = inputs.stories.map((s) => {
211
+ const mine = tasks.filter((t) => t.story === s.id);
212
+ const open = branches.filter((b) => b.story === s.id && (b.state === 'active' || b.state === 'idle'));
213
+ const out = { id: s.id, epic: s.epic, short: (/-(S\d+)$/.exec(s.id) || [])[1] || s.id, title: s.title || '', status: s.status || 'unknown',
214
+ repos: asList(s.repos), build: s.build || {}, taskCount: mine.length, tasksLive: mine.filter((t) => t.state === 'live').length, roles: { owner: resolve(s.owner) } };
215
+ role(out.roles.owner, 'owner');
216
+ if (s.status === 'shipped') {
217
+ out.state = mine.length && mine.every((t) => t.state === 'live') ? 'live' : 'merged';
218
+ out.verified = mine.length > 0 && mine.every((t) => t.verified);
219
+ out.stateLabel = out.state === 'live' ? 'Shipped and in Production' : 'Shipped, waiting for release';
220
+ } else if (started(s) || mine.length || open.length) {
221
+ out.state = 'active'; out.stateLabel = 'Being built';
222
+ } else {
223
+ out.state = 'planned'; out.stateLabel = s.status === 'approved' ? 'Approved, not started' : s.status === 'draft' ? 'Draft' : String(s.status || 'Not started');
224
+ }
225
+ return out;
226
+ });
227
+
228
+ // Epics.
229
+ for (const e of epics) {
230
+ const mine = stories.filter((s) => s.epic === e.id);
231
+ e.storyCount = mine.length;
232
+ e.storiesShipped = mine.filter((s) => s.status === 'shipped').length;
233
+ e.taskCount = tasks.filter((t) => t.epic === e.id).length;
234
+ const owner = resolve(e.owner);
235
+ role(owner, 'owner');
236
+ const stepOwners = Object.entries(e.stepOwners || {}).map(([step, name]) => ({ step, person: resolve(name) })).filter((x) => x.person);
237
+ for (const so of stepOwners) role(so.person, 'owner');
238
+ const seenApproval = new Set();
239
+ const approvers = (e.approvals || []).map((a) => ({ step: a.step, person: resolve(a.approver) }))
240
+ .filter((x) => x.person && !seenApproval.has(`${x.step}\0${x.person}`) && seenApproval.add(`${x.step}\0${x.person}`));
241
+ for (const a of approvers) role(a.person, 'approver');
242
+ e.roles = { owner, stepOwners, approvers };
243
+ const todo = !e.steps?.length || e.steps.every((s) => s.status === 'todo');
244
+ if (mine.length && mine.every((s) => s.state === 'live')) { e.state = 'live'; e.stateLabel = 'All stories in Production'; }
245
+ else if (mine.length && mine.every((s) => s.status === 'shipped')) { e.state = 'merged'; e.stateLabel = 'All stories shipped, waiting for release'; }
246
+ else if (mine.some((s) => s.state !== 'planned') || branches.some((b) => b.epic === e.id && b.state !== 'idle')) { e.state = 'active'; e.stateLabel = `Building — ${e.storiesShipped} of ${mine.length} stories shipped`; }
247
+ else if (todo || e.currentStep === 'backfill-pending') { e.state = 'planned'; e.stateLabel = 'Not started'; }
248
+ else if (e.currentStep === 'ready-for-build') { e.state = 'planned'; e.stateLabel = 'Planned, ready for build'; }
249
+ else { e.state = 'active'; e.stateLabel = `Planning — at step “${e.currentStep}”`; }
250
+ delete e.owner; delete e.stepOwners; delete e.approvals;
251
+ }
252
+
253
+ // Waiting on whom: each open gate's owner, by the same rule `yad standup` reads (gateWaits).
254
+ // The person a gate waits on is that step's owner (the live E47 owner, else the epic's): an owner role.
255
+ const waiting = (inputs.waits || []).map((w) => ({ epic: w.epic, step: w.step, kind: w.kind, person: resolve(w.owner) }));
256
+ for (const w of waiting) role(w.person, 'owner');
257
+
258
+ // The single-person note: every part of the epic so far came from one person.
259
+ const notes = { onePerson: [] };
260
+ for (const e of epics) {
261
+ const keys = new Set([e.roles.owner, ...e.roles.stepOwners.map((x) => x.person), ...e.roles.approvers.map((x) => x.person)]);
262
+ let parts = 0;
263
+ for (const s of stories.filter((x) => x.epic === e.id)) { if (s.roles.owner) keys.add(s.roles.owner); }
264
+ for (const t of tasks.filter((x) => x.epic === e.id)) { parts++; keys.add(t.roles.builder); for (const r of t.roles.reviewers) keys.add(r); }
265
+ for (const b of branches.filter((x) => x.epic === e.id)) { parts++; keys.add(b.roles.builder); }
266
+ parts += e.roles.approvers.length;
267
+ keys.delete(null); keys.delete(undefined);
268
+ if (keys.size === 1 && parts > 0) notes.onePerson.push(e.id);
269
+ }
270
+
271
+ // People, sorted by name, each with the roles they hold — no counts.
272
+ // Everyone the map names is listed, so every badge and every "by" can be looked up; a person seen only as the
273
+ // author of a repo's latest Production or Development commit holds no role.
274
+ const peopleList = [...people.values()]
275
+ .map((p) => ({ key: p.key, name: p.name, initials: initials(p.name), hue: hueOf(p.key), roles: [...(roles.get(p.key) || [])].sort(), ambiguous: p.ambiguous }))
276
+ .sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }) || a.key.localeCompare(b.key));
277
+
278
+ // Repos: by label only, never a path on this machine.
279
+ const repos = inputs.repos.map((r) => ({ name: r.name, available: !!r.available, integrationBranch: r.integrationBranch || null, productionBranch: r.productionBranch || null,
280
+ productionGuessed: !!r.productionGuessed, waitingCommits: r.waitingCommits ?? null, productionAhead: r.productionAhead ?? null, fetchedAt: r.fetchedAt || null,
281
+ production: r.production ? { date: r.production.date, by: resolve(r.production.author) } : null,
282
+ integration: r.integration ? { date: r.integration.date, by: resolve(r.integration.author) } : null }));
283
+
284
+ let model = {
285
+ generatedAt: new Date(now).toISOString(), staleDays, anonymous: !!anonymous,
286
+ product: { name: inputs.product?.name || 'Product', branch: inputs.product?.branch || null, sha: inputs.product?.sha || null, behind: inputs.product?.behind ?? null, fetchedAt: inputs.product?.fetchedAt || null },
287
+ repos, groups: groups.map((g) => ({ id: g.id, label: g.label })), epics, stories, tasks, branches, people: peopleList, waiting, notes, moved: [], since: null,
288
+ };
289
+ model.summary = summarize(model);
290
+
291
+ if (anonymous) model = anonymize(model, people);
292
+
293
+ // What moved: against the previous saved map's digest ({ at, states: { id: state } }).
294
+ // An anonymous map never says what moved: its masked ids would read as new against a named map's digest.
295
+ if (!anonymous && previous && previous.states && typeof previous.states === 'object') {
296
+ const now2 = digestOf(model).states;
297
+ model.moved = Object.entries(now2).filter(([id, st]) => Object.hasOwn(previous.states, id) ? previous.states[id] !== st : true)
298
+ .map(([id, st]) => ({ id, from: Object.hasOwn(previous.states, id) ? previous.states[id] : null, to: st }));
299
+ model.since = typeof previous.at === 'string' ? previous.at : null;
300
+ }
301
+ return model;
302
+ }
303
+
304
+ function summarize(m) {
305
+ const vis = (o) => (o.state === 'merged' && o.verified === false ? 'unver' : o.state);
306
+ return {
307
+ epics: { total: m.epics.length, byState: tally(m.epics, 'state') },
308
+ stories: { total: m.stories.length, byState: tally(m.stories, vis), shipped: m.stories.filter((s) => s.status === 'shipped').length },
309
+ tasks: { total: m.tasks.length, byState: tally(m.tasks, vis), verified: m.tasks.filter((t) => t.verified).length },
310
+ branches: Object.fromEntries(m.repos.filter((r) => r.available).map((r) => {
311
+ const mine = m.branches.filter((b) => b.repo === r.name);
312
+ return [r.name, { total: mine.length, byState: tally(mine, 'state'), waitingCommits: r.waitingCommits, lastRelease: r.production ? r.production.date : null }];
313
+ })),
314
+ };
315
+ }
316
+
317
+ // The state of every item, by id — what a later map compares itself with.
318
+ export function digestOf(model) {
319
+ const states = {};
320
+ const vis = (o) => (o.state === 'merged' && o.verified === false ? 'unver' : o.state);
321
+ for (const e of model.epics) states[`epic:${e.id}`] = e.state;
322
+ for (const s of model.stories) states[`story:${s.id}`] = vis(s);
323
+ for (const t of model.tasks) states[`task:${t.id}`] = vis(t);
324
+ for (const b of model.branches) states[`branch:${b.id}`] = b.state;
325
+ return { at: model.generatedAt, states };
326
+ }
327
+
328
+ // The names to mask from a raw value that may hold an address, never a domain. A value with no @ is returned
329
+ // as it is. Otherwise the values are the UNION of two readings, so a later change to one can never mask less:
330
+ // First an @ with a space AFTER it is joined to both sides (`kit @ x.com`, `kit@ x.com`): the word after such an
331
+ // @ is its domain. An @ with no space after it is left alone, so the handle in `Bo @quinn` stays a handle
332
+ // (the cost: `Bo @ Quinn` reads as an address whose domain is `quinn`).
333
+ // 1. word by word on whitespace — each word with a non-leading @ cut to what comes before its last @, the
334
+ // @ signs left becoming spaces (`kit@x.com Kit Marsh` → `kit kit marsh`, `@quinn` → `quinn`);
335
+ // 2. the same cut after the wrapping round an address is undone — wrapping just before an @ dropped
336
+ // (`"kit"@x.com`), and the value split on anything that is not part of a name (a letter, a combining
337
+ // mark, a digit, `.`, `_`, `-`, `'`, `+`), so `Bo <kit@x.com>` and
338
+ // `mailto:kit@x.com` give `kit`; the words with no @ are given joined too (`kit marsh`, for `kitmarsh`).
339
+ // A leading @ is dropped, not cut: a handle (`@quinn`), or a domain (`@x.com`) masked on purpose.
340
+ const cutAddress = (t) => (t.lastIndexOf('@') > 0 ? t.slice(0, t.lastIndexOf('@')) : t).replace(/@/g, ' ').trim();
341
+ function addressFree(r) {
342
+ if (!r.includes('@')) return [r];
343
+ const closed = r.replace(/\s*@\s+/g, '@');
344
+ const byWord = closed.split(/\s+/).map(cutAddress).filter(Boolean);
345
+ const pieces = closed.replace(/(?<=\S)[<>()[\]{}",;:]+@/g, '@')
346
+ .split(/[^\p{L}\p{M}\p{N}._@'+-]+/u).filter(Boolean);
347
+ const cut = pieces.map(cutAddress).filter(Boolean);
348
+ return [byWord.join(' '), cut.join(' '), pieces.filter((t) => !t.includes('@')).join(' '), ...cut];
349
+ }
350
+
351
+ // `--anonymous`: every person becomes "Person A…" (in the order of their key, so the same team always gets
352
+ // the same letters), and nothing else can name them: the capture-branch name, a branch part that is a
353
+ // person's name, PR links. Ids are rebuilt from the masked names, so no id carries one either.
354
+ function anonymize(model, people) {
355
+ const keys = model.people.map((p) => p.key).sort();
356
+ const alias = new Map(keys.map((k, i) => [k, { key: `p${i + 1}`, name: personLetter(i) }]));
357
+ // The placeholder for an address is not a name, so its words (`name`, `with`) are never masked.
358
+ const raws = [...people.values()].filter((p) => alias.has(p.key))
359
+ .flatMap((p) => [...p.raws, ...(p.name === AT_NAME ? [] : [p.name])])
360
+ .map((r) => String(r).toLowerCase())
361
+ .flatMap(addressFree)
362
+ .filter((r) => r.length >= 2);
363
+ // Each name, each of its words (3 letters or more), and the name with its separators taken out
364
+ // (`bobbuilder`), so `bob.builder/x`, `feat/bob_builder` and `bobbuilder-fix` are all masked.
365
+ const parts = new Set(raws.flatMap((r) => [r, r.replace(/[\s._-]+/g, ''), ...r.split(/[\s._-]+/).filter((x) => x.length >= 3)]).filter(Boolean));
366
+ const k = (key) => (key && alias.has(key) ? alias.get(key).key : null);
367
+ // A masked address part carries a fingerprint (a hash of the address): in an anonymous map that hash could be
368
+ // matched against a list of the team's emails, so each one is renumbered in the order it is met.
369
+ const addressNo = new Map();
370
+ const renumber = (n) => n.replace(/an-address-[0-9a-f]{6}/g, (fp) => { if (!addressNo.has(fp)) addressNo.set(fp, addressNo.size + 1); return `an-address-${addressNo.get(fp)}`; });
371
+ const maskBranch = (name) => {
372
+ if (!name) return name;
373
+ let n = renumber(String(name)).replace(/^yad\/wip\/[^/]+\//, 'yad/wip/someone/');
374
+ n = n.split('/').map((seg) => (parts.has(seg.toLowerCase()) || parts.has(seg.toLowerCase().replace(/[._-]+/g, '')) ? 'someone'
375
+ : seg.split(/([._-])/).map((w) => (parts.has(w.toLowerCase()) ? 'someone' : w)).join(''))).join('/');
376
+ return parts.has(n.toLowerCase()) ? 'someone' : n;
377
+ };
378
+ const out = JSON.parse(JSON.stringify(model));
379
+ out.people = model.people.map((p) => { const a = alias.get(p.key); return { ...p, key: a.key, name: a.name, initials: a.name.replace(/^Person /, ''), hue: hueOf(a.key), ambiguous: null }; })
380
+ .sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }));
381
+ for (const e of out.epics) {
382
+ e.roles = { owner: k(e.roles.owner), stepOwners: e.roles.stepOwners.map((x) => ({ step: x.step, person: k(x.person) })), approvers: e.roles.approvers.map((x) => ({ step: x.step, person: k(x.person) })) };
383
+ if (e.sourceBranch) e.sourceBranch = maskBranch(e.sourceBranch);
384
+ if (e.productBranches) e.productBranches = e.productBranches.map(maskBranch);
385
+ }
386
+ for (const s of out.stories) s.roles = { owner: k(s.roles.owner) };
387
+ for (const t of out.tasks) {
388
+ t.roles = { builder: k(t.roles.builder), reviewers: t.roles.reviewers.map(k).filter(Boolean) };
389
+ t.branch = maskBranch(t.branch); t.pr = null;
390
+ if (t.via) { t.via = maskBranch(t.via); t.note = t.note && t.note.replace(/“[^”]*”/, `“${t.via}”`); }
391
+ }
392
+ for (const b of out.branches) {
393
+ b.roles = { builder: k(b.roles.builder) };
394
+ const masked = maskBranch(b.name);
395
+ b.name = masked; b.id = `${b.repo}:${masked}`;
396
+ }
397
+ for (const r of out.repos) {
398
+ if (r.production) r.production.by = k(r.production.by);
399
+ if (r.integration) r.integration.by = k(r.integration.by);
400
+ }
401
+ out.waiting = out.waiting.map((w) => ({ ...w, person: k(w.person) }));
402
+ if (out.product?.branch) out.product.branch = maskBranch(out.product.branch);
403
+ return out;
404
+ }
405
+
406
+ // Delivered straight to Production on a branch of its own (a merge on the Production branch's first-parent
407
+ // line): a branch that names this TASK after the story id counts for it — the task read by its number (T1
408
+ // and T01 are one task), after any of - _ . / ; a branch that names only the story (the whole story rebuilt,
409
+ // no task id after it) counts for each of its tasks. → { date, branch } | null
410
+ export function portFor(direct, story, task) {
411
+ const num = /^T0*(\d+)$/i.exec(String(task))?.[1];
412
+ const taskRe = num ? new RegExp(`${reEsc(story)}[-_./]T0*${num}(?![A-Za-z0-9])`, 'i') : new RegExp(`${reEsc(story)}[-_./]${reEsc(String(task))}(?![A-Za-z0-9])`);
413
+ const storyRe = new RegExp(`${reEsc(story)}(?![\\d])(?![-_./]T\\d)`, 'i');
414
+ // From the FIRST place the story id appears (any later one too), no task id anywhere after it.
415
+ const firstRe = new RegExp(`${reEsc(story)}(?!\\d)`, 'i');
416
+ const storyOnly = (branch) => {
417
+ const m = firstRe.exec(branch);
418
+ return !!m && storyRe.test(branch) && !/[-_./]T\d/i.test(branch.slice(m.index + story.length));
419
+ };
420
+ return direct.find((d) => taskRe.test(d.branch)) || direct.find((d) => storyOnly(d.branch)) || null;
421
+ }
422
+
423
+ // ---- gathering (git and files) -------------------------------------------------------------------
424
+
425
+ const gitIn = (runner) => (cwd, args, o = {}) => {
426
+ const r = runner('git', ['-C', cwd, ...args], { encoding: 'utf8', maxBuffer: 1 << 29, windowsHide: true, ...o });
427
+ return { ok: r.status === 0, code: r.status, out: String(r.stdout ?? ''), err: String(r.stderr ?? '') };
428
+ };
429
+ const isRepo = (g, p) => fs.existsSync(p) && g(p, ['rev-parse', '--git-dir']).ok;
430
+ const hasRef = (g, repo, ref) => g(repo, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).ok;
431
+ const lines = (s) => String(s || '').split('\n').map((x) => x.trim()).filter(Boolean);
432
+ function fetchTime(g, repo) {
433
+ const d = g(repo, ['rev-parse', '--absolute-git-dir']);
434
+ if (!d.ok) return null;
435
+ try { return fs.statSync(path.join(d.out.trim(), 'FETCH_HEAD')).mtime.toISOString(); } catch { return null; }
436
+ }
437
+ // Each remote-tracking branch of origin: name, sha, committer date, author name. Fields split by NUL.
438
+ function remoteBranches(g, repo) {
439
+ const fmt = ['%(refname:lstrip=3)', '%(objectname)', '%(committerdate:iso-strict)', '%(authorname)'].join('%00');
440
+ return lines(g(repo, ['for-each-ref', 'refs/remotes/origin', `--format=${fmt}`]).out).map((l) => {
441
+ const [name, sha, date, author] = l.split('\0');
442
+ return { name, sha, date, author };
443
+ }).filter((b) => b.name && b.name !== 'HEAD');
444
+ }
445
+ const mergedInto = (g, repo, ref) => new Set(lines(g(repo, ['for-each-ref', 'refs/remotes/origin', '--merged', ref, '--format=%(refname:lstrip=3)']).out));
446
+ const count = (g, repo, range) => { const r = g(repo, ['rev-list', '--count', range, '--']); return r.ok ? Number(r.out.trim()) : null; };
447
+
448
+ // Read one epic from the working tree.
449
+ function epicFromTree(root, id) {
450
+ const dir = epicRoot(root, id);
451
+ const led = loadLedger(dir);
452
+ const fm = readFrontmatter(path.join(dir, 'epic.md'));
453
+ let epicMd = '';
454
+ try { epicMd = fs.readFileSync(path.join(dir, 'epic.md'), 'utf8'); } catch { /* no epic.md */ }
455
+ const state = led.state || {};
456
+ const stories = [];
457
+ const sdir = path.join(dir, 'stories');
458
+ if (fs.existsSync(sdir)) {
459
+ for (const f of fs.readdirSync(sdir).filter((n) => n.endsWith('.md')).sort()) {
460
+ let text;
461
+ try { text = fs.readFileSync(path.join(sdir, f), 'utf8'); } catch { continue; }
462
+ const s = frontmatterText(text);
463
+ stories.push({ id: s.id || f.replace(/\.md$/, ''), epic: id, title: storyTitle(text), status: s.status || 'unknown', owner: s.owner || null, repos: asList(s.repos), build: {} });
464
+ }
465
+ }
466
+ for (const b of Object.values(led.buildStates || {})) {
467
+ const s = stories.find((x) => x.id === b?.story);
468
+ if (!s) continue;
469
+ for (const [repo, v] of Object.entries(b.repos || {})) s.build[repo] = { currentStep: v?.currentStep || null, steps: (v?.steps || []).map((x) => ({ id: x.id, status: x.status })) };
470
+ }
471
+ const ships = readShips(dir);
472
+ const stepOwners = {};
473
+ for (const o of readOwners(root, id)) if (!o.error && o.live) stepOwners[o.step] = o.name || o.owner;
474
+ return {
475
+ epic: { id, title: fm.title || heading(epicMd) || null, type: state.type || fm.type || null, currentStep: state.currentStep || null, createdAt: state.createdAt || null,
476
+ owner: typeof fm.owner === 'string' ? fm.owner : null, parent: fm.parent || null, repos: asList(fm.repos), steps: (state.steps || []).map((s) => ({ id: s.id, status: s.status })),
477
+ onMain: true, stepOwners, approvals: (Array.isArray(led.approvals) ? led.approvals : []).filter((a) => a && a.status !== 'revoked').map((a) => ({ step: a.step, approver: a.approver })) },
478
+ stories,
479
+ tasks: ships.filter((t) => t && t.story && t.task).map((t) => ({ story: t.story, epic: id, task: t.task, repo: t.repo, branch: t.branch || null, pr: t.pr || null,
480
+ mergeCommit: t.mergeCommit || null, shippedAt: t.shippedAt || null, reviewers: (t.engineer_review || []).map((r) => r?.approver).filter(Boolean) })),
481
+ ledger: led,
482
+ };
483
+ }
484
+
485
+ // An epic that so far lives only on a Product branch (being written): read from that ref.
486
+ function epicFromRef(runner, root, ref, id) {
487
+ const files = listTreeAt(root, ref, [`epics/${id}`], { runner });
488
+ if (!files.some((f) => f.endsWith('/.sdlc/state.json'))) return null;
489
+ const want = files.filter((f) => /\/\.sdlc\/state\.json$|\/epic\.md$|\/stories\/[^/]+\.md$|\/\.sdlc\/build-log\.json$|\/\.sdlc\/build-log\/[^/]+\.json$/.test(f));
490
+ const got = readFilesAt(root, ref, want, { runner });
491
+ const base = `epics/${id}/`;
492
+ const state = json(got.get(`${base}.sdlc/state.json`)) || {};
493
+ const epicMd = got.get(`${base}epic.md`) || '';
494
+ const fm = frontmatterText(epicMd);
495
+ const stories = [], tasks = [];
496
+ const addShip = (t) => { if (t && t.story && t.task) tasks.push({ story: t.story, epic: id, task: t.task, repo: t.repo, branch: t.branch || null, pr: t.pr || null, mergeCommit: t.mergeCommit || null, shippedAt: t.shippedAt || null, reviewers: (t.engineer_review || []).map((r) => r?.approver).filter(Boolean) }); };
497
+ for (const f of want) {
498
+ const text = got.get(f);
499
+ if (/\/stories\//.test(f)) {
500
+ const s = frontmatterText(text);
501
+ stories.push({ id: s.id || path.posix.basename(f, '.md'), epic: id, title: storyTitle(text), status: s.status || 'unknown', owner: s.owner || null, repos: asList(s.repos), build: {} });
502
+ } else if (/\/build-log\.json$/.test(f)) { for (const t of json(text)?.ships || []) addShip(t); }
503
+ else if (/\/build-log\//.test(f)) addShip(json(text));
504
+ }
505
+ return {
506
+ epic: { id, title: fm.title || heading(epicMd) || null, type: state.type || fm.type || null, currentStep: state.currentStep || null, createdAt: state.createdAt || null,
507
+ owner: typeof fm.owner === 'string' ? fm.owner : null, parent: fm.parent || null, repos: asList(fm.repos), steps: (state.steps || []).map((s) => ({ id: s.id, status: s.status })),
508
+ onMain: false, sourceBranch: ref.replace(/^origin\//, ''), stepOwners: {}, approvals: [] },
509
+ stories, tasks,
510
+ };
511
+ }
512
+
513
+ // Everything `mapModel` needs, read from this machine. Read-only, except `git fetch origin` with `fetch`.
514
+ // → { inputs, problems: [text] }
515
+ export function gatherMap(root, { fetch = false, runner = spawnSync, now = Date.now(), log = () => {} } = {}) {
516
+ const g = gitIn(runner);
517
+ const problems = [];
518
+ const productConfig = readJSON(productConfigPath(root), null) || {};
519
+ const mapCfg = productConfig.map && typeof productConfig.map === 'object' ? productConfig.map : {};
520
+ if (fetch && isRepo(g, root)) {
521
+ log('downloading the latest for the Product (nothing is uploaded) …');
522
+ if (!g(root, ['fetch', 'origin']).ok) problems.push('the Product could not be fetched; using what is already here');
523
+ }
524
+ const branch = isRepo(g, root) ? g(root, ['rev-parse', '--abbrev-ref', 'HEAD']).out.trim() : null;
525
+ const sha = isRepo(g, root) ? g(root, ['rev-parse', '--verify', '--quiet', 'HEAD']).out.trim() || null : null;
526
+ const def = isRepo(g, root) ? g(root, ['rev-parse', '--abbrev-ref', 'origin/HEAD']).out.trim() : '';
527
+ const behind = def && sha ? count(g, root, `HEAD..${def}`) : null;
528
+
529
+ // The epics in this checkout, then those only on a branch.
530
+ const epics = [], stories = [], tasks = [], ledgers = new Map();
531
+ for (const id of epicIds(root).filter((x) => x !== FOUNDATION_EPIC)) {
532
+ try {
533
+ const e = epicFromTree(root, id);
534
+ epics.push(e.epic); stories.push(...e.stories); tasks.push(...e.tasks); ledgers.set(id, e.ledger);
535
+ } catch (err) { problems.push(`${id}: its ledger cannot be read (${shown(String(err.message || err).split('\n')[0].split(root + path.sep).join(''))})`); }
536
+ }
537
+ const seen = new Set(epics.map((e) => e.id));
538
+ if (isRepo(g, root)) {
539
+ const pBranches = remoteBranches(g, root).sort((a, z) => String(z.date).localeCompare(String(a.date)));
540
+ for (const b of pBranches) {
541
+ const id = b.name.split('/').find((seg) => /^EP-[A-Za-z0-9-]+$/.test(seg));
542
+ if (!id || seen.has(id)) continue;
543
+ const e = epicFromRef(runner, root, `origin/${b.name}`, id);
544
+ if (!e) continue;
545
+ seen.add(id);
546
+ epics.push(e.epic); stories.push(...e.stories); tasks.push(...e.tasks);
547
+ }
548
+ for (const e of epics) e.productBranches = pBranches.filter((b) => b.name.split('/').includes(e.id)).map((b) => b.name);
549
+ }
550
+
551
+ // Waiting on whom (the gate rule `yad standup` reads).
552
+ const identity = productIdentity(root, { productConfig });
553
+ const members = (() => { try { return readMembers(root, { identity }).members; } catch { return []; } })();
554
+ const waits = [];
555
+ try {
556
+ const gw = gateWaits(root, { ledgers, members, productConfig, identity });
557
+ for (const { owner, item } of gw.waits) if (item.kind === 'gate') waits.push({ epic: item.epic, step: item.step, kind: item.kind, owner: owner ? owner.display : null });
558
+ } catch (err) { problems.push(`the open gates could not be read (${shown(String(err.message || err).split('\n')[0])})`); }
559
+
560
+ // Code repos.
561
+ const { registry, problem } = readRegistry(root);
562
+ if (problem) problems.push(problem);
563
+ const repos = [], branches = [];
564
+ const productionCfg = mapCfg.production && typeof mapCfg.production === 'object' ? mapCfg.production : {};
565
+ for (const r of registry.repos) {
566
+ if (!r || typeof r.name !== 'string') continue;
567
+ const p = path.resolve(root, typeof r.path === 'string' ? r.path : '');
568
+ const info = { name: r.name, available: typeof r.path === 'string' && isRepo(g, p), integrationBranch: r.default_branch || null, productionBranch: null, productionGuessed: false };
569
+ repos.push(info);
570
+ const mine = tasks.filter((t) => t.repo === r.name);
571
+ if (!info.available) continue;
572
+ if (fetch) {
573
+ log(`downloading the latest for ${r.name} (nothing is uploaded) …`);
574
+ if (!g(p, ['fetch', 'origin']).ok) problems.push(`${r.name} could not be fetched; using what is already here`);
575
+ }
576
+ let live = null;
577
+ if (fetch) { const ls = g(p, ['ls-remote', '--heads', 'origin']); if (ls.ok) live = new Set(lines(ls.out).map((l) => l.split('\t')[1]?.replace('refs/heads/', '')).filter(Boolean)); }
578
+ const all = remoteBranches(g, p);
579
+ info.fetchedAt = fetchTime(g, p);
580
+ const integ = info.integrationBranch && hasRef(g, p, `origin/${info.integrationBranch}`) ? `origin/${info.integrationBranch}` : null;
581
+ const chosen = typeof productionCfg[r.name] === 'string' ? productionCfg[r.name] : null;
582
+ const prodName = chosen && hasRef(g, p, `origin/${chosen}`) ? chosen : (!chosen ? PRODUCTION_GUESSES.find((n) => n !== info.integrationBranch && hasRef(g, p, `origin/${n}`)) : null);
583
+ if (chosen && !prodName) problems.push(`${r.name}: map.production names "${shown(chosen)}", which origin does not have`);
584
+ info.productionBranch = prodName || null;
585
+ info.productionGuessed = !!prodName && !chosen;
586
+ const prod = prodName ? `origin/${prodName}` : null;
587
+ const inProd = prod ? mergedInto(g, p, prod) : new Set();
588
+ const inInteg = integ ? mergedInto(g, p, integ) : new Set();
589
+ if (prod && integ) { info.waitingCommits = count(g, p, `${prod}..${integ}`); info.productionAhead = count(g, p, `${integ}..${prod}`); }
590
+ for (const b of all) {
591
+ if (b.name === prodName) info.production = { date: b.date, author: b.author };
592
+ if (b.name === info.integrationBranch) info.integration = { date: b.date, author: b.author };
593
+ }
594
+ for (const b of all) {
595
+ if (b.name === prodName || b.name === info.integrationBranch) continue;
596
+ if (live && !live.has(b.name)) continue;
597
+ const merged = (prod && inProd.has(b.name)) || (integ && inInteg.has(b.name));
598
+ branches.push({ repo: r.name, name: b.name, sha: b.sha, date: b.date, author: b.author, inProd: !!(prod && inProd.has(b.name)), inInteg: !!(integ && inInteg.has(b.name)),
599
+ ahead: merged ? 0 : count(g, p, `${integ || prod || 'HEAD'}..origin/${b.name}`) });
600
+ }
601
+ // Work rebuilt on its own branch and merged straight into Production names the story in its merge.
602
+ const direct = prod ? lines(g(p, ['log', '--first-parent', '--merges', '-n', '500', '--format=%cI%x00%s', prod]).out).map((l) => {
603
+ const [date, subject] = l.split('\0');
604
+ const m = /Merge branch '([^']+)'/.exec(subject || '') || /Merge pull request #\d+ from [^/\s]+\/(\S+)/.exec(subject || '');
605
+ return m ? { date, branch: m[1] } : null;
606
+ }).filter(Boolean) : [];
607
+ const memo = new Map();
608
+ const reach = (c, ref) => {
609
+ const key = `${c}\0${ref}`;
610
+ if (!memo.has(key)) { const code = g(p, ['merge-base', '--is-ancestor', c, ref]).code; memo.set(key, code === 0 ? true : code === 1 ? false : null); }
611
+ return memo.get(key);
612
+ };
613
+ for (const t of mine) {
614
+ if (!t.mergeCommit || !/^[0-9a-f]{4,64}$/i.test(t.mergeCommit) || !g(p, ['cat-file', '-e', `${t.mergeCommit}^{commit}`]).ok) { t.reach = { found: false }; continue; }
615
+ const via = portFor(direct, t.story, t.task);
616
+ t.reach = { found: true, prod: !!(prod && reach(t.mergeCommit, prod)), integ: !!(integ && reach(t.mergeCommit, integ)), via };
617
+ // The builder: the author of the merged branch's tip (the merge's second parent), else of the commit.
618
+ const parents = g(p, ['rev-list', '--parents', '-n', '1', t.mergeCommit]).out.trim().split(/\s+/);
619
+ const tip = parents.length > 2 ? `${t.mergeCommit}^2` : t.mergeCommit;
620
+ const an = g(p, ['log', '-1', '--format=%an', tip, '--']);
621
+ if (an.ok && an.out.trim()) t.builder = an.out.trim();
622
+ }
623
+ }
624
+
625
+ for (const grp of Array.isArray(mapCfg.groups) ? mapCfg.groups : []) {
626
+ if (grp && typeof grp.pattern === 'string' && !compiles(grp.pattern)) problems.push(`map.groups: the pattern of "${shown(String(grp.id))}" is not a valid pattern, so that group is left out`);
627
+ }
628
+ return {
629
+ problems,
630
+ inputs: {
631
+ product: { name: typeof productConfig.name === 'string' && productConfig.name.trim() ? productConfig.name.trim() : path.basename(root), branch: branch && branch !== 'HEAD' ? branch : null, sha, behind, fetchedAt: isRepo(g, root) ? fetchTime(g, root) : null },
632
+ staleDays: Number.isInteger(mapCfg.staleDays) ? mapCfg.staleDays : DEFAULT_STALE_DAYS,
633
+ groups: Array.isArray(mapCfg.groups) ? mapCfg.groups.filter((x) => x && typeof x.id === 'string' && (!x.pattern || typeof x.pattern === 'string')) : [],
634
+ members, epics, stories, tasks, repos, branches, waits, now,
635
+ },
636
+ };
637
+ }