@bbcsoftwarefactory/cli 1.1.4 β†’ 1.2.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/dist/bbc.js CHANGED
@@ -29,6 +29,7 @@ import { sweepGithub, sweepGithubUsage } from "./sweep-github.js";
29
29
  import { sweepIssues, sweepIssuesUsage } from "./sweep-issues.js";
30
30
  import { sweep, sweepUsage } from "./sweep.js";
31
31
  import { triageQuestion, triageQuestionUsage } from "./triage-question.js";
32
+ import { validatePrArtifactCli, validatePrArtifactUsage } from "./validate-pr-artifact.js";
32
33
  import { validateSkills, validateSkillsUsage } from "./validate-skills.js";
33
34
  import { watchLive, watchLiveUsage } from "./watch-live.js";
34
35
  const usage = 'Usage: bbc <command> [arguments]\n';
@@ -52,6 +53,7 @@ async function main([command, ...args]) {
52
53
  ` ${checkIssueClaimUsage}\n` +
53
54
  ` ${triageQuestionUsage}\n` +
54
55
  ` ${auditLedgerUsage}\n` +
56
+ ` ${validatePrArtifactUsage}\n` +
55
57
  ` ${validateSkillsUsage}\n` +
56
58
  ` ${resolveContainersUsage}\n` +
57
59
  ` ${summarizeLogsUsage}\n` +
@@ -87,6 +89,8 @@ async function main([command, ...args]) {
87
89
  return triageQuestion(args);
88
90
  if (command === 'audit-ledger')
89
91
  return auditLedger(args);
92
+ if (command === 'validate-pr-artifact')
93
+ return validatePrArtifactCli(args);
90
94
  if (command === 'validate-skills')
91
95
  return validateSkills(args);
92
96
  if (command === 'resolve-containers')
@@ -5,7 +5,7 @@ license: Apache-2.0
5
5
  compatibility: Requires Node.js 22.18+ (`@bbcsoftwarefactory/cli`) and Git for `bbc classify-change-lane`, `bbc check-worktree-guard`, and `bbc check-issue-claim` (Linux, macOS and Windows).
6
6
  metadata:
7
7
  author: bbc-skill-internals
8
- version: "1.7"
8
+ version: "1.8"
9
9
  pre_hook: "bbc check-issue-claim (references/issue-claim.md) + git worktree add -b feat/<task> + bbc-delivery-ledger.json (references/worktree-isolation.md)"
10
10
  post_hook: "question-gate (bbc triage-question) + Quest-Tree HUD (references/hud-output.md)"
11
11
  ---
@@ -50,7 +50,7 @@ Use to scope a feature, investigate a fix, draft or file an issue, or implement
50
50
  2. For the canonical issue, [claim it](references/issue-claim.md) first, continue only on `claimed-by-you`, record the `claim` stage, and move the issue on the GitHub Project v2 board (`read-approved-project-board` β†’ `update-approved-project-status`) to `"Trabajando"` / `"Working"` / `"In Progress"` (or record an explicit `🟑 GAP` if the board or `project` token scope is unavailable). Before any authorized write or writer delegation, prepare and verify a dedicated linked worktree on `feat/<issue-number>-<slug>` from the remote's verified default branch, and verify it with `npx -y @bbcsoftwarefactory/cli check-worktree-guard`. Use the [isolation preflight](references/worktree-isolation.md); stop the affected work if isolation is unavailable. Start the ledger in that worktree with the worktree record, canonical `issue`, Project board status (or gap), and the stages already met. Then follow the host's ODD workflow and track large work by reference. Reuse a reproducible RED tied to the criterion and relevant baseline, or produce one before changing production code when a test is applicable. If a reported bug cannot be reproduced safely, document the gap; do not implement a speculative fix.
51
51
  3. Make the smallest scoped change, following DDD and repository conventions. Prefer `skill-clean-architecture` for guidance. Rerun the focused test and applicable existing checks on the resulting revision. If no meaningful runnable test applies, document why and verify proportionately without claiming RED/GREEN.
52
52
  4. After each implementation slice reaches GREEN, verify TypeSafe, EarlyReturn, and BigO on the slice diff before closing or committing it. Prefer `code-quality-gate` (`--working` or `--range`); equivalent evidence must cover all three checks on the same diff. If blocked, address the findings and rerun the affected tests and quality checks.
53
- 5. Commit the slice and open or update the PR through the host workflow when authorized; CI is owned by the platform team, and no companion skill covers this step. When the delivery implements a canonical GitHub issue, include `Closes #<n>` (or `Refs #<n>`) in the PR body **and** immediately go to that issue via `tool-depot` (`github-write` / `comment-approved-issue`) to comment the opened PR link (URL, branch, and head SHA) with a visual reference of the change so the issue is never left orphaned. Record the PR link, head SHA, CI results, andβ€”when an issue existsβ€”`issue`, `issue_linked: true`, and the Tool Depot record in the ledger.
53
+ 5. Draft the PR body using the lane-scaled [PR / PRD + Runbook + Risk Matrix contract](references/pr-handoff-template.md) and validate it offline with `npx -y @bbcsoftwarefactory/cli validate-pr-artifact --pr-body <file> --ledger <ledger>` (`P1`–`P3`; zero violations required). Commit the slice and open or update the PR through the host workflow when authorized; CI is owned by the platform team, and no companion skill covers this step. When the delivery implements a canonical GitHub issue, include `Closes #<n>` (or `Refs #<n>`) in the PR body **and** immediately go to that issue via `tool-depot` (`github-write` / `comment-approved-issue`) to comment the opened PR link (URL, branch, and head SHA) with a visual reference of the change so the issue is never left orphaned. Record the PR link, head SHA, CI results, andβ€”when an issue existsβ€”`issue`, `issue_linked: true`, and the Tool Depot record in the ledger.
54
54
  6. Run `greptile-review-loop` on every PR this workflow opens or updates, before the human handoff. The authorization to commit and publish that PR covers triggering its Greptile review and pushing in-scope fixes for confirmed findings to the same branch, within the loop's round budget. Require fresh Greptile evidence for the exact PR head. If Greptile is not configured, does not answer within the wait limit, or the budget ends, record the observed score (or unknown) and the open findings and continue: the gap goes to the Code Owner, it does not block the handoff.
55
55
  7. Run `workflow-auditor` on the ledger of every PR this workflow opens or updates, after the Greptile loop and before the human handoff. Return each violation to the stage that owns it and rerun the audit after the fix; do not hand off a PR with open violations. Gaps travel with the PR.
56
56
  8. Hand the PR, criteria, verification evidence, Greptile result, and audit verdict to the human Code Owner for review and merge. Requested changes return to step 3. If material operational risk remains or corrections expanded scope, prefer `risk-scout` for a read-only residual-risk assessment against the reviewed revision.
@@ -66,7 +66,7 @@ Check the active skill catalog for the named companion before relying on it. If
66
66
 
67
67
  ## Output Contract
68
68
 
69
- In **human-facing chat turns**, render the compact **Game HUD + Traffic-Light (`🟒` / `🟑` / `πŸ”΄`)** format in [hud-output.md](references/hud-output.md): short 1-line stage status, active `🌿` branch/short-SHA (keep full worktree path, base SHA, commands, and YAML in `bbc-delivery-ledger.json`, PR body, or on `"detalle"`), and at most one `🟑 BOSS GATE` decision with `[A]`/`[B]`, recommendation, and 1-line why. Keep `observation` vs. `hypothesis` vs. `verified cause` distinct, and never promote a `🟑` gap or `πŸ”΄` failure to `🟒`.
69
+ In **human-facing chat turns**, render the compact **Game HUD + Traffic-Light (`🟒` / `🟑` / `πŸ”΄`)** format in [hud-output.md](references/hud-output.md): short 1-line stage status, active `🌿` branch/short-SHA (keep full worktree path, base SHA, commands, and YAML in `bbc-delivery-ledger.json`, PR body, or on `"detalle"`), and at most one `🟑 BOSS GATE` decision with `[A]`/`[B]`, a recommendation carrying `βœ… Por quΓ©` and `⚠️ Riesgo` in one line each, and optional progress bars only for counted sets with a real denominator. Keep `observation` vs. `hypothesis` vs. `verified cause` distinct, and never promote a `🟑` gap or `πŸ”΄` failure to `🟒`.
70
70
 
71
71
  ## References
72
72
 
@@ -77,4 +77,5 @@ In **human-facing chat turns**, render the compact **Game HUD + Traffic-Light (`
77
77
  - [Search before filing an issue: reuse, reopen, or create](references/issue-dedup.md)
78
78
  - [Claim the issue before working on it: rules CL1-CL12 and C1-C4](references/issue-claim.md)
79
79
  - [Visual reference on every issue write](references/visual-reference.md)
80
+ - [PR / PRD + Runbook + Risk Matrix handoff contract](references/pr-handoff-template.md)
80
81
  - [Synthetic exercise: Sleuth report to issue and regression test](references/sleuth-regression-exercise.md)
@@ -17,6 +17,49 @@ Use this **RPG Quest-Tree HUD** for **human-facing chat updates and decisions**
17
17
  3. **Always verify first** via `question-gate` (`bbc triage-question`) before emitting a `🟑 BOSS GATE`. Never put QA, lint, or doc audits inside a decision prompt.
18
18
  4. **Match the user's language** (`es` / `en` / `pt`) and keep each line crisp and scannable.
19
19
  5. **Truthfulness stays intact:** never turn a `🟑` gap or `πŸ”΄` failure into `🟒`, and keep `observation` vs. `hypothesis` clear in 1 short phrase.
20
+ 6. **Every recommendation carries its risk** in the `βœ…` / `⚠️` pair below. Bars are optional and only for counted sets.
21
+
22
+ ## Recommendation with risk
23
+
24
+ Every `πŸ‘‰ Recomendado` says what it does, why, and what can break: three short lines at the same tree level. The question stays one line; the recommendation is the only place that carries the reasoning.
25
+
26
+ ```text
27
+ β”œβ”€β”€ πŸ‘‰ Recomendado: [A] <verb + exact object>
28
+ β”‚ β”œβ”€β”€ βœ… Por quΓ© Β· <verifiable evidence, not an opinion>
29
+ β”‚ └── ⚠️ Riesgo Β· <worst real case + whether it reverts>
30
+ ```
31
+
32
+ | Line | Must say | Must not say |
33
+ |---|---|---|
34
+ | what | `merge`, `cambiar RG4`, `postear #31` | "avanzar", "aplicar", "continuar" |
35
+ | `βœ… Por quΓ©` | `QA 12/12`, `3/40 casos`, `audit conforms` | "todo estΓ‘ bien", "parece seguro" |
36
+ | `⚠️ Riesgo` | the real worst case and its recovery (`revert` inmediato, sin vuelta) | "riesgo bajo" with no object |
37
+
38
+ - **Risk can change the recommendation.** When it is high and cannot be reverted, recommend the option that reduces exposure (`[B]`) even if it is slower, and say so in the `⚠️` line.
39
+ - **No real risk is stated explicitly:** `⚠️ Riesgo · ninguno observado: cambio de solo lectura, sin migración`. Never invent a percentage, a probability, or a "15% de daño" figure; no evidence produces them.
40
+ - A quality check, a lint, or a doc audit is never a decision. They appear as evidence in `βœ… Por quΓ©`; the gate only asks what a person must approve.
41
+
42
+ ## Progress bars (optional)
43
+
44
+ A progress bar shows how much of a counted set is done. It is optional, it never replaces the count, and it never appears without one.
45
+
46
+ Ten cells, one line, the count always beside the bar:
47
+
48
+ ```text
49
+ β”œβ”€β”€ πŸ§ͺ QA Β·Β·Β·Β·Β·Β·Β·Β·Β· β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ 12/12 Β· 🟒
50
+ β”œβ”€β”€ πŸ› οΈ Pipeline Β·Β·Β·Β· β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘ 7/10 Β· 🟑 falta visual y review
51
+ └── πŸ“‹ ACs Β·Β·Β·Β·Β·Β·Β·Β·Β· β–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ 2/8 Β· 🟑 spec abierta
52
+ ```
53
+
54
+ Allowed: test results, closed pipeline stages, acceptance criteria, and evidence-source coverage in a support diagnosis. Never allowed: risk probability, confidence in a hypothesis, or any set whose total is unknown.
55
+
56
+ 1. **No denominator, no bar.** Without "out of how many", state the status in words.
57
+ 2. **A gap is never filled.** `β–‘` marks what is unknown, and the unknown is named next to the bar.
58
+ 3. **A bar never changes the light.** `β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘` under `🟑` stays `🟑`; nothing is half-green.
59
+ 4. **The bar lives in the HUD, not in the gate.** Inside `🟑 BOSS GATE` there is no bar: decision, why, risk.
60
+ 5. **No percentages.** A count is honest; `60%` invites inventing the rest.
61
+
62
+ Fallback when the terminal cannot render blocks: `[##########] 12/12`, `[#######---] 7/10`.
20
63
 
21
64
  ## Standard Quest-Tree HUD Template
22
65
 
@@ -38,8 +81,9 @@ Use this **RPG Quest-Tree HUD** for **human-facing chat updates and decisions**
38
81
  β”‚
39
82
  β”œβ”€β”€ ❓ <Single focused question?>
40
83
  β”‚
41
- β”œβ”€β”€ πŸ‘‰ Recomendado: [A]
42
- β”‚ └── <1-line reason>
84
+ β”œβ”€β”€ πŸ‘‰ Recomendado: [A] <verb + exact object>
85
+ β”‚ β”œβ”€β”€ βœ… Por quΓ© Β· <verifiable evidence>
86
+ β”‚ └── ⚠️ Riesgo Β· <worst real case + whether it reverts>
43
87
  β”‚
44
88
  └── ⚑ Opciones
45
89
  β”œβ”€β”€ [A] <fast action>
@@ -0,0 +1,97 @@
1
+ # PR / PRD + Runbook + Risk Matrix Handoff Contract
2
+
3
+ Every PR opened or updated by `delivery-coordinator` follows a lane-scaled structure enforced offline by `bbc validate-pr-artifact` (rules **`P1`–`P3`**).
4
+
5
+ `bbc classify-change-lane` is the single source of truth for required sections (`required_pr_sections`):
6
+
7
+ | Lane | Required PR sections |
8
+ |---|---|
9
+ | `trivial` | `header`, `problem`, `source_of_truth`, `solution` |
10
+ | `standard` | `header`, `problem`, `impact`, `source_of_truth`, `solution`, `risk_matrix`, `runbook_compact`, `gaps` |
11
+ | `high-risk` | `header`, `problem`, `impact`, `source_of_truth`, `solution`, `risk_matrix`, `five_scenarios`, `runbook_full`, `gaps` |
12
+
13
+ ## Required Header
14
+
15
+ Include these four fields at the top of the PR body:
16
+
17
+ ```markdown
18
+ - **lane:** trivial | standard | high-risk
19
+ - **readiness:** conforms | gaps | blocked
20
+ - **canonical_issue:** <owner/repo>#<n>
21
+ - **manual_deploy_action:** yes | no
22
+ ```
23
+
24
+ ## Template (`standard` & `high-risk`)
25
+
26
+ Both English and Spanish section headings are accepted by `bbc validate-pr-artifact`:
27
+
28
+ ```markdown
29
+ ## 1. Problem / ΒΏCuΓ‘l es el problema?
30
+ - **Observed:** ...
31
+ - **Expected:** ...
32
+
33
+ ## 2. Impact / ΒΏCΓ³mo afecta?
34
+ Who/what is affected (users, services, workflows, operational cost) and blast radius.
35
+
36
+ ## 3. Source of Truth / Origen de la verdad
37
+ At least one typed verifiable reference (`issue`, `pr`, `test_red_green`, `sanitized_log`, `visual_image`, `sanitized_message`). Never fabricate evidence or include secrets/PII.
38
+ | Type | Reference | What it proves |
39
+ |---|---|---|
40
+ | issue | owner/repo#123 | Approved scope and acceptance criteria |
41
+ | test_red_green | `node --test ...` | Failed RED before fix, passed GREEN after |
42
+ | visual_image | ![Visual](https://...) | Sanitized diagram or screenshot (`V1`) |
43
+
44
+ ## 4. Solution / SoluciΓ³n
45
+ Scoped architectural change, key files/layers touched, and what is explicitly out of scope.
46
+
47
+ ## 5. Risk Matrix / Matriz de riesgos
48
+ Traffic-light rules (`P3`):
49
+ - `Unknown` / `Unrated` likelihood or impact MUST NEVER be marked `🟒`.
50
+ - Any unmitigated `πŸ”΄` (missing concrete mitigation or evidence) blocks handoff.
51
+ - Header `readiness` cannot be `conforms` (`🟒`) when any `🟑` or `πŸ”΄` risk row exists.
52
+
53
+ | Light | ID | Risk | Likelihood | Impact | Confidence | Evidence | Mitigation | Early signal |
54
+ |---|---|---|---|---|---|---|---|---|
55
+ | 🟒 | R1 | ... | Low | Low | High | `test` | ... | ... |
56
+ | 🟑 | R2 | ... | Medium | Medium | Medium | `#123` | ... | ... |
57
+
58
+ ### Progressive Scenarios (required on `high-risk`)
59
+ 1. Happy path: ...
60
+ 2. Recoverable failure: ...
61
+ 3. Partial degradation: ...
62
+ 4. Major incident (reference risk ID): ...
63
+ 5. Cascading failure (reference risk ID): ...
64
+
65
+ ## 6. Runbook
66
+ Required on `standard` (`runbook_compact`):
67
+ - **pre_checks:** ...
68
+ - **deploy_steps:** ...
69
+ - **post_deploy_verification:** ...
70
+ - **rollback_steps:** ...
71
+
72
+ Additional fields required on `high-risk` (`runbook_full`):
73
+ - **deploy_dependencies:** ...
74
+ - **abort_signals:** ...
75
+ - **data_reversibility:** ...
76
+ - **rollback_verification:** ...
77
+ - **release_owner:** @handle
78
+
79
+ ## 7. Gaps
80
+ List every explicit `🟑 GAP` (or `None` when zero gaps remain).
81
+ ```
82
+
83
+ ## Validation Command
84
+
85
+ Validate the drafted PR body before opening or updating the PR:
86
+
87
+ ```bash
88
+ npx -y @bbcsoftwarefactory/cli validate-pr-artifact \
89
+ --pr-body pr-body.md \
90
+ --lane standard \
91
+ --ledger "$(git rev-parse --git-path bbc-delivery-ledger.json)" \
92
+ --format hud
93
+ ```
94
+
95
+ - Exit `0` (`conforms` or `gaps`): ready for PR publish / Code Owner handoff.
96
+ - Exit `1` (`violations`): fix every `P1`/`P2`/`P3` violation and re-run before handoff.
97
+ - Exit `2` (`unusable`): fix CLI arguments or unreadable input files.
@@ -5,7 +5,7 @@ license: Apache-2.0
5
5
  compatibility: Requires Node.js 22.18+ (`@bbcsoftwarefactory/cli`) and an authenticated gh CLI for `fetch-issue-attachments`; `plan-issue-triage` runs offline.
6
6
  metadata:
7
7
  author: bbc-skill-internals
8
- version: "1.3"
8
+ version: "1.4"
9
9
  pre_hook: "tool-depot (github-read / github-write / ssh)"
10
10
  post_hook: "question-gate (bbc triage-question --require-hud)"
11
11
  ---
@@ -89,8 +89,9 @@ When reviewing a bug or incident claim, validate both codebase/PR state and runt
89
89
  β”‚
90
90
  β”œβ”€β”€ ❓ ΒΏAplico este tΓ­tulo y descripciΓ³n mejorados y el triage (asignar a @<autor>, etiquetas y P<n>) en el issue #<number>? (o ΒΏcomento y cierro como falsa alarma / ya resuelto?)
91
91
  β”‚
92
- β”œβ”€β”€ πŸ‘‰ Recomendado: [A]
93
- β”‚ └── Conserva los adjuntos originales, deja al autor como responsable de confirmar y prioriza con evidencia (o documenta el descarte)
92
+ β”œβ”€β”€ πŸ‘‰ Recomendado: [A] <verbo + objeto exacto del issue>
93
+ β”‚ β”œβ”€β”€ βœ… Por quΓ© Β· <evidencia verificada: adjunto, cΓ³digo, logs>
94
+ β”‚ └── ⚠️ Riesgo Β· <peor caso real + si se puede revertir>
94
95
  β”‚
95
96
  └── ⚑ Opciones
96
97
  β”œβ”€β”€ [A] Actualizar issue #<number> en GitHub, aplicar el triage y comentarlo (o comentar/cerrar si es falsa alarma/resuelto)
@@ -5,7 +5,7 @@ license: Apache-2.0
5
5
  compatibility: Requires Node.js 22.18+ for the bundled @bbcsoftwarefactory/cli triage command.
6
6
  metadata:
7
7
  author: bbc-skill-internals
8
- version: "1.1"
8
+ version: "1.2"
9
9
  pre_hook: "AGENTS.md -> npx -y @bbcsoftwarefactory/cli triage-question --question"
10
10
  post_hook: "stop / AfterAgent / experimental.idle -> npx -y @bbcsoftwarefactory/cli triage-question --stdin --format <client>"
11
11
  post_install: "configure client stop hook JSON per references/client-hooks.md"
@@ -32,7 +32,7 @@ Run before finishing a turn with a question or pausing to ask the user what to d
32
32
  | `allow_question` | Genuine human gate only (`human_approval_required`). Present the single focused decision with your recommendation and wait for the person. |
33
33
  | `block_question` (`do_not_ask`) | Do **not** ask the blocked clause. Execute the named `resolved_by` diagram skill(s) (or proceed directly if `already_authorized`), then rerun the gate if a separate human approval still remains. |
34
34
  | `block_question` with a `needs_classification` clause | No skill or human rule recognised the clause. Route it to its owning skill, or, if a person must decide, declare the owner with a `🟑 BOSS GATE ─ <Role>` header (`PM`, `Tech Lead`, `Commit & PR`, `Code Owner`, `Release Owner`) and rerun the gate: a valid declared role turns it into `allow_question` for that role. An invented role stays blocked. |
35
- | `block_format` | Reformat the human decision or choice prompt using the Quest-Tree HUD + `🟑 BOSS GATE` (`❓`, `πŸ‘‰ Recomendado: [A]`, `⚑ Opciones` with `[A]`/`[B]`) before stopping. |
35
+ | `block_format` | Reformat the human decision or choice prompt using the Quest-Tree HUD + `🟑 BOSS GATE` (`❓`, `πŸ‘‰ Recomendado: [A]` with `βœ… Por quΓ©` and `⚠️ Riesgo`, `⚑ Opciones` with `[A]`/`[B]`) before stopping. |
36
36
  | `unusable` | Fix invalid CLI arguments or malformed ledger JSON before proceeding. |
37
37
 
38
38
  ## Execution Steps
@@ -56,7 +56,7 @@ Check the active skill catalog for the named companion before relying on it; if
56
56
  ## Output Contract
57
57
 
58
58
  - **Machine / hook mode (`triage-question`):** return `verdict`, `resolved_by`, `human_gates`, and `rewrite_suggestion` (if any) without leaking secrets, tokens, or raw logs.
59
- - **Human-facing chat mode (`allow_question`):** format the single isolated `human_approval_required` gate as a compact **Quest-Tree Boss Gate** (`🟑 BOSS GATE ─ <Role>`, `❓` 1-line question, `πŸ‘‰ Recomendado: [A]`, `⚑ Opciones: [A] / [B]`), matching the user's language for fast decisions. See [diagram-routing.md](references/diagram-routing.md#agile-decision-card).
59
+ - **Human-facing chat mode (`allow_question`):** format the single isolated `human_approval_required` gate as a compact **Quest-Tree Boss Gate** (`🟑 BOSS GATE ─ <Role>`, `❓` 1-line question, `πŸ‘‰ Recomendado: [A]` with `βœ… Por quΓ©` and `⚠️ Riesgo`, `⚑ Opciones: [A] / [B]`), matching the user's language for fast decisions. See [diagram-routing.md](references/diagram-routing.md#agile-decision-card).
60
60
 
61
61
  ## References
62
62
 
@@ -49,10 +49,13 @@ When `verdict` is `allow_question`, present the remaining `human_approval_requir
49
49
  β”‚
50
50
  β”œβ”€β”€ ❓ <1-line question?>
51
51
  β”‚
52
- β”œβ”€β”€ πŸ‘‰ Recomendado: [A]
53
- β”‚ └── <1-line reason>
52
+ β”œβ”€β”€ πŸ‘‰ Recomendado: [A] <verb + exact object>
53
+ β”‚ β”œβ”€β”€ βœ… Por quΓ© Β· <verifiable evidence>
54
+ β”‚ └── ⚠️ Riesgo Β· <worst real case + whether it reverts>
54
55
  β”‚
55
56
  └── ⚑ Opciones
56
57
  β”œβ”€β”€ [A] <action>
57
58
  └── [B] <action>
58
59
  ```
60
+
61
+ The `βœ…` / `⚠️` pair is required; the gate format check only looks for `BOSS GATE`, `Recomendado:` and `[A]`/`[B]`, so this pair is the skill's contract, not the CLI's. See [the recommendation and risk rules](../../delivery-coordinator/references/hud-output.md#recommendation-with-risk).
@@ -4,7 +4,7 @@ description: "Trigger: PRD, product requirements, SPEC, acceptance criteria. Tur
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: bbc-skill-internals
7
- version: "1.1"
7
+ version: "1.2"
8
8
  post_hook: "question-gate (open product decisions -> BOSS GATE)"
9
9
  ---
10
10
 
@@ -38,7 +38,7 @@ When asking the user to resolve an open decision (never auto-approve on their be
38
38
  - Present it as a compact **Quest-Tree Boss Gate** card matching the user's language:
39
39
  - `🟑 BOSS GATE ─ Product Manager (<OD-ID>)`
40
40
  - `β”œβ”€β”€ ❓` 1-line question
41
- - `β”œβ”€β”€ πŸ‘‰ Recomendado: [A/B]` + 1 short sentence why
41
+ - `β”œβ”€β”€ πŸ‘‰ Recomendado: [A/B] <acciΓ³n concreta>`, `βœ… Por quΓ©` (la evidencia) y `⚠️ Riesgo` (quΓ© se rompe si sale mal)
42
42
  - `└── ⚑ Opciones` (`[A]` vs `[B]`)
43
43
  - Wait for the user's confirmation before locking the criterion or proceeding.
44
44
 
@@ -37,13 +37,14 @@ Check each item against the evidence the ledger points to. Report any mismatch a
37
37
  - **Issue claim (`C1`–`C4`):** apply the [semantic checks of the claim protocol](../../delivery-coordinator/references/issue-claim.md#semantic-checks-for-the-auditor-llm): the `check` and `verify` verdicts are `bbc check-issue-claim` output for reads made in this delivery, the claimant is the authorizing person, a handover cites the holder's or Tech Lead's message, and a delivery that stopped before its PR released the claim.
38
38
  - **Issue triage (`I1`–`I2`):** the [triage](../../issue-reviewer/references/triage.md) writes match the `bbc plan-issue-triage` commands the person approved, the only assignee added is the issue author, and the later comment states the assignee, the label changes, the priority with its rationale, and any gap.
39
39
  - **Visual reference (`V1`):** every issue publish, update, or comment, including the PR back-link, embeds the image recorded in `visual`, and the image is sanitized. A stated gap (`G2`) must also appear in the issue text.
40
+ - **PR artifact, Runbook & Risk Matrix (`P1`–`P3`):** run `npx -y @bbcsoftwarefactory/cli validate-pr-artifact --pr-body <file> --ledger <ledger>` against the opened/updated PR body and verify zero violations: `P1` lane & required sections match `classify-change-lane`, `P2` typed verifiable Source of Truth + visual/`🟑 GAP` + ledger cross-check + zero secret/PII leakage, and `P3` traffic-light Risk Matrix (`Unknown`/`Unrated` never `🟒`, unmitigated `πŸ”΄` blocks, readiness coherent with worst row) plus lane-appropriate Runbook (`runbook_compact` on `standard`, `five_scenarios` + `runbook_full` on `high-risk`). See [pr-handoff-template.md](../../delivery-coordinator/references/pr-handoff-template.md).
40
41
  - **Tool use (`T1`):** if the session's tool calls are visible, every covered SSH, public web, or GitHub operation in them appears in `tool_uses`. A call that is missing is `T1`. A call made after a `denied` or `needs-approval` decision for the same target, through any tool or agent, is `T2`.
41
42
  - **Authorizations (`A1`, `A2`):** each one is traceable to a person's message or decision, and its scope covers what was done.
42
43
 
43
44
  ## 4. Hand back
44
45
 
45
46
  - `conforms` or `gaps`: return the report to `delivery-coordinator` for the Code Owner handoff. Gaps travel with the PR.
46
- - `violations`: return each one to the stage that owns it: `W1` and `K1` to Delivery Coordinator, `S*` and `E*` to the earliest missing or failing stage, `Q1` to `code-quality-gate`, `R1` to `greptile-review-loop`, `R2` to Delivery Coordinator (link PR back on canonical issue via Tool Depot), `V1` to the skill that wrote on the issue (`delivery-coordinator` or `issue-reviewer`), `D1` to Delivery Coordinator (search before filing), `I*` to `issue-reviewer` (triage), `C*` to Delivery Coordinator (claim the issue; a handover goes to the person who holds it), `A*`, `H*`, and `T5` to the person whose decision is missing, and other `T*` rules to the requesting skill and `tool-depot`. Rerun the audit after the fix.
47
+ - `violations`: return each one to the stage that owns it: `W1` and `K1` to Delivery Coordinator, `S*` and `E*` to the earliest missing or failing stage, `Q1` to `code-quality-gate`, `R1` to `greptile-review-loop`, `R2` to Delivery Coordinator (link PR back on canonical issue via Tool Depot), `V1` to the skill that wrote on the issue (`delivery-coordinator` or `issue-reviewer`), `P1`–`P3` to Delivery Coordinator (or `risk-scout` for `P3` high-risk scenarios/matrix), `D1` to Delivery Coordinator (search before filing), `I*` to `issue-reviewer` (triage), `C*` to Delivery Coordinator (claim the issue; a handover goes to the person who holds it), `A*`, `H*`, and `T5` to the person whose decision is missing, and other `T*` rules to the requesting skill and `tool-depot`. Rerun the audit after the fix.
47
48
  - `unusable`: report what is missing. Do not issue a verdict.
48
49
 
49
50
  A `conforms` verdict is not an approval. It does not replace Greptile, the Code Owner's review, or the Release Owner's decision, and it grants no permission.
@@ -1,24 +1,30 @@
1
+ export type PrSection = 'header' | 'problem' | 'impact' | 'source_of_truth' | 'solution' | 'risk_matrix' | 'five_scenarios' | 'runbook_compact' | 'runbook_full' | 'gaps';
1
2
  declare const plans: {
2
3
  trivial: {
3
4
  test_mode: string;
4
5
  required_stages: string[];
5
6
  skipped_stages: string[];
6
7
  extra_checks: string[];
8
+ required_pr_sections: readonly PrSection[];
7
9
  };
8
10
  standard: {
9
11
  test_mode: string;
10
12
  required_stages: string[];
11
13
  skipped_stages: string[];
12
14
  extra_checks: string[];
15
+ required_pr_sections: readonly PrSection[];
13
16
  };
14
17
  'high-risk': {
15
18
  test_mode: string;
16
19
  required_stages: string[];
17
20
  skipped_stages: never[];
18
21
  extra_checks: string[];
22
+ required_pr_sections: readonly PrSection[];
19
23
  };
20
24
  };
21
- type Lane = keyof typeof plans;
25
+ export type Lane = keyof typeof plans;
26
+ export declare function prSectionsForLane(lane: Lane): readonly PrSection[];
27
+ export declare function isLane(value: string): value is Lane;
22
28
  export interface ChangeSet {
23
29
  files: readonly string[];
24
30
  added: number;
@@ -36,6 +42,7 @@ export interface LaneReport {
36
42
  required_stages: readonly string[];
37
43
  skipped_stages: readonly string[];
38
44
  extra_checks: readonly string[];
45
+ required_pr_sections: readonly PrSection[];
39
46
  }
40
47
  export declare function classify(change: ChangeSet, windows: boolean): LaneReport;
41
48
  export {};
@@ -33,12 +33,16 @@ const plans = {
33
33
  required_stages: ['specify', 'implement', 'quality', 'docs', 'commit_pr', 'review'],
34
34
  skipped_stages: ['requirements-spec-full-prd', 'risk-scout', 'reproduce-runtime-red', 'verify-runtime-green'],
35
35
  extra_checks: ['documentation-steward', 'bbc validate-skills'],
36
+ required_pr_sections: ['header', 'problem', 'source_of_truth', 'solution'],
36
37
  },
37
38
  standard: {
38
39
  test_mode: 'tdd',
39
40
  required_stages: ['specify', 'reproduce', 'implement', 'verify', 'quality', 'commit_pr', 'review'],
40
41
  skipped_stages: ['risk-scout'],
41
42
  extra_checks: ['code-quality-gate'],
43
+ required_pr_sections: [
44
+ 'header', 'problem', 'impact', 'source_of_truth', 'solution', 'risk_matrix', 'runbook_compact', 'gaps',
45
+ ],
42
46
  },
43
47
  'high-risk': {
44
48
  test_mode: 'tdd',
@@ -47,8 +51,18 @@ const plans = {
47
51
  ],
48
52
  skipped_stages: [],
49
53
  extra_checks: ['risk-scout', 'code-quality-gate', 'human-security-review'],
54
+ required_pr_sections: [
55
+ 'header', 'problem', 'impact', 'source_of_truth', 'solution',
56
+ 'risk_matrix', 'five_scenarios', 'runbook_full', 'gaps',
57
+ ],
50
58
  },
51
59
  };
60
+ export function prSectionsForLane(lane) {
61
+ return plans[lane].required_pr_sections;
62
+ }
63
+ export function isLane(value) {
64
+ return value === 'trivial' || value === 'standard' || value === 'high-risk';
65
+ }
52
66
  function normalize(path) {
53
67
  return path.replaceAll('\\', '/');
54
68
  }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Pure offline PR/PRD + Runbook + Risk Matrix parser and validator (rules P1-P3).
4
+ * Rules: Zero I/O, single-pass section parsing, strict traffic-light and anti-leakage checks.
5
+ * BigO: O(n) score:3
6
+ * keywords: [PrArtifactValidator, RiskMatrixGuard, RunbookContract]
7
+ * GOAL: Enforce lane-scaled PR handoff structure, verifiable evidence, and safe release runbooks.
8
+ */
9
+ import { type Lane, type PrSection } from '../change-lane/classification.ts';
10
+ export type PrRule = 'P1' | 'P2' | 'P3';
11
+ export type PrVerdict = 'conforms' | 'gaps' | 'violations';
12
+ export type Readiness = 'conforms' | 'gaps' | 'blocked';
13
+ export type TrafficLight = 'green' | 'yellow' | 'red';
14
+ export interface PrFinding {
15
+ rule: PrRule;
16
+ detail: string;
17
+ }
18
+ export interface LedgerSummary {
19
+ lane?: string;
20
+ issue?: string;
21
+ stages?: readonly {
22
+ stage?: string;
23
+ status?: string;
24
+ }[];
25
+ }
26
+ export interface PrValidationInput {
27
+ markdown: string;
28
+ expectedLane?: Lane;
29
+ ledger?: LedgerSummary;
30
+ }
31
+ export interface PrValidationReport {
32
+ verdict: PrVerdict;
33
+ lane: Lane | null;
34
+ declared_lane: string | null;
35
+ readiness: Readiness | null;
36
+ required_sections: readonly PrSection[];
37
+ present_sections: readonly PrSection[];
38
+ risk_summary: {
39
+ green: number;
40
+ yellow: number;
41
+ red: number;
42
+ };
43
+ violations: readonly PrFinding[];
44
+ gaps: readonly PrFinding[];
45
+ }
46
+ export declare function validatePrArtifact(input: PrValidationInput): PrValidationReport;
@@ -0,0 +1,446 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Pure offline PR/PRD + Runbook + Risk Matrix parser and validator (rules P1-P3).
4
+ * Rules: Zero I/O, single-pass section parsing, strict traffic-light and anti-leakage checks.
5
+ * BigO: O(n) score:3
6
+ * keywords: [PrArtifactValidator, RiskMatrixGuard, RunbookContract]
7
+ * GOAL: Enforce lane-scaled PR handoff structure, verifiable evidence, and safe release runbooks.
8
+ */
9
+ import { isLane, prSectionsForLane } from "../change-lane/classification.js";
10
+ const EVIDENCE_KINDS = new Set([
11
+ 'issue',
12
+ 'pr',
13
+ 'test_red_green',
14
+ 'sanitized_log',
15
+ 'visual_image',
16
+ 'sanitized_message',
17
+ ]);
18
+ const PLACEHOLDER_RE = /^(?:-|β€”|–|n\/a|na|tbd|todo|none|pending|ninguno|ninguna|por definir|\?+)$/i;
19
+ const UNKNOWN_RE = /\b(?:unknown|unrated|desconocid[oa]|sin calificar)\b/i;
20
+ const VISUAL_IMAGE_RE = /!\[[^\]]*\]\(https:\/\/[^)\s]+\)|<img\b[^>]*\bsrc=["']https:\/\/[^"'\s]+["']/i;
21
+ const VISUAL_GAP_RE = /🟑\s*GAP\b[^\n]*(?:visual|image|imagen|screenshot|captura|diagram|diagrama|V1)/i;
22
+ const REF_SIGNAL_RE = /(?:#\d+|https?:\/\/\S+|`[^`]+`|\b[0-9a-f]{7,40}\b|🟑\s*GAP)/i;
23
+ const SECRET_RULES = [
24
+ { label: 'GitHub token', pattern: /\b(?:ghp|gho|ghu|ghs)_[A-Za-z0-9]{20,}\b|\bgithub_pat_[A-Za-z0-9_]{20,}\b/ },
25
+ { label: 'API secret key', pattern: /\bsk-[A-Za-z0-9_-]{20,}\b/ },
26
+ { label: 'AWS access key', pattern: /\bAKIA[0-9A-Z]{16}\b/ },
27
+ { label: 'JWT token', pattern: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/ },
28
+ { label: 'PEM private key', pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
29
+ { label: 'Bearer authorization header', pattern: /Authorization\s*:\s*Bearer\s+[A-Za-z0-9._-]{12,}/i },
30
+ ];
31
+ const EMAIL_RE = /\b[A-Za-z0-9._%+-]+@([A-Za-z0-9.-]+\.[A-Za-z]{2,})\b/g;
32
+ const SAFE_EMAIL_DOMAINS = new Set(['example.com', 'example.invalid', 'noreply.github.com', 'users.noreply.github.com']);
33
+ const COMPACT_RUNBOOK_FIELDS = [
34
+ { key: 'pre_checks', aliases: ['pre_checks', 'pre-checks', 'prechecks', 'pre-requisitos', 'prerequisitos'] },
35
+ { key: 'deploy_steps', aliases: ['deploy_steps', 'pasos de despliegue', 'pasos', 'deploy'] },
36
+ { key: 'post_deploy_verification', aliases: ['post_deploy_verification', 'verificaciΓ³n post-deploy', 'verificacion post-deploy', 'smoke'] },
37
+ { key: 'rollback_steps', aliases: ['rollback_steps', 'rollback', 'pasos de rollback'] },
38
+ ];
39
+ const FULL_RUNBOOK_FIELDS = [
40
+ ...COMPACT_RUNBOOK_FIELDS,
41
+ { key: 'deploy_dependencies', aliases: ['deploy_dependencies', 'dependencias', 'dependencies'] },
42
+ { key: 'abort_signals', aliases: ['abort_signals', 'seΓ±ales de alerta', 'senales de alerta', 'abort'] },
43
+ { key: 'data_reversibility', aliases: ['data_reversibility', 'reversibilidad', 'reversibility'] },
44
+ { key: 'rollback_verification', aliases: ['rollback_verification', 'verificaciΓ³n de rollback', 'verificacion de rollback'] },
45
+ { key: 'release_owner', aliases: ['release_owner', 'release owner', 'responsable de release'] },
46
+ ];
47
+ function stripMarkdownFormatting(text) {
48
+ return text.replace(/[*`]/g, '').trim();
49
+ }
50
+ function classifyHeading(rawHeading) {
51
+ const h = stripMarkdownFormatting(rawHeading).toLowerCase();
52
+ if (/(?:^|\b)(?:header|cabecera|resumen ejecutivo)(?:\b|$)/.test(h))
53
+ return 'header';
54
+ if (/(?:problem|problema)/.test(h))
55
+ return 'problem';
56
+ if (/(?:impact|impacto|afecta)/.test(h))
57
+ return 'impact';
58
+ if (/(?:source of truth|origen de la verdad|evidencia|evidence)/.test(h))
59
+ return 'source_of_truth';
60
+ if (/(?:solution|soluciΓ³n|solucion)/.test(h))
61
+ return 'solution';
62
+ if (/(?:risk matrix|matriz de riesgo|riesgos)/.test(h))
63
+ return 'risk_matrix';
64
+ if (/(?:scenarios|escenarios|5 escenarios|five scenarios)/.test(h))
65
+ return 'five_scenarios';
66
+ if (/(?:runbook|despliegue|deploy)/.test(h))
67
+ return 'runbook_compact';
68
+ if (/(?:gaps|brechas|pendientes)/.test(h))
69
+ return 'gaps';
70
+ return null;
71
+ }
72
+ function parseSections(markdown) {
73
+ const lines = markdown.split(/\r?\n/);
74
+ const preambleLines = [];
75
+ const buckets = new Map();
76
+ let current = null;
77
+ let inFence = false;
78
+ for (const line of lines) {
79
+ if (/^\s*```/.test(line)) {
80
+ inFence = !inFence;
81
+ }
82
+ if (!inFence) {
83
+ const h2 = /^##\s+(.+)$/.exec(line);
84
+ if (h2 !== null) {
85
+ current = classifyHeading(h2[1] ?? '');
86
+ if (current !== null && !buckets.has(current))
87
+ buckets.set(current, []);
88
+ continue;
89
+ }
90
+ const h3 = /^###\s+(.+)$/.exec(line);
91
+ if (h3 !== null) {
92
+ const sub = classifyHeading(h3[1] ?? '');
93
+ if (sub === 'five_scenarios') {
94
+ current = 'five_scenarios';
95
+ if (!buckets.has(current))
96
+ buckets.set(current, []);
97
+ continue;
98
+ }
99
+ }
100
+ }
101
+ if (current === null) {
102
+ preambleLines.push(line);
103
+ }
104
+ else {
105
+ buckets.get(current)?.push(line);
106
+ }
107
+ }
108
+ const sections = new Map();
109
+ for (const [key, list] of buckets.entries()) {
110
+ sections.set(key, list.join('\n').trim());
111
+ }
112
+ return { preamble: preambleLines.join('\n').trim(), sections };
113
+ }
114
+ function parseReadiness(raw) {
115
+ const clean = stripMarkdownFormatting(raw).toLowerCase();
116
+ if (/(?:conforms|conform|ready|green|🟒)/.test(clean))
117
+ return 'conforms';
118
+ if (/(?:gaps|gap|yellow|caution|🟑)/.test(clean))
119
+ return 'gaps';
120
+ if (/(?:blocked|block|red|πŸ”΄)/.test(clean))
121
+ return 'blocked';
122
+ return null;
123
+ }
124
+ function parseKeyValues(text) {
125
+ const map = new Map();
126
+ for (const line of text.split(/\r?\n/)) {
127
+ const match = /^\s*(?:[-*]\s+)?(?:\*\*)?([A-Za-z0-9_Γ‘Γ©Γ­Γ³ΓΊΓ±ΓΓ‰ΓΓ“ΓšΓ‘ -]{2,40})(?:\*\*)?\s*:\s*(?:\*\*)?\s*(.+?)\s*$/.exec(line);
128
+ if (match === null)
129
+ continue;
130
+ const rawKey = stripMarkdownFormatting(match[1] ?? '').toLowerCase();
131
+ const value = (match[2] ?? '').replace(/^\*\*|\*\*$/g, '').trim();
132
+ if (rawKey.length > 0 && !map.has(rawKey))
133
+ map.set(rawKey, value);
134
+ }
135
+ return map;
136
+ }
137
+ function parseHeader(preamble, headerSection) {
138
+ const kv = parseKeyValues(`${preamble}\n${headerSection ?? ''}`);
139
+ const laneRaw = kv.get('lane') ?? kv.get('carril') ?? null;
140
+ const readinessRaw = kv.get('readiness') ?? kv.get('estado') ?? null;
141
+ const canonicalIssue = kv.get('canonical_issue') ?? kv.get('issue') ?? kv.get('canonical issue') ?? null;
142
+ const manualDeployAction = kv.get('manual_deploy_action') ?? kv.get('manual deploy action') ?? kv.get('acciΓ³n manual') ?? null;
143
+ return {
144
+ lane: laneRaw !== null ? stripMarkdownFormatting(laneRaw).toLowerCase() : null,
145
+ readiness: readinessRaw !== null ? parseReadiness(readinessRaw) : null,
146
+ rawReadiness: readinessRaw,
147
+ canonicalIssue: canonicalIssue !== null ? stripMarkdownFormatting(canonicalIssue) : null,
148
+ manualDeployAction: manualDeployAction !== null ? stripMarkdownFormatting(manualDeployAction).toLowerCase() : null,
149
+ };
150
+ }
151
+ function splitTableRow(line) {
152
+ const trimmed = line.trim();
153
+ if (!trimmed.startsWith('|') || !trimmed.endsWith('|'))
154
+ return null;
155
+ const cells = trimmed.slice(1, -1).split('|').map((cell) => cell.trim());
156
+ if (cells.every((cell) => /^:?-{2,}:?$/.test(cell)))
157
+ return null;
158
+ return cells;
159
+ }
160
+ function parseEvidence(sectionBody) {
161
+ const items = [];
162
+ for (const line of sectionBody.split(/\r?\n/)) {
163
+ const row = splitTableRow(line);
164
+ if (row !== null && row.length >= 2) {
165
+ const kind = stripMarkdownFormatting(row[0] ?? '').toLowerCase();
166
+ if (EVIDENCE_KINDS.has(kind)) {
167
+ const ref = (row[1] ?? '').trim();
168
+ items.push({ kind, ref, isGap: /🟑\s*GAP/i.test(line) });
169
+ continue;
170
+ }
171
+ }
172
+ const bullet = /^\s*[-*]\s+(?:\*\*)?([a-z_]+)(?:\*\*)?\s*:\s*(.+)$/i.exec(line);
173
+ if (bullet !== null) {
174
+ const kind = (bullet[1] ?? '').toLowerCase();
175
+ if (EVIDENCE_KINDS.has(kind)) {
176
+ const ref = (bullet[2] ?? '').trim();
177
+ items.push({ kind, ref, isGap: /🟑\s*GAP/i.test(line) });
178
+ }
179
+ }
180
+ }
181
+ return items;
182
+ }
183
+ function parseLight(cell) {
184
+ if (cell.includes('πŸ”΄') || /\bred\b|\brojo\b/i.test(cell))
185
+ return 'red';
186
+ if (cell.includes('🟑') || /\byellow\b|\bamarillo\b/i.test(cell))
187
+ return 'yellow';
188
+ if (cell.includes('🟒') || /\bgreen\b|\bverde\b/i.test(cell))
189
+ return 'green';
190
+ return null;
191
+ }
192
+ function findRiskId(cells) {
193
+ const c0 = stripMarkdownFormatting(cells[0] ?? '');
194
+ if (/^R\d+$/i.test(c0))
195
+ return c0.toUpperCase();
196
+ const c1 = stripMarkdownFormatting(cells[1] ?? '');
197
+ if (/^R\d+$/i.test(c1))
198
+ return c1.toUpperCase();
199
+ const c2 = stripMarkdownFormatting(cells[2] ?? '');
200
+ if (/^R\d+$/i.test(c2))
201
+ return c2.toUpperCase();
202
+ return null;
203
+ }
204
+ function parseRiskRows(sectionBody) {
205
+ const rows = [];
206
+ for (const line of sectionBody.split(/\r?\n/)) {
207
+ const cells = splitTableRow(line);
208
+ if (cells === null || cells.length < 5)
209
+ continue;
210
+ const light = parseLight(cells[0] ?? '') ?? parseLight(cells[1] ?? '');
211
+ const id = findRiskId(cells);
212
+ if (light === null || id === null)
213
+ continue;
214
+ const likelihood = cells[3] ?? '';
215
+ const impact = cells[4] ?? '';
216
+ const evidence = cells.length >= 8 ? (cells[6] ?? '') : (cells[5] ?? '');
217
+ const mitigation = cells.length >= 8 ? (cells[7] ?? '') : (cells[cells.length - 1] ?? '');
218
+ rows.push({ id, light, likelihood, impact, evidence, mitigation });
219
+ }
220
+ return rows;
221
+ }
222
+ function extractIssueNumber(raw) {
223
+ const match = /#(\d+)\b/.exec(raw);
224
+ return match === null ? null : match[1];
225
+ }
226
+ function scanSecretsAndPii(markdown, violations) {
227
+ for (const { label, pattern } of SECRET_RULES) {
228
+ if (pattern.test(markdown)) {
229
+ violations.push({ rule: 'P2', detail: `Potential secret leakage detected (${label}); sanitize PR body before publishing.` });
230
+ }
231
+ }
232
+ EMAIL_RE.lastIndex = 0;
233
+ let match = EMAIL_RE.exec(markdown);
234
+ while (match !== null) {
235
+ const domain = (match[1] ?? '').toLowerCase();
236
+ if (!SAFE_EMAIL_DOMAINS.has(domain)) {
237
+ violations.push({ rule: 'P2', detail: 'Potential personal email PII detected; replace with handle or example.invalid.' });
238
+ break;
239
+ }
240
+ match = EMAIL_RE.exec(markdown);
241
+ }
242
+ }
243
+ function resolveRunbookFieldValue(kv, aliases) {
244
+ for (const alias of aliases) {
245
+ const value = kv.get(alias);
246
+ if (value !== undefined)
247
+ return value;
248
+ }
249
+ return null;
250
+ }
251
+ function validateRunbook(runbookBody, lane, violations) {
252
+ const fields = lane === 'high-risk' ? FULL_RUNBOOK_FIELDS : COMPACT_RUNBOOK_FIELDS;
253
+ const kv = parseKeyValues(runbookBody);
254
+ for (const field of fields) {
255
+ const foundValue = resolveRunbookFieldValue(kv, field.aliases);
256
+ if (foundValue === null || foundValue.length === 0 || PLACEHOLDER_RE.test(stripMarkdownFormatting(foundValue))) {
257
+ violations.push({
258
+ rule: 'P3',
259
+ detail: `Runbook missing concrete value for required field '${field.key}' in lane '${lane}'.`,
260
+ });
261
+ }
262
+ }
263
+ }
264
+ function validateFiveScenarios(body, violations) {
265
+ for (let n = 1; n <= 5; n++) {
266
+ const re = new RegExp(`^\\s*${n}\\.\\s+\\S`, 'm');
267
+ if (!re.test(body)) {
268
+ violations.push({
269
+ rule: 'P3',
270
+ detail: `High-risk PR requires 5 progressive scenarios (missing numbered scenario '${n}.').`,
271
+ });
272
+ }
273
+ }
274
+ }
275
+ export function validatePrArtifact(input) {
276
+ const violations = [];
277
+ const gaps = [];
278
+ const { preamble, sections } = parseSections(input.markdown);
279
+ const header = parseHeader(preamble, sections.get('header'));
280
+ // Resolve effective lane (CLI --lane / --lane-json / ledger takes precedence as truth)
281
+ const ledgerLane = typeof input.ledger?.lane === 'string' && isLane(input.ledger.lane) ? input.ledger.lane : undefined;
282
+ const authoritativeLane = input.expectedLane ?? ledgerLane;
283
+ const declaredLane = header.lane !== null && isLane(header.lane) ? header.lane : null;
284
+ const effectiveLane = authoritativeLane ?? declaredLane;
285
+ // P1: Header & lane conformance
286
+ if (header.lane === null || declaredLane === null) {
287
+ violations.push({ rule: 'P1', detail: 'Header must declare a valid lane (trivial, standard, or high-risk).' });
288
+ }
289
+ else if (authoritativeLane !== undefined && declaredLane !== authoritativeLane) {
290
+ violations.push({
291
+ rule: 'P1',
292
+ detail: `Header lane '${declaredLane}' does not match expected lane '${authoritativeLane}'.`,
293
+ });
294
+ }
295
+ if (header.readiness === null) {
296
+ violations.push({ rule: 'P1', detail: 'Header must declare readiness (conforms, gaps, or blocked).' });
297
+ }
298
+ if (header.canonicalIssue === null || header.canonicalIssue.length === 0) {
299
+ violations.push({ rule: 'P1', detail: 'Header must declare canonical_issue (e.g. #122 or owner/repo#122).' });
300
+ }
301
+ if (header.manualDeployAction === null || !/^(?:yes|no|sΓ­|si)\b/i.test(header.manualDeployAction)) {
302
+ violations.push({ rule: 'P1', detail: 'Header must declare manual_deploy_action (yes or no).' });
303
+ }
304
+ const requiredSections = effectiveLane !== null ? prSectionsForLane(effectiveLane) : [];
305
+ const presentSections = [];
306
+ if (header.lane !== null && header.readiness !== null && header.canonicalIssue !== null && header.manualDeployAction !== null) {
307
+ presentSections.push('header');
308
+ }
309
+ for (const section of requiredSections) {
310
+ if (section === 'header')
311
+ continue;
312
+ const lookupKey = section === 'runbook_full' ? 'runbook_compact' : section;
313
+ const content = sections.get(lookupKey);
314
+ if (content !== undefined && content.length > 0) {
315
+ presentSections.push(section);
316
+ }
317
+ else {
318
+ violations.push({
319
+ rule: 'P1',
320
+ detail: `Missing or empty required section '${section}' for lane '${effectiveLane}'.`,
321
+ });
322
+ }
323
+ }
324
+ // P2: Source of Truth, visual evidence, ledger cross-check, anti-leakage
325
+ const sotBody = sections.get('source_of_truth') ?? '';
326
+ const evidenceItems = parseEvidence(sotBody);
327
+ const concreteEvidence = evidenceItems.filter((item) => item.ref.length > 0 && !PLACEHOLDER_RE.test(stripMarkdownFormatting(item.ref)) && REF_SIGNAL_RE.test(item.ref));
328
+ if (concreteEvidence.length === 0) {
329
+ violations.push({
330
+ rule: 'P2',
331
+ detail: 'Source of Truth must include at least one typed verifiable reference (issue, pr, test_red_green, sanitized_log, visual_image, sanitized_message).',
332
+ });
333
+ }
334
+ if (!VISUAL_IMAGE_RE.test(input.markdown)) {
335
+ if (VISUAL_GAP_RE.test(input.markdown)) {
336
+ gaps.push({ rule: 'P2', detail: 'Visual reference recorded as explicit 🟑 GAP instead of an embedded https:// image.' });
337
+ }
338
+ else {
339
+ violations.push({
340
+ rule: 'P2',
341
+ detail: 'PR body must include a sanitized https:// visual image or an explicit 🟑 GAP visual note (V1).',
342
+ });
343
+ }
344
+ }
345
+ if (input.ledger !== undefined) {
346
+ if (typeof input.ledger.issue === 'string' && input.ledger.issue.trim().length > 0 && header.canonicalIssue !== null) {
347
+ const ledgerNum = extractIssueNumber(input.ledger.issue);
348
+ const headerNum = extractIssueNumber(header.canonicalIssue);
349
+ const same = ledgerNum !== null && headerNum !== null
350
+ ? ledgerNum === headerNum
351
+ : input.ledger.issue.trim() === header.canonicalIssue.trim();
352
+ if (!same) {
353
+ violations.push({
354
+ rule: 'P2',
355
+ detail: `Header canonical_issue '${header.canonicalIssue}' does not match ledger issue '${input.ledger.issue}'.`,
356
+ });
357
+ }
358
+ }
359
+ const claimsRedGreen = concreteEvidence.some((item) => item.kind === 'test_red_green' && !item.isGap);
360
+ if (claimsRedGreen) {
361
+ const stages = input.ledger.stages ?? [];
362
+ const hasVerifyPass = stages.some((s) => s.stage === 'verify' && (s.status === 'done' || s.status === 'reused'));
363
+ if (!hasVerifyPass) {
364
+ violations.push({
365
+ rule: 'P2',
366
+ detail: 'PR claims test_red_green evidence, but the delivery ledger has no passing verify stage.',
367
+ });
368
+ }
369
+ }
370
+ }
371
+ scanSecretsAndPii(input.markdown, violations);
372
+ // P3: Traffic-light Risk Matrix, Scenarios, and Runbook
373
+ const riskSummary = { green: 0, yellow: 0, red: 0 };
374
+ if (effectiveLane === 'standard' || effectiveLane === 'high-risk') {
375
+ const riskBody = sections.get('risk_matrix') ?? '';
376
+ const riskRows = parseRiskRows(riskBody);
377
+ if (riskRows.length === 0) {
378
+ violations.push({
379
+ rule: 'P3',
380
+ detail: `Lane '${effectiveLane}' requires at least one traffic-light risk row (🟒/🟑/πŸ”΄ with ID R1..Rn).`,
381
+ });
382
+ }
383
+ for (const row of riskRows) {
384
+ riskSummary[row.light] += 1;
385
+ if (row.light === 'green' && (UNKNOWN_RE.test(row.likelihood) || UNKNOWN_RE.test(row.impact))) {
386
+ violations.push({
387
+ rule: 'P3',
388
+ detail: `Risk ${row.id} has Unknown/Unrated likelihood or impact and cannot be marked 🟒.`,
389
+ });
390
+ }
391
+ if (row.light === 'red') {
392
+ const badMitigation = row.mitigation.length === 0 || PLACEHOLDER_RE.test(stripMarkdownFormatting(row.mitigation));
393
+ const badEvidence = row.evidence.length === 0 || PLACEHOLDER_RE.test(stripMarkdownFormatting(row.evidence));
394
+ if (badMitigation || badEvidence) {
395
+ violations.push({
396
+ rule: 'P3',
397
+ detail: `Unmitigated πŸ”΄ RED risk ${row.id} (missing concrete mitigation or evidence) blocks handoff.`,
398
+ });
399
+ }
400
+ }
401
+ }
402
+ if (riskSummary.red > 0 && header.readiness === 'conforms') {
403
+ violations.push({
404
+ rule: 'P3',
405
+ detail: 'Header readiness cannot be conforms/🟒 when a πŸ”΄ risk row is present.',
406
+ });
407
+ }
408
+ else if (riskSummary.yellow > 0 && header.readiness === 'conforms') {
409
+ violations.push({
410
+ rule: 'P3',
411
+ detail: 'Header readiness cannot be conforms/🟒 when a 🟑 risk row is present; declare gaps/🟑.',
412
+ });
413
+ }
414
+ const runbookBody = sections.get('runbook_compact') ?? '';
415
+ if (runbookBody.length > 0) {
416
+ validateRunbook(runbookBody, effectiveLane, violations);
417
+ }
418
+ if (effectiveLane === 'high-risk') {
419
+ const scenariosBody = sections.get('five_scenarios') ?? '';
420
+ if (scenariosBody.length > 0) {
421
+ validateFiveScenarios(scenariosBody, violations);
422
+ }
423
+ }
424
+ }
425
+ // Record explicit gaps listed in the Gaps section
426
+ const gapsBody = sections.get('gaps') ?? '';
427
+ if (gapsBody.length > 0 && /🟑\s*GAP\b/i.test(gapsBody)) {
428
+ for (const line of gapsBody.split(/\r?\n/)) {
429
+ if (/🟑\s*GAP\b/i.test(line)) {
430
+ gaps.push({ rule: 'P1', detail: line.replace(/^\s*[-*]\s*/, '').trim() });
431
+ }
432
+ }
433
+ }
434
+ const verdict = violations.length > 0 ? 'violations' : gaps.length > 0 ? 'gaps' : 'conforms';
435
+ return {
436
+ verdict,
437
+ lane: effectiveLane,
438
+ declared_lane: header.lane,
439
+ readiness: header.readiness,
440
+ required_sections: requiredSections,
441
+ present_sections: presentSections,
442
+ risk_summary: riskSummary,
443
+ violations,
444
+ gaps,
445
+ };
446
+ }
@@ -0,0 +1,2 @@
1
+ export declare const validatePrArtifactUsage = "bbc validate-pr-artifact [--pr-body <file> | --stdin] [--lane trivial|standard|high-risk | --lane-json <file>] [--ledger <file>] [--format json|hud]";
2
+ export declare function validatePrArtifactCli(argv: readonly string[]): number;
@@ -0,0 +1,152 @@
1
+ /**
2
+ * LAYER: Interface
3
+ * Contains: CLI entry point for bbc validate-pr-artifact.
4
+ * Rules: Offline validation of PR/PRD + Runbook + Risk Matrix markdown; exit 0 conforms/gaps, 1 violations, 2 unusable.
5
+ * BigO: O(n) score:3
6
+ * keywords: [ValidatePrArtifactCli, PrArtifactReport]
7
+ * GOAL: Run machine-enforced P1-P3 PR artifact validation from the bbc CLI.
8
+ */
9
+ import { readFileSync } from 'node:fs';
10
+ import { EOL } from 'node:os';
11
+ import { isLane } from "./change-lane/classification.js";
12
+ import { validatePrArtifact } from "./pr-artifact/validator.js";
13
+ export const validatePrArtifactUsage = 'bbc validate-pr-artifact [--pr-body <file> | --stdin] [--lane trivial|standard|high-risk | --lane-json <file>] [--ledger <file>] [--format json|hud]';
14
+ const HELP = `Usage: ${validatePrArtifactUsage}\n` +
15
+ 'Validate a PR/PRD + Runbook + Risk Matrix body offline against rules P1-P3.\n' +
16
+ 'Exit 0: conforms or gaps only; 1: blocking violations; 2: unusable input or arguments.';
17
+ class CliUsageError extends Error {
18
+ }
19
+ function writeOut(text) {
20
+ process.stdout.write(`${text.replaceAll('\n', EOL)}${EOL}`);
21
+ }
22
+ function parseArgs(argv) {
23
+ let prBodyPath = null;
24
+ let useStdin = false;
25
+ let lane = null;
26
+ let laneJsonPath = null;
27
+ let ledgerPath = null;
28
+ let format = 'json';
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const arg = argv[i] ?? '';
31
+ if (arg === '-h' || arg === '--help')
32
+ return null;
33
+ if (arg === '--stdin') {
34
+ useStdin = true;
35
+ }
36
+ else if (arg === '--pr-body' && argv[i + 1] !== undefined) {
37
+ prBodyPath = argv[++i];
38
+ }
39
+ else if (arg === '--lane' && argv[i + 1] !== undefined) {
40
+ const value = argv[++i];
41
+ if (!isLane(value))
42
+ throw new CliUsageError(`Invalid --lane value: ${value}`);
43
+ lane = value;
44
+ }
45
+ else if (arg === '--lane-json' && argv[i + 1] !== undefined) {
46
+ laneJsonPath = argv[++i];
47
+ }
48
+ else if (arg === '--ledger' && argv[i + 1] !== undefined) {
49
+ ledgerPath = argv[++i];
50
+ }
51
+ else if (arg === '--format' && argv[i + 1] !== undefined) {
52
+ const value = argv[++i];
53
+ if (value !== 'json' && value !== 'hud')
54
+ throw new CliUsageError(`Invalid --format value: ${value}`);
55
+ format = value;
56
+ }
57
+ else {
58
+ throw new CliUsageError(`Unexpected argument: ${arg}`);
59
+ }
60
+ }
61
+ if (useStdin && prBodyPath !== null) {
62
+ throw new CliUsageError('Cannot combine --stdin with --pr-body.');
63
+ }
64
+ if (!useStdin && prBodyPath === null) {
65
+ throw new CliUsageError('Provide --pr-body <file> or --stdin.');
66
+ }
67
+ if (lane !== null && laneJsonPath !== null) {
68
+ throw new CliUsageError('Cannot combine --lane with --lane-json.');
69
+ }
70
+ return { prBodyPath, useStdin, lane, laneJsonPath, ledgerPath, format };
71
+ }
72
+ function readJsonObject(path, label) {
73
+ let raw;
74
+ try {
75
+ raw = readFileSync(path, 'utf8');
76
+ }
77
+ catch (err) {
78
+ throw new CliUsageError(`Cannot read ${label} (${path}): ${err instanceof Error ? err.message : String(err)}`);
79
+ }
80
+ let parsed;
81
+ try {
82
+ parsed = JSON.parse(raw);
83
+ }
84
+ catch {
85
+ throw new CliUsageError(`Invalid JSON in ${label}: ${path}`);
86
+ }
87
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
88
+ throw new CliUsageError(`${label} must be a JSON object: ${path}`);
89
+ }
90
+ return parsed;
91
+ }
92
+ function formatHud(report) {
93
+ const icon = report.verdict === 'violations' ? 'πŸ”΄' : report.verdict === 'gaps' ? '🟑' : '🟒';
94
+ const lines = [
95
+ `${icon} PR ARTIFACT ─ ${report.verdict.toUpperCase()}`,
96
+ `Lane : ${report.lane ?? 'unknown'} (declared: ${report.declared_lane ?? 'missing'})`,
97
+ `Readiness: ${report.readiness ?? 'missing'} Β· Risks: 🟒${report.risk_summary.green} 🟑${report.risk_summary.yellow} πŸ”΄${report.risk_summary.red}`,
98
+ `Sections : ${report.present_sections.length}/${report.required_sections.length}`,
99
+ ];
100
+ for (const v of report.violations)
101
+ lines.push(`βœ– [${v.rule}] ${v.detail}`);
102
+ for (const g of report.gaps)
103
+ lines.push(`! [${g.rule}] ${g.detail}`);
104
+ return lines.join('\n');
105
+ }
106
+ export function validatePrArtifactCli(argv) {
107
+ let parsed;
108
+ try {
109
+ parsed = parseArgs(argv);
110
+ }
111
+ catch (err) {
112
+ process.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}${EOL}`);
113
+ return 2;
114
+ }
115
+ if (parsed === null) {
116
+ writeOut(HELP);
117
+ return 0;
118
+ }
119
+ let markdown;
120
+ let expectedLane = parsed.lane ?? undefined;
121
+ let ledger;
122
+ try {
123
+ markdown = parsed.useStdin ? readFileSync(0, 'utf8') : readFileSync(parsed.prBodyPath, 'utf8');
124
+ if (parsed.laneJsonPath !== null) {
125
+ const obj = readJsonObject(parsed.laneJsonPath, '--lane-json');
126
+ if (typeof obj.lane !== 'string' || !isLane(obj.lane)) {
127
+ throw new CliUsageError(`--lane-json missing valid 'lane' field: ${parsed.laneJsonPath}`);
128
+ }
129
+ expectedLane = obj.lane;
130
+ }
131
+ if (parsed.ledgerPath !== null) {
132
+ const obj = readJsonObject(parsed.ledgerPath, '--ledger');
133
+ ledger = {
134
+ lane: typeof obj.lane === 'string' ? obj.lane : undefined,
135
+ issue: typeof obj.issue === 'string' ? obj.issue : undefined,
136
+ stages: Array.isArray(obj.stages) ? obj.stages : undefined,
137
+ };
138
+ }
139
+ }
140
+ catch (err) {
141
+ process.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}${EOL}`);
142
+ return 2;
143
+ }
144
+ const report = validatePrArtifact({ markdown, expectedLane, ledger });
145
+ if (parsed.format === 'hud') {
146
+ writeOut(formatHud(report));
147
+ }
148
+ else {
149
+ writeOut(JSON.stringify(report));
150
+ }
151
+ return report.verdict === 'violations' ? 1 : 0;
152
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bbcsoftwarefactory/cli",
3
- "version": "1.1.4",
3
+ "version": "1.2.0",
4
4
  "description": "Command line interface for the BuilderBot agent skills: Big O scoring, change classification, README workflow rendering, and diff scope extraction.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -14,7 +14,7 @@
14
14
  "dist"
15
15
  ],
16
16
  "dependencies": {
17
- "@bbcsoftwarefactory/cli-core": "^1.1.4"
17
+ "@bbcsoftwarefactory/cli-core": "^1.2.0"
18
18
  },
19
19
  "scripts": {
20
20
  "build": "tsc -p tsconfig.build.json && node build.ts",