Skip to content

refactor(engine): extract the stranded linked-reference parsers out of the D1 repository layer - #5773

Closed
glorydavid03023 wants to merge 1 commit into
JSONbored:mainfrom
glorydavid03023:refactor/engine-linked-references-v2
Closed

refactor(engine): extract the stranded linked-reference parsers out of the D1 repository layer#5773
glorydavid03023 wants to merge 1 commit into
JSONbored:mainfrom
glorydavid03023:refactor/engine-linked-references-v2

Conversation

@glorydavid03023

Copy link
Copy Markdown
Contributor

Closes #4882

Summary

#4882 asks for a sweep of the largest I/O-bound files for pure logic stranded inside them, and names its own first candidate: "a pure regex-based parser living inside the very large D1-query-heavy repository-access file."

That file is src/db/repositories.ts (~386KB, D1-query-heavy), and that parser is the linked-issue / linked-PR reference extractor — extractLinkedIssueNumbersWithOverflow, extractLinkedIssueNumbers, extractLinkedPrNumbers, MAX_LINKED_ISSUE_NUMBERS. It is pure regex logic with no D1 or Env dependency, yet four core modules (src/github/backfill.ts, src/review/enrichment-wire.ts, src/review/linked-issue-hard-rules.ts, src/signals/engine.ts) reach into the database layer purely to get at it.

This PR moves it into @loopover/engine, which also closes a real divergence — the reason this was the right candidate to move first.

The divergence this closes

The engine cannot import from src/, so packages/loopover-engine/src/signals/predicted-gate-engine.ts carried a hand-written second copy of the parser. That copy had drifted: it was missing the inline-code-span guard the live gate's copy has, and it silently lacked the MAX_LINKED_ISSUE_NUMBERS (50) overflow cap that linked-issue-hard-rules.ts relies on.

The consequence: a closing keyword wrapped in backticks is not a real GitHub closing directive, and the live gate correctly ignores it — but the engine's copy counted it. So the miner's predicted gate could report a linked issue for a body the live gate reads as having none, telling a contributor their PR was safe immediately before the linked-issue hard rule closed it. The pre-submit oracle was wrong in exactly the failure mode it exists to prevent.

What changed

  • New packages/loopover-engine/src/github/linked-references.ts — the parsers, moved with their regexes byte-for-byte identical, so the live gate's behavior is provably unchanged. It sits in the engine's existing github/ directory next to constants.ts and sanitize-public-comment.ts.
  • packages/loopover-engine/src/signals/predicted-gate-engine.ts — the hand-written duplicate is deleted; it imports the shared parser. The two gates can no longer disagree.
  • src/db/repositories.ts — the stranded implementation is gone; the file re-exports from the engine as a thin shim, so all four existing importers keep working unchanged. Imported by relative source path, matching the convention in src/signals/check-summary.ts.

No public API changed, and no host-side gate behavior changed.

Other stranded-pure-logic candidates found in the same sweep

Recorded so the next slice of #4882 need not re-derive them. All are pure, top-level, and D1-free inside src/db/repositories.ts:

  1. Product-usage rollup analytics (~:6900-7290) — buildProductUsageDailyRollupRecord, buildProductUsageActivationFunnel, buildProductUsageRetentionRollups, productUsageRetentionRate, intersectionCount, addProductUsageUtcDays. The largest pure cluster in the file.
  2. Product-usage sanitizerssanitizeProductUsageMetadata / sanitizeProductUsageJson / sanitizeProductUsageString.
  3. Settings-column parsers (parseAutonomyPolicy, parseGatePack, parseTypeLabelSet, normalizeReviewNagPolicy, …) — deliberately left alone: they belong to the settings/ slice tracked by Finish the settings/ slice extraction #4879, and moving them here would collide with it.

loginMatches is not a candidate despite looking pure — it builds a Drizzle sql fragment and belongs with the query layer.

