@bbcsoftwarefactory/skills 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.
Files changed (100) hide show
  1. package/dist/index.json +42 -0
  2. package/dist/skills/code-quality-gate/SKILL.md +59 -0
  3. package/dist/skills/code-quality-gate/references/gate-bigo.md +31 -0
  4. package/dist/skills/code-quality-gate/references/gate-earlyreturn.md +73 -0
  5. package/dist/skills/code-quality-gate/references/gate-typesafe.md +32 -0
  6. package/dist/skills/code-quality-gate/references/output-schema.yml +40 -0
  7. package/dist/skills/code-quality-gate/scripts/extract-diff-scope.py +225 -0
  8. package/dist/skills/code-quality-gate/tests/extract-diff-scope.test.sh +200 -0
  9. package/dist/skills/delivery-coordinator/SKILL.md +81 -0
  10. package/dist/skills/delivery-coordinator/references/hud-output.md +55 -0
  11. package/dist/skills/delivery-coordinator/references/intake.md +86 -0
  12. package/dist/skills/delivery-coordinator/references/issue-claim.md +143 -0
  13. package/dist/skills/delivery-coordinator/references/issue-dedup.md +38 -0
  14. package/dist/skills/delivery-coordinator/references/sleuth-regression-exercise.md +60 -0
  15. package/dist/skills/delivery-coordinator/references/visual-reference.md +45 -0
  16. package/dist/skills/delivery-coordinator/references/worktree-isolation.md +19 -0
  17. package/dist/skills/delivery-coordinator/scripts/check-issue-claim.py +363 -0
  18. package/dist/skills/delivery-coordinator/scripts/check-worktree-guard.py +220 -0
  19. package/dist/skills/delivery-coordinator/scripts/classify-change-lane.py +263 -0
  20. package/dist/skills/delivery-coordinator/tests/check-issue-claim.test.sh +221 -0
  21. package/dist/skills/delivery-coordinator/tests/check-worktree-guard.test.sh +123 -0
  22. package/dist/skills/delivery-coordinator/tests/classify-change-lane.test.sh +124 -0
  23. package/dist/skills/documentation-steward/SKILL.md +43 -0
  24. package/dist/skills/documentation-steward/references/discovery.md +17 -0
  25. package/dist/skills/documentation-steward/references/handoff.md +15 -0
  26. package/dist/skills/greptile-review-loop/SKILL.md +57 -0
  27. package/dist/skills/greptile-review-loop/references/review-protocol.md +37 -0
  28. package/dist/skills/greptile-review-loop/scripts/review-loop.py +435 -0
  29. package/dist/skills/greptile-review-loop/tests/review-loop.test.sh +331 -0
  30. package/dist/skills/issue-reviewer/SKILL.md +87 -0
  31. package/dist/skills/issue-reviewer/references/review-format.md +100 -0
  32. package/dist/skills/issue-reviewer/references/triage.md +105 -0
  33. package/dist/skills/issue-reviewer/scripts/fetch-issue-attachments.py +239 -0
  34. package/dist/skills/issue-reviewer/scripts/plan-issue-triage.py +311 -0
  35. package/dist/skills/issue-reviewer/tests/fetch-issue-attachments.test.sh +90 -0
  36. package/dist/skills/issue-reviewer/tests/plan-issue-triage.test.sh +168 -0
  37. package/dist/skills/question-gate/SKILL.md +66 -0
  38. package/dist/skills/question-gate/references/client-hooks.md +111 -0
  39. package/dist/skills/question-gate/references/diagram-routing.md +58 -0
  40. package/dist/skills/question-gate/scripts/triage-question.py +713 -0
  41. package/dist/skills/question-gate/tests/fixtures/question-corpus.json +481 -0
  42. package/dist/skills/question-gate/tests/question-corpus.test.sh +32 -0
  43. package/dist/skills/question-gate/tests/triage-question.test.sh +441 -0
  44. package/dist/skills/regression-testing/SKILL.md +49 -0
  45. package/dist/skills/regression-testing/references/evidence-record.md +35 -0
  46. package/dist/skills/requirements-spec/SKILL.md +59 -0
  47. package/dist/skills/risk-scout/SKILL.md +53 -0
  48. package/dist/skills/risk-scout/references/risk-matrix.md +49 -0
  49. package/dist/skills/skill-clean-architecture/SKILL.md +54 -0
  50. package/dist/skills/skill-clean-architecture/references/layer-rules.md +22 -0
  51. package/dist/skills/skill-clean-architecture/references/source-headers.md +31 -0
  52. package/dist/skills/skill-clean-architecture/scripts/measure-bigo.py +427 -0
  53. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/bad-utf8.js +1 -0
  54. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-crlf.ts +6 -0
  55. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-mixed.ts +15 -0
  56. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/empty.js +0 -0
  57. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/no-newline.js +1 -0
  58. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo.expected.yml +95 -0
  59. package/dist/skills/skill-clean-architecture/tests/measure-bigo.test.sh +222 -0
  60. package/dist/skills/tool-depot/SKILL.md +47 -0
  61. package/dist/skills/tool-depot/references/checkout.md +29 -0
  62. package/dist/skills/tool-depot/references/loki-read.md +41 -0
  63. package/dist/skills/tool-depot/references/readonly-access.md +84 -0
  64. package/dist/skills/tool-depot/references/tool-catalog.json +47 -0
  65. package/dist/skills/tool-depot/scripts/loki-runtime-logs.py +305 -0
  66. package/dist/skills/tool-depot/tests/loki-runtime-logs.test.sh +101 -0
  67. package/dist/skills/watcher-observability/SKILL.md +73 -0
  68. package/dist/skills/watcher-observability/references/batch-protocol.md +44 -0
  69. package/dist/skills/watcher-observability/references/configuration.md +31 -0
  70. package/dist/skills/watcher-observability/references/error-scan.md +102 -0
  71. package/dist/skills/watcher-observability/references/live-protocol.md +49 -0
  72. package/dist/skills/watcher-observability/references/server-account.md +72 -0
  73. package/dist/skills/watcher-observability/scripts/error-scan.py +318 -0
  74. package/dist/skills/watcher-observability/scripts/resolve-containers.py +155 -0
  75. package/dist/skills/watcher-observability/scripts/save-counts.py +381 -0
  76. package/dist/skills/watcher-observability/scripts/summarize-logs.py +113 -0
  77. package/dist/skills/watcher-observability/scripts/watch-live.py +606 -0
  78. package/dist/skills/watcher-observability/server/watcher-gate.sh +51 -0
  79. package/dist/skills/watcher-observability/tests/error-scan.test.sh +257 -0
  80. package/dist/skills/watcher-observability/tests/live-windows.test.sh +177 -0
  81. package/dist/skills/watcher-observability/tests/resolve-containers.test.sh +87 -0
  82. package/dist/skills/watcher-observability/tests/save-counts.test.sh +338 -0
  83. package/dist/skills/watcher-observability/tests/sleuth.test.sh +176 -0
  84. package/dist/skills/watcher-observability/tests/summarize-logs.test.sh +105 -0
  85. package/dist/skills/watcher-observability/tests/watcher-config.test.sh +70 -0
  86. package/dist/skills/watcher-observability/tests/watcher-gate.test.sh +110 -0
  87. package/dist/skills/watcher-observability/watcher.json +1 -0
  88. package/dist/skills/workflow-auditor/SKILL.md +55 -0
  89. package/dist/skills/workflow-auditor/references/audit-protocol.md +49 -0
  90. package/dist/skills/workflow-auditor/references/ledger.md +122 -0
  91. package/dist/skills/workflow-auditor/scripts/audit-ledger.py +624 -0
  92. package/dist/skills/workflow-auditor/scripts/list-zed-commands.py +183 -0
  93. package/dist/skills/workflow-auditor/scripts/render-workflow.py +201 -0
  94. package/dist/skills/workflow-auditor/scripts/validate-skills.py +444 -0
  95. package/dist/skills/workflow-auditor/tests/audit-ledger.test.sh +660 -0
  96. package/dist/skills/workflow-auditor/tests/list-zed-commands.test.sh +93 -0
  97. package/dist/skills/workflow-auditor/tests/render-workflow.test.sh +135 -0
  98. package/dist/skills/workflow-auditor/tests/validate-skills.test.sh +190 -0
  99. package/package.json +27 -6
  100. package/README.md +0 -3
