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.
Files changed (107) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +4 -3
  3. package/bin/commands.mjs +7 -0
  4. package/bin/yad.mjs +123 -8
  5. package/cli/agent-guard.mjs +793 -65
  6. package/cli/agent-rules.mjs +40 -5
  7. package/cli/argv-flags.mjs +1 -1
  8. package/cli/build.mjs +1 -1
  9. package/cli/ci-check.mjs +45 -1
  10. package/cli/codeowners-command.mjs +72 -6
  11. package/cli/commit.mjs +17 -3
  12. package/cli/docs.mjs +2 -0
  13. package/cli/doctor.mjs +176 -12
  14. package/cli/epic-state.mjs +94 -4
  15. package/cli/epic.mjs +11 -7
  16. package/cli/fold.mjs +31 -6
  17. package/cli/guide.mjs +3 -1
  18. package/cli/hook.mjs +50 -7
  19. package/cli/issue-links.mjs +61 -0
  20. package/cli/issues-act.mjs +327 -0
  21. package/cli/issues-write.mjs +428 -0
  22. package/cli/issues.mjs +474 -0
  23. package/cli/lifecycle.mjs +7 -0
  24. package/cli/machine.mjs +141 -0
  25. package/cli/manifest.mjs +9 -3
  26. package/cli/openpr.mjs +69 -9
  27. package/cli/plan.mjs +2 -0
  28. package/cli/platform.mjs +157 -2
  29. package/cli/preview.mjs +253 -0
  30. package/cli/protection.mjs +21 -3
  31. package/cli/reconcile.mjs +1 -1
  32. package/cli/repo.mjs +64 -3
  33. package/cli/review.mjs +4 -0
  34. package/cli/run-checks.mjs +10 -2
  35. package/cli/scan.mjs +314 -0
  36. package/cli/setup.mjs +12 -3
  37. package/cli/standup.mjs +33 -7
  38. package/cli/story-frames.mjs +307 -0
  39. package/cli/test-agents-file.mjs +378 -11
  40. package/cli/test-build.mjs +25 -0
  41. package/cli/test-ci-check.mjs +469 -10
  42. package/cli/test-guide.mjs +7 -0
  43. package/cli/test-machine.mjs +140 -0
  44. package/cli/test-node.mjs +15 -0
  45. package/cli/test-preview.mjs +511 -0
  46. package/cli/test-run-checks.mjs +17 -0
  47. package/cli/test-setup-agent.mjs +14 -0
  48. package/cli/test-story-frames.mjs +409 -0
  49. package/cli/toolbox-connect.mjs +244 -0
  50. package/cli/toolbox.mjs +159 -5
  51. package/package.json +7 -3
  52. package/skills/sdlc/config.yaml +1 -1
  53. package/skills/sdlc/module-help.csv +3 -1
  54. package/skills/yad-analysis/SKILL.md +4 -0
  55. package/skills/yad-backfill/SKILL.md +4 -0
  56. package/skills/yad-change/SKILL.md +4 -0
  57. package/skills/yad-checks/SKILL.md +13 -7
  58. package/skills/yad-checks/references/check-gates.md +62 -30
  59. package/skills/yad-checks/templates/checks/member-check.mjs +3 -2
  60. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  61. package/skills/yad-checks/templates/checks/verified-commits.sh +3 -3
  62. package/skills/yad-checks/templates/github/yad-checks.yml +357 -69
  63. package/skills/yad-checks/templates/github/yad-pr-text.yml +118 -0
  64. package/skills/yad-checks/templates/github/yad-product-checks.yml +130 -54
  65. package/skills/yad-checks/templates/github/yad-product-pr-text.yml +131 -0
  66. package/skills/yad-checks/templates/github/yad-update-guard.yml +2 -1
  67. package/skills/yad-checks/templates/github/yad-verified-commits.yml +49 -3
  68. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +79 -20
  69. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +59 -9
  70. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +1 -0
  71. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +49 -1
  72. package/skills/yad-checks/templates/hooks/agent-guard.mjs +44 -10
  73. package/skills/yad-checks/templates/hooks/ledger-guard-cursor.mjs +12 -6
  74. package/skills/yad-commit/SKILL.md +3 -1
  75. package/skills/yad-connect-design/SKILL.md +48 -13
  76. package/skills/yad-connect-design/references/design-context.md +56 -3
  77. package/skills/yad-connect-design/references/design-registry.md +4 -4
  78. package/skills/yad-connect-learning/SKILL.md +12 -2
  79. package/skills/yad-connect-repos/SKILL.md +12 -0
  80. package/skills/yad-connect-testing/SKILL.md +22 -5
  81. package/skills/yad-connect-testing/references/testing-context.md +1 -1
  82. package/skills/yad-engineer-review/SKILL.md +13 -0
  83. package/skills/yad-epic/SKILL.md +4 -0
  84. package/skills/yad-epic/references/state-schema.md +21 -0
  85. package/skills/yad-guide/SKILL.md +8 -4
  86. package/skills/yad-implement/SKILL.md +69 -3
  87. package/skills/yad-implement/references/implement-conventions.md +2 -1
  88. package/skills/yad-issues/SKILL.md +53 -0
  89. package/skills/yad-learn/SKILL.md +4 -0
  90. package/skills/yad-open-pr/SKILL.md +10 -1
  91. package/skills/yad-pair-review/SKILL.md +5 -0
  92. package/skills/yad-pr-template/SKILL.md +2 -1
  93. package/skills/yad-pr-template/templates/checks/pr-title.sh +34 -2
  94. package/skills/yad-pr-template/templates/github/pull_request_template.md +1 -0
  95. package/skills/yad-pr-template/templates/gitlab/merge_request_templates/Default.md +1 -0
  96. package/skills/yad-product-bridge/references/bridge.md +28 -0
  97. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +25 -11
  98. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +38 -14
  99. package/skills/yad-review-companion/SKILL.md +4 -1
  100. package/skills/yad-run/SKILL.md +5 -0
  101. package/skills/yad-scan/SKILL.md +51 -0
  102. package/skills/yad-spec/SKILL.md +32 -0
  103. package/skills/yad-stories/SKILL.md +22 -0
  104. package/skills/yad-stories/references/story-schema.md +1 -0
  105. package/skills/yad-test-cases/SKILL.md +18 -2
  106. package/skills/yad-ui/SKILL.md +48 -8
  107. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +0 -49
