@bbcsoftwarefactory/cli 0.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/dist/audit-ledger.d.ts +2 -0
  2. package/dist/audit-ledger.js +71 -0
  3. package/dist/bbc-install.d.ts +2 -0
  4. package/dist/bbc-install.js +1250 -0
  5. package/dist/bbc.d.ts +2 -0
  6. package/dist/bbc.js +124 -0
  7. package/dist/bigo/complexity.d.ts +18 -0
  8. package/dist/bigo/complexity.js +139 -0
  9. package/dist/bigo/functions.d.ts +5 -0
  10. package/dist/bigo/functions.js +174 -0
  11. package/dist/bigo/keywords.d.ts +1 -0
  12. package/dist/bigo/keywords.js +43 -0
  13. package/dist/bigo/lexical.d.ts +14 -0
  14. package/dist/bigo/lexical.js +69 -0
  15. package/dist/bigo/source-files.d.ts +1 -0
  16. package/dist/bigo/source-files.js +80 -0
  17. package/dist/change-lane/classification.d.ts +41 -0
  18. package/dist/change-lane/classification.js +104 -0
  19. package/dist/change-lane/git.d.ts +8 -0
  20. package/dist/change-lane/git.js +105 -0
  21. package/dist/check-issue-claim.d.ts +2 -0
  22. package/dist/check-issue-claim.js +146 -0
  23. package/dist/check-worktree-guard.d.ts +2 -0
  24. package/dist/check-worktree-guard.js +114 -0
  25. package/dist/classify-change-lane.d.ts +2 -0
  26. package/dist/classify-change-lane.js +128 -0
  27. package/dist/diff-scope/git-diff.d.ts +25 -0
  28. package/dist/diff-scope/git-diff.js +146 -0
  29. package/dist/error-scan.d.ts +3 -0
  30. package/dist/error-scan.js +216 -0
  31. package/dist/export-public.d.ts +9 -0
  32. package/dist/export-public.js +274 -0
  33. package/dist/extract-diff-scope.d.ts +2 -0
  34. package/dist/extract-diff-scope.js +111 -0
  35. package/dist/fetch-issue-attachments.d.ts +22 -0
  36. package/dist/fetch-issue-attachments.js +325 -0
  37. package/dist/issue-claim/evaluation.d.ts +66 -0
  38. package/dist/issue-claim/evaluation.js +259 -0
  39. package/dist/issue-claim/loaders.d.ts +5 -0
  40. package/dist/issue-claim/loaders.js +116 -0
  41. package/dist/list-zed-commands.d.ts +7 -0
  42. package/dist/list-zed-commands.js +288 -0
  43. package/dist/measure-bigo.d.ts +2 -0
  44. package/dist/measure-bigo.js +84 -0
  45. package/dist/plan-issue-triage.d.ts +3 -0
  46. package/dist/plan-issue-triage.js +404 -0
  47. package/dist/question-gate/ledger.d.ts +5 -0
  48. package/dist/question-gate/ledger.js +115 -0
  49. package/dist/question-gate/rules.d.ts +40 -0
  50. package/dist/question-gate/rules.js +483 -0
  51. package/dist/recap/board.d.ts +5 -0
  52. package/dist/recap/board.js +384 -0
  53. package/dist/recap/git-and-github.d.ts +11 -0
  54. package/dist/recap/git-and-github.js +620 -0
  55. package/dist/recap/report-and-hud.d.ts +2 -0
  56. package/dist/recap/report-and-hud.js +294 -0
  57. package/dist/recap/time-and-refs.d.ts +27 -0
  58. package/dist/recap/time-and-refs.js +148 -0
  59. package/dist/recap.d.ts +2 -0
  60. package/dist/recap.js +217 -0
  61. package/dist/render-workflow.d.ts +2 -0
  62. package/dist/render-workflow.js +142 -0
  63. package/dist/resolve-containers.d.ts +2 -0
  64. package/dist/resolve-containers.js +96 -0
  65. package/dist/review-loop.d.ts +7 -0
  66. package/dist/review-loop.js +622 -0
  67. package/dist/save-counts.d.ts +2 -0
  68. package/dist/save-counts.js +191 -0
  69. package/dist/summarize-logs.d.ts +2 -0
  70. package/dist/summarize-logs.js +41 -0
  71. package/dist/sweep-github.d.ts +10 -0
  72. package/dist/sweep-github.js +453 -0
  73. package/dist/sweep-issues.d.ts +56 -0
  74. package/dist/sweep-issues.js +650 -0
  75. package/dist/sweep.d.ts +2 -0
  76. package/dist/sweep.js +301 -0
  77. package/dist/triage-question.d.ts +2 -0
  78. package/dist/triage-question.js +189 -0
  79. package/dist/validate-skills.d.ts +2 -0
  80. package/dist/validate-skills.js +48 -0
  81. package/dist/watch-live.d.ts +7 -0
  82. package/dist/watch-live.js +83 -0
  83. package/dist/watcher/config.d.ts +11 -0
  84. package/dist/watcher/config.js +265 -0
  85. package/dist/watcher/live-classifier.d.ts +52 -0
  86. package/dist/watcher/live-classifier.js +510 -0
  87. package/dist/watcher/safe-fs.d.ts +9 -0
  88. package/dist/watcher/safe-fs.js +159 -0
  89. package/dist/watcher/stream.d.ts +27 -0
  90. package/dist/watcher/stream.js +340 -0
  91. package/dist/watcher/summarizer.d.ts +19 -0
  92. package/dist/watcher/summarizer.js +121 -0
  93. package/dist/wave3/process.d.ts +14 -0
  94. package/dist/wave3/process.js +84 -0
  95. package/dist/wave4/process.d.ts +14 -0
  96. package/dist/wave4/process.js +128 -0
  97. package/dist/workflow/render.d.ts +13 -0
  98. package/dist/workflow/render.js +31 -0
  99. package/dist/workflow/schema.d.ts +25 -0
  100. package/dist/workflow/schema.js +99 -0
  101. package/dist/workflow-auditor/audit.d.ts +27 -0
  102. package/dist/workflow-auditor/audit.js +583 -0
  103. package/dist/workflow-auditor/ledger-io.d.ts +5 -0
  104. package/dist/workflow-auditor/ledger-io.js +99 -0
  105. package/dist/workflow-auditor/skills-validator.d.ts +10 -0
  106. package/dist/workflow-auditor/skills-validator.js +533 -0
  107. package/dist/worktree-guard/evaluation.d.ts +19 -0
  108. package/dist/worktree-guard/evaluation.js +84 -0
  109. package/dist/worktree-guard/git.d.ts +3 -0
  110. package/dist/worktree-guard/git.js +61 -0
  111. package/package.json +32 -33
  112. package/src/bbc.ts +0 -39
  113. package/src/bigo/complexity.ts +0 -138
  114. package/src/bigo/functions.ts +0 -183
  115. package/src/bigo/keywords.ts +0 -41
  116. package/src/bigo/lexical.ts +0 -68
  117. package/src/bigo/source-files.ts +0 -80
  118. package/src/change-lane/classification.ts +0 -128
  119. package/src/change-lane/git.ts +0 -110
  120. package/src/classify-change-lane.ts +0 -140
  121. package/src/diff-scope/git-diff.ts +0 -161
  122. package/src/extract-diff-scope.ts +0 -130
  123. package/src/measure-bigo.ts +0 -86
  124. package/src/render-workflow.ts +0 -144
  125. package/src/workflow/render.ts +0 -40
  126. package/src/workflow/schema.ts +0 -141