@@ -0,0 +1,49 @@
1
+ # Research protocol and risk matrix
2
+
3
+ ## Research common failures
4
+
5
+ 1. Use public component names, versions, and generic symptoms. Try distinct queries: official docs/release notes, upstream GitHub issues/discussions, and community reports (Reddit, Stack Overflow, or a project forum).
6
+ 2. Fetch the strongest results and inspect the relevant issue or discussion, not just the search snippet. Record the source link, affected version and environment, prerequisites, and whether a maintainer confirmed the behavior or released a fix. Note if your target version or conditions differ. If a page cannot be read, mark it unverified.
7
+ 3. Prefer local evidence and primary sources. Use community reports as leads, not proof; duplicate reposts are not independent corroboration. If there is no relevant source, say what was searched and keep the item a hypothesis.
8
+ 4. Check only failure modes relevant to the change: compatibility, incorrect data, operational limits, dependency failures, concurrency, detection gaps, or difficulty recovering. Do not assume every category applies.
9
+
10
+ ## Qualitative scoring
11
+
12
+ | Rating | Likelihood | Impact |
13
+ |---|---|---|
14
+ | Low | Requires unusual conditions and a relevant, verified control limits exposure | Local, reversible degradation with no material data or service loss |
15
+ | Medium | Credible and applicable under specific conditions, but not demonstrated as routine | Meaningful disruption or manual recovery for a limited scope |
16
+ | High | Reproduced in the target context or supported by strong evidence under routine conditions | Broad or prolonged outage, material loss, exposure, or difficult recovery |
17
+ | Unknown | Necessary context or evidence is missing | Blast radius or recovery consequences cannot be established |
18
+
19
+ | Likelihood ↓ / Impact → | Low | Medium | High |
20
+ |---|---|---|---|
21
+ | Low | Low | Low | Medium |
22
+ | Medium | Low | Medium | High |
23
+ | High | Medium | High | Critical |
24
+
25
+ If either input is unknown, report **Unrated** and name the missing information. Flag a possible high-impact outcome for early verification even if likelihood is unknown. Confidence is separate: **high** for direct, applicable verification; **medium** for credible, applicable external evidence without local verification; **low** for anecdotes, version mismatch, or hypotheses. This is a local qualitative rubric, not a probability or the host's native review tier.
26
+
27
+ ## Five scenarios: happy path to cascading failure
28
+
29
+ Write one scenario per level for the same assessed change. Increase the consequences, not the claimed likelihood.
30
+
31
+ | Level | Scenario | Question to answer |
32
+ |---|---|---|
33
+ | 1 | Happy path | Under normal conditions, what observable result proves success? |
34
+ | 2 | Recoverable failure | If one operation fails transiently, does retry, fallback, or a clear error keep the impact local? |
35
+ | 3 | Partial degradation | If a dependency slows down or only part of the work succeeds, which users or data are affected and which guarantees still hold? |
36
+ | 4 | Major incident | If the primary path fails persistently, how do we detect it, limit its impact, and recover? |
37
+ | 5 | Cascading failure | In the worst plausible case, which safeguards fail together, how does the impact spread, and what breaks the chain? |
38
+
39
+ For each level, state the initial conditions and trigger, observable result or symptom, affected scope, early signal, and a proposed safe verification. For failure scenarios, add containment or recovery and related risk IDs. If the level is not supported by the scope or evidence, keep it in the list and mark it not applicable or hypothetical with the reason. Do not invent an outage, treat a severe scenario as likely, execute chaos experiments, or touch production. Propose tabletop exercises or isolated synthetic tests only.
40
+
41
+ ## Report format
42
+
43
+ | ID | Failure mode and trigger | Likelihood | Impact and affected scope | Priority | Confidence and evidence | Mitigation, early signal, and safe verification |
44
+ |---|---|---|---|---|---|---|
45
+ | R1 | Example: a retry after a lost acknowledgement may repeat a write | Unknown | High if the affected write is irreversible | Unrated — verify early | Low; hypothesis, no target reproduction | Verify with an isolated fixture whether repeating the same request creates a duplicate. |
46
+
47
+ For each priority risk, state the next observable check and who would need to decide if the risk cannot be reduced. Do not lower the rating based on an unverified proposed mitigation.
48
+
49
+ Method references: [NIST risk assessment guide](https://csrc.nist.gov/pubs/sp/800/30/r1/final) for separating likelihood and impact; [Google SRE canarying releases](https://sre.google/workbook/canarying-releases/) for blast radius and detection. The scoring table above is specific to this skill.
@@ -0,0 +1,54 @@
1
+ ---
2
+ name: skill-clean-architecture
3
+ description: "Trigger: DDD, hexagonal architecture, Clean Architecture, Clean Code. Implement or refactor code with clear layer boundaries and mandatory source headers."
4
+ license: Apache-2.0
5
+ compatibility: Requires Python 3.8+ for the Big O scorer (standard library only; Linux, macOS and Windows).
6
+ metadata:
7
+ author: leifermendez
8
+ version: "2.4"
9
+ post_hook: "python3 -I -B scripts/measure-bigo.py <file-or-dir>"
10
+ scripts: "scripts/measure-bigo.py"
11
+ ---
12
+
13
+ ## Activation Contract
14
+
15
+ Apply when implementing, reviewing, or refactoring code where domain boundaries, ports and adapters, or Clean Code are in scope.
16
+
17
+ **Company role:** Software Engineer. Production changes require explicit authorization from the human Tech Lead or project owner.
18
+
19
+ ## Hard Rules
20
+
21
+ - Keep invariants in Domain; orchestrate them in Application; isolate external I/O in Infrastructure; translate requests and responses in Interface. Dependencies point inward.
22
+ - Put ports in the inner layer that owns the contract. Wire concrete adapters at the composition root. Keep framework, persistence, and transport types out of the core.
23
+ - Prefer explicit types, guard clauses, and small units with one responsibility. Do not add CQRS, event buses, or abstraction layers without a concrete need.
24
+ - Give every new or edited source file the mandatory header from [Source headers](references/source-headers.md). Copy `header_bigo` from the bundled scorer; never invent it.
25
+
26
+ ## Decision Gates
27
+
28
+ | If | Then |
29
+ |---|---|
30
+ | A business invariant must hold regardless of the caller | Put it in Domain. |
31
+ | A use case needs external I/O | Define an inner-layer port and inject an adapter. |
32
+ | A refactor crosses an existing boundary | Make the smallest behavior-preserving change and verify it before continuing. |
33
+
34
+ ## Execution Steps
35
+
36
+ 1. Locate the source roots and composition root; trace the affected use case and its dependencies.
37
+ 2. Classify the affected files and check the [layer rules](references/layer-rules.md) before editing.
38
+ 3. Make the scoped change and run applicable focused tests.
39
+ 4. Score each new or edited source file; finalize each header. Rerun the scorer if control flow changes.
40
+
41
+ ## Companion Handoffs
42
+
43
+ After implementation, look for `regression-testing` for verification and `code-quality-gate` for slice quality. Pass the affected criteria and exact diff or revision.
44
+
45
+ Check the active skill catalog for the named companion before relying on it. If availability is unknown and its help is needed, ask whether it is available; do not ask when equivalent evidence already satisfies the handoff. Never assume installation, install automatically, or transfer permissions.
46
+
47
+ ## Output Contract
48
+
49
+ Report changed files by layer, boundary violations found or fixed, verification results, and any file whose mandatory header could not be verified.
50
+
51
+ ## References
52
+
53
+ - [Layer rules and Clean Code checks](references/layer-rules.md)
54
+ - [Source headers and scoring](references/source-headers.md)
@@ -0,0 +1,22 @@
1
+ # Layer rules and Clean Code checks
2
+
3
+ | Layer | Owns | Keep out |
4
+ |---|---|---|
5
+ | Domain | Entities, value objects, business invariants, domain-owned repository contracts | HTTP, ORM, database clients, framework decorators |
6
+ | Application | Use-case orchestration, input/output DTOs, application-owned ports | Business invariants duplicated from entities, concrete adapters |
7
+ | Infrastructure | Database and external API adapters, mapping, provider configuration | Business decisions, transport-specific response formatting |
8
+ | Interface | HTTP, CLI, or event entry points; boundary validation and response mapping | Business decisions and direct persistence calls |
9
+
10
+ ## Dependency check
11
+
12
+ 1. Trace one request: entry point → use case → domain rule → port. The concrete adapter implements the port but the use case does not import it.
13
+ 2. Instantiate dependencies in the composition root. Use manual constructor injection unless the project already has an established mechanism.
14
+ 3. Convert external data at the boundary. Do not pass ORM models, request objects, or SDK types to inner layers.
15
+
16
+ ## Clean Code checks
17
+
18
+ - Use guard clauses for invalid or exceptional inputs. Keep the main path easy to follow.
19
+ - Use explicit types at boundaries. Treat untrusted TypeScript input as `unknown` and narrow or validate it before use.
20
+ - Keep use cases focused on one operation. Extract business decisions into domain behavior, not into thin wrappers that only hide line count.
21
+ - Document non-obvious contracts and side effects; do not restate the code.
22
+ - For incremental refactors, preserve observable behavior and verify the affected use case before moving other boundaries.
@@ -0,0 +1,31 @@
1
+ # Mandatory source headers
2
+
3
+ Add a header at the top of every new or edited source file. Use the language's comment syntax and preserve any required leading directives, such as a shebang. Keep these fields:
4
+
5
+ ```typescript
6
+ /**
7
+ * LAYER: Application
8
+ * Contains: Create user use case
9
+ * Rules: Orchestrates domain behavior through ports.
10
+ * BigO: O(1) score:5
11
+ * keywords: [CreateUserUseCase, IUserRepository, IIdGenerator]
12
+ * GOAL: Register a valid user and return its DTO.
13
+ */
14
+ ```
15
+
16
+ Use one of `Domain`, `Application`, `Infrastructure`, or `Interface`. Choose two to six PascalCase keywords that identify the use case or its collaborators. Write `GOAL` as one sentence about the file's responsibility.
17
+
18
+ ## Required scoring step
19
+
20
+ Run the [bundled scorer](../scripts/measure-bigo.py) by resolving its path from the directory containing `SKILL.md`:
21
+
22
+ ```bash
23
+ python3 -I -B <skill-root>/scripts/measure-bigo.py <source-file>
24
+ # Windows: py -3 -I -B <skill-root>\scripts\measure-bigo.py <source-file>
25
+ ```
26
+
27
+ Copy `header_bigo` into `BigO`. Treat `loc` and `code_lines` as diagnostics, not header fields. Rerun after control-flow changes. If the tool cannot run or produce a result, report the blocker instead of inserting a guessed score.
28
+
29
+ The scorer is a lexical heuristic, not a proof of runtime complexity. `O(1)` scores 5, `O(log n)` 4, `O(n)` 3, `O(n log n)` 2, and `O(n²)`/`O(n³)` 1. Do not rewrite a correct single pass to chase a higher score.
30
+
31
+ The header value is **per file**: the worst construct sets the file's value, so one quadratic helper marks the whole file `O(n²)`. To find which function it is, read `functions`: each named function (JavaScript/TypeScript functions, arrow functions assigned to a name, methods, Go `func`, Python `def`) gets its own `bigo` and `bigo_score`, measured on the lines it owns. A nested named function is measured on its own, while anonymous callbacks count toward the function that contains them. Check `signals` to see which construct triggered the file's value. It detects nested loops, `includes`/`indexOf` inside a loop, an iteration or search inside another call's callback on the same line (`ids.map(id => items.find(...))`), and object spread inside `reduce`. A sequential chain such as `a.filter(...).map(...)` stays `O(n)`. It does not follow calls into other functions or files.
@@ -0,0 +1,427 @@
1
+ #!/usr/bin/env python3
2
+ """measure-bigo.py: count lines and estimate a BigO score for the file-header contract.
3
+
4
+ BigO: O(n) score:3
5
+ keywords: [CreateUserUseCase, IUserRepository]
6
+ GOAL: <written by the agent, not by this script>
7
+
8
+ Score (5 is best). Do not rewrite a correct single pass just to raise it.
9
+ 5 O(1) no loop over unbounded data
10
+ 4 O(log n) logarithmic search (mid + low/high inside one loop)
11
+ 3 O(n) one pass, including several sequential passes
12
+ 2 O(n log n) sort
13
+ 1 O(n^2) nested loops, lookup inside a loop, or object-spread inside reduce
14
+ 1 O(n^3) three or more nested loops (same score, worse notation)
15
+
16
+ Usage (from the repo root):
17
+ python3 -I -B skills/skill-clean-architecture/scripts/measure-bigo.py <file-or-dir> [more...]
18
+ python3 -I -B .agents/skills/skill-clean-architecture/scripts/measure-bigo.py <file-or-dir> [more...]
19
+
20
+ Pure standard library, one process for every file: no awk, find or sort, so it
21
+ behaves the same on Linux, macOS and Windows.
22
+ """
23
+
24
+ from bisect import bisect_left
25
+ import os
26
+ import re
27
+ import sys
28
+
29
+ EXTENSIONS = ('.ts', '.tsx', '.js', '.mjs', '.cjs', '.py', '.java', '.go', '.php')
30
+ EXCLUDED = ('/node_modules/', '/dist/', '/.git/', '/coverage/')
31
+
32
+ ITER = r'forEach|map|filter|reduce|reduceRight|flatMap|some|every|find|findIndex'
33
+ # One alternation instead of six searches per line: minified bundles have lines of
34
+ # 100k+ characters, and this test runs on every line.
35
+ LOOP = re.compile('|'.join('(?:' + expr + ')' for expr in (
36
+ r'(^|[^A-Za-z0-9_.$])for\s*(await\s*)?\(',
37
+ r'(^|[^A-Za-z0-9_.$])for\s+',
38
+ r'(^|[^A-Za-z0-9_.$])while\s*\(',
39
+ r'(^|[^A-Za-z0-9_.$])while\s+.*:\s*$',
40
+ r'(^|[^A-Za-z0-9_.$])do\s*\{',
41
+ r'\.(' + ITER + r'|sort)\s*\(',
42
+ )), re.ASCII)
43
+ # The stripper jumps between these tokens instead of visiting every character.
44
+ SPECIAL = re.compile(r'//|/\*|["\'`]')
45
+ # Body of a string opened by the quote: escaped pairs or any other character, then
46
+ # the closing quote. A trailing lone backslash cannot match, which leaves the string
47
+ # unterminated to the end of the line, as the character loop did.
48
+ STRING_END = {q: re.compile(r'(?:[^\\' + q + r']|\\.)*' + q, re.S) for q in '"\'`'}
49
+ REDUCE = re.compile(r'\.reduce\s*\(', re.ASCII)
50
+ SORT = re.compile(r'\.sort\s*\(', re.ASCII)
51
+ LOOKUP = re.compile(r'\.(includes|indexOf)\s*\(', re.ASCII)
52
+ CALL = re.compile(r'\.(' + ITER + r')\s*\(', re.ASCII)
53
+ INNER = re.compile(r'\.(' + ITER + r'|includes|indexOf)\s*\(', re.ASCII)
54
+ SPREAD = re.compile(r'\.\.\.[A-Za-z_]')
55
+ MID = re.compile(r'(^|[^A-Za-z0-9_])mid([^A-Za-z0-9_]|$)')
56
+ BOUND = re.compile(r'(^|[^A-Za-z0-9_])(low|high|left|right)([^A-Za-z0-9_]|$)')
57
+ BLANK = re.compile(r'^[ \t]*$')
58
+ LONE_BRACE = re.compile(r'^[ \t]*\{[ \t]*$')
59
+
60
+ IMPORT_LINE = re.compile(r'^\s*import\s', re.ASCII)
61
+ EXPORT_LINE = re.compile(r'^\s*export\s', re.ASCII)
62
+ BRACES = re.compile(r'\{[^}]*\}')
63
+ EXPORT_DECL = re.compile(r'(class|interface|type|function|const|enum)\s+([A-Za-z_][A-Za-z0-9_]*)', re.ASCII)
64
+ KEYWORD_LIMIT = 12
65
+
66
+
67
+ class Stripper:
68
+ """Drop comments and string contents, carrying /* ... */ state across lines."""
69
+
70
+ def __init__(self):
71
+ self.in_block = False
72
+
73
+ def strip(self, line):
74
+ if self.in_block:
75
+ end = line.find('*/')
76
+ if end < 0:
77
+ return ''
78
+ self.in_block = False
79
+ line = line[end + 2:]
80
+ out = []
81
+ i, n = 0, len(line)
82
+ while i < n:
83
+ token = SPECIAL.search(line, i)
84
+ if not token:
85
+ out.append(line[i:])
86
+ break
87
+ out.append(line[i:token.start()])
88
+ mark = token.group(0)
89
+ if mark == '//':
90
+ break
91
+ if mark == '/*':
92
+ end = line.find('*/', token.end())
93
+ if end < 0:
94
+ self.in_block = True
95
+ break
96
+ i = end + 2
97
+ continue
98
+ body = STRING_END[mark].match(line, token.end())
99
+ i = body.end() if body else n
100
+ out.append(' ')
101
+ return ''.join(out)
102
+
103
+
104
+ def line_indent(text):
105
+ width = 0
106
+ for char in text:
107
+ if char == ' ':
108
+ width += 1
109
+ elif char == '\t':
110
+ width += 2
111
+ else:
112
+ break
113
+ return width
114
+
115
+
116
+ def loop_kind(text):
117
+ if REDUCE.search(text):
118
+ return 'reduce'
119
+ if SORT.search(text):
120
+ return 'sort'
121
+ if LOOP.search(text):
122
+ return 'loop'
123
+ return ''
124
+
125
+
126
+ def inline_lookup(text):
127
+ """#43: ids.map(id => items.find(...)) nests a pass inside one line.
128
+
129
+ A call is nested only when the second iteration sits inside the first call's
130
+ parentheses; a chain like a.filter(...).map(...) stays sequential.
131
+ """
132
+ rest = text
133
+ while True:
134
+ match = CALL.search(rest)
135
+ if not match:
136
+ return False
137
+ rest = rest[match.end():]
138
+ depth, inner = 1, []
139
+ for char in rest:
140
+ if char == '(':
141
+ depth += 1
142
+ elif char == ')':
143
+ depth -= 1
144
+ if depth == 0:
145
+ break
146
+ inner.append(char)
147
+ if INNER.search(''.join(inner)):
148
+ return True
149
+
150
+
151
+ def records(text):
152
+ """Split like awk's default RS: on \\n only, keeping a final unterminated line."""
153
+ lines = text.split('\n')
154
+ if lines and lines[-1] == '':
155
+ lines.pop()
156
+ return lines
157
+
158
+
159
+ def analyze(text):
160
+ counts = dict.fromkeys(('loc', 'code_lines', 'loops', 'max_nest', 'lookup', 'spread', 'sorts', 'binary'), 0)
161
+ stripper = Stripper()
162
+ stack = [] # (indent, kind) of the open loops
163
+ saw_mid = saw_bound = False
164
+ for raw in records(text):
165
+ if raw.endswith('\r'):
166
+ raw = raw[:-1]
167
+ counts['loc'] += 1
168
+ stripped = stripper.strip(raw)
169
+ if BLANK.match(stripped):
170
+ continue
171
+ counts['code_lines'] += 1
172
+ if LONE_BRACE.match(stripped):
173
+ continue
174
+ indent = line_indent(stripped)
175
+ while stack and stack[-1][0] >= indent:
176
+ stack.pop()
177
+ kind = loop_kind(stripped)
178
+ if kind:
179
+ counts['loops'] += 1
180
+ stack.append((indent, kind))
181
+ counts['max_nest'] = max(counts['max_nest'], len(stack))
182
+ # #55: count a sort even when the same line is classed as reduce
183
+ # (`xs.sort(...).reduce(...)`); the kind stays reduce for spread detection.
184
+ if SORT.search(stripped):
185
+ counts['sorts'] += 1
186
+ if stack and (LOOKUP.search(stripped) or inline_lookup(stripped)):
187
+ counts['lookup'] += 1
188
+ if any(k == 'reduce' for _, k in stack) and SPREAD.search(stripped):
189
+ counts['spread'] += 1
190
+ if stack:
191
+ saw_mid = saw_mid or bool(MID.search(stripped))
192
+ saw_bound = saw_bound or bool(BOUND.search(stripped))
193
+ if saw_mid and saw_bound:
194
+ counts['binary'] = 1
195
+ return counts
196
+
197
+
198
+ # #43: per-function breakdown, standard library only (ADR 0001). Named functions
199
+ # are found on comment- and string-free lines; a brace language's body is the
200
+ # matching {...} block, a Python body is the indented block under `def`. Each body
201
+ # is scored with the same analyze() as the file. Anonymous callbacks are part of
202
+ # the function that contains them.
203
+ DECLARATIONS = (
204
+ re.compile(r'^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\('),
205
+ re.compile(r'^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s+)?'
206
+ r'(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)'),
207
+ re.compile(r'^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)\s*\('),
208
+ re.compile(r'^\s*(?:(?:public|private|protected|static|final|abstract|async|override|readonly|'
209
+ r'synchronized|function)\s+)*(?:[\w$<>\[\],.?]+\s+)?([A-Za-z_$][\w$]*)\s*\([^;]*\)\s*'
210
+ r'(?::\s*[^{;=]+)?(?:throws\s+[\w.,\s]+)?\{\s*$'),
211
+ )
212
+ NOT_FUNCTIONS = {'if', 'for', 'while', 'switch', 'catch', 'return', 'function', 'do', 'else', 'with',
213
+ 'typeof', 'new', 'await', 'super', 'constructor_call'}
214
+ PY_DEF = re.compile(r'^([ \t]*)(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(')
215
+
216
+
217
+ def brace_pairs(stripped):
218
+ """One pass: (open line, close line) for every {...} in order of its opening."""
219
+ pairs, stack = [], []
220
+ for index, line in enumerate(stripped):
221
+ for char in line:
222
+ if char == '{':
223
+ stack.append(len(pairs))
224
+ pairs.append([index, None])
225
+ elif char == '}' and stack:
226
+ pairs[stack.pop()][1] = index
227
+ return [(opened, closed) for opened, closed in pairs if closed is not None]
228
+
229
+
230
+ def find_functions(text, python):
231
+ lines = [raw[:-1] if raw.endswith('\r') else raw for raw in records(text)]
232
+ found = []
233
+ if python:
234
+ for index, line in enumerate(lines):
235
+ match = PY_DEF.match(line)
236
+ if not match:
237
+ continue
238
+ indent, end = len(match.group(1).expandtabs()), index
239
+ for later in range(index + 1, len(lines)):
240
+ if lines[later].strip() and len(lines[later]) - len(lines[later].lstrip()) <= indent \
241
+ and not lines[later].lstrip().startswith('#'):
242
+ break
243
+ if lines[later].strip():
244
+ end = later
245
+ found.append((match.group(2), index, end))
246
+ return lines, found
247
+ stripper = Stripper()
248
+ stripped = [stripper.strip(line) for line in lines]
249
+ pairs = brace_pairs(stripped)
250
+ opens = [opened for opened, _ in pairs]
251
+ for index, line in enumerate(stripped):
252
+ for pattern in DECLARATIONS:
253
+ match = pattern.match(line)
254
+ if not match or match.group(1) in NOT_FUNCTIONS:
255
+ continue
256
+ arrow = pattern is DECLARATIONS[1]
257
+ if arrow and '{' not in line:
258
+ found.append((match.group(1), index, index)) # expression-bodied arrow
259
+ break
260
+ # The body is the first {...} opening on this line or within the next two.
261
+ first = bisect_left(opens, index)
262
+ if first < len(pairs) and pairs[first][0] <= index + 2:
263
+ found.append((match.group(1), index, pairs[first][1]))
264
+ break
265
+ return lines, found
266
+
267
+
268
+ def function_reports(text, python):
269
+ """Score each function on the lines it owns: a line belongs to the innermost
270
+ named function around it, so nested named functions are measured on their own
271
+ and the total work stays linear in the file size."""
272
+ lines, found = find_functions(text, python)
273
+ if not found:
274
+ return []
275
+ owner = [None] * len(lines)
276
+ for number, (_, start, end) in sorted(enumerate(found), key=lambda item: (item[1][1], -item[1][2])):
277
+ owner[start:end + 1] = [number] * (end + 1 - start)
278
+ bodies = [[] for _ in found]
279
+ for index, number in enumerate(owner):
280
+ if number is not None:
281
+ bodies[number].append(lines[index])
282
+ return [(name, start + 1, *decide_bigo(analyze('\n'.join(bodies[number]) + '\n')))
283
+ for number, (name, start, _) in enumerate(found)]
284
+
285
+
286
+ def suggest_keywords(text):
287
+ exports, imports, seen = [], [], set()
288
+
289
+ def emit(bucket, name):
290
+ name = name.strip(' \t')
291
+ if not name or name in ('type', 'typeof', 'as', 'from') or re.search(r'[^A-Za-z0-9_]', name):
292
+ return
293
+ if (bucket, name) in seen:
294
+ return
295
+ seen.add((bucket, name))
296
+ (exports if bucket == 'export' else imports).append(name)
297
+
298
+ for line in records(text):
299
+ if IMPORT_LINE.match(line):
300
+ braces = BRACES.search(line)
301
+ if braces:
302
+ inner = re.sub(r'type\s+', '', braces.group(0)[1:-1], flags=re.ASCII)
303
+ for item in inner.split(','):
304
+ # #55: `B as C` binds the local name C, which is what the file uses.
305
+ alias = re.search(r'\sas\s+([A-Za-z_][A-Za-z0-9_]*)', item, re.ASCII)
306
+ item = alias.group(1) if alias else item
307
+ emit('import', re.sub(r'[^A-Za-z0-9_]', '', item))
308
+ if EXPORT_LINE.match(line):
309
+ decl = EXPORT_DECL.search(line)
310
+ if decl:
311
+ emit('export', decl.group(2))
312
+ return (exports + imports)[:KEYWORD_LIMIT]
313
+
314
+
315
+ def decide_bigo(c):
316
+ if c['max_nest'] >= 3:
317
+ return 'O(n^3)', 1
318
+ if c['max_nest'] >= 2 or c['lookup'] > 0 or c['spread'] > 0:
319
+ return 'O(n^2)', 1
320
+ if c['sorts'] > 0:
321
+ return 'O(n log n)', 2
322
+ if c['binary'] > 0 and c['loops'] > 0:
323
+ return 'O(log n)', 4
324
+ if c['loops'] > 0:
325
+ return 'O(n)', 3
326
+ return 'O(1)', 5
327
+
328
+
329
+ def signals(c):
330
+ out = []
331
+ clean = c['max_nest'] < 2 and c['lookup'] == 0 and c['spread'] == 0
332
+ if c['max_nest'] >= 3:
333
+ out.append('deep_nesting')
334
+ if c['max_nest'] >= 2:
335
+ out.append('nested_loop')
336
+ if c['lookup'] > 0:
337
+ out.append('lookup_in_loop')
338
+ if c['spread'] > 0:
339
+ out.append('spread_in_reduce')
340
+ if c['sorts'] > 0:
341
+ out.append('sort')
342
+ if c['binary'] > 0 and clean:
343
+ out.append('logarithmic')
344
+ if c['loops'] > 0 and clean and c['sorts'] == 0 and c['binary'] == 0:
345
+ out.append('single_pass')
346
+ if c['loops'] == 0 or not out:
347
+ out.append('constant')
348
+ return out
349
+
350
+
351
+ def quote(value):
352
+ return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'
353
+
354
+
355
+ def collect_files(target):
356
+ if os.path.isfile(target):
357
+ return [target]
358
+ if not os.path.isdir(target):
359
+ print(f'Not a file or directory: {target}', file=sys.stderr)
360
+ return []
361
+ found = []
362
+ for root, _dirs, files in os.walk(target):
363
+ for name in files:
364
+ path = os.path.join(root, name)
365
+ probe = path.replace(os.sep, '/')
366
+ if (name.endswith(EXTENSIONS) and not os.path.islink(path)
367
+ and not any(part in probe for part in EXCLUDED)):
368
+ found.append(path)
369
+ return sorted(found)
370
+
371
+
372
+ def report(path):
373
+ with open(path, encoding='utf-8', errors='replace', newline='') as handle:
374
+ text = handle.read()
375
+ c = analyze(text)
376
+ bigo, score = decide_bigo(c)
377
+ lines = [
378
+ f' - file: {quote(path)}',
379
+ f' loc: {c["loc"]}',
380
+ f' code_lines: {c["code_lines"]}',
381
+ f' bigo: {quote(bigo)}',
382
+ f' bigo_score: {score}',
383
+ f' header_bigo: {quote(f"{bigo} score:{score}")}',
384
+ f' loops: {c["loops"]}',
385
+ f' max_loop_nesting: {c["max_nest"]}',
386
+ f' lookup_in_loop: {c["lookup"]}',
387
+ f' spread_in_reduce: {c["spread"]}',
388
+ f' sorts: {c["sorts"]}',
389
+ ' signals:',
390
+ ]
391
+ lines += [f' - {name}' for name in signals(c)]
392
+ keywords = suggest_keywords(text)
393
+ if keywords:
394
+ lines.append(' suggested_keywords:')
395
+ lines += [f' - {quote(word)}' for word in keywords]
396
+ else:
397
+ lines.append(' suggested_keywords: []')
398
+ functions = function_reports(text, path.endswith('.py'))
399
+ if functions:
400
+ lines.append(' functions:')
401
+ for name, line, f_bigo, f_score in functions:
402
+ lines += [f' - name: {quote(name)}', f' line: {line}',
403
+ f' bigo: {quote(f_bigo)}', f' bigo_score: {f_score}']
404
+ else:
405
+ lines.append(' functions: []')
406
+ return '\n'.join(lines)
407
+
408
+
409
+ def main(argv):
410
+ if not argv:
411
+ print(f'Usage: {sys.argv[0]} <file-or-directory> [more...]', file=sys.stderr)
412
+ return 1
413
+ out = sys.stdout
414
+ out.write('results:\n')
415
+ found = False
416
+ for target in argv:
417
+ for path in collect_files(target):
418
+ out.write(report(path) + '\n')
419
+ found = True
420
+ if not found:
421
+ print('No source files found.', file=sys.stderr)
422
+ return 1
423
+ return 0
424
+
425
+
426
+ if __name__ == '__main__':
427
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1 @@
1
+ �� broken utf8 � for (x of y) {}
@@ -0,0 +1,6 @@
1
+ import { type A, B as C, D } from "x"
2
+ export default function Main() {
3
+ for (const a of b) {
4
+ if (c.includes(a)) {}
5
+ }
6
+ }
@@ -0,0 +1,15 @@
1
+ /* start
2
+ for (;;) {
3
+ end */ const s = "for (x) { \" while(" ; // for (
4
+ let t = `a ${b.map(x => y.find(z))}`
5
+ while (lo <= hi) { const mid = (lo + hi) >> 1; left = mid }
6
+ export class Foo {}
7
+ export const bar = 1
8
+ export interface Baz {}
9
+ x.sort((a,b)=>a-b).reduce((acc, v) => ({...acc, v}), {})
10
+ "unterminated
11
+ for (a in b) {
12
+ for (c in d) {
13
+ for (e in f) {}
14
+ }
15
+ }
@@ -0,0 +1 @@
1
+ export function noNewline() { return [1].map(x => x) }