@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,183 +0,0 @@
1
- /**
2
- * LAYER: Domain
3
- * Contains: Heuristic function boundaries and scores.
4
- * Rules: An inner named function owns its lines; anonymous callbacks do not.
5
- * BigO: O(n^2) score:1
6
- * keywords: [FunctionBoundary, FunctionScore]
7
- * GOAL: Score the lines owned by each named declaration in source order.
8
- */
9
- import { analyze, decideBigo } from './complexity.ts';
10
- import type { Complexity } from './complexity.ts';
11
- import { createStripper, records, unicodeSpace, unicodeWord, withoutTrailingCR } from './lexical.ts';
12
-
13
- const word = unicodeWord.slice(1, -1);
14
- function declarationPattern(pattern: string): RegExp {
15
- return new RegExp(pattern.replace('function\\b', `function(?!${unicodeWord})`)
16
- .replaceAll('\\s', unicodeSpace).replaceAll('\\w', word), 'u');
17
- }
18
-
19
- const declarations = [
20
- String.raw`^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(`,
21
- String.raw`^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s+)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)`,
22
- String.raw`^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_][\w]*)\s*\(`,
23
- ].map(declarationPattern);
24
- const methodPrefix = declarationPattern(String.raw`^\s*(?:(?:public|private|protected|static|final|abstract|async|override|readonly|synchronized|function)\s+)*(?:[\w$<>\[\],.?]+\s+)?([A-Za-z_$][\w$]*)\s*\(`);
25
- const whitespaceOnly = new RegExp(`^${unicodeSpace}*$`, 'u');
26
- const methodTail = new RegExp(`^${unicodeSpace}*(?:throws${unicodeSpace}[${word}.,${unicodeSpace.slice(1, -1)}]+)?$`, 'u');
27
- const returnType = new RegExp(`\\)${unicodeSpace}*:[^{;=]+$`, 'u');
28
- const notFunctions = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'function', 'do', 'else', 'with',
29
- 'typeof', 'new', 'await', 'super', 'constructor_call']);
30
- const pyDef = new RegExp(`^([ \\t]*)(?:async${unicodeSpace}+)?def${unicodeSpace}+([A-Za-z_]${unicodeWord}*)${unicodeSpace}*\\(`, 'u');
31
- const pyLeading = new RegExp(`^${unicodeSpace}*`);
32
-
33
- interface Boundary {
34
- name: string;
35
- start: number;
36
- end: number;
37
- }
38
-
39
- interface Span {
40
- start: number;
41
- end: number;
42
- }
43
-
44
- function scanBraces(line: string, index: number, pairs: Span[], open: Span[]): void {
45
- for (const char of line) {
46
- if (char === '{') {
47
- const pair = { start: index, end: -1 };
48
- pairs.push(pair);
49
- open.push(pair);
50
- }
51
- if (char !== '}') continue;
52
- const pair = open.pop();
53
- if (pair) pair.end = index;
54
- }
55
- }
56
-
57
- function bracePairs(lines: readonly string[]): Span[] {
58
- const pairs: Span[] = [];
59
- const open: Span[] = [];
60
- for (const [index, line] of lines.entries()) scanBraces(line, index, pairs, open);
61
- return pairs.filter((pair) => pair.end !== -1);
62
- }
63
-
64
- function methodName(line: string): string | undefined {
65
- const brace = line.lastIndexOf('{');
66
- if (brace < 0 || !whitespaceOnly.test(line.slice(brace + 1))) return undefined;
67
- const prefix = methodPrefix.exec(line);
68
- const name = prefix?.[1];
69
- if (!prefix || !name || notFunctions.has(name) || prefix[0].length > brace) return undefined;
70
- const body = line.slice(prefix[0].length, brace);
71
- const lastClose = body.lastIndexOf(')');
72
- if (lastClose < 0 || body.includes(';')) return undefined;
73
- if (methodTail.test(body.slice(lastClose + 1))) return name;
74
- // An earlier ')' can still end the parameters when a return annotation contains ')'.
75
- // Start after the last forbidden type character so failed candidates cannot rescan the suffix.
76
- const typeStart = Math.max(body.lastIndexOf('{'), body.lastIndexOf('=')) + 1;
77
- if (returnType.test(body.slice(typeStart))) return name;
78
- }
79
-
80
- function braceDeclaration(line: string): { name: string; expression: boolean } | undefined {
81
- for (const [index, pattern] of declarations.entries()) {
82
- const name = pattern.exec(line)?.[1];
83
- if (name && !notFunctions.has(name)) return { name, expression: index === 1 && !line.includes('{') };
84
- }
85
- const method = methodName(line);
86
- if (method) return { name: method, expression: false };
87
- }
88
-
89
- function braceFunctions(lines: readonly string[]): Boundary[] {
90
- const strip = createStripper();
91
- const stripped = lines.map(strip);
92
- const pairs = bracePairs(stripped);
93
- const found: Boundary[] = [];
94
- let first = 0;
95
- for (const [index, line] of stripped.entries()) {
96
- while ((pairs[first]?.start ?? Infinity) < index) first += 1;
97
- const declaration = braceDeclaration(line);
98
- if (!declaration) continue;
99
- const { name, expression } = declaration;
100
- const pair = pairs[first];
101
- if (expression) found.push({ name, start: index, end: index });
102
- else if (pair && pair.start <= index + 2) found.push({ name, start: index, end: pair.end });
103
- }
104
- return found;
105
- }
106
-
107
- function expandTabWidth(indent: string): number {
108
- let width = 0;
109
- for (const char of indent) width += char === '\t' ? 8 - (width % 8) : 1;
110
- return width;
111
- }
112
-
113
- interface PythonLine {
114
- index: number;
115
- text: string;
116
- indent: number;
117
- previousNonblank: number;
118
- }
119
-
120
- function indexPythonLines(lines: readonly string[]): { indexed: PythonLine[]; lastNonblank: number } {
121
- let lastNonblank = -1;
122
- const indexed = lines.map((text, index) => {
123
- const indent = pyLeading.exec(text)?.[0].length ?? 0;
124
- const previousNonblank = lastNonblank;
125
- if (indent < text.length) lastNonblank = index;
126
- return { index, text, indent, previousNonblank };
127
- });
128
- return { indexed, lastNonblank };
129
- }
130
-
131
- function nearestDedent(candidates: readonly PythonLine[], width: number): PythonLine | undefined {
132
- let low = 0;
133
- let high = candidates.length;
134
- while (low < high) {
135
- const mid = low + Math.floor((high - low) / 2);
136
- if ((candidates[mid]?.indent ?? Infinity) <= width) low = mid + 1;
137
- else high = mid;
138
- }
139
- return candidates[low - 1];
140
- }
141
-
142
- function pythonFunctions(lines: readonly string[]): Boundary[] {
143
- const { indexed, lastNonblank } = indexPythonLines(lines);
144
- const found: Boundary[] = [];
145
- const candidates: PythonLine[] = [];
146
- for (const line of indexed.reverse()) {
147
- const { index, text, indent } = line;
148
- const [, defIndent, name] = pyDef.exec(text) ?? [];
149
- if (defIndent !== undefined && name !== undefined) {
150
- // The legacy rule compares the expanded declaration indent with raw body whitespace.
151
- const stop = nearestDedent(candidates, expandTabWidth(defIndent));
152
- found.push({ name, start: index, end: stop?.previousNonblank ?? lastNonblank });
153
- }
154
- if (indent === text.length || text[indent] === '#') continue;
155
- // A closer candidate of equal or smaller indent hides every farther candidate it pops.
156
- while ((candidates.at(-1)?.indent ?? -1) >= indent) candidates.pop();
157
- candidates.push(line);
158
- }
159
- return found.reverse();
160
- }
161
-
162
- export function functionReports(text: string, python: boolean): (Complexity & { name: string; line: number })[] {
163
- const lines = records(text).map(withoutTrailingCR);
164
- const found = python ? pythonFunctions(lines) : braceFunctions(lines);
165
- if (found.length === 0) return [];
166
- const open: { end: number; body: string[] }[] = [];
167
- const bodies = found.map((): string[] => []);
168
- let next = 0;
169
- for (const [index, line] of lines.entries()) {
170
- const current = found[next];
171
- const body = bodies[next];
172
- // Discovery emits at most one declaration per line, in start order.
173
- if (current?.start === index && body) {
174
- open.push({ end: current.end, body });
175
- next += 1;
176
- }
177
- while ((open.at(-1)?.end ?? Infinity) < index) open.pop();
178
- open.at(-1)?.body.push(line);
179
- }
180
- return found.map(({ name, start }, index) => ({
181
- name, line: start + 1, ...decideBigo(analyze(`${bodies[index]?.join('\n') ?? ''}\n`)),
182
- }));
183
- }
@@ -1,41 +0,0 @@
1
- /**
2
- * LAYER: Domain
3
- * Contains: Heuristic keyword suggestions from import and export lines.
4
- * Rules: Prefer exported declarations, deduplicate within each group, and cap suggestions at twelve.
5
- * BigO: O(n) score:3
6
- * keywords: [KeywordSuggestions, LocalImportName]
7
- * GOAL: Preserve the legacy keyword names and ordering for source headers.
8
- */
9
- import { asciiSpace as ws, records } from './lexical.ts';
10
-
11
- const importLine = new RegExp(`^${ws}*import${ws}`);
12
- const exportLine = new RegExp(`^${ws}*export${ws}`);
13
- const exportDecl = new RegExp(`(?:class|interface|type|function|const|enum)${ws}+([A-Za-z_][A-Za-z0-9_]*)`);
14
- const importType = new RegExp(`type${ws}+`, 'g');
15
- const alias = new RegExp(`${ws}as${ws}+([A-Za-z_][A-Za-z0-9_]*)`);
16
- const reserved = new Set(['type', 'typeof', 'as', 'from']);
17
-
18
- function addImports(line: string, imports: Set<string>): void {
19
- const open = line.indexOf('{');
20
- if (open < 0) return;
21
- const close = line.indexOf('}', open + 1);
22
- if (close < 0) return;
23
- const names = line.slice(open + 1, close).replace(importType, '').split(',');
24
- for (const item of names) {
25
- const name = alias.exec(item)?.[1] ?? item.replace(/[^A-Za-z0-9_]/g, '');
26
- if (name && !reserved.has(name)) imports.add(name);
27
- }
28
- }
29
-
30
- export function suggestKeywords(text: string): string[] {
31
- const exports = new Set<string>();
32
- const imports = new Set<string>();
33
- for (const line of records(text)) {
34
- if (importLine.test(line)) addImports(line, imports);
35
- if (exportLine.test(line)) {
36
- const name = exportDecl.exec(line)?.[1];
37
- if (name && !reserved.has(name)) exports.add(name);
38
- }
39
- }
40
- return [...exports, ...imports].slice(0, 12);
41
- }
@@ -1,68 +0,0 @@
1
- /**
2
- * LAYER: Domain
3
- * Contains: Lexical preprocessing for the Big O heuristic.
4
- * Rules: Keep legacy line boundaries and strip only the recognized tokens.
5
- * BigO: O(n^2) score:1
6
- * keywords: [SourceRecords, CommentStripper]
7
- * GOAL: Expose the source lines used by the legacy heuristics.
8
- */
9
- export const asciiSpace = '[\\t-\\r ]';
10
- export const unicodeSpace = '[\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]';
11
- export const unicodeWord = '[\\p{L}\\p{N}_]';
12
-
13
- export function records(text: string): string[] {
14
- const lines = text.split('\n');
15
- if (lines.at(-1) === '') lines.pop();
16
- return lines;
17
- }
18
-
19
- export function withoutTrailingCR(line: string): string {
20
- return line.endsWith('\r') ? line.slice(0, -1) : line;
21
- }
22
-
23
- function afterString(line: string, start: number, quote: string): number {
24
- for (let cursor = start; cursor < line.length; cursor += 1) {
25
- const char = line[cursor];
26
- if (char === quote) return cursor + 1;
27
- if (char === '\\') cursor += 1;
28
- }
29
- return line.length;
30
- }
31
-
32
- export function createStripper(): (line: string) => string {
33
- let inBlock = false;
34
- const special = /\/\/|\/\*|["'`]/g;
35
- return (line) => {
36
- let cursor = 0;
37
- if (inBlock) {
38
- const end = line.indexOf('*/');
39
- if (end < 0) return '';
40
- inBlock = false;
41
- cursor = end + 2;
42
- }
43
- const fragments: string[] = [];
44
- while (cursor < line.length) {
45
- special.lastIndex = cursor;
46
- const token = special.exec(line);
47
- if (!token) {
48
- fragments.push(line.slice(cursor));
49
- break;
50
- }
51
- fragments.push(line.slice(cursor, token.index));
52
- const [mark] = token;
53
- if (mark === '//') break;
54
- if (mark !== '/*') {
55
- cursor = afterString(line, special.lastIndex, mark);
56
- fragments.push(' ');
57
- continue;
58
- }
59
- const end = line.indexOf('*/', special.lastIndex);
60
- if (end < 0) {
61
- inBlock = true;
62
- break;
63
- }
64
- cursor = end + 2;
65
- }
66
- return fragments.join('');
67
- };
68
- }
@@ -1,80 +0,0 @@
1
- /**
2
- * LAYER: Infrastructure
3
- * Contains: Filesystem discovery for the Big O CLI.
4
- * Rules: Retain argument spelling and do not descend into discovered links or excluded trees.
5
- * BigO: O(n log n) score:2
6
- * keywords: [SourceDiscovery, DirectoryExclusions]
7
- * GOAL: Collect regular source files in legacy path order without following discovered symlinks.
8
- */
9
- import { readdirSync, statSync } from 'node:fs';
10
- import type { Dirent } from 'node:fs';
11
- import { sep } from 'node:path';
12
-
13
- const extensions = /\.(ts|tsx|js|mjs|cjs|py|java|go|php)$/;
14
- const excluded = /\/(node_modules|dist|\.git|coverage)\//;
15
- const windows = sep === '\\';
16
-
17
- function endsWithSeparator(path: string): boolean {
18
- return path.endsWith(sep) || (windows && path.endsWith('/'));
19
- }
20
-
21
- function childPath(parent: string, name: string): string {
22
- // path.join normalizes away caller-provided dots, redundant separators, and mixed separators.
23
- const canAppend = endsWithSeparator(parent) || (windows && /^[A-Za-z]:$/.test(parent));
24
- return canAppend ? parent + name : parent + sep + name;
25
- }
26
-
27
- function excludedPath(path: string): boolean {
28
- return excluded.test(windows ? path.replaceAll('\\', '/') : path);
29
- }
30
-
31
- function comparePaths(a: string, b: string): number {
32
- // Python sorts Unicode code points, not UTF-16 code units.
33
- let offset = 0;
34
- for (const char of a) {
35
- const other = b.codePointAt(offset);
36
- if (other === undefined) return 1;
37
- const point = char.codePointAt(0) ?? 0;
38
- if (point !== other) return point - other;
39
- offset += char.length;
40
- }
41
- return offset - b.length;
42
- }
43
-
44
- function readDirectory(path: string): Dirent[] {
45
- try {
46
- return readdirSync(path, { withFileTypes: true });
47
- } catch {
48
- // Like os.walk without an onerror handler, ignore inaccessible directories.
49
- return [];
50
- }
51
- }
52
-
53
- function targetStat(target: string) {
54
- try {
55
- return statSync(target, { throwIfNoEntry: false });
56
- } catch {
57
- // Python's stat-based isfile/isdir predicates also reject inaccessible targets.
58
- return undefined;
59
- }
60
- }
61
-
62
- function scanDirectory(root: string, pending: string[], found: string[]): void {
63
- if (excludedPath(childPath(root, '_'))) return;
64
- for (const entry of readDirectory(root)) {
65
- const path = childPath(root, entry.name);
66
- if (entry.isDirectory()) pending.push(path);
67
- else if (entry.isFile() && extensions.test(entry.name)) found.push(path);
68
- }
69
- }
70
-
71
- export function targetFiles(target: string): string[] | undefined {
72
- const stat = targetStat(target);
73
- // Node's Windows stat accepts a regular file even with a trailing separator; Python rejects it.
74
- if (stat?.isFile()) return endsWithSeparator(target) ? undefined : [target];
75
- if (!stat?.isDirectory()) return undefined;
76
- const pending = [target];
77
- const found: string[] = [];
78
- for (let root = pending.pop(); root !== undefined; root = pending.pop()) scanDirectory(root, pending, found);
79
- return found.sort(comparePaths);
80
- }
@@ -1,128 +0,0 @@
1
- /**
2
- * LAYER: Domain
3
- * Contains: Change-lane policies and report construction.
4
- * Rules: Risk takes precedence over file extensions; thresholds are strict.
5
- * BigO: O(n) score:3
6
- * keywords: [ChangeLanePolicy, LaneReport]
7
- * GOAL: Classify paths and line totals without reading Git or the worktree.
8
- */
9
- import { win32 } from 'node:path';
10
-
11
- const largeLines = 300;
12
- const largeFiles = 10;
13
- const trivialExtensions = new Set(['.md', '.mdx', '.txt', '.svg', '.excalidraw', '.png', '.jpg', '.jpeg', '.webp', '.gif']);
14
- const trivialNames = new Set([
15
- 'CHANGELOG.md', 'README.md', 'AGENTS.md', 'INSTALLATION.md', 'CONTRIBUTING.md',
16
- 'SUPPORT.md', 'SECURITY.md', 'LICENSE', 'NOTICE',
17
- ]);
18
-
19
- const riskPatterns = [
20
- /(^|\/)skills\/watcher-observability\//i,
21
- /(^|\/)skills\/tool-depot\//i,
22
- /(^|\/)skills\/workflow-auditor\/scripts\/audit-ledger\.py$/i,
23
- /(^|\/)skills\/question-gate\/scripts\/triage-question\.py$/i,
24
- /(^|\/)skills\/delivery-coordinator\/scripts\/check-worktree-guard\.py$/i,
25
- /(^|\/)tools\/export-public\.py$/i,
26
- /(^|\/)\.github\/workflows\//i,
27
- /(^|\/)(?:auth|oauth|jwt|session|token|crypto|secret|permission|rbac|security|migration|migrations|prisma|schema|deploy|infra)(?:\/|[._-]|$)/i,
28
- /\.sql$/i,
29
- ];
30
-
31
- const plans = {
32
- trivial: {
33
- test_mode: 'proportional',
34
- required_stages: ['specify', 'implement', 'quality', 'docs', 'commit_pr', 'review'],
35
- skipped_stages: ['requirements-spec-full-prd', 'risk-scout', 'reproduce-runtime-red', 'verify-runtime-green'],
36
- extra_checks: ['documentation-steward', 'validate-skills.py'],
37
- },
38
- standard: {
39
- test_mode: 'tdd',
40
- required_stages: ['specify', 'reproduce', 'implement', 'verify', 'quality', 'commit_pr', 'review'],
41
- skipped_stages: ['risk-scout'],
42
- extra_checks: ['code-quality-gate'],
43
- },
44
- 'high-risk': {
45
- test_mode: 'tdd',
46
- required_stages: [
47
- 'specify', 'risk-scout', 'reproduce', 'implement', 'verify', 'quality', 'commit_pr', 'review', 'residual_risk',
48
- ],
49
- skipped_stages: [],
50
- extra_checks: ['risk-scout', 'code-quality-gate', 'human-security-review'],
51
- },
52
- };
53
-
54
- type Lane = keyof typeof plans;
55
-
56
- export interface ChangeSet {
57
- files: readonly string[];
58
- added: number;
59
- removed: number;
60
- }
61
-
62
- export interface LaneReport {
63
- lane: Lane;
64
- reasons: readonly string[];
65
- files_changed: number;
66
- lines_added: number;
67
- lines_removed: number;
68
- lines_changed: number;
69
- files: readonly string[];
70
- test_mode: string;
71
- required_stages: readonly string[];
72
- skipped_stages: readonly string[];
73
- extra_checks: readonly string[];
74
- }
75
-
76
- function normalize(path: string): string {
77
- return path.replaceAll('\\', '/');
78
- }
79
-
80
- function isHighRisk(path: string): boolean {
81
- // Python re.I adds these four case equivalents for ASCII letters in the patterns.
82
- const norm = normalize(path)
83
- .replace(/[İı]/g, 'i').replace(/ſ/g, 's').replace(/K/g, 'k');
84
- // Python's $ also accepts the position just before a final newline.
85
- const subject = norm.endsWith('\n') ? norm.slice(0, -1) : norm;
86
- return riskPatterns.some((pattern) => pattern.test(subject));
87
- }
88
-
89
- function isTrivial(path: string, windows: boolean): boolean {
90
- const norm = normalize(path);
91
- const local = windows ? norm.slice(win32.parse(norm).root.length) : norm;
92
- // pathlib ignores trailing slash and "." components, but does not collapse "..".
93
- const parts = local.split('/');
94
- const name = parts.filter((part) => part !== '' && part !== '.').at(-1) ?? '';
95
- const dot = name.lastIndexOf('.');
96
- return trivialNames.has(name) || (dot > 0 && trivialExtensions.has(name.slice(dot).toLowerCase()));
97
- }
98
-
99
- function decide({ files, added, removed }: ChangeSet, windows: boolean): [Lane, string[]] {
100
- if (files.length === 0) return ['trivial', ['No changed files detected.']];
101
-
102
- const hits = files.filter(isHighRisk);
103
- const lines = added + removed;
104
- const reasons: string[] = [];
105
- if (hits.length > 0) reasons.push(`Touched high-risk path(s): ${hits.slice(0, 5).join(', ')}`);
106
- if (lines > largeLines) reasons.push(`Large diff (${lines} lines > ${largeLines}).`);
107
- if (files.length > largeFiles) reasons.push(`Broad change (${files.length} files > ${largeFiles}).`);
108
- if (reasons.length > 0) return ['high-risk', reasons];
109
- if (files.every((path) => isTrivial(path, windows))) {
110
- return ['trivial', ['Only documentation, markdown, or visual assets changed.']];
111
- }
112
- return ['standard', ['Scoped code or skill change without high-risk paths or oversized diff.']];
113
- }
114
-
115
- export function classify(change: ChangeSet, windows: boolean): LaneReport {
116
- const { files, added, removed } = change;
117
- const [lane, reasons] = decide(change, windows);
118
- return {
119
- lane,
120
- reasons,
121
- files_changed: files.length,
122
- lines_added: added,
123
- lines_removed: removed,
124
- lines_changed: added + removed,
125
- files,
126
- ...plans[lane],
127
- };
128
- }
@@ -1,110 +0,0 @@
1
- /**
2
- * LAYER: Infrastructure
3
- * Contains: Git diff and working-tree statistics adapter.
4
- * Rules: Read only; use Git's NUL-delimited paths and ignore untracked non-files.
5
- * BigO: O(n log n) score:2
6
- * keywords: [GitDiff, ChangeStatistics]
7
- * GOAL: Collect the paths and line counts consumed by the classifier.
8
- */
9
- import { spawnSync } from 'node:child_process';
10
- import { readFileSync, statSync } from 'node:fs';
11
- import type { ChangeSet } from './classification.ts';
12
-
13
- export type GitSelection =
14
- | { mode: 'working' | 'staged' }
15
- | { mode: 'range' | 'head'; value: string };
16
-
17
- const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
18
- const diff = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff', '--no-textconv'];
19
-
20
- function git(args: readonly string[]): Buffer | undefined {
21
- const result = spawnSync('git', args, {
22
- env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_NO_LAZY_FETCH: '1' },
23
- timeout: 10_000,
24
- maxBuffer: Number.MAX_SAFE_INTEGER,
25
- });
26
- return result.status === 0 && !result.error ? result.stdout : undefined;
27
- }
28
-
29
- function diffArguments(selection: GitSelection): string[] {
30
- switch (selection.mode) {
31
- case 'working':
32
- return git(['rev-parse', '--verify', 'HEAD']) === undefined ? ['--staged'] : ['HEAD'];
33
- case 'staged':
34
- return ['--staged'];
35
- case 'range':
36
- return [selection.value];
37
- case 'head':
38
- return [`HEAD~${selection.value}..HEAD`];
39
- }
40
- }
41
-
42
- function paths(raw: Buffer): string[] | undefined {
43
- try {
44
- return decoder.decode(raw).split('\0').filter(Boolean);
45
- } catch {
46
- return undefined;
47
- }
48
- }
49
-
50
- function isRegularFile(path: string): boolean {
51
- try {
52
- return statSync(path).isFile();
53
- } catch {
54
- return false;
55
- }
56
- }
57
-
58
- function untrackedPaths(): string[] | undefined {
59
- const raw = git(['-c', 'core.quotePath=false', 'ls-files', '--others', '--exclude-standard', '-z']);
60
- if (raw === undefined) return [];
61
- return paths(raw)?.filter(isRegularFile);
62
- }
63
-
64
- function trackedCounts(args: string[], files: string[]): [number, number] {
65
- if (files.length === 0) return [0, 0];
66
- const raw = git([...diff, ...args, '--numstat', '--', ...files]);
67
- if (raw === undefined) return [0, 0];
68
- let added = 0;
69
- let removed = 0;
70
- for (const row of raw.toString('utf8').split('\n')) {
71
- const [plus = '', minus = ''] = row.split('\t', 2);
72
- if (/^[0-9]+$/.test(plus)) added += Number(plus);
73
- if (/^[0-9]+$/.test(minus)) removed += Number(minus);
74
- }
75
- return [added, removed];
76
- }
77
-
78
- function countNewlines(path: string): number {
79
- let data: Buffer;
80
- try {
81
- data = readFileSync(path);
82
- } catch {
83
- return 0;
84
- }
85
- let lines = 0;
86
- for (const byte of data) {
87
- if (byte === 0x0a) lines++;
88
- }
89
- return lines;
90
- }
91
-
92
- function sortedFiles(tracked: string[], untracked: string[]): string[] {
93
- // UTF-8 byte sorting preserves Python's code-point order for valid UTF-8 names.
94
- return Array.from(new Set([...tracked, ...untracked]), (file) => ({ file, bytes: Buffer.from(file) }))
95
- .sort((a, b) => Buffer.compare(a.bytes, b.bytes))
96
- .map(({ file }) => file);
97
- }
98
-
99
- export function readGitChanges(selection: GitSelection): ChangeSet | undefined {
100
- const args = diffArguments(selection);
101
- const names = git([...diff, ...args, '--name-only', '-z']);
102
- if (names === undefined) return undefined;
103
- const tracked = paths(names);
104
- const untracked = selection.mode === 'working' ? untrackedPaths() : [];
105
- if (tracked === undefined || untracked === undefined) return undefined;
106
-
107
- const [added, removed] = trackedCounts(args, tracked);
108
- const untrackedLines = untracked.reduce((sum, path) => sum + countNewlines(path), 0);
109
- return { files: sortedFiles(tracked, untracked), added: added + untrackedLines, removed };
110
- }