Scope

  • The PR title follows type(scope): short summary Conventional Commit format.
  • This PR is focused and does not mix unrelated backend, UI, MCP, docs, dependency, and deploy changes.
  • This follows CONTRIBUTING.md and does not reintroduce GitHub Pages, VitePress, site/, or CNAME.
  • I linked a currently open issue this PR resolves — see the closing reference at the top of this body. A linked open issue is required for every contributor PR.

Validation

  • git diff --check
  • npm run actionlint
  • npm run typecheck
  • npm run test:coverage locally; codecov/patch requires ≥99% coverage of the lines AND branches you changed.
  • npm run test:workers
  • npm run build:mcp
  • npm run test:mcp-pack
  • npm run ui:openapi:check
  • npm run ui:lint
  • npm run ui:typecheck
  • npm run ui:build
  • npm audit --audit-level=moderate
  • New or changed behavior has unit/integration tests for new branches, fallback paths, and sanitizer boundaries

New suite test/unit/linked-references.test.ts (12 tests) covers the moved module at 100% statements / branches / functions / lines (29/29, 19/19, 7/7, 21/21):

  • every supported closing keyword, bare and owner/repo-qualified, plus the cross-repo form that must not count;
  • the inline-code-span guard, with a span overlapping the match, a span before it, and a span after it — both sides of the overlap predicate;
  • why the spans cannot simply be blanked out first (text on either side of a span must not combine into a fake reference);
  • dedupe, a zero issue number, and a 400-digit number that overflows to Infinity;
  • overflow at the default cap and at explicit / fractional / negative limits;
  • regression tests asserting the predicted gate and the live gate now return the same answer for an unedited PR-template line, and across the whole closing-keyword grammar.

npm run engine-parity:drift-check passes (22 duplicated pairs agree), as do test:engine-parity, test:live-gate-parity, test:driver-parity, and the @loopover/engine workspace suite.

If any required check was skipped, explain why:

  • None skipped.

Safety

  • No secrets, wallet details, hotkeys, coldkeys, user PATs, private keys, raw trust scores, private rankings, or private maintainer evidence are exposed.
  • Public GitHub text stays sanitized, low-noise, and does not imply compensation guarantees or optimization tactics.
  • Auth, cookie, CORS, GitHub App, Cloudflare, or session changes include negative-path tests.
  • API/OpenAPI/MCP behavior is updated and tested where needed.
  • UI changes use live API data or real empty/error/loading states, not production mock/demo fallbacks.
  • Visible UI changes include a UI Evidence section with JPG/PNG screenshots. Not applicable here.
  • Public docs/changelogs are updated where needed; changelogs are only edited for release-prep PRs.

UI Evidence

Not applicable — no UI, frontend, docs, or extension surface is touched. The diff is three backend/engine TypeScript files plus one new unit-test file.

Notes

  • The regexes are moved byte-for-byte, so the live gate's behavior is provably unchanged; the only behavior change is that the predicted gate stops disagreeing with it.
  • The new module is intentionally not re-exported from packages/loopover-engine/src/index.ts: both consumers import it by relative source path per the existing convention, so adding an unused export there would widen the public surface for no caller.

…f the D1 repository layer (JSONbored#4882)

`src/db/repositories.ts` is a ~386KB, D1-query-heavy repository-access file, and JSONbored#4882 calls out the
exact candidate stranded inside it: "a pure regex-based parser living inside the very large
D1-query-heavy repository-access file". That parser is the linked-issue/PR reference extractor --
pure regex logic with no D1 or `Env` dependency, yet four core modules reach into the database layer
purely to get at it.

Move it to `@loopover/engine` as `github/linked-references.ts` (regexes byte-for-byte identical, so
the live gate's behavior is provably unchanged), and re-export it from `src/db/repositories.ts` as a
thin shim so every existing importer keeps working.

This also converges a real divergence. Because the engine cannot import from `src/`,
`signals/predicted-gate-engine.ts` carried a hand-written second copy that had drifted: it was
missing the inline-code-span guard. This repo's own PR template contains "(e.g. `Closes JSONbored#123`)" on
the line contributors are told to fill out, not replace -- so the predicted gate read a linked issue
where the live gate correctly sees none, telling contributors their PR was safe right before the
linked-issue hard rule closed it. The engine copy also lacked the MAX_LINKED_ISSUE_NUMBERS overflow
cap that linked-issue-hard-rules.ts relies on. Both gates now resolve one shared module.

Tests cover the moved module at 100% statements/branches/functions/lines, including both sides of the
code-span overlap predicate, the cross-repo qualified form, overflow at default/explicit/fractional/
negative limits, and regression tests pinning that the predicted gate and the live gate now agree on
the unedited PR template.
@superagent-security

Copy link
Copy Markdown
Contributor

Superagent didn't find any vulnerabilities or security issues in this PR.

@loopover-orb loopover-orb Bot added the gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier. label Jul 14, 2026
@loopover-orb

loopover-orb Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Caution

🟥🟥🟥🟥🟥🟥🟥🟥🟥🟥🟥🟥

🛑 LoopOver review result - reject/close recommended

Review updated: 2026-07-14 14:00:41 UTC

4 files · 1 AI reviewer · 1 blocker · readiness 100/100 · CI green · clean

🛑 Suggested Action - Reject/Close

Review summary
This is a clean, well-scoped extraction: the pure regex-based linked-issue/PR parser moves from the D1-heavy repositories.ts into @​loopover/engine's linked-references.ts, with repositories.ts re-exporting the same symbols so existing callers are unaffected. It also fixes a real divergence — the predicted-gate-engine's hand-written duplicate lacked the inline-code-span guard and the MAX_LINKED_ISSUE_NUMBERS cap — by deleting that copy and importing the canonical implementation, with regression tests asserting the two gates now agree on the PR template's own `Closes #123` example. The move is byte-for-byte identical regex logic and is backed by convergence tests plus all-green CI, so the refactor is low-risk and directly closes the linked issue #4882's named first candidate.

Nits — 4 non-blocking
  • src/db/repositories.ts re-exports via a relative path into packages/loopover-engine/src rather than the `@​loopover/engine` package import already used at the top of the file for `parsePullRequestTargetKey` — worth confirming this relative-path convention is intentional (the comment says it matches src/signals/check-summary.ts) rather than an inconsistency to clean up later.
  • The two pre-existing long-file smells on predicted-gate-engine.ts and repositories.ts are not introduced by this diff (repositories.ts actually shrinks by 33 lines here) so they're not this PR's responsibility, but worth noting they remain candidates for further Sweep for pure logic stranded inside I/O-bound files #4882 sweeps.
  • Consider following up by importing extractLinkedPrNumbers via the `@​loopover/engine` public export path in repositories.ts once the package is built/published, matching the pattern noted in the comment.
  • If other stranded-parser candidates exist per Sweep for pure logic stranded inside I/O-bound files #4882's sweep, a short follow-up issue list would help track the remaining split-out work.

Why this is blocked

  • No linked issue detected — If this PR is intended to solve an issue, link it explicitly in the PR body.
📋 Copy for AI agents — paste into your coding agent
Fix the following blocker(s) from this PR review:

1. No linked issue detected — If this PR is intended to solve an issue, link it explicitly in the PR body.
Signal Result Evidence
Code review ❌ 1 blocker 1 reviewer
Linked issue ✅ Linked #4882
Related work ✅ No active overlap found No same-issue or scoped active PR overlap found.
Change scope ✅ 20/20 Low review scope from cached public metadata (1 linked issue).
Validation posture ✅ 25/25 PR body includes validation/test evidence.
Contributor workload ✅ 10/10 Author activity: 273 registered-repo PR(s), 165 merged, 20 issue(s).
Contributor context ✅ Confirmed Gittensor contributor glorydavid03023; Gittensor profile; 273 PR(s), 20 issue(s).
Gate result ❌ Blocking Repo-configured hard blocker found.
Improvement ✅ Minor risk: clean · value: minor — Code changes are accompanied by test evidence. LLM value judgment: moderate — The diff is a well-targeted, test-backed extraction that both satisfies the linked issue's explicit first candidate and fixes a genuine live-vs-predicted-gate divergence, making it a solid but narrowly-scoped maintainability win rather than a large-impact change.
Linked issue satisfaction

Addressed
The PR extracts the pure regex-based linked-issue/PR parser out of the D1-heavy repositories.ts file into the engine package as standalone functions, exactly matching the issue's named first candidate, and adds a new test file covering the moved functions alongside the extraction.

Review context
  • Author: glorydavid03023
  • Role context: outside_contributor
  • Public audience mode: oss maintainer
  • Lane context: Repository is configured for direct PR review.
  • Public profile languages: not available
  • Official Gittensor activity: 273 PR(s), 20 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Keep the PR focused and include validation evidence before maintainer review.
Signal definitions
  • Related work = same linked issue, overlapping active PRs, or title/path similarity.
  • Change scope = cached public metadata such as size labels, draft state, and review-burden hints.
  • Validation posture = whether the PR provides enough public validation/test evidence for maintainer review.
  • Contributor workload = public contributor activity and cleanup pressure, not a repo-wide quality failure.
  • Contributor context = public GitHub/Gittensor identity context; non-Gittensor status is not a blocker.
[BETA] Chat with Gittensory

Ask Gittensory a question about this PR directly in a comment — grounded only in the same cached, public-safe facts shown above, never a new claim.

  • @gittensory ask <question> answers contribution-quality Q&A with source citations and freshness.
  • @gittensory chat <question> answers in natural prose from cached decision-pack facts via local inference (maintainer/collaborator; read-only).
  • A plain-language @gittensory mention with a real question is routed to the closest matching read-only command automatically -- no exact syntax required.

Full command reference: https://gittensory.aethereal.dev/docs/gittensory-commands

🟩 Safe / merged · 🟦 Advisory · 🟨 Held for review · 🟥 Blocked / closed


💰 Earn for open-source contributions like this. Gittensor lets GitHub contributors earn for the work they already do — register to start earning →.

Checked by LoopOver, a quiet PR intelligence layer for OSS maintainers.

  • Re-run LoopOver review

@codecov

codecov Bot commented Jul 14, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.07%. Comparing base (97c98b3) to head (def3730).
⚠️ Report is 1 commits behind head on main.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5773      +/-   ##
==========================================
- Coverage   95.07%   95.07%   -0.01%     
==========================================
  Files         582      583       +1     
  Lines       46216    46211       -5     
  Branches    14820    14820              
==========================================
- Hits        43940    43935       -5     
  Misses       1516     1516              
  Partials      760      760              
Flag Coverage Δ
shard-1 43.93% <82.60%> (-0.02%) ⬇️
shard-2 35.79% <78.26%> (+0.02%) ⬆️
shard-3 32.24% <91.30%> (-0.01%) ⬇️
shard-4 32.94% <100.00%> (+0.01%) ⬆️
shard-5 31.72% <82.60%> (-0.01%) ⬇️
shard-6 44.64% <82.60%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...es/loopover-engine/src/github/linked-references.ts 100.00% <100.00%> (ø)
...opover-engine/src/signals/predicted-gate-engine.ts 100.00% <ø> (ø)
src/db/repositories.ts 96.67% <ø> (-0.05%) ⬇️
🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@loopover-orb

loopover-orb Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Gittensory is closing this pull request on the maintainer's behalf (No linked issue detected). This is an automated maintenance action — to pursue this change, please open a new pull request with the issues resolved. Closed PRs may be analyzed later to improve review accuracy, but they are not automatically reopened or re-reviewed.

@loopover-orb loopover-orb Bot closed this Jul 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gittensor:bug Gittensor-scored bug fix — scores a 0.05x multiplier.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sweep for pure logic stranded inside I/O-bound files

1 participant