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.
Files changed (93) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +4 -3
  3. package/bin/commands.mjs +6 -0
  4. package/bin/yad.mjs +101 -6
  5. package/cli/agent-guard.mjs +793 -65
  6. package/cli/agent-rules.mjs +33 -5
  7. package/cli/argv-flags.mjs +1 -1
  8. package/cli/ci-check.mjs +45 -1
  9. package/cli/codeowners-command.mjs +72 -6
  10. package/cli/commit.mjs +17 -3
  11. package/cli/docs.mjs +2 -0
  12. package/cli/doctor.mjs +71 -12
  13. package/cli/epic-state.mjs +94 -4
  14. package/cli/epic.mjs +11 -7
  15. package/cli/fold.mjs +31 -6
  16. package/cli/guide.mjs +3 -1
  17. package/cli/hook.mjs +50 -7
  18. package/cli/issue-links.mjs +61 -0
  19. package/cli/issues-act.mjs +327 -0
  20. package/cli/issues-write.mjs +428 -0
  21. package/cli/issues.mjs +474 -0
  22. package/cli/lifecycle.mjs +7 -0
  23. package/cli/manifest.mjs +9 -3
  24. package/cli/openpr.mjs +24 -4
  25. package/cli/plan.mjs +2 -0
  26. package/cli/platform.mjs +157 -2
  27. package/cli/protection.mjs +21 -3
  28. package/cli/reconcile.mjs +1 -1
  29. package/cli/run-checks.mjs +10 -2
  30. package/cli/scan.mjs +314 -0
  31. package/cli/setup.mjs +12 -3
  32. package/cli/standup.mjs +33 -7
  33. package/cli/story-frames.mjs +17 -6
  34. package/cli/test-agents-file.mjs +378 -11
  35. package/cli/test-build.mjs +25 -0
  36. package/cli/test-ci-check.mjs +469 -10
  37. package/cli/test-guide.mjs +7 -0
  38. package/cli/test-node.mjs +15 -0
  39. package/cli/test-run-checks.mjs +17 -0
  40. package/cli/test-setup-agent.mjs +14 -0
  41. package/cli/test-story-frames.mjs +74 -4
  42. package/cli/toolbox-connect.mjs +244 -0
  43. package/cli/toolbox.mjs +129 -9
  44. package/package.json +7 -3
  45. package/skills/sdlc/config.yaml +1 -1
  46. package/skills/sdlc/module-help.csv +3 -1
  47. package/skills/yad-analysis/SKILL.md +4 -0
  48. package/skills/yad-backfill/SKILL.md +4 -0
  49. package/skills/yad-change/SKILL.md +4 -0
  50. package/skills/yad-checks/SKILL.md +13 -7
  51. package/skills/yad-checks/references/check-gates.md +62 -30
  52. package/skills/yad-checks/templates/checks/member-check.mjs +3 -2
  53. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  54. package/skills/yad-checks/templates/checks/verified-commits.sh +3 -3
  55. package/skills/yad-checks/templates/github/yad-checks.yml +357 -69
  56. package/skills/yad-checks/templates/github/yad-pr-text.yml +118 -0
  57. package/skills/yad-checks/templates/github/yad-product-checks.yml +130 -54
  58. package/skills/yad-checks/templates/github/yad-product-pr-text.yml +131 -0
  59. package/skills/yad-checks/templates/github/yad-update-guard.yml +2 -1
  60. package/skills/yad-checks/templates/github/yad-verified-commits.yml +49 -3
  61. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +79 -20
  62. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +59 -9
  63. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +1 -0
  64. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +49 -1
  65. package/skills/yad-checks/templates/hooks/agent-guard.mjs +44 -10
  66. package/skills/yad-checks/templates/hooks/ledger-guard-cursor.mjs +12 -6
  67. package/skills/yad-commit/SKILL.md +3 -1
  68. package/skills/yad-connect-design/SKILL.md +42 -10
  69. package/skills/yad-connect-design/references/design-context.md +35 -5
  70. package/skills/yad-connect-design/references/design-registry.md +3 -3
  71. package/skills/yad-connect-learning/SKILL.md +12 -2
  72. package/skills/yad-connect-repos/SKILL.md +4 -0
  73. package/skills/yad-connect-testing/SKILL.md +22 -5
  74. package/skills/yad-connect-testing/references/testing-context.md +1 -1
  75. package/skills/yad-epic/SKILL.md +4 -0
  76. package/skills/yad-epic/references/state-schema.md +15 -0
  77. package/skills/yad-guide/SKILL.md +8 -4
  78. package/skills/yad-implement/SKILL.md +56 -4
  79. package/skills/yad-implement/references/implement-conventions.md +2 -1
  80. package/skills/yad-issues/SKILL.md +53 -0
  81. package/skills/yad-learn/SKILL.md +4 -0
  82. package/skills/yad-open-pr/SKILL.md +6 -0
  83. package/skills/yad-pr-template/SKILL.md +2 -1
  84. package/skills/yad-pr-template/templates/checks/pr-title.sh +34 -2
  85. package/skills/yad-product-bridge/references/bridge.md +28 -0
  86. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +25 -11
  87. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +38 -14
  88. package/skills/yad-run/SKILL.md +5 -0
  89. package/skills/yad-scan/SKILL.md +51 -0
  90. package/skills/yad-spec/SKILL.md +13 -2
  91. package/skills/yad-test-cases/SKILL.md +18 -2
  92. package/skills/yad-ui/SKILL.md +43 -8
  93. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +0 -49
