@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,42 @@
1
+ {
2
+ "name": "@bbcsoftwarefactory/skills",
3
+ "version": "0.1.1",
4
+ "description": "Public BuilderBot agent skills and slash commands, packaged for installation by the CLI.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22.18.0"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "scripts": {
14
+ "build": "node build.ts",
15
+ "prepack": "node build.ts",
16
+ "test": "node --test \"*.test.ts\""
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/builberbot/bbc-skill-internals.git",
21
+ "directory": "packages/skills"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "provenance": true
26
+ },
27
+ "skills": [
28
+ "code-quality-gate",
29
+ "delivery-coordinator",
30
+ "documentation-steward",
31
+ "greptile-review-loop",
32
+ "issue-reviewer",
33
+ "question-gate",
34
+ "regression-testing",
35
+ "requirements-spec",
36
+ "risk-scout",
37
+ "skill-clean-architecture",
38
+ "tool-depot",
39
+ "watcher-observability",
40
+ "workflow-auditor"
41
+ ]
42
+ }
@@ -0,0 +1,59 @@
1
+ ---
2
+ name: code-quality-gate
3
+ description: "Trigger: quality gate, post-wave gate, TypeSafe, EarlyReturn, BigO, code review gate. Enforce TypeSafe, Early Return, and Big O gates on changed code after each wave or before commit."
4
+ license: Apache-2.0
5
+ compatibility: Requires Python 3.8+ and Git for scripts/extract-diff-scope.py (standard library only; Linux, macOS and Windows).
6
+ metadata:
7
+ author: bbc-skill-internals
8
+ version: "1.3"
9
+ pre_hook: "python3 -I -B scripts/extract-diff-scope.py --working|--staged|--range <base>..HEAD"
10
+ scripts: "scripts/extract-diff-scope.py"
11
+ ---
12
+
13
+ ## Activation Contract
14
+
15
+ Run after every implementation wave, fix slice, or before committing to verify all added or modified TypeScript/JavaScript code passes three blocking quality gates: **TypeSafe**, **EarlyReturn**, and **BigO**.
16
+
17
+ **Company role:** Software Engineer self-check, run by the agent that implemented the slice. It does not replace peer review by a human code owner.
18
+
19
+ ## Hard Rules
20
+
21
+ - Scope to **added and modified lines** in the active wave or commit diff (including untracked new source files in `--working` mode). Do not rewrite untouched legacy code outside the slice.
22
+ - **No warn-only or silent bypass:** any confirmed violation in `typesafe`, `earlyreturn`, or `bigo` sets `gate.status: block` and must be fixed before advancing to the next wave or committing.
23
+ - Never approve or block from regex matches alone. Extract the diff with the bundled scope script, read surrounding function context, and verify semantically.
24
+ - Only documented exceptions (`external-boundary` for TypeSafe, bounded `fixture` `<= 10` items for BigO) may pass, and every exception must be recorded explicitly in `exceptions`.
25
+
26
+ ## Decision Gates
27
+
28
+ | Condition | Action |
29
+ |---|---|
30
+ | Diff contains zero `.ts`/`.tsx`/`.js`/`.jsx`/`.mts`/`.cts`/`.mjs`/`.cjs` files | Emit `gate.status: pass` with `files_changed: 0`. |
31
+ | Confirmed violation in TypeSafe, EarlyReturn, or BigO | Emit `gate.status: block`, remediate the exact file and line, rerun affected tests, and rerun this gate. |
32
+ | Valid `external-boundary` cast or bounded `<= 10` test fixture | Allow and record under `exceptions` with justification. |
33
+
34
+ ## Execution Steps
35
+
36
+ 1. Extract the wave or commit scope using `python3 -I -B <skill-root>/scripts/extract-diff-scope.py` (on Windows, `py -3 -I -B`) (`--working` after a wave, `--staged` before commit, or `--range <base>..HEAD` for a branch/PR slice).
37
+ 2. Inspect every added or modified record in its enclosing function and module against [TypeSafe](references/gate-typesafe.md), [EarlyReturn](references/gate-earlyreturn.md), and [BigO](references/gate-bigo.md).
38
+ 3. Run the repository typechecker (`tsc --noEmit`, `build.types`, or equivalent) and, if `skill-clean-architecture` is installed, verify Big O headers on touched source files.
39
+ 4. If `gate.status` is `block`, apply the minimal fix, rerun affected tests to keep GREEN, and repeat steps 1–3 until `gate.status: pass`.
40
+ 5. Return the final structured YAML verdict matching [Output schema](references/output-schema.yml).
41
+
42
+ ## Companion Handoffs
43
+
44
+ When a finding needs tests or architecture work, look for `regression-testing` or `skill-clean-architecture`. Pass the exact diff and relevant findings.
45
+
46
+ 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.
47
+
48
+ ## Output Contract
49
+
50
+ - **In chat (agile HUD):** emit a single traffic-light line (`🛡️ **Quality:** 🟢 TypeSafe · EarlyReturn · BigO · Types` on `pass`, or `🔴 BLOCK` with exact `file:line -> fix` lines when `gate.status: block`).
51
+ - **Full YAML / ledger / `"detalle"`:** produce the strict YAML report matching [Output schema](references/output-schema.yml) (`scan`, `gates_checked: [typesafe, earlyreturn, bigo]`, `violations`, `exceptions`, `gate`, `actions_required`) plus the exact typecheck command and exit status.
52
+
53
+ ## References
54
+
55
+ - [Gate TypeSafe rules](references/gate-typesafe.md)
56
+ - [Gate EarlyReturn rules](references/gate-earlyreturn.md)
57
+ - [Gate BigO rules](references/gate-bigo.md)
58
+ - [Strict output YAML schema](references/output-schema.yml)
59
+ - [Wave diff scope extractor](scripts/extract-diff-scope.py)
@@ -0,0 +1,31 @@
1
+ # Gate BigO
2
+
3
+ Added or modified code must not introduce avoidable superlinear time complexity. Aim for single-pass processing and `O(1)` lookups via `Map`/`Set` instead of repeated scans over unbounded collections.
4
+
5
+ ## Blocking Rule
6
+
7
+ Every confirmed violation is `severity: BLOCK`.
8
+
9
+ ## Violation Rules
10
+
11
+ | Rule ID | Pattern to Detect | Avoid | Prefer |
12
+ |---|---|---|---|
13
+ | `NESTED_LOOP` | Nested `for` / `forEach` / `map` over unbounded arrays (`O(n^2)` or `O(n*m)`) | `items.forEach(a => others.forEach(b => ...))` | Single pass or pre-indexed lookup |
14
+ | `LOOKUP_IN_LOOP` | `includes`, `indexOf`, `find`, `some`, or `filter` inside a loop over another collection | `list.filter(x => ids.includes(x.id))` | `const idSet = new Set(ids)` then `idSet.has(x.id)` |
15
+ | `FILTER_FIND_COMBO` | `filter(...).find(...)` or `filter(...).map(...)` inside an outer iteration | `rows.map(r => cols.filter(c => c.k === r.k))` | Pre-group once into a `Map<K, V[]>` |
16
+ | `LOOKUP_BY_INDEX` | Linear index scan inside another loop to match records by key | `for (i...) for (j...) if (a[j].id === b[i].id)` | `const byId = new Map(a.map(x => [x.id, x]))` |
17
+ | `REBUILD_PER_ITER` | Recomputing or filtering an invariant collection on every loop iteration | Inside `map`: `getAll().filter(...)` | Hoist invariant computation outside the loop |
18
+ | `SPREAD_IN_REDUCE` | Object/array spread inside `reduce` or loop (`{ ...acc, [k]: v }` or `[...acc, x]`), `O(n^2)` copies | `arr.reduce((acc, x) => ({ ...acc, [x.id]: x }), {})` | Mutate a local `Map` or pre-allocated object/array in one pass |
19
+
20
+ ## Documented Exception
21
+
22
+ | Case | Condition |
23
+ |---|---|
24
+ | `fixture` | Unit test or bounded static constant with explicit `<= 10` items. Record under `exceptions[]` with collection size. Never exempt unbounded runtime or user-supplied data. |
25
+
26
+ ## Semantic Checks
27
+
28
+ 1. Evaluate complexity only on added or modified lines in the diff scope.
29
+ 2. Treat collection sizes as unbounded unless a constant or explicit bound (`<= 10`) is visible in code.
30
+ 3. Do not micro-optimize tiny fixed tuples (`<= 3` static constants); target avoidable superlinear work over growing collections.
31
+ 4. When `skill-clean-architecture` is installed, run `measure-bigo.py` on modified source files to keep file headers accurate.
@@ -0,0 +1,73 @@
1
+ # Gate EarlyReturn
2
+
3
+ New or modified functions must validate inputs first (guard clauses), exit early, and keep the happy path flat and readable.
4
+
5
+ ## Blocking Rule
6
+
7
+ Every confirmed violation is `severity: BLOCK`.
8
+
9
+ ## Violation Rules
10
+
11
+ | Rule ID | Pattern to Detect | Avoid | Prefer |
12
+ |---|---|---|---|
13
+ | `ELSE_AFTER_RETURN` | `else` immediately after a branch ending in `return`, `throw`, `continue`, or `break` | `if (x) { return a } else { return b }` | `if (x) return a` followed by `return b` |
14
+ | `GUARD_MISSING` | Late input/state validation forcing the main body inside a wrapper `if` | `if (input) { /* 20 lines */ }` | `if (!input) return` / `throw` at the top |
15
+ | `NESTING_DEPTH` | Conditional or loop+conditional nesting `> 2` levels inside added code | `if (a) { if (b) { if (c) { ... } } }` | Invert conditions, return early, or extract a focused helper |
16
+ | `ELSE_IF_CHAIN` | Long `else if` branch chain where guards or a `switch`/`Map` lookup is clearer | `if (k === 'a') ... else if (k === 'b') ... else if ...` | `switch`, `Map` dispatch, or independent guard returns |
17
+ | `TRY_NO_EARLY_EXIT` | Oversized `try` wrapping preconditions and happy path together | `try { validate(); work(); } catch ...` | Validate preconditions before `try`; wrap only the fallible I/O call |
18
+ | `CALLBACK_NESTED` | Nested `.then()` or nested callbacks inside async/event flows | `fetch(a).then(() => fetch(b).then(...))` | Sequential `await` with guard clauses between steps |
19
+ | `DUPLICATE_BRANCH_CALL` | Duplicating the same call across `if/else` or ternary branches solely to omit an optional `undefined` argument | `options ? await fn(a, b, options) : await fn(a, b)` | Single call `await fn(a, b, options)` (or build `resolvedOptions` once before calling) |
20
+
21
+ ## Bad Examples and Recommendations
22
+
23
+ ### 1. Duplicate branch call for an optional argument (`DUPLICATE_BRANCH_CALL`)
24
+
25
+ ```typescript
26
+ // AVOID: duplicates the entire call just to omit an optional parameter
27
+ const event = options
28
+ ? await this.fbpixel.buildPurchaseEvent(userId, amount, resolvedCurrency, browserData, userData, options)
29
+ : await this.fbpixel.buildPurchaseEvent(userId, amount, resolvedCurrency, browserData, userData)
30
+
31
+ // ALSO AVOID: early-return branch duplicating the exact same call
32
+ if (options) {
33
+ await this.trackEvents.trackEventPaySuccess(email, amount, data, userData, currency, resolvedOptions)
34
+ return
35
+ }
36
+ await this.trackEvents.trackEventPaySuccess(email, amount, data, userData, currency)
37
+ ```
38
+
39
+ ```typescript
40
+ // PREFER: compute options once, invoke once
41
+ const resolvedOptions = options ? { ...options, eventId } : undefined
42
+ const event = await this.fbpixel.buildPurchaseEvent(
43
+ userId,
44
+ amount,
45
+ resolvedCurrency,
46
+ browserData,
47
+ userData,
48
+ resolvedOptions,
49
+ )
50
+ ```
51
+
52
+ **Recommendations:**
53
+ - Never duplicate a multi-argument function call in production code just to satisfy a brittle exact-arity spy (`expect(fn).toHaveBeenCalledWith(a, b)`). Pass the optional `options` argument in one call and update the test expectation to include `undefined` or `expect.objectContaining(...)`.
54
+ - When conditional properties belong inside an options object, construct `resolvedOptions` before the call and keep a single invocation.
55
+ - Flatten post-call `if (result.success) { ... } else { ... }` blocks by handling the failure path with an early `return` first.
56
+
57
+ ## Reference Pattern
58
+
59
+ ```typescript
60
+ // Prefer: guard clauses first, flat happy path
61
+ function sendMessage(message: Message): SendResult {
62
+ if (!message.recipient) throw new Error('Missing recipient')
63
+ if (!message.body) throw new Error('Missing body')
64
+
65
+ return channel.send(message)
66
+ }
67
+ ```
68
+
69
+ ## Semantic Checks
70
+
71
+ 1. Do validation guards appear before business logic so the happy path sits at minimum indentation?
72
+ 2. Can any `3+` level nested block be flattened by inverting a condition and returning early?
73
+ 3. Do not flag legitimate structures dogmatically: flat `if (a && b)` checks and clean `switch` statements with early `return` per case are compliant.
@@ -0,0 +1,32 @@
1
+ # Gate TypeSafe
2
+
3
+ Added or modified code must preserve compiler-verified type invariants without unsafe escapes.
4
+
5
+ ## Blocking Rule
6
+
7
+ Every confirmed violation is `severity: BLOCK`. There is no warn-only mode.
8
+
9
+ ## Violation Rules
10
+
11
+ | Rule ID | Pattern to Detect | Avoid | Prefer |
12
+ |---|---|---|---|
13
+ | `ANY_UNJUSTIFIED` | `: any` or `as any` in added lines | `const x: any = getThing()` | Real type or `unknown` + type guard narrowing |
14
+ | `CAST_UNSAFE` | `as T` on `unknown` or a union without prior narrowing | `const id = raw as string` | `typeof raw === 'string' ? raw : fallback` or type guard |
15
+ | `NON_NULL_UNSAFE` | `!` on a nullable value without an earlier guard in the same function | `user!.email` | `user?.email` or `if (!user) return` / `throw` |
16
+ | `TS_IGNORE_UNJUSTIFIED` | `@ts-ignore` or `@ts-expect-error` without an inline root-cause comment | `// @ts-ignore` | Fix the underlying type; if unavoidable, `@ts-expect-error` with explanation |
17
+ | `UNKNOWN_DUMP` | Casting `unknown` directly to a concrete interface without runtime validation | `(payload as Payload).id` | Runtime schema/type-guard check before reading fields |
18
+ | `ANY_FROM_GENERIC` | Generics defaulting or instantiated with `any` | `function f<T = any>()` | Constrain `<T extends ...>` or pass explicit concrete type argument |
19
+ | `COMPILER_SILENCER` | Disabling type checks (`@ts-nocheck`, bare `as unknown as T`) | `// @ts-nocheck` | Define DTO/declaration at the boundary and narrow properly |
20
+
21
+ ## Documented Exception
22
+
23
+ | Case | Condition |
24
+ |---|---|
25
+ | `external-boundary` | Untyped third-party SDK/wire boundary only: single entry-point `as unknown as T` accompanied by a cause comment and immediate runtime narrowing/DTO mapping. Record under `exceptions[]`. |
26
+
27
+ ## Semantic Checks
28
+
29
+ 1. Did the added line introduce a type escape that did not exist before?
30
+ 2. Is a concrete domain/DTO type available instead of `any` or an unchecked cast?
31
+ 3. For `!`, is there an explicit guard (`if (!x) return/throw`) in the same function scope?
32
+ 4. For `@ts-expect-error`, does it fail cleanly if the upstream type improves?
@@ -0,0 +1,40 @@
1
+ # Strict output schema — code-quality-gate
2
+
3
+ scan:
4
+ mode: working | staged | range | head # required
5
+ range: string # required when mode = range
6
+ files_changed: int # required
7
+ lines_added: int # required
8
+ gates_checked: # required: always all 3
9
+ - typesafe
10
+ - earlyreturn
11
+ - bigo
12
+
13
+ violations: # empty list [] when gate.status = pass
14
+ - gate: typesafe | earlyreturn | bigo # required
15
+ rule: string # required: rule ID from references/gate-*.md
16
+ file: string # required
17
+ line: int # required
18
+ match: string # required: offending line content
19
+ severity: BLOCK # required
20
+
21
+ exceptions: # empty list [] when none used
22
+ - gate: typesafe | bigo # required
23
+ type: external-boundary | fixture # required
24
+ file: string # required
25
+ line: int # required
26
+ justification: string # required
27
+
28
+ gate:
29
+ status: pass | block # required
30
+ reason: string # required
31
+ gates_failed: # required when status = block
32
+ - typesafe
33
+ - earlyreturn
34
+ - bigo
35
+ pass_conditions: string # required when status = block
36
+
37
+ actions_required: # required (>= 1 P0) when block; [] when pass
38
+ - priority: P0 | P1 # required
39
+ action: string # required: file:line + concrete verb
40
+ suggestion: string # required: exact fix or command
@@ -0,0 +1,225 @@
1
+ #!/usr/bin/env python3
2
+ """extract-diff-scope.py: extract added/modified TypeScript/JavaScript lines as
3
+ structured YAML for code-quality-gate (TypeSafe, EarlyReturn, BigO).
4
+
5
+ Usage:
6
+ python3 -I -B scripts/extract-diff-scope.py # working tree vs HEAD + untracked (default)
7
+ python3 -I -B scripts/extract-diff-scope.py --working # working tree vs HEAD + untracked
8
+ python3 -I -B scripts/extract-diff-scope.py --staged # staged diff only
9
+ python3 -I -B scripts/extract-diff-scope.py --range A..B # commit range
10
+ python3 -I -B scripts/extract-diff-scope.py --head N # last N commits (HEAD~N..HEAD)
11
+ python3 -I -B scripts/extract-diff-scope.py --help
12
+
13
+ Standard library and git only: one `git diff` for all sections, and no awk, so
14
+ it behaves the same on Linux, macOS and Windows (ADR 0001).
15
+ """
16
+
17
+ import os
18
+ import re
19
+ import subprocess
20
+ import sys
21
+
22
+ CODE_RE = re.compile(r'\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$')
23
+ EXCLUDE_RE = re.compile(
24
+ r'(^|/)(dist|node_modules|graphify-out|\.next|\.vite|build|\.vercel|coverage)/|^prisma/generated/|^server/dist/')
25
+
26
+ # [[:space:]] -> \s and [[:alnum:]] -> [A-Za-z0-9] under re.ASCII, matching awk's C-locale classes.
27
+ GATES = (
28
+ ('typesafe_candidates', re.compile(
29
+ r'(:\s*any([^A-Za-z0-9_]|$)|\sas\s+any([^A-Za-z0-9_]|$)|\sas\s+[A-Za-z_]|!\.|!\[|'
30
+ r'@ts-ignore|@ts-expect-error|@ts-nocheck|<any>)', re.ASCII)),
31
+ ('earlyreturn_candidates', re.compile(
32
+ r'([}]\s*else(\s|$)|else\s+if\s*\(|^\s{12,}(if|for|while)\s*\(|[.]then\s*\(|'
33
+ r'^\s*[?:]\s*(await\s+)?[A-Za-z0-9_$.]+\()', re.ASCII)),
34
+ ('bigo_candidates', re.compile(
35
+ r'([.](forEach|map|filter|find|some|includes|indexOf|reduce)\s*\(|for\s*\(|while\s*\(|\.\.\.acc)',
36
+ re.ASCII)),
37
+ )
38
+ HUNK_START = re.compile(r'\S+\s+\S+\s+\+?([0-9]*)')
39
+
40
+
41
+ def _usage_text():
42
+ lines = __doc__.strip('\n').split('\n')
43
+ return '\n'.join(lines[:10]) + '\n'
44
+
45
+
46
+ def text(raw):
47
+ """Decode git/file bytes without loss; surrogateescape round-trips any byte."""
48
+ return raw.decode('utf-8', 'surrogateescape')
49
+
50
+
51
+ def git(args, quiet):
52
+ try:
53
+ result = subprocess.run(['git', *args], stdout=subprocess.PIPE,
54
+ stderr=subprocess.DEVNULL if quiet else None)
55
+ except OSError:
56
+ return b'', 1
57
+ return result.stdout, result.returncode
58
+
59
+
60
+ def yaml_escape(value):
61
+ # Mirrors the retired awk helper: records split on \n (a trailing \n ends the
62
+ # last record instead of starting an empty one) and are joined by a literal \n.
63
+ parts = value.split('\n')
64
+ if len(parts) > 1 and parts[-1] == '':
65
+ parts.pop()
66
+ return '\\n'.join(p.replace('\\', '\\\\').replace('"', '\\"') for p in parts)
67
+
68
+
69
+ def awk_quote(value):
70
+ return value.replace('\\', '\\\\').replace('"', '\\"')
71
+
72
+
73
+ def is_target(path):
74
+ return bool(CODE_RE.search(path)) and not EXCLUDE_RE.search(path)
75
+
76
+
77
+ def records_of(lines):
78
+ """Split like awk's default RS: on \\n only, keeping a final unterminated record."""
79
+ if lines and lines[-1] == '':
80
+ lines = lines[:-1]
81
+ return lines
82
+
83
+
84
+ def tracked_records(diff_args, files):
85
+ """(file, line, content) for every added line, parsed as the awk version did."""
86
+ raw, _ = git(['-c', 'core.quotePath=false', '-c', 'diff.noprefix=false', 'diff', *diff_args,
87
+ '-U0', '--no-color', '--', *files], quiet=False)
88
+ out, current, line = [], '', 0
89
+ for row in records_of(text(raw).split('\n')):
90
+ if row.startswith('+++ b/'):
91
+ current, line = row[6:], 0
92
+ elif row.startswith('+++ /dev/null'):
93
+ current, line = '', 0
94
+ elif row.startswith('@@ '):
95
+ fields = row.split()
96
+ start = fields[2] if len(fields) > 2 else ''
97
+ start = start[1:] if start.startswith('+') else start
98
+ digits = re.match(r'[0-9]*', start.split(',')[0]).group(0)
99
+ line = int(digits) if digits else 0
100
+ elif row.startswith('+') and not row.startswith('+++'):
101
+ if current and line > 0:
102
+ out.append((current, line, row[1:]))
103
+ line += 1
104
+ elif line > 0 and row.startswith(' '):
105
+ # Only lines present in the new file advance the counter: context
106
+ # lines do; removed lines ("-") and ""
107
+ # do not. Counting them shifted every added line after a deletion.
108
+ line += 1
109
+ return out
110
+
111
+
112
+ def untracked_records(path):
113
+ try:
114
+ with open(path, 'rb') as handle:
115
+ data = handle.read()
116
+ except OSError:
117
+ return []
118
+ # The awk version passed yaml_escape(path) through `awk -v`, which undoes those
119
+ # escapes, so untracked records carried the raw path. Kept for equivalence.
120
+ return [(path, number, row) for number, row in enumerate(records_of(text(data).split('\n')), 1)]
121
+
122
+
123
+ def parse_args(argv):
124
+ mode, value = 'working', ''
125
+ i = 0
126
+ while i < len(argv):
127
+ arg = argv[i]
128
+ if arg in ('--working', '--staged'):
129
+ mode = arg[2:]
130
+ elif arg in ('--range', '--head'):
131
+ if i + 1 >= len(argv) or not argv[i + 1]:
132
+ sys.stderr.write(f'error: {arg} requires {"A..B" if arg == "--range" else "N"}\n')
133
+ return None
134
+ mode, value = arg[2:], argv[i + 1]
135
+ i += 1
136
+ elif arg in ('--help', '-h'):
137
+ sys.stdout.write(_usage_text())
138
+ return 'help'
139
+ else:
140
+ sys.stderr.write(f'error: unknown option: {arg}\n' + _usage_text())
141
+ return None
142
+ i += 1
143
+ if mode == 'head' and not re.fullmatch(r'[1-9][0-9]*', value):
144
+ sys.stderr.write(f'error: --head requires a positive integer: {value}\n')
145
+ return None
146
+ return mode, value
147
+
148
+
149
+ def main(argv):
150
+ parsed = parse_args(argv)
151
+ if parsed is None:
152
+ return 1
153
+ if parsed == 'help':
154
+ return 0
155
+ mode, value = parsed
156
+
157
+ has_head = git(['rev-parse', '--verify', 'HEAD'], quiet=True)[1] == 0
158
+ diff_args = {
159
+ 'working': ['HEAD'] if has_head else ['--staged'],
160
+ 'staged': ['--staged'],
161
+ 'range': [value],
162
+ 'head': [f'HEAD~{value}..HEAD'],
163
+ }[mode]
164
+
165
+ names, _ = git(['-c', 'core.quotePath=false', 'diff', *diff_args, '--name-only', '-z'], quiet=True)
166
+ tracked = [p for p in text(names).split('\0') if p and is_target(p)]
167
+ untracked = []
168
+ if mode == 'working':
169
+ others, _ = git(['-c', 'core.quotePath=false', 'ls-files', '--others', '--exclude-standard', '-z'],
170
+ quiet=True)
171
+ untracked =[p for p in text(others).split('\0') if p and is_target(p) and os.path.isfile(p)]
172
+ all_files = tracked + untracked
173
+
174
+ out = ['scope:', f' mode: "{mode}"']
175
+ if mode == 'range':
176
+ out.append(f' range: "{yaml_escape(value)}"')
177
+ out.append(f' files_changed: {len(all_files)}')
178
+ if not all_files:
179
+ out += [' lines_added: 0', ' lines_removed: 0', ' files: []', ' records: []',
180
+ ' typesafe_candidates: []', ' earlyreturn_candidates: []', ' bigo_candidates: []']
181
+ return emit(out)
182
+
183
+ added = removed = 0
184
+ if tracked:
185
+ stat, _ = git(['-c', 'core.quotePath=false', 'diff', *diff_args, '--numstat', '--', *tracked],
186
+ quiet=False)
187
+ for row in text(stat).split('\n'):
188
+ cols = row.split('\t')
189
+ if cols and cols[0].isdigit() and cols[0].isascii():
190
+ added += int(cols[0])
191
+ if len(cols) > 1 and cols[1].isdigit() and cols[1].isascii():
192
+ removed += int(cols[1])
193
+ for path in untracked:
194
+ try:
195
+ with open(path, 'rb') as handle:
196
+ added += handle.read().count(b'\n')
197
+ except OSError:
198
+ pass
199
+
200
+ out += [f' lines_added: {added}', f' lines_removed: {removed}', ' files:']
201
+ out += [f' - "{yaml_escape(path)}"' for path in all_files]
202
+
203
+ records = tracked_records(diff_args, tracked) if tracked else []
204
+ for path in untracked:
205
+ records += untracked_records(path)
206
+
207
+ for key, pattern in (('records', None), *GATES):
208
+ rows = [r for r in records if pattern is None or pattern.search(r[2])]
209
+ if not rows:
210
+ out.append(f' {key}: []')
211
+ continue
212
+ out.append(f' {key}:')
213
+ for path, line, content in rows:
214
+ out += [f' - file: "{path}"', f' line: {line}', ' added: true',
215
+ f' content: "{awk_quote(content)}"']
216
+ return emit(out)
217
+
218
+
219
+ def emit(lines):
220
+ sys.stdout.buffer.write(('\n'.join(lines) + '\n').encode('utf-8', 'surrogateescape'))
221
+ return 0
222
+
223
+
224
+ if __name__ == '__main__':
225
+ sys.exit(main(sys.argv[1:]))