@bbcsoftwarefactory/cli 0.0.0-stage → 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.
@@ -0,0 +1,84 @@
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.js";
12
+ import { functionReports } from "./bigo/functions.js";
13
+ import { suggestKeywords } from "./bigo/keywords.js";
14
+ import { targetFiles } from "./bigo/source-files.js";
15
+ export const measureBigoUsage = 'bbc measure-bigo <file-or-directory> [more...]';
16
+ function quote(value) {
17
+ return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
18
+ }
19
+ function report(path, text) {
20
+ const counts = analyze(text);
21
+ const { bigo, score } = decideBigo(counts);
22
+ const lines = [
23
+ ` - file: ${quote(path)}`,
24
+ ` loc: ${counts.loc}`,
25
+ ` code_lines: ${counts.codeLines}`,
26
+ ` bigo: ${quote(bigo)}`,
27
+ ` bigo_score: ${score}`,
28
+ ` header_bigo: ${quote(`${bigo} score:${score}`)}`,
29
+ ` loops: ${counts.loops}`,
30
+ ` max_loop_nesting: ${counts.maxNest}`,
31
+ ` lookup_in_loop: ${counts.lookup}`,
32
+ ` spread_in_reduce: ${counts.spread}`,
33
+ ` sorts: ${counts.sorts}`,
34
+ ' signals:',
35
+ ...signals(counts).map((signal) => ` - ${signal}`),
36
+ ];
37
+ const keywords = suggestKeywords(text);
38
+ lines.push(keywords.length ? ' suggested_keywords:' : ' suggested_keywords: []');
39
+ for (const word of keywords)
40
+ lines.push(` - ${quote(word)}`);
41
+ const functions = functionReports(text, path.endsWith('.py'));
42
+ lines.push(functions.length ? ' functions:' : ' functions: []');
43
+ for (const entry of functions) {
44
+ lines.push(` - name: ${quote(entry.name)}`, ` line: ${entry.line}`, ` bigo: ${quote(entry.bigo)}`, ` bigo_score: ${entry.score}`);
45
+ }
46
+ // The legacy stream also translates LF embedded in a path on Windows.
47
+ return `${lines.join('\n')}\n`.replaceAll('\n', EOL);
48
+ }
49
+ function writeReports(files) {
50
+ for (const path of files) {
51
+ let text;
52
+ try {
53
+ text = readFileSync(path, 'utf8');
54
+ }
55
+ catch {
56
+ process.stderr.write(`Cannot read source file: ${path}\n`.replaceAll('\n', EOL));
57
+ return false;
58
+ }
59
+ process.stdout.write(report(path, text));
60
+ }
61
+ return true;
62
+ }
63
+ export function measureBigo(targets) {
64
+ if (targets.length === 0) {
65
+ process.stderr.write(`Usage: ${measureBigoUsage}${EOL}`);
66
+ return 1;
67
+ }
68
+ process.stdout.write(`results:${EOL}`);
69
+ let found = false;
70
+ for (const target of targets) {
71
+ const files = targetFiles(target);
72
+ if (!files) {
73
+ process.stderr.write(`Not a file or directory: ${target}\n`.replaceAll('\n', EOL));
74
+ continue;
75
+ }
76
+ if (!writeReports(files))
77
+ return 1;
78
+ found ||= files.length > 0;
79
+ }
80
+ if (found)
81
+ return 0;
82
+ process.stderr.write(`No source files found.${EOL}`);
83
+ return 1;
84
+ }
@@ -0,0 +1,2 @@
1
+ export declare const renderWorkflowUsage = "bbc render-workflow [--check | --write] [repo-root]";
2
+ export declare function renderWorkflow(args: readonly string[]): number;
@@ -0,0 +1,144 @@
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.js";
17
+ import { validateWorkflow, WorkflowError } from "./workflow/schema.js";
18
+ export const renderWorkflowUsage = 'bbc render-workflow [--check | --write] [repo-root]';
19
+ const sourceName = pythonPath('docs/diagrams/workflow.json');
20
+ const readmeName = 'README.md';
21
+ const agentsName = 'AGENTS.md';
22
+ // The package sits at packages/cli/src, so the repository root is three levels up.
23
+ const defaultRoot = pythonPath(fileURLToPath(new URL('../../../', import.meta.url)));
24
+ const helpText = `render-workflow.py: generate the README workflow Mermaid block from one source.
25
+
26
+ Usage:
27
+ python3 -I -B scripts/render-workflow.py [--check | --write] [repo-root]
28
+
29
+ docs/diagrams/workflow.json is the single source of the workflow stages and edges
30
+ (ADR 0002). --check (the default, used by CI) only reads: it fails when the README
31
+ block between the workflow markers differs from what the JSON generates, when the
32
+ JSON is invalid, or when a stage's \`agents\` phrase is missing from the AGENTS.md
33
+ handoff block. --write replaces only the text between the two markers, atomically.
34
+
35
+ Standard library only. JSON is parsed with \`json\`, which cannot run code.
36
+ `;
37
+ const usageText = 'Usage:\n python3 -I -B scripts/render-workflow.py [--check | --write] [repo-root]';
38
+ const native = (text) => text.replaceAll('\n', EOL);
39
+ const flagsAllowed = ['--check', '--write', '--help'];
40
+ const handoffBlock = /## Skill handoffs\s+```text\n([\s\S]*?)```/;
41
+ function readText(path) {
42
+ let regular = false;
43
+ try {
44
+ const stat = lstatSync(path);
45
+ regular = stat.isFile() && !stat.isSymbolicLink();
46
+ }
47
+ catch {
48
+ regular = false;
49
+ }
50
+ if (!regular)
51
+ throw new WorkflowError(`${path}: must be a regular file, not a symlink`);
52
+ return universalNewlines(readFileSync(path, 'utf8'));
53
+ }
54
+ function sectionBounds(readme) {
55
+ const begin = readme.split(workflowBegin).length - 1;
56
+ const end = readme.split(workflowEnd).length - 1;
57
+ if (begin !== 1 || end !== 1)
58
+ throw new WorkflowError(`${readmeName}: needs exactly one pair of workflow markers`);
59
+ const start = readme.indexOf(workflowBegin);
60
+ const stop = readme.indexOf(workflowEnd) + workflowEnd.length;
61
+ if (start >= stop)
62
+ throw new WorkflowError(`${readmeName}: workflow markers are out of order`);
63
+ return [start, stop];
64
+ }
65
+ function load(sourcePath) {
66
+ const body = readText(sourcePath);
67
+ try {
68
+ return validateWorkflow(parseJsonText(body));
69
+ }
70
+ catch (error) {
71
+ if (error instanceof JsonError)
72
+ throw new WorkflowError(`${sourcePath}: invalid JSON (${error.message})`);
73
+ throw error;
74
+ }
75
+ }
76
+ function checkAgents(root, document) {
77
+ const block = handoffBlock.exec(readText(pythonJoin(root, agentsName)));
78
+ if (block === null)
79
+ throw new WorkflowError(`${agentsName}: handoff block not found`);
80
+ const words = block[1] ?? '';
81
+ const missing = Object.entries(document.nodes)
82
+ .filter(([, node]) => !words.includes(node.agents))
83
+ .map(([id, node]) => `${id} (${pythonRepr(node.agents)})`);
84
+ if (missing.length > 0) {
85
+ throw new WorkflowError(`${agentsName}: handoff block lacks the agents phrase of ${missing.join(', ')}`);
86
+ }
87
+ }
88
+ function writeAtomic(path, body) {
89
+ const temporary = join(dirname(path), `.README.${randomUUID().slice(0, 8)}.tmp`);
90
+ try {
91
+ writeFileSync(temporary, body, { encoding: 'utf8', flag: 'wx' });
92
+ renameSync(temporary, path);
93
+ }
94
+ catch (error) {
95
+ try {
96
+ unlinkSync(temporary);
97
+ }
98
+ catch {
99
+ // The temporary file was never created; nothing to remove.
100
+ }
101
+ throw error;
102
+ }
103
+ }
104
+ function run(root, write) {
105
+ const sourcePath = pythonJoin(root, sourceName);
106
+ const document = load(sourcePath);
107
+ checkAgents(root, document);
108
+ const readmePath = pythonJoin(root, readmeName);
109
+ const readme = readText(readmePath);
110
+ const [start, stop] = sectionBounds(readme);
111
+ const expected = generatedSection(document);
112
+ if (readme.slice(start, stop) === expected)
113
+ return 'up to date';
114
+ if (!write) {
115
+ throw new WorkflowError(`${readmeName}: workflow block differs from ${sourceName}; run render-workflow.py --write`);
116
+ }
117
+ writeAtomic(readmePath, readme.slice(0, start) + expected + readme.slice(stop));
118
+ return 'written';
119
+ }
120
+ export function renderWorkflow(args) {
121
+ const flags = args.filter((argument) => argument.startsWith('--'));
122
+ const paths = args.filter((argument) => !argument.startsWith('--'));
123
+ const unknown = flags.some((flag) => !flagsAllowed.includes(flag));
124
+ const conflicting = flags.includes('--check') && flags.includes('--write');
125
+ if (unknown || conflicting || paths.length > 1) {
126
+ process.stderr.write(native(`${usageText}\n`));
127
+ return 2;
128
+ }
129
+ if (flags.includes('--help')) {
130
+ process.stdout.write(native(`${helpText}\n`));
131
+ return 0;
132
+ }
133
+ const root = paths[0] ?? defaultRoot;
134
+ try {
135
+ process.stdout.write(native(`workflow: ${run(root, flags.includes('--write'))}\n`));
136
+ }
137
+ catch (error) {
138
+ if (!(error instanceof WorkflowError))
139
+ throw error;
140
+ process.stderr.write(native(`workflow: ${error.message}\n`));
141
+ return 1;
142
+ }
143
+ return 0;
144
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * LAYER: Application
3
+ * Contains: Mermaid rendering of a validated workflow document.
4
+ * Rules: Print a node label at its first appearance only.
5
+ * BigO: placeholder
6
+ * keywords: [MermaidRender, MarkerSection]
7
+ * GOAL: Produce the deterministic README block the workflow source describes.
8
+ */
9
+ import type { WorkflowDocument } from './schema.ts';
10
+ export declare const workflowBegin = "<!-- workflow:begin generated by skills/workflow-auditor/scripts/render-workflow.py from docs/diagrams/workflow.json; do not edit by hand -->";
11
+ export declare const workflowEnd = "<!-- workflow:end -->";
12
+ export declare function renderFlowchart(document: WorkflowDocument): string;
13
+ export declare function generatedSection(document: WorkflowDocument): string;
@@ -0,0 +1,31 @@
1
+ export const workflowBegin = '<!-- workflow:begin generated by skills/workflow-auditor/scripts/render-workflow.py from docs/diagrams/workflow.json; do not edit by hand -->';
2
+ export const workflowEnd = '<!-- workflow:end -->';
3
+ const arrows = { solid: '-->', dotted: '-.->' };
4
+ export function renderFlowchart(document) {
5
+ const declared = new Set();
6
+ const reference = (id) => {
7
+ if (declared.has(id))
8
+ return id;
9
+ declared.add(id);
10
+ return `${id}["${document.nodes[id]?.label ?? ''}"]`;
11
+ };
12
+ const line = (edge, indent) => {
13
+ let arrow = arrows[edge.style ?? 'solid'];
14
+ if (edge.label !== undefined)
15
+ arrow += `|${edge.label}|`;
16
+ return `${indent}${reference(edge.from)} ${arrow} ${reference(edge.to)}`;
17
+ };
18
+ const out = [`flowchart ${document.direction}`];
19
+ for (const group of document.groups) {
20
+ out.push(` subgraph ${group.id}["${group.title}"]`);
21
+ for (const edge of group.edges)
22
+ out.push(line(edge, ' '));
23
+ out.push(' end');
24
+ }
25
+ for (const edge of document.edges)
26
+ out.push(line(edge, ' '));
27
+ return `${out.join('\n')}\n`;
28
+ }
29
+ export function generatedSection(document) {
30
+ return `${workflowBegin}\n\n\`\`\`mermaid\n${renderFlowchart(document)}\`\`\`\n\n${workflowEnd}`;
31
+ }
@@ -0,0 +1,25 @@
1
+ export declare class WorkflowError extends Error {
2
+ }
3
+ export interface WorkflowNode {
4
+ label: string;
5
+ agents: string;
6
+ }
7
+ export interface WorkflowEdge {
8
+ from: string;
9
+ to: string;
10
+ style?: 'solid' | 'dotted';
11
+ label?: string;
12
+ }
13
+ export interface WorkflowGroup {
14
+ id: string;
15
+ title: string;
16
+ edges: WorkflowEdge[];
17
+ }
18
+ export interface WorkflowDocument {
19
+ version: 1;
20
+ direction: 'TD' | 'LR';
21
+ nodes: Record<string, WorkflowNode>;
22
+ groups: WorkflowGroup[];
23
+ edges: WorkflowEdge[];
24
+ }
25
+ export declare function validateWorkflow(value: unknown): WorkflowDocument;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Workflow document model and its invariants.
4
+ * Rules: Reject every shape the legacy renderer rejects, with the same message.
5
+ * BigO: placeholder
6
+ * keywords: [WorkflowDocument, SourceInvariants]
7
+ * GOAL: Validate docs/diagrams/workflow.json before anything renders it.
8
+ */
9
+ import { compareCodePoints, describeValue, pythonListRepr, pythonRepr } from '@bbcsoftwarefactory/cli-core/python-compat';
10
+ export class WorkflowError extends Error {
11
+ }
12
+ const idPattern = /^[A-Za-z][A-Za-z0-9]{0,39}$/;
13
+ const idSource = '[A-Za-z][A-Za-z0-9]{0,39}';
14
+ const unsafeLabel = /["`[\n\r]/;
15
+ const unsafeEdgeLabel = /[|"`\n\r]/;
16
+ const unsafeAgents = /[\n\r]/;
17
+ function require(condition, message) {
18
+ if (!condition)
19
+ throw new WorkflowError(message);
20
+ }
21
+ function isPlainObject(value) {
22
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
23
+ }
24
+ function exactKeys(value, required, optional, where) {
25
+ require(isPlainObject(value), `${where}: must be an object`);
26
+ const keys = Object.keys(value);
27
+ const missing = required.filter((key) => !keys.includes(key)).sort(compareCodePoints);
28
+ require(missing.length === 0, `${where}: missing ${pythonListRepr(missing)}`);
29
+ const unknown = keys.filter((key) => !required.includes(key) && !optional.includes(key)).sort(compareCodePoints);
30
+ require(unknown.length === 0, `${where}: unknown ${pythonListRepr(unknown)}`);
31
+ return value;
32
+ }
33
+ function text(value, where, unsafe) {
34
+ require(typeof value === 'string' && value.trim() === value && value !== '', `${where}: must be a trimmed, non-empty string`);
35
+ require([...value].length <= 160, `${where}: longer than 160 characters`);
36
+ require(!unsafe.test(value), `${where}: contains a character that would break Mermaid syntax`);
37
+ return value;
38
+ }
39
+ function edge(value, where, nodes, used) {
40
+ const keys = exactKeys(value, ['from', 'to'], ['style', 'label'], where);
41
+ for (const end of ['from', 'to']) {
42
+ const target = keys[end];
43
+ require(typeof target === 'string' && Object.hasOwn(nodes, target), `${where}.${end}: unknown node ${describeValue(target)}`);
44
+ used.add(target);
45
+ }
46
+ const style = keys.style ?? 'solid';
47
+ require(style === 'solid' || style === 'dotted', `${where}.style: must be solid or dotted`);
48
+ const label = 'label' in keys ? text(keys.label, `${where}.label`, unsafeEdgeLabel) : undefined;
49
+ const rendered = { from: keys.from, to: keys.to, style };
50
+ if (label !== undefined)
51
+ rendered.label = label;
52
+ return rendered;
53
+ }
54
+ export function validateWorkflow(value) {
55
+ const top = exactKeys(value, ['version', 'direction', 'nodes', 'groups', 'edges'], [], 'workflow');
56
+ require(top.version === 1, 'workflow.version: must be 1');
57
+ require(top.direction === 'TD' || top.direction === 'LR', 'workflow.direction: must be TD or LR');
58
+ require(isPlainObject(top.nodes) && Object.keys(top.nodes).length > 0, 'workflow.nodes: must be a non-empty object');
59
+ const nodes = {};
60
+ for (const [id, node] of Object.entries(top.nodes)) {
61
+ require(idPattern.test(id), `node id ${pythonRepr(id)}: must match ${idSource}`);
62
+ const keys = exactKeys(node, ['label', 'agents'], [], `nodes.${id}`);
63
+ nodes[id] = {
64
+ label: text(keys.label, `nodes.${id}.label`, unsafeLabel),
65
+ agents: text(keys.agents, `nodes.${id}.agents`, unsafeAgents),
66
+ };
67
+ }
68
+ require(Array.isArray(top.groups), 'workflow.groups: must be a list');
69
+ require(Array.isArray(top.edges), 'workflow.edges: must be a list');
70
+ const seen = new Set();
71
+ const groups = [];
72
+ top.groups.forEach((group, index) => {
73
+ const keys = exactKeys(group, ['id', 'title', 'edges'], [], `groups[${index}]`);
74
+ require(typeof keys.id === 'string' && idPattern.test(keys.id) && !Object.hasOwn(nodes, keys.id), `groups[${index}].id: invalid or reused`);
75
+ require(!seen.has(keys.id), `groups[${index}].id: duplicate ${keys.id}`);
76
+ seen.add(keys.id);
77
+ const title = text(keys.title, `groups[${index}].title`, unsafeLabel);
78
+ require(Array.isArray(keys.edges) && keys.edges.length > 0, `groups[${index}].edges: must be a non-empty list`);
79
+ groups.push({ id: keys.id, title, edges: [] });
80
+ });
81
+ const used = new Set();
82
+ top.groups.forEach((group, index) => {
83
+ const keys = group;
84
+ const target = groups[index];
85
+ if (target === undefined)
86
+ return;
87
+ target.edges = keys.edges.map((item, position) => edge(item, `groups[${index}].edges[${position}]`, nodes, used));
88
+ });
89
+ const edges = top.edges.map((item, position) => edge(item, `edges[${position}]`, nodes, used));
90
+ const unused = Object.keys(nodes).filter((id) => !used.has(id)).sort(compareCodePoints);
91
+ require(unused.length === 0, `nodes not used by any edge: ${pythonListRepr(unused)}`);
92
+ return {
93
+ version: 1,
94
+ direction: top.direction,
95
+ nodes,
96
+ groups,
97
+ edges,
98
+ };
99
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
- {
2
- "name": "@bbcsoftwarefactory/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@bbcsoftwarefactory/cli",
3
+ "version": "0.1.1",
4
+ "description": "Command line interface for the BuilderBot agent skills: Big O scoring, change classification, README workflow rendering, and diff scope extraction.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22.18.0"
9
+ },
10
+ "bin": {
11
+ "bbc": "./dist/bbc.js"
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "dependencies": {
17
+ "@bbcsoftwarefactory/cli-core": "^0.1.1"
18
+ },
19
+ "scripts": {
20
+ "build": "tsc -p tsconfig.build.json",
21
+ "prepack": "npm run build",
22
+ "test": "node --test \"src/*.test.ts\""
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/builberbot/bbc-skill-internals.git",
27
+ "directory": "packages/cli"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "provenance": true
32
+ }
33
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.