@bbcsoftwarefactory/cli 0.1.0 → 0.1.1

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 (46) hide show
  1. package/dist/bbc.d.ts +2 -0
  2. package/dist/bbc.js +40 -0
  3. package/dist/bigo/complexity.d.ts +18 -0
  4. package/dist/bigo/complexity.js +139 -0
  5. package/dist/bigo/functions.d.ts +5 -0
  6. package/dist/bigo/functions.js +174 -0
  7. package/dist/bigo/keywords.d.ts +1 -0
  8. package/dist/bigo/keywords.js +43 -0
  9. package/dist/bigo/lexical.d.ts +14 -0
  10. package/dist/bigo/lexical.js +69 -0
  11. package/dist/bigo/source-files.d.ts +1 -0
  12. package/dist/bigo/source-files.js +80 -0
  13. package/dist/change-lane/classification.d.ts +41 -0
  14. package/dist/change-lane/classification.js +102 -0
  15. package/dist/change-lane/git.d.ts +8 -0
  16. package/dist/change-lane/git.js +105 -0
  17. package/dist/classify-change-lane.d.ts +2 -0
  18. package/dist/classify-change-lane.js +128 -0
  19. package/dist/diff-scope/git-diff.d.ts +25 -0
  20. package/dist/diff-scope/git-diff.js +146 -0
  21. package/dist/extract-diff-scope.d.ts +2 -0
  22. package/dist/extract-diff-scope.js +111 -0
  23. package/dist/measure-bigo.d.ts +2 -0
  24. package/dist/measure-bigo.js +84 -0
  25. package/dist/render-workflow.d.ts +2 -0
  26. package/dist/render-workflow.js +144 -0
  27. package/dist/workflow/render.d.ts +13 -0
  28. package/dist/workflow/render.js +31 -0
  29. package/dist/workflow/schema.d.ts +25 -0
  30. package/dist/workflow/schema.js +99 -0
  31. package/package.json +7 -7
  32. package/src/bbc.ts +0 -39
  33. package/src/bigo/complexity.ts +0 -138
  34. package/src/bigo/functions.ts +0 -183
  35. package/src/bigo/keywords.ts +0 -41
  36. package/src/bigo/lexical.ts +0 -68
  37. package/src/bigo/source-files.ts +0 -80
  38. package/src/change-lane/classification.ts +0 -128
  39. package/src/change-lane/git.ts +0 -110
  40. package/src/classify-change-lane.ts +0 -140
  41. package/src/diff-scope/git-diff.ts +0 -161
  42. package/src/extract-diff-scope.ts +0 -130
  43. package/src/measure-bigo.ts +0 -86
  44. package/src/render-workflow.ts +0 -144
  45. package/src/workflow/render.ts +0 -40
  46. package/src/workflow/schema.ts +0 -141
