@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
@@ -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,6 @@
1
1
  {
2
2
  "name": "@bbcsoftwarefactory/cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Command line interface for the BuilderBot agent skills: Big O scoring, change classification, README workflow rendering, and diff scope extraction.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -8,18 +8,18 @@
8
8
  "node": ">=22.18.0"
9
9
  },
10
10
  "bin": {
11
- "bbc": "./src/bbc.ts"
11
+ "bbc": "./dist/bbc.js"
12
12
  },
13
13
  "files": [
14
- "src/",
15
- "!src/**/*.test.ts"
14
+ "dist"
16
15
  ],
17
16
  "dependencies": {
18
- "@bbcsoftwarefactory/cli-core": "^0.1.0"
17
+ "@bbcsoftwarefactory/cli-core": "^0.1.1"
19
18
  },
20
19
  "scripts": {
21
- "test": "node --test \"src/*.test.ts\"",
22
- "pack:check": "npm pack --dry-run"
20
+ "build": "tsc -p tsconfig.build.json",
21
+ "prepack": "npm run build",
22
+ "test": "node --test \"src/*.test.ts\""
23
23
  },
24
24
  "repository": {
25
25
  "type": "git",
package/src/bbc.ts DELETED
@@ -1,39 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * LAYER: Interface
4
- * Contains: CLI entry point.
5
- * Rules: Write help to stdout and input errors to stderr.
6
- * BigO: O(1) score:5
7
- * keywords: [CliEntryPoint, CommandArguments]
8
- * GOAL: Translate command-line arguments into process output and exit status.
9
- */
10
- import { classifyChangeLane, classifyChangeLaneUsage } from './classify-change-lane.ts';
11
- import { extractDiffScope, extractDiffScopeUsage } from './extract-diff-scope.ts';
12
- import { measureBigo, measureBigoUsage } from './measure-bigo.ts';
13
- import { renderWorkflow, renderWorkflowUsage } from './render-workflow.ts';
14
-
15
- const usage = 'Usage: bbc <command> [arguments]\n';
16
-
17
- function main([command, ...args]: readonly string[]): number {
18
- const [argument] = args;
19
- if (command === undefined) {
20
- process.stderr.write(usage);
21
- return 1;
22
- }
23
- if (command === '--help' && argument !== undefined) {
24
- process.stderr.write(`Unexpected argument after --help: ${JSON.stringify(argument)}\n${usage}`);
25
- return 1;
26
- }
27
- if (command === '--help') {
28
- process.stdout.write(`${usage}\nCommands:\n ${measureBigoUsage}\n ${classifyChangeLaneUsage}\n ${renderWorkflowUsage}\n ${extractDiffScopeUsage}\n`);
29
- return 0;
30
- }
31
- if (command === 'measure-bigo') return measureBigo(args);
32
- if (command === 'classify-change-lane') return classifyChangeLane(args);
33
- if (command === 'render-workflow') return renderWorkflow(args);
34
- if (command === 'extract-diff-scope') return extractDiffScope(args);
35
- process.stderr.write(`Unknown command: ${JSON.stringify(command)}\n${usage}`);
36
- return 1;
37
- }
38
-
39
- process.exitCode = main(process.argv.slice(2));
@@ -1,138 +0,0 @@
1
- /**
2
- * LAYER: Domain
3
- * Contains: Big O counters, classifications, and ordered signals.
4
- * Rules: Infer complexity from lexical evidence rather than parsed syntax.
5
- * BigO: O(n^2) score:1
6
- * keywords: [ComplexityCounters, LoopNesting, ComplexitySignals]
7
- * GOAL: Score a file or function body using the legacy heuristic.
8
- */
9
- import { asciiSpace as ws, createStripper, records, withoutTrailingCR } from './lexical.ts';
10
-
11
- const iter = 'forEach|map|filter|reduce|reduceRight|flatMap|some|every|find|findIndex';
12
- const loop = new RegExp([
13
- `for${ws}*(await${ws}*)?\\(`, `for${ws}+`, `while${ws}*\\(`, `do${ws}*\\{`,
14
- ].map((pattern) => `(?:^|[^A-Za-z0-9_.$])${pattern}`).concat(`\\.(${iter}|sort)${ws}*\\(`).join('|'));
15
- const colonEnd = new RegExp(`:${ws}*$`);
16
- const pythonWhile = new RegExp(`(?:^|[^A-Za-z0-9_.$])while${ws}+`);
17
- const reduce = new RegExp(`\\.reduce${ws}*\\(`);
18
- const sort = new RegExp(`\\.sort${ws}*\\(`);
19
- const lookup = new RegExp(`\\.(includes|indexOf)${ws}*\\(`);
20
- const call = new RegExp(`\\.(${iter})${ws}*\\(`, 'g');
21
- const inner = new RegExp(`\\.(${iter}|includes|indexOf)${ws}*\\(`);
22
- const spread = /\.\.\.[A-Za-z_]/;
23
- const mid = /(^|[^A-Za-z0-9_])mid([^A-Za-z0-9_]|$)/;
24
- const bound = /(^|[^A-Za-z0-9_])(low|high|left|right)([^A-Za-z0-9_]|$)/;
25
-
26
- interface Counts {
27
- loc: number;
28
- codeLines: number;
29
- loops: number;
30
- maxNest: number;
31
- lookup: number;
32
- spread: number;
33
- sorts: number;
34
- binary: boolean;
35
- }
36
-
37
- export interface Complexity {
38
- bigo: string;
39
- score: number;
40
- }
41
-
42
- type LoopKind = 'reduce' | 'sort' | 'loop';
43
-
44
- function loopKind(line: string): LoopKind | undefined {
45
- if (reduce.test(line)) return 'reduce';
46
- if (sort.test(line)) return 'sort';
47
- if (loop.test(line) || (colonEnd.test(line) && pythonWhile.test(line))) return 'loop';
48
- }
49
-
50
- function lineIndent(line: string): number {
51
- let width = 0;
52
- for (const char of line) {
53
- if (char === ' ') width += 1;
54
- else if (char === '\t') width += 2;
55
- else break;
56
- }
57
- return width;
58
- }
59
-
60
- function callBodyEnd(line: string, start: number): number {
61
- let depth = 1;
62
- for (let index = start; index < line.length; index += 1) {
63
- if (line[index] === '(') depth += 1;
64
- if (line[index] === ')' && --depth === 0) return index;
65
- }
66
- return line.length;
67
- }
68
-
69
- function inlineLookup(line: string): boolean {
70
- call.lastIndex = 0;
71
- while (call.exec(line)) {
72
- const start = call.lastIndex;
73
- const end = callBodyEnd(line, start);
74
- if (inner.test(line.slice(start, end))) return true;
75
- // All candidate calls inside this body are included in `inner`; a miss lets us skip the span.
76
- call.lastIndex = Math.min(end + 1, line.length);
77
- }
78
- return false;
79
- }
80
-
81
- export function analyze(text: string): Counts {
82
- const lines = records(text);
83
- const counts = { loc: lines.length, codeLines: 0, loops: 0, maxNest: 0, lookup: 0, spread: 0, sorts: 0, binary: false };
84
- const strip = createStripper();
85
- const stack: { indent: number; kind: LoopKind }[] = [];
86
- let reduceDepth = 0;
87
- let sawMid = false;
88
- let sawBound = false;
89
- for (const raw of lines) {
90
- const line = strip(withoutTrailingCR(raw));
91
- if (/^[ \t]*$/.test(line)) continue;
92
- counts.codeLines += 1;
93
- if (/^[ \t]*\{[ \t]*$/.test(line)) continue;
94
- const indent = lineIndent(line);
95
- for (let top = stack.at(-1); top && top.indent >= indent; top = stack.at(-1)) {
96
- reduceDepth -= Number(top.kind === 'reduce');
97
- stack.pop();
98
- }
99
- const kind = loopKind(line);
100
- if (kind) {
101
- stack.push({ indent, kind });
102
- counts.loops += 1;
103
- counts.maxNest = Math.max(counts.maxNest, stack.length);
104
- reduceDepth += Number(kind === 'reduce');
105
- counts.sorts += Number(sort.test(line));
106
- }
107
- if (stack.length === 0) continue;
108
- if (lookup.test(line) || inlineLookup(line)) counts.lookup += 1;
109
- if (reduceDepth > 0 && spread.test(line)) counts.spread += 1;
110
- sawMid ||= mid.test(line);
111
- sawBound ||= bound.test(line);
112
- counts.binary ||= sawMid && sawBound;
113
- }
114
- return counts;
115
- }
116
-
117
- export function decideBigo(c: Counts): Complexity {
118
- if (c.maxNest >= 3) return { bigo: 'O(n^3)', score: 1 };
119
- if (c.maxNest >= 2 || c.lookup || c.spread) return { bigo: 'O(n^2)', score: 1 };
120
- if (c.sorts) return { bigo: 'O(n log n)', score: 2 };
121
- if (c.binary && c.loops) return { bigo: 'O(log n)', score: 4 };
122
- if (c.loops) return { bigo: 'O(n)', score: 3 };
123
- return { bigo: 'O(1)', score: 5 };
124
- }
125
-
126
- export function signals(c: Counts): string[] {
127
- const out: string[] = [];
128
- const clean = c.maxNest < 2 && !c.lookup && !c.spread;
129
- if (c.maxNest >= 3) out.push('deep_nesting');
130
- if (c.maxNest >= 2) out.push('nested_loop');
131
- if (c.lookup) out.push('lookup_in_loop');
132
- if (c.spread) out.push('spread_in_reduce');
133
- if (c.sorts) out.push('sort');
134
- if (c.binary && clean) out.push('logarithmic');
135
- if (c.loops && clean && !c.sorts && !c.binary) out.push('single_pass');
136
- if (!c.loops || out.length === 0) out.push('constant');
137
- return out;
138
- }