@@ -0,0 +1,84 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Worktree guard evaluation and hook payload formatting.
4
+ * Rules: Pure policy rules only; never invoke git or read the filesystem.
5
+ * BigO: O(n) score:3
6
+ * keywords: [WorktreePolicy, HookFormat]
7
+ * GOAL: Decide whether a target worktree and branch satisfy feat/<task> isolation.
8
+ */
9
+ import { pythonRepr } from '@bbcsoftwarefactory/cli-core/python-compat';
10
+ const PROTECTED_BRANCHES = new Set(['main', 'master', 'HEAD']);
11
+ export function evaluateGitInfo(info) {
12
+ const { branch, is_linked_worktree: isLinked, toplevel } = info;
13
+ const isFeat = branch.startsWith('feat/') && branch.length > 'feat/'.length;
14
+ if (!isLinked) {
15
+ return {
16
+ report: {
17
+ decision: 'block',
18
+ is_linked_worktree: false,
19
+ branch,
20
+ toplevel,
21
+ reason: `Blocked write in primary checkout (branch ${pythonRepr(branch)}). Prepare a linked Git worktree on feat/<task> first.`,
22
+ },
23
+ status: 1,
24
+ };
25
+ }
26
+ if (PROTECTED_BRANCHES.has(branch) || !isFeat) {
27
+ return {
28
+ report: {
29
+ decision: 'block',
30
+ is_linked_worktree: true,
31
+ branch,
32
+ toplevel,
33
+ reason: `Blocked write on non-feature branch ${pythonRepr(branch)}. Worktrees must use a unique feat/<task> branch.`,
34
+ },
35
+ status: 1,
36
+ };
37
+ }
38
+ return {
39
+ report: {
40
+ decision: 'allow',
41
+ is_linked_worktree: true,
42
+ branch,
43
+ toplevel,
44
+ reason: `Verified linked worktree on ${branch}.`,
45
+ },
46
+ status: 0,
47
+ };
48
+ }
49
+ export function extractPayloadPath(payload) {
50
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload))
51
+ return undefined;
52
+ const record = payload;
53
+ const toolInput = record.tool_input;
54
+ if (typeof toolInput === 'object' && toolInput !== null && !Array.isArray(toolInput)) {
55
+ const nested = toolInput;
56
+ for (const key of ['file_path', 'path', 'target_file', 'working_directory']) {
57
+ const value = nested[key];
58
+ if (typeof value === 'string' && value.trim() !== '')
59
+ return value.trim();
60
+ }
61
+ }
62
+ for (const key of ['file_path', 'path', 'cwd', 'working_directory']) {
63
+ const value = record[key];
64
+ if (typeof value === 'string' && value.trim() !== '')
65
+ return value.trim();
66
+ }
67
+ return undefined;
68
+ }
69
+ export function formatHookOutput(report, status, format) {
70
+ if (status === 0 || status === 2)
71
+ return {};
72
+ const { reason } = report;
73
+ if (format === 'cursor-hook') {
74
+ return {
75
+ permission: 'deny',
76
+ user_message: reason,
77
+ agent_message: reason,
78
+ };
79
+ }
80
+ return {
81
+ decision: 'block',
82
+ reason,
83
+ };
84
+ }
@@ -0,0 +1,3 @@
1
+ import type { GitWorktreeInfo } from './evaluation.ts';
2
+ export declare function findExistingDirectory(pathStr: string): string | undefined;
3
+ export declare function probeGitWorktree(directory: string): GitWorktreeInfo | undefined;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * LAYER: Infrastructure
3
+ * Contains: Read-only filesystem ancestor resolution and git rev-parse probing.
4
+ * Rules: Read-only git queries only; never modify files or git state.
5
+ * BigO: O(n) score:3
6
+ * keywords: [GitWorktreeProbe, AncestorResolve]
7
+ * GOAL: Inspect the nearest existing directory and read linked-worktree metadata from git.
8
+ */
9
+ import { spawnSync } from 'node:child_process';
10
+ import { existsSync, realpathSync, statSync } from 'node:fs';
11
+ import { homedir } from 'node:os';
12
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
13
+ function expandUser(raw) {
14
+ if (raw === '~')
15
+ return homedir();
16
+ if (raw.startsWith('~/') || raw.startsWith('~\\'))
17
+ return join(homedir(), raw.slice(2));
18
+ return raw;
19
+ }
20
+ function resolveSafe(path) {
21
+ try {
22
+ return existsSync(path) ? realpathSync.native(path) : resolve(path);
23
+ }
24
+ catch {
25
+ return resolve(path);
26
+ }
27
+ }
28
+ export function findExistingDirectory(pathStr) {
29
+ let cur = resolveSafe(expandUser(pathStr));
30
+ while (!existsSync(cur)) {
31
+ const parent = dirname(cur);
32
+ if (parent === cur)
33
+ break;
34
+ cur = parent;
35
+ }
36
+ if (!existsSync(cur))
37
+ return undefined;
38
+ try {
39
+ return statSync(cur).isDirectory() ? cur : dirname(cur);
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
45
+ export function probeGitWorktree(directory) {
46
+ const result = spawnSync('git', ['-C', directory, 'rev-parse', '--git-dir', '--git-common-dir', '--abbrev-ref', 'HEAD', '--show-toplevel'], { timeout: 10_000, encoding: 'latin1' });
47
+ if (result.error || result.signal || result.status !== 0)
48
+ return undefined;
49
+ const lines = Buffer.from(result.stdout, 'latin1').toString('utf8').split(/\r?\n/);
50
+ if (lines.length < 4)
51
+ return undefined;
52
+ const [gitDirRaw = '', commonDirRaw = '', branchRaw = '', toplevel = ''] = lines;
53
+ const branch = branchRaw.trim();
54
+ const gitDir = resolveSafe(isAbsolute(gitDirRaw) ? gitDirRaw : resolve(directory, gitDirRaw));
55
+ const commonDir = resolveSafe(isAbsolute(commonDirRaw) ? commonDirRaw : resolve(directory, commonDirRaw));
56
+ return {
57
+ is_linked_worktree: gitDir !== commonDir,
58
+ branch,
59
+ toplevel,
60
+ };
61
+ }
package/package.json CHANGED
@@ -1,33 +1,32 @@
1
- {
2
- "name": "@bbcsoftwarefactory/cli",
3
- "version": "0.1.0",
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": "./src/bbc.ts"
12
- },
13
- "files": [
14
- "src/",
15
- "!src/**/*.test.ts"
16
- ],
17
- "dependencies": {
18
- "@bbcsoftwarefactory/cli-core": "^0.1.0"
19
- },
20
- "scripts": {
21
- "test": "node --test \"src/*.test.ts\"",
22
- "pack:check": "npm pack --dry-run"
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
- }
1
+ {
2
+ "name": "@bbcsoftwarefactory/cli",
3
+ "version": "1.1.2",
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": "^1.1.2"
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
+ }
32
+ }
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
- }
@@ -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
- }