package/cli/hook.mjs CHANGED
@@ -29,7 +29,7 @@ import { fileURLToPath } from 'node:url';
29
29
  import { note, readJSON, run } from './lib.mjs';
30
30
  import { isVerifiedLedger, mirrorDrift, productConfigPath, HOOK_PROJECT_DIR_ENVS, PROJECT_FILES } from './manifest.mjs';
31
31
  import { DISCOVERY_EPIC, FOUNDATION_DIR, FOUNDATION_EPIC } from './epic-state.mjs';
32
- import { agentGuardDecision, payloadCommand, isCursorPayload } from './agent-guard.mjs';
32
+ import { agentGuardDecision, agentGuardPreapproval, payloadCommand, isCursorPayload } from './agent-guard.mjs';
33
33
 
34
34
  // The CI-owned files, exactly as `templates/checks/ledger-guard.sh` lists them. NOT `contract-lock.json`
35
35
  // (artifact-side: the architect commits it with the architecture) and NOT `change.json` — both are a
@@ -511,12 +511,38 @@ export function runStagedLedgerGuard({ env = process.env, cwd = process.cwd(), g
511
511
  return 2;
512
512
  }
513
513
 
514
+ // Read all of stdin. Asking `process.stdin.isTTY` makes Node open stdin as a stream, and on a pipe that
515
+ // switches fd 0 to non-blocking: a read then throws EAGAIN ("no data yet") whenever the payload arrives a
516
+ // moment after the hook starts. `fs.readFileSync(0)` gave up there, the hook read no payload, and it
517
+ // allowed — the macOS CI failures on #459 (a deny allowed) and #460 (no Cursor verdict: with no payload
518
+ // the hook could not tell it was Cursor). So this reads in a loop and, on EAGAIN, waits 5 ms and tries
519
+ // again, for up to `limitMs`; after that the error goes to the caller, which fails open. Keep the loop:
520
+ // the non-blocking mode is also what gives the limit — a blocking read would hang for ever on a parent
521
+ // that never closes stdin. A read of 0 bytes (or Windows' EOF error) is the end.
522
+ export function readStdin({ fd = 0, readSync = fs.readSync, limitMs = 5000 } = {}) {
523
+ const chunks = [];
524
+ const buf = Buffer.alloc(64 * 1024);
525
+ const nap = new Int32Array(new SharedArrayBuffer(4));
526
+ const until = Date.now() + limitMs;
527
+ for (;;) {
528
+ let n;
529
+ try { n = readSync(fd, buf, 0, buf.length, null); } catch (e) {
530
+ if (e?.code === 'EAGAIN' && Date.now() < until) { Atomics.wait(nap, 0, 0, 5); continue; }
531
+ if (e?.code === 'EOF') break;
532
+ throw e;
533
+ }
534
+ if (n === 0) break;
535
+ chunks.push(Buffer.from(buf.subarray(0, n)));
536
+ }
537
+ return Buffer.concat(chunks).toString('utf8');
538
+ }
539
+
514
540
  // Read the harness payload off stdin. Absent, empty, or unparseable all mean "nothing to inspect" —
515
541
  // never an error, and never a block.
516
542
  function readPayload() {
517
543
  try {
518
544
  if (process.stdin.isTTY) return null;
519
- const raw = fs.readFileSync(0, 'utf8').trim();
545
+ const raw = readStdin().trim();
520
546
  if (!raw) return null;
521
547
  return JSON.parse(raw);
522
548
  } catch {
@@ -581,10 +607,10 @@ const isReadOnlyCall = (payload) => {
581
607
  };
582
608
 
583
609
  export function runLedgerGuardHook({ paths = [], format = 'exit' } = {}) {
584
- // Only read stdin when there is nothing else to go on. `readFileSync(0)` blocks until EOF, and a
585
- // caller that passes `--path` (the documented stdin-free alternative) may well have inherited an
586
- // open pipe from a long-lived parent — `isTTY` is false there, so the TTY guard does not trip and
587
- // the hook would hang forever. A hang is strictly worse for an agent than a block.
610
+ // Only read stdin when there is nothing else to go on. A caller that passes `--path` (the documented
611
+ // stdin-free alternative) may well have inherited an open pipe from a long-lived parent — `isTTY` is
612
+ // false there, so the TTY guard does not trip, and `readStdin` would wait out its whole limit before
613
+ // going on. Every agent tool call would pay that wait.
588
614
  const payload = paths.length ? null : readPayload();
589
615
  const all = isReadOnlyCall(payload) ? [...paths] : [...new Set([...payloadPaths(payload), ...paths])];
590
616
  const verdict = ledgerGuardDecision(all, {
@@ -618,6 +644,11 @@ export function runLedgerGuardHook({ paths = [], format = 'exit' } = {}) {
618
644
  // `agentGuardDecision`, answered in the protocol the payload names (Cursor's `beforeShellExecution` wants a
619
645
  // JSON verdict; Claude Code reads the exit code) unless `--format` says which. `YAD_HOOK_DISABLE` turns it
620
646
  // off, as it does the ledger guard. Fail-open: no payload, or no command in it, is allowed.
647
+ //
648
+ // Pre-approval (E167, #353): under Claude Code, a line `agentGuardPreapproval` sees only reads is answered with
649
+ // a PreToolUse "allow" on stdout, so it runs with no permission prompt; any other allowed line gets no answer
650
+ // (exit 0, nothing printed), which leaves the prompt to Claude Code as before. `YAD_NO_PREAPPROVE=1` keeps the
651
+ // refusals and drops this half. Cursor's answer is unchanged.
621
652
  export function runAgentGuardHook({ format = null } = {}) {
622
653
  const payload = readPayload();
623
654
  const cursor = format ? format === 'cursor' : isCursorPayload(payload);
@@ -630,8 +661,20 @@ export function runAgentGuardHook({ format = null } = {}) {
630
661
  if (!verdict.allow) console.error(verdict.message);
631
662
  return 0;
632
663
  }
633
- if (verdict.allow) return 0;
664
+ if (verdict.allow) {
665
+ if (!process.env.YAD_HOOK_DISABLE && !process.env.YAD_NO_PREAPPROVE) {
666
+ // Claude Code names the project in CLAUDE_PROJECT_DIR and where the command runs in the payload's `cwd`.
667
+ const root = process.env.CLAUDE_PROJECT_DIR || process.cwd();
668
+ const pre = agentGuardPreapproval(payloadCommand(payload), { root, cwd: typeof payload?.cwd === 'string' && payload.cwd ? payload.cwd : root });
669
+ if (pre.preapproved) process.stdout.write(`${claudePreapproval(pre.reason)}\n`);
670
+ }
671
+ return 0;
672
+ }
634
673
  console.error(verdict.message);
635
674
  process.exitCode = 2;
636
675
  return 2;
637
676
  }
677
+
678
+ // Claude Code's PreToolUse answer that skips the permission prompt. A team's own `deny` or `ask` rule still wins.
679
+ export const claudePreapproval = (reason) => JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow',
680
+ permissionDecisionReason: `yad agent guard: a read-only command (${reason}), pre-approved (E167; YAD_NO_PREAPPROVE=1 turns this off)` } });
@@ -0,0 +1,61 @@
1
+ // E170 — which tracker items (GitHub issues, GitLab work items) belong to an epic. One sidecar per epic,
2
+ // `.sdlc/issue-links.json`, holding only where the item is: its text stays on the platform, so private text
3
+ // does not spread into the repo. It is a separate file so `state.json` and `epic.md` keep their bytes, and
4
+ // the approvals bound to them stay valid.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { readJSONStrict, writeJSON } from './lib.mjs';
8
+ import { err } from './errors.mjs';
9
+ import { epicIds, epicRoot, epicStories, featureStatus, loadLedger, PRODUCT_EPICS } from './epic-state.mjs';
10
+
11
+ export const ISSUE_LINKS_FILE = path.join('.sdlc', 'issue-links.json');
12
+ export const linksPath = (root, epic) => path.join(epicRoot(root, epic), ISSUE_LINKS_FILE);
13
+ export const itemKey = ({ host, repo, number }) => `${String(host).toLowerCase()}/${String(repo).toLowerCase()}#${number}`;
14
+
15
+ // The one rule for what a record is: an entry that fails it makes the whole file unreadable, never "not linked".
16
+ const validLink = (l) => !!l && typeof l === 'object' && !Array.isArray(l) && !!l.host && !!l.repo && Number.isInteger(l.number);
17
+
18
+ // Strict: this is read before a write, and a file that cannot be understood is refused, never replaced.
19
+ export function readLinks(root, epic) {
20
+ const p = linksPath(root, epic);
21
+ const doc = readJSONStrict(p, { items: [] });
22
+ if (!doc || typeof doc !== 'object' || !Array.isArray(doc.items) || !doc.items.every(validLink)) throw err('YAD-STATE-001', `${p} is not an issue-links file (it needs an "items" list of records)`, 'fix the file or restore it from git');
23
+ return doc.items;
24
+ }
25
+ export function writeLinks(root, epic, items) {
26
+ const p = linksPath(root, epic);
27
+ fs.mkdirSync(path.dirname(p), { recursive: true });
28
+ writeJSON(p, { items });
29
+ }
30
+
31
+ const featureEpics = (root) => epicIds(root).filter((e) => !PRODUCT_EPICS.includes(e));
32
+
33
+ // Every link in the Product, as Map(itemKey → [epic id]). An epic whose sidecar cannot be read is named in
34
+ // `unreadable`: its items would otherwise look unlinked, and "unknown" must never read as "none".
35
+ export function allLinks(root) {
36
+ const byItem = new Map();
37
+ const unreadable = [];
38
+ for (const epic of featureEpics(root)) {
39
+ let items;
40
+ try { items = readLinks(root, epic); } catch { unreadable.push(epic); continue; }
41
+ for (const l of items) {
42
+ const k = itemKey(l);
43
+ byItem.set(k, [...(byItem.get(k) || []), epic]);
44
+ }
45
+ }
46
+ return { byItem, unreadable };
47
+ }
48
+
49
+ // An epic's stage (`featureStatus`), or null when its ledger cannot be read.
50
+ export function epicStage(root, epic) {
51
+ try {
52
+ const dir = epicRoot(root, epic);
53
+ return featureStatus(loadLedger(dir), { stories: epicStories(dir) });
54
+ } catch { return null; }
55
+ }
56
+
57
+ // One stage for an item with several epics: the first that has not shipped, else shipped. Null if any is unread.
58
+ export function combinedStage(stages) {
59
+ if (!stages.length || stages.some((s) => s === null)) return null;
60
+ return stages.find((s) => s !== 'shipped') ?? 'shipped';
61
+ }
@@ -0,0 +1,327 @@
1
+ // E173 — the agent acts on an issue or work item when an engineer asks: open one for an idea, assign it,
2
+ // set its priority or type, edit it, comment, close or reopen it. The request is the permission: the agent
3
+ // does it, then reports what changed with the link. It never does any of this on its own initiative.
4
+ //
5
+ // A new item goes to the Product repo unless the engineer names a registered repo. Every write is checked
6
+ // against what the platform answers, so a dropped label, assignee or state is reported, never hidden. A
7
+ // security item is never opened where it would announce the hole: on GitHub only a repo known to be private
8
+ // takes one, and on GitLab it is confidential. The text is the engineer's, so mentions and links stay, but
9
+ // anything shaped like a token is redacted.
10
+ import fs from 'node:fs';
11
+ import { run, forTerminal, c, log, fail, hand, info, warn, emitJSON } from './lib.mjs';
12
+ import { addItemLabels, removeItemLabels, commentOnItem, closeItem, newItem, editItem, reopenItem, setAssignee, makeConfidential, platformLogin } from './platform.mjs';
13
+ import { api, httpStatus } from './protection.mjs';
14
+ import { labelRules, ITEM_TYPES, PRIORITIES } from './issues.mjs';
15
+ import { readItem, resolveTarget } from './issues-write.mjs';
16
+ import { allLinks, itemKey } from './issue-links.mjs';
17
+ import { redactTokens, repoFacts, routeFor } from './scan.mjs';
18
+
19
+ const MAX_TITLE = 256;
20
+ const MAX_BODY = 60000;
21
+ const LOGIN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
22
+ // Only tokens with a known prefix are redacted, so commit hashes and long names in the engineer's text stay.
23
+ const oneLine = (v) => forTerminal(redactTokens(String(v ?? ''))).replace(/\s+/g, ' ').trim();
24
+ const lines = (v) => redactTokens(String(v ?? '')).split(/\r?\n/).map((l) => forTerminal(l)).join('\n');
25
+ const REDACTED_NOTE = 'something shaped like a token was replaced with [redacted]';
26
+ // Only what redaction itself replaced: an engineer who typed `[redacted]` is not told something was removed.
27
+ const tokenIn = (...raws) => raws.some((r) => typeof r === 'string' && redactTokens(r) !== r);
28
+ // `p1` and `Feature` mean the same as `P1` and `feature`.
29
+ const normPriority = (v) => (v == null ? null : String(v).toUpperCase());
30
+ const normType = (v) => (v == null ? null : String(v).toLowerCase());
31
+ const NOT_PRIVATE = 'is not known to be a private repo (it is public, internal, or its visibility could not be read)';
32
+
33
+ class Refused extends Error {
34
+ constructor(message, hint = null) { super(message); this.hint = hint; }
35
+ }
36
+ const refusedOut = (json, e) => {
37
+ process.exitCode = 1;
38
+ if (json) return emitJSON({ ok: false, error: e.message, hint: e.hint });
39
+ fail(e.message); if (e.hint) hand(e.hint);
40
+ return undefined;
41
+ };
42
+
43
+ function titleOf(v) {
44
+ // The length is judged on what was written: redaction can shrink a long run to `[redacted]`.
45
+ if (String(v ?? '').trim().length > MAX_TITLE) throw new Refused(`the title is longer than ${MAX_TITLE} characters`);
46
+ const t = oneLine(v);
47
+ if (!t) throw new Refused('a title is needed', 'pass --title "<one line>"');
48
+ if (t.length > MAX_TITLE) throw new Refused(`the title is longer than ${MAX_TITLE} characters`);
49
+ return t;
50
+ }
51
+
52
+ // The body from `--body` (one line) or `--body-file` (written by the agent outside the repo). Null if neither.
53
+ // The raw body last read, so a redaction note compares what was written with what is sent.
54
+ let lastRaw = null;
55
+ function bodyOf({ body, bodyFile }) {
56
+ lastRaw = null;
57
+ if (body != null && bodyFile != null) throw new Refused('pass --body or --body-file, not both');
58
+ if (bodyFile != null) {
59
+ let raw;
60
+ try { raw = fs.readFileSync(bodyFile, 'utf8'); } catch { throw new Refused('the --body-file could not be read'); }
61
+ if (raw.length > MAX_BODY) throw new Refused(`the body is longer than ${MAX_BODY} characters`);
62
+ lastRaw = raw;
63
+ const t = lines(raw);
64
+ if (t.length > MAX_BODY) throw new Refused(`the body is longer than ${MAX_BODY} characters`);
65
+ return t;
66
+ }
67
+ if (body != null && String(body).length > MAX_BODY) throw new Refused(`the body is longer than ${MAX_BODY} characters`);
68
+ lastRaw = body ?? null;
69
+ return body != null ? lines(body) : null;
70
+ }
71
+
72
+ // The repo: the Product unless a registered one is named. `ref` resolution does the registry and login checks.
73
+ function targetOf(root, repo, { env, runner }) {
74
+ const r = resolveTarget(root, repo && repo !== 'Product' ? `${repo}#1` : '1', { env, runner });
75
+ if (!r.ok) throw new Refused(r.why, r.hint);
76
+ if (!r.t.ok) throw new Refused(`${forTerminal(r.label)}: ${r.t.why}`);
77
+ return { t: r.t, label: r.label, productConfig: r.productConfig };
78
+ }
79
+
80
+ function itemOf(root, ref, { env, runner }) {
81
+ const r = resolveTarget(root, ref, { env, runner });
82
+ if (!r.ok) throw new Refused(r.why, r.hint);
83
+ if (!r.t.ok) throw new Refused(`${forTerminal(r.label)}: ${r.t.why}`);
84
+ const item = readItem(r.t, r.number, { runner });
85
+ if (!item.ok) throw new Refused(item.why);
86
+ return { ...r, item, ref: `${r.label === 'Product' ? '' : r.label}#${r.number}` };
87
+ }
88
+
89
+ // The login to assign: a name the engineer gave, or their own (`--me`).
90
+ function loginOf(root, t, { assignee, me, env, runner }) {
91
+ if (me) {
92
+ const l = platformLogin(root, t.platform, { host: t.host, runner, env });
93
+ if (!l) throw new Refused('your login on this platform could not be read', 'pass the login instead of --me');
94
+ return l;
95
+ }
96
+ if (!LOGIN.test(String(assignee ?? ''))) throw new Refused(`"${forTerminal(String(assignee ?? ''))}" is not a login`);
97
+ return assignee;
98
+ }
99
+
100
+ // GitLab assigns by user id. Exactly one user must have the login.
101
+ function gitlabUserId(t, login, runner) {
102
+ const res = api(runner, 'glab', t.host, `users?username=${encodeURIComponent(login)}`);
103
+ if (!res.ok || !Array.isArray(res.body)) throw new Refused(`the user ${forTerminal(login)} could not be looked up on ${t.host}`);
104
+ if (res.body.length !== 1 || !Number.isInteger(res.body[0]?.id)) throw new Refused(`${t.host} has no user ${forTerminal(login)}`);
105
+ return res.body[0].id;
106
+ }
107
+
108
+ const why = (t, r) => (httpStatus(r) ? `${t.host} answered HTTP ${httpStatus(r)}` : forTerminal(String(r.stderr || 'the platform refused it')).replace(/\s+/g, ' ').slice(0, 200));
109
+
110
+ function report(out, json) {
111
+ if (out.dropped.length) { out.ok = false; process.exitCode = 1; }
112
+ if (json) return out;
113
+ if (out.changed.length) log(` ${c.bold(forTerminal(out.ref))} ${out.changed.map(forTerminal).join('; ')}${out.url ? ` ${out.url}` : ''}`);
114
+ for (const n of out.notes) info(n);
115
+ for (const d of out.dropped) warn(`not as asked: ${forTerminal(d)}`);
116
+ return undefined;
117
+ }
118
+ const answer = (ref, url) => ({ ok: true, ref, url: url ?? null, changed: [], dropped: [], notes: [] });
119
+
120
+ // ---- yad issues new --------------------------------------------------------------------------------
121
+
122
+ export async function runIssuesNew(root, { title, body = null, bodyFile = null, type: rawType = null, priority: rawPriority = null, assignee = null, me = false, repo = null, json = false, env = process.env, runner = run } = {}) {
123
+ const type = normType(rawType);
124
+ const priority = normPriority(rawPriority);
125
+ try {
126
+ const t0 = titleOf(title);
127
+ const text = bodyOf({ body, bodyFile }) ?? '';
128
+ if (type !== null && !ITEM_TYPES.includes(type)) throw new Refused(`unknown --type ${forTerminal(String(type))}`, `use one of ${ITEM_TYPES.join(', ')}`);
129
+ if (priority !== null && !PRIORITIES.includes(priority)) throw new Refused(`unknown --priority ${forTerminal(String(priority))}`, `use one of ${PRIORITIES.join(', ')}`);
130
+ if (assignee !== null && me) throw new Refused('pass --assignee or --me, not both');
131
+ const { t, label, productConfig } = targetOf(root, repo, { env, runner });
132
+ const rules = labelRules(productConfig);
133
+ // A vulnerability written in the open announces it before it is fixed.
134
+ let confidential = false;
135
+ if (type === 'security') {
136
+ if (t.platform === 'gitlab') confidential = true;
137
+ else if (routeFor('security', 'github', repoFacts(t, runner).vis) !== 'issue') {
138
+ throw new Refused(`${forTerminal(label)} ${NOT_PRIVATE}, so a security item there could be public`, 'open a private security advisory on GitHub instead, or file it in a private repo');
139
+ }
140
+ }
141
+ const login = assignee !== null || me ? loginOf(root, t, { assignee, me, env, runner }) : null;
142
+ const who = login && t.platform === 'gitlab' ? gitlabUserId(t, login, runner) : login;
143
+ const labels = [...(type ? [rules.type[type][0]] : []), ...(priority ? [rules.priority[priority][0]] : [])];
144
+ if (t.platform === 'gitlab' && labels.some((l) => l.includes(','))) throw new Refused('a GitLab label name with a comma cannot be sent', 'rename that label in the issues settings of .sdlc/product.json');
145
+ const r = newItem(t, { title: t0, body: text, labels, assignee: who, confidential }, { runner });
146
+ if (!r.ok) throw new Refused(`the item was not created: ${why(t, r)}`);
147
+ let b = {};
148
+ try { b = JSON.parse(r.stdout); } catch { /* checked below */ }
149
+ const number = t.platform === 'github' ? b.number : b.iid;
150
+ const out = answer(`${label === 'Product' ? '' : label}#${number ?? '?'}`, b.html_url ?? b.web_url);
151
+ out.changed.push(`opened in ${label}${labels.length ? ` with ${labels.join(', ')}` : ''}${login ? `, assigned to ${login}` : ''}`);
152
+ const got = (Array.isArray(b.labels) ? b.labels : []).map((l) => String(typeof l === 'string' ? l : l?.name).toLowerCase());
153
+ for (const l of labels) if (!got.includes(l.toLowerCase())) out.dropped.push(`the label ${l} was not set`);
154
+ const logins = (Array.isArray(b.assignees) ? b.assignees : []).map((a) => String(a?.login ?? a?.username ?? '').toLowerCase());
155
+ if (login && !logins.includes(login.toLowerCase())) out.dropped.push(`${login} was not assigned`);
156
+ if (confidential && b.confidential !== true) out.dropped.push('it was NOT made confidential: restrict it now');
157
+ if (!Number.isInteger(number)) out.dropped.push('the answer named no item number');
158
+ if (tokenIn(title, lastRaw)) out.notes.push(REDACTED_NOTE);
159
+ return report(out, json);
160
+ } catch (e) {
161
+ if (e instanceof Refused) return refusedOut(json, e);
162
+ throw e;
163
+ }
164
+ }
165
+
166
+ // ---- changing an item ------------------------------------------------------------------------------
167
+
168
+ // Read, write, read again: what the platform shows afterwards is what is reported.
169
+ async function act(root, ref, { json, env, runner }, fn) {
170
+ try {
171
+ const got = itemOf(root, ref, { env, runner });
172
+ const out = answer(got.ref, got.item.url);
173
+ const r = await fn(got, out);
174
+ if (r && !r.ok) throw new Refused(`nothing was changed: ${why(got.t, r)}`);
175
+ return report(out, json);
176
+ } catch (e) {
177
+ if (e instanceof Refused) return refusedOut(json, e);
178
+ throw e;
179
+ }
180
+ }
181
+
182
+ const reread = (got, runner) => { const r = readItem(got.t, got.number, { runner }); return r.ok ? r : null; };
183
+
184
+ export async function runIssuesAssign(root, { ref, assignee = null, me = false, none = false, json = false, env = process.env, runner = run } = {}) {
185
+ return act(root, ref, { json, env, runner }, async (got, out) => {
186
+ if ([assignee !== null, me, none].filter(Boolean).length !== 1) throw new Refused('name one: a login, --me or --none');
187
+ const login = none ? null : loginOf(root, got.t, { assignee, me, env, runner });
188
+ const who = login && got.t.platform === 'gitlab' ? gitlabUserId(got.t, login, runner) : login;
189
+ const r = setAssignee(got.t, got.number, who, { current: got.item.logins, runner });
190
+ if (!r.ok) return r;
191
+ const before = got.item.logins.filter((l) => !login || l.toLowerCase() !== login.toLowerCase());
192
+ out.changed.push(login ? `assigned to ${login}${before.length ? ` (replacing ${before.join(', ')})` : ''}` : `unassigned${before.length ? ` ${before.join(', ')}` : ''}`);
193
+ const after = reread(got, runner);
194
+ if (!after) out.notes.push('the item could not be read again to check the change');
195
+ else if (login ? !after.logins.map((l) => l.toLowerCase()).includes(login.toLowerCase()) : after.logins.length) out.dropped.push(login ? `${login} was not assigned` : 'someone is still assigned');
196
+ return null;
197
+ });
198
+ }
199
+
200
+ export async function runIssuesLabel(root, { ref, priority: rawPriority = null, type: rawType = null, json = false, env = process.env, runner = run } = {}) {
201
+ const priority = normPriority(rawPriority);
202
+ const type = normType(rawType);
203
+ return act(root, ref, { json, env, runner }, async (got, out) => {
204
+ if (priority === null && type === null) throw new Refused('pass --priority, --type or both');
205
+ if (priority !== null && !PRIORITIES.includes(priority)) throw new Refused(`unknown --priority ${forTerminal(String(priority))}`, `use one of ${PRIORITIES.join(', ')}`);
206
+ if (type !== null && !ITEM_TYPES.includes(type)) throw new Refused(`unknown --type ${forTerminal(String(type))}`, `use one of ${ITEM_TYPES.join(', ')}`);
207
+ if (type === 'security' && got.t.platform === 'github' && !got.item.confidential && routeFor('security', 'github', repoFacts(got.t, runner).vis) !== 'issue') {
208
+ throw new Refused(`this repo ${NOT_PRIVATE}, so a security label could mark a public item as a vulnerability`, 'move the report to a private security advisory instead');
209
+ }
210
+ // A confidential item's labels are not read, so the old ones could not be removed.
211
+ if (got.item.confidential) throw new Refused('a confidential item\'s labels are not read, so they cannot be replaced here', 'change them on GitLab');
212
+ const rules = labelRules(got.productConfig);
213
+ const have = new Set(got.item.labels.map((l) => l.toLowerCase()));
214
+ const add = [];
215
+ const remove = [];
216
+ for (const [kind, value] of [['priority', priority], ['type', type]]) {
217
+ if (value === null) continue;
218
+ const want = rules[kind][value][0];
219
+ if (!rules[kind][value].some((l) => have.has(l.toLowerCase()))) add.push(want);
220
+ for (const [other, names] of Object.entries(rules[kind])) if (other !== value) remove.push(...names.filter((l) => have.has(l.toLowerCase())));
221
+ }
222
+ const realNames = new Map(got.item.labels.map((l) => [l.toLowerCase(), l]));
223
+ const stale = remove.map((l) => realNames.get(l.toLowerCase()) ?? l);
224
+ if (got.t.platform === 'gitlab' && [...add, ...stale].some((l) => l.includes(','))) throw new Refused('a GitLab label name with a comma cannot be sent', 'rename that label in the issues settings of .sdlc/product.json');
225
+ // On GitLab a vulnerability is confidential first, so the label is never on a public item. This runs even when
226
+ // the label is already there: a public item that carries it is exactly what must not stay.
227
+ let madeConfidential = false;
228
+ if (type === 'security' && got.t.platform === 'gitlab') {
229
+ const r = makeConfidential(got.t, got.number, { runner });
230
+ if (!r.ok) return r;
231
+ const after = reread(got, runner);
232
+ if (!after || !after.confidential) throw new Refused('the item could not be made confidential, so it was not marked as a vulnerability', 'make it confidential on GitLab first');
233
+ out.changed.push('made confidential');
234
+ madeConfidential = true;
235
+ }
236
+ if (!add.length && !stale.length) { out.notes.push('it already has those labels'); return null; }
237
+ if (add.length) {
238
+ const r = addItemLabels(got.t, got.number, add, { runner });
239
+ if (!r.ok && !madeConfidential) return r;
240
+ if (r.ok) out.changed.push(`labels +${add.join(', +')}`); else out.dropped.push(`the labels ${add.join(', ')} were not set`);
241
+ }
242
+ if (stale.length) { const r = removeItemLabels(got.t, got.number, stale, { runner }); if (r.ok) out.changed.push(`labels -${stale.join(', -')}`); else out.dropped.push(`the old labels ${stale.join(', ')} were not removed`); }
243
+ // A confidential item's labels are not read back, so they cannot be checked.
244
+ const after = madeConfidential ? null : reread(got, runner);
245
+ if (madeConfidential) out.notes.push('it is confidential now, so its labels could not be read back to check');
246
+ else if (!after) out.notes.push('the item could not be read again to check the change');
247
+ else {
248
+ const now = new Set(after.labels.map((l) => l.toLowerCase()));
249
+ for (const l of add) if (!now.has(l.toLowerCase())) out.dropped.push(`the label ${l} was not set`);
250
+ }
251
+ return null;
252
+ });
253
+ }
254
+
255
+ export async function runIssuesEdit(root, { ref, title = null, body = null, bodyFile = null, json = false, env = process.env, runner = run } = {}) {
256
+ return act(root, ref, { json, env, runner }, async (got, out) => {
257
+ const fields = {};
258
+ if (title !== null) fields.title = titleOf(title);
259
+ const text = bodyOf({ body, bodyFile });
260
+ if (text !== null) fields.body = text;
261
+ if (!Object.keys(fields).length) throw new Refused('pass --title, --body or --body-file');
262
+ const r = editItem(got.t, got.number, fields, { runner });
263
+ if (!r.ok) return r;
264
+ out.changed.push(`edited the ${Object.keys(fields).join(' and ')}`);
265
+ if (tokenIn(title, lastRaw)) out.notes.push(REDACTED_NOTE);
266
+ if (fields.title && !got.item.confidential) {
267
+ const after = reread(got, runner);
268
+ if (after && after.title !== fields.title) out.dropped.push('the title is not the one sent');
269
+ }
270
+ return null;
271
+ });
272
+ }
273
+
274
+ export async function runIssuesComment(root, { ref, body = null, bodyFile = null, json = false, env = process.env, runner = run } = {}) {
275
+ return act(root, ref, { json, env, runner }, async (got, out) => {
276
+ const text = bodyOf({ body, bodyFile });
277
+ if (!text || !text.trim()) throw new Refused('the comment is empty', 'pass --body "<text>" or --body-file <file>');
278
+ const r = commentOnItem(got.t, got.number, text, { runner });
279
+ if (!r.ok) return r;
280
+ out.changed.push('commented');
281
+ if (tokenIn(lastRaw)) out.notes.push(REDACTED_NOTE);
282
+ return null;
283
+ });
284
+ }
285
+
286
+ // The epics an item is linked to, for the note a close or reopen adds.
287
+ function linkedEpics(root, got) {
288
+ try { return allLinks(root).byItem.get(itemKey({ host: got.t.host, repo: got.t.repo, number: got.number })) ?? []; } catch { return []; }
289
+ }
290
+
291
+ export async function runIssuesClose(root, { ref, json = false, env = process.env, runner = run } = {}) {
292
+ return act(root, ref, { json, env, runner }, async (got, out) => {
293
+ if (got.item.state === 'closed') { out.notes.push('it is already closed'); return null; }
294
+ const r = closeItem(got.t, got.number, { runner });
295
+ if (!r.ok) return r;
296
+ out.changed.push('closed');
297
+ const epics = linkedEpics(root, got);
298
+ if (epics.length) out.notes.push(`it is linked to ${epics.join(', ')}; its status shows done from now on`);
299
+ const after = reread(got, runner);
300
+ if (after && after.state !== 'closed') out.dropped.push('it is still open');
301
+ return null;
302
+ });
303
+ }
304
+
305
+ export async function runIssuesReopen(root, { ref, json = false, env = process.env, runner = run } = {}) {
306
+ return act(root, ref, { json, env, runner }, async (got, out) => {
307
+ if (got.item.state === 'open') { out.notes.push('it is already open'); return null; }
308
+ const r = reopenItem(got.t, got.number, { runner });
309
+ if (!r.ok) return r;
310
+ out.changed.push('reopened');
311
+ if (linkedEpics(root, got).length) out.notes.push('`yad issues sync` will not close it again: a reopened item is the team\'s call');
312
+ const after = reread(got, runner);
313
+ if (after && after.state !== 'open') out.dropped.push('it is still closed');
314
+ return null;
315
+ });
316
+ }
317
+
318
+ const ACT_FLAGS = {
319
+ new: ['--title', '--body', '--body-file', '--type', '--priority', '--assignee', '--me', '--repo'],
320
+ assign: ['--me', '--none'],
321
+ label: ['--priority', '--type'],
322
+ edit: ['--title', '--body', '--body-file'],
323
+ comment: ['--body', '--body-file'],
324
+ close: [], reopen: [],
325
+ };
326
+ export const ACT_ACTIONS = Object.keys(ACT_FLAGS);
327
+ export const actForeignFlags = (argv, action) => argv.filter((a) => a.startsWith('-') && ![...ACT_FLAGS[action], '--json', '--dir'].includes(a.split('=')[0]));