@@ -1,140 +0,0 @@
1
- /**
2
- * LAYER: Interface
3
- * Contains: Change-lane command parsing and output formatting.
4
- * Rules: Emit the legacy report format, with native CLI help and read-only Git arguments.
5
- * BigO: O(n) score:3
6
- * keywords: [ClassifyChangeLane, LaneArguments]
7
- * GOAL: Translate a local change selection into a lane report and process status.
8
- */
9
- import { EOL } from 'node:os';
10
- import { classify, type LaneReport } from './change-lane/classification.ts';
11
- import { readGitChanges, type GitSelection } from './change-lane/git.ts';
12
-
13
- export const classifyChangeLaneUsage =
14
- 'bbc classify-change-lane [--working|--staged|--range A..B|--head N|--files <p1>...] [--format json|hud]';
15
-
16
- type Selection = GitSelection | { mode: 'files'; files: string[] };
17
- type Format = 'json' | 'hud';
18
- type Parsed =
19
- | { kind: 'help' }
20
- | { kind: 'error'; message: string }
21
- | { kind: 'run'; selection: Selection; format: Format };
22
-
23
- function error(message: string): Parsed {
24
- return { kind: 'error', message };
25
- }
26
-
27
- function explicitPaths(args: readonly string[], from: number): { files: string[]; next: number } {
28
- const files: string[] = [];
29
- let next = from;
30
- while (next < args.length) {
31
- const path = args[next];
32
- if (path === undefined || path.startsWith('--')) break;
33
- files.push(path);
34
- next++;
35
- }
36
- return { files, next };
37
- }
38
-
39
- const selectionFlags = new Set(['--working', '--staged', '--range', '--head', '--files']);
40
-
41
- function selectionError(selection: Selection): string | undefined {
42
- if (selection.mode === 'head' && !/^[1-9][0-9]*$/.test(selection.value)) {
43
- return `--head requires a positive integer: ${selection.value}`;
44
- }
45
- if (selection.mode === 'range' && selection.value.startsWith('-')) {
46
- return '--range must not start with -';
47
- }
48
- if (selection.mode === 'files' && selection.files.length === 0) {
49
- return '--files requires at least one path';
50
- }
51
- return undefined;
52
- }
53
-
54
- function replacementError(selection: Selection | undefined, flag: string | undefined): string | undefined {
55
- if (!selection || !flag || !selectionFlags.has(flag)) return undefined;
56
- if (flag !== `--${selection.mode}`) return `cannot combine --${selection.mode} with ${flag}`;
57
- // Keep the existing conflict diagnostic, but never let a same-mode flag hide an invalid value.
58
- return selectionError(selection);
59
- }
60
-
61
- function parse(args: readonly string[]): Parsed {
62
- let selection: Selection | undefined;
63
- let format: Format | undefined;
64
- for (let i = 0; i < args.length; i++) {
65
- const arg = args[i];
66
- const value = args[i + 1];
67
- const invalidReplacement = replacementError(selection, arg);
68
- if (invalidReplacement !== undefined) return error(invalidReplacement);
69
- switch (arg) {
70
- case '-h':
71
- case '--help':
72
- return { kind: 'help' };
73
- case '--working':
74
- case '--staged':
75
- selection = { mode: arg === '--working' ? 'working' : 'staged' };
76
- break;
77
- case '--range':
78
- case '--head':
79
- if (!value) return error(`${arg} requires an argument`);
80
- selection = { mode: arg === '--range' ? 'range' : 'head', value };
81
- i++;
82
- break;
83
- case '--files': {
84
- const { files, next } = explicitPaths(args, i + 1);
85
- selection = { mode: 'files', files };
86
- i = next - 1;
87
- break;
88
- }
89
- case '--format':
90
- if (format !== undefined) return error('--format may only be specified once');
91
- if (value !== 'json' && value !== 'hud') return error('--format must be json or hud');
92
- format = value;
93
- i++;
94
- break;
95
- default:
96
- return error(`unknown option: ${arg}`);
97
- }
98
- }
99
-
100
- selection ??= { mode: 'working' };
101
- const invalidSelection = selectionError(selection);
102
- if (invalidSelection !== undefined) return error(invalidSelection);
103
- return { kind: 'run', selection, format: format ?? 'json' };
104
- }
105
-
106
- const badges = { trivial: '🟢', standard: '🟡', 'high-risk': '🔴' };
107
-
108
- function formatReport(report: LaneReport, format: Format): string {
109
- if (format === 'hud') {
110
- const { lane, files_changed: files, lines_changed: lines, reasons } = report;
111
- return `🛣️ Lane: ${badges[lane]} ${lane} (${files} files, ${lines} lines) — ${reasons[0] ?? ''}`;
112
- }
113
- // Python json.dumps defaults to ASCII and escapes even DEL.
114
- return JSON.stringify(report, null, 2).replace(/[\u007f-\uffff]/g, (char) =>
115
- `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
116
- }
117
-
118
- function fail(message: string, status: number): number {
119
- process.stderr.write(`error: ${message}\n`.replaceAll('\n', EOL));
120
- return status;
121
- }
122
-
123
- export function classifyChangeLane(args: readonly string[]): number {
124
- const parsed = parse(args);
125
- if (parsed.kind === 'help') {
126
- process.stdout.write(`Usage: ${classifyChangeLaneUsage}\nClassifies a change into trivial, standard, or high-risk.\n`
127
- + 'Do not combine different selection modes or repeat --format.\n');
128
- return 0;
129
- }
130
- if (parsed.kind === 'error') return fail(parsed.message, 1);
131
-
132
- const { selection, format } = parsed;
133
- const change = selection.mode === 'files'
134
- ? { files: selection.files, added: 0, removed: 0 }
135
- : readGitChanges(selection);
136
- if (change === undefined) return fail('failed to inspect git diff', 2);
137
- const report = classify(change, process.platform === 'win32');
138
- process.stdout.write(`${formatReport(report, format)}\n`);
139
- return 0;
140
- }
@@ -1,161 +0,0 @@
1
- /**
2
- * LAYER: Infrastructure
3
- * Contains: Git diff scope collection.
4
- * Rules: Keep bytes intact with a latin1 round-trip and never rewrite git output.
5
- * BigO: O(n) score:3
6
- * keywords: [DiffScope, HunkParsing]
7
- * GOAL: Turn a local Git diff into the sections the quality gate consumes.
8
- */
9
- import { spawnSync } from 'node:child_process';
10
- import { statSync } from 'node:fs';
11
- import { readFileSync } from 'node:fs';
12
-
13
- const codePattern = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/;
14
- const excludedPattern = /(^|\/)(dist|node_modules|graphify-out|\.next|\.vite|build|\.vercel|coverage)\/|^prisma\/generated\/|^server\/dist\//;
15
-
16
- export const gates: readonly (readonly [string, RegExp | null])[] = [
17
- ['records', null],
18
- ['typesafe_candidates', /(:\s*any([^A-Za-z0-9_]|$)|\sas\s+any([^A-Za-z0-9_]|$)|\sas\s+[A-Za-z_]|!\.|!\[|@ts-ignore|@ts-expect-error|@ts-nocheck|<any>)/],
19
- ['earlyreturn_candidates', /(}\s*else(\s|$)|else\s+if\s*\(|^\s{12,}(if|for|while)\s*\(|\.then\s*\(|^\s*[?:]\s*(await\s+)?[A-Za-z0-9_$.]+\()/],
20
- ['bigo_candidates', /(\.(forEach|map|filter|find|some|includes|indexOf|reduce)\s*\(|for\s*\(|while\s*\(|\.\.\.acc)/],
21
- ];
22
-
23
- export type Mode = 'working' | 'staged' | 'range' | 'head';
24
-
25
- export interface ScopeRequest {
26
- mode: Mode;
27
- value: string;
28
- }
29
-
30
- export interface Record {
31
- path: string;
32
- line: number;
33
- content: string;
34
- }
35
-
36
- const decode = (buffer: Buffer): string => buffer.toString('latin1');
37
-
38
- function git(args: readonly string[], quiet: boolean): { stdout: Buffer; status: number } {
39
- const result = spawnSync('git', [...args], {
40
- stdio: ['ignore', 'pipe', quiet ? 'ignore' : 'inherit'],
41
- });
42
- if (result.error !== undefined || result.stdout === null) return { stdout: Buffer.alloc(0), status: 1 };
43
- return { stdout: result.stdout, status: result.status ?? 1 };
44
- }
45
-
46
- export function isTarget(path: string): boolean {
47
- return codePattern.test(path) && !excludedPattern.test(path);
48
- }
49
-
50
- export function yamlEscape(value: string): string {
51
- const parts = value.split('\n');
52
- if (parts.length > 1 && parts.at(-1) === '') parts.pop();
53
- return parts.map((part) => part.replaceAll('\\', '\\\\').replaceAll('"', '\\"')).join('\\n');
54
- }
55
-
56
- export function awkQuote(value: string): string {
57
- return value.replaceAll('\\', '\\\\').replaceAll('"', '\\"');
58
- }
59
-
60
- function recordsOf(lines: readonly string[]): readonly string[] {
61
- return lines.length > 0 && lines.at(-1) === '' ? lines.slice(0, -1) : lines;
62
- }
63
-
64
- export function diffArgs(request: ScopeRequest, hasHead: boolean): string[] {
65
- if (request.mode === 'staged') return ['--staged'];
66
- if (request.mode === 'range') return [request.value];
67
- if (request.mode === 'head') return [`HEAD~${request.value}..HEAD`];
68
- return hasHead ? ['HEAD'] : ['--staged'];
69
- }
70
-
71
- export function hasHeadCommit(): boolean {
72
- return git(['rev-parse', '--verify', 'HEAD'], true).status === 0;
73
- }
74
-
75
- export function changedFiles(args: readonly string[]): string[] {
76
- const names = git(['-c', 'core.quotePath=false', 'diff', ...args, '--name-only', '-z'], true);
77
- return decode(names.stdout).split('\0').filter((path) => path !== '' && isTarget(path));
78
- }
79
-
80
- export function untrackedFiles(): string[] {
81
- const others = git(['-c', 'core.quotePath=false', 'ls-files', '--others', '--exclude-standard', '-z'], true);
82
- return decode(others.stdout)
83
- .split('\0')
84
- .filter((path) => path !== '' && isTarget(path))
85
- .filter((path) => {
86
- try {
87
- return statSync(path, { throwIfNoEntry: false })?.isFile() === true;
88
- } catch {
89
- return false;
90
- }
91
- });
92
- }
93
-
94
- function hunkStart(row: string): number {
95
- const fields = row.split(/\s+/);
96
- let start = fields[2] ?? '';
97
- if (start.startsWith('+')) start = start.slice(1);
98
- const digits = /^[0-9]*/.exec(start.split(',')[0] ?? '')?.[0] ?? '';
99
- return digits === '' ? 0 : Number(digits);
100
- }
101
-
102
- export function trackedRecords(args: readonly string[], files: readonly string[]): Record[] {
103
- const diff = git(
104
- ['-c', 'core.quotePath=false', '-c', 'diff.noprefix=false', 'diff', ...args, '-U0', '--no-color', '--', ...files],
105
- false,
106
- );
107
- const out: Record[] = [];
108
- let current = '';
109
- let line = 0;
110
- for (const row of recordsOf(decode(diff.stdout).split('\n'))) {
111
- if (row.startsWith('+++ b/')) {
112
- current = row.slice(6);
113
- line = 0;
114
- } else if (row.startsWith('+++ /dev/null')) {
115
- current = '';
116
- line = 0;
117
- } else if (row.startsWith('@@ ')) {
118
- line = hunkStart(row);
119
- } else if (row.startsWith('+') && !row.startsWith('+++')) {
120
- if (current !== '' && line > 0) out.push({ path: current, line, content: row.slice(1) });
121
- line += 1;
122
- } else if (line > 0 && row.startsWith(' ')) {
123
- line += 1;
124
- }
125
- }
126
- return out;
127
- }
128
-
129
- export function untrackedRecords(path: string): Record[] {
130
- let data: Buffer;
131
- try {
132
- data = readFileSync(path);
133
- } catch {
134
- return [];
135
- }
136
- return recordsOf(decode(data).split('\n')).map((content, index) => ({ path, line: index + 1, content }));
137
- }
138
-
139
- export function countLines(args: readonly string[], files: readonly string[]): { added: number; removed: number } {
140
- const stat = git(['-c', 'core.quotePath=false', 'diff', ...args, '--numstat', '--', ...files], false);
141
- let added = 0;
142
- let removed = 0;
143
- for (const row of decode(stat.stdout).split('\n')) {
144
- const columns = row.split('\t');
145
- const first = columns[0] ?? '';
146
- if (/^[0-9]+$/.test(first)) added += Number(first);
147
- const second = columns[1] ?? '';
148
- if (/^[0-9]+$/.test(second)) removed += Number(second);
149
- }
150
- return { added, removed };
151
- }
152
-
153
- export function untrackedLineCount(path: string): number {
154
- try {
155
- let total = 0;
156
- for (const byte of readFileSync(path)) if (byte === 0x0a) total += 1;
157
- return total;
158
- } catch {
159
- return 0;
160
- }
161
- }
@@ -1,130 +0,0 @@
1
- /**
2
- * LAYER: Interface
3
- * Contains: extract-diff-scope command.
4
- * Rules: Emit the legacy YAML sections and exit statuses byte for byte.
5
- * BigO: O(n^2) score:1
6
- * keywords: [DiffScopeCommand, GateSections]
7
- * GOAL: List the changed code lines the quality gates must inspect.
8
- */
9
- import {
10
- awkQuote,
11
- changedFiles,
12
- countLines,
13
- diffArgs,
14
- gates,
15
- hasHeadCommit,
16
- trackedRecords,
17
- untrackedFiles,
18
- untrackedLineCount,
19
- untrackedRecords,
20
- yamlEscape,
21
- type Mode,
22
- type Record,
23
- type ScopeRequest,
24
- } from './diff-scope/git-diff.ts';
25
- import { EOL } from 'node:os';
26
-
27
- export const extractDiffScopeUsage = 'bbc extract-diff-scope [--working|--staged|--range A..B|--head N]';
28
-
29
- const usageText = `extract-diff-scope.py: extract added/modified TypeScript/JavaScript lines as
30
- structured YAML for code-quality-gate (TypeSafe, EarlyReturn, BigO).
31
-
32
- Usage:
33
- python3 -I -B scripts/extract-diff-scope.py # working tree vs HEAD + untracked (default)
34
- python3 -I -B scripts/extract-diff-scope.py --working # working tree vs HEAD + untracked
35
- python3 -I -B scripts/extract-diff-scope.py --staged # staged diff only
36
- python3 -I -B scripts/extract-diff-scope.py --range A..B # commit range
37
- python3 -I -B scripts/extract-diff-scope.py --head N # last N commits (HEAD~N..HEAD)
38
- python3 -I -B scripts/extract-diff-scope.py --help
39
- `;
40
-
41
- const native = (text: string): Buffer => Buffer.from(text.replaceAll('\n', EOL), 'latin1');
42
-
43
- function parseArgs(args: readonly string[]): ScopeRequest | 'help' | undefined {
44
- let mode: Mode = 'working';
45
- let value = '';
46
- for (let index = 0; index < args.length; index += 1) {
47
- const argument = args[index];
48
- if (argument === '--working' || argument === '--staged') {
49
- mode = argument.slice(2) as Mode;
50
- continue;
51
- }
52
- if (argument === '--range' || argument === '--head') {
53
- const next = args[index + 1];
54
- if (next === undefined || next === '') {
55
- process.stderr.write(native(`error: ${argument} requires ${argument === '--range' ? 'A..B' : 'N'}\n`));
56
- return undefined;
57
- }
58
- mode = argument.slice(2) as Mode;
59
- value = next;
60
- index += 1;
61
- continue;
62
- }
63
- if (argument === '--help' || argument === '-h') {
64
- process.stdout.write(native(usageText));
65
- return 'help';
66
- }
67
- process.stderr.write(native(`error: unknown option: ${argument}\n${usageText}`));
68
- return undefined;
69
- }
70
- if (mode === 'head' && !/^[1-9][0-9]*$/.test(value)) {
71
- process.stderr.write(native(`error: --head requires a positive integer: ${value}\n`));
72
- return undefined;
73
- }
74
- return { mode, value };
75
- }
76
-
77
- function emit(lines: readonly string[]): number {
78
- process.stdout.write(Buffer.from(`${lines.join('\n')}\n`, 'latin1'));
79
- return 0;
80
- }
81
-
82
- function emptyScope(mode: Mode, value: string, files: readonly string[]): string[] {
83
- const out = ['scope:', ` mode: "${mode}"`];
84
- if (mode === 'range') out.push(` range: "${yamlEscape(value)}"`);
85
- out.push(` files_changed: ${files.length}`);
86
- return [
87
- ...out,
88
- ' lines_added: 0',
89
- ' lines_removed: 0',
90
- ' files: []',
91
- ' records: []',
92
- ' typesafe_candidates: []',
93
- ' earlyreturn_candidates: []',
94
- ' bigo_candidates: []',
95
- ];
96
- }
97
-
98
- export function extractDiffScope(args: readonly string[]): number {
99
- const parsed = parseArgs(args);
100
- if (parsed === undefined) return 1;
101
- if (parsed === 'help') return 0;
102
- const diff = diffArgs(parsed, hasHeadCommit());
103
- const tracked = changedFiles(diff);
104
- const untracked = parsed.mode === 'working' ? untrackedFiles() : [];
105
- const files = [...tracked, ...untracked];
106
- if (files.length === 0) return emit(emptyScope(parsed.mode, parsed.value, files));
107
-
108
- const counted = tracked.length > 0 ? countLines(diff, tracked) : { added: 0, removed: 0 };
109
- const added = counted.added + untracked.reduce((total, path) => total + untrackedLineCount(path), 0);
110
- const header = ['scope:', ` mode: "${parsed.mode}"`];
111
- if (parsed.mode === 'range') header.push(` range: "${yamlEscape(parsed.value)}"`);
112
- header.push(` files_changed: ${files.length}`, ` lines_added: ${added}`, ` lines_removed: ${counted.removed}`, ' files:');
113
- const out = [...header, ...files.map((path) => ` - "${yamlEscape(path)}"`)];
114
-
115
- const records: Record[] = tracked.length > 0 ? trackedRecords(diff, tracked) : [];
116
- for (const path of untracked) records.push(...untrackedRecords(path));
117
-
118
- for (const [key, pattern] of gates) {
119
- const rows = records.filter((row) => pattern === null || pattern.test(row.content));
120
- if (rows.length === 0) {
121
- out.push(` ${key}: []`);
122
- continue;
123
- }
124
- out.push(` ${key}:`);
125
- for (const row of rows) {
126
- out.push(` - file: "${row.path}"`, ` line: ${row.line}`, ' added: true', ` content: "${awkQuote(row.content)}"`);
127
- }
128
- }
129
- return emit(out);
130
- }
@@ -1,86 +0,0 @@
1
- /**
2
- * LAYER: Interface
3
- * Contains: Big O command and report formatting.
4
- * Rules: Write reports to stdout and diagnostics to stderr using native line endings.
5
- * BigO: O(n) score:3
6
- * keywords: [MeasureBigoCommand, ComplexityReport]
7
- * GOAL: Score local files and emit the legacy line-oriented report.
8
- */
9
- import { readFileSync } from 'node:fs';
10
- import { EOL } from 'node:os';
11
- import { analyze, decideBigo, signals } from './bigo/complexity.ts';
12
- import { functionReports } from './bigo/functions.ts';
13
- import { suggestKeywords } from './bigo/keywords.ts';
14
- import { targetFiles } from './bigo/source-files.ts';
15
-
16
- export const measureBigoUsage = 'bbc measure-bigo <file-or-directory> [more...]';
17
-
18
- function quote(value: string): string {
19
- return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
20
- }
21
-
22
- function report(path: string, text: string): string {
23
- const counts = analyze(text);
24
- const { bigo, score } = decideBigo(counts);
25
- const lines = [
26
- ` - file: ${quote(path)}`,
27
- ` loc: ${counts.loc}`,
28
- ` code_lines: ${counts.codeLines}`,
29
- ` bigo: ${quote(bigo)}`,
30
- ` bigo_score: ${score}`,
31
- ` header_bigo: ${quote(`${bigo} score:${score}`)}`,
32
- ` loops: ${counts.loops}`,
33
- ` max_loop_nesting: ${counts.maxNest}`,
34
- ` lookup_in_loop: ${counts.lookup}`,
35
- ` spread_in_reduce: ${counts.spread}`,
36
- ` sorts: ${counts.sorts}`,
37
- ' signals:',
38
- ...signals(counts).map((signal) => ` - ${signal}`),
39
- ];
40
- const keywords = suggestKeywords(text);
41
- lines.push(keywords.length ? ' suggested_keywords:' : ' suggested_keywords: []');
42
- for (const word of keywords) lines.push(` - ${quote(word)}`);
43
- const functions = functionReports(text, path.endsWith('.py'));
44
- lines.push(functions.length ? ' functions:' : ' functions: []');
45
- for (const entry of functions) {
46
- lines.push(` - name: ${quote(entry.name)}`, ` line: ${entry.line}`,
47
- ` bigo: ${quote(entry.bigo)}`, ` bigo_score: ${entry.score}`);
48
- }
49
- // The legacy stream also translates LF embedded in a path on Windows.
50
- return `${lines.join('\n')}\n`.replaceAll('\n', EOL);
51
- }
52
-
53
- function writeReports(files: readonly string[]): boolean {
54
- for (const path of files) {
55
- let text: string;
56
- try {
57
- text = readFileSync(path, 'utf8');
58
- } catch {
59
- process.stderr.write(`Cannot read source file: ${path}\n`.replaceAll('\n', EOL));
60
- return false;
61
- }
62
- process.stdout.write(report(path, text));
63
- }
64
- return true;
65
- }
66
-
67
- export function measureBigo(targets: readonly string[]): number {
68
- if (targets.length === 0) {
69
- process.stderr.write(`Usage: ${measureBigoUsage}${EOL}`);
70
- return 1;
71
- }
72
- process.stdout.write(`results:${EOL}`);
73
- let found = false;
74
- for (const target of targets) {
75
- const files = targetFiles(target);
76
- if (!files) {
77
- process.stderr.write(`Not a file or directory: ${target}\n`.replaceAll('\n', EOL));
78
- continue;
79
- }
80
- if (!writeReports(files)) return 1;
81
- found ||= files.length > 0;
82
- }
83
- if (found) return 0;
84
- process.stderr.write(`No source files found.${EOL}`);
85
- return 1;
86
- }
@@ -1,144 +0,0 @@
1
- /**
2
- * LAYER: Interface
3
- * Contains: render-workflow command.
4
- * Rules: Check by default; write only between the workflow markers, atomically.
5
- * BigO: O(n^2) score:1
6
- * keywords: [RenderWorkflowCommand, ReadmeMarkers]
7
- * GOAL: Keep the README workflow block identical to the workflow source.
8
- */
9
- import { lstatSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
10
- import { dirname, join } from 'node:path';
11
- import { EOL } from 'node:os';
12
- import { randomUUID } from 'node:crypto';
13
- import { fileURLToPath } from 'node:url';
14
- import { JsonError, parseJsonText } from '@bbcsoftwarefactory/cli-core/python-json';
15
- import { pythonJoin, pythonPath, pythonRepr, universalNewlines } from '@bbcsoftwarefactory/cli-core/python-compat';
16
- import { generatedSection, workflowBegin, workflowEnd } from './workflow/render.ts';
17
- import { validateWorkflow, WorkflowError, type WorkflowDocument } from './workflow/schema.ts';
18
-
19
- export const renderWorkflowUsage = 'bbc render-workflow [--check | --write] [repo-root]';
20
-
21
- const sourceName = pythonPath('docs/diagrams/workflow.json');
22
- const readmeName = 'README.md';
23
- const agentsName = 'AGENTS.md';
24
- // The package sits at packages/cli/src, so the repository root is three levels up.
25
- const defaultRoot = pythonPath(fileURLToPath(new URL('../../../', import.meta.url)));
26
-
27
- const helpText = `render-workflow.py: generate the README workflow Mermaid block from one source.
28
-
29
- Usage:
30
- python3 -I -B scripts/render-workflow.py [--check | --write] [repo-root]
31
-
32
- docs/diagrams/workflow.json is the single source of the workflow stages and edges
33
- (ADR 0002). --check (the default, used by CI) only reads: it fails when the README
34
- block between the workflow markers differs from what the JSON generates, when the
35
- JSON is invalid, or when a stage's \`agents\` phrase is missing from the AGENTS.md
36
- handoff block. --write replaces only the text between the two markers, atomically.
37
-
38
- Standard library only. JSON is parsed with \`json\`, which cannot run code.
39
- `;
40
-
41
- const usageText = 'Usage:\n python3 -I -B scripts/render-workflow.py [--check | --write] [repo-root]';
42
- const native = (text: string): string => text.replaceAll('\n', EOL);
43
-
44
- const flagsAllowed = ['--check', '--write', '--help'];
45
- const handoffBlock = /## Skill handoffs\s+```text\n([\s\S]*?)```/;
46
-
47
- function readText(path: string): string {
48
- let regular = false;
49
- try {
50
- const stat = lstatSync(path);
51
- regular = stat.isFile() && !stat.isSymbolicLink();
52
- } catch {
53
- regular = false;
54
- }
55
- if (!regular) throw new WorkflowError(`${path}: must be a regular file, not a symlink`);
56
- return universalNewlines(readFileSync(path, 'utf8'));
57
- }
58
-
59
- function sectionBounds(readme: string): [number, number] {
60
- const begin = readme.split(workflowBegin).length - 1;
61
- const end = readme.split(workflowEnd).length - 1;
62
- if (begin !== 1 || end !== 1) throw new WorkflowError(`${readmeName}: needs exactly one pair of workflow markers`);
63
- const start = readme.indexOf(workflowBegin);
64
- const stop = readme.indexOf(workflowEnd) + workflowEnd.length;
65
- if (start >= stop) throw new WorkflowError(`${readmeName}: workflow markers are out of order`);
66
- return [start, stop];
67
- }
68
-
69
- function load(sourcePath: string): WorkflowDocument {
70
- const body = readText(sourcePath);
71
- try {
72
- return validateWorkflow(parseJsonText(body));
73
- } catch (error) {
74
- if (error instanceof JsonError) throw new WorkflowError(`${sourcePath}: invalid JSON (${error.message})`);
75
- throw error;
76
- }
77
- }
78
-
79
- function checkAgents(root: string, document: WorkflowDocument): void {
80
- const block = handoffBlock.exec(readText(pythonJoin(root, agentsName)));
81
- if (block === null) throw new WorkflowError(`${agentsName}: handoff block not found`);
82
- const words = block[1] ?? '';
83
- const missing = Object.entries(document.nodes)
84
- .filter(([, node]) => !words.includes(node.agents))
85
- .map(([id, node]) => `${id} (${pythonRepr(node.agents)})`);
86
- if (missing.length > 0) {
87
- throw new WorkflowError(`${agentsName}: handoff block lacks the agents phrase of ${missing.join(', ')}`);
88
- }
89
- }
90
-
91
- function writeAtomic(path: string, body: string): void {
92
- const temporary = join(dirname(path), `.README.${randomUUID().slice(0, 8)}.tmp`);
93
- try {
94
- writeFileSync(temporary, body, { encoding: 'utf8', flag: 'wx' });
95
- renameSync(temporary, path);
96
- } catch (error) {
97
- try {
98
- unlinkSync(temporary);
99
- } catch {
100
- // The temporary file was never created; nothing to remove.
101
- }
102
- throw error;
103
- }
104
- }
105
-
106
- function run(root: string, write: boolean): string {
107
- const sourcePath = pythonJoin(root, sourceName);
108
- const document = load(sourcePath);
109
- checkAgents(root, document);
110
- const readmePath = pythonJoin(root, readmeName);
111
- const readme = readText(readmePath);
112
- const [start, stop] = sectionBounds(readme);
113
- const expected = generatedSection(document);
114
- if (readme.slice(start, stop) === expected) return 'up to date';
115
- if (!write) {
116
- throw new WorkflowError(`${readmeName}: workflow block differs from ${sourceName}; run render-workflow.py --write`);
117
- }
118
- writeAtomic(readmePath, readme.slice(0, start) + expected + readme.slice(stop));
119
- return 'written';
120
- }
121
-
122
- export function renderWorkflow(args: readonly string[]): number {
123
- const flags = args.filter((argument) => argument.startsWith('--'));
124
- const paths = args.filter((argument) => !argument.startsWith('--'));
125
- const unknown = flags.some((flag) => !flagsAllowed.includes(flag));
126
- const conflicting = flags.includes('--check') && flags.includes('--write');
127
- if (unknown || conflicting || paths.length > 1) {
128
- process.stderr.write(native(`${usageText}\n`));
129
- return 2;
130
- }
131
- if (flags.includes('--help')) {
132
- process.stdout.write(native(`${helpText}\n`));
133
- return 0;
134
- }
135
- const root = paths[0] ?? defaultRoot;
136
- try {
137
- process.stdout.write(native(`workflow: ${run(root, flags.includes('--write'))}\n`));
138
- } catch (error) {
139
- if (!(error instanceof WorkflowError)) throw error;
140
- process.stderr.write(native(`workflow: ${error.message}\n`));
141
- return 1;
142
- }
143
- return 0;
144
- }