yadflow 4.8.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 +114 -0
- package/README.md +4 -3
- package/bin/commands.mjs +7 -0
- package/bin/yad.mjs +123 -8
- package/cli/agent-guard.mjs +793 -65
- package/cli/agent-rules.mjs +40 -5
- package/cli/argv-flags.mjs +1 -1
- package/cli/build.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 +176 -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/machine.mjs +141 -0
- package/cli/manifest.mjs +9 -3
- package/cli/openpr.mjs +69 -9
- package/cli/plan.mjs +2 -0
- package/cli/platform.mjs +157 -2
- package/cli/preview.mjs +253 -0
- package/cli/protection.mjs +21 -3
- package/cli/reconcile.mjs +1 -1
- package/cli/repo.mjs +64 -3
- package/cli/review.mjs +4 -0
- 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 +307 -0
- 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-machine.mjs +140 -0
- package/cli/test-node.mjs +15 -0
- package/cli/test-preview.mjs +511 -0
- package/cli/test-run-checks.mjs +17 -0
- package/cli/test-setup-agent.mjs +14 -0
- package/cli/test-story-frames.mjs +409 -0
- package/cli/toolbox-connect.mjs +244 -0
- package/cli/toolbox.mjs +159 -5
- 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 +48 -13
- package/skills/yad-connect-design/references/design-context.md +56 -3
- package/skills/yad-connect-design/references/design-registry.md +4 -4
- package/skills/yad-connect-learning/SKILL.md +12 -2
- package/skills/yad-connect-repos/SKILL.md +12 -0
- package/skills/yad-connect-testing/SKILL.md +22 -5
- package/skills/yad-connect-testing/references/testing-context.md +1 -1
- package/skills/yad-engineer-review/SKILL.md +13 -0
- package/skills/yad-epic/SKILL.md +4 -0
- package/skills/yad-epic/references/state-schema.md +21 -0
- package/skills/yad-guide/SKILL.md +8 -4
- package/skills/yad-implement/SKILL.md +69 -3
- 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 +10 -1
- package/skills/yad-pair-review/SKILL.md +5 -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-pr-template/templates/github/pull_request_template.md +1 -0
- package/skills/yad-pr-template/templates/gitlab/merge_request_templates/Default.md +1 -0
- 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-review-companion/SKILL.md +4 -1
- package/skills/yad-run/SKILL.md +5 -0
- package/skills/yad-scan/SKILL.md +51 -0
- package/skills/yad-spec/SKILL.md +32 -0
- package/skills/yad-stories/SKILL.md +22 -0
- package/skills/yad-stories/references/story-schema.md +1 -0
- package/skills/yad-test-cases/SKILL.md +18 -2
- package/skills/yad-ui/SKILL.md +48 -8
- package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +0 -49
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
// E170 — an issue or work item seeds and links an epic, and the link is written back to the item.
|
|
2
|
+
// `yad issues show <ref>` the full item, for a skill to read. Title and body are marked untrusted.
|
|
3
|
+
// `yad issues link|unlink` the sidecar, and the comment and labels on the item.
|
|
4
|
+
// `yad epic new --issue` the item's type label sets the epic type; a defect or change finds its parent
|
|
5
|
+
// from a definite link, or gets a stub parent. It never guesses from wording.
|
|
6
|
+
// The item must be read before anything is created. A failed write-back leaves the link in place and says so.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { run, readJSON, forTerminal, c, log, fail, hand, info, ok as said, warn, emitJSON } from './lib.mjs';
|
|
10
|
+
import { epicFiles, productConfigPath } from './manifest.mjs';
|
|
11
|
+
import { epicIds, epicRoot, isGenesisType, isValidEpicId, PRODUCT_EPICS, WORK_ITEM_TYPES } from './epic-state.mjs';
|
|
12
|
+
import { addItemLabels, closeItem, commentOnItem, removeItemLabels } from './platform.mjs';
|
|
13
|
+
import { productIdentity } from './members.mjs';
|
|
14
|
+
import { prTarget } from './pr-list.mjs';
|
|
15
|
+
import { repoSources } from './standup.mjs';
|
|
16
|
+
import { api, shown, whyFailed, httpStatus, TIMEOUT } from './protection.mjs';
|
|
17
|
+
import { labelRules, pick, pickType, itemStatus } from './issues.mjs';
|
|
18
|
+
import { runEpicNew, epicIdFrom } from './epic.mjs';
|
|
19
|
+
import { allLinks, combinedStage, epicStage, itemKey, readLinks, writeLinks } from './issue-links.mjs';
|
|
20
|
+
|
|
21
|
+
export { closeItem };
|
|
22
|
+
|
|
23
|
+
const clean = (v) => forTerminal(String(v ?? '')).replace(/\s+/g, ' ').trim();
|
|
24
|
+
// A body keeps its lines; everything else `forTerminal` removes is removed from each one.
|
|
25
|
+
const cleanBody = (v) => String(v ?? '').split(/\r?\n/).map((l) => forTerminal(l)).join('\n');
|
|
26
|
+
const httpUrl = (v) => { try { const u = new URL(v); return ['http:', 'https:'].includes(u.protocol) ? u.href : null; } catch { return null; } };
|
|
27
|
+
const NO_FIELD = /doesn't exist on type|Field '[^']+' doesn't exist/i;
|
|
28
|
+
|
|
29
|
+
const ITEM_TO_EPIC = { bug: 'defect', feature: 'feature', enhancement: 'change', security: 'defect', 'tech-debt': 'change', suggestion: 'change' };
|
|
30
|
+
const EPIC_TO_ITEM = { defect: 'bug', hotfix: 'bug', feature: 'feature', change: 'enhancement' };
|
|
31
|
+
|
|
32
|
+
// `12`, `#12` (the Product repo) or `<repo>#12`. A bare `#12` is a shell comment unless quoted, so `12` works too.
|
|
33
|
+
export function parseRef(ref) {
|
|
34
|
+
const m = /^(?:(.*[^#])#|#)?(\d{1,10})$/.exec(String(ref ?? '').trim());
|
|
35
|
+
return m ? { label: m[1] ?? 'Product', number: Number(m[2]) } : null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function resolveTarget(root, ref, { env, runner, authCache = new Map() }) {
|
|
39
|
+
const parsed = parseRef(ref);
|
|
40
|
+
if (!parsed || parsed.number < 1) return { ok: false, why: `"${forTerminal(String(ref ?? ''))}" is not an item reference`, hint: 'use 12, "#12" for the Product repo, or <repo>#12' };
|
|
41
|
+
const productConfig = readJSON(productConfigPath(root), null);
|
|
42
|
+
const identity = productIdentity(root, { productConfig, runner });
|
|
43
|
+
const notRead = [];
|
|
44
|
+
const sources = repoSources(root, identity, productConfig, notRead, env, { localPaths: false });
|
|
45
|
+
const s = sources.find((x) => x.label === parsed.label);
|
|
46
|
+
if (!s) return { ok: false, why: notRead.length ? `the repo list could not be read, so ${forTerminal(parsed.label)} is unknown` : `no registered repo is called ${forTerminal(parsed.label)}`, hint: `known: ${sources.map((x) => x.label).join(', ')}` };
|
|
47
|
+
const t = prTarget({ platform: s.platform, gitUrl: s.gitUrl }, { env, authCache, runner });
|
|
48
|
+
return { ok: true, t, label: s.label, number: parsed.number, productConfig };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// The parent item, from the platform's own hierarchy. `{ parent: {repo,number}|null }`, or `{ unknown:true }`.
|
|
52
|
+
// A server too old to have the field has no hierarchy at all: that is a real "none".
|
|
53
|
+
function readParent(t, number, runner) {
|
|
54
|
+
const gh = t.platform === 'github';
|
|
55
|
+
const [owner, name] = t.repo.split('/');
|
|
56
|
+
const args = gh
|
|
57
|
+
? ['api', '--hostname', t.host, 'graphql', '-f', 'query=query($o:String!,$n:String!,$i:Int!){repository(owner:$o,name:$n){issue(number:$i){parent{number repository{nameWithOwner}}}}}', '-f', `o=${owner}`, '-f', `n=${name}`, '-F', `i=${number}`]
|
|
58
|
+
: ['api', '--hostname', t.host, 'graphql', '-f', `query=query($p:ID!){project(fullPath:$p){workItems(iids:["${number}"]){nodes{widgets{... on WorkItemWidgetHierarchy{parent{iid namespace{fullPath}}}}}}}}`, '-f', `p=${t.repo}`];
|
|
59
|
+
const r = runner(t.cli, args, { timeout: TIMEOUT });
|
|
60
|
+
if (NO_FIELD.test(`${r.stdout || ''}${r.stderr || ''}`)) return { parent: null };
|
|
61
|
+
if (!r.ok) return { unknown: true };
|
|
62
|
+
let d;
|
|
63
|
+
try { d = JSON.parse(r.stdout)?.data; } catch { return { unknown: true }; }
|
|
64
|
+
if (gh) {
|
|
65
|
+
const issue = d?.repository?.issue;
|
|
66
|
+
if (!issue) return { unknown: true };
|
|
67
|
+
return { parent: issue.parent?.number ? { repo: issue.parent.repository?.nameWithOwner ?? t.repo, number: issue.parent.number } : null };
|
|
68
|
+
}
|
|
69
|
+
const node = d?.project?.workItems?.nodes?.[0];
|
|
70
|
+
if (!node) return { unknown: true };
|
|
71
|
+
const p = (node.widgets || []).find((w) => w && w.parent)?.parent;
|
|
72
|
+
return { parent: p?.iid ? { repo: p.namespace?.fullPath ?? t.repo, number: Number(p.iid) } : null };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// One item, in one shape, or `{ ok:false, why }`. A pull request is not an item.
|
|
76
|
+
export function readItem(t, number, { runner = run } = {}) {
|
|
77
|
+
const gh = t.platform === 'github';
|
|
78
|
+
const at = gh ? `repos/${t.repo}/issues/${number}` : `projects/${encodeURIComponent(t.repo)}/issues/${number}`;
|
|
79
|
+
const res = api(runner, t.cli, t.host, at);
|
|
80
|
+
const what = `item ${number} of ${shown(t.repo)}`;
|
|
81
|
+
if (!res.ok || !res.body || typeof res.body !== 'object') return { ok: false, why: res.ok || res.status !== 404 ? whyFailed(res.ok ? { unreadable: true } : res, { platform: t.platform, host: t.host, what }) : `${what} does not exist, or your login cannot see it` };
|
|
82
|
+
const n = res.body;
|
|
83
|
+
if (gh && n.pull_request) return { ok: false, why: `${number} in ${shown(t.repo)} is a pull request, not an issue` };
|
|
84
|
+
const confidential = n.confidential === true;
|
|
85
|
+
// A confidential item's labels and text drive nothing: not the type, not the parent, not a message.
|
|
86
|
+
const labels = confidential ? [] : (Array.isArray(n.labels) ? n.labels : []).map((l) => clean(typeof l === 'string' ? l : l?.name)).filter(Boolean);
|
|
87
|
+
const logins = (Array.isArray(n.assignees) ? n.assignees : []).map((a) => clean(gh ? a?.login : a?.username)).filter(Boolean);
|
|
88
|
+
return { ok: true, number, confidential, labels, logins, rawText: confidential ? '' : `${n.title ?? ''}\n${(gh ? n.body : n.description) ?? ''}`,
|
|
89
|
+
title: confidential ? null : clean(n.title), body: confidential ? null : cleanBody(gh ? n.body : n.description),
|
|
90
|
+
url: httpUrl(gh ? n.html_url : n.web_url), state: (n.state === 'closed') ? 'closed' : 'open', kind: !gh && ['issue', 'task', 'incident', 'test_case'].includes(n.issue_type) ? n.issue_type : 'issue' };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const bailer = (json) => (message, hint) => {
|
|
94
|
+
if (json) emitJSON({ ok: false, error: message, hint: hint ?? null });
|
|
95
|
+
else { fail(message); if (hint) hand(hint); }
|
|
96
|
+
process.exitCode = 1;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
function loadItem(root, ref, { env, runner, bail }) {
|
|
100
|
+
const r = resolveTarget(root, ref, { env, runner });
|
|
101
|
+
if (!r.ok) return void bail(r.why, r.hint);
|
|
102
|
+
if (!r.t.ok) return void bail(`${forTerminal(r.label)}: ${r.t.why}`);
|
|
103
|
+
const item = readItem(r.t, r.number, { runner });
|
|
104
|
+
if (!item.ok) return void bail(item.why);
|
|
105
|
+
return { ...r, item };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function runIssuesShow(root, { ref, json = false, env = process.env, runner = run } = {}) {
|
|
109
|
+
const bail = bailer(json);
|
|
110
|
+
const got = loadItem(root, ref, { env, runner, bail });
|
|
111
|
+
if (!got) return undefined;
|
|
112
|
+
const { item, t, label, productConfig } = got;
|
|
113
|
+
const rules = labelRules(productConfig);
|
|
114
|
+
const out = { ref: `${label === 'Product' ? '' : label}#${item.number}`, repo: label, platform: t.platform, host: t.host, number: item.number, url: item.url, state: item.state, kind: item.kind,
|
|
115
|
+
priority: item.confidential ? null : pick(item.labels, rules.priority).value, type: item.confidential ? null : pickType(item.labels, rules.type).value,
|
|
116
|
+
labels: item.confidential ? [] : item.labels, assignees: item.logins, confidential: item.confidential, title: item.title, body: item.body, untrusted: true, untrustedFields: ['title', 'body', 'labels'] };
|
|
117
|
+
if (json) return emitJSON({ ok: true, ...out });
|
|
118
|
+
log(`${c.bold(out.ref)} ${out.title ?? '(confidential: open it on GitLab to read it)'}`);
|
|
119
|
+
info(`${out.state} · priority ${out.priority ?? 'none'} · type ${out.type ?? 'none'} · assigned ${out.assignees.join(', ') || 'nobody'}`);
|
|
120
|
+
if (out.url) info(out.url);
|
|
121
|
+
if (out.body) log(`\n${out.body}`);
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Null when a linked epic cannot be read: a label yad cannot stand behind is not written.
|
|
126
|
+
const statusFor = (root, epics, state) => {
|
|
127
|
+
if (state === 'closed') return 'done'; // closed is done, whatever the epic says
|
|
128
|
+
const stage = combinedStage(epics.map((e) => epicStage(root, e)));
|
|
129
|
+
return stage === null ? null : itemStatus(state, stage).status;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
// Put the comment and labels on the item. Never throws, and returns what failed; the link is kept either way.
|
|
133
|
+
export function writeBack(root, epic, entry, t, { item, rules, epicType, runner = run, epics = [epic], unreadable = [], dryRun = false }) {
|
|
134
|
+
const failed = [];
|
|
135
|
+
const failedWhy = (what, r) => { const code = httpStatus(r); failed.push(`${what}: ${code ? `${t.host} answered HTTP ${code}` : clean(r.stderr || 'the write failed').slice(0, 200)}`); };
|
|
136
|
+
const out = { commented: false, labelled: [], removed: [], failed, notes: [] };
|
|
137
|
+
if (!entry.commentedAt && dryRun) out.commented = true;
|
|
138
|
+
else if (!entry.commentedAt) {
|
|
139
|
+
const r = commentOnItem(t, entry.number, `Linked to yadflow epic \`${epic}\`${epicType ? ` (type: ${epicType})` : ''}.`, { runner });
|
|
140
|
+
if (r.ok) { entry.commentedAt = new Date().toISOString(); out.commented = true; } else failedWhy('the comment', r);
|
|
141
|
+
}
|
|
142
|
+
if (item.confidential) { out.notes.push('a confidential item is left unlabelled, because its labels are not read'); return out; }
|
|
143
|
+
const have = new Set(item.labels.map((l) => l.toLowerCase()));
|
|
144
|
+
const add = [];
|
|
145
|
+
const typeOf = EPIC_TO_ITEM[epicType];
|
|
146
|
+
// Only an item with no type label gets one: a second would make the item's type ambiguous.
|
|
147
|
+
if (typeOf && !pickType(item.labels, rules.type).value) add.push(rules.type[typeOf][0]);
|
|
148
|
+
const status = statusFor(root, epics, item.state);
|
|
149
|
+
const linksUnknown = item.state !== 'closed' && unreadable.length > 0;
|
|
150
|
+
if (linksUnknown) failed.push(`the status label: the item links of ${unreadable.join(', ')} could not be read (.sdlc/issue-links.json), so this item's epics are unknown`);
|
|
151
|
+
else if (status === null) failed.push('the status label: a linked epic could not be read, so the status is unknown');
|
|
152
|
+
const known = status !== null && !linksUnknown;
|
|
153
|
+
if (known && !have.has(rules.status[status][0].toLowerCase())) add.push(rules.status[status][0]);
|
|
154
|
+
const stale = known ? Object.entries(rules.status).filter(([s]) => s !== status).flatMap(([, names]) => names).filter((l) => have.has(l.toLowerCase())) : [];
|
|
155
|
+
if (dryRun) { out.labelled = add; out.removed = stale; return out; }
|
|
156
|
+
if (add.length) { const r = addItemLabels(t, entry.number, add, { runner }); if (r.ok) out.labelled = add; else failedWhy(`the labels ${add.join(', ')}`, r); }
|
|
157
|
+
if (stale.length) { if (removeItemLabels(t, entry.number, stale, { runner }).ok) out.removed = stale; else failed.push('the old status label could not be removed'); }
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function makeEntry(t, item, now) {
|
|
162
|
+
return { platform: t.platform, host: t.host, repo: t.repo, number: item.number, url: item.url, linkedAt: new Date(now).toISOString() };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Add the link (or find the one there) and write back. `{ entry, created, back }`.
|
|
166
|
+
function linkAndWriteBack(root, epic, t, item, { rules, epicType, now, runner }) {
|
|
167
|
+
const items = readLinks(root, epic);
|
|
168
|
+
const key = itemKey({ host: t.host, repo: t.repo, number: item.number });
|
|
169
|
+
let entry = items.find((l) => itemKey(l) === key);
|
|
170
|
+
const created = !entry;
|
|
171
|
+
if (created) { entry = makeEntry(t, item, now); items.push(entry); writeLinks(root, epic, items); }
|
|
172
|
+
const every = allLinks(root);
|
|
173
|
+
const back = writeBack(root, epic, entry, t, { item, rules, epicType, runner, epics: every.byItem.get(key) || [epic], unreadable: every.unreadable });
|
|
174
|
+
writeLinks(root, epic, items);
|
|
175
|
+
return { entry, created, back };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function sayBack(back) {
|
|
179
|
+
if (back.commented) info('commented on the item');
|
|
180
|
+
if (back.labelled.length) info(`labels added: ${back.labelled.map(forTerminal).join(', ')}`);
|
|
181
|
+
for (const n of back.notes) info(forTerminal(n));
|
|
182
|
+
for (const f of back.failed) warn(`not written to the item — ${forTerminal(f)}. The link is kept${/^the labels/.test(f) ? '; `yad issues labels` creates missing labels' : ''}`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const SEED_FLAGS = new Set(['--issue', '--type', '--profile', '--stub', '--parent', '--inherits', '--json', '--dir']);
|
|
186
|
+
// `epic new --issue` writes to a platform, so a flag it does not use (`--repo`, `--dry-run`) is refused, not dropped.
|
|
187
|
+
export const seedForeignFlags = (argv) => argv.filter((a) => a.startsWith('-') && !SEED_FLAGS.has(a.split('=')[0]));
|
|
188
|
+
|
|
189
|
+
// A leftover approvals.json the child's seed would refuse: records in it, or one that does not parse.
|
|
190
|
+
const hasApprovals = (p) => { if (!fs.existsSync(p)) return false; try { const a = JSON.parse(fs.readFileSync(p, 'utf8')); return !Array.isArray(a) || a.length > 0; } catch { return true; } };
|
|
191
|
+
|
|
192
|
+
// Whether a person ever reopened the item: true, false, or null when the history could not all be read.
|
|
193
|
+
function everReopened(t, number, runner) {
|
|
194
|
+
const gh = t.platform === 'github';
|
|
195
|
+
const at = gh ? `repos/${t.repo}/issues/${number}/events?per_page=100` : `projects/${encodeURIComponent(t.repo)}/issues/${number}/resource_state_events?per_page=100`;
|
|
196
|
+
for (let page = 1; page <= 10; page++) {
|
|
197
|
+
const res = api(runner, t.cli, t.host, `${at}&page=${page}`);
|
|
198
|
+
if (!res.ok || !Array.isArray(res.body)) return null;
|
|
199
|
+
if (res.body.some((e) => (gh ? e?.event === 'reopened' : e?.state === 'reopened'))) return true;
|
|
200
|
+
if (res.body.length < 100) return false;
|
|
201
|
+
}
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ---- sync (E171) -------------------------------------------------------------------------------------
|
|
206
|
+
|
|
207
|
+
// The repos yad may write to, as Map(host/repo → target). The links file is committed, so anyone with a PR could
|
|
208
|
+
// point it at another repo: an item is only ever written if its repo is registered here.
|
|
209
|
+
function registeredTargets(root, { env, runner }) {
|
|
210
|
+
const productConfig = readJSON(productConfigPath(root), null);
|
|
211
|
+
const identity = productIdentity(root, { productConfig, runner });
|
|
212
|
+
const notRead = [];
|
|
213
|
+
const sources = repoSources(root, identity, productConfig, notRead, env, { localPaths: false });
|
|
214
|
+
const authCache = new Map();
|
|
215
|
+
const targets = new Map();
|
|
216
|
+
for (const s of sources) {
|
|
217
|
+
const t = prTarget({ platform: s.platform, gitUrl: s.gitUrl }, { env, authCache, runner });
|
|
218
|
+
if (t.host && t.repo) targets.set(`${t.host}/${t.repo}`.toLowerCase(), { ...t, label: s.label });
|
|
219
|
+
}
|
|
220
|
+
return { targets, productConfig, registryUnread: notRead.length > 0 };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Bring each linked item up to date. `only` limits it to one epic's items. Returns the plan of what happened.
|
|
224
|
+
export function syncItems(root, { only = null, dryRun = false, close = true, env = process.env, runner = run, now = Date.now() } = {}) {
|
|
225
|
+
const links = allLinks(root);
|
|
226
|
+
const epicsOf = (key) => links.byItem.get(key) || [];
|
|
227
|
+
const scope = new Set();
|
|
228
|
+
const entriesByEpic = new Map();
|
|
229
|
+
for (const epic of new Set([...links.byItem.values()].flat())) {
|
|
230
|
+
const items = readLinks(root, epic);
|
|
231
|
+
entriesByEpic.set(epic, items);
|
|
232
|
+
if (only === null || epic === only) for (const l of items) scope.add(itemKey(l));
|
|
233
|
+
}
|
|
234
|
+
const out = { items: [], unreadable: links.unreadable, skipped: [], dryRun };
|
|
235
|
+
if (!scope.size) return out;
|
|
236
|
+
const { targets, productConfig, registryUnread } = registeredTargets(root, { env, runner });
|
|
237
|
+
const rules = labelRules(productConfig);
|
|
238
|
+
const touched = new Set();
|
|
239
|
+
for (const key of scope) {
|
|
240
|
+
const epics = epicsOf(key);
|
|
241
|
+
const entries = epics.map((epic) => ({ epic, entry: entriesByEpic.get(epic).find((l) => itemKey(l) === key) }));
|
|
242
|
+
const first = entries[0].entry;
|
|
243
|
+
const t = targets.get(`${first.host}/${first.repo}`.toLowerCase());
|
|
244
|
+
const shownRef = `${forTerminal(first.repo)}#${first.number}`;
|
|
245
|
+
if (!t) { out.skipped.push(`${shownRef}: ${registryUnread ? 'the repo list could not be read' : 'its repo is not registered in this Product'}, so it was not written`); continue; }
|
|
246
|
+
if (!t.ok) { out.items.push({ ref: shownRef, epics, commented: false, labelled: [], removed: [], closed: false, failed: [t.why], notes: [] }); continue; }
|
|
247
|
+
const item = readItem(t, first.number, { runner });
|
|
248
|
+
if (!item.ok) { out.items.push({ ref: shownRef, epics, commented: false, labelled: [], removed: [], closed: false, failed: [item.why], notes: [] }); continue; }
|
|
249
|
+
const row = { ref: shownRef, epics, commented: false, labelled: [], removed: [], closed: false, failed: [], notes: [] };
|
|
250
|
+
for (const { epic, entry } of entries) {
|
|
251
|
+
const had = entry.commentedAt;
|
|
252
|
+
const back = writeBack(root, epic, entry, t, { item, rules, epicType: epicTypeOf(root, epic), runner, epics, unreadable: links.unreadable, dryRun });
|
|
253
|
+
if (entry.commentedAt !== had) touched.add(epic);
|
|
254
|
+
row.commented ||= back.commented;
|
|
255
|
+
row.labelled.push(...back.labelled);
|
|
256
|
+
row.removed.push(...back.removed);
|
|
257
|
+
for (const f of back.failed) if (!row.failed.includes(f)) row.failed.push(f);
|
|
258
|
+
for (const n of back.notes) if (!row.notes.includes(n)) row.notes.push(n);
|
|
259
|
+
// What the next epic of this item must see, so the same label is not sent twice.
|
|
260
|
+
const gone = new Set(back.removed.map((l) => l.toLowerCase()));
|
|
261
|
+
item.labels = [...item.labels.filter((l) => !gone.has(l.toLowerCase())), ...back.labelled];
|
|
262
|
+
}
|
|
263
|
+
// Close once, and only when every epic has shipped. An item a person reopened keeps its `closedByYadAt`.
|
|
264
|
+
const allShipped = !links.unreadable.length && epics.every((e) => epicStage(root, e) === 'shipped');
|
|
265
|
+
if (close && item.state === 'open' && allShipped && !entries.some(({ entry }) => entry.closedByYadAt)) {
|
|
266
|
+
// The links file may not be committed, so the platform decides: an item ever reopened is a person's call.
|
|
267
|
+
const again = everReopened(t, first.number, runner);
|
|
268
|
+
if (again === null) row.failed.push('could not read whether the item was reopened, so it was not closed');
|
|
269
|
+
else if (again) row.notes.push('someone reopened this item, so it stays open');
|
|
270
|
+
else if (dryRun) row.closed = true;
|
|
271
|
+
else if (closeItem(t, first.number, { runner }).ok) {
|
|
272
|
+
row.closed = true;
|
|
273
|
+
for (const { entry } of entries) entry.closedByYadAt = new Date(now).toISOString();
|
|
274
|
+
for (const { epic } of entries) { writeLinks(root, epic, entriesByEpic.get(epic)); touched.add(epic); }
|
|
275
|
+
} else row.failed.push('the item could not be closed');
|
|
276
|
+
}
|
|
277
|
+
out.items.push(row);
|
|
278
|
+
}
|
|
279
|
+
if (!dryRun) for (const epic of touched) writeLinks(root, epic, entriesByEpic.get(epic));
|
|
280
|
+
return out;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export async function runIssuesSync(root, { dryRun = false, json = false, env = process.env, runner = run, now = Date.now() } = {}) {
|
|
284
|
+
if (!fs.existsSync(productConfigPath(root))) return bailer(json)('not a Product (no .sdlc/product.json here)', 'run it from the Product, or pass --dir');
|
|
285
|
+
if (env.YAD_PLATFORM_READ === '0') return bailer(json)('platform reads are turned off (YAD_PLATFORM_READ=0)', 'unset it to sync');
|
|
286
|
+
const r = syncItems(root, { dryRun, env, runner, now });
|
|
287
|
+
const failed = r.items.filter((i) => i.failed.length).length + r.skipped.length;
|
|
288
|
+
if (failed || r.unreadable.length) process.exitCode = 1;
|
|
289
|
+
if (json) return emitJSON({ ok: !failed && !r.unreadable.length, ...r });
|
|
290
|
+
for (const i of r.items) {
|
|
291
|
+
const did = [i.commented && 'comment', i.labelled.length && `labels +${i.labelled.map(forTerminal).join(', +')}`, i.removed.length && `labels -${i.removed.map(forTerminal).join(', -')}`, i.closed && 'close'].filter(Boolean);
|
|
292
|
+
log(` ${i.ref} (${i.epics.join(', ')}): ${did.length ? `${dryRun ? 'would ' : ''}${did.join('; ')}` : 'up to date'}`);
|
|
293
|
+
for (const n of i.notes ?? []) info(`${i.ref}: ${forTerminal(n)}`);
|
|
294
|
+
for (const f of i.failed) warn(`${i.ref}: ${forTerminal(f)}`);
|
|
295
|
+
}
|
|
296
|
+
for (const s of r.skipped) warn(s);
|
|
297
|
+
for (const e of r.unreadable) warn(`${e}: its .sdlc/issue-links.json could not be read, so status labels and closes were held back`);
|
|
298
|
+
if (!r.items.length && !r.skipped.length && !r.unreadable.length) info('no items are linked to an epic');
|
|
299
|
+
else if (!dryRun) info('commit any .sdlc/issue-links.json this changed, so the team keeps the record');
|
|
300
|
+
return undefined;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// After a gate advances, on this machine. Best effort: it prints a warning and never fails the gate. An epic
|
|
304
|
+
// with no linked items makes no network call. A gate advanced in CI is caught by the next `yad issues sync`.
|
|
305
|
+
export function syncAfterGate(root, epic, { env = process.env, runner = run, now = Date.now() } = {}) {
|
|
306
|
+
try {
|
|
307
|
+
if (env.YAD_PLATFORM_READ === '0') return;
|
|
308
|
+
if (!readLinks(root, epic).length) return;
|
|
309
|
+
// Status and labels only. Closing an item is asked for, with `yad issues sync`.
|
|
310
|
+
const r = syncItems(root, { only: epic, close: false, env, runner, now });
|
|
311
|
+
const changed = r.items.filter((i) => i.commented || i.labelled.length || i.removed.length);
|
|
312
|
+
for (const i of changed) info(`updated ${i.ref}: ${[i.commented && 'comment', ...i.labelled.map((l) => `+${forTerminal(l)}`), ...i.removed.map((l) => `-${forTerminal(l)}`)].filter(Boolean).join(', ')}`);
|
|
313
|
+
if (changed.some((i) => i.commented)) info('commit .sdlc/issue-links.json so the team keeps the record');
|
|
314
|
+
for (const i of r.items) for (const f of i.failed) warn(`${i.ref}: ${forTerminal(f)}. The gate still passed; \`yad issues sync\` catches up`);
|
|
315
|
+
for (const s of r.skipped) warn(s);
|
|
316
|
+
} catch (e) {
|
|
317
|
+
warn(`the linked items were not updated (${forTerminal(e?.message ?? String(e))}). The gate still passed; \`yad issues sync\` catches up`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const epicTypeOf = (root, epic) => readJSON(epicFiles(epicRoot(root, epic)).state, null)?.type ?? null;
|
|
322
|
+
const knownEpic = (root, epic) => isValidEpicId(epic) && !PRODUCT_EPICS.includes(epic) && fs.existsSync(epicFiles(epicRoot(root, epic)).state);
|
|
323
|
+
|
|
324
|
+
export async function runIssuesLink(root, { ref, epic: raw, json = false, now = Date.now(), env = process.env, runner = run } = {}) {
|
|
325
|
+
const bail = bailer(json);
|
|
326
|
+
const epic = epicIdFrom(raw);
|
|
327
|
+
if (!epic || !knownEpic(root, epic)) return bail(`no epic ${forTerminal(String(raw ?? ''))} here`, 'usage: yad issues link <ref> <EP-id>');
|
|
328
|
+
const got = loadItem(root, ref, { env, runner, bail });
|
|
329
|
+
if (!got) return undefined;
|
|
330
|
+
const rules = labelRules(got.productConfig);
|
|
331
|
+
const { entry, created, back } = linkAndWriteBack(root, epic, got.t, got.item, { rules, epicType: epicTypeOf(root, epic), now, runner });
|
|
332
|
+
if (json) return emitJSON({ ok: true, epic, url: entry.url, number: entry.number, created, commented: back.commented, labelled: back.labelled, failed: back.failed, notes: back.notes });
|
|
333
|
+
said(`${created ? 'linked' : 'already linked:'} ${got.label === 'Product' ? '' : forTerminal(got.label)}#${entry.number} → ${epic}`);
|
|
334
|
+
sayBack(back);
|
|
335
|
+
if (created) info('commit .sdlc/issue-links.json on the epic\'s branch so the team sees the link');
|
|
336
|
+
return undefined;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Unlink never needs the item, and removes nothing from the platform: a person can tidy the comment and labels.
|
|
340
|
+
export async function runIssuesUnlink(root, { ref, epic: raw, json = false, env = process.env, runner = run } = {}) {
|
|
341
|
+
const bail = bailer(json);
|
|
342
|
+
const epic = epicIdFrom(raw);
|
|
343
|
+
if (!epic || !knownEpic(root, epic)) return bail(`no epic ${forTerminal(String(raw ?? ''))} here`, 'usage: yad issues unlink <ref> <EP-id>');
|
|
344
|
+
const r = resolveTarget(root, ref, { env, runner });
|
|
345
|
+
if (!r.ok) return bail(r.why, r.hint);
|
|
346
|
+
if (!r.t.host || !r.t.repo) return bail(`${forTerminal(r.label)}: the repo's address could not be worked out`);
|
|
347
|
+
const key = itemKey({ host: r.t.host, repo: r.t.repo, number: r.number });
|
|
348
|
+
const items = readLinks(root, epic);
|
|
349
|
+
const kept = items.filter((l) => itemKey(l) !== key);
|
|
350
|
+
if (kept.length === items.length) return bail(`${forTerminal(String(ref))} is not linked to ${epic}`);
|
|
351
|
+
writeLinks(root, epic, kept);
|
|
352
|
+
if (json) return emitJSON({ ok: true, epic, number: r.number, removed: true });
|
|
353
|
+
said(`unlinked ${forTerminal(String(ref))} from ${epic}`);
|
|
354
|
+
info('the comment and labels on the item were left as they are');
|
|
355
|
+
return undefined;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// The epics an item names for certain: a label `epic: EP-x`, an `EP-x` in its text, or a parent item that is
|
|
359
|
+
// already linked. Only epics that exist count. `{ ids }`, or `{ unknown:true, why }` if the hierarchy or a links file could not be read.
|
|
360
|
+
export function definiteParents(root, t, item, { self, runner = run }) {
|
|
361
|
+
// A parent needs an epic.md: an epic only just seeded cannot be threaded off yet.
|
|
362
|
+
const known = new Set(epicIds(root).filter((e) => !PRODUCT_EPICS.includes(e) && e !== self && fs.existsSync(path.join(epicRoot(root, e), 'epic.md'))));
|
|
363
|
+
const found = new Set();
|
|
364
|
+
for (const l of item.labels) { const m = /^epic:\s*(EP-[a-z0-9][a-z0-9-]*)$/i.exec(l); if (m) found.add(m[1]); }
|
|
365
|
+
for (const m of item.rawText.matchAll(/(?<![A-Za-z0-9-])EP-[a-z0-9]+(?:-[a-z0-9]+)*/g)) found.add(m[0]);
|
|
366
|
+
const p = readParent(t, item.number, runner);
|
|
367
|
+
const links = p.parent ? allLinks(root) : null;
|
|
368
|
+
if (p.parent) for (const e of links.byItem.get(itemKey({ host: t.host, repo: p.parent.repo, number: p.parent.number })) || []) found.add(e);
|
|
369
|
+
const ids = [...found].filter((e) => known.has(e)).sort();
|
|
370
|
+
if (ids.length) return { ids };
|
|
371
|
+
if (p.unknown) return { unknown: true, why: 'could not read whether the item has a parent item' };
|
|
372
|
+
if (links?.unreadable.length) return { unknown: true, why: `the item has a parent item, but the item links of ${links.unreadable.join(', ')} could not be read (.sdlc/issue-links.json)` };
|
|
373
|
+
return { ids };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// `yad epic new <slug> --issue <ref>`.
|
|
377
|
+
export async function runEpicNewFromIssue(root, { slug, issue, type = null, profile = null, stub = false, parent = null, inherits = null, today, json = false, now = Date.now(), env = process.env, runner = run } = {}) {
|
|
378
|
+
const bail = bailer(json);
|
|
379
|
+
if (stub) return bail('--issue and --stub cannot be used together', 'a stub anchors code that already shipped; an item seeds new work');
|
|
380
|
+
const epic = epicIdFrom(slug);
|
|
381
|
+
if (!epic || !isValidEpicId(epic)) return bail(`invalid epic id: ${forTerminal(String(slug ?? ''))} (expected EP-<slug>, [a-z0-9-] only)`);
|
|
382
|
+
if (fs.existsSync(epicFiles(epicRoot(root, epic)).state)) return bail(`${epic} already has a lifecycle`, `to link an item to it: yad issues link ${forTerminal(String(issue))} ${epic}`);
|
|
383
|
+
readLinks(root, epic); // a leftover links file that cannot be read refuses here, before anything is made
|
|
384
|
+
const got = loadItem(root, issue, { env, runner, bail });
|
|
385
|
+
if (!got) return undefined;
|
|
386
|
+
const { t, item, productConfig } = got;
|
|
387
|
+
const rules = labelRules(productConfig);
|
|
388
|
+
let epicType = type;
|
|
389
|
+
if (!epicType) {
|
|
390
|
+
const ty = pickType(item.labels, rules.type);
|
|
391
|
+
if (ty.more) return bail('the item has more than one type label', 'choose with --type feature|change|defect|chore|hotfix');
|
|
392
|
+
if (!ty.value) return bail('the item has no type label', item.confidential ? 'a confidential item\'s labels are not used. Pass --type' : 'add one (bug, feature, enhancement), or pass --type');
|
|
393
|
+
epicType = ITEM_TO_EPIC[ty.value];
|
|
394
|
+
}
|
|
395
|
+
if (!WORK_ITEM_TYPES.includes(epicType)) return bail(`unknown work-item type: ${forTerminal(String(epicType))}`, `use one of ${WORK_ITEM_TYPES.join(', ')}`);
|
|
396
|
+
let parentId = parent;
|
|
397
|
+
let stubbed = null;
|
|
398
|
+
if (!isGenesisType(epicType) && !parentId) {
|
|
399
|
+
const d = definiteParents(root, t, item, { self: epic, runner });
|
|
400
|
+
if (d.unknown) return bail(d.why, 'pass --parent <EP-id>, so a duplicate stub is not created');
|
|
401
|
+
if (d.ids.length > 1) return bail(`the item points at more than one epic: ${d.ids.join(', ')}`, 'choose one with --parent');
|
|
402
|
+
if (d.ids.length) parentId = d.ids[0];
|
|
403
|
+
else {
|
|
404
|
+
// Everything that would refuse the child is refused here first: a stub left behind by a typo stays for good.
|
|
405
|
+
if (profile && profile !== 'classic') return bail(`a new stub parent is on the classic route, and a child takes its parent's route: --profile ${forTerminal(profile)} cannot apply`, 'drop --profile, or pass --parent');
|
|
406
|
+
if (inherits) return bail('a new stub parent has nothing to inherit', 'drop --inherits, or pass --parent');
|
|
407
|
+
if (fs.existsSync(path.join(epicRoot(root, epic), 'epic.md'))) return bail(`${epic} already has an epic.md`, 'pass --parent, so its header and the parent agree');
|
|
408
|
+
if (hasApprovals(epicFiles(epicRoot(root, epic)).approvals)) return bail(`${epic} has approval records but no lifecycle`, 'look at that folder first: nothing here overwrites a ledger');
|
|
409
|
+
stubbed = `${epic}-parent`;
|
|
410
|
+
if (fs.existsSync(epicFiles(epicRoot(root, stubbed)).state) || fs.existsSync(path.join(epicRoot(root, stubbed), 'epic.md'))) return bail(`${stubbed} already exists`, `if it is this item's parent, pass --parent ${stubbed}`);
|
|
411
|
+
const s = await runEpicNew(root, { slug: stubbed, stub: true, today, json: true, returnResult: true });
|
|
412
|
+
if (!s?.ok) return bail(`the stub parent ${stubbed} could not be created: ${s?.error ?? 'unknown reason'}`, s?.hint);
|
|
413
|
+
// The same header the yad-stub skill writes: a parent needs an epic.md. It names only the ids, so the
|
|
414
|
+
// item's text stays on the platform.
|
|
415
|
+
fs.writeFileSync(path.join(epicRoot(root, stubbed), 'epic.md'), `---\nid: ${stubbed}\ntitle: Parent of ${epic}\nstatus: draft\nkind: feature\ntype: feature\nthread: ${stubbed}\ntheme:\nverified: false\nstub: backfill-pending\norigin: brownfield\nowner:\nrepos: []\ncreated: ${today}\n---\n\n## Feature (stub)\nAn anchor made so ${epic} can thread off it. Nothing is known about this feature yet: document it with the yad-backfill skill.\n`);
|
|
416
|
+
parentId = stubbed;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
const seeded = await runEpicNew(root, { slug: epic, type: epicType, profile, parent: parentId, inherits, today, json: true, returnResult: true });
|
|
420
|
+
if (!seeded?.ok) return bail(`${seeded?.error ?? 'the epic could not be seeded'}${stubbed ? ` (the stub ${stubbed} was created and stays)` : ''}`, seeded?.hint);
|
|
421
|
+
const { entry, back } = linkAndWriteBack(root, epic, t, item, { rules, epicType, now, runner });
|
|
422
|
+
if (json) return emitJSON({ ...seeded, issue: { number: entry.number, url: entry.url }, parent: parentId ?? null, stubParent: stubbed, commented: back.commented, labelled: back.labelled, failed: back.failed, notes: back.notes });
|
|
423
|
+
said(`${epic} seeded from item ${entry.number} — type ${epicType}${parentId ? `, parent ${parentId}${stubbed ? ' (new stub)' : ''}` : ''}`);
|
|
424
|
+
sayBack(back);
|
|
425
|
+
if (seeded.next) hand(`next: the ${seeded.next} skill. It reads the item with \`yad issues show\``);
|
|
426
|
+
info('the item\'s text is not copied here. Commit the seed on this epic\'s authoring branch');
|
|
427
|
+
return undefined;
|
|
428
|
+
}
|