diff --git a/.devspark.work/roadmap/roadmap.md b/.devspark.work/roadmap/roadmap.md new file mode 100644 index 0000000..c97a06a --- /dev/null +++ b/.devspark.work/roadmap/roadmap.md @@ -0,0 +1,91 @@ +# Roadmap: git-spark + +## Direction + +git-spark is a Git-only analytics CLI and library for maintainers and engineering leads. It turns +`git log` into reports a team can trust and share. Over the next few releases the outcomes that matter +are: + +1. **Every number is right.** A metric is either derived correctly from Git or not shown + (constitution principles 1 and 5). +2. **Every option does what it says.** A flag or config key either works or is removed. +3. **Reports are safe to share.** Redaction is complete, and the local report server does not expose + repository data to the network. + +Breadth (new metrics, new outputs) comes after these. Each item below ships on its own and leaves the +tool releasable. + +## Current Baseline + +Assessed on 2026-11-21 at `main` `6ec37fa` (git-spark 2.0.2 published, PR #19 merged, unreleased). + +- **Collection** streams `git log --no-merges --numstat` with `\x1e`/`\x1f` separators + (`src/core/collector.ts`). Since PR #19 the collector matches `git log` commit counts exactly, + `--path` takes Git pathspec globs, and `--branch` combines with `--path`. These three fixes sit in + CHANGELOG `[Unreleased]` waiting for 2.0.3. +- **Analysis** lives in one 2,597-line `src/core/analyzer.ts`. The HTML output was decomposed earlier + (issues #5, #6, #9 closed); the analyzer was not. +- **Quality gates** pass: 345 tests, coverage 80.23% branches / 96.2% functions / 94.92% lines, + production `npm audit` clean. Dependabot alert #75 is the allowlisted dev-only minimatch advisory + (GHSA-g3hv-75wg-m249) in `audit-ci.jsonc`. +- **Code review (2026-11-21)** found the defects listed under Findings and the outcome-sized + problems turned into Prospective Specs below. Evidence for each is in the PS or finding. + +## Themes + +Priority order. Lower `order` comes first within a theme. + +- **Trustworthy numbers** + - [ps-001 Accurate per-file change records](specs/ps-001-accurate-file-change-records.md) + - [ps-002 Correct contributor identity](specs/ps-002-correct-contributor-identity.md) + - [ps-003 Timezone-consistent day and hour buckets](specs/ps-003-timezone-consistent-buckets.md) + - [ps-004 Exact date windows](specs/ps-004-exact-date-windows.md) + - [ps-005 Accurate commit message scoring](specs/ps-005-accurate-commit-message-scoring.md) +- **Options that do what they say** + - [ps-006 Complete, collision-free email redaction](specs/ps-006-complete-email-redaction.md) + - [ps-007 Honor or retire inert options](specs/ps-007-honor-or-retire-inert-options.md) + - [ps-008 Multiple and exclude path filters](specs/ps-008-multiple-and-exclude-path-filters.md) +- **Maintainability** + - [ps-009 Decompose the analyzer](specs/ps-009-decompose-the-analyzer.md) + +## Findings + +Defects too small for a Prospective Spec. Each is independent and fits `/devspark-quickfix`. + +F1 to F4 (the `validate` import, the `html --serve` network exposure, `analyze` ignoring global +options, and `NaN%` bus factor) were fixed on branch `chore/roadmap-and-cli-fixes` and are listed in +CHANGELOG `[Unreleased]`. + +| # | Severity | Defect | Evidence | +| - | -------- | ------ | -------- | +| F5 | Low | The streaming collector ignores `git log`'s exit code and stderr, so a failing `git log` yields a partial or empty report instead of an error. | `src/core/collector.ts:265-274` | +| F6 | Low | Finding the first commit date reads the entire `git log --all` into memory under a 60 s timeout; on very large repositories it times out and silently returns `null`, which disables range capping. `git log --all --max-parents=0` returns only root commits. | `src/utils/git.ts:212-232` | +| F7 | Low | On Windows, `--open` runs `cmd.exe /c start "" `; an output path containing `&` or `^` is interpreted by `cmd`. The path is user-supplied, so impact is self-inflicted. | `src/cli/report-command.ts:281-284` | + +## Planning Housekeeping + +Open items carried over from other planning records, consolidated here: + +- **Release 2.0.3** with the PR #19 fixes (CHANGELOG `[Unreleased]`). Release work, not a PS. +- **Article update**: after 2.0.3 ships, update the `--path` note in "Getting to Know Your Repository + with git-spark" (https://claude.ai/artifact/CULQDaKVQDNo8oShqN3nXN), which says `**` globs do not + work. +- **DevSpark migration record** (`.devspark.work/migrations/2026-10-20-devspark.md`): its work is + complete. It stays in `.devspark.work/` because the release archiver needs a + `.knowledge/taxonomy-registry.json` lifecycle entry to archive an uncategorized document. Adding that + registry entry lets the next release archive it. +- **Docs date re-stamp**: `postbuild` (`scripts/update-docs-version.js`) rewrites dates in + `docs/index.html` and `docs/performance-tuning.md` on every build, including the pre-push build, + leaving the tree dirty after each push. Stamp only during release. +- **Dependabot #75**: allowlisted dev-only minimatch advisory; drop the allowlist entry when typedoc + ships a fixed minimatch. + +## Decisions + +- **2026-11-21: One roadmap.** All planning lives in this roadmap. Durable decisions stay in + `.knowledge/architecture/decisions.md`; the CHANGELOG records what shipped. Basis: the developer asked + to consolidate planning into a single DevSpark roadmap. + +## Delivered + +None yet. diff --git a/.devspark.work/roadmap/specs/ps-001-accurate-file-change-records.md b/.devspark.work/roadmap/specs/ps-001-accurate-file-change-records.md new file mode 100644 index 0000000..665d4d5 --- /dev/null +++ b/.devspark.work/roadmap/specs/ps-001-accurate-file-change-records.md @@ -0,0 +1,51 @@ +--- +id: ps-001 +title: Accurate per-file change records +status: proposed +order: 10 +depends_on: [] +blockers: [] +delivery: [] +--- + +# ps-001: Accurate per-file change records + +## Outcome + +Every file change in a report names the real file and its real change status. Hotspots, risk +scores, file counts, file-type breakdowns, and author file ownership then describe files that exist. + +## Current Reality + +- `git log --numstat` reports renames in brace form, for example + `{.devspark.work => .archive/2026-10-20}/specs/.../spec.md`. `parseFileStats` splits on ` => `, so + the recorded path becomes `.archive/2026-10-20}/specs/.../spec.md` and the old path becomes + `{.devspark.work` (`src/core/collector.ts:336-340`). In this repository 110 of 134 rename lines use + brace form, so most renames produce corrupted paths. +- Status is guessed from line counts: any change with insertions and no deletions is `added`, and any + with deletions and no insertions is `deleted` (`collector.ts:341-345`). An edit that only appends + lines is reported as a new file. + +## Scope and Independence + +In scope: correct path and old-path expansion for both brace and plain rename forms, and change status +taken from Git (added, modified, deleted, renamed) rather than inferred. Out of scope: following +history across renames (`--follow`) and merging a renamed file's stats with its old path. + +Standalone: the collector's `FileChange` contract is unchanged in shape; only its values become +correct. Shipping this alone leaves every report more accurate. + +## Future Health + +Keeps one `git log` invocation (Git can emit `--numstat` together with `--raw` or `--name-status`). +Leaves room for later rename-aware history without changing the contract again. + +## Dependencies and Decisions + +None. Decide whether the JSON `status` change is a fix (patch) or a behavior change (minor) at +release; it changes values, not the schema. + +## Completion Expectations + +A regression test with a brace-form rename and an append-only edit shows the correct path, old path, +and status. On this repository no recorded path contains `{` or `}` unless the real filename does. diff --git a/.devspark.work/roadmap/specs/ps-002-correct-contributor-identity.md b/.devspark.work/roadmap/specs/ps-002-correct-contributor-identity.md new file mode 100644 index 0000000..7f2fa8b --- /dev/null +++ b/.devspark.work/roadmap/specs/ps-002-correct-contributor-identity.md @@ -0,0 +1,51 @@ +--- +id: ps-002 +title: Correct contributor identity +status: proposed +order: 20 +depends_on: [] +blockers: [] +delivery: [] +--- + +# ps-002: Correct contributor identity + +## Outcome + +One person counts as one contributor, and co-authored commits are recognized. Contributor counts, bus +factor, and author profiles then match how a team would describe itself. + +## Current Reality + +- The collector reads raw `%an`/`%ae` (`src/core/collector.ts:182`), so a repository's `.mailmap` is + ignored. Authors are keyed by email (`src/core/analyzer.ts:308,1405`). The 2026-11-21 repo story + found one person under three email identities in this repository, which inflates contributor count + and deflates bus-factor concentration. +- Co-author detection matches only `Co-authored-by:` exactly (`collector.ts:368`). Git trailers are + case-insensitive; this repository has 36 commit bodies with `Co-Authored-By:` that are missed versus + 13 detected. +- File ownership is keyed by author name in one place and by email elsewhere + (`analyzer.ts:1222-1231` versus `:821`), so the same person can be split or merged depending on the + section. + +## Scope and Independence + +In scope: honoring `.mailmap` (Git's `%aN`/`%aE` do this natively), case-insensitive co-author +trailers, and one identity key used consistently across analyses. Out of scope: heuristic identity +merging without a `.mailmap` (guessing would violate constitution principle 1), and bot exclusion +(ps-007). + +Standalone: repositories without a `.mailmap` behave as today except for co-author detection. + +## Future Health + +A single identity key makes ps-006 (redaction) simpler: redact at output, never as the grouping key. + +## Dependencies and Decisions + +None. Document in the author section's limitations that identity follows `.mailmap`. + +## Completion Expectations + +A test repository with a `.mailmap` mapping two emails to one person reports one author. A +`Co-Authored-By:` trailer marks the commit co-authored. Every section uses the same author key. diff --git a/.devspark.work/roadmap/specs/ps-003-timezone-consistent-buckets.md b/.devspark.work/roadmap/specs/ps-003-timezone-consistent-buckets.md new file mode 100644 index 0000000..419aaea --- /dev/null +++ b/.devspark.work/roadmap/specs/ps-003-timezone-consistent-buckets.md @@ -0,0 +1,52 @@ +--- +id: ps-003 +title: Timezone-consistent day and hour buckets +status: proposed +order: 30 +depends_on: [] +blockers: [] +delivery: [] +--- + +# ps-003: Timezone-consistent day and hour buckets + +## Outcome + +Every per-day and per-hour figure uses the analysis timezone (`--timezone` or config, default +`America/Chicago`), and the same commit lands in the same day everywhere in a report, whatever +timezone the machine running git-spark uses. + +## Current Reality + +- Daily trends convert with `new Date(date.toLocaleString('en-US', { timeZone }))` and then take + `toISOString()` as the day key (`src/core/daily-trends-helpers.ts:11-14`, + `src/core/daily-trends.ts:168-169`). The round trip is only correct on a UTC machine. Verified on an + `America/Chicago` machine: a commit at 8 pm Chicago time on 2026-11-21 is bucketed as 2026-11-22. + On a developer laptop, every evening commit moves to the next day. +- Author work patterns (hour of day, weekend, after hours) use `Date.getHours()`/`getDay()` in the + machine's timezone and ignore `--timezone` (`src/core/analyzer.ts:410-422`). The same repository + gives different patterns locally and in CI. +- The timeline buckets by UTC date (`analyzer.ts:1249,1270`), which disagrees with daily trends. + +## Scope and Independence + +In scope: one timezone-aware day/hour helper built on `Intl.DateTimeFormat#formatToParts` (no new +dependency), used by daily trends, author work patterns, and the timeline. Out of scope: per-author +timezones taken from commit offsets (a possible later option). + +Standalone: no output schema change; values become correct and consistent. + +## Future Health + +Removes the "would use date-fns-tz in production" placeholder comment. A single helper lets a later +"author's local time" option be a one-line switch. + +## Dependencies and Decisions + +Decide whether hour-of-day patterns should use the analysis timezone (consistent, recommended) or each +commit's own offset (closer to the author's clock). Record the choice in the metric's limitations. + +## Completion Expectations + +Tests run with `TZ` set to a non-UTC zone and show identical day keys and hour buckets to a UTC run. +Daily trends and the timeline agree on per-day commit counts. diff --git a/.devspark.work/roadmap/specs/ps-004-exact-date-windows.md b/.devspark.work/roadmap/specs/ps-004-exact-date-windows.md new file mode 100644 index 0000000..23d9d8f --- /dev/null +++ b/.devspark.work/roadmap/specs/ps-004-exact-date-windows.md @@ -0,0 +1,51 @@ +--- +id: ps-004 +title: Exact date windows +status: proposed +order: 40 +depends_on: [] +blockers: [] +delivery: [] +--- + +# ps-004: Exact date windows + +## Outcome + +`--since`, `--until`, `--days`, and `periods` select exactly the commits a user expects: whole days +from the start of `--since` through the end of `--until`, independent of the time of day the command +runs. + +## Current Reality + +- Git reads a bare `YYYY-MM-DD` as that date at the current time of day (the reason for the PR #19-era + first-commit fix in `src/core/collector.ts:137-142`). Bare dates are still passed through for + `--since`/`--until`, so `--since 2026-11-01 --until 2026-11-21` run at 9 am drops commits before + 9 am on Nov 1 and after 9 am on Nov 21. +- `--days` derives a bare UTC date (`collector.ts:122-128`), so the window shifts with clock time and + UTC offset. `periods` does the same for its lookback start (`src/cli/periods-command.ts:71`). +- `--since X --until X` (a single day) is rejected as "Since date must be before until date" + (`src/utils/validation.ts:43-48`). + +## Scope and Independence + +In scope: expanding bare dates to explicit start-of-day and end-of-day timestamps in the analysis +timezone, `--days N` as an exact timestamp offset, allowing single-day ranges, and stating the +resolved window in report metadata. Out of scope: new relative-date syntax. + +Standalone: CLI syntax is unchanged; results become deterministic. + +## Future Health + +Uses the timezone helper from ps-003 if it has shipped; otherwise uses the same `Intl` approach so the +two converge. Keeps `options` immutable rather than mutating `options.since` (`collector.ts:126,142`), +which the current regression test relies on and should check through metadata instead. + +## Dependencies and Decisions + +No hard dependency. Ship ps-003 first if both are planned, so both use one timezone helper. + +## Completion Expectations + +Tests at fixed fake clock times (morning, evening, across a UTC date change) return the same commits +for the same window. A single-day range is accepted. The report shows the resolved window. diff --git a/.devspark.work/roadmap/specs/ps-005-accurate-commit-message-scoring.md b/.devspark.work/roadmap/specs/ps-005-accurate-commit-message-scoring.md new file mode 100644 index 0000000..737ea5a --- /dev/null +++ b/.devspark.work/roadmap/specs/ps-005-accurate-commit-message-scoring.md @@ -0,0 +1,52 @@ +--- +id: ps-005 +title: Accurate commit message scoring +status: proposed +order: 50 +depends_on: [] +blockers: [] +delivery: [] +--- + +# ps-005: Accurate commit message scoring + +## Outcome + +The governance score rewards the commit practices it claims to measure, and no longer penalizes +detailed commit messages. + +## Current Reality + +- The length rule (10 to 72 characters earns 0.15) is applied to the whole message, subject plus + body (`src/core/analyzer.ts:1469`, message built at `src/core/collector.ts:310`). Any commit with a + body fails it. In this repository 107 of 222 non-merge commits have a body and lose the points. +- The conventional-commit pattern does not accept breaking-change markers (`feat!:`, `feat(api)!:`) + or the `revert` type (`src/utils/validation.ts:299`). +- WIP detection matches `wip` anywhere, including "wipe" and "swipe" (`validation.ts:303`). + Traceability counts the words "fixes", "closes", or "resolves" anywhere, even without an issue + reference (`validation.ts:302`). +- Governance weights in config (`analysis.weights.governance`) are not used; the weights are + hard-coded (`analyzer.ts:1467-1471`). + +## Scope and Independence + +In scope: applying the length rule to the subject line, matching the Conventional Commits 1.0 header +grammar, word-boundary WIP detection, and requiring an actual reference for traceability. Out of +scope: honoring config weights (ps-007 decides whether those keys stay). + +Standalone: the score changes value, not shape. The governance section's limitations text describes +the rules exactly. + +## Future Health + +Moves the scoring rules next to `validateCommitMessage` so the rules and the score cannot drift. + +## Dependencies and Decisions + +The score will rise for well-documented repositories. Call this out in the CHANGELOG so users +comparing scores across versions are not misled. + +## Completion Expectations + +Table-driven tests cover subject length with and without a body, `feat!:`, `revert:`, "wipe", and +"fixes the build" without an issue reference. diff --git a/.devspark.work/roadmap/specs/ps-006-complete-email-redaction.md b/.devspark.work/roadmap/specs/ps-006-complete-email-redaction.md new file mode 100644 index 0000000..0f5c322 --- /dev/null +++ b/.devspark.work/roadmap/specs/ps-006-complete-email-redaction.md @@ -0,0 +1,51 @@ +--- +id: ps-006 +title: Complete, collision-free email redaction +status: proposed +order: 60 +depends_on: [] +blockers: [] +delivery: [] +--- + +# ps-006: Complete, collision-free email redaction + +## Outcome + +`--redact-emails` (or `output.redactEmails` in config) produces reports in every format that contain +no author email address, without merging different people into one. + +## Current Reality + +- The root command declares `--redact-emails` but never copies it into `GitSparkOptions` + (`src/cli/commands.ts:251-268`), and the `html` subcommand has no such option. Verified: a JSON + report generated with the flag still contains full addresses. Only the config key works + (`src/utils/config.ts:109-111`). +- Redaction is applied as the grouping key: `sanitizeEmail` keeps the first letter and the domain + (`src/utils/validation.ts:272-281`), and authors are grouped by the redacted value + (`src/core/analyzer.ts:359-363`). `mark@example.com` and `mike@example.com` become one author. +- Redaction is applied in the author list and file authors only. Other paths use the raw email, for + example daily-trends contributor data (`src/core/daily-trends-helpers.ts:62`). + +## Scope and Independence + +In scope: wiring the flag on the root and `html` commands, grouping by real identity and redacting at +output, and a check that no email pattern appears in any output format when redaction is on. Out of +scope: redacting names. + +Standalone: fixes a privacy promise without depending on other items. + +## Future Health + +If ps-002 has shipped, redact its single identity key at output. If not, this PS introduces the +"group by real, display redacted" rule that ps-002 then keeps. + +## Dependencies and Decisions + +Decide the redacted form: keep `m***@example.com`, or use a stable per-run alias such as +`author-3@example.com` that cannot collide. + +## Completion Expectations + +A test generates every format with redaction on from a repository with two same-initial, +same-domain authors. It finds no email address and two distinct authors. diff --git a/.devspark.work/roadmap/specs/ps-007-honor-or-retire-inert-options.md b/.devspark.work/roadmap/specs/ps-007-honor-or-retire-inert-options.md new file mode 100644 index 0000000..8faa536 --- /dev/null +++ b/.devspark.work/roadmap/specs/ps-007-honor-or-retire-inert-options.md @@ -0,0 +1,57 @@ +--- +id: ps-007 +title: Honor or retire inert options +status: proposed +order: 70 +depends_on: [] +blockers: [] +delivery: [] +--- + +# ps-007: Honor or retire inert options + +## Outcome + +Every CLI flag and `.git-spark.json` key either changes the report or is gone, and users can exclude +bot accounts from analysis. + +## Current Reality + +`git-spark init` writes, and the CLI accepts, settings that nothing reads: + +- `--heavy` and `--no-cache` are copied into options (`src/cli/commands.ts:262-264`) but no analysis + reads `heavy` or `noCache`, and no cache exists. +- `analysis.excludePaths`, `analysis.excludeAuthors`, `analysis.includeAuthors`, + `analysis.thresholds.*`, `analysis.weights.*`, and `performance.*` are in the default and generated + config (`src/index.ts:218-474`, `src/cli/commands.ts:570-596`) but are never applied. Thresholds are + hard-coded instead, for example large commit `> 500` (`src/core/analyzer.ts:1296`). +- `--author` rejects bot names such as `github-actions[bot]` because `[` and `]` are refused + (`src/utils/input-validation.ts:74`). Bots therefore cannot be included or excluded. The 2026-11-21 + repo story counted 14 of 134 commits from automation in this repository. + +## Scope and Independence + +In scope: implementing `excludeAuthors` (config plus an `--exclude-authors` flag) with bracket-safe +matching; applying `excludePaths` and the thresholds the analyzer already hard-codes; removing +`--heavy`, `--no-cache`, `performance.*`, and the unused `weights` and `includeAuthors`, with a +deprecation warning for one minor version; and making `init` write only live keys. Out of scope: +building a cache. + +Standalone: each removal keeps accepting the old input with a warning, so existing configs and +scripts do not break. + +## Future Health + +A config whose keys are all live is safe to extend. Keep the warning list in one place so the removals +can be completed in the next major version. + +## Dependencies and Decisions + +Decide per key: implement or retire. The recommendation above implements the cheap, useful ones +(`excludeAuthors`, `excludePaths`, thresholds) and retires the rest. Removing flags is a minor-version +change with warnings and a major-version removal. + +## Completion Expectations + +A test asserts every key in the generated config affects output or triggers a deprecation warning. +Excluding `github-actions[bot]` removes its commits from every section. diff --git a/.devspark.work/roadmap/specs/ps-008-multiple-and-exclude-path-filters.md b/.devspark.work/roadmap/specs/ps-008-multiple-and-exclude-path-filters.md new file mode 100644 index 0000000..d7849c8 --- /dev/null +++ b/.devspark.work/roadmap/specs/ps-008-multiple-and-exclude-path-filters.md @@ -0,0 +1,48 @@ +--- +id: ps-008 +title: Multiple and exclude path filters +status: proposed +order: 80 +depends_on: [] +blockers: [] +delivery: [] +--- + +# ps-008: Multiple and exclude path filters + +## Outcome + +Users can scope an analysis to several paths and exclude others in one run, for example "`src` and +`test`, but not `src/generated`". + +## Current Reality + +Since PR #19, `--path` accepts a single Git pathspec glob (`src/core/collector.ts:190`). Git supports +several pathspecs and `:(exclude)` / `:!` magic, but the CLI accepts one value, and `validatePathString` +rejects `(`, `)`, and `!`-style magic as unsafe characters (`src/utils/input-validation.ts:143`). +Excluding a directory today needs `--exclude-extensions` (extensions only) or `.gitignore` (current +files only). + +## Scope and Independence + +In scope: a repeatable `--path` option, a repeatable `--exclude-path` option translated internally to +`:(exclude)` pathspecs, and validation that allows exactly those forms while still rejecting +traversal and control characters. Out of scope: arbitrary pathspec magic such as `:(icase)` or +`:(attr)`. + +Standalone: a single `--path` keeps working unchanged. + +## Future Health + +Pathspecs stay Git's job; the CLI composes them and never evaluates patterns itself, preserving the +spawn-argument safety model (constitution principle 3). + +## Dependencies and Decisions + +If ps-007 implements `analysis.excludePaths`, back it with this mechanism rather than a second +matcher. + +## Completion Expectations + +Collector tests show `--path src --path test --exclude-path src/generated` returns exactly the commits +`git log -- src test ':(exclude)src/generated'` returns. diff --git a/.devspark.work/roadmap/specs/ps-009-decompose-the-analyzer.md b/.devspark.work/roadmap/specs/ps-009-decompose-the-analyzer.md new file mode 100644 index 0000000..ce3ea34 --- /dev/null +++ b/.devspark.work/roadmap/specs/ps-009-decompose-the-analyzer.md @@ -0,0 +1,45 @@ +--- +id: ps-009 +title: Decompose the analyzer +status: proposed +order: 90 +depends_on: [] +blockers: [] +delivery: [] +--- + +# ps-009: Decompose the analyzer + +## Outcome + +Analysis is split into focused modules (repository stats, authors, files and risk, governance, +team score) that can each be read and tested on their own, with no behavior change. + +## Current Reality + +`src/core/analyzer.ts` is 2,597 lines, five times the 500-line threshold cited when the HTML output +modules were decomposed (issues #5, #6, #9, closed 2026-05-11). It holds data flow, every metric, and +the limitations text. ps-002 through ps-007 all edit it, and identity and timezone logic is currently +duplicated across its sections. + +## Scope and Independence + +In scope: moving existing methods into modules behind the current `GitAnalyzer` API, with identical +report output. Out of scope: metric changes. Those belong to their own PS. + +Standalone: the public API and the JSON report are byte-for-byte unchanged on a fixed repository. + +## Future Health + +Makes later metric work reviewable. It is only worth doing as its own outcome if several of ps-002 +to ps-007 are still ahead; otherwise each of those should leave its section cleaner as it goes. + +## Dependencies and Decisions + +Best scheduled after ps-003 and ps-005, which settle the shared timezone and scoring helpers the +modules would import. Decide whether to do it at all once those land. + +## Completion Expectations + +A golden-report test (JSON for a fixed fixture repository) passes before and after. No module exceeds +500 lines. diff --git a/CHANGELOG.md b/CHANGELOG.md index 98430e2..f8168df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `--path` accepts Git glob patterns such as `src/**` and `src/core/*.ts`. It was validated as a regular expression, so `**` failed with "Path pattern is not a valid regex pattern" even though the value is passed to Git as a pathspec - `--branch` combined with `--path` now analyzes the requested branch. The branch was placed after Git's `--` separator, so Git read it as a second path and analyzed the current branch instead - The oldest commit in the analyzed range is no longer dropped when its message has a multi-line body. The last record of the Git log stream was parsed as if its header ended at the first newline, so a body spanning several lines made it look malformed and it was silently skipped, undercounting commits, churn, and files in any window or path filter whose oldest commit had a detailed message +- `git-spark validate` recognizes a Git repository again. It always reported "Failed to validate Git repository" because a module import lacked the `.js` extension that Node ESM requires +- `git-spark analyze` now applies the global options (`--days`, `--format`, `--output`, `--path`, and the rest). It only read `--repo`, so the other options were silently ignored +- Bus Factor shows `0%` instead of `NaN%` when the analyzed window has no commits, in the CLI summary, health check, and console, HTML, and Markdown reports + +### Security + +- `git-spark html --serve` listens on `127.0.0.1` only and no longer sends `Access-Control-Allow-Origin: *`. It listened on every network interface, so anyone on the local network could read the report, including author names and emails. Requests other than GET and HEAD now return 405 ## [2.0.2] - 2026-11-21 diff --git a/src/cli/commands.ts b/src/cli/commands.ts index c257019..4edb348 100644 --- a/src/cli/commands.ts +++ b/src/cli/commands.ts @@ -10,6 +10,7 @@ import { getVersion } from '../version-fallback.js'; import { resolveOptionsWithConfig } from '../utils/config.js'; import { executeHTMLReport, openHTMLReport } from './report-command.js'; import { executePeriodsReport } from './periods-command.js'; +import { busFactorShare } from '../core/analyzer-helpers.js'; import chalk from 'chalk'; import boxen from 'boxen'; import ora from 'ora'; @@ -153,8 +154,10 @@ export async function createCLI(): Promise { .command('analyze') .description('Run detailed analysis') .option('-r, --repo ', 'repository path', process.cwd()) - .action(async options => { - await executeAnalysis({ ...options, repoPath: options.repo }); + .action(async (options, command) => { + // Global options such as --days and --format are stored on the parent command + const parentOptions = command.parent?.opts() || {}; + await executeAnalysis({ ...parentOptions, ...options }); }); program @@ -404,7 +407,7 @@ async function validateEnvironment(): Promise { // Check current directory is a Git repository try { - const { GitExecutor } = await import('../utils/git'); + const { GitExecutor } = await import('../utils/git.js'); const git = new GitExecutor(process.cwd()); const isValid = await git.validateRepository(); @@ -466,7 +469,7 @@ function displaySummary(report: AnalysisReport, version: string): void { chalk.blue(`Active Contributors: ${repository.totalAuthors}\n`) + chalk.blue(`Files Changed: ${repository.totalFiles}\n`) + chalk.blue( - `Bus Factor: ${Math.round((repository.busFactor / repository.totalAuthors) * 100)}%` + `Bus Factor: ${busFactorShare(repository.busFactor, repository.totalAuthors)}%` ), { padding: 1, @@ -504,7 +507,7 @@ function displayHealthSummary(report: AnalysisReport): void { chalk.blue(`Governance Score: ${Math.round(governance.score * 100)}%\n`) + chalk.blue(`Risk Level: ${report.risks.overallRisk.toUpperCase()}\n`) + chalk.blue( - `Bus Factor: ${Math.round((repository.busFactor / repository.totalAuthors) * 100)}%\n` + `Bus Factor: ${busFactorShare(repository.busFactor, repository.totalAuthors)}%\n` ) + chalk.blue(`Active Days: ${repository.activeDays}`), { diff --git a/src/cli/report-command.ts b/src/cli/report-command.ts index afee15a..4515fe9 100644 --- a/src/cli/report-command.ts +++ b/src/cli/report-command.ts @@ -10,9 +10,14 @@ import { GitSparkOptions, OutputFormat, LogLevel } from '../types/index.js'; import { validateOptions } from '../utils/validation.js'; import { resolveOptionsWithConfig } from '../utils/config.js'; import { createLogger } from '../utils/logger.js'; +import { busFactorShare } from '../core/analyzer-helpers.js'; +import type { Server } from 'http'; const logger = createLogger('cli:report'); +/** The report server only listens on loopback so the report never reaches the network. */ +export const REPORT_SERVER_HOST = '127.0.0.1'; + interface HTMLReportCliOptions { repo?: string; since?: string; @@ -135,7 +140,7 @@ export async function executeHTMLReport(options: HTMLReportCliOptions): Promise< chalk.blue(`📁 Files Analyzed: ${report.repository.totalFiles}\n`) + chalk.blue(`📊 Activity Index: ${Math.round(report.repository.healthScore * 100)}%\n`) + chalk.blue( - `🚌 Bus Factor: ${Math.round((report.repository.busFactor / report.repository.totalAuthors) * 100)}%` + `🚌 Bus Factor: ${busFactorShare(report.repository.busFactor, report.repository.totalAuthors)}%` ), { padding: 1, @@ -190,46 +195,46 @@ export async function executeHTMLReport(options: HTMLReportCliOptions): Promise< * @param reportPath - Path to the HTML report file * @param port - Port number to serve on */ +export async function createReportServer(reportPath: string): Promise { + const { createServer } = await import('http'); + const { readFileSync } = await import('fs'); + + // No CORS headers: other origins must not be able to read the report + return createServer((req, res) => { + if (req.method !== 'GET' && req.method !== 'HEAD') { + res.writeHead(405, { 'Content-Type': 'text/plain', Allow: 'GET, HEAD' }); + res.end('Method Not Allowed'); + return; + } + + if (req.url === '/' || req.url === '/index.html') { + try { + const htmlContent = readFileSync(reportPath, 'utf-8'); + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(htmlContent); + } catch { + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('Report not found'); + } + } else { + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('Not Found'); + } + }); +} + export async function startHTMLServer(reportPath: string, port: number): Promise { const spinner = ora(`Starting HTTP server on port ${port}`).start(); try { - const { createServer } = await import('http'); - const { readFileSync } = await import('fs'); - - const server = createServer((req, res) => { - // Add CORS headers - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); - res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); - - if (req.method === 'OPTIONS') { - res.writeHead(200); - res.end(); - return; - } - - if (req.url === '/' || req.url === '/index.html') { - try { - const htmlContent = readFileSync(reportPath, 'utf-8'); - res.writeHead(200, { 'Content-Type': 'text/html' }); - res.end(htmlContent); - } catch (error) { - res.writeHead(404, { 'Content-Type': 'text/plain' }); - res.end('Report not found'); - } - } else { - res.writeHead(404, { 'Content-Type': 'text/plain' }); - res.end('Not Found'); - } - }); + const server = await createReportServer(reportPath); - server.listen(port, () => { + server.listen(port, REPORT_SERVER_HOST, () => { spinner.succeed(`HTTP server started`); console.log( boxen( chalk.bold('🌐 HTML Report Server Running\n\n') + - chalk.green(`📊 Report URL: http://localhost:${port}\n`) + + chalk.green(`📊 Report URL: http://${REPORT_SERVER_HOST}:${port}\n`) + chalk.blue(`📁 Serving: ${reportPath}\n`) + chalk.yellow(`⚡ Press Ctrl+C to stop server`), { diff --git a/src/core/analyzer-helpers.ts b/src/core/analyzer-helpers.ts index 2dbe29f..dbdf729 100644 --- a/src/core/analyzer-helpers.ts +++ b/src/core/analyzer-helpers.ts @@ -5,6 +5,14 @@ import { CommitData } from '../types/index.js'; +/** + * Bus factor as a whole-number percentage of contributors. Returns 0 when there are no + * contributors (an empty analysis window) instead of NaN. + */ +export function busFactorShare(busFactor: number, totalAuthors: number): number { + return totalAuthors > 0 ? Math.round((busFactor / totalAuthors) * 100) : 0; +} + /** * Calculate the longest streak of active days (with up to 2-day gaps allowed) * diff --git a/src/core/analyzer.ts b/src/core/analyzer.ts index c1f7cb5..d3cf3fb 100644 --- a/src/core/analyzer.ts +++ b/src/core/analyzer.ts @@ -31,6 +31,7 @@ import { DailyTrendsAnalyzer } from './daily-trends.js'; import { createLogger } from '../utils/logger.js'; import { validateCommitMessage, sanitizeEmail } from '../utils/validation.js'; import { + busFactorShare, calculateLongestStreak, detectCommitBursts, calculateCommitGaps, @@ -1374,7 +1375,7 @@ export class GitAnalyzer { 'Code Churn': repository.totalChurn, 'Activity Index': Math.round(repository.healthScore * 100), 'Governance Score': Math.round(governance.score * 100), - 'Bus Factor': Math.round((repository.busFactor / repository.totalAuthors) * 100), + 'Bus Factor': busFactorShare(repository.busFactor, repository.totalAuthors), }; const insights = this.generateInsights(repository, authors, files, risks, governance); diff --git a/src/output/console.ts b/src/output/console.ts index fb743ab..ef143ef 100644 --- a/src/output/console.ts +++ b/src/output/console.ts @@ -8,6 +8,7 @@ import { import chalk from 'chalk'; import { table } from 'table'; import { createLogger } from '../utils/logger.js'; +import { busFactorShare } from '../core/analyzer-helpers.js'; const logger = createLogger('console-exporter'); /** @@ -63,7 +64,7 @@ export class ConsoleExporter { ['Contributors', repository.totalAuthors.toString()], ['Files Changed', repository.totalFiles.toLocaleString()], ['Code Churn', repository.totalChurn.toLocaleString() + ' lines'], - ['Bus Factor', Math.round((repository.busFactor / repository.totalAuthors) * 100) + '%'], + ['Bus Factor', busFactorShare(repository.busFactor, repository.totalAuthors) + '%'], ['Active Days', repository.activeDays.toString()], ]; diff --git a/src/output/html.ts b/src/output/html.ts index 150c1af..ef179d5 100644 --- a/src/output/html.ts +++ b/src/output/html.ts @@ -16,6 +16,7 @@ import { import { writeFileSync, mkdirSync } from 'fs'; import { resolve, dirname, basename } from 'path'; import { createLogger } from '../utils/logger.js'; +import { busFactorShare } from '../core/analyzer-helpers.js'; import { createHash } from 'crypto'; const logger = createLogger('html-exporter'); @@ -74,7 +75,7 @@ export class HTMLExporter { { label: 'Code Churn', value: compactFmt(report.repository.totalChurn) }, { label: 'Bus Factor', - value: `${Math.round((report.repository.busFactor / report.repository.totalAuthors) * 100)}%`, + value: `${busFactorShare(report.repository.busFactor, report.repository.totalAuthors)}%`, }, ]; @@ -292,7 +293,7 @@ export class HTMLExporter {
Bus Factor - ${Math.round((report.repository.busFactor / report.repository.totalAuthors) * 100)}% + ${busFactorShare(report.repository.busFactor, report.repository.totalAuthors)}% Percentage of authors for 50% of commits
diff --git a/src/output/markdown.ts b/src/output/markdown.ts index 097df40..d0e8621 100644 --- a/src/output/markdown.ts +++ b/src/output/markdown.ts @@ -2,6 +2,7 @@ import { AnalysisReport } from '../types/index.js'; import { writeFileSync, mkdirSync } from 'fs'; import { resolve, dirname } from 'path'; import { createLogger } from '../utils/logger.js'; +import { busFactorShare } from '../core/analyzer-helpers.js'; const logger = createLogger('markdown-exporter'); @@ -56,7 +57,7 @@ Generated on ${report.metadata.generatedAt.toLocaleDateString()} | Contributors | ${repository.totalAuthors} | | Files Changed | ${repository.totalFiles} | | Health Score | ${Math.round(repository.healthScore * 100)}% | -| Bus Factor | ${Math.round((repository.busFactor / repository.totalAuthors) * 100)}% | +| Bus Factor | ${busFactorShare(repository.busFactor, repository.totalAuthors)}% | ${ summary.insights.length > 0 diff --git a/test/cli-fixes-regression.test.ts b/test/cli-fixes-regression.test.ts new file mode 100644 index 0000000..e00e60e --- /dev/null +++ b/test/cli-fixes-regression.test.ts @@ -0,0 +1,104 @@ +import { readdirSync, readFileSync, rmSync, writeFileSync, mkdtempSync } from 'fs'; +import { join } from 'path'; +import { tmpdir } from 'os'; +import type { AddressInfo } from 'net'; +import { request } from 'http'; +import { busFactorShare } from '../src/core/analyzer-helpers.js'; +import { createReportServer, REPORT_SERVER_HOST } from '../src/cli/report-command.js'; + +// chalk, boxen, and ora are ESM-only; Jest runs CommonJS, so replace them with pass-throughs +jest.mock('chalk', () => { + const style: unknown = new Proxy((text: string) => text, { get: () => style }); + return { __esModule: true, default: style }; +}); +jest.mock('boxen', () => ({ __esModule: true, default: (text: string) => text })); +jest.mock('ora', () => ({ + __esModule: true, + default: () => { + const spinner = { + text: '', + start: () => spinner, + succeed: () => spinner, + fail: () => spinner, + warn: () => spinner, + }; + return spinner; + }, +})); + +function listSourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap(entry => { + const full = join(dir, entry.name); + if (entry.isDirectory()) return listSourceFiles(full); + return entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') ? [full] : []; + }); +} + +describe('relative imports', () => { + it('always carry a .js extension so Node ESM can resolve them', () => { + // Jest resolves extensionless imports, so a runtime test would not catch a missing extension + const relativeImport = /(?:from\s+|import\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g; + const offenders: string[] = []; + for (const file of listSourceFiles(join(process.cwd(), 'src'))) { + for (const match of readFileSync(file, 'utf-8').matchAll(relativeImport)) { + if (!match[1].endsWith('.js')) offenders.push(`${file}: ${match[1]}`); + } + } + expect(offenders).toEqual([]); + }); +}); + +describe('busFactorShare', () => { + it('returns 0 for an empty window instead of NaN', () => { + expect(busFactorShare(0, 0)).toBe(0); + }); + + it('rounds the share of contributors to a whole percentage', () => { + expect(busFactorShare(1, 3)).toBe(33); + expect(busFactorShare(2, 2)).toBe(100); + }); +}); + +describe('report server', () => { + const dir = mkdtempSync(join(tmpdir(), 'git-spark-server-')); + const reportPath = join(dir, 'report.html'); + + beforeAll(() => writeFileSync(reportPath, 'report')); + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + function send(port: number, method: string, path = '/') { + return new Promise<{ status: number; headers: Record; body: string }>( + (resolve, reject) => { + const req = request({ host: REPORT_SERVER_HOST, port, method, path }, res => { + let body = ''; + res.on('data', chunk => (body += chunk)); + res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body })); + }); + req.on('error', reject); + req.end(); + } + ); + } + + it('listens on loopback only', () => { + expect(REPORT_SERVER_HOST).toBe('127.0.0.1'); + }); + + it('serves the report without CORS headers and rejects other methods', async () => { + const server = await createReportServer(reportPath); + await new Promise(resolve => server.listen(0, REPORT_SERVER_HOST, resolve)); + const { port } = server.address() as AddressInfo; + try { + const get = await send(port, 'GET'); + expect(get.status).toBe(200); + expect(get.body).toBe('report'); + expect(get.headers['access-control-allow-origin']).toBeUndefined(); + + expect((await send(port, 'OPTIONS')).status).toBe(405); + expect((await send(port, 'POST')).status).toBe(405); + expect((await send(port, 'GET', '/other')).status).toBe(404); + } finally { + await new Promise(resolve => server.close(resolve)); + } + }); +});