This file provides context for AI assistants working on the Citation Bot project.
- Language: PHP 8.4+
- Main logic: Template.php (very large file)
- Test command: composer run test
- CS1 regression gate (run before and after citation-logic changes):
php tools/cs1_harness.phpandphp tools/cs1_harness.php --slow - CLI smoke-test (requires credentials, use --savetofiles to avoid writing to Wikipedia): php src/process_page.php "Page" --savetofiles
- Code style: verbose, explicit, spaced-out, highly formatted style
- First task: Read src/includes/Template.php, src/includes/Parameter.php, and src/includes/constants/parameters.php
Citation Bot is a Wikipedia maintenance tool that automatically expands and formats bibliographic references. It retrieves metadata from authoritative sources (CrossRef, PubMed, arXiv, JSTOR, NASA ADS, Google Books and more) and generates properly formatted Wikipedia citation templates.
Key Facts:
- Language: PHP 8.4+
- License: GPL-3.0-or-later
- Status: Production service is active; repository is classified as stable (maintenance mode)
- Repository: https://github.com/ms609/citation-bot
- Production: https://citations.toolforge.org
- Platform: Wikimedia Toolforge (Kubernetes)
The system has three main components:
- Web Interface (
src/index.php+src/process_page.php) - Batch processes entire Wikipedia pages - Gadget API (
src/gadgetapi.php) - Real-time in-browser citation expansion during editing - Template Generator (
src/generate_template.php) - Creates a single wiki citation from an identifier
Wikipedia Page → Extract Templates → Query External APIs →
Add Missing Metadata → Clean Formatting → Post to Wikipedia
src/includes/setup.php- Bootstrap configuration and initializationsrc/includes/constants.php- Application-wide constantssrc/includes/Page.php- Page class - Manages Wikipedia page content (fetch, process, write)src/includes/Template.php- Template class - Core citation expansion logicsrc/includes/Parameter.php- Parameter class - Template parameter handlingsrc/includes/WikipediaBot.php- WikipediaBot class - Wikipedia API client with OAuthsrc/includes/Statistics.php- Statistics helpers – UCB tag parsing, aggregation, and wikitext generation forUser:Citation bot/statisticssrc/includes/GadgetApi.php- Gadget API validation and rate limiting helperssrc/includes/PublicConfig.php- Public URL/host/origin canonicalization and CORS helperssrc/includes/RequestRateLimit.php- Token-bucket rate limiting for gadget/generate-template requests, plus the big-run admission gate (big_run_try_acquire/big_run_release) that gives single requests priority over bulk runssrc/includes/request_security.php- CSRF and session security helpers for web entrypointssrc/includes/TextTools.php- String manipulation and CS1 identifier validatorssrc/includes/WikiThings.php- Wiki markup handling (nowiki, comments, etc.) — contains abstract class WikiThings + 9 concrete subclassessrc/includes/URLtools.php- URL normalization and metadata extraction (standalone functions, no class)src/includes/NameTools.php- Author name parsing and formatting (standalone functions, no class)src/includes/MathTools.php- MathML to LaTeX conversion (standalone function, no class)
Important characteristics of this codebase:
- Uses a verbose, explicit, spaced-out, highly formatted style
- Assignments within conditionals are common (to note possible side effects)
- Multi-line if/foreach/else statements (with braces)
- Method calls that modify state often occur within assignments
- Action can happen through method calls in equality checks
- String operations should use multi-byte versions except when byte counts are required, such as HTTP header lengths
Good (matches project style):
if ($doi = $template->get('doi')) {
$crossRef = query_crossref($doi);
if ($crossRef) {
$template->add_if_new('title', $crossRef->title);
}
}Avoid (too compact for this project):
if ($doi = $template->get('doi') && $crossRef = query_crossref($doi))
$template->add_if_new('title', $crossRef->title);The bot integrates with multiple external services. Sometimes these APIs will fail:
| Service | Identifier | Purpose |
|---|---|---|
| CrossRef | DOI | Journal article metadata |
| PubMed | PMID | Biomedical literature |
| PubMed Central | PMC | Open access articles |
| arXiv | arXiv ID | Scientific preprints |
| JSTOR | JSTOR ID | Scholarly articles |
| Zotero (via Citoid) | URL | Generic URL metadata extraction via Wikimedia's Citoid endpoint |
| SSRN (via Zotero) | SSRN ID | Social Science Research Network metadata |
| NASA ADS | Bibcode | Astrophysical literature via SAO/NASA ADS |
| Semantic Scholar | S2 ID / DOI | Identifier mapping and open-access status lookup |
| Google Books | ISBN / Google ID | Book metadata |
| Unpaywall | DOI | Open-access location finder |
| Fatcat (via Unpaywall) | DOI | Pre-1909 Archive.org PDF lookup via scholar.archive.org |
| ISSN (local) | ISSN | Hardcoded ISSN-to-newspaper mapping (no live API) |
| Internet Archive | URL | Archive-hosted page title retrieval (Wayback Machine, Ghostarchive) |
| PII | PII | Publisher Item Identifier to DOI conversion |
| SICI (local) | SICI | Serial Item and Contribution Identifier (local parsing, no external API) |
- Expands existing identifiers (DOI, PMID, etc.)
- Adds missing parameters
- Cleans formatting
- Excludes: bibcode searches, URL expansion
- Reason: Must complete within the 120-second configured time limit
- All fast mode operations
- Plus: Bibcode searches, Zotero URL expansion
- Takes longer but more thorough
Web processing above BIG_RUN_PAGE_THRESHOLD (4 runnable pages) is
admission-controlled. This reserves capacity; it is not a web-server scheduler
and does not reorder already-arrived FastCGI requests.
- Probe-before-I/O: category/linked entry points acquire a short-lived
phase=probelease before the first remote discovery API call. Default probe capacity is 4. Probes spend no tokens and do not consume the normal total. Once bulk discovery is proven, the same lease must atomically becomephase=discoverybefore more bulk discovery occurs. - Concurrency: default normal bulk capacity is 10; at most 4 normal leases
may be large (>=50 pages).
phase=probeis separately capped at 4. - Worker invariant: production was reported/configured with 24 web workers.
Keep the actual worker count strictly greater than
big_run_max_total() + big_run_max_discovery_probes()and leave deliberate headroom for singles/gadget/API/authentication traffic. Verify the custom worker setting after migrations or web-service recreation before relying on the reservation guarantee. - Trusted users:
DEV_USERSare token-exempt but not concurrency-exempt; testing bypasses both. CLI bypasses the web gate only under the documented resource-isolation assumption. - Discovery: category discovery stops at accepted maximum + 1; linked-page discovery is paginated. Fifth-runnable/raw-candidate/five-batch bounds remain defense in depth after the initial probe semaphore.
- Large-user lease: acquire the per-user >=50-page lease as soon as discovery
reaches 50 runnable pages, except for finitely bounded category discovery:
that defers acquisition until the oversized-category bound is ruled out, so a
category about to be cancelled never takes the lease. The persistent
_guardserializes takeover and inode ownership is authoritative. Ownership loss is terminal. A private process-ownedcitation-bot-big-jobsdirectory under/dev/shmis preferred when available; otherwise the same private directory is created undersys_get_temp_dir(). The first deployment that moves existing leases into this private subdirectory must be drained so old direct-/dev/shmleases cannot overlap new leases. - Shared state machine:
probe -> discovery -> running. Final promotion charges tokens exactly once. Probe-to-discovery promotion checks the normal total atomically. Wrong/missing phases fail closed. - Shared ownership loss:
big_run_heartbeat_status()distinguishesok, retryable infrastructure failure, andlost.lostmeans a valid snapshot no longer owns that ID; the request must stop immediately rather than continuing outside concurrency accounting. - State integrity:
big-run.lockis the permanent flock target;big-run.jsonis atomically replaced. The private state root must be a real, writable, process-owned directory; symlinked lock/state paths are rejected. Snapshots are capped at 64 KiB. Every persisted lease entry is mandatory-schema data (started_at,tier,last_seen_at,phase); any malformed entry makes the whole snapshot invalid/fail-closed. Invalid-state logs identify the failure class but must never include raw snapshot contents. - Operator recovery: never make malformed state self-heal or fail open.
tools/reset_big_run_state.php --checkdiagnoses shared state under the permanent lock.--resetis an operator-only recovery action: drain/quiesce bulk workers first, acquirebig-run.lock, preserve the previous regular snapshot as.recovery-*, and atomically install fresh empty/full-token state. The reset must refuse symlinked/non-regular state, unsafe state roots, and lock contention. Automatic corruption recovery remains forbidden. The manualsrc/reset_big_run_state.phpHTTP path is permitted only with the same 256-bitDEPLOY_TOKEN/X-Deploy-Token, one-time browser CSRF nonce, constant-time token check, method restrictions, and public-request hardening pattern used bygitpull.php; reset must remain POST-only with explicit drain/quiesce confirmation. Keepbig-run.lock; retained recovery snapshots are forensic/operator artifacts. - Liveness: common cURL hooks renew before/after transfers and from the
libcurl progress callback while
curl_exec()is active; page-loop hooks remain an additional renewal point. Shared heartbeat interval stays bounded relative to stale timeout and transient renewal failures retry promptly. Per-user large-job heartbeat/kill checks use their separate guarded lease. Do not replace the progress callback without preserving both response size enforcement and these heartbeat calls. - HTTP: deferred and lease-lost work returns 503,
Retry-After, andCache-Control: no-storewhile admission output is still replaceable. - Tuning: reviewed defaults are 10 total, 4 probes, 4 large, 400 tokens, 4.0 tokens/s. Environment overrides exist; tune against measured worker occupancy, interactive p95/p99 latency, CPU/memory pressure and deferral logs.
- Deployment: local JSON +
flock()is single-instance/shared-filesystem only. Horizontal replicas require shared transactional state. Preserve the drained migration procedure for the historical direct-json-lock -> permanent lock-inode transition. - Code: state/admission in
RequestRateLimit.php; web policy/buffering inWebTools.php; discovery inWikipediaBot.php; per-user large ownership inbig_jobs.php. - progpilot caveat:
progpilot.jsonincludes line-dependent suppressions for pre-existing rate-limit code. Keep the big-run subsystem below that block or deliberately regenerate suppressions after line-moving changes.
docker compose up -d
# Access at http://localhost:8081/src/
docker compose exec php composer installbecome citations[-dev]
webservice stop
webservice --backend=kubernetes php8.4 startphp src/process_page.php "PageName|Another Page" --slow --savetofilesRequired: Create root-level env.php from env.php.example
Must include:
- Public URL and web-request configuration:
PUBLIC_BASE_URL,ALLOWED_HOSTS,ALLOWED_ORIGINS - OAuth tokens:
PHP_OAUTH_CONSUMER_TOKEN,PHP_OAUTH_CONSUMER_SECRET,PHP_OAUTH_ACCESS_TOKEN,PHP_OAUTH_ACCESS_SECRET(required for CLI) - Web user OAuth:
PHP_WP_OAUTH_CONSUMER,PHP_WP_OAUTH_SECRET(required for web interface) - Optional:
PHP_ADSABSAPIKEY(ADS),PHP_ADSABSAPILIMITACTION(sleep|exit|ignore),PHP_S2APIKEY(Semantic Scholar),NLM_APIKEY/NLM_EMAIL(NCBI),DEPLOY_TOKEN(deployment endpoint),CITOID_RATE_LIMIT_DIR/CITOID_RATE_LIMIT_NAMESPACE_ID/CITOID_ALLOW_LOCAL_FALLBACK(fail-closed Citoid, see docs/citoid-rate-limit-locking.md),CITATION_BOT_BIG_RUN_*tuning (see env.php.example:68-79, normally leave unset)
Security:
chmod go-rwx env.phpThe project uses extensive automated testing:
- PHPUnit - Unit tests (via paratest for parallel execution)
- PHPStan (level 7) - Static analysis
- Psalm - Static analysis for coding quality
- Psalm (taint analysis) - Security-focused taint data checks
- Phan - PHP static analyzer
- PHP_CodeSniffer - Code style enforcement
- PHPLint - Basic PHP syntax check
- DesignSecurity (progpilot) - Tainted data / design security analysis
- CodeQL - Security vulnerability scanning
- Trivy - Container security scanning
- HTML5 and CSS Validator - Validates HTML/CSS files
- Config lint / misc-file validation - Validates JSON, YAML, Markdown and misc repo files (
config-lint.yml,misc-file-validation.yml) - Browser UI / Docker build - Validates web UI and container build (
browser-ui.yml,docker-build.yml) - ESLint / Python lint / Secret scan / Codespell - Lints JS/Python, scans secrets, checks spelling (
eslint.yml,python-lint.yml,secret-scan.yml,codespell.yml) - Action Lint - Validates GitHub Actions
- Shellcheck - Lints shell scripts (e.g.
tools/update_cffconvert_lock.sh) - Link Checker - Validates URLs in documentation and HTML - runs weekly
- Composer audit - Checks Composer dependencies for known vulnerabilities
- Dependabot - Automated dependency updates for Composer, GitHub Actions, and pip (cffconvert lockfile)
- Dependency Review - Checks dependency changes for known vulnerabilities
- Harden Runner - Audits GitHub Actions runner behavior
- OpenSSF Scorecard - Evaluates repository security practices
- Zizmor - Analyzes GitHub Actions workflows for security issues
- CITATION.cff validation - Validates citation metadata using a hash-pinned cffconvert closure (
.github/cffconvert-requirements.txt) - CS1 Harness - Runs
tools/cs1_harness.phpin fast + slow mode on changes tosrc/**ortools/**(.github/workflows/cs1-harness.yml), plus a weekly schedule; fails if any must-pass case would trigger a CS1 error, or if a known-gap case unexpectedly resolves (XPASS) - Citation fuzz - Runs
tools/fuzz_citations.phpoffline with networking disabled (fuzz-citations.yml); 1,000 cases per target on PRs touching parsers, 800,000 weekly onmaster - Patch artifacts - Rejects tracked
*.patch/*.orig/*.rejfiles (patch-artifacts.yml)
The CS1 harness is the conformance regression gate: it drives the bot's real expansion on a matrix of citations and flags any output that would trigger a Help:CS1 errors message or an explicitly-tracked maintenance category (e.g. CS1 maint: periodical has ISBN, which emits no error message). Run it locally (php tools/cs1_harness.php and --slow) before and after any citation-expansion change; a new fix should flip one of its documented gap cases to RESOLVED and add a matrix case.
Local PHPUnit note: phpunit.xml.dist requests coverage. Install PCOV or Xdebug before running focused PHPUnit tests directly, for example: php -d memory_limit=2G vendor/bin/phpunit <path>.
All tests must pass before merging. Some tests are network-dependent (Zotero, PubMed, Unpaywall, JSTOR) and may pass/fail with upstream API availability; distinguish upstream failures from local regressions before attributing cause.
- Create new file
API[ServiceName].php - Implement metadata retrieval function
- Add identifier extraction to
URLtools.php - Update
Template.phpexpansion logic - Add tests in
tests/ - Update documentation
- Main logic is in
Template.php - Use
Template::add_if_new($param, $value)to add parameters Template::tidy()handles cleanup and normalization- Test with real Wikipedia pages using
--savetofilesflag
- Update the relevant constants or aliases in
src/includes/constants/parameters.php - Add extraction logic in relevant
API*.phpfiles - Update
Template.phpif parameter needs special handling - Add validation rules if needed
The harness (tools/cs1_harness.php) checks expanded citations against the CS1 error rules. It has no credentials and is deterministic when upstream APIs respond normally (the matrix uses fabricated identifiers/titles that cannot match).
php tools/cs1_harness.php # fast mode
php tools/cs1_harness.php --slow # slow mode (bibcode search + URL expansion)
php tools/cs1_harness.php --list # print the matrix without running- Must-pass cases must satisfy every checker rule; a violation exits 1.
- Known-gap cases document current CS1 violations the bot leaves in place; while still a known gap they are reported but don't fail the run. A gap that stops violating prints
RESOLVEDand fails the run (XPASS), forcing it to be converted to a must-pass case or confirmed intentional. - When adding identifier validation or parameter handling, mirror the existing validators in
src/includes/TextTools.php(arxiv_id_valid,pmid_valid,pmc_valid,rxiv_id_valid,bibcode_valid,isbn_valid,doi_valid,ssrn_valid,s2cid_valid,jstor_valid,hdl_valid,oclc_valid,url_valid,archive_url_valid) and thereport_inactiongate pattern inTemplate::add_if_new. - Every new harness checker rule must cite its
Help:CS1 errorssection orModule:Citation/CS1anchor in a comment. Rules that mirror bot behavior rather than CS1 documentation do not belong in the checker: maintenance categories must be labeledCS1 maint, never quoted asCS1 "…"errors. - Every matrix case must be able to fail when the bot misbehaves: either its input contains a CS1 violation the bot must repair (
pass) or leave (gap), or it is a valid citation the bot must keep clean — so that introducing an error, corrupting a value, or dropping a load-bearing base triggers a checker rule. Cases that cannot fail under any bot behavior — parameter-routing destinations (e.g.work=→series=), placeholder handling, and journal-specific tidying preferences with no CS1 mapping — do not belong in the matrix; lock those behaviors in the relevant PHPUnit test undertests/instead.
The gadget MUST:
- Complete within the 120-second configured time limit
- Not perform slow operations (bibcode search, URL expansion)
- Handle browser timeout gracefully
- Provide useful partial results if API calls fail
- Respect rate limits
- Use OAuth authentication
- Include proper User-Agent
- Implement retry with bounded backoff and honor Retry-After headers
- Never post if page hasn't changed
/
├── src/
│ ├── index.php # Web frontend
│ ├── process_page.php # Main processor
│ ├── gadgetapi.php # Gadget endpoint
│ ├── generate_template.php # Single citation generator
│ ├── authenticate.php # OAuth authentication
│ ├── resume.php # Resume saved OAuth-gated request
│ ├── category.php # Category processing
│ ├── linked_pages.php # Processes pages linking to a given page
│ ├── kill_big_job.php # Kill large batch jobs
│ ├── gitpull.php # Password-protected deployment/update endpoint
│ ├── reset_big_run_state.php # Authenticated big-run state recovery endpoint
│ ├── update_statistics.php # Daily cron to update User:Citation bot/statistics
│ └── includes/
│ ├── setup.php # Bootstrap configuration
│ ├── constants.php # Application constants
│ ├── Page.php # Page management
│ ├── Template.php # Citation expansion core
│ ├── Parameter.php # Parameter handling
│ ├── WikipediaBot.php # Wikipedia API client
│ ├── Statistics.php # Statistics helpers for User:Citation bot/statistics
│ ├── GadgetApi.php # Gadget API validation and rate limiting helpers
│ ├── PublicConfig.php # Public URL/host/origin canonicalization and CORS helpers
│ ├── RequestRateLimit.php # Rate limiting + big-run admission gate
│ ├── request_security.php # CSRF and session security helpers
│ ├── URLtools.php # URL normalization & metadata
│ ├── NameTools.php # Author name parsing
│ ├── MathTools.php # MathML to LaTeX conversion
│ ├── WikiThings.php # Wiki markup handling
│ ├── miscTools.php # Miscellaneous utilities
│ ├── TextTools.php # String manipulation
│ ├── WebTools.php # Web helpers incl. gate_big_run()
│ ├── bot_curl.php # Curl wrapper with defaults
│ ├── user_messages.php # Bot activity reporting
│ ├── doiTools.php # DOI validation & normalization
│ ├── big_jobs.php # Large batch job handling
│ ├── api/ # External API integrations
│ │ ├── APIarchives.php # Internet Archive metadata
│ │ ├── APIarXiv.php # arXiv metadata
│ │ ├── APIBibCode.php # Bibcode metadata via NASA ADS
│ │ ├── APIdoi.php # DOI/CrossRef metadata
│ │ ├── APIfatcat.php # Fatcat pre-1909 free PDF lookup
│ │ ├── APIgoogle.php # Google Books metadata
│ │ ├── APIissn.php # ISSN metadata
│ │ ├── APIjstor.php # JSTOR metadata
│ │ ├── APIpii.php # PII to DOI conversion
│ │ ├── APIPubMed.php # PubMed/PMC metadata
│ │ ├── APIResponseGuard.php # Defensive decoding of external API responses
│ │ ├── APIS2.php # Semantic Scholar metadata
│ │ ├── APIsici.php # SICI parsing
│ │ ├── APIunpaywall.php # Unpaywall open-access lookup
│ │ └── APIzotero.php # Zotero URL metadata
│ └── constants/ # Sub-constant definitions
│ ├── bad_data.php # Incorrect data from outside sources
│ ├── capitalization.php # Title and name capitalization rules
│ ├── free_doi.php # Known open-access DOI prefixes
│ ├── isbn.php # ISBN hyphenation and formatting data
│ ├── italics.php # Italics
│ ├── math.php # MathML tag and entity definitions
│ ├── mistakes.php # Common misspellings
│ ├── null_bad_doi.php # Confirmed dead/invalid DOIs
│ ├── null_good_doi.php # DOIs falsely reported as dead
│ ├── parameters.php # Citation template and parameter maps
│ ├── regular_expressions.php # Regular expression constants
│ └── translations.php # Translations
├── tests/ # PHPUnit tests
├── .github/workflows/ # CI/CD workflows (incl. browser-ui, docker-build, eslint, python-lint, secret-scan, fuzz-citations, patch-artifacts, etc.)
├── .github/labeler.yml # PR auto-labeling (update on new/renamed files)
├── .github/actions/, .github/scripts/ # Composite actions + CI helpers
├── .github/dependabot.yml # Automated dependency update configuration
├── .github/cffconvert-requirements.txt # Hash-pinned cffconvert closure for CITATION.cff validation
├── .github/codespell-requirements.txt # Hash-pinned codespell closure for the Codespell workflow
├── tools/update_cffconvert_lock.sh # Regenerates the hash-pinned cffconvert closure
├── tools/update_codespell_lock.sh # Regenerates the hash-pinned codespell closure
├── tools/cs1_harness.php # CS1 conformance regression gate
├── tools/fuzz_citations.php # Offline citation parser fuzz harness
├── tools/reset_big_run_state.php # Operator recovery for shared big-run admission state
├── tools/cleanup-citoid-pending.php # Offline cleanup of stale Citoid pending writes
├── tools/verify-citoid-shared-flock.php # Offline cross-host flock smoke check for the Citoid mutex
├── docs/citoid-*.md # Citoid rate-limit locking and distributed deployment validation
├── vendor/ # Composer dependencies
├── composer.json # Dependency configuration
├── docker-compose.yml # Docker setup
├── Dockerfile # Container definition
├── toolforge.yaml # Toolforge Jobs definition for daily statistics
├── phpunit.xml.dist # PHPUnit configuration
├── phpstan.neon # PHPStan configuration
├── psalm.xml # Psalm configuration
├── .phpcs.xml # Code style configuration
├── progpilot.yml # Security analysis config
├── env.php.example # Configuration template
└── ...other config files
php src/process_page.php "Article_Name" --savetofiles
# Check output in Article_Name.mdCheck src/includes/setup.php for debug flags and logging configuration.
OAuth failures:
- Verify tokens in
env.php - Check token permissions on Wikipedia
- Ensure OAuth client is approved
API timeouts:
- Check network connectivity
- Verify API keys are valid
- Check API rate limits
Template not expanding:
- Verify template syntax is correct
- Check if identifier is valid
- Look for errors in logs
- Test identifier in
generate_template.php
- (Historical observation; unverified) Each external API call adds latency (100-500ms)
- Wikipedia API calls are rate-limited
- (Historical observation; unverified) Slow mode can take 30-120 seconds for large pages
- (Historical observation; unverified) Fast mode targets < 10 seconds
- Batch processing is more efficient than individual pages
- Never commit
env.phpor credentials - Validate all external API responses
- Sanitize user input before Wikipedia API calls
- Keep dependencies updated
- Review security scan results (Trivy, Psalm)
- Use OAuth, never passwords
-
Fork the repository
-
Create a feature branch
-
Write tests for new functionality
-
Ensure all CI checks pass
-
Follow existing code style
-
Update documentation
-
Always check whether
.github/labeler.ymlneeds a new entry when adding or renaming files (especially new tooling, workflows, or entrypoints); the automatic PR labeling depends on it -
Submit pull request with clear description
-
Common Pitfalls:
- Forgetting multi-byte string functions
- Not handling API failures gracefully
- Violating the verbose code style with compact one-liners
- Entry points that use
src/includes/user_messages.phpwithout loadingsetup.php(e.g.src/kill_big_job.php) must define theCIandHTML_OUTPUTconstants themselves: output helpers insrc/includes/user_messages.phpreadHTML_OUTPUTunguarded, and an undefined constant fatals mid-page, truncating the output to a blank page. Note that tests extendingtestBaseClass.phploadsetup.phpand will mask this failure — use the standalone separate-process pattern intests/phpunit/killBigJobPageTest.phpwhen testing such pages.
Primary channel: https://en.wikipedia.org/wiki/User_talk:Citation_bot
Include:
- Page name or URL
- Expected behavior
- Actual behavior
- Error messages (if any)
- Screenshot (if applicable)
# Run the full test suite
composer run test
# Focused PHPUnit run (requires PCOV or Xdebug because phpunit.xml.dist requests coverage)
php -d memory_limit=2G vendor/bin/phpunit <path>
# CS1 conformance regression gate (fast + slow)
php tools/cs1_harness.php
php tools/cs1_harness.php --slow
# Static analysis
php vendor/bin/phpstan analyze
php vendor/bin/psalm
# Code style check
php vendor/bin/phpcs
# Process single page locally
php src/process_page.php "Wikipedia:Sandbox" --savetofiles
# Update statistics page (dry-run)
php src/update_statistics.php --dry-run
# Update dependencies
composer updateThe bot recognizes many CS1/CS2 citation templates and processes them at different levels of depth. See src/includes/constants/parameters.php for the authoritative lists of fully, slightly, and barely processed templates. Examples include:
{{cite journal}}- Academic journals{{cite book}}- Books{{cite web}}- Websites{{cite news}}- News articles{{citation}}- Any reference- And many more...
| Parameter | Description |
|---|---|
title |
Article/book title |
author, last, first |
Author names |
journal |
Journal name |
volume, issue |
Journal volume/issue |
pages, page |
Page numbers |
date, year |
Publication date |
doi |
Digital Object Identifier |
pmid |
PubMed ID |
pmc |
PubMed Central ID |
arxiv, eprint |
arXiv identifier |
ssrn |
SSRN identifier (Social Science Research Network) |
isbn |
Book identifier |
url |
Web URL |
access-date |
Date URL accessed |
- Status: Production service active; repository classified as stable (maintenance mode)
- Maintenance: Provided as time allows
- Community: Open source contributions welcome
- Response time: May vary due to volunteer nature
- Documentation: https://en.wikipedia.org/wiki/User:Citation_bot/use
- Bug reports: https://en.wikipedia.org/wiki/User_talk:Citation_bot
- Source code: https://github.com/ms609/citation-bot
When helping with this project:
- Remember: Avoid dense compound conditionals; assignments in clearly separated conditions are common in this codebase
- Test: For behavior that depends on real wikitext or APIs, additionally smoke-test a representative page with
--savetofiles; never rely on this instead of the automated suite - Security: Never expose OAuth tokens or API keys
- Performance: Consider gadget timeout constraints
- Standards: Follow existing patterns in the codebase.
- Testing: Run full test suite before submitting changes
- Documentation: Update relevant docs with any changes
- See also: docs/CONTRIBUTING.md for detailed contribution guidelines
- API Stability: Keep the external API stable - code on Wikipedia relies on this API, and that code is not part of this codebase
- No stubs: Do not implement placeholders or simple implementations. We want full implementations
- Code reuse: Never assume something is not implemented - search the code base first
- Code consistency: Before changing behavior, identify the existing pattern elsewhere in the repository and follow it. Do not modernize existing code unless requested. Avoid unnecessary refactoring.
- Do not touch vendor/, hash-pinned lockfiles (use the tools/update_*_lock.sh scripts), attic/, and progpilot*.json.
The bot runs on Wikimedia Toolforge, which has excellent PHP support and infrastructure for Wikipedia bots.
The project prioritizes readability and maintainability over compactness. With 15,000+ commits and multiple contributors over many years, explicit code is easier to debug and modify safely.
The bot has reached a stable, feature-complete state. It reliably processes Wikipedia pages daily. New features are welcome but the focus is on stability and bug fixes.