@bbcsoftwarefactory/cli 0.1.1 → 1.1.3

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 (155) hide show
  1. package/dist/audit-ledger.d.ts +2 -0
  2. package/dist/audit-ledger.js +71 -0
  3. package/dist/bbc-install.d.ts +2 -0
  4. package/dist/bbc-install.js +1278 -0
  5. package/dist/bbc.js +87 -3
  6. package/dist/bundle/commands/daily/SKILL.md +112 -0
  7. package/dist/bundle/commands/daily/adapters/command.md +17 -0
  8. package/dist/bundle/commands/daily/adapters/gemini.toml +17 -0
  9. package/dist/bundle/commands/issue-clean-and-close/SKILL.md +85 -0
  10. package/dist/bundle/commands/issue-clean-and-close/adapters/command.md +17 -0
  11. package/dist/bundle/commands/issue-clean-and-close/adapters/gemini.toml +17 -0
  12. package/dist/bundle/commands/issue-clean-and-close/references/policy.md +87 -0
  13. package/dist/bundle/commands/recap/SKILL.md +84 -0
  14. package/dist/bundle/commands/recap/adapters/command.md +17 -0
  15. package/dist/bundle/commands/recap/adapters/gemini.toml +17 -0
  16. package/dist/bundle/installer/clients.json +103 -0
  17. package/dist/bundle/skills/code-quality-gate/SKILL.md +58 -0
  18. package/dist/bundle/skills/code-quality-gate/references/gate-bigo.md +31 -0
  19. package/dist/bundle/skills/code-quality-gate/references/gate-earlyreturn.md +73 -0
  20. package/dist/bundle/skills/code-quality-gate/references/gate-typesafe.md +32 -0
  21. package/dist/bundle/skills/code-quality-gate/references/output-schema.yml +40 -0
  22. package/dist/bundle/skills/delivery-coordinator/SKILL.md +80 -0
  23. package/dist/bundle/skills/delivery-coordinator/references/hud-output.md +55 -0
  24. package/dist/bundle/skills/delivery-coordinator/references/intake.md +86 -0
  25. package/dist/bundle/skills/delivery-coordinator/references/issue-claim.md +143 -0
  26. package/dist/bundle/skills/delivery-coordinator/references/issue-dedup.md +38 -0
  27. package/dist/bundle/skills/delivery-coordinator/references/sleuth-regression-exercise.md +60 -0
  28. package/dist/bundle/skills/delivery-coordinator/references/visual-reference.md +45 -0
  29. package/dist/bundle/skills/delivery-coordinator/references/worktree-isolation.md +19 -0
  30. package/dist/bundle/skills/documentation-steward/SKILL.md +43 -0
  31. package/dist/bundle/skills/documentation-steward/references/discovery.md +17 -0
  32. package/dist/bundle/skills/documentation-steward/references/handoff.md +15 -0
  33. package/dist/bundle/skills/greptile-review-loop/SKILL.md +56 -0
  34. package/dist/bundle/skills/greptile-review-loop/references/review-protocol.md +37 -0
  35. package/dist/bundle/skills/issue-reviewer/SKILL.md +84 -0
  36. package/dist/bundle/skills/issue-reviewer/references/review-format.md +100 -0
  37. package/dist/bundle/skills/issue-reviewer/references/triage.md +105 -0
  38. package/dist/bundle/skills/question-gate/SKILL.md +64 -0
  39. package/dist/bundle/skills/question-gate/references/client-hooks.md +111 -0
  40. package/dist/bundle/skills/question-gate/references/diagram-routing.md +58 -0
  41. package/dist/bundle/skills/question-gate/tests/fixtures/question-corpus.json +481 -0
  42. package/dist/bundle/skills/regression-testing/SKILL.md +49 -0
  43. package/dist/bundle/skills/regression-testing/references/evidence-record.md +35 -0
  44. package/dist/bundle/skills/requirements-spec/SKILL.md +59 -0
  45. package/dist/bundle/skills/risk-scout/SKILL.md +53 -0
  46. package/dist/bundle/skills/risk-scout/references/risk-matrix.md +49 -0
  47. package/dist/bundle/skills/skill-clean-architecture/SKILL.md +53 -0
  48. package/dist/bundle/skills/skill-clean-architecture/references/layer-rules.md +22 -0
  49. package/dist/bundle/skills/skill-clean-architecture/references/source-headers.md +30 -0
  50. package/dist/bundle/skills/skill-clean-architecture/tests/fixtures/bigo/bad-utf8.js +1 -0
  51. package/dist/bundle/skills/skill-clean-architecture/tests/fixtures/bigo/edge-crlf.ts +6 -0
  52. package/dist/bundle/skills/skill-clean-architecture/tests/fixtures/bigo/edge-mixed.ts +15 -0
  53. package/dist/bundle/skills/skill-clean-architecture/tests/fixtures/bigo/empty.js +0 -0
  54. package/dist/bundle/skills/skill-clean-architecture/tests/fixtures/bigo/no-newline.js +1 -0
  55. package/dist/bundle/skills/skill-clean-architecture/tests/fixtures/bigo.expected.yml +95 -0
  56. package/dist/bundle/skills/tool-depot/SKILL.md +47 -0
  57. package/dist/bundle/skills/tool-depot/references/checkout.md +29 -0
  58. package/dist/bundle/skills/tool-depot/references/loki-read.md +41 -0
  59. package/dist/bundle/skills/tool-depot/references/readonly-access.md +84 -0
  60. package/dist/bundle/skills/tool-depot/references/tool-catalog.json +47 -0
  61. package/dist/bundle/skills/tool-depot/scripts/loki-runtime-logs.py +305 -0
  62. package/dist/bundle/skills/tool-depot/tests/loki-runtime-logs.test.sh +101 -0
  63. package/dist/bundle/skills/watcher-observability/SKILL.md +72 -0
  64. package/dist/bundle/skills/watcher-observability/references/batch-protocol.md +44 -0
  65. package/dist/bundle/skills/watcher-observability/references/configuration.md +31 -0
  66. package/dist/bundle/skills/watcher-observability/references/error-scan.md +102 -0
  67. package/dist/bundle/skills/watcher-observability/references/live-protocol.md +49 -0
  68. package/dist/bundle/skills/watcher-observability/references/server-account.md +72 -0
  69. package/dist/bundle/skills/watcher-observability/server/watcher-gate.sh +51 -0
  70. package/dist/bundle/skills/watcher-observability/tests/watcher-gate.test.sh +113 -0
  71. package/dist/bundle/skills/watcher-observability/watcher.json +1 -0
  72. package/dist/bundle/skills/workflow-auditor/SKILL.md +53 -0
  73. package/dist/bundle/skills/workflow-auditor/references/audit-protocol.md +49 -0
  74. package/dist/bundle/skills/workflow-auditor/references/ledger.md +122 -0
  75. package/dist/change-lane/classification.js +3 -1
  76. package/dist/check-issue-claim.d.ts +2 -0
  77. package/dist/check-issue-claim.js +146 -0
  78. package/dist/check-worktree-guard.d.ts +2 -0
  79. package/dist/check-worktree-guard.js +114 -0
  80. package/dist/error-scan.d.ts +3 -0
  81. package/dist/error-scan.js +216 -0
  82. package/dist/export-public.d.ts +9 -0
  83. package/dist/export-public.js +274 -0
  84. package/dist/fetch-issue-attachments.d.ts +22 -0
  85. package/dist/fetch-issue-attachments.js +325 -0
  86. package/dist/issue-claim/evaluation.d.ts +66 -0
  87. package/dist/issue-claim/evaluation.js +259 -0
  88. package/dist/issue-claim/loaders.d.ts +5 -0
  89. package/dist/issue-claim/loaders.js +116 -0
  90. package/dist/list-zed-commands.d.ts +7 -0
  91. package/dist/list-zed-commands.js +288 -0
  92. package/dist/plan-issue-triage.d.ts +3 -0
  93. package/dist/plan-issue-triage.js +404 -0
  94. package/dist/question-gate/ledger.d.ts +5 -0
  95. package/dist/question-gate/ledger.js +115 -0
  96. package/dist/question-gate/rules.d.ts +40 -0
  97. package/dist/question-gate/rules.js +483 -0
  98. package/dist/recap/board.d.ts +5 -0
  99. package/dist/recap/board.js +384 -0
  100. package/dist/recap/git-and-github.d.ts +11 -0
  101. package/dist/recap/git-and-github.js +620 -0
  102. package/dist/recap/report-and-hud.d.ts +2 -0
  103. package/dist/recap/report-and-hud.js +294 -0
  104. package/dist/recap/time-and-refs.d.ts +27 -0
  105. package/dist/recap/time-and-refs.js +148 -0
  106. package/dist/recap.d.ts +2 -0
  107. package/dist/recap.js +217 -0
  108. package/dist/render-workflow.js +12 -14
  109. package/dist/resolve-containers.d.ts +2 -0
  110. package/dist/resolve-containers.js +96 -0
  111. package/dist/review-loop.d.ts +7 -0
  112. package/dist/review-loop.js +622 -0
  113. package/dist/save-counts.d.ts +2 -0
  114. package/dist/save-counts.js +191 -0
  115. package/dist/summarize-logs.d.ts +2 -0
  116. package/dist/summarize-logs.js +41 -0
  117. package/dist/sweep-github.d.ts +10 -0
  118. package/dist/sweep-github.js +453 -0
  119. package/dist/sweep-issues.d.ts +56 -0
  120. package/dist/sweep-issues.js +650 -0
  121. package/dist/sweep.d.ts +2 -0
  122. package/dist/sweep.js +301 -0
  123. package/dist/triage-question.d.ts +2 -0
  124. package/dist/triage-question.js +189 -0
  125. package/dist/validate-skills.d.ts +2 -0
  126. package/dist/validate-skills.js +48 -0
  127. package/dist/watch-live.d.ts +7 -0
  128. package/dist/watch-live.js +83 -0
  129. package/dist/watcher/config.d.ts +11 -0
  130. package/dist/watcher/config.js +265 -0
  131. package/dist/watcher/live-classifier.d.ts +52 -0
  132. package/dist/watcher/live-classifier.js +510 -0
  133. package/dist/watcher/safe-fs.d.ts +9 -0
  134. package/dist/watcher/safe-fs.js +159 -0
  135. package/dist/watcher/stream.d.ts +27 -0
  136. package/dist/watcher/stream.js +340 -0
  137. package/dist/watcher/summarizer.d.ts +19 -0
  138. package/dist/watcher/summarizer.js +121 -0
  139. package/dist/wave3/process.d.ts +14 -0
  140. package/dist/wave3/process.js +84 -0
  141. package/dist/wave4/process.d.ts +14 -0
  142. package/dist/wave4/process.js +128 -0
  143. package/dist/workflow/render.d.ts +1 -1
  144. package/dist/workflow/render.js +1 -1
  145. package/dist/workflow-auditor/audit.d.ts +27 -0
  146. package/dist/workflow-auditor/audit.js +583 -0
  147. package/dist/workflow-auditor/ledger-io.d.ts +5 -0
  148. package/dist/workflow-auditor/ledger-io.js +99 -0
  149. package/dist/workflow-auditor/skills-validator.d.ts +10 -0
  150. package/dist/workflow-auditor/skills-validator.js +533 -0
  151. package/dist/worktree-guard/evaluation.d.ts +19 -0
  152. package/dist/worktree-guard/evaluation.js +84 -0
  153. package/dist/worktree-guard/git.d.ts +3 -0
  154. package/dist/worktree-guard/git.js +61 -0
  155. package/package.json +32 -33
@@ -0,0 +1,404 @@
1
+ /**
2
+ * LAYER: Application
3
+ * Contains: Offline issue triage planner implementing rules TR1-TR8.
4
+ * Rules: Never call GitHub; assign only the author when assignable; never create labels.
5
+ * BigO: O(n) score:4
6
+ * keywords: [TriagePlan, PriorityLevel, IssueTriage, TriageReport]
7
+ * GOAL: Turn a reviewer triage proposal into deterministic, safe GitHub CLI writes.
8
+ */
9
+ import { readFileSync } from 'node:fs';
10
+ import { percentEncodeAll } from "./wave3/process.js";
11
+ export const planIssueTriageUsage = 'bbc plan-issue-triage --repo <owner/repo> --issue-json <file> --labels-json <file> --proposal-json <file> --author-assignable yes|no|unknown [--claim-label status:in-progress]';
12
+ const DEFAULT_CLAIM_LABEL = 'status:in-progress';
13
+ const ASSIGNABLE = new Set(['yes', 'no', 'unknown']);
14
+ const PRIORITIES = ['P0', 'P1', 'P2', 'P3'];
15
+ const PRIORITY_NAME = /^(?:(?:priority|prioridad|prio)\s*[:/_ -]\s*(.+)|(p[0-3])\b.*)$/;
16
+ const LEVEL_WORDS = new Map([
17
+ ['p0', 0], ['critical', 0], ['critica', 0], ['crítica', 0], ['urgent', 0], ['urgente', 0], ['blocker', 0],
18
+ ['p1', 1], ['high', 1], ['alta', 1],
19
+ ['p2', 2], ['medium', 2], ['media', 2], ['normal', 2],
20
+ ['p3', 3], ['low', 3], ['baja', 3], ['minor', 3],
21
+ ]);
22
+ const INVALID_RULES = new Set(['TR5', 'TR6', 'TR7']);
23
+ const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
24
+ const HELP = 'Usage: bbc plan-issue-triage --repo <owner/repo>\n' +
25
+ ' --issue-json <file> gh api repos/<o>/<r>/issues/<n> (or gh issue view <n> --json ...)\n' +
26
+ ' --labels-json <file> gh api --paginate --slurp "repos/<o>/<r>/labels?per_page=100"\n' +
27
+ ' --proposal-json <file> {"priority": "P0-P3", "add": [...], "remove": [...], "rationale": "..."}\n' +
28
+ ' --author-assignable yes|no|unknown gh api repos/<o>/<r>/assignees/<author> (204 yes, 404 no)\n' +
29
+ ' [--claim-label status:in-progress]\n' +
30
+ 'Exit 0: ready or ready-with-gaps; 1: invalid-proposal; 2: unusable.';
31
+ class UnusableError extends Error {
32
+ }
33
+ function fold(value) {
34
+ return typeof value === 'string' ? value.trim().toLowerCase() : '';
35
+ }
36
+ function extractLogin(value) {
37
+ let candidate = value;
38
+ if (candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate)) {
39
+ candidate = candidate.login;
40
+ }
41
+ return typeof candidate === 'string' && candidate.trim() ? candidate : null;
42
+ }
43
+ function flattenPages(value) {
44
+ if (Array.isArray(value) && value.every((item) => Array.isArray(item))) {
45
+ return value.flat();
46
+ }
47
+ return value;
48
+ }
49
+ function extractNames(items) {
50
+ if (!Array.isArray(items))
51
+ return [];
52
+ const names = [];
53
+ for (const item of items) {
54
+ const rawName = item !== null && typeof item === 'object' && !Array.isArray(item)
55
+ ? item.name
56
+ : item;
57
+ if (typeof rawName === 'string' && rawName.trim()) {
58
+ names.push(rawName);
59
+ }
60
+ }
61
+ return names;
62
+ }
63
+ function loadJson(path, label) {
64
+ let raw;
65
+ try {
66
+ raw = readFileSync(path, 'utf8');
67
+ }
68
+ catch {
69
+ throw new UnusableError(`${label} cannot be read.`);
70
+ }
71
+ try {
72
+ return JSON.parse(raw);
73
+ }
74
+ catch {
75
+ throw new UnusableError(`${label} is not valid JSON.`);
76
+ }
77
+ }
78
+ function isPlainObject(value) {
79
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
80
+ }
81
+ function loadIssue(path) {
82
+ const raw = loadJson(path, 'Issue JSON');
83
+ if (!isPlainObject(raw) || typeof raw.number !== 'number' || !Number.isInteger(raw.number)) {
84
+ throw new UnusableError('Issue JSON needs a numeric number.');
85
+ }
86
+ if (typeof raw.state !== 'string' || raw.state.toLowerCase() !== 'open') {
87
+ throw new UnusableError('Only an open issue is triaged; reopen it first.');
88
+ }
89
+ const user = isPlainObject(raw.user) ? raw.user : raw.author;
90
+ const author = extractLogin(user);
91
+ if (author === null) {
92
+ throw new UnusableError('Issue JSON needs the author login (user.login).');
93
+ }
94
+ const userObj = isPlainObject(user) ? user : null;
95
+ const kind = userObj?.type;
96
+ const assigneesRaw = Array.isArray(raw.assignees) ? raw.assignees : [];
97
+ const assignees = [];
98
+ for (const entry of assigneesRaw) {
99
+ const login = extractLogin(entry);
100
+ if (login)
101
+ assignees.push(login);
102
+ }
103
+ return {
104
+ number: raw.number,
105
+ author,
106
+ bot: kind === 'Bot' || author.endsWith('[bot]') || Boolean(userObj?.is_bot),
107
+ assignees,
108
+ labels: extractNames(raw.labels),
109
+ };
110
+ }
111
+ function Unusable(message) {
112
+ return new UnusableError(message);
113
+ }
114
+ function loadLabels(path) {
115
+ const raw = flattenPages(loadJson(path, 'Repository labels JSON'));
116
+ if (!Array.isArray(raw)) {
117
+ throw new UnusableError('Repository labels JSON must be an array.');
118
+ }
119
+ return extractNames(raw);
120
+ }
121
+ function loadProposal(path) {
122
+ const raw = loadJson(path, 'Proposal JSON');
123
+ if (!isPlainObject(raw)) {
124
+ throw new UnusableError('Proposal JSON must be an object.');
125
+ }
126
+ const priority = raw.priority;
127
+ if (typeof priority !== 'string' || !PRIORITIES.includes(priority.trim().toUpperCase())) {
128
+ throw new UnusableError(`Proposal priority must be one of: ${PRIORITIES.join(', ')}.`);
129
+ }
130
+ if (typeof raw.rationale !== 'string' || !raw.rationale.trim()) {
131
+ throw new UnusableError('Proposal needs a rationale grounded in the evidence.');
132
+ }
133
+ const lists = { add: [], remove: [] };
134
+ for (const key of ['add', 'remove']) {
135
+ const value = raw[key] ?? [];
136
+ if (!Array.isArray(value) || !value.every((item) => typeof item === 'string' && item.trim())) {
137
+ throw new UnusableError(`Proposal "${key}" must be an array of label names.`);
138
+ }
139
+ lists[key] = value;
140
+ }
141
+ const addFolded = new Set(lists.add.map((name) => fold(name)));
142
+ const both = [...new Set(lists.remove.map((name) => fold(name)).filter((name) => addFolded.has(name)))].sort();
143
+ if (both.length > 0) {
144
+ throw new UnusableError(`A label cannot be added and removed at once: ${both.join(', ')}.`);
145
+ }
146
+ return {
147
+ priority: priority.trim().toUpperCase(),
148
+ add: lists.add,
149
+ remove: lists.remove,
150
+ rationale: raw.rationale.trim(),
151
+ };
152
+ }
153
+ export function priorityLevel(name) {
154
+ const match = PRIORITY_NAME.exec(fold(name));
155
+ if (!match)
156
+ return [false, null];
157
+ const group1 = match[1] ?? '';
158
+ const word = match[2] ?? (group1.trim().split(/[\s:/_-]+/)[0] ?? '');
159
+ return [true, LEVEL_WORDS.get(word) ?? null];
160
+ }
161
+ function isPriority(name) {
162
+ return priorityLevel(name)[0];
163
+ }
164
+ class Report {
165
+ findings = [];
166
+ add(rule, detail, labels) {
167
+ const finding = labels && labels.length > 0
168
+ ? { rule, detail, labels }
169
+ : { rule, detail };
170
+ this.findings.push(finding);
171
+ }
172
+ verdict() {
173
+ const rules = new Set(this.findings.map((finding) => finding.rule));
174
+ for (const rule of INVALID_RULES) {
175
+ if (rules.has(rule))
176
+ return 'invalid-proposal';
177
+ }
178
+ return rules.size > 0 ? 'ready-with-gaps' : 'ready';
179
+ }
180
+ }
181
+ function planAssignment(issue, assignable, report) {
182
+ if (issue.bot) {
183
+ report.add('TR2', 'The author is a bot; nobody is assigned. Say so in the triage comment.');
184
+ return [null, false];
185
+ }
186
+ const assigneeSet = new Set(issue.assignees.map((login) => fold(login)));
187
+ if (assigneeSet.has(fold(issue.author))) {
188
+ return [null, true];
189
+ }
190
+ if (assignable !== 'yes') {
191
+ const reason = assignable === 'no' ? 'cannot be assigned in this repository' : 'was not verified as assignable';
192
+ report.add('TR3', `The author ${reason}; nobody is assigned. Say so in the triage comment.`);
193
+ return [null, false];
194
+ }
195
+ return [issue.author, false];
196
+ }
197
+ function planPriority(proposal, resolvedAdd, repoLabels, current, report) {
198
+ const level = Number.parseInt(proposal.priority.slice(1), 10);
199
+ const chosen = resolvedAdd.filter((name) => isPriority(name));
200
+ if (chosen.length > 1) {
201
+ report.add('TR6', 'Only one priority label may be set.', chosen);
202
+ return null;
203
+ }
204
+ if (chosen.length === 1) {
205
+ const firstChosen = chosen[0];
206
+ const [, chosenLevel] = priorityLevel(firstChosen);
207
+ if (chosenLevel !== level) {
208
+ report.add('TR7', `The priority label does not match ${proposal.priority}.`, chosen);
209
+ }
210
+ return firstChosen;
211
+ }
212
+ const candidates = repoLabels.filter((name) => {
213
+ const [isPrio, prioLevel] = priorityLevel(name);
214
+ return isPrio && prioLevel === level;
215
+ });
216
+ const onIssue = candidates.filter((name) => current.has(fold(name)));
217
+ if (candidates.length === 1 || onIssue.length === 1) {
218
+ return (onIssue[0] ?? candidates[0]) ?? null;
219
+ }
220
+ if (candidates.length > 0) {
221
+ report.add('TR7', `Several repository labels mean ${proposal.priority}; name one in "add".`, candidates);
222
+ return null;
223
+ }
224
+ const detail = repoLabels.some((name) => isPriority(name))
225
+ ? `The repository has no label for ${proposal.priority}`
226
+ : 'The repository has no priority labels';
227
+ report.add('TR8', `${detail}; state the priority in the triage comment only. A maintainer may create the label.`);
228
+ return null;
229
+ }
230
+ function evaluateTriage(issue, repoLabels, proposal, assignable, claimLabel) {
231
+ const report = new Report();
232
+ const real = new Map();
233
+ for (const name of repoLabels) {
234
+ const key = fold(name);
235
+ if (!real.has(key))
236
+ real.set(key, name);
237
+ }
238
+ const current = new Map();
239
+ for (const name of issue.labels) {
240
+ current.set(fold(name), name);
241
+ }
242
+ const claimFolded = fold(claimLabel);
243
+ const protectedLabels = [...proposal.add, ...proposal.remove].filter((name) => {
244
+ const f = fold(name);
245
+ return f === claimFolded || f.startsWith('status:');
246
+ });
247
+ if (protectedLabels.length > 0) {
248
+ report.add('TR5', 'Status and claim labels belong to the delivery workflow; triage never changes them.', protectedLabels);
249
+ }
250
+ const resolvedAdd = [];
251
+ const missing = [];
252
+ const seen = new Set();
253
+ for (const name of proposal.add) {
254
+ const f = fold(name);
255
+ const canonical = real.get(f);
256
+ if (canonical === undefined) {
257
+ missing.push(name);
258
+ }
259
+ else if (!seen.has(f)) {
260
+ seen.add(f);
261
+ resolvedAdd.push(canonical);
262
+ }
263
+ }
264
+ if (missing.length > 0) {
265
+ report.add('TR4', 'Labels missing in the repository were dropped; the workflow never creates labels.', missing);
266
+ }
267
+ const priorityLabel = planPriority(proposal, resolvedAdd, repoLabels, current, report);
268
+ if (priorityLabel !== null && !seen.has(fold(priorityLabel))) {
269
+ resolvedAdd.push(priorityLabel);
270
+ }
271
+ const labelsAdd = resolvedAdd.filter((name) => !current.has(fold(name)));
272
+ const labelsRemove = [];
273
+ for (const name of proposal.remove) {
274
+ const existing = current.get(fold(name));
275
+ if (existing !== undefined)
276
+ labelsRemove.push(existing);
277
+ }
278
+ const removed = new Set(labelsRemove.map((name) => fold(name)));
279
+ const priorityFolded = fold(priorityLabel);
280
+ for (const name of issue.labels) {
281
+ const f = fold(name);
282
+ if (isPriority(name) && f !== priorityFolded && !removed.has(f)) {
283
+ removed.add(f);
284
+ labelsRemove.push(name);
285
+ }
286
+ }
287
+ const [assign, alreadyAssigned] = planAssignment(issue, assignable, report);
288
+ const finalLabels = [
289
+ ...issue.labels.filter((name) => !removed.has(fold(name))),
290
+ ...labelsAdd,
291
+ ];
292
+ return {
293
+ verdict: report.verdict(),
294
+ issue: issue.number,
295
+ author: issue.author,
296
+ assign,
297
+ already_assigned: alreadyAssigned,
298
+ labels_add: labelsAdd,
299
+ labels_remove: labelsRemove,
300
+ labels_final: finalLabels,
301
+ priority: proposal.priority,
302
+ priority_label: priorityLabel,
303
+ missing_labels: missing,
304
+ rationale: proposal.rationale,
305
+ findings: report.findings,
306
+ };
307
+ }
308
+ function shellArg(value) {
309
+ return `"${value.replace(/(["$`\\])/g, '\\$1')}"`;
310
+ }
311
+ function buildCommands(plan, repo) {
312
+ const base = `repos/${repo}/issues/${plan.issue}`;
313
+ const lines = [];
314
+ if (plan.assign) {
315
+ lines.push(`gh api -X POST ${base}/assignees -f ${shellArg(`assignees[]=${plan.assign}`)}`);
316
+ }
317
+ if (plan.labels_add.length > 0) {
318
+ const flags = plan.labels_add.map((name) => `-f ${shellArg(`labels[]=${name}`)}`).join(' ');
319
+ lines.push(`gh api -X POST ${base}/labels ${flags}`);
320
+ }
321
+ for (const name of plan.labels_remove) {
322
+ lines.push(`gh api -X DELETE ${base}/labels/${percentEncodeAll(name)}`);
323
+ }
324
+ return lines;
325
+ }
326
+ function parseArgs(argv) {
327
+ const options = {
328
+ repo: null,
329
+ issue: null,
330
+ labels: null,
331
+ proposal: null,
332
+ assignable: null,
333
+ claim_label: DEFAULT_CLAIM_LABEL,
334
+ };
335
+ const keyMap = new Map([
336
+ ['--repo', 'repo'],
337
+ ['--issue-json', 'issue'],
338
+ ['--labels-json', 'labels'],
339
+ ['--proposal-json', 'proposal'],
340
+ ['--author-assignable', 'assignable'],
341
+ ['--claim-label', 'claim_label'],
342
+ ]);
343
+ const queue = [...argv];
344
+ while (queue.length > 0) {
345
+ const arg = queue.shift();
346
+ if (arg === '-h' || arg === '--help')
347
+ return null;
348
+ const key = keyMap.get(arg);
349
+ if (!key || queue.length === 0) {
350
+ throw new UnusableError(`Unexpected argument ${arg}; see --help.`);
351
+ }
352
+ options[key] = queue.shift();
353
+ }
354
+ const missing = [];
355
+ for (const [flag, key] of keyMap.entries()) {
356
+ if (key !== 'claim_label' && !options[key])
357
+ missing.push(flag);
358
+ }
359
+ if (missing.length > 0) {
360
+ throw new UnusableError(`Required: ${missing.join(', ')}.`);
361
+ }
362
+ if (!REPO_RE.test(options.repo)) {
363
+ throw new UnusableError('--repo must be <owner>/<repo>.');
364
+ }
365
+ if (!ASSIGNABLE.has(options.assignable)) {
366
+ throw new UnusableError(`--author-assignable must be one of: ${[...ASSIGNABLE].join(', ')}.`);
367
+ }
368
+ return {
369
+ repo: options.repo,
370
+ issue: options.issue,
371
+ labels: options.labels,
372
+ proposal: options.proposal,
373
+ assignable: options.assignable,
374
+ claimLabel: options.claim_label,
375
+ };
376
+ }
377
+ export function planIssueTriage(argv) {
378
+ let options;
379
+ let plan;
380
+ try {
381
+ options = parseArgs(argv);
382
+ if (options === null) {
383
+ process.stdout.write(`${HELP}\n`);
384
+ return 0;
385
+ }
386
+ const issue = loadIssue(options.issue);
387
+ const repoLabels = loadLabels(options.labels);
388
+ const proposal = loadProposal(options.proposal);
389
+ plan = evaluateTriage(issue, repoLabels, proposal, options.assignable, options.claimLabel);
390
+ }
391
+ catch (error) {
392
+ const detail = error instanceof Error ? error.message : String(error);
393
+ process.stdout.write(`${JSON.stringify({ verdict: 'unusable', proceed: false, findings: [{ rule: 'TR1', detail }] }, null, 2)}\n`);
394
+ return 2;
395
+ }
396
+ const proceed = plan.verdict !== 'invalid-proposal';
397
+ const output = {
398
+ ...plan,
399
+ proceed,
400
+ commands: proceed ? buildCommands(plan, options.repo) : [],
401
+ };
402
+ process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
403
+ return proceed ? 0 : 1;
404
+ }
@@ -0,0 +1,5 @@
1
+ export declare class UnusableQuestionInputError extends Error {
2
+ }
3
+ export declare function findDefaultLedger(): string | undefined;
4
+ export declare function loadLedger(path: string): Record<string, unknown>;
5
+ export declare function readLastAssistantFromTranscript(transcriptPath: unknown): string;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * LAYER: Infrastructure
3
+ * Contains: Ledger discovery/loading and assistant transcript reading for triage-question.
4
+ * Rules: Read-only git rev-parse and file inspection; never modify files.
5
+ * BigO: O(n^2) score:1
6
+ * keywords: [LedgerDiscovery, TranscriptReader]
7
+ * GOAL: Locate and load optional delivery ledgers and hook transcripts safely.
8
+ */
9
+ import { spawnSync } from 'node:child_process';
10
+ import { readFileSync, statSync } from 'node:fs';
11
+ import { parseJsonText } from '@bbcsoftwarefactory/cli-core/python-json';
12
+ const LEDGER_NAME = 'bbc-delivery-ledger.json';
13
+ export class UnusableQuestionInputError extends Error {
14
+ }
15
+ function isRegularFile(path) {
16
+ try {
17
+ return statSync(path).isFile();
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
23
+ export function findDefaultLedger() {
24
+ const result = spawnSync('git', ['rev-parse', '--git-path', LEDGER_NAME], {
25
+ timeout: 5_000,
26
+ encoding: 'utf8',
27
+ });
28
+ if (result.error || result.signal || result.status !== 0)
29
+ return undefined;
30
+ const candidate = result.stdout.trim();
31
+ if (candidate === '')
32
+ return undefined;
33
+ return isRegularFile(candidate) ? candidate : undefined;
34
+ }
35
+ export function loadLedger(path) {
36
+ let raw;
37
+ try {
38
+ raw = readFileSync(path, 'utf8');
39
+ }
40
+ catch (error) {
41
+ throw new UnusableQuestionInputError(`Delivery ledger is unreadable or invalid JSON: ${String(error)}`);
42
+ }
43
+ let data;
44
+ try {
45
+ data = parseJsonText(raw);
46
+ }
47
+ catch (error) {
48
+ const message = error instanceof Error ? error.message : String(error);
49
+ throw new UnusableQuestionInputError(`Delivery ledger is unreadable or invalid JSON: ${message}`);
50
+ }
51
+ if (typeof data !== 'object' || data === null || Array.isArray(data) || data.version !== 1) {
52
+ throw new UnusableQuestionInputError('Delivery ledger must be a JSON object with version 1.');
53
+ }
54
+ return data;
55
+ }
56
+ export function readLastAssistantFromTranscript(transcriptPath) {
57
+ if (typeof transcriptPath !== 'string' || transcriptPath.trim() === '')
58
+ return '';
59
+ if (!isRegularFile(transcriptPath))
60
+ return '';
61
+ let content;
62
+ try {
63
+ content = readFileSync(transcriptPath, 'utf8');
64
+ }
65
+ catch {
66
+ return '';
67
+ }
68
+ let lastText = '';
69
+ for (const rawLine of content.split(/\r?\n/)) {
70
+ const line = rawLine.trim();
71
+ if (line === '')
72
+ continue;
73
+ let entry;
74
+ try {
75
+ entry = JSON.parse(line);
76
+ }
77
+ catch {
78
+ continue;
79
+ }
80
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry))
81
+ continue;
82
+ const obj = entry;
83
+ if (obj.role !== 'assistant')
84
+ continue;
85
+ const message = obj.message;
86
+ if (typeof message === 'string' && message.trim() !== '') {
87
+ lastText = message;
88
+ continue;
89
+ }
90
+ if (typeof message !== 'object' || message === null || Array.isArray(message))
91
+ continue;
92
+ const msgContent = message.content;
93
+ if (typeof msgContent === 'string' && msgContent.trim() !== '') {
94
+ lastText = msgContent;
95
+ }
96
+ else if (Array.isArray(msgContent)) {
97
+ const texts = [];
98
+ for (const part of msgContent) {
99
+ if (typeof part === 'object' &&
100
+ part !== null &&
101
+ !Array.isArray(part) &&
102
+ part.type === 'text' &&
103
+ typeof part.text === 'string') {
104
+ const text = part.text;
105
+ if (text.trim() !== '')
106
+ texts.push(text);
107
+ }
108
+ }
109
+ const joined = texts.join('\n').trim();
110
+ if (joined !== '')
111
+ lastText = joined;
112
+ }
113
+ }
114
+ return lastText;
115
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Question-gate clause classification, compound splitting, and HUD format rules.
4
+ * Rules: Pure offline triage rules matching triage-question.py behavior.
5
+ * BigO: O(n^2) score:1
6
+ * keywords: [QuestionGateRules, BossGateFormat, CompoundSplit]
7
+ * GOAL: Classify draft questions/prompts into delegable skills, ledger auths, or human gates.
8
+ */
9
+ export interface LedgerState {
10
+ present: boolean;
11
+ commit_authorized: boolean;
12
+ missing_prereqs: string[];
13
+ }
14
+ export interface ClassifiedClause {
15
+ clause: string;
16
+ disposition: 'delegate_to_skill' | 'already_authorized' | 'human_approval_required' | 'needs_classification';
17
+ resolved_by: string;
18
+ role: string;
19
+ stage: string;
20
+ reason: string;
21
+ }
22
+ export interface HumanGateSummary {
23
+ clause: string;
24
+ role: string;
25
+ stage: string;
26
+ }
27
+ export interface TriageReport {
28
+ verdict: 'no_question' | 'allow_question' | 'block_question' | 'block_format';
29
+ ledger_checked: boolean;
30
+ clauses: ClassifiedClause[];
31
+ resolved_by: string[];
32
+ human_gates: HumanGateSummary[];
33
+ hud_format_ok: boolean;
34
+ rewrite_suggestion: string | null;
35
+ }
36
+ export type HookOutputFormat = 'json' | 'cursor-hook' | 'claude-hook' | 'codex-hook' | 'gemini-hook';
37
+ export declare function extractLedgerState(ledger: Record<string, unknown> | null): LedgerState;
38
+ export declare function evaluateQuestionText(rawText: string, ledger?: Record<string, unknown> | null, requireHud?: boolean): TriageReport;
39
+ export declare function pythonJsonCompact(value: unknown): string;
40
+ export declare function formatTriageOutput(report: TriageReport, format: HookOutputFormat): string;