package/cli/platform.mjs CHANGED
@@ -76,14 +76,14 @@ export function platformLogin(cwd, platform, { runner = run, env = process.env,
76
76
  const ghHost = platform === 'github'
77
77
  ? (host || hostFromGitUrl(runner('git', ['remote', 'get-url', 'origin'], { cwd }).stdout) || null)
78
78
  : null;
79
- const key = `${platform}\0${cwd}\0${ghHost || ''}`;
79
+ const key = `${platform}\0${cwd}\0${ghHost || host || ''}`;
80
80
  if (runner === run && loginCache.has(key)) return loginCache.get(key);
81
81
  let login = null;
82
82
  if (platform === 'github') {
83
83
  const r = runner('gh', ['api', ...(ghHost ? ['--hostname', ghHost] : []), 'user', '--jq', '.login'], { cwd, timeout: 10000 });
84
84
  if (r.ok) login = r.stdout.trim();
85
85
  } else {
86
- const r = runner('glab', ['api', 'user'], { cwd, timeout: 10000 });
86
+ const r = runner('glab', ['api', ...(host ? ['--hostname', host] : []), 'user'], { cwd, timeout: 10000 });
87
87
  if (r.ok) { try { login = String(JSON.parse(r.stdout).username || ''); } catch { /* not JSON — no login */ } }
88
88
  }
89
89
  if (!login || !LOGIN_RE.test(login)) login = null;
@@ -472,6 +472,72 @@ export function resolveBaseBranch(platform, {
472
472
  return { base: 'main', source: 'fallback', platformDefault };
473
473
  }
474
474
 
475
+ // The branch a task branch was really cut from, when it is not the base (#450). A branch cut from an
476
+ // integration branch (`develop`) and opened with no --base gets the platform default (`main`), and then
477
+ // `origin/main..HEAD` holds commits `develop` has that `main` lacks: other tasks' commits, read as this PR's
478
+ // tasks, its Spec path, its size. So, for each remote branch: the commits of `origin/<base>..<fork point>`
479
+ // (the fork point = merge-base of that branch and HEAD) are in the PR's range and came from that branch; the
480
+ // ones whose `Task:` line names ANOTHER task are the ones that matter. A commit with no `Task:` line, or with
481
+ // this task's own id, is not counted (a teammate's copy cut from this branch, when it was cut from the base,
482
+ // holds only those, and is never named).
483
+ // Git cannot always tell the integration branch from a teammate's copy of this branch, or from a release
484
+ // branch cut from develop earlier (reviews 2 and 3): every branch with any such commit is returned, newest
485
+ // fork point first (fewest commits from it to HEAD), ties by name, and the person picks — never one guess.
486
+ // Returns { branch, foreign, others }, { skipped: n } past FORK_REF_CAP remote branches, or null — none, or
487
+ // git could not tell. Left out up front: origin/HEAD, the base, the task branch's own pushed copy,
488
+ // task-shaped names (a branch cut FROM this one), and every branch that already holds HEAD.
489
+ export const FORK_REF_CAP = 200;
490
+ const TASK_SHAPED = /-S\d+-T\d+(?:-|$)/i;
491
+ const TASK_ID = /^EP-[a-z0-9-]+-S\d+-T\d+$/i;
492
+ // The task a branch carries, wherever its id sits in the name (`feat/team/EP-x-S01-T02-word`).
493
+ export function branchTaskId(branch = '') {
494
+ const m = String(branch).match(/(?:^|[/_-])(EP-[a-z0-9-]+?-S\d+-T\d+)(?=-|$)/i);
495
+ return m ? m[1] : null;
496
+ }
497
+ export function forkBranch(cwd, { base, head, runner = run } = {}) {
498
+ const g = (args) => runner('git', args, { cwd });
499
+ const baseRef = `origin/${base}`;
500
+ if (!g(['rev-parse', '--verify', '--quiet', `${baseRef}^{commit}`]).ok) return null;
501
+ // The full name, never `refname:short`: a short name can come out as `remotes/origin/x` when ambiguous.
502
+ const refs = g(['for-each-ref', '--format=%(refname)', '--no-contains', 'HEAD', 'refs/remotes/origin/']);
503
+ if (!refs.ok) return null;
504
+ const skip = new Set(['origin/HEAD', baseRef, `origin/${head}`]);
505
+ const cands = refs.stdout.split('\n').map((r) => r.replace(/^refs\/remotes\//, ''))
506
+ .filter((r) => r.startsWith('origin/') && !skip.has(r) && !TASK_SHAPED.test(r)).sort();
507
+ if (cands.length > FORK_REF_CAP) return { skipped: cands.length };
508
+ const own = (branchTaskId(head) || '').toLowerCase();
509
+ const found = [];
510
+ for (const cand of cands) {
511
+ const mb = g(['merge-base', cand, 'HEAD']);
512
+ if (!mb.ok || !mb.stdout) continue;
513
+ const log = g(['log', '--no-merges', '--format=%(trailers:key=Task,valueonly,separator=%x1e)%x00', `${baseRef}..${mb.stdout}`]);
514
+ if (!log.ok) return null;
515
+ const foreign = log.stdout.split('\0').map((x) => x.split('\x1e')[0].trim())
516
+ .filter((t) => TASK_ID.test(t) && t.toLowerCase() !== own).length;
517
+ if (!foreign) continue;
518
+ const toHead = g(['rev-list', '--count', `${mb.stdout}..HEAD`]);
519
+ if (!toHead.ok) return null;
520
+ found.push({ branch: cand.slice('origin/'.length), foreign, n: Number(toHead.stdout) });
521
+ }
522
+ if (!found.length) return null;
523
+ found.sort((x, y) => x.n - y.n || x.branch.localeCompare(y.branch));
524
+ return { branch: found[0].branch, foreign: found[0].foreign, others: found.slice(1).map((f) => f.branch) };
525
+ }
526
+
527
+ // The words both commands print for a forkBranch answer (#450): one sentence, and the two ways out.
528
+ // `yad open-pr --base` takes a branch name; `yad run checks --base` takes a ref, so it asks for origin/<name>.
529
+ export function forkBranchWords(fork, base, { ref = '', verb = 'open the PR/MR against' } = {}) {
530
+ const n = fork.foreign === 1 ? '1 commit' : `${fork.foreign} commits`;
531
+ const others = fork.others || [];
532
+ if (!others.length) {
533
+ return `this branch holds ${n} of other tasks from origin/${fork.branch} that origin/${base} does not have, so it was likely cut from origin/${fork.branch} — pass --base ${ref}${fork.branch}, or --base ${ref}${base} to ${verb} ${base} anyway`;
534
+ }
535
+ // Each name in the form this command's --base takes, so one can be copied as it is (review 4).
536
+ const all = [fork.branch, ...others].slice(0, 5).map((b) => `${ref}${b}`);
537
+ const more = others.length + 1 > 5 ? ` (and ${others.length + 1 - 5} more)` : '';
538
+ return `this branch holds commits of other tasks that origin/${base} does not have (${n} from origin/${fork.branch}), so it was cut from another branch — pass the one it was cut from as --base: ${all.join(', ')}${more}; or --base ${ref}${base} to ${verb} ${base} anyway`;
539
+ }
540
+
475
541
  // ---- create a PR/MR -----------------------------------------------------------------------------
476
542
  // `assignees` = the committer/PR-opener on GitLab (empty when `glab` cannot say who is logged in);
477
543
  // GitHub callers pass none and get `@me`, so the PR is owned by whoever pushed it;
@@ -669,3 +735,92 @@ export function issueUrl(platform, repo, { title = '', body = '', labels = [] }
669
735
  if (labels.length) q.set('labels', labels.join(','));
670
736
  return `https://github.com/${repo}/issues/new?${q.toString()}`;
671
737
  }
738
+
739
+ // ---- writes to a tracker item (E170) -----------------------------------------------------------------
740
+ // `t` is a `prTarget`: { platform, cli, host, repo }. Each returns the runner's result. `-f` sends the value as
741
+ // plain text, so a body starting with `@` is never read as a file name.
742
+ const itemAt = (t, number) => (t.platform === 'github' ? `repos/${t.repo}/issues/${number}` : `projects/${encodeURIComponent(t.repo)}/issues/${number}`);
743
+ const itemWrite = (t, method, at, fields, runner) => runner(t.cli, ['api', '--hostname', t.host, '-X', method, at, ...fields.flatMap((f) => ['-f', f])], { timeout: 30000 });
744
+
745
+ export function addItemLabels(t, number, labels, { runner = run } = {}) {
746
+ if (t.platform === 'github') return itemWrite(t, 'POST', `${itemAt(t, number)}/labels`, labels.map((l) => `labels[]=${l}`), runner);
747
+ if (labels.some((l) => l.includes(','))) return { ok: false, stderr: 'a GitLab label name with a comma cannot be sent' };
748
+ return itemWrite(t, 'PUT', itemAt(t, number), [`add_labels=${labels.join(',')}`], runner);
749
+ }
750
+
751
+ export function removeItemLabels(t, number, labels, { runner = run } = {}) {
752
+ if (t.platform === 'github') {
753
+ let last = { ok: true };
754
+ for (const l of labels) { const r = itemWrite(t, 'DELETE', `${itemAt(t, number)}/labels/${encodeURIComponent(l)}`, [], runner); if (!r.ok) last = r; }
755
+ return last;
756
+ }
757
+ if (labels.some((l) => l.includes(','))) return { ok: false, stderr: 'a GitLab label name with a comma cannot be sent' };
758
+ return itemWrite(t, 'PUT', itemAt(t, number), [`remove_labels=${labels.join(',')}`], runner);
759
+ }
760
+
761
+ export function commentOnItem(t, number, body, { runner = run } = {}) {
762
+ return itemWrite(t, 'POST', `${itemAt(t, number)}/${t.platform === 'github' ? 'comments' : 'notes'}`, [`body=${body}`], runner);
763
+ }
764
+
765
+ export function closeItem(t, number, { runner = run } = {}) {
766
+ return itemWrite(t, t.platform === 'github' ? 'PATCH' : 'PUT', itemAt(t, number), [t.platform === 'github' ? 'state=closed' : 'state_event=close'], runner);
767
+ }
768
+
769
+ // ---- filing findings (E172) --------------------------------------------------------------------------
770
+ // A number goes with `-F` so it is sent as a number. `confidential` exists on GitLab only.
771
+ export function createFinding(t, { title, body, labels, milestone = null, confidential = false }, { runner = run } = {}) {
772
+ if (t.platform === 'github') {
773
+ const fields = ['-f', `title=${title}`, '-f', `body=${body}`, ...labels.flatMap((l) => ['-f', `labels[]=${l}`]), ...(milestone !== null ? ['-F', `milestone=${milestone}`] : [])];
774
+ return runner('gh', ['api', '--hostname', t.host, '-X', 'POST', `repos/${t.repo}/issues`, ...fields], { timeout: 30000 });
775
+ }
776
+ const fields = ['-f', `title=${title}`, '-f', `description=${body}`, '-f', `labels=${labels.join(',')}`, ...(milestone !== null ? ['-F', `milestone_id=${milestone}`] : []), ...(confidential ? ['-F', 'confidential=true'] : [])];
777
+ return runner('glab', ['api', '--hostname', t.host, '-X', 'POST', `projects/${encodeURIComponent(t.repo)}/issues`, ...fields], { timeout: 30000 });
778
+ }
779
+
780
+ export function createMilestone(t, title, { runner = run } = {}) {
781
+ const at = t.platform === 'github' ? `repos/${t.repo}/milestones` : `projects/${encodeURIComponent(t.repo)}/milestones`;
782
+ return runner(t.cli, ['api', '--hostname', t.host, '-X', 'POST', at, '-f', `title=${title}`], { timeout: 30000 });
783
+ }
784
+
785
+ // A draft a person publishes or discards. GitHub needs an affected package; `other` fits an application.
786
+ export function createDraftAdvisory(t, { summary, description, severity, cwe }, { runner = run } = {}) {
787
+ return runner('gh', ['api', '--hostname', t.host, '-X', 'POST', `repos/${t.repo}/security-advisories`, '-f', `summary=${summary}`, '-f', `description=${description}`, '-f', `severity=${severity}`, '-f', `cwe_ids[]=${cwe}`, '-f', 'vulnerabilities[][package][ecosystem]=other'], { timeout: 30000 });
788
+ }
789
+
790
+ // ---- acting on an item when a person asks (E173) -------------------------------------------------------
791
+ // Each returns the runner's result. A GitLab list field cannot be sent through `glab api` (it refuses a
792
+ // bracketed field name), so GitLab takes one assignee by id.
793
+ export function newItem(t, { title, body, labels, assignee = null, confidential = false }, { runner = run } = {}) {
794
+ if (t.platform === 'github') {
795
+ const fields = ['-f', `title=${title}`, '-f', `body=${body}`, ...labels.flatMap((l) => ['-f', `labels[]=${l}`]), ...(assignee ? ['-f', `assignees[]=${assignee}`] : [])];
796
+ return runner('gh', ['api', '--hostname', t.host, '-X', 'POST', `repos/${t.repo}/issues`, ...fields], { timeout: 30000 });
797
+ }
798
+ const fields = ['-f', `title=${title}`, '-f', `description=${body}`, '-f', `labels=${labels.join(',')}`, ...(assignee ? ['-F', `assignee_id=${assignee}`] : []), ...(confidential ? ['-F', 'confidential=true'] : [])];
799
+ return runner('glab', ['api', '--hostname', t.host, '-X', 'POST', `projects/${encodeURIComponent(t.repo)}/issues`, ...fields], { timeout: 30000 });
800
+ }
801
+
802
+ // `fields` is a map of plain-text fields. GitHub's body is `body`, GitLab's `description`.
803
+ export function editItem(t, number, fields, { runner = run } = {}) {
804
+ const gh = t.platform === 'github';
805
+ return itemWrite(t, gh ? 'PATCH' : 'PUT', itemAt(t, number), Object.entries(fields).map(([k, v]) => `${k === 'body' && !gh ? 'description' : k}=${v}`), runner);
806
+ }
807
+
808
+ export function reopenItem(t, number, { runner = run } = {}) {
809
+ return itemWrite(t, t.platform === 'github' ? 'PATCH' : 'PUT', itemAt(t, number), [t.platform === 'github' ? 'state=open' : 'state_event=reopen'], runner);
810
+ }
811
+
812
+ // GitHub: PATCH with one login replaces every assignee; clearing removes the current ones by name.
813
+ // GitLab: one user id, or 0 to clear.
814
+ export function setAssignee(t, number, who, { current = [], runner = run } = {}) {
815
+ if (t.platform === 'github') {
816
+ if (who !== null) return itemWrite(t, 'PATCH', itemAt(t, number), [`assignees[]=${who}`], runner);
817
+ if (!current.length) return { ok: true, code: 0, stdout: '{}', stderr: '' };
818
+ return itemWrite(t, 'DELETE', `${itemAt(t, number)}/assignees`, current.map((l) => `assignees[]=${l}`), runner);
819
+ }
820
+ return runner('glab', ['api', '--hostname', t.host, '-X', 'PUT', itemAt(t, number), '-F', `assignee_id=${who ?? 0}`], { timeout: 30000 });
821
+ }
822
+
823
+ // GitLab only: make an item confidential before it is marked as a vulnerability.
824
+ export function makeConfidential(t, number, { runner = run } = {}) {
825
+ return runner('glab', ['api', '--hostname', t.host, '-X', 'PUT', itemAt(t, number), '-F', 'confidential=true'], { timeout: 30000 });
826
+ }
@@ -716,14 +716,15 @@ function unknownHint(r) {
716
716
  }
717
717
 
718
718
  // E160b — what `yad ci check` reads beyond protection and approvals: the rules that make yad's checks hold a
719
- // merge. Read-only, the same calls `readProtection` makes plus a few GETs, and the same trap: a failed call is
719
+ // merge. Read-only, the same calls `readProtection` makes plus a few GETs and one GraphQL query, and the same trap: a failed call is
720
720
  // never "none". `readProtection` runs first, so a repo that cannot be read (no platform, reads turned off,
721
721
  // no login…) comes back with only `protection`, and every platform row is "not known" with its reason.
722
722
  // GitHub — `rules`: the active rules on the branch (null when not read; `full` when a whole page came
723
723
  // back, which proves nothing about what is past it). `classic`: classic branch protection, the
724
724
  // string 'none' when PROVEN absent (the branch reads `protected: false`, or GitHub answers 404 with
725
725
  // exactly "Branch not protected"), or null — GitHub answers a bare 404 to anyone who is not an
726
- // admin, even on a protected branch.
726
+ // admin, even on a protected branch. `mergeQueue` (#433): 'on' / 'off' from one GraphQL query (a read),
727
+ // null when it was not answered.
727
728
  // GitLab — the project's merge settings, the protected-branch entries that match the branch (null when not
728
729
  // read), the approval settings (Premium) and the push rule (Premium; a 404 is "no push rule").
729
730
  export function readCiSettings(target, { runner: ask = run, env = process.env, authCache = new Map() } = {}) {
@@ -750,7 +751,24 @@ export function readCiSettings(target, { runner: ask = run, env = process.env, a
750
751
  if (c.ok && c.body && typeof c.body === 'object' && !Array.isArray(c.body)) classic = c.body;
751
752
  else if (c.status === 404 && c.body?.message === 'Branch not protected') classic = 'none';
752
753
  }
753
- return { protection, rules, rulesFull: !!rules && rules.length >= PAGE, classic };
754
+ // #433: a merge queue can be turned on by a ruleset or by classic branch protection, and the classic answer
755
+ // does not show it. GraphQL names the queue whatever turned it on: an object when on, null when off.
756
+ // The names go in as variables, never into the query text, and with -f, as plain strings: -F would turn
757
+ // `123` or `true` into a number or a boolean, and read a file for a value that starts with `@`.
758
+ // Anything else is not known (null).
759
+ const [owner, name] = repo.split('/');
760
+ const q = runner('gh', ['api', '--hostname', host, 'graphql',
761
+ '-f', 'query=query($owner: String!, $name: String!, $branch: String!) { repository(owner: $owner, name: $name) { mergeQueue(branch: $branch) { id } } }',
762
+ '-f', `owner=${owner}`, '-f', `branch=${branch}`, '-f', `name=${name}`], { timeout: TIMEOUT });
763
+ let mergeQueue = null;
764
+ if (q.ok) {
765
+ try {
766
+ const body = JSON.parse(q.stdout);
767
+ const repoNode = body?.data?.repository;
768
+ if (!body?.errors && repoNode && typeof repoNode === 'object' && 'mergeQueue' in repoNode) mergeQueue = repoNode.mergeQueue ? 'on' : 'off';
769
+ } catch { /* not JSON: not known */ }
770
+ }
771
+ return { protection, rules, rulesFull: !!rules && rules.length >= PAGE, classic, mergeQueue };
754
772
  }
755
773
  const at = `projects/${encodeURIComponent(repo)}`;
756
774
  const obj = (res) => (res.ok && res.body && typeof res.body === 'object' && !Array.isArray(res.body) ? res.body : null);
package/cli/reconcile.mjs CHANGED
@@ -218,7 +218,7 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
218
218
  // `product` is on disk or this run installs one — the same test `yad doctor` makes (review 2).
219
219
  const productRel = (p) => path.relative(root, p).split(path.sep).join('/');
220
220
  const installsProduct = actions.filter((a) => a.managed && a.managed.root === root
221
- && /(^|\/)yad-product-checks\.yml$/.test(productRel(a.managed.dest))
221
+ && /(^|\/)yad-product-(checks|pr-text)\.yml$/.test(productRel(a.managed.dest))
222
222
  && a.status !== 'ok' && a.status !== 'modified' && (scope === 'all' || a.status !== 'missing'))
223
223
  .map((a) => productRel(a.managed.dest));
224
224
  const passing = [...new Set([...workflowsPassingProduct(root), ...installsProduct])];
@@ -33,7 +33,7 @@ import path from 'node:path';
33
33
  import { spawn, spawnSync } from 'node:child_process';
34
34
  import { setTimeout, clearTimeout, setImmediate } from 'node:timers';
35
35
  import { c, log, info, warn, fail, hand, ok, run, exists, readJSON, refuse, inJSON, asset, contentSha } from './lib.mjs';
36
- import { detectPlatform, resolveBaseBranch } from './platform.mjs';
36
+ import { detectPlatform, forkBranch, forkBranchWords, resolveBaseBranch } from './platform.mjs';
37
37
  import { registryEntryFor } from './find-product.mjs';
38
38
  import { repoPathFromGitUrl } from './protection.mjs';
39
39
  import { rangeTasks, groupWarnings } from './build.mjs';
@@ -314,6 +314,7 @@ export async function runChecks(dir, opts = {}) {
314
314
 
315
315
  // The base: as given, else the branch `yad open-pr` would open the PR against, fetched first.
316
316
  let base = opts.base;
317
+ let chosenBase = null;
317
318
  if (!base) {
318
319
  // The Product's own default_branch counts only for the Product itself: a code repo's trunk is its own.
319
320
  const chosen = resolveBaseBranch(platform, { cwd: repoRoot, meta, productConfig: isProduct ? settings : null, probe: false });
@@ -321,6 +322,9 @@ export async function runChecks(dir, opts = {}) {
321
322
  if (!b) return refuse(`the base branch '${chosen.base}' (from ${chosen.source}) is not a branch name git accepts`, 'pass --base <ref>');
322
323
  if (opts.fetch !== false && !fetchBranch(repoRoot, b).ok) warn(`could not fetch ${b} from origin — the last fetched origin/${b} is the base`);
323
324
  base = `origin/${b}`;
325
+ // A base nobody chose may not be where this branch was cut from (#450) — `yad open-pr` stops there;
326
+ // this run only warns, as it opens nothing.
327
+ if (!['registry', 'product'].includes(chosen.source)) chosenBase = b;
324
328
  } else if (base.startsWith('-')) {
325
329
  return refuse(`--base '${base}' is not a ref`, 'pass a branch or commit, such as origin/main');
326
330
  }
@@ -328,6 +332,10 @@ export async function runChecks(dir, opts = {}) {
328
332
  return refuse(`base '${base}' is not a commit here`, 'fetch it (git fetch origin), or pass --base <ref>');
329
333
  }
330
334
  info(`${isProduct ? 'Product' : 'code repo'} ${path.basename(repoRoot)} · branch ${branchName} · base ${base}`);
335
+ if (chosenBase) {
336
+ const fork = forkBranch(repoRoot, { base: chosenBase, head: branchName });
337
+ if (fork && !fork.skipped) warn(forkBranchWords(fork, chosenBase, { ref: 'origin/', verb: 'check against' }));
338
+ }
331
339
  // A grouped PR (#350) — commits carrying several tasks — is warned about over its size limit, as
332
340
  // `yad open-pr` warns. Never a failed gate.
333
341
  if (!isProduct) {
@@ -412,7 +420,7 @@ export async function runChecks(dir, opts = {}) {
412
420
  const results = [];
413
421
  let record = null;
414
422
  try {
415
- // The changed paths, for the Product's pr-title/pr-template split, built as yad-product-checks.yml does.
423
+ // The changed paths, for the Product's pr-title/pr-template split, built as yad-product-pr-text.yml does.
416
424
  const changedFile = path.join(scratch, 'changed');
417
425
  if (isProduct) {
418
426
  const d = git(repoRoot, ['-c', 'core.quotePath=false', 'diff', '--no-renames', '--name-only', `${base}...HEAD`]);
package/cli/scan.mjs ADDED
@@ -0,0 +1,314 @@
1
+ // E172 — the findings of a scan, filed on the repo's own GitHub issues or GitLab work items. The CLI never starts an
2
+ // AI: the yad-scan skill does the judging and hands a findings file to `yad scan file`, which does everything that
3
+ // must be exact: checking the file, finding duplicates, routing security findings, labels, milestones and filing.
4
+ //
5
+ // A finding's text came from a model that read possibly hostile code, so it is untrusted. Secrets are redacted, and
6
+ // it is escaped so it cannot notify a person, link anywhere, or forge a fingerprint.
7
+ // The platform is the record of what was filed: a fingerprint in each body, so there is no file here to keep.
8
+ import fs from 'node:fs';
9
+ import { createHash } from 'node:crypto';
10
+ import { run, readJSON, forTerminal, c, log, fail, hand, info, warn, emitJSON } from './lib.mjs';
11
+ import { productConfigPath } from './manifest.mjs';
12
+ import { productIdentity } from './members.mjs';
13
+ import { prTarget } from './pr-list.mjs';
14
+ import { repoSources } from './standup.mjs';
15
+ import { api, httpStatus, shown, whyFailed } from './protection.mjs';
16
+ import { createFinding, createDraftAdvisory, createMilestone } from './platform.mjs';
17
+ import { createLabel, labelRules, mdEscape, PRIORITIES, readLabels } from './issues.mjs';
18
+
19
+ export const CATEGORIES = ['security', 'tech-debt', 'suggestion'];
20
+ export const MAX_FILED = 20;
21
+ const MAX_IN_FILE = 200;
22
+ const PAGE = 100;
23
+ const MAX_PAGES = 10;
24
+ export const FINDING_LABEL = 'yad: finding';
25
+ export const DEFAULT_MILESTONES = { security: 'yad: Security', 'tech-debt': 'yad: Technical debt', suggestion: 'yad: Suggestions' };
26
+ const CATEGORY_NAME = { security: 'Security', 'tech-debt': 'Technical debt', suggestion: 'Suggestion' };
27
+ const SEVERITY = { P0: 'critical', P1: 'high', P2: 'medium', P3: 'low' };
28
+ const MARKER = /<!-- yad-finding: ([0-9a-f]{64}) -->/g;
29
+
30
+ // ---- checking the file -------------------------------------------------------------------------------
31
+
32
+ export function badPath(p) {
33
+ if (typeof p !== 'string' || !p || p.length > 300) return true;
34
+ if (/^[/\\]|^[a-zA-Z]:|\\/.test(p) || [...p].some((ch) => ch.charCodeAt(0) < 32)) return true;
35
+ return p.split('/').some((seg) => seg === '..' || seg === '.' || seg === '');
36
+ }
37
+
38
+ const text = (v, max) => typeof v === 'string' && v.trim() !== '' && v.length <= max;
39
+
40
+ // Why one finding is refused, or null.
41
+ function problemWith(f) {
42
+ if (!f || typeof f !== 'object' || Array.isArray(f)) return 'it is not an object';
43
+ if (!CATEGORIES.includes(f.category)) return `category must be one of ${CATEGORIES.join(', ')}`;
44
+ if (!PRIORITIES.includes(f.priority)) return `priority must be one of ${PRIORITIES.join(', ')}`;
45
+ if (f.category === 'security' ? !/^CWE-\d{1,6}$/.test(f.rule ?? '') : !/^[a-z0-9][a-z0-9-]{0,63}$/.test(f.rule ?? '')) return f.category === 'security' ? 'a security rule must be a CWE number, such as CWE-79' : 'rule must be a short lower-case slug';
46
+ if (typeof f.symbol !== 'string' || f.symbol.length > 200) return 'symbol must be a string (it may be empty)';
47
+ if (badPath(f.file)) return 'file must be a path relative to the repo';
48
+ if (!Number.isInteger(f.line) || f.line < 1) return 'line must be a positive whole number';
49
+ if (!text(f.title, 200)) return 'title must be text of at most 200 characters';
50
+ if (!text(f.why, 4000)) return 'why must be text of at most 4000 characters';
51
+ if (!text(f.fix, 4000)) return 'fix must be text of at most 4000 characters';
52
+ return null;
53
+ }
54
+
55
+ // `{ findings }` or `{ error }`. One bad finding refuses the whole file: the skill wrote it, and should fix it.
56
+ export function parseFindings(raw) {
57
+ let doc;
58
+ try { doc = JSON.parse(raw); } catch { return { error: 'the findings file is not JSON' }; }
59
+ const list = Array.isArray(doc) ? doc : doc?.findings;
60
+ if (!Array.isArray(list)) return { error: 'the findings file needs a "findings" list' };
61
+ if (list.length > MAX_IN_FILE) return { error: `the findings file has more than ${MAX_IN_FILE} findings` };
62
+ const problems = list.flatMap((f, i) => { const p = problemWith(f); return p ? [`finding ${i + 1}: ${p}`] : []; });
63
+ return problems.length ? { error: problems.slice(0, 10).join('; ') } : { findings: list };
64
+ }
65
+
66
+ // Not the line: it moves. Not the title: two runs word it differently.
67
+ export const fingerprint = (f) => createHash('sha256').update(JSON.stringify([f.category, f.file, f.rule, f.symbol])).digest('hex');
68
+
69
+ // ---- making text safe to post ------------------------------------------------------------------------
70
+
71
+ const SECRET = /(gh[pousr]_[A-Za-z0-9]{10,}|github_pat_[A-Za-z0-9_]{10,}|glpat-[A-Za-z0-9_-]{10,}|AKIA[0-9A-Z]{12,}|xox[abprs]-[A-Za-z0-9-]{10,}|sk-[A-Za-z0-9_-]{16,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]+)?|-----BEGIN[^-]*-----|[A-Za-z0-9+_=-]{40,})/g;
72
+ // Text a person wrote keeps its commit hashes and long names: only tokens with a known prefix are redacted.
73
+ const PREFIXED = /(gh[pousr]_[A-Za-z0-9]{10,}|github_pat_[A-Za-z0-9_]{10,}|glpat-[A-Za-z0-9_-]{10,}|AKIA[0-9A-Z]{12,}|xox[abprs]-[A-Za-z0-9-]{10,}|sk-[A-Za-z0-9_-]{16,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]+)?|-----BEGIN[^-]*-----)/g;
74
+ export const redactTokens = (s) => String(s ?? '').replace(PREFIXED, '[redacted]');
75
+ export const redact = (s) => String(s ?? '').replace(SECRET, '[redacted]');
76
+ const plain = (s, max) => { const t = forTerminal(redact(s)).replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
77
+ // An invisible space after each trigger stops a mention or a reference. GitHub reads backslashes and HTML entities as
78
+ // the real character before it looks for one, so neither of those is enough (checked against its renderer).
79
+ const ZWSP = '\u200b';
80
+ const breakRefs = (t) => t.replace(/GH-(?=\d)/gi, (m) => `${m}${ZWSP}`).replace(/[%$](?=[\w"])/g, (m) => `${m}${ZWSP}`);
81
+ // A title is not Markdown, but a mention in one can still notify.
82
+ export const safeTitle = (s) => breakRefs(plain(s, 200).replace(/[@#!~&](?=\S)/g, (m) => `${m}${ZWSP}`));
83
+ // `mdEscape` stops links, images, tags and code.
84
+ // A leading `/` is broken too: at the start of a line GitLab runs it as a quick action, such as `/assign`.
85
+ export const safeMd = (s, max = 2000) => breakRefs(mdEscape(plain(s, max)).replace(/\\([@#!~&])/g, `$1${ZWSP}`)).replace(/^\//, `${ZWSP}/`);
86
+
87
+ export function findingBody(f, fp, { task = null, labelled = true } = {}) {
88
+ return [
89
+ `**Category:** ${CATEGORY_NAME[f.category]} · **Priority:** ${f.priority}${labelled ? '' : ` · **Rule:** ${safeMd(f.rule, 80)}`}`,
90
+ `**Where:** ${safeMd(f.file, 300)}, line ${f.line}${f.symbol ? ` (${safeMd(f.symbol, 200)})` : ''}`,
91
+ '', '### Why it matters', safeMd(f.why, 4000),
92
+ '', '### What to do', safeMd(f.fix, 4000),
93
+ '', `_Found by the yadflow scan${task ? ` of task ${safeMd(task, 80)}` : ''}. Check it before acting on it._`,
94
+ `<!-- yad-finding: ${fp} -->`,
95
+ ].join('\n');
96
+ }
97
+
98
+ // ---- reading what is already there -------------------------------------------------------------------
99
+
100
+ // Every fingerprint on items labelled as findings, open and closed. Null if any page failed or the limit was reached.
101
+ function filedFingerprints(t, runner) {
102
+ const gh = t.platform === 'github';
103
+ const label = encodeURIComponent(FINDING_LABEL);
104
+ const at = gh ? `repos/${t.repo}/issues?labels=${label}&state=all&per_page=${PAGE}` : `projects/${encodeURIComponent(t.repo)}/issues?labels=${label}&scope=all&per_page=${PAGE}`;
105
+ const seen = new Set();
106
+ for (let page = 1; page <= MAX_PAGES; page++) {
107
+ const res = api(runner, t.cli, t.host, `${at}&page=${page}`);
108
+ if (!res.ok || !Array.isArray(res.body)) return { why: whyFailed(res.ok ? { unreadable: true } : res, { platform: t.platform, host: t.host, what: `the findings already filed on ${shown(t.repo)}`, plural: true }) };
109
+ for (const it of res.body) for (const m of String((gh ? it?.body : it?.description) ?? '').matchAll(MARKER)) seen.add(m[1]);
110
+ if (res.body.length < PAGE) return { seen };
111
+ }
112
+ return { why: `${shown(t.repo)} has more filed findings than yad reads` };
113
+ }
114
+
115
+ // Paging here is by cursor, so a full page is treated as not fully read.
116
+ function draftAdvisories(t, runner) {
117
+ // Every state: a draft a person closed or published must not come back.
118
+ const res = api(runner, t.cli, t.host, `repos/${t.repo}/security-advisories?per_page=${PAGE}`);
119
+ if (!res.ok || !Array.isArray(res.body)) return { why: res.ok ? 'the advisories could not be understood' : `the advisories could not be read${res.status ? ` (HTTP ${res.status})` : ''}: an administrator or security manager must run this` };
120
+ if (res.body.length >= PAGE) return { why: 'there are too many advisories to read them all' };
121
+ const seen = new Set();
122
+ for (const a of res.body) for (const m of String(a?.description ?? '').matchAll(MARKER)) seen.add(m[1]);
123
+ return { seen };
124
+ }
125
+
126
+ // `vis` is public, private, internal, or null. `noPush` is true only when GitHub says so: it silently drops the labels
127
+ // and milestone of an item made without push access, and the next run could not recognise that item.
128
+ export function repoFacts(t, runner) {
129
+ const res = api(runner, t.cli, t.host, `repos/${t.repo}`);
130
+ if (!res.ok || !res.body || typeof res.body !== 'object') return { vis: null, noPush: false };
131
+ const b = res.body;
132
+ const vis = ['public', 'private', 'internal'].includes(b.visibility) ? b.visibility : (b.private === true ? 'private' : null);
133
+ return { vis, noPush: b.permissions?.push === false };
134
+ }
135
+
136
+ // What the platform really did with an item: why it is not what was asked, or null.
137
+ function droppedFrom(stdout, confidential) {
138
+ let b;
139
+ try { b = JSON.parse(stdout); } catch { return 'the answer could not be read'; }
140
+ const names = (Array.isArray(b?.labels) ? b.labels : []).map((l) => String(typeof l === 'string' ? l : l?.name).toLowerCase());
141
+ if (confidential && b?.confidential !== true) return 'it was NOT made confidential: restrict it now';
142
+ if (!names.includes(FINDING_LABEL)) return 'the platform dropped its label, so a later scan would file it again';
143
+ return null;
144
+ }
145
+
146
+ // Map(title → id), across open and closed. Null if unread. GitHub assigns by number, GitLab by id.
147
+ function readMilestones(t, runner) {
148
+ const gh = t.platform === 'github';
149
+ const at = gh ? `repos/${t.repo}/milestones?state=all&per_page=${PAGE}` : `projects/${encodeURIComponent(t.repo)}/milestones?per_page=${PAGE}`;
150
+ const map = new Map();
151
+ for (let page = 1; page <= MAX_PAGES; page++) {
152
+ const res = api(runner, t.cli, t.host, `${at}&page=${page}`);
153
+ if (!res.ok || !Array.isArray(res.body)) return null;
154
+ for (const m of res.body) { const id = gh ? m?.number : m?.id; if (typeof m?.title === 'string' && Number.isInteger(id)) map.set(m.title, id); }
155
+ if (res.body.length < PAGE) return map;
156
+ }
157
+ return null;
158
+ }
159
+
160
+ // ---- routing ------------------------------------------------------------------------------------------
161
+
162
+ // Where one finding goes: 'issue', 'confidential', 'advisory', or 'none'. Only a repo known to be private gets a
163
+ // normal issue for a security finding on GitHub: an unknown one is treated as public.
164
+ export function routeFor(category, platform, vis) {
165
+ if (category !== 'security') return 'issue';
166
+ if (platform === 'gitlab') return 'confidential';
167
+ if (vis === 'private') return 'issue';
168
+ return vis === 'public' ? 'advisory' : 'none';
169
+ }
170
+ const ROUTE_WHY = 'this repo\'s visibility could not be confirmed as private or public, so it was kept off the tracker';
171
+
172
+ function scanSettings(productConfig) {
173
+ const set = productConfig?.issues?.scan;
174
+ const titles = { ...DEFAULT_MILESTONES };
175
+ for (const k of CATEGORIES) if (typeof set?.milestones?.[k] === 'string' && set.milestones[k].trim()) titles[k] = set.milestones[k].trim();
176
+ return { enabled: set?.enabled !== false, titles };
177
+ }
178
+
179
+ function targetFor(root, productConfig, repo, { env, runner }) {
180
+ const identity = productIdentity(root, { productConfig, runner });
181
+ const notRead = [];
182
+ // The first source is the Product itself. Findings belong to a registered code repo, even one named `Product`.
183
+ const s = repoSources(root, identity, productConfig, notRead, env, { localPaths: false }).slice(1).find((x) => x.label === repo);
184
+ if (!s) return { why: notRead.length ? 'the repo list could not be read' : `no registered repo is called ${forTerminal(repo)}` };
185
+ const t = prTarget({ platform: s.platform, gitUrl: s.gitUrl }, { env, runner });
186
+ return t.ok ? { t } : { why: t.why };
187
+ }
188
+
189
+ const NO_PUSH = 'your login cannot push to this repo, so the platform would drop its labels';
190
+ const rank = (p) => PRIORITIES.indexOf(p);
191
+
192
+ // ---- the command --------------------------------------------------------------------------------------
193
+
194
+ export async function runScanFile(root, { file, repo, task = null, dryRun = false, json = false, env = process.env, runner = run } = {}) {
195
+ const refuse = (message, hint) => {
196
+ process.exitCode = 1;
197
+ if (json) return emitJSON({ ok: false, error: message, hint: hint ?? null });
198
+ fail(message); if (hint) hand(hint);
199
+ return undefined;
200
+ };
201
+ if (!fs.existsSync(productConfigPath(root))) return refuse('not a Product (no .sdlc/product.json here)', 'run it from the Product, or pass --dir');
202
+ if (!file || !repo) return refuse('usage: yad scan file <findings.json> --repo <name> [--task <id>] [--dry-run] [--json]');
203
+ if (task !== null && !/^[A-Za-z0-9._-]{1,64}$/.test(task)) return refuse('--task must be a plain task id');
204
+ let raw;
205
+ try { raw = fs.readFileSync(file, 'utf8'); } catch { return refuse('the findings file could not be read'); }
206
+ const parsed = parseFindings(raw);
207
+ if (parsed.error) return refuse(`findings refused: ${forTerminal(parsed.error)}`, 'fix the file and run it again. Nothing was filed');
208
+ const productConfig = readJSON(productConfigPath(root), null);
209
+ const settings = scanSettings(productConfig);
210
+ const skip = (why) => { if (json) return emitJSON({ ok: true, skipped: why, filed: [], duplicates: 0, notFiled: [], failed: [], notes: [], overCap: 0, dryRun }); info(`scan not filed: ${why}`); return undefined; };
211
+ if (!settings.enabled) return skip('issues.scan.enabled is false in .sdlc/product.json');
212
+ if (env.YAD_PLATFORM_READ === '0') return skip('platform reads are turned off (YAD_PLATFORM_READ=0)');
213
+ const where = targetFor(root, productConfig, repo, { env, runner });
214
+ if (!where.t) return refuse(`${forTerminal(repo)}: ${where.why}`, 'nothing was filed. The findings file can be run again');
215
+ const { t } = where;
216
+ // A read that failed is unknown, not "nothing filed yet": filing now could post every finding a second time.
217
+ const filed = filedFingerprints(t, runner);
218
+ if (!filed.seen) return refuse(`nothing was filed: ${filed.why}`, 'the findings file can be run again');
219
+
220
+ const unique = [...new Map(parsed.findings.map((f) => [fingerprint(f), f])).entries()];
221
+ const fresh = unique.filter(([fp]) => !filed.seen.has(fp));
222
+ let duplicates = unique.length - fresh.length;
223
+ const { vis, noPush } = t.platform === 'github' && fresh.length ? repoFacts(t, runner) : { vis: null, noPush: false };
224
+ const notFiled = [];
225
+ const ordered = [];
226
+ let drafts = null;
227
+ for (const [fp, f] of fresh) {
228
+ const route = routeFor(f.category, t.platform, vis);
229
+ if (route === 'none') { notFiled.push({ fingerprint: fp, category: f.category, priority: f.priority, title: plain(f.title, 200), file: f.file, line: f.line, why: ROUTE_WHY }); continue; }
230
+ if (route === 'advisory') {
231
+ drafts ??= draftAdvisories(t, runner);
232
+ if (!drafts.seen) { notFiled.push({ fingerprint: fp, category: f.category, priority: f.priority, title: plain(f.title, 200), file: f.file, line: f.line, why: drafts.why }); continue; }
233
+ if (drafts.seen.has(fp)) { duplicates++; continue; }
234
+ }
235
+ ordered.push({ fp, f, route });
236
+ }
237
+ ordered.sort((a, b) => rank(a.f.priority) - rank(b.f.priority));
238
+ const chosen = ordered.slice(0, MAX_FILED);
239
+ const overCap = ordered.length - chosen.length;
240
+ const rules = labelRules(productConfig);
241
+ const result = { ok: true, skipped: null, dryRun, filed: [], duplicates, notFiled, failed: [], notes: [], overCap };
242
+ const labelsOf = (f) => [FINDING_LABEL, rules.priority[f.priority][0], rules.type[f.category][0]];
243
+
244
+ const wantsTracker = chosen.filter((x) => x.route !== 'advisory');
245
+ if (dryRun) {
246
+ for (const { fp, f, route } of chosen) {
247
+ const row = { fingerprint: fp, category: f.category, priority: f.priority, title: plain(f.title, 200) };
248
+ if (noPush && route !== 'advisory') result.failed.push({ ...row, why: NO_PUSH });
249
+ else result.filed.push({ ...row, to: route, url: null, wouldFile: true });
250
+ }
251
+ } else {
252
+ // A finding without its label could not be recognised next time, and would be filed again: labels come first.
253
+ let labelsReady = !noPush;
254
+ if (wantsTracker.length && labelsReady) {
255
+ const have = readLabels(t, runner);
256
+ if (!have.ok) labelsReady = false;
257
+ else for (const name of new Set(wantsTracker.flatMap(({ f }) => labelsOf(f)))) {
258
+ if (have.names.has(name.toLowerCase())) continue;
259
+ if (!createLabel(t, name, name === FINDING_LABEL ? '5319e7' : '1d76db', runner).ok) labelsReady = false;
260
+ }
261
+ }
262
+ const milestones = new Map();
263
+ const existing = wantsTracker.length && labelsReady ? readMilestones(t, runner) : null;
264
+ if (wantsTracker.length && labelsReady && !existing) result.notes.push('the milestones could not be read, so these findings have none');
265
+ const milestoneFor = (category) => {
266
+ if (!existing) return null;
267
+ if (milestones.has(category)) return milestones.get(category);
268
+ const title = settings.titles[category];
269
+ let id = existing.get(title) ?? null;
270
+ if (id === null) {
271
+ const r = createMilestone(t, title, { runner });
272
+ try { id = r.ok ? (t.platform === 'github' ? JSON.parse(r.stdout).number : JSON.parse(r.stdout).id) ?? null : null; } catch { id = null; }
273
+ if (id === null) result.notes.push(`the milestone ${forTerminal(title)} could not be created`);
274
+ }
275
+ milestones.set(category, id);
276
+ return id;
277
+ };
278
+ // Once the platform has dropped something, the next item would lose the same thing.
279
+ let halted = false;
280
+ for (const { fp, f, route } of chosen) {
281
+ const title = safeTitle(f.title);
282
+ const row = { fingerprint: fp, category: f.category, priority: f.priority, title };
283
+ if (route === 'advisory') {
284
+ const r = createDraftAdvisory(t, { summary: title, description: findingBody(f, fp, { task, labelled: false }), severity: SEVERITY[f.priority], cwe: f.rule }, { runner });
285
+ if (r.ok) { let url = null; try { url = JSON.parse(r.stdout).html_url ?? null; } catch { /* filed, with no address */ } result.filed.push({ ...row, to: 'advisory', url }); }
286
+ else notFiled.push({ ...row, file: f.file, line: f.line, why: [403, 404].includes(httpStatus(r)) ? `the draft advisory was refused (HTTP ${httpStatus(r)}): an administrator or security manager must run this` : `GitHub did not accept the draft advisory${httpStatus(r) ? ` (HTTP ${httpStatus(r)})` : ''}` });
287
+ continue;
288
+ }
289
+ if (halted) { result.failed.push({ ...row, why: 'not sent: an earlier finding in this run did not come back as asked. Fix that first; running the scan again would send one more' }); continue; }
290
+ if (!labelsReady) { result.failed.push({ ...row, why: noPush ? NO_PUSH : 'the labels could not be read or created, so it would not be recognised next time' }); continue; }
291
+ const r = createFinding(t, { title, body: findingBody(f, fp, { task }), labels: labelsOf(f), milestone: milestoneFor(f.category), confidential: route === 'confidential' }, { runner });
292
+ if (r.ok) {
293
+ let url = null;
294
+ try { const b = JSON.parse(r.stdout); url = b.html_url ?? b.web_url ?? null; } catch { /* the check below says so */ }
295
+ const dropped = droppedFrom(r.stdout, route === 'confidential');
296
+ if (dropped) { halted = true; result.failed.push({ ...row, url, why: dropped }); } else result.filed.push({ ...row, to: route, url });
297
+ }
298
+ else result.failed.push({ ...row, why: httpStatus(r) ? `${t.host} answered HTTP ${httpStatus(r)}` : 'the platform refused it' });
299
+ }
300
+ }
301
+ if (result.failed.length) { process.exitCode = 1; result.ok = false; }
302
+ // The answer of a --json run: the command runner prints what is returned, once.
303
+ if (json) return result;
304
+ for (const x of result.filed) {
305
+ const line = `${x.priority} ${x.category}: ${forTerminal(x.title)} ${c.dim(`→ ${dryRun ? 'would file as ' : ''}${x.to}`)}${x.url ? ` ${x.url}` : ''}`;
306
+ if (x.priority === 'P0') warn(line); else log(` ${line}`);
307
+ }
308
+ for (const x of notFiled) warn(`NOT FILED ${x.priority} ${x.category}: ${forTerminal(x.title)} (${forTerminal(x.file)}:${x.line}): ${forTerminal(x.why)}`);
309
+ for (const x of result.failed) warn(`failed ${x.priority} ${x.category}: ${forTerminal(x.title)}: ${forTerminal(x.why)}${x.url ? ` ${x.url}` : ''}`);
310
+ for (const n of result.notes) info(n);
311
+ if (overCap) info(`${overCap} more finding(s) were left out: at most ${MAX_FILED} are filed per run, most urgent first. Run the scan again to file them`);
312
+ info(`${result.filed.length} ${dryRun ? 'would be filed' : 'filed'}, ${duplicates} already filed, ${notFiled.length} not filed`);
313
+ return undefined;
314
+ }