@bbcsoftwarefactory/cli 0.1.0 → 1.1.2

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 (126) 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 +1250 -0
  5. package/dist/bbc.d.ts +2 -0
  6. package/dist/bbc.js +124 -0
  7. package/dist/bigo/complexity.d.ts +18 -0
  8. package/dist/bigo/complexity.js +139 -0
  9. package/dist/bigo/functions.d.ts +5 -0
  10. package/dist/bigo/functions.js +174 -0
  11. package/dist/bigo/keywords.d.ts +1 -0
  12. package/dist/bigo/keywords.js +43 -0
  13. package/dist/bigo/lexical.d.ts +14 -0
  14. package/dist/bigo/lexical.js +69 -0
  15. package/dist/bigo/source-files.d.ts +1 -0
  16. package/dist/bigo/source-files.js +80 -0
  17. package/dist/change-lane/classification.d.ts +41 -0
  18. package/dist/change-lane/classification.js +104 -0
  19. package/dist/change-lane/git.d.ts +8 -0
  20. package/dist/change-lane/git.js +105 -0
  21. package/dist/check-issue-claim.d.ts +2 -0
  22. package/dist/check-issue-claim.js +146 -0
  23. package/dist/check-worktree-guard.d.ts +2 -0
  24. package/dist/check-worktree-guard.js +114 -0
  25. package/dist/classify-change-lane.d.ts +2 -0
  26. package/dist/classify-change-lane.js +128 -0
  27. package/dist/diff-scope/git-diff.d.ts +25 -0
  28. package/dist/diff-scope/git-diff.js +146 -0
  29. package/dist/error-scan.d.ts +3 -0
  30. package/dist/error-scan.js +216 -0
  31. package/dist/export-public.d.ts +9 -0
  32. package/dist/export-public.js +274 -0
  33. package/dist/extract-diff-scope.d.ts +2 -0
  34. package/dist/extract-diff-scope.js +111 -0
  35. package/dist/fetch-issue-attachments.d.ts +22 -0
  36. package/dist/fetch-issue-attachments.js +325 -0
  37. package/dist/issue-claim/evaluation.d.ts +66 -0
  38. package/dist/issue-claim/evaluation.js +259 -0
  39. package/dist/issue-claim/loaders.d.ts +5 -0
  40. package/dist/issue-claim/loaders.js +116 -0
  41. package/dist/list-zed-commands.d.ts +7 -0
  42. package/dist/list-zed-commands.js +288 -0
  43. package/dist/measure-bigo.d.ts +2 -0
  44. package/dist/measure-bigo.js +84 -0
  45. package/dist/plan-issue-triage.d.ts +3 -0
  46. package/dist/plan-issue-triage.js +404 -0
  47. package/dist/question-gate/ledger.d.ts +5 -0
  48. package/dist/question-gate/ledger.js +115 -0
  49. package/dist/question-gate/rules.d.ts +40 -0
  50. package/dist/question-gate/rules.js +483 -0
  51. package/dist/recap/board.d.ts +5 -0
  52. package/dist/recap/board.js +384 -0
  53. package/dist/recap/git-and-github.d.ts +11 -0
  54. package/dist/recap/git-and-github.js +620 -0
  55. package/dist/recap/report-and-hud.d.ts +2 -0
  56. package/dist/recap/report-and-hud.js +294 -0
  57. package/dist/recap/time-and-refs.d.ts +27 -0
  58. package/dist/recap/time-and-refs.js +148 -0
  59. package/dist/recap.d.ts +2 -0
  60. package/dist/recap.js +217 -0
  61. package/dist/render-workflow.d.ts +2 -0
  62. package/dist/render-workflow.js +142 -0
  63. package/dist/resolve-containers.d.ts +2 -0
  64. package/dist/resolve-containers.js +96 -0
  65. package/dist/review-loop.d.ts +7 -0
  66. package/dist/review-loop.js +622 -0
  67. package/dist/save-counts.d.ts +2 -0
  68. package/dist/save-counts.js +191 -0
  69. package/dist/summarize-logs.d.ts +2 -0
  70. package/dist/summarize-logs.js +41 -0
  71. package/dist/sweep-github.d.ts +10 -0
  72. package/dist/sweep-github.js +453 -0
  73. package/dist/sweep-issues.d.ts +56 -0
  74. package/dist/sweep-issues.js +650 -0
  75. package/dist/sweep.d.ts +2 -0
  76. package/dist/sweep.js +301 -0
  77. package/dist/triage-question.d.ts +2 -0
  78. package/dist/triage-question.js +189 -0
  79. package/dist/validate-skills.d.ts +2 -0
  80. package/dist/validate-skills.js +48 -0
  81. package/dist/watch-live.d.ts +7 -0
  82. package/dist/watch-live.js +83 -0
  83. package/dist/watcher/config.d.ts +11 -0
  84. package/dist/watcher/config.js +265 -0
  85. package/dist/watcher/live-classifier.d.ts +52 -0
  86. package/dist/watcher/live-classifier.js +510 -0
  87. package/dist/watcher/safe-fs.d.ts +9 -0
  88. package/dist/watcher/safe-fs.js +159 -0
  89. package/dist/watcher/stream.d.ts +27 -0
  90. package/dist/watcher/stream.js +340 -0
  91. package/dist/watcher/summarizer.d.ts +19 -0
  92. package/dist/watcher/summarizer.js +121 -0
  93. package/dist/wave3/process.d.ts +14 -0
  94. package/dist/wave3/process.js +84 -0
  95. package/dist/wave4/process.d.ts +14 -0
  96. package/dist/wave4/process.js +128 -0
  97. package/dist/workflow/render.d.ts +13 -0
  98. package/dist/workflow/render.js +31 -0
  99. package/dist/workflow/schema.d.ts +25 -0
  100. package/dist/workflow/schema.js +99 -0
  101. package/dist/workflow-auditor/audit.d.ts +27 -0
  102. package/dist/workflow-auditor/audit.js +583 -0
  103. package/dist/workflow-auditor/ledger-io.d.ts +5 -0
  104. package/dist/workflow-auditor/ledger-io.js +99 -0
  105. package/dist/workflow-auditor/skills-validator.d.ts +10 -0
  106. package/dist/workflow-auditor/skills-validator.js +533 -0
  107. package/dist/worktree-guard/evaluation.d.ts +19 -0
  108. package/dist/worktree-guard/evaluation.js +84 -0
  109. package/dist/worktree-guard/git.d.ts +3 -0
  110. package/dist/worktree-guard/git.js +61 -0
  111. package/package.json +32 -33
  112. package/src/bbc.ts +0 -39
  113. package/src/bigo/complexity.ts +0 -138
  114. package/src/bigo/functions.ts +0 -183
  115. package/src/bigo/keywords.ts +0 -41
  116. package/src/bigo/lexical.ts +0 -68
  117. package/src/bigo/source-files.ts +0 -80
  118. package/src/change-lane/classification.ts +0 -128
  119. package/src/change-lane/git.ts +0 -110
  120. package/src/classify-change-lane.ts +0 -140
  121. package/src/diff-scope/git-diff.ts +0 -161
  122. package/src/extract-diff-scope.ts +0 -130
  123. package/src/measure-bigo.ts +0 -86
  124. package/src/render-workflow.ts +0 -144
  125. package/src/workflow/render.ts +0 -40
  126. package/src/workflow/schema.ts +0 -141
package/dist/sweep.js ADDED
@@ -0,0 +1,301 @@
1
+ /**
2
+ * LAYER: Application
3
+ * Contains: Orchestrator for /issue-clean-and-close (`plan` and `apply`) with state logging.
4
+ * Rules: Plan never writes to GitHub; apply rejects plans >60 min old or for another repo.
5
+ * BigO: O(n) score:4
6
+ * keywords: [SweepOrchestrator, PlanTtl, PolicyFetch, StateLog]
7
+ * GOAL: Run the two-step issue sweep workflow with local plan archiving and TTL guards.
8
+ */
9
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
10
+ import { homedir } from 'node:os';
11
+ import { basename, join } from 'node:path';
12
+ import { parseOnly, sweepApply, sweepFetch, SweepGithubUnusableError } from "./sweep-github.js";
13
+ import { evaluateSweepPlan, loadSnapshot, loadSweepConfig, SweepUnusableError } from "./sweep-issues.js";
14
+ import { parseCommandOverride, runCommand } from "./wave3/process.js";
15
+ export const sweepUsage = 'bbc sweep <plan|apply> [--repo <owner/repo>] [--keep 30 | --plan <file> [--only 12,15] [--dry-run]]';
16
+ const CONFIG_PATH = '.github/issue-sweeper.json';
17
+ const DEFAULT_KEEP = 30;
18
+ const PLAN_TTL_MS = 60 * 60 * 1000;
19
+ const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
20
+ const REMOTE_RE = /github\.com[:/]([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\/?$/;
21
+ const HELP = 'Usage: bbc sweep plan [--repo <owner/repo>] [--keep 30]\n' +
22
+ ' bbc sweep apply [--repo <owner/repo>] --plan <file> [--only 12,15] [--dry-run]\n' +
23
+ "Without --repo, the repository is the current checkout's origin on github.com.\n" +
24
+ `Needs an authenticated gh CLI. ${CONFIG_PATH} on the default branch is optional (thresholds).\n` +
25
+ 'State: ~/.issue-clean-and-close/<owner>__<repo>/ (SWEEP_HOME overrides it).\n' +
26
+ 'Exit 0: done; 1: some writes failed (listed); 2: unusable input, plan, or policy file.';
27
+ class UnusableError extends Error {
28
+ }
29
+ function formatUtcIso(date = new Date()) {
30
+ return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
31
+ }
32
+ function formatPlanStamp(date = new Date()) {
33
+ const iso = date.toISOString(); // YYYY-MM-DDTHH:MM:SS.sssZ
34
+ const basic = iso.replace(/[-:]/g, '').replace(/\.\d{3}Z$/, '');
35
+ const ms = String(date.getUTCMilliseconds()).padStart(3, '0');
36
+ const seq = String(Math.floor(Math.random() * 1000)).padStart(3, '0');
37
+ return `${basic}${ms}${seq}Z`;
38
+ }
39
+ function execCommand(argv) {
40
+ try {
41
+ const res = runCommand(argv);
42
+ return { code: res.code, stdout: res.stdout, stderr: res.stderr.slice(0, 500) };
43
+ }
44
+ catch (error) {
45
+ const msg = error instanceof Error ? error.message : String(error);
46
+ throw new UnusableError(`${argv[0]} is not available: ${msg}`);
47
+ }
48
+ }
49
+ function runGh(args) {
50
+ const cmd = parseCommandOverride('SWEEP_GH', 'gh');
51
+ return execCommand([...cmd, ...args]);
52
+ }
53
+ function detectRepo() {
54
+ const res = execCommand(['git', 'remote', 'get-url', 'origin']);
55
+ const match = res.code === 0 ? REMOTE_RE.exec(res.stdout.trim()) : null;
56
+ if (!match || !match[1]) {
57
+ throw new UnusableError('This is not a checkout with a github.com origin; pass --repo <owner/repo>.');
58
+ }
59
+ return match[1];
60
+ }
61
+ function stateDir(repo) {
62
+ const home = process.env.SWEEP_HOME || join(homedir(), '.issue-clean-and-close');
63
+ const dir = join(home, repo.replaceAll('/', '__'));
64
+ mkdirSync(dir, { recursive: true });
65
+ return dir;
66
+ }
67
+ function appendRunLog(state, entry) {
68
+ const line = JSON.stringify({ ...entry, at: formatUtcIso() });
69
+ appendFileSync(join(state, 'runs.log'), `${line}\n`, 'utf8');
70
+ }
71
+ function currentLogin() {
72
+ const res = runGh(['api', 'user', '--jq', '.login']);
73
+ if (res.code !== 0 || !res.stdout.trim()) {
74
+ throw new UnusableError(`gh is not authenticated: ${res.stderr}`);
75
+ }
76
+ return res.stdout.trim();
77
+ }
78
+ function fetchPolicy(repo, state) {
79
+ const res = runGh([
80
+ 'api',
81
+ '-H',
82
+ 'Accept: application/vnd.github.raw+json',
83
+ `repos/${repo}/contents/${CONFIG_PATH}`,
84
+ ]);
85
+ if (res.code !== 0) {
86
+ if (res.stderr.includes('404') || res.stderr.toLowerCase().includes('not found')) {
87
+ return null;
88
+ }
89
+ throw new UnusableError(`Cannot read ${CONFIG_PATH}: ${res.stderr}`);
90
+ }
91
+ let policy;
92
+ try {
93
+ policy = JSON.parse(res.stdout);
94
+ }
95
+ catch {
96
+ throw new UnusableError(`${CONFIG_PATH} on the default branch is not valid JSON.`);
97
+ }
98
+ const path = join(state, 'config.json');
99
+ writeFileSync(path, JSON.stringify(policy, null, 2), 'utf8');
100
+ return path;
101
+ }
102
+ function summarizeEntry(entry) {
103
+ const steps = entry.steps.map((s) => s.action + (s.label ? `:${s.label}` : '') + (s.state_reason ? `:${s.state_reason}` : ''));
104
+ return { issue: entry.issue, rule: entry.rule, url: entry.url, steps };
105
+ }
106
+ function runPlan(repo, keep) {
107
+ const state = stateDir(repo);
108
+ const login = currentLogin();
109
+ const configPath = fetchPolicy(repo, state);
110
+ const snapshotPath = join(state, 'snapshot.json');
111
+ let result;
112
+ try {
113
+ sweepFetch(repo, snapshotPath, login);
114
+ const config = loadSweepConfig(configPath ?? undefined, login);
115
+ const snapshot = loadSnapshot(snapshotPath);
116
+ result = evaluateSweepPlan(snapshot, config, Date.now());
117
+ }
118
+ catch (error) {
119
+ if (error instanceof SweepGithubUnusableError || error instanceof SweepUnusableError) {
120
+ const reason = error.message.slice(0, 500);
121
+ appendRunLog(state, { step: 'plan', repo, verdict: 'unusable', reason });
122
+ throw new UnusableError(`No plan: ${reason}`);
123
+ }
124
+ throw error;
125
+ }
126
+ const plansDir = join(state, 'plans');
127
+ mkdirSync(plansDir, { recursive: true });
128
+ let stamp = formatPlanStamp();
129
+ let planFile = join(plansDir, `${stamp}.json`);
130
+ const existing = new Set(readdirSync(plansDir));
131
+ while (existing.has(`${stamp}.json`)) {
132
+ stamp = formatPlanStamp();
133
+ planFile = join(plansDir, `${stamp}.json`);
134
+ }
135
+ writeFileSync(planFile, JSON.stringify(result, null, 2), 'utf8');
136
+ const jsonFiles = readdirSync(plansDir)
137
+ .filter((name) => name.endsWith('.json'))
138
+ .sort();
139
+ if (jsonFiles.length > keep) {
140
+ for (const old of jsonFiles.slice(0, jsonFiles.length - keep)) {
141
+ unlinkSync(join(plansDir, old));
142
+ }
143
+ }
144
+ writeFileSync(join(state, 'report.md'), `${result.report_markdown}\n`, 'utf8');
145
+ appendRunLog(state, {
146
+ step: 'plan',
147
+ repo,
148
+ run_by: login,
149
+ plan: basename(planFile),
150
+ actions: result.actions.length,
151
+ deferred: result.deferred.length,
152
+ gaps: result.gaps.length,
153
+ });
154
+ return [
155
+ {
156
+ verdict: 'planned',
157
+ repo,
158
+ run_by: login,
159
+ plan: planFile,
160
+ config: configPath ? CONFIG_PATH : 'defaults',
161
+ report_issue: result.report_issue,
162
+ actions: result.actions.map((entry) => summarizeEntry(entry)),
163
+ deferred: result.deferred.map((entry) => entry.issue),
164
+ report_only: result.report_only.map((entry) => ({ issue: entry.issue, rule: entry.rule })),
165
+ gaps: result.gaps,
166
+ metrics: result.metrics,
167
+ report_markdown: result.report_markdown,
168
+ },
169
+ 0,
170
+ ];
171
+ }
172
+ function checkPlanFile(planPath, repo) {
173
+ let data;
174
+ try {
175
+ data = JSON.parse(readFileSync(planPath, 'utf8'));
176
+ }
177
+ catch {
178
+ throw new UnusableError('The plan file cannot be read as JSON.');
179
+ }
180
+ const generated = data !== null && typeof data === 'object' && !Array.isArray(data)
181
+ ? data.generated_at
182
+ : null;
183
+ const generatedStr = String(generated ?? '');
184
+ const normalized = generatedStr.endsWith('Z') || /[+-]\d{2}:\d{2}$/.test(generatedStr) ? generatedStr : `${generatedStr}Z`;
185
+ const generatedMs = Date.parse(normalized);
186
+ if (!Number.isFinite(generatedMs)) {
187
+ throw new UnusableError('The plan has no generated_at; run plan again.');
188
+ }
189
+ if (Date.now() - generatedMs > PLAN_TTL_MS) {
190
+ throw new UnusableError('The plan is older than 60 minutes; run plan again and approve the new one.');
191
+ }
192
+ const planRepo = data !== null && typeof data === 'object' && !Array.isArray(data)
193
+ ? data.repo
194
+ : null;
195
+ if (String(planRepo ?? '').toLowerCase() !== repo.toLowerCase()) {
196
+ throw new UnusableError(`The plan is for ${String(planRepo)}, not ${repo}.`);
197
+ }
198
+ }
199
+ function runApply(repo, planPath, onlyRaw, dryRun) {
200
+ const state = stateDir(repo);
201
+ checkPlanFile(planPath, repo);
202
+ let result;
203
+ let code;
204
+ try {
205
+ const onlySet = onlyRaw ? parseOnly(onlyRaw) : null;
206
+ [result, code] = sweepApply(repo, planPath, dryRun, onlySet);
207
+ }
208
+ catch (error) {
209
+ if (error instanceof SweepGithubUnusableError) {
210
+ throw new UnusableError(error.message);
211
+ }
212
+ throw error;
213
+ }
214
+ const numbers = onlyRaw
215
+ ? onlyRaw
216
+ .split(',')
217
+ .map((item) => item.trim().replace(/^#+/, ''))
218
+ .filter((item) => item.length > 0)
219
+ .map((item) => Number.parseInt(item, 10))
220
+ .sort((a, b) => a - b)
221
+ : null;
222
+ const appliedList = result.applied ?? result.writes ?? [];
223
+ appendRunLog(state, {
224
+ step: 'apply',
225
+ repo,
226
+ plan: basename(planPath),
227
+ only: numbers,
228
+ dry_run: dryRun,
229
+ applied: appliedList.length,
230
+ errors: result.errors ?? [],
231
+ });
232
+ return [result, code];
233
+ }
234
+ function parseArgs(argv) {
235
+ if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h' || argv.includes('--help')) {
236
+ return null;
237
+ }
238
+ const command = argv[0];
239
+ if (command !== 'plan' && command !== 'apply') {
240
+ throw new UnusableError(`Unknown command: ${command} (plan or apply).`);
241
+ }
242
+ const rest = argv.slice(1);
243
+ const allowed = command === 'plan' ? new Set(['--repo', '--keep']) : new Set(['--repo', '--plan', '--only']);
244
+ const values = { keep: String(DEFAULT_KEEP) };
245
+ let dryRun = false;
246
+ for (let idx = 0; idx < rest.length;) {
247
+ const key = rest[idx];
248
+ const value = rest[idx + 1];
249
+ if (key === '--dry-run' && command === 'apply') {
250
+ dryRun = true;
251
+ idx += 1;
252
+ }
253
+ else if (allowed.has(key) && value !== undefined) {
254
+ values[key.slice(2)] = value;
255
+ idx += 2;
256
+ }
257
+ else {
258
+ throw new UnusableError(`Unknown or incomplete argument for ${command}: ${key}`);
259
+ }
260
+ }
261
+ if (values.repo !== undefined && !REPO_RE.test(values.repo)) {
262
+ throw new UnusableError('--repo must be owner/name.');
263
+ }
264
+ const keepRaw = values.keep ?? String(DEFAULT_KEEP);
265
+ if (!/^\d+$/.test(keepRaw) || Number.parseInt(keepRaw, 10) < 1) {
266
+ throw new UnusableError('--keep must be a positive integer.');
267
+ }
268
+ if (command === 'apply' && !('plan' in values)) {
269
+ throw new UnusableError('apply needs --plan: the exact plan file the person approved.');
270
+ }
271
+ return {
272
+ command,
273
+ repo: values.repo,
274
+ keep: Number.parseInt(keepRaw, 10),
275
+ plan: values.plan,
276
+ only: values.only,
277
+ dryRun,
278
+ };
279
+ }
280
+ export function sweep(argv) {
281
+ try {
282
+ const args = parseArgs(argv);
283
+ if (args === null) {
284
+ process.stdout.write(`${HELP}\n`);
285
+ return 0;
286
+ }
287
+ const repo = args.repo ?? detectRepo();
288
+ const [result, code] = args.command === 'plan'
289
+ ? runPlan(repo, args.keep)
290
+ : runApply(repo, args.plan, args.only, args.dryRun);
291
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
292
+ return code;
293
+ }
294
+ catch (error) {
295
+ if (error instanceof UnusableError) {
296
+ process.stdout.write(`${JSON.stringify({ verdict: 'unusable', reason: error.message })}\n`);
297
+ return 2;
298
+ }
299
+ throw error;
300
+ }
301
+ }
@@ -0,0 +1,2 @@
1
+ export declare const triageQuestionUsage = "bbc triage-question [--question <text> | --stdin] [--ledger <file> | --no-ledger] [--require-hud] [--no-hud] [--format json|cursor-hook|claude-hook|codex-hook|gemini-hook]";
2
+ export declare function triageQuestion(argv: readonly string[]): number;
@@ -0,0 +1,189 @@
1
+ /**
2
+ * LAYER: Interface
3
+ * Contains: CLI entry point, stdin payload extraction, and output rendering for triage-question.
4
+ * Rules: Match triage-question.py stdout/stderr/exit codes byte-for-byte.
5
+ * BigO: O(n) score:3
6
+ * keywords: [TriageQuestionCli, HookPayload]
7
+ * GOAL: Run Question Gate triage on draft questions or client stop-hook payloads.
8
+ */
9
+ import { readFileSync } from 'node:fs';
10
+ import { EOL } from 'node:os';
11
+ import { parseJsonText } from '@bbcsoftwarefactory/cli-core/python-json';
12
+ import { findDefaultLedger, loadLedger, readLastAssistantFromTranscript, UnusableQuestionInputError, } from "./question-gate/ledger.js";
13
+ import { evaluateQuestionText, formatTriageOutput, pythonJsonCompact, } from "./question-gate/rules.js";
14
+ export const triageQuestionUsage = 'bbc triage-question [--question <text> | --stdin] [--ledger <file> | --no-ledger] [--require-hud] [--no-hud] [--format json|cursor-hook|claude-hook|codex-hook|gemini-hook]';
15
+ const VALID_FORMATS = new Set(['json', 'cursor-hook', 'claude-hook', 'codex-hook', 'gemini-hook']);
16
+ const HELP = 'usage: bbc triage-question [-h] [--question QUESTION] [--stdin]\n' +
17
+ ' [--ledger LEDGER] [--no-ledger] [--require-hud]\n' +
18
+ ' [--no-hud]\n' +
19
+ ' [--format {json,cursor-hook,claude-hook,codex-hook,gemini-hook}]\n\n' +
20
+ 'Check whether a proposed question can be resolved by a diagram skill before\n' +
21
+ 'asking the user.\n\n' +
22
+ 'options:\n' +
23
+ ' -h, --help show this help message and exit\n' +
24
+ ' --question QUESTION Proposed question or draft assistant message.\n' +
25
+ ' --stdin Read question or hook JSON payload from stdin.\n' +
26
+ ' --ledger LEDGER Path to bbc-delivery-ledger.json.\n' +
27
+ ' --no-ledger Skip auto-discovering bbc-delivery-ledger.json.\n' +
28
+ ' --require-hud Require Quest-Tree 🟡 BOSS GATE formatting for human\n' +
29
+ ' decisions and choice offers.\n' +
30
+ ' --no-hud Disable 🟡 BOSS GATE format enforcement in client hook\n' +
31
+ ' modes.\n' +
32
+ ' --format {json,cursor-hook,claude-hook,codex-hook,gemini-hook}\n' +
33
+ ' Output format (default: json).';
34
+ function writeLine(text) {
35
+ process.stdout.write(`${text.replaceAll('\n', EOL)}${EOL}`);
36
+ }
37
+ function parseArgs(argv) {
38
+ const parsed = {
39
+ useStdin: false,
40
+ noLedger: false,
41
+ requireHud: false,
42
+ noHud: false,
43
+ format: 'json',
44
+ };
45
+ for (let i = 0; i < argv.length; i++) {
46
+ const arg = argv[i] ?? '';
47
+ if (arg === '-h' || arg === '--help')
48
+ return 'help';
49
+ if (arg === '--stdin') {
50
+ parsed.useStdin = true;
51
+ continue;
52
+ }
53
+ if (arg === '--no-ledger') {
54
+ parsed.noLedger = true;
55
+ continue;
56
+ }
57
+ if (arg === '--require-hud') {
58
+ parsed.requireHud = true;
59
+ continue;
60
+ }
61
+ if (arg === '--no-hud') {
62
+ parsed.noHud = true;
63
+ continue;
64
+ }
65
+ if (arg === '--question' || arg === '--ledger' || arg === '--format') {
66
+ const value = argv[i + 1];
67
+ if (value === undefined) {
68
+ process.stderr.write(`error: argument ${arg}: expected one argument${EOL}`);
69
+ return 'error';
70
+ }
71
+ if (arg === '--question')
72
+ parsed.question = value;
73
+ else if (arg === '--ledger')
74
+ parsed.ledger = value;
75
+ else {
76
+ if (!VALID_FORMATS.has(value)) {
77
+ process.stderr.write(`error: invalid --format value: ${value}${EOL}`);
78
+ return 'error';
79
+ }
80
+ parsed.format = value;
81
+ }
82
+ i++;
83
+ continue;
84
+ }
85
+ process.stderr.write(`error: unrecognized arguments: ${arg}${EOL}`);
86
+ return 'error';
87
+ }
88
+ return parsed;
89
+ }
90
+ function extractInputFromStdin(rawStdin) {
91
+ const trimmed = rawStdin.trim();
92
+ if (trimmed === '')
93
+ return { text: '', shouldSkip: false };
94
+ if (trimmed.startsWith('{')) {
95
+ let payload;
96
+ try {
97
+ payload = parseJsonText(trimmed);
98
+ }
99
+ catch (error) {
100
+ const message = error instanceof Error ? error.message : String(error);
101
+ throw new UnusableQuestionInputError(`Malformed JSON payload on stdin: ${message}`);
102
+ }
103
+ if (typeof payload === 'object' && payload !== null && !Array.isArray(payload)) {
104
+ const obj = payload;
105
+ if (obj.stop_hook_active === true)
106
+ return { text: '', shouldSkip: true };
107
+ if (typeof obj.status === 'string' && obj.status !== 'completed')
108
+ return { text: '', shouldSkip: true };
109
+ if (typeof obj.loop_count === 'number' && Number.isInteger(obj.loop_count) && obj.loop_count >= 2) {
110
+ return { text: '', shouldSkip: true };
111
+ }
112
+ for (const key of [
113
+ 'last_assistant_message',
114
+ 'prompt_response',
115
+ 'assistant_message',
116
+ 'message',
117
+ 'question',
118
+ 'text',
119
+ ]) {
120
+ const value = obj[key];
121
+ if (typeof value === 'string' && value.trim() !== '')
122
+ return { text: value, shouldSkip: false };
123
+ }
124
+ return { text: readLastAssistantFromTranscript(obj.transcript_path), shouldSkip: false };
125
+ }
126
+ return { text: '', shouldSkip: false };
127
+ }
128
+ return { text: rawStdin, shouldSkip: false };
129
+ }
130
+ export function triageQuestion(argv) {
131
+ const parsed = parseArgs(argv);
132
+ if (parsed === 'help') {
133
+ writeLine(HELP);
134
+ return 0;
135
+ }
136
+ if (parsed === 'error')
137
+ return 2;
138
+ let rawText = '';
139
+ if (parsed.question !== undefined) {
140
+ rawText = parsed.question;
141
+ }
142
+ else if (parsed.useStdin) {
143
+ try {
144
+ const extracted = extractInputFromStdin(readFileSync(0, 'utf8'));
145
+ if (extracted.shouldSkip) {
146
+ writeLine(formatTriageOutput({
147
+ verdict: 'no_question',
148
+ ledger_checked: false,
149
+ clauses: [],
150
+ resolved_by: [],
151
+ human_gates: [],
152
+ hud_format_ok: true,
153
+ rewrite_suggestion: null,
154
+ }, parsed.format));
155
+ return 0;
156
+ }
157
+ rawText = extracted.text;
158
+ }
159
+ catch (error) {
160
+ const detail = error instanceof UnusableQuestionInputError ? error.message : String(error);
161
+ writeLine(pythonJsonCompact({ verdict: 'unusable', detail }));
162
+ return 2;
163
+ }
164
+ }
165
+ else {
166
+ writeLine(pythonJsonCompact({ verdict: 'unusable', detail: 'Pass --question "..." or --stdin.' }));
167
+ return 2;
168
+ }
169
+ let ledger = null;
170
+ try {
171
+ if (!parsed.noLedger) {
172
+ const ledgerPath = parsed.ledger ?? findDefaultLedger();
173
+ if (ledgerPath !== undefined)
174
+ ledger = loadLedger(ledgerPath);
175
+ }
176
+ }
177
+ catch (error) {
178
+ const detail = error instanceof UnusableQuestionInputError ? error.message : String(error);
179
+ writeLine(pythonJsonCompact({ verdict: 'unusable', detail }));
180
+ return 2;
181
+ }
182
+ const requireHud = parsed.requireHud || (parsed.format !== 'json' && !parsed.noHud);
183
+ const report = evaluateQuestionText(rawText, ledger, requireHud);
184
+ writeLine(formatTriageOutput(report, parsed.format));
185
+ if (parsed.format === 'json' && (report.verdict === 'block_question' || report.verdict === 'block_format')) {
186
+ return 1;
187
+ }
188
+ return 0;
189
+ }
@@ -0,0 +1,2 @@
1
+ export declare const validateSkillsUsage = "bbc validate-skills [repo-root] [--release-tag v<VERSION>]";
2
+ export declare function validateSkills(argv: readonly string[]): number;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * LAYER: Interface
3
+ * Contains: CLI entry point and JSON formatting for validate-skills.
4
+ * Rules: Match validate-skills.py stdout and exit codes byte-for-byte.
5
+ * BigO: O(1) score:5
6
+ * keywords: [ValidateSkillsCli, ReleaseTagCheck]
7
+ * GOAL: Run repository skill, catalog, link, diagram, and release-tag validation from bbc.
8
+ */
9
+ import { EOL } from 'node:os';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { pythonRepr } from '@bbcsoftwarefactory/cli-core/python-compat';
12
+ import { readPackageVersion, validateRepo } from "./workflow-auditor/skills-validator.js";
13
+ export const validateSkillsUsage = 'bbc validate-skills [repo-root] [--release-tag v<VERSION>]';
14
+ const HELP = 'Usage: bbc validate-skills [repo-root] [--release-tag v<VERSION>]\n' +
15
+ 'Checks skills/*/SKILL.md and commands/*/SKILL.md frontmatter, referenced ' +
16
+ 'scripts/adapters, compatibility on scripted skills, aggregate frontmatter size, ' +
17
+ 'relative Markdown links, the Tool Depot catalog shape and protocol paths, and ' +
18
+ 'that every cited catalog purpose exists.';
19
+ function escapeAscii(text) {
20
+ return text.replace(/[\u007f-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
21
+ }
22
+ function writeOut(text) {
23
+ process.stdout.write(`${text.replaceAll('\n', EOL)}${EOL}`);
24
+ }
25
+ export function validateSkills(argv) {
26
+ const args = [...argv];
27
+ if (args.length > 0 && (args[0] === '-h' || args[0] === '--help')) {
28
+ writeOut(HELP);
29
+ return 0;
30
+ }
31
+ let tag = null;
32
+ if (args.length >= 2 && args.at(-2) === '--release-tag') {
33
+ tag = args.at(-1);
34
+ args.splice(args.length - 2, 2);
35
+ }
36
+ const root = args.length > 0 ? args[0] : fileURLToPath(new URL('../../..', import.meta.url));
37
+ const report = validateRepo(root);
38
+ if (tag !== null) {
39
+ const version = readPackageVersion(root);
40
+ const versionRepr = version === null ? 'None' : pythonRepr(version);
41
+ if (version === null || tag !== `v${version}`) {
42
+ report.errors.push(`release tag ${pythonRepr(tag)} does not match VERSION ${versionRepr} (expected v<VERSION>)`);
43
+ report.verdict = 'fail';
44
+ }
45
+ }
46
+ writeOut(escapeAscii(JSON.stringify(report, null, 2)));
47
+ return report.verdict === 'pass' ? 0 : 1;
48
+ }
@@ -0,0 +1,7 @@
1
+ import { type SleuthEvidence } from './watcher/live-classifier.ts';
2
+ export declare const watchLiveUsage = "bbc watch-live [--sleuth] <ssh-alias> <exact-container>";
3
+ export declare function captureLive(alias: string, container: string, sleuthRequested: boolean): Promise<{
4
+ rows: string[];
5
+ evidence: SleuthEvidence | null;
6
+ } | null>;
7
+ export declare function watchLive(argv: readonly string[]): Promise<number>;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * LAYER: Interface
3
+ * Contains: CLI entry point for bbc watch-live.
4
+ * Rules: Match watch-live.py help, error text, 4x15s windows, and --sleuth JSON output.
5
+ * BigO: O(n) score:3
6
+ * keywords: [WatchLiveCli, SleuthLive]
7
+ * GOAL: Stream 60 seconds of live container logs without writing to disk.
8
+ */
9
+ import { EOL } from 'node:os';
10
+ import { aliasPattern, ConfigError, CONTAINER_RE, resolveSshExecutable, SSH_OPTIONS } from "./watcher/config.js";
11
+ import { liveOutput, observeWithStream } from "./watcher/live-classifier.js";
12
+ import { ProcessLogStream } from "./watcher/stream.js";
13
+ export const watchLiveUsage = 'bbc watch-live [--sleuth] <ssh-alias> <exact-container>';
14
+ const INVALID = 'Watcher live mode requires a valid SSH alias and exact container name or ID.';
15
+ const FAILED = 'Watcher live capture failed; no counts.';
16
+ const HELP = 'Usage: bbc watch-live <ssh-alias> <exact-container>\n' +
17
+ 'Observe one authorized container for 60 seconds; report four 15-second windows.';
18
+ const SLEUTH_HELP = 'Usage: bbc watch-live --sleuth <ssh-alias> <exact-container>\n' +
19
+ 'Add bounded, redacted evidence to the live summary; no raw IDs or logs.';
20
+ function writeOut(text) {
21
+ process.stdout.write(`${text.replaceAll('\n', EOL)}${EOL}`);
22
+ }
23
+ function writeErr(text) {
24
+ process.stderr.write(`${text.replaceAll('\n', EOL)}${EOL}`);
25
+ }
26
+ export async function captureLive(alias, container, sleuthRequested) {
27
+ if (!aliasPattern().test(alias) || !CONTAINER_RE.test(container)) {
28
+ throw new TypeError(INVALID);
29
+ }
30
+ const ssh = resolveSshExecutable();
31
+ if (ssh === null)
32
+ return null;
33
+ const stream = new ProcessLogStream(ssh, [
34
+ ...SSH_OPTIONS,
35
+ alias,
36
+ 'docker',
37
+ 'logs',
38
+ '-f',
39
+ '--tail=0',
40
+ '--',
41
+ container,
42
+ ]);
43
+ return observeWithStream(stream, sleuthRequested, () => performance.now() / 1000);
44
+ }
45
+ export async function watchLive(argv) {
46
+ let args = [...argv];
47
+ if (args.length === 1 && args[0] === '--help') {
48
+ writeOut(HELP);
49
+ return 0;
50
+ }
51
+ const sleuthRequested = args[0] === '--sleuth';
52
+ if (sleuthRequested) {
53
+ args = args.slice(1);
54
+ if (args.length === 1 && args[0] === '--help') {
55
+ writeOut(SLEUTH_HELP);
56
+ return 0;
57
+ }
58
+ }
59
+ if (args.length !== 2) {
60
+ writeErr(INVALID);
61
+ return 1;
62
+ }
63
+ let result;
64
+ try {
65
+ result = await captureLive(args[0], args[1], sleuthRequested);
66
+ }
67
+ catch (error) {
68
+ if (error instanceof ConfigError) {
69
+ writeErr(error.message);
70
+ return 1;
71
+ }
72
+ writeErr(INVALID);
73
+ return 1;
74
+ }
75
+ if (result === null) {
76
+ writeErr(FAILED);
77
+ return 1;
78
+ }
79
+ for (const line of liveOutput(result.rows, result.evidence)) {
80
+ writeOut(line);
81
+ }
82
+ return 0;
83
+ }
@@ -0,0 +1,11 @@
1
+ export declare class ConfigError extends Error {
2
+ }
3
+ export declare const CONTAINER_RE: RegExp;
4
+ export declare const SSH_OPTIONS: readonly ["-nT", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", "-o", "UpdateHostKeys=no", "-o", "ClearAllForwardings=yes", "-o", "PermitLocalCommand=no", "-o", "ControlPath=none"];
5
+ export declare function gitRoot(start: string): string | null;
6
+ export declare function configPath(cwd?: string): string;
7
+ export declare function strictJsonParse(text: string): unknown;
8
+ export declare function aliasPrefixes(cwd?: string): string[];
9
+ export declare function aliasPattern(cwd?: string): RegExp;
10
+ export declare function resolveSshExecutable(): string | null;
11
+ export declare function readFileUtf8IfSmall(path: string): string;