yadflow 4.9.0 → 4.10.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.
- package/CHANGELOG.md +87 -0
- package/README.md +4 -3
- package/bin/commands.mjs +6 -0
- package/bin/yad.mjs +101 -6
- package/cli/agent-guard.mjs +793 -65
- package/cli/agent-rules.mjs +33 -5
- package/cli/argv-flags.mjs +1 -1
- package/cli/ci-check.mjs +45 -1
- package/cli/codeowners-command.mjs +72 -6
- package/cli/commit.mjs +17 -3
- package/cli/docs.mjs +2 -0
- package/cli/doctor.mjs +71 -12
- package/cli/epic-state.mjs +94 -4
- package/cli/epic.mjs +11 -7
- package/cli/fold.mjs +31 -6
- package/cli/guide.mjs +3 -1
- package/cli/hook.mjs +50 -7
- package/cli/issue-links.mjs +61 -0
- package/cli/issues-act.mjs +327 -0
- package/cli/issues-write.mjs +428 -0
- package/cli/issues.mjs +474 -0
- package/cli/lifecycle.mjs +7 -0
- package/cli/manifest.mjs +9 -3
- package/cli/openpr.mjs +24 -4
- package/cli/plan.mjs +2 -0
- package/cli/platform.mjs +157 -2
- package/cli/protection.mjs +21 -3
- package/cli/reconcile.mjs +1 -1
- package/cli/run-checks.mjs +10 -2
- package/cli/scan.mjs +314 -0
- package/cli/setup.mjs +12 -3
- package/cli/standup.mjs +33 -7
- package/cli/story-frames.mjs +17 -6
- package/cli/test-agents-file.mjs +378 -11
- package/cli/test-build.mjs +25 -0
- package/cli/test-ci-check.mjs +469 -10
- package/cli/test-guide.mjs +7 -0
- package/cli/test-node.mjs +15 -0
- package/cli/test-run-checks.mjs +17 -0
- package/cli/test-setup-agent.mjs +14 -0
- package/cli/test-story-frames.mjs +74 -4
- package/cli/toolbox-connect.mjs +244 -0
- package/cli/toolbox.mjs +129 -9
- package/package.json +7 -3
- package/skills/sdlc/config.yaml +1 -1
- package/skills/sdlc/module-help.csv +3 -1
- package/skills/yad-analysis/SKILL.md +4 -0
- package/skills/yad-backfill/SKILL.md +4 -0
- package/skills/yad-change/SKILL.md +4 -0
- package/skills/yad-checks/SKILL.md +13 -7
- package/skills/yad-checks/references/check-gates.md +62 -30
- package/skills/yad-checks/templates/checks/member-check.mjs +3 -2
- package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
- package/skills/yad-checks/templates/checks/verified-commits.sh +3 -3
- package/skills/yad-checks/templates/github/yad-checks.yml +357 -69
- package/skills/yad-checks/templates/github/yad-pr-text.yml +118 -0
- package/skills/yad-checks/templates/github/yad-product-checks.yml +130 -54
- package/skills/yad-checks/templates/github/yad-product-pr-text.yml +131 -0
- package/skills/yad-checks/templates/github/yad-update-guard.yml +2 -1
- package/skills/yad-checks/templates/github/yad-verified-commits.yml +49 -3
- package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +79 -20
- package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +59 -9
- package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +1 -0
- package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +49 -1
- package/skills/yad-checks/templates/hooks/agent-guard.mjs +44 -10
- package/skills/yad-checks/templates/hooks/ledger-guard-cursor.mjs +12 -6
- package/skills/yad-commit/SKILL.md +3 -1
- package/skills/yad-connect-design/SKILL.md +42 -10
- package/skills/yad-connect-design/references/design-context.md +35 -5
- package/skills/yad-connect-design/references/design-registry.md +3 -3
- package/skills/yad-connect-learning/SKILL.md +12 -2
- package/skills/yad-connect-repos/SKILL.md +4 -0
- package/skills/yad-connect-testing/SKILL.md +22 -5
- package/skills/yad-connect-testing/references/testing-context.md +1 -1
- package/skills/yad-epic/SKILL.md +4 -0
- package/skills/yad-epic/references/state-schema.md +15 -0
- package/skills/yad-guide/SKILL.md +8 -4
- package/skills/yad-implement/SKILL.md +56 -4
- package/skills/yad-implement/references/implement-conventions.md +2 -1
- package/skills/yad-issues/SKILL.md +53 -0
- package/skills/yad-learn/SKILL.md +4 -0
- package/skills/yad-open-pr/SKILL.md +6 -0
- package/skills/yad-pr-template/SKILL.md +2 -1
- package/skills/yad-pr-template/templates/checks/pr-title.sh +34 -2
- package/skills/yad-product-bridge/references/bridge.md +28 -0
- package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +25 -11
- package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +38 -14
- package/skills/yad-run/SKILL.md +5 -0
- package/skills/yad-scan/SKILL.md +51 -0
- package/skills/yad-spec/SKILL.md +13 -2
- package/skills/yad-test-cases/SKILL.md +18 -2
- package/skills/yad-ui/SKILL.md +43 -8
- package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +0 -49
package/cli/issues.mjs
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
// E169 — the team's backlog, read from GitHub issues and GitLab issues/tasks/incidents ("tracker items": in
|
|
2
|
+
// yadflow "work item" already names an epic's type). Read live from the Product repo and every registered
|
|
3
|
+
// code repo, as `yad standup` reads pull requests, and E70's rule holds: an empty list is an answer only
|
|
4
|
+
// when the platform answered it. A repo that cannot be read is "not read", never "no items".
|
|
5
|
+
//
|
|
6
|
+
// THIS COMMAND PRINTS TITLES, unlike standup and `yad usage`: a backlog with no titles is no use. So:
|
|
7
|
+
// - a title or label is written by anyone who can open an item. It is cleaned once when read (`forTerminal`)
|
|
8
|
+
// and escaped for each output; the HTML page's script only moves rows, it never builds markup;
|
|
9
|
+
// - a GitLab confidential item keeps its number and facts, and its title is never read into the model.
|
|
10
|
+
// Status is worked out from facts (open or closed, and later the linked epic). A `status:` label is never read.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import { run, readJSON, forTerminal, c, log, fail, hand, info, note } from './lib.mjs';
|
|
13
|
+
import { productConfigPath } from './manifest.mjs';
|
|
14
|
+
import { platformLogin } from './platform.mjs';
|
|
15
|
+
import { readMembers, productIdentity } from './members.mjs';
|
|
16
|
+
import { prTarget } from './pr-list.mjs';
|
|
17
|
+
import { repoSources, whoseAccount } from './standup.mjs';
|
|
18
|
+
import { api, httpStatus, shown, whyFailed, PAGE, TIMEOUT } from './protection.mjs';
|
|
19
|
+
import { esc, writeReport } from './usage.mjs';
|
|
20
|
+
import { allLinks, combinedStage, epicStage, itemKey } from './issue-links.mjs';
|
|
21
|
+
|
|
22
|
+
export const MAX_ITEMS = 1000;
|
|
23
|
+
const MAX_PAGES = Math.ceil(MAX_ITEMS / PAGE);
|
|
24
|
+
const DAY = 86_400_000;
|
|
25
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
26
|
+
export const DEFAULT_CLOSED_DAYS = 30;
|
|
27
|
+
export const PRIORITIES = ['P0', 'P1', 'P2', 'P3'];
|
|
28
|
+
export const ITEM_TYPES = ['bug', 'feature', 'enhancement', 'security', 'tech-debt', 'suggestion'];
|
|
29
|
+
export const STATUSES = ['todo', 'in progress', 'done'];
|
|
30
|
+
const SORTS = ['priority', 'type', 'status', 'due', 'updated'];
|
|
31
|
+
const DATE_FIELDS = ['created', 'updated', 'due'];
|
|
32
|
+
const LABEL_COLOR = { priority: 'b60205', type: '1d76db', status: '0e8a16' };
|
|
33
|
+
|
|
34
|
+
// ---- labels --------------------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
// The accepted labels of each value: the first is what `yad issues labels` creates. `issues.priority` and
|
|
37
|
+
// `issues.type` in the Product settings replace a value's list, one value at a time.
|
|
38
|
+
export function labelRules(productConfig, notes = []) {
|
|
39
|
+
const rules = {
|
|
40
|
+
priority: Object.fromEntries(PRIORITIES.map((p) => [p, [`priority: ${p}`, p]])),
|
|
41
|
+
type: { bug: ['bug', 'type: bug'], feature: ['feature', 'type: feature'], enhancement: ['enhancement', 'type: enhancement'], security: ['security', 'type: security'], 'tech-debt': ['tech-debt', 'type: tech-debt'], suggestion: ['suggestion', 'type: suggestion'] },
|
|
42
|
+
status: Object.fromEntries(STATUSES.map((s) => [s, [`status: ${s}`]])),
|
|
43
|
+
};
|
|
44
|
+
const set = productConfig?.issues;
|
|
45
|
+
if (set === undefined || set === null) return rules;
|
|
46
|
+
if (typeof set !== 'object' || Array.isArray(set)) { notes.push('the "issues" settings in .sdlc/product.json are not an object — the default labels are used'); return rules; }
|
|
47
|
+
for (const kind of ['priority', 'type']) {
|
|
48
|
+
if (set[kind] === undefined) continue;
|
|
49
|
+
for (const [value, list] of Object.entries(set[kind] ?? {})) {
|
|
50
|
+
const good = Object.hasOwn(rules[kind], value) && Array.isArray(list) && list.length > 0 && list.every((l) => typeof l === 'string' && l.trim());
|
|
51
|
+
if (good) rules[kind][value] = list.map((l) => l.trim());
|
|
52
|
+
else notes.push(`the "issues.${forTerminal(kind)}.${forTerminal(value)}" setting in .sdlc/product.json is not a list of labels for a known value — ignored`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return rules;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// The first value (in the fixed order: most urgent first) with a label on the item, and whether two differ.
|
|
59
|
+
export function pick(labels, table) {
|
|
60
|
+
const have = new Set(labels.map((l) => l.toLowerCase()));
|
|
61
|
+
const found = Object.keys(table).filter((v) => table[v].some((l) => have.has(l.toLowerCase())));
|
|
62
|
+
return { value: found[0] ?? null, more: found.length > 1 };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// An item's type. A finding's label sits beside an ordinary one (`bug` and `security` is common), and the ordinary one
|
|
66
|
+
// decides: only two ordinary labels, or two finding labels with no ordinary one, are "more than one".
|
|
67
|
+
const FINDING_TYPES = new Set(['security', 'tech-debt', 'suggestion']);
|
|
68
|
+
export function pickType(labels, table) {
|
|
69
|
+
const part = (keep) => Object.fromEntries(Object.entries(table).filter(([k]) => keep(FINDING_TYPES.has(k))));
|
|
70
|
+
const ordinary = pick(labels, part((f) => !f));
|
|
71
|
+
return ordinary.value ? ordinary : pick(labels, part((f) => f));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// ---- reading ---------------------------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
const str = (v) => (typeof v === 'string' && v ? v : null);
|
|
77
|
+
const clean = (v) => forTerminal(String(v ?? '')).replace(/\s+/g, ' ').trim();
|
|
78
|
+
const day = (v) => (typeof v === 'string' && !Number.isNaN(Date.parse(v)) ? new Date(v).toISOString().slice(0, 10) : null);
|
|
79
|
+
const httpUrl = (v) => { try { const u = new URL(v); return ['http:', 'https:'].includes(u.protocol) ? u.href : null; } catch { return null; } };
|
|
80
|
+
|
|
81
|
+
const ghFields = 'number title url state createdAt updatedAt closedAt milestone{dueOn} assignees(first:20){nodes{login}} labels(first:100){nodes{name}}';
|
|
82
|
+
const GH_ITEMS = `query($owner:String!,$name:String!,$cursor:String,$states:[IssueState!],$since:DateTime){repository(owner:$owner,name:$name){hasIssuesEnabled issues(first:${PAGE},after:$cursor,filterBy:{states:$states,since:$since},orderBy:{field:UPDATED_AT,direction:DESC}){pageInfo{hasNextPage endCursor} nodes{${ghFields}}}}}`;
|
|
83
|
+
|
|
84
|
+
// One state of one GitHub repo, page by page. `{ ok:true, nodes, partial, why?, off? }` or `{ ok:false, why }`.
|
|
85
|
+
function readGitHub(t, runner, state, since) {
|
|
86
|
+
const [owner, name, ...rest] = t.repo.split('/');
|
|
87
|
+
if (!name || rest.length) return { ok: false, kind: 'no-url', why: `${shown(t.repo)} is not an owner/name GitHub repo path` };
|
|
88
|
+
const what = `the issues of ${shown(t.repo)}`;
|
|
89
|
+
const nodes = [];
|
|
90
|
+
let cursor = null;
|
|
91
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
92
|
+
const args = ['api', '--hostname', t.host, 'graphql', '-f', `query=${GH_ITEMS}`, '-f', `owner=${owner}`, '-f', `name=${name}`, '-f', `states=${state}`];
|
|
93
|
+
if (since) args.push('-f', `since=${since}`);
|
|
94
|
+
if (cursor) args.push('-f', `cursor=${cursor}`);
|
|
95
|
+
const r = runner('gh', args, { timeout: TIMEOUT });
|
|
96
|
+
let why = null;
|
|
97
|
+
let repo = null;
|
|
98
|
+
if (!r.ok) {
|
|
99
|
+
why = httpStatus(r) == null && /\bGraphQL:/.test(`${r.stderr || ''}${r.stdout || ''}`)
|
|
100
|
+
? `GitHub answered the issue query for ${shown(t.repo)} with an error (the repo may not exist, or your login may not see it)`
|
|
101
|
+
: whyFailed({ ok: false, status: httpStatus(r) }, { platform: 'github', host: t.host, what, plural: true });
|
|
102
|
+
} else {
|
|
103
|
+
try { repo = JSON.parse(r.stdout)?.data?.repository; } catch { /* judged just below */ }
|
|
104
|
+
if (!repo || (repo.hasIssuesEnabled !== false && !Array.isArray(repo.issues?.nodes))) why = whyFailed({ unreadable: true }, { platform: 'github', host: t.host, what, plural: true });
|
|
105
|
+
}
|
|
106
|
+
if (why) return page === 0 ? { ok: false, kind: 'other', why } : { ok: true, nodes, partial: true, why };
|
|
107
|
+
if (repo.hasIssuesEnabled === false) return { ok: true, nodes: [], partial: false, off: true };
|
|
108
|
+
nodes.push(...repo.issues.nodes);
|
|
109
|
+
if (!repo.issues.pageInfo?.hasNextPage) return { ok: true, nodes, partial: false };
|
|
110
|
+
cursor = repo.issues.pageInfo.endCursor;
|
|
111
|
+
if (!cursor) return { ok: true, nodes, partial: true };
|
|
112
|
+
}
|
|
113
|
+
return { ok: true, nodes, partial: true };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function readGitLab(t, runner, state, since) {
|
|
117
|
+
const what = `the issues of ${shown(t.repo)}`;
|
|
118
|
+
const at = `projects/${encodeURIComponent(t.repo)}/issues?state=${state}&order_by=updated_at&sort=desc&per_page=${PAGE}${since ? `&updated_after=${encodeURIComponent(since)}` : ''}`;
|
|
119
|
+
const nodes = [];
|
|
120
|
+
for (let page = 1; page <= MAX_PAGES; page++) {
|
|
121
|
+
const res = api(runner, 'glab', t.host, `${at}&page=${page}`);
|
|
122
|
+
const list = res.ok && Array.isArray(res.body) ? res.body : null;
|
|
123
|
+
if (!list) {
|
|
124
|
+
const why = whyFailed(res.ok ? { unreadable: true } : res, { platform: 'gitlab', host: t.host, what, plural: true });
|
|
125
|
+
return page === 1 ? { ok: false, kind: 'other', why } : { ok: true, nodes, partial: true, why };
|
|
126
|
+
}
|
|
127
|
+
nodes.push(...list);
|
|
128
|
+
if (list.length < PAGE) return { ok: true, nodes, partial: false };
|
|
129
|
+
}
|
|
130
|
+
return { ok: true, nodes, partial: true };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// The platform's answer in one shape. Nothing but these fields leaves this function.
|
|
134
|
+
function ghItem(n) {
|
|
135
|
+
return { number: n.number, title: clean(n.title), url: httpUrl(n.url), state: n.state === 'CLOSED' ? 'closed' : 'open', kind: 'issue',
|
|
136
|
+
labels: (n.labels?.nodes || []).map((l) => clean(l?.name)).filter(Boolean),
|
|
137
|
+
logins: (n.assignees?.nodes || []).map((a) => str(a?.login)).filter(Boolean),
|
|
138
|
+
created: day(n.createdAt), updated: day(n.updatedAt), closed: day(n.closedAt), due: day(n.milestone?.dueOn), confidential: false };
|
|
139
|
+
}
|
|
140
|
+
function glItem(n) {
|
|
141
|
+
const confidential = n.confidential === true;
|
|
142
|
+
return { number: n.iid, title: confidential ? '(confidential: open it on GitLab to read the title)' : clean(n.title), url: httpUrl(n.web_url), state: n.state === 'closed' ? 'closed' : 'open',
|
|
143
|
+
kind: ['issue', 'task', 'incident', 'test_case'].includes(n.issue_type) ? n.issue_type : 'issue',
|
|
144
|
+
labels: confidential ? [] : (Array.isArray(n.labels) ? n.labels.map(clean).filter(Boolean) : []),
|
|
145
|
+
logins: (Array.isArray(n.assignees) ? n.assignees : []).map((a) => str(a?.username)).filter(Boolean),
|
|
146
|
+
created: day(n.created_at), updated: day(n.updated_at), closed: day(n.closed_at), due: day(n.due_date), confidential };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// The items of one repo: open ones, and those closed since `closedSinceMs`.
|
|
150
|
+
// `{ ok:true, items, partial, why?, off? }` or `{ ok:false, kind, why }`.
|
|
151
|
+
export function listTrackerItems(target, { closedSinceMs, runner = run, env = process.env, authCache = new Map() } = {}) {
|
|
152
|
+
const t = target?.cli ? target : prTarget(target, { runner, env, authCache });
|
|
153
|
+
if (!t.ok) return t;
|
|
154
|
+
const gh = t.platform === 'github';
|
|
155
|
+
const read = gh ? readGitHub : readGitLab;
|
|
156
|
+
// Whole UTC days: what is asked, what is kept and what the report's heading says are the same day.
|
|
157
|
+
const since = `${new Date(closedSinceMs).toISOString().slice(0, 10)}T00:00:00.000Z`;
|
|
158
|
+
const open = read(t, runner, gh ? 'OPEN' : 'opened', null);
|
|
159
|
+
if (!open.ok) return { ...t, ...open };
|
|
160
|
+
if (open.off) return { ...t, ok: true, items: [], partial: false, off: true };
|
|
161
|
+
const closed = read(t, runner, gh ? 'CLOSED' : 'closed', since);
|
|
162
|
+
const toItem = gh ? ghItem : glItem;
|
|
163
|
+
const nodes = [...open.nodes, ...(closed.ok ? closed.nodes : [])].filter((n) => n && Number.isInteger(n.number ?? n.iid));
|
|
164
|
+
const items = nodes.map(toItem).filter((i) => i.state === 'open' || (i.closed && Date.parse(i.closed) >= Date.parse(since.slice(0, 10))));
|
|
165
|
+
const why = open.why || (closed.ok ? closed.why : `the closed items were not read: ${closed.why}`) || null;
|
|
166
|
+
return { ...t, ok: true, items, partial: !!(open.partial || closed.partial || !closed.ok), ...(why ? { why } : {}) };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ---- the model -------------------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
// Status from facts. `epicStage` is the linked epic's stage, or null with no linked epic.
|
|
172
|
+
export function itemStatus(state, epicStage = null) {
|
|
173
|
+
if (state === 'closed') return { status: 'done', flags: epicStage && epicStage !== 'shipped' ? ['closed, epic still running'] : [] };
|
|
174
|
+
if (epicStage === 'shipped') return { status: 'done', flags: ['epic shipped, item still open'] };
|
|
175
|
+
return { status: epicStage ? 'in progress' : 'todo', flags: [] };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const rank = (list, v) => { const i = list.indexOf(v); return i < 0 ? list.length : i; };
|
|
179
|
+
const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
180
|
+
const late = (v) => v || '9999-99-99';
|
|
181
|
+
const tie = (a, b) => cmp(rank(PRIORITIES, a.priority), rank(PRIORITIES, b.priority)) || cmp(late(a.due), late(b.due)) || cmp(b.updated || '', a.updated || '') || cmp(a.ref, b.ref);
|
|
182
|
+
export const SORTERS = {
|
|
183
|
+
priority: tie,
|
|
184
|
+
type: (a, b) => cmp(rank(ITEM_TYPES, a.type), rank(ITEM_TYPES, b.type)) || tie(a, b),
|
|
185
|
+
status: (a, b) => cmp(rank(STATUSES, a.status), rank(STATUSES, b.status)) || tie(a, b),
|
|
186
|
+
due: (a, b) => cmp(late(a.due), late(b.due)) || tie(a, b),
|
|
187
|
+
updated: (a, b) => cmp(b.updated || '', a.updated || '') || tie(a, b),
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
// One account, across platforms: the same login on two hosts can be two people.
|
|
191
|
+
export const accountId = (a) => `${a.platform}/${String(a.host).toLowerCase()}/${String(a.login).toLowerCase()}`;
|
|
192
|
+
|
|
193
|
+
// The Product repo's items are `#12`, every other repo's `<label>#12`.
|
|
194
|
+
export function buildIssues(root, { now = Date.now(), closedSinceMs = now - DEFAULT_CLOSED_DAYS * DAY, env = process.env, runner, authCache = new Map() } = {}) {
|
|
195
|
+
const r = runner ? { runner } : {};
|
|
196
|
+
const notes = [];
|
|
197
|
+
const productConfig = readJSON(productConfigPath(root), null);
|
|
198
|
+
const rules = labelRules(productConfig, notes);
|
|
199
|
+
const identity = productIdentity(root, { productConfig, ...r });
|
|
200
|
+
const got = readMembers(root, { identity });
|
|
201
|
+
const notRead = [];
|
|
202
|
+
// With no local paths judged, the one thing written here is an unreadable registry: code repos went unread.
|
|
203
|
+
const sources = repoSources(root, identity, productConfig, notRead, env, { localPaths: false });
|
|
204
|
+
const registryUnread = notRead.length > 0;
|
|
205
|
+
const seen = new Set();
|
|
206
|
+
const links = allLinks(root);
|
|
207
|
+
if (links.unreadable.length) notes.push(`the item links of ${links.unreadable.join(', ')} could not be read, so items linked there show as unlinked`);
|
|
208
|
+
const stages = new Map();
|
|
209
|
+
const stageOf = (e) => { if (!stages.has(e)) stages.set(e, epicStage(root, e)); return stages.get(e); };
|
|
210
|
+
const items = [];
|
|
211
|
+
const repos = [];
|
|
212
|
+
for (const s of sources) {
|
|
213
|
+
const target = prTarget({ platform: s.platform, gitUrl: s.gitUrl }, { env, authCache, ...r });
|
|
214
|
+
const key = target.host && target.repo ? `${target.host}/${target.repo}`.toLowerCase() : null;
|
|
215
|
+
if (key && seen.has(key)) continue;
|
|
216
|
+
if (key) seen.add(key);
|
|
217
|
+
const res = target.ok ? listTrackerItems(target, { closedSinceMs, env, ...r }) : target;
|
|
218
|
+
repos.push({ label: s.label, platform: target.platform ?? null, host: target.host ?? null, repo: target.repo ?? null, read: !!res.ok, why: res.ok ? null : res.why, partial: !!res.partial, issuesOff: !!res.off });
|
|
219
|
+
if (!res.ok) { notRead.push(`${s.label}: not read — ${res.why}`); continue; }
|
|
220
|
+
if (res.off) notes.push(`${s.label}: issues are turned off for this repo`);
|
|
221
|
+
if (res.partial) notes.push(`${s.label}: not every item was read${res.why ? ` — ${res.why}` : ` (the limit is ${MAX_ITEMS} of each state)`}, so the list is incomplete`);
|
|
222
|
+
for (const it of res.items) {
|
|
223
|
+
const p = pick(it.labels, rules.priority);
|
|
224
|
+
const ty = pickType(it.labels, rules.type);
|
|
225
|
+
// Several epics can share an item. A linked epic whose ledger cannot be read still counts as started.
|
|
226
|
+
const linked = links.byItem.get(itemKey({ host: target.host, repo: target.repo, number: it.number })) || [];
|
|
227
|
+
const st = itemStatus(it.state, linked.length ? (combinedStage(linked.map(stageOf)) ?? 'in-shape') : null);
|
|
228
|
+
const flags = [...st.flags];
|
|
229
|
+
const epicRows = linked.map((id) => ({ id, stage: stageOf(id) }));
|
|
230
|
+
if (epicRows.some((e) => e.stage === null)) flags.push('linked epic could not be read, so this status is a guess');
|
|
231
|
+
if (p.more) flags.push('more than one priority label');
|
|
232
|
+
if (ty.more) flags.push('more than one type label');
|
|
233
|
+
const assignees = it.logins.map((login) => {
|
|
234
|
+
const m = whoseAccount(got.members, { platform: target.platform, host: target.host, login }, got.disputed);
|
|
235
|
+
return { login: clean(login), member: m.member ? m.member.primary.login : null, memberKey: m.member ? accountId(m.member.primary) : null, ambiguous: !!m.ambiguous };
|
|
236
|
+
});
|
|
237
|
+
items.push({ ref: `${s.label === 'Product' ? '' : s.label}#${it.number}`, repo: s.label, platform: target.platform, host: target.host, number: it.number, title: it.title, url: it.url,
|
|
238
|
+
state: it.state, kind: it.kind, priority: p.value, type: ty.value, labels: it.labels, assignees, created: it.created, updated: it.updated, closed: it.closed, due: it.due,
|
|
239
|
+
confidential: it.confidential, status: st.status, epic: epicRows[0] ?? null, epics: epicRows, flags });
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
items.sort(SORTERS.priority);
|
|
243
|
+
return { items, repos, notRead, notes, closedSince: new Date(closedSinceMs).toISOString().slice(0, 10), untrustedFields: ['title', 'labels'], registryUnread, memberErrors: got.errors?.length ?? 0 };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const list = (v) => String(v).split(',').map((x) => x.trim()).filter(Boolean);
|
|
247
|
+
const lower = (v) => String(v).toLowerCase();
|
|
248
|
+
|
|
249
|
+
// Narrow and sort. `mine` (from `--me`) is a map `platform\0host` → this person's login.
|
|
250
|
+
export function applyFilters(items, { priority, type, status, assignee, repo, since, until, date = 'created', sort = 'priority', mine = null } = {}) {
|
|
251
|
+
const inList = (want, v, none) => !want || list(want).map(lower).includes(lower(v ?? none));
|
|
252
|
+
const out = items.filter((i) => inList(priority, i.priority, 'none') && inList(type, i.type, 'none') && inList(status, i.status, '') && inList(repo, i.repo, '')
|
|
253
|
+
&& (!assignee || (lower(assignee) === 'none' ? i.assignees.length === 0 : i.assignees.some((a) => [a.login, a.member].filter(Boolean).map(lower).includes(lower(assignee)))))
|
|
254
|
+
&& (!mine || i.assignees.some((a) => mine.get(`${i.platform}\0${i.host}`)?.toLowerCase() === a.login.toLowerCase()))
|
|
255
|
+
&& (!since || (i[date] && i[date] >= since)) && (!until || (i[date] && i[date] <= until)));
|
|
256
|
+
return out.sort(SORTERS[sort]);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export function summarize(items) {
|
|
260
|
+
const by = (key, values) => Object.fromEntries([...values, 'none'].map((v) => [v, items.filter((i) => (i[key] ?? 'none') === v).length]));
|
|
261
|
+
return { total: items.length, status: Object.fromEntries(STATUSES.map((s) => [s, items.filter((i) => i.status === s).length])), priority: by('priority', PRIORITIES), type: by('type', ITEM_TYPES),
|
|
262
|
+
unassigned: items.filter((i) => !i.assignees.length).length };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ---- output ----------------------------------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
const FOOTER = 'Item titles are included. Check this report before sharing it outside the team. A repo listed under "Not read" may hold more items.';
|
|
268
|
+
const who = (i) => (i.assignees.length ? i.assignees.map((a) => a.member || a.login).join(', ') : 'unassigned');
|
|
269
|
+
const counts = (s) => `${s.total} item${s.total === 1 ? '' : 's'}: ${STATUSES.map((v) => `${s.status[v]} ${v}`).join(', ')}; ${s.priority.none} with no priority, ${s.type.none} with no type, ${s.unassigned} unassigned`;
|
|
270
|
+
const gaps = (m) => [...m.notRead, ...m.notes];
|
|
271
|
+
|
|
272
|
+
function renderText(m) {
|
|
273
|
+
info(c.bold(counts(m.summary)));
|
|
274
|
+
for (const i of m.items) {
|
|
275
|
+
log(` ${i.ref.padEnd(14)} ${(i.priority ?? '--').padEnd(3)} ${(i.type ?? '-').padEnd(12)} ${i.status.padEnd(12)} ${who(i).padEnd(16)} ${i.title}${i.flags.length ? c.yellow(` [${i.flags.join('; ')}]`) : ''}`);
|
|
276
|
+
}
|
|
277
|
+
if (!m.items.length) log(m.notRead.length ? ' nothing found in the repos that answered' : ' no items');
|
|
278
|
+
for (const g of gaps(m)) note(c.yellow(g));
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// A title in Markdown: every character that could start a link, an image, code or a tag is escaped, and so
|
|
282
|
+
// are the triggers of GitHub's automatic links (`https:`, `www.`, an address's `@`).
|
|
283
|
+
export const mdEscape = (s) => String(s ?? '').replace(/\r?\n/g, ' ').replace(/([\\`*_{}[\]()<>#|!~&:@])/g, '\\$1').replace(/(?<![a-z0-9])www\./gi, (w) => `${w.slice(0, 3)}\\.`);
|
|
284
|
+
|
|
285
|
+
export function renderMarkdown(m) {
|
|
286
|
+
const L = ['# Issues and work items', '', `- ${counts(m.summary)}`, `- Closed items since ${m.closedSince}`, '', '| Item | Priority | Type | Status | Assignee | Due | Title | Notes |', '|---|---|---|---|---|---|---|---|'];
|
|
287
|
+
for (const i of m.items) {
|
|
288
|
+
L.push(`| ${i.url ? `[${mdEscape(i.ref)}](${i.url.replace(/[()|]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`)})` : mdEscape(i.ref)} | ${i.priority ?? 'none'} | ${i.type ?? 'none'} | ${i.status} | ${mdEscape(who(i))} | ${i.due ?? ''} | ${mdEscape(i.title)} | ${mdEscape(i.flags.join('; '))} |`);
|
|
289
|
+
}
|
|
290
|
+
if (gaps(m).length) L.push('', '## Not read, or incomplete', '', ...gaps(m).map((g) => `- ${mdEscape(g)}`));
|
|
291
|
+
L.push('', `_${FOOTER}_`, '');
|
|
292
|
+
return L.join('\n');
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const options = (values) => values.map((v) => `<option value="${esc(lower(v))}">${esc(v)}</option>`).join('');
|
|
296
|
+
|
|
297
|
+
// One self-contained file. The table is written here, escaped, and reads with scripting off. The script only
|
|
298
|
+
// hides and re-orders those rows using their data attributes; it never builds markup from an item's text.
|
|
299
|
+
export function renderHtml(m) {
|
|
300
|
+
const people = [...new Set(m.items.flatMap((i) => i.assignees.map((a) => a.member || a.login)))].sort();
|
|
301
|
+
const repos = [...new Set(m.items.map((i) => i.repo))].sort();
|
|
302
|
+
const cell = (label, inner, cls = '') => `<td data-label="${label}"${cls ? ` class="${cls}"` : ''}>${inner}</td>`;
|
|
303
|
+
const row = (i) => {
|
|
304
|
+
const members = i.assignees.map((a) => lower(a.member || a.login)).join('\n');
|
|
305
|
+
const num = i.url ? `<a href="${esc(i.url)}" rel="noopener noreferrer">${esc(i.ref)}</a>` : esc(i.ref);
|
|
306
|
+
return `<tr data-priority="${rank(PRIORITIES, i.priority)}" data-p="${esc(lower(i.priority ?? 'none'))}" data-type="${rank(ITEM_TYPES, i.type)}" data-t="${esc(lower(i.type ?? 'none'))}" data-status="${rank(STATUSES, i.status)}" data-s="${esc(i.status)}" data-repo="${esc(lower(i.repo))}" data-members="${esc(members)}" data-created="${esc(i.created ?? '')}" data-updated="${esc(i.updated ?? '')}" data-due="${esc(i.due ?? '')}" data-ref="${esc(i.ref)}">`
|
|
307
|
+
+ cell('Item', num, 'ref') + cell('Priority', i.priority ? `<span class="pri pri-${esc(lower(i.priority))}">${esc(i.priority)}</span>` : '<span class="dim">none</span>')
|
|
308
|
+
+ cell('Type', i.type ? esc(i.type) : '<span class="dim">none</span>') + cell('Status', `<span class="st st-${rank(STATUSES, i.status)}">${esc(i.status)}</span>`)
|
|
309
|
+
+ cell('Title', `${esc(i.title)}${i.flags.map((f) => `<span class="flag">${esc(f)}</span>`).join('')}`, 'title') + cell('Assignee', i.assignees.length ? esc(who(i)) : '<span class="dim">unassigned</span>')
|
|
310
|
+
+ cell('Epic', i.epic ? esc(i.epic.id) : '<span class="dim">none</span>') + cell('Created', esc(i.created ?? ''), 'date') + cell('Updated', esc(i.updated ?? ''), 'date') + cell('Due', esc(i.due ?? ''), 'date') + '</tr>';
|
|
311
|
+
};
|
|
312
|
+
const th = (key, label) => `<th scope="col"${key ? ` aria-sort="none"` : ''}>${key ? `<button type="button" data-sort="${key}">${label}</button>` : label}</th>`;
|
|
313
|
+
const select = (id, label, opts) => `<label>${label}<select id="${id}"><option value="">All</option>${opts}</select></label>`;
|
|
314
|
+
const missing = gaps(m);
|
|
315
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
316
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'">
|
|
317
|
+
<title>Issues and work items</title><style>
|
|
318
|
+
:root{--bg:#fff;--fg:#1d2026;--dim:#5d6470;--card:#f6f7f9;--line:#e1e4ea;--link:#0b57d0;--warn:#8a4b00;--p0:#b3261e;--p1:#b3541e}
|
|
319
|
+
@media (prefers-color-scheme:dark){:root{--bg:#0f1115;--fg:#e6e8ee;--dim:#9aa0ad;--card:#181b22;--line:#2b303a;--link:#8ab4f8;--warn:#f0b35a;--p0:#f28b82;--p1:#f6ae74}}
|
|
320
|
+
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
|
|
321
|
+
.wrap{max-width:1240px;margin:0 auto;padding:28px 16px}h1{font-size:22px;margin:0 0 4px}.sub{color:var(--dim);margin:0 0 16px}a{color:var(--link)}.dim{color:var(--dim)}
|
|
322
|
+
.gaps{border:1px solid var(--line);border-left:4px solid var(--warn);border-radius:6px;padding:10px 14px;margin:0 0 16px}.gaps h2{font-size:14px;margin:0 0 4px}.gaps ul{margin:0;padding-left:18px}
|
|
323
|
+
.filters{display:flex;flex-wrap:wrap;gap:10px;background:var(--card);border:1px solid var(--line);border-radius:8px;padding:12px;margin:0 0 12px}
|
|
324
|
+
.filters label{display:flex;flex-direction:column;font-size:12px;color:var(--dim);gap:2px}select,input,#reset{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:5px;padding:4px 6px;min-height:32px}#reset{align-self:flex-end;cursor:pointer}
|
|
325
|
+
#count{margin:0 0 8px;color:var(--dim)}table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}th{font-size:12px;color:var(--dim);white-space:nowrap}th button{all:unset;cursor:pointer}th button:focus-visible{outline:2px solid var(--link)}
|
|
326
|
+
[aria-sort=ascending] button::after{content:" ▲"}[aria-sort=descending] button::after{content:" ▼"}td.ref,td.date{white-space:nowrap}td.title{min-width:260px;overflow-wrap:anywhere}
|
|
327
|
+
.pri{font-weight:600}.pri-p0{color:var(--p0)}.pri-p1{color:var(--p1)}.st{white-space:nowrap}.st-0{color:var(--dim)}.flag{display:block;color:var(--warn);font-size:12px}
|
|
328
|
+
footer{color:var(--dim);font-size:12px;margin-top:20px;border-top:1px solid var(--line);padding-top:10px}
|
|
329
|
+
@media (max-width:720px){thead{position:absolute;left:-9999px}tr{display:block;border:1px solid var(--line);border-radius:8px;margin:0 0 10px;padding:6px 10px}td{display:flex;gap:10px;border:0;padding:3px 0}td::before{content:attr(data-label);color:var(--dim);flex:0 0 72px;font-size:12px}td:empty{display:none}td.title{min-width:0;display:block}td.title::before{display:block}}
|
|
330
|
+
</style></head><body><div class="wrap"><h1>Issues and work items</h1>
|
|
331
|
+
<p class="sub">${esc(counts(m.summary))}. Closed items since ${esc(m.closedSince)}.</p>
|
|
332
|
+
${missing.length ? `<section class="gaps"><h2>Not read, or incomplete</h2><ul>${missing.map((g) => `<li>${esc(g)}</li>`).join('')}</ul></section>` : ''}
|
|
333
|
+
<form class="filters" id="filters">${select('f-member', 'Member', `<option value="\n">Unassigned</option>${options(people)}`)}${select('f-t', 'Type', `${options(ITEM_TYPES)}<option value="none">None</option>`)}${select('f-p', 'Priority', `${options(PRIORITIES)}<option value="none">None</option>`)}${select('f-s', 'Status', options(STATUSES))}${select('f-repo', 'Repo', options(repos))}
|
|
334
|
+
<label>Date<select id="f-date">${DATE_FIELDS.map((d) => `<option value="${d}">${d[0].toUpperCase()}${d.slice(1)}</option>`).join('')}</select></label><label>From<input type="date" id="f-from"></label><label>To<input type="date" id="f-to"></label><button type="reset" id="reset">Clear</button></form>
|
|
335
|
+
<p id="count" role="status"></p><table><thead><tr>${th('ref', 'Item')}${th('priority', 'Priority')}${th('type', 'Type')}${th('status', 'Status')}${th('', 'Title')}${th('', 'Assignee')}${th('', 'Epic')}${th('created', 'Created')}${th('updated', 'Updated')}${th('due', 'Due')}</tr></thead>
|
|
336
|
+
<tbody id="rows">${m.items.map(row).join('\n')}</tbody></table>${m.items.length ? '' : `<p class="dim">${m.notRead.length ? 'Nothing found in the repos that answered.' : 'No items.'}</p>`}
|
|
337
|
+
<footer>${esc(FOOTER)}</footer></div>
|
|
338
|
+
<script>${PAGE_SCRIPT}</script></body></html>\n`;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Fixed text: no value from an item is ever part of this script.
|
|
342
|
+
const PAGE_SCRIPT = `(function(){var body=document.getElementById('rows'),rows=[].slice.call(body.rows),all=rows.length,$=function(i){return document.getElementById(i)},count=$('count');
|
|
343
|
+
function apply(){var m=$('f-member').value,t=$('f-t').value,p=$('f-p').value,s=$('f-s').value,r=$('f-repo').value,d=$('f-date').value,a=$('f-from').value,b=$('f-to').value,n=0;rows.forEach(function(x){var v=x.dataset[d],on=(!t||x.dataset.t===t)&&(!p||x.dataset.p===p)&&(!s||x.dataset.s===s)&&(!r||x.dataset.repo===r)&&(!m||(m==='\\n'?x.dataset.members==='':x.dataset.members.split('\\n').indexOf(m)>=0))&&(!a||(v&&v>=a))&&(!b||(v&&v<=b));x.hidden=!on;if(on)n++});count.textContent='Showing '+n+' of '+all}
|
|
344
|
+
var form=$('filters');form.addEventListener('input',apply);form.addEventListener('change',apply);form.addEventListener('reset',function(){setTimeout(apply,0)});form.addEventListener('submit',function(e){e.preventDefault()});
|
|
345
|
+
var num={priority:1,type:1,status:1};document.querySelectorAll('[data-sort]').forEach(function(btn){btn.addEventListener('click',function(){var k=btn.dataset.sort,th=btn.parentNode,up=th.getAttribute('aria-sort')!=='ascending';document.querySelectorAll('th[aria-sort]').forEach(function(h){h.setAttribute('aria-sort','none')});th.setAttribute('aria-sort',up?'ascending':'descending');rows.sort(function(x,y){var a=x.dataset[k],b=y.dataset[k];if(!a!==!b)return a?-1:1;var c=num[k]?a-b:a.localeCompare(b,undefined,{numeric:true});return up?c:-c});rows.forEach(function(x){body.appendChild(x)})})});apply()})();`;
|
|
346
|
+
|
|
347
|
+
// ---- the commands ----------------------------------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
const LIST_ONLY = new Set(['--priority', '--type', '--status', '--assignee', '--me', '--repo', '--since', '--until', '--date', '--sort', '--closed-since', '--format', '--out', '--json', '--dir']);
|
|
350
|
+
// The Markdown link of an item's URL, with the characters that would end it encoded.
|
|
351
|
+
export const mdUrl = (u) => u.replace(/[()|]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
352
|
+
|
|
353
|
+
const LABEL_FLAGS = new Set(['--dry-run', '--json', '--dir']);
|
|
354
|
+
const WORD_FLAGS = new Set(['--json', '--dir']);
|
|
355
|
+
export const foreignFlags = (argv, action) => argv.filter((a) => a.startsWith('-') && !(action === 'labels' || action === 'sync' ? LABEL_FLAGS : action === 'list' ? LIST_ONLY : WORD_FLAGS).has(a.split('=')[0]));
|
|
356
|
+
|
|
357
|
+
function checkValues(flag, value, allowed) {
|
|
358
|
+
if (!value) return null;
|
|
359
|
+
const bad = list(value).filter((v) => !allowed.map(lower).includes(lower(v)));
|
|
360
|
+
return bad.length ? `unknown ${flag} ${forTerminal(bad.join(', '))} (use ${allowed.join(', ')})` : null;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const oneValue = (flag, value, allowed) => (value && !allowed.map(lower).includes(lower(value)) ? `unknown ${flag} ${forTerminal(String(value))} (use one of ${allowed.join(', ')})` : null);
|
|
364
|
+
const realDate = (v) => DATE_RE.test(v) && !Number.isNaN(Date.parse(v)) && new Date(v).toISOString().slice(0, 10) === v;
|
|
365
|
+
|
|
366
|
+
function closedSince(value, now) {
|
|
367
|
+
if (value === null || value === undefined) return { ms: now - DEFAULT_CLOSED_DAYS * DAY };
|
|
368
|
+
const d = String(value).match(/^(\d{1,4})d$/);
|
|
369
|
+
if (d) return { ms: now - Number(d[1]) * DAY };
|
|
370
|
+
if (realDate(value)) return { ms: Date.parse(value) };
|
|
371
|
+
return { error: `--closed-since must be YYYY-MM-DD or <N>d (got ${forTerminal(String(value))})` };
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// `yad issues [list]`. Returns the model (E1 makes it the `--json` answer), or undefined after refusing.
|
|
375
|
+
export async function runIssuesList(root, { priority = null, type = null, status = null, assignee = null, me = false, repo = null, since = null, until = null, date = null, sort = null, closedSince: closed = null, format = null, out = null, json = false, now = Date.now(), env = process.env, runner, loginOf = platformLogin } = {}) {
|
|
376
|
+
const refuse = (msg, hint) => { fail(msg); if (hint) hand(hint); process.exitCode = 1; };
|
|
377
|
+
if (!fs.existsSync(productConfigPath(root))) return refuse('not a Product (no .sdlc/product.json here)', 'run it from the Product, or pass --dir');
|
|
378
|
+
if (!format && out) format = /\.html?$/i.test(out) ? 'html' : 'md';
|
|
379
|
+
if (format && !['md', 'html'].includes(format)) return refuse(`unknown --format ${forTerminal(String(format))}`, 'use --format md or --format html (or --json for the data)');
|
|
380
|
+
if (assignee && me) return refuse('pass --assignee <login> or --me, not both');
|
|
381
|
+
for (const bad of [checkValues('--priority', priority, [...PRIORITIES, 'none']), checkValues('--type', type, [...ITEM_TYPES, 'none']), checkValues('--status', status, STATUSES), oneValue('--sort', sort, SORTS), oneValue('--date', date, DATE_FIELDS)]) if (bad) return refuse(bad);
|
|
382
|
+
for (const [flag, v] of [['--since', since], ['--until', until]]) if (v && !realDate(v)) return refuse(`${flag} must be a real date, YYYY-MM-DD (got ${forTerminal(String(v))})`);
|
|
383
|
+
const window = closedSince(closed, now);
|
|
384
|
+
if (window.error) return refuse(window.error);
|
|
385
|
+
const whole = buildIssues(root, { now, closedSinceMs: window.ms, env, ...(runner ? { runner } : {}) });
|
|
386
|
+
let mine = null;
|
|
387
|
+
if (me) {
|
|
388
|
+
mine = new Map();
|
|
389
|
+
for (const r of whole.repos) {
|
|
390
|
+
if (!r.read) continue;
|
|
391
|
+
const key = `${r.platform}\0${r.host}`;
|
|
392
|
+
if (!mine.has(key)) { const l = loginOf(root, r.platform, { env, host: r.host, ...(runner ? { runner } : {}) }); if (l) mine.set(key, l); }
|
|
393
|
+
}
|
|
394
|
+
if (!mine.size && whole.repos.some((r) => r.read)) return refuse('yad cannot tell who you are on these platforms', 'pass --assignee <login>, or log in (gh auth login / glab auth login)');
|
|
395
|
+
for (const r of whole.repos) if (r.read && !mine.has(`${r.platform}\0${r.host}`)) whole.notes.push(`${r.label}: yad cannot tell who you are on ${shown(r.host)}, so its items are left out of --me`);
|
|
396
|
+
}
|
|
397
|
+
// With no readable registry the list of names is incomplete, so a name it lacks proves nothing.
|
|
398
|
+
if (repo && !whole.registryUnread) {
|
|
399
|
+
const known = whole.repos.map((r) => r.label);
|
|
400
|
+
const bad = list(repo).filter((v) => !known.map(lower).includes(lower(v)));
|
|
401
|
+
if (bad.length) return refuse(`no repo named ${forTerminal(bad.join(', '))}`, `use one of: ${known.join(', ')}`);
|
|
402
|
+
}
|
|
403
|
+
const items = applyFilters(whole.items, { priority, type, status, assignee, repo, since, until, date: date ? lower(date) : 'created', sort: sort ? lower(sort) : 'priority', mine });
|
|
404
|
+
const model = { ...whole, items, summary: summarize(items), unfiltered: whole.items.length };
|
|
405
|
+
if (format) {
|
|
406
|
+
const dest = out || `issues-report.${format}`;
|
|
407
|
+
writeReport(dest, format === 'md' ? renderMarkdown(model) : renderHtml(model));
|
|
408
|
+
if (json) note(`wrote ${format.toUpperCase()} report → ${dest}`); else info(`wrote ${format.toUpperCase()} report → ${c.bold(dest)}`);
|
|
409
|
+
for (const g of gaps(model)) if (!json) note(c.yellow(g));
|
|
410
|
+
return { ...model, out: dest };
|
|
411
|
+
}
|
|
412
|
+
if (!json) renderText(model);
|
|
413
|
+
return { ...model, out: null };
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// Every label name on one repo, lower-cased, or `{ ok:false, why }`.
|
|
417
|
+
export function readLabels(t, runner) {
|
|
418
|
+
const gh = t.platform === 'github';
|
|
419
|
+
const at = gh ? `repos/${t.repo}/labels?per_page=${PAGE}` : `projects/${encodeURIComponent(t.repo)}/labels?per_page=${PAGE}`;
|
|
420
|
+
const names = new Set();
|
|
421
|
+
for (let page = 1; page <= MAX_PAGES; page++) {
|
|
422
|
+
const res = api(runner, t.cli, t.host, `${at}&page=${page}`);
|
|
423
|
+
if (!res.ok || !Array.isArray(res.body)) return { ok: false, why: whyFailed(res.ok ? { unreadable: true } : res, { platform: t.platform, host: t.host, what: `the labels of ${shown(t.repo)}`, plural: true }) };
|
|
424
|
+
for (const l of res.body) if (typeof l?.name === 'string') names.add(l.name.toLowerCase());
|
|
425
|
+
if (res.body.length < PAGE) return { ok: true, names };
|
|
426
|
+
}
|
|
427
|
+
return { ok: false, why: `${shown(t.repo)} has more labels than yad reads` };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export function createLabel(t, name, color, runner) {
|
|
431
|
+
const gh = t.platform === 'github';
|
|
432
|
+
const at = gh ? `repos/${t.repo}/labels` : `projects/${encodeURIComponent(t.repo)}/labels`;
|
|
433
|
+
return runner(t.cli, ['api', '--hostname', t.host, '-X', 'POST', at, '-f', `name=${name}`, '-f', `color=${gh ? color : `#${color}`}`], { timeout: TIMEOUT });
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// `yad issues labels`: add the predefined labels each repo lacks. A label counts as there if ANY accepted
|
|
437
|
+
// spelling is (a repo with `P1` is not given `priority: P1`).
|
|
438
|
+
export async function runIssuesLabels(root, { dryRun = false, json = false, env = process.env, runner = run } = {}) {
|
|
439
|
+
if (!fs.existsSync(productConfigPath(root))) { fail('not a Product (no .sdlc/product.json here)'); hand('run it from the Product, or pass --dir'); process.exitCode = 1; return undefined; }
|
|
440
|
+
const notes = [];
|
|
441
|
+
const productConfig = readJSON(productConfigPath(root), null);
|
|
442
|
+
const rules = labelRules(productConfig, notes);
|
|
443
|
+
const identity = productIdentity(root, { productConfig, runner });
|
|
444
|
+
const notRead = [];
|
|
445
|
+
const sources = repoSources(root, identity, productConfig, notRead, env, { localPaths: false });
|
|
446
|
+
const authCache = new Map();
|
|
447
|
+
const seen = new Set();
|
|
448
|
+
const repos = [];
|
|
449
|
+
for (const s of sources) {
|
|
450
|
+
const t = prTarget({ platform: s.platform, gitUrl: s.gitUrl }, { env, authCache, runner });
|
|
451
|
+
const key = t.host && t.repo ? `${t.host}/${t.repo}`.toLowerCase() : null;
|
|
452
|
+
if (key && seen.has(key)) continue;
|
|
453
|
+
if (key) seen.add(key);
|
|
454
|
+
if (!t.ok) { repos.push({ label: s.label, read: false, why: t.why, created: [], failed: [], missing: [] }); continue; }
|
|
455
|
+
const have = readLabels(t, runner);
|
|
456
|
+
if (!have.ok) { repos.push({ label: s.label, read: false, why: have.why, created: [], failed: [], missing: [] }); continue; }
|
|
457
|
+
const missing = Object.entries(rules).flatMap(([kind, table]) => Object.values(table).filter((names) => !names.some((n) => have.names.has(n.toLowerCase()))).map((names) => ({ name: names[0], color: LABEL_COLOR[kind] })));
|
|
458
|
+
const created = [];
|
|
459
|
+
const failed = [];
|
|
460
|
+
if (!dryRun) for (const l of missing) (createLabel(t, l.name, l.color, runner).ok ? created : failed).push(l.name);
|
|
461
|
+
repos.push({ label: s.label, read: true, why: null, created, failed, missing: missing.map((l) => l.name) });
|
|
462
|
+
}
|
|
463
|
+
if (!json) {
|
|
464
|
+
for (const r of repos) {
|
|
465
|
+
if (!r.read) note(c.yellow(`${r.label}: not read — ${r.why}`));
|
|
466
|
+
else if (!r.missing.length) info(`${r.label}: every label is there`);
|
|
467
|
+
else if (dryRun) info(`${r.label}: would create ${r.missing.join(', ')}`);
|
|
468
|
+
else { if (r.created.length) info(`${r.label}: created ${r.created.join(', ')}`); if (r.failed.length) note(c.yellow(`${r.label}: could not create ${r.failed.join(', ')} (your login may not be allowed to)`)); }
|
|
469
|
+
}
|
|
470
|
+
for (const n of [...notRead, ...notes]) note(c.yellow(n));
|
|
471
|
+
}
|
|
472
|
+
if (notRead.length || repos.some((r) => !r.read || r.failed.length)) process.exitCode = 1;
|
|
473
|
+
return { dryRun, repos, notRead, notes };
|
|
474
|
+
}
|
package/cli/lifecycle.mjs
CHANGED
|
@@ -57,6 +57,11 @@ export function loadDefault(n = DEFAULT_VERSION) {
|
|
|
57
57
|
//
|
|
58
58
|
// Read when the validator first needs it, not when this module loads: every `yad` command imports this
|
|
59
59
|
// module, and only the validator needs the older defaults.
|
|
60
|
+
// E164: folders the engine commits with a yadflow step that no default lists, because `extraPaths` takes
|
|
61
|
+
// files, never a folder, and a shipped default never changes. The UI design's `design/` (the epic's design
|
|
62
|
+
// file) is the one: `artifactPaths('ui-design')` in cli/epic-state.mjs names it, and a test ties the two.
|
|
63
|
+
// Its name is reserved for that step, and every file inside it is that step's review, like a folder artifact.
|
|
64
|
+
export const ENGINE_FOLDERS = { 'ui-design': ['design/'] };
|
|
60
65
|
let claims = null;
|
|
61
66
|
export function yadflowClaims() {
|
|
62
67
|
if (claims) return claims;
|
|
@@ -73,6 +78,7 @@ export function yadflowClaims() {
|
|
|
73
78
|
for (const f of [art?.path, ...extras]) if (f) byKey.set(artifactKey(f), o);
|
|
74
79
|
}
|
|
75
80
|
}
|
|
81
|
+
for (const [o, dirs] of Object.entries(ENGINE_FOLDERS)) for (const d of dirs) byKey.set(artifactKey(d), o);
|
|
76
82
|
claims = { byOrigin, byKey };
|
|
77
83
|
return claims;
|
|
78
84
|
}
|
|
@@ -437,6 +443,7 @@ export function lifecycleProblems(raw) {
|
|
|
437
443
|
claimsList.push({ step: s.id, where, path: claimed, key, level: stepLevel, member, productSet });
|
|
438
444
|
}
|
|
439
445
|
if (n.artifact?.type === 'folder' && artPath) folders.push({ step: s.id, level: stepLevel, prefix: artPath.replace(/\/?$/, '/').toLowerCase() });
|
|
446
|
+
for (const d of origin !== null && Object.hasOwn(ENGINE_FOLDERS, origin) ? ENGINE_FOLDERS[origin] : []) folders.push({ step: s.id, level: stepLevel, prefix: d.toLowerCase() });
|
|
440
447
|
allPaths.push(...[artPath, ...extras].filter((x) => typeof x === 'string').map((x) => ({ step: s.id, level: stepLevel, path: x })));
|
|
441
448
|
|
|
442
449
|
// Behaviours.
|
package/cli/manifest.mjs
CHANGED
|
@@ -63,6 +63,8 @@ export const SKILLS = [
|
|
|
63
63
|
'yad-defects',
|
|
64
64
|
'yad-reconcile',
|
|
65
65
|
'yad-stub',
|
|
66
|
+
'yad-issues',
|
|
67
|
+
'yad-scan',
|
|
66
68
|
];
|
|
67
69
|
|
|
68
70
|
// Old skill names. `check`/`update` migrate any install still carrying one: remove the old copy,
|
|
@@ -189,7 +191,7 @@ export const MODULE_CONFIG = '.sdlc/config.yaml';
|
|
|
189
191
|
// the fallback `registerDesign`/setup use when an unknown tool is named, and `none` is the explicit
|
|
190
192
|
// markdown-only choice. (doctor does NOT fall back — an unknown tool there is a hard YAD-CFG-002 fail,
|
|
191
193
|
// mirroring how registerRepo falls back on platform while doctor fails on an unknown Product platform.)
|
|
192
|
-
export const DESIGN_TOOLS = ['figma', 'pencil'];
|
|
194
|
+
export const DESIGN_TOOLS = ['figma', 'pencil', 'openpencil'];
|
|
193
195
|
export const DESIGN_PRIMARY = 'figma';
|
|
194
196
|
|
|
195
197
|
// Supported testing-tool adapters (mirrors skills/sdlc/config.yaml `testing.tools`); `TESTING_PRIMARY`
|
|
@@ -492,6 +494,8 @@ export const REPO_WIRING = {
|
|
|
492
494
|
],
|
|
493
495
|
github: [
|
|
494
496
|
{ src: 'skills/yad-checks/templates/github/yad-checks.yml', dest: '.github/workflows/yad-checks.yml' },
|
|
497
|
+
// pr-title + pr-template, the only checks an edit of the PR text re-runs (#425).
|
|
498
|
+
{ src: 'skills/yad-checks/templates/github/yad-pr-text.yml', dest: '.github/workflows/yad-pr-text.yml' },
|
|
495
499
|
// Integrity gate for direct-to-default pushes (`yad update --push`): verified-commits + commit-message.
|
|
496
500
|
{ src: 'skills/yad-checks/templates/github/yad-update-guard.yml', dest: '.github/workflows/yad-update-guard.yml' },
|
|
497
501
|
{ src: 'skills/yad-pr-template/templates/github/pull_request_template.md', dest: '.github/pull_request_template.md' },
|
|
@@ -549,6 +553,7 @@ export const PRODUCT_WIRING = {
|
|
|
549
553
|
{ src: 'skills/yad-product-bridge/templates/github/yad-gate-sync.yml', dest: '.github/workflows/yad-gate-sync.yml' },
|
|
550
554
|
{ src: 'skills/yad-checks/templates/github/yad-verified-commits.yml', dest: '.github/workflows/yad-verified-commits.yml' },
|
|
551
555
|
{ src: 'skills/yad-checks/templates/github/yad-product-checks.yml', dest: '.github/workflows/yad-product-checks.yml' },
|
|
556
|
+
{ src: 'skills/yad-checks/templates/github/yad-product-pr-text.yml', dest: '.github/workflows/yad-product-pr-text.yml' },
|
|
552
557
|
// Integrity gate for the Product's own direct-to-default pushes (`yad update --push`; the machine-
|
|
553
558
|
// state `yad checkpoint`/`gate ci` commits carry [skip ci] and are intentionally not re-checked).
|
|
554
559
|
{ src: 'skills/yad-checks/templates/github/yad-update-guard.yml', dest: '.github/workflows/yad-update-guard.yml' },
|
|
@@ -574,8 +579,9 @@ export const PROTECTION_GUIDE_URL = 'https://github.com/abdelrahmannasr/yadflow/
|
|
|
574
579
|
// check is named after its job (the jobs set no `name:`), on GitLab a job is the job's key. `yad ci check`
|
|
575
580
|
// reads the GitHub list against the branch's required checks; on GitLab "Pipelines must succeed" covers
|
|
576
581
|
// every job, so the list there is for the docs only. `productVerified` is the Product's verified-commits
|
|
577
|
-
// workflow, required when that file is there.
|
|
578
|
-
//
|
|
582
|
+
// workflow, required when that file is there. On GitHub, pr-title and pr-template run from their own file
|
|
583
|
+
// (yad-pr-text.yml / yad-product-pr-text.yml, #425). Tests hold each list equal to the jobs of its templates
|
|
584
|
+
// and to the table in docs/branch-protection.md.
|
|
579
585
|
export const REQUIRED_CHECKS = Object.freeze({
|
|
580
586
|
github: Object.freeze({
|
|
581
587
|
product: Object.freeze(['commit-message', 'pr-title', 'pr-template', 'ledger-guard', 'member-check']),
|
package/cli/openpr.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import fs from 'node:fs';
|
|
|
7
7
|
import { c, log, ok, info, warn, hand, fail, run, exists, readJSON } from './lib.mjs';
|
|
8
8
|
import { PROJECT_FILES , productConfigPath, settingsEditHint } from './manifest.mjs';
|
|
9
9
|
import {
|
|
10
|
-
detectPlatform, createPr, platformLogin, resolveBaseBranch, prNumberFromUrl, editPrBody,
|
|
10
|
+
detectPlatform, createPr, platformLogin, resolveBaseBranch, prNumberFromUrl, editPrBody, forkBranch, forkBranchWords, branchTaskId,
|
|
11
11
|
} from './platform.mjs';
|
|
12
12
|
import { taskFromBranch } from './commit.mjs';
|
|
13
13
|
import { parseReviewBranch, artifactFromBase, gateCapFor, capLimit, peopleWord, gateRuleSum, gateRuleEnforced, legacyLogins } from './epic-state.mjs';
|
|
@@ -164,8 +164,8 @@ export function routeCount(repoRoot, baseBranch, opts = {}) {
|
|
|
164
164
|
if (high.length && opts.risk !== 'high') lines.push([warn, `the body says Risk level: ${opts.risk || 'low'}, but the risk map on ${map.base} marks ${high.join(', ')} high — the larger counts`]);
|
|
165
165
|
// E72 — the cap, SHOWN and never enforced here. The Build count never holds a merge: the platform's
|
|
166
166
|
// branch protection does (Part 9), and the user decided (2026-09-21) that the Build half stays
|
|
167
|
-
// reported even after E108 turns the Shape cap on. That is also E66's answer:
|
|
168
|
-
//
|
|
167
|
+
// reported even after E108 turns the Shape cap on. That is also E66's answer: CI runs the base branch's copy of the script
|
|
168
|
+
// that counts (#426), but the workflow calling it comes from the PR — harmless only because nothing blocks on it.
|
|
169
169
|
// `gateRuleEnforced` is called WITHOUT the cap on purpose, so the line keeps saying "advisory".
|
|
170
170
|
const cap = gateCapFor(rule, opts.active);
|
|
171
171
|
const capped = cap?.capped ? `, capped to ${cap.to} for ${cap.active} active ${peopleWord(cap.active)}` : '';
|
|
@@ -368,6 +368,21 @@ export async function runOpenPr(root, opts = {}) {
|
|
|
368
368
|
if (!fetched && auto) throw err('YAD-STATE-009', `could not fetch ${baseBranch} from origin, so the tasks ${branch} carries are not known`, 'check the network and your login, then run this again');
|
|
369
369
|
if (!fetched) warn(`could not fetch ${baseBranch} from origin — the tasks this PR carries are read against the last fetched ${baseRef}`);
|
|
370
370
|
const haveBase = run('git', ['rev-parse', '--verify', '--quiet', `${baseRef}^{commit}`], { cwd: repoRoot }).ok;
|
|
371
|
+
// A base nobody chose (the platform's default, origin/HEAD, or 'main') may not be where this branch was
|
|
372
|
+
// cut from (#450): then the range below holds another branch's commits. Stop before anything is pushed.
|
|
373
|
+
// A --base, or a default_branch someone set in repos.json or the Product settings, is trusted as it is.
|
|
374
|
+
if (haveBase && !['flag', 'registry', 'product'].includes(baseSource)) {
|
|
375
|
+
const fork = forkBranch(repoRoot, { base: baseBranch, head: branch });
|
|
376
|
+
if (fork?.skipped) info(`origin has ${fork.skipped} branches, so yad did not check which one ${branch} was cut from — pass --base if it is not ${baseBranch}`);
|
|
377
|
+
else if (fork) {
|
|
378
|
+
const why = forkBranchWords(fork, baseBranch);
|
|
379
|
+
if (auto) throw err('YAD-STATE-009', why, 'a person picks the base and opens it with --base <branch>');
|
|
380
|
+
fail(why);
|
|
381
|
+
if (meta?.name) hand(`if tasks in ${meta.name} always go to one branch, set its default_branch in .sdlc/repos.json`);
|
|
382
|
+
process.exitCode = 1;
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
371
386
|
const commitIds = haveBase ? rangeTasks(repoRoot, `${baseRef}..HEAD`) : null;
|
|
372
387
|
let groupIds = null;
|
|
373
388
|
if (auto) {
|
|
@@ -381,7 +396,12 @@ export async function runOpenPr(root, opts = {}) {
|
|
|
381
396
|
Object.assign(auto, { tasks, ...autoOpenCheck(auto.productRoot, { story: auto.story, tasks, repo: auto.repo }) });
|
|
382
397
|
if (ids.length > 1) groupIds = ids;
|
|
383
398
|
info(`opened on the standing approval: the checks of ${ids.join(', ')} passed, and the open-pr dial is auto`);
|
|
384
|
-
} else if (commitIds && commitIds.length > 1)
|
|
399
|
+
} else if (commitIds && commitIds.length > 1) {
|
|
400
|
+
// The branch's own task first, so the body's Spec path is its story, not the newest commit's (#450).
|
|
401
|
+
const own = (branchTaskId(branch) || '').toLowerCase();
|
|
402
|
+
const at = commitIds.findIndex((t) => t.toLowerCase() === own);
|
|
403
|
+
groupIds = at > 0 ? [commitIds[at], ...commitIds.filter((_t, i) => i !== at)] : commitIds;
|
|
404
|
+
}
|
|
385
405
|
if (groupIds) {
|
|
386
406
|
info(`a grouped PR/MR: ${groupIds.join(', ')}`);
|
|
387
407
|
const settings = readJSON(productConfigPath(opts.product || root), {}) || {};
|
package/cli/plan.mjs
CHANGED
|
@@ -762,6 +762,8 @@ export const PRODUCT_PROFILE_FIX = 'add `product` to its `case "$PROFILE" in` li
|
|
|
762
762
|
// The Product's checks workflows, under the new name and the old (E123): an edited old one is kept, and runs.
|
|
763
763
|
export const PRODUCT_CHECK_WORKFLOWS = Object.freeze([
|
|
764
764
|
'.github/workflows/yad-product-checks.yml', '.gitlab/ci/yad-product-checks.yml',
|
|
765
|
+
// pr-title + pr-template moved here on GitHub (#425), with their `--no-renames` diff lines.
|
|
766
|
+
'.github/workflows/yad-product-pr-text.yml',
|
|
765
767
|
'.github/workflows/yad-hub-checks.yml', '.gitlab/ci/yad-hub-checks.yml',
|
|
766
768
|
]);
|
|
767
769
|
// Those of them on disk that pass `--profile product` to the gates.
|