Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Redesign scientific writing safeguards
Timothy Kassis3441b926edcf
diff --git a/skills/scientific-writing/SKILL.md b/skills/scientific-writing/SKILL.mdindex 58ea4613..b5250365 100644--- a/skills/scientific-writing/SKILL.md+++ b/skills/scientific-writing/SKILL.md@@ -1,717 +1,356 @@---name: scientific-writing-description: Core skill for the deep research and writing tool. Write scientific manuscripts in full paragraphs (never bullet points). Use two-stage process with (1) section outlines with key points using research-lookup then (2) convert to flowing prose. IMRAD structure, citations (APA/AMA/Vancouver), figures/tables, reporting guidelines (CONSORT/STROBE/PRISMA), for research papers and journal submissions.-allowed-tools: Read Write Edit Bash-license: MIT license-required_environment_variables: [{"name": "OPENROUTER_API_KEY", "prompt": "OpenRouter API key for the skill's LLM-powered steps.", "required_for": "optional features"}]-metadata: {"version": "1.2", "skill-author": "K-Dense Inc.", "openclaw": {"primaryEnv": "OPENROUTER_API_KEY", "envVars": [{"name": "OPENROUTER_API_KEY", "required": false, "description": "OpenRouter API key for the skill's LLM-powered steps."}]}}+description: Draft, revise, and audit scientific manuscripts or reports with explicit evidence provenance, reporting-guideline coverage, authorship accountability, confidentiality controls, and local consistency checks. Use for manuscript sections, references, declarations, tables, figures, or submission preparation when scientific accuracy and traceability matter.+license: MIT+compatibility: Requires Python 3.11+ only for optional dependency-free local CLIs; core guidance is platform-neutral. Bundled tools are offline and require no API keys.+metadata:+ version: "2.0"+ skill-author: K-Dense Inc.---# Scientific Writing-## Overview+## Purpose-**This is the core skill for the deep research and writing tool**—combining AI-driven deep research with well-formatted written outputs. Every document produced is backed by comprehensive literature search and verified citations through the research-lookup skill.+Produce clear scientific prose without inventing evidence or concealing uncertainty.+Keep drafting, evidence verification, and submission approval as separate stages.-Scientific writing is a process for communicating research with precision and clarity. Write manuscripts using IMRAD structure, citations (APA/AMA/Vancouver), figures/tables, and reporting guidelines (CONSORT/STROBE/PRISMA). Apply this skill for research papers and journal submissions.+The accountable human authors control scientific decisions and final approval. AI is+not an author, and generated fluency is never evidence [SW-S01, SW-S03].-**Critical Principle: Always write in full paragraphs with flowing prose. Never submit bullet points in the final manuscript.** Use a two-stage process: first create section outlines with key points using research-lookup, then convert those outlines into complete paragraphs.+## Non-negotiable safety rules-## When to Use This Skill+### Confidentiality-This skill should be used when:-- Writing or revising any section of a scientific manuscript (abstract, introduction, methods, results, discussion)-- Structuring a research paper using IMRAD or other standard formats-- Formatting citations and references in specific styles (APA, AMA, Vancouver, Chicago, IEEE)-- Creating, formatting, or improving figures, tables, and data visualizations-- Applying study-specific reporting guidelines (CONSORT for trials, STROBE for observational studies, PRISMA for reviews)-- Drafting abstracts that meet journal requirements (structured or unstructured)-- Preparing manuscripts for submission to specific journals-- Improving writing clarity, conciseness, and precision-- Ensuring proper use of field-specific terminology and nomenclature-- Addressing reviewer comments and revising manuscripts+Do not send unpublished manuscripts, peer-review or editorial material, sensitive or+restricted data, PHI or other personal data, proprietary content, or source documents+to an external service without:-## Visual Enhancement with Scientific Schematics+1. explicit authorization from a person or body empowered to grant it; and+2. a documented review of journal, institutional, funder, consent, ethics, contractual,+ legal, and data-use policy.-**⚠️ MANDATORY: Every scientific paper MUST include a graphical abstract plus 1-2 additional AI-generated figures using the scientific-schematics skill.**+When authorization or policy is unclear, keep processing local and use only the minimum+metadata needed. De-identification requires expert review; removing obvious names is+not sufficient. See `references/authorship_ai_confidentiality.md`.-This is not optional. Scientific papers without visual elements are incomplete. Before finalizing any document:-1. **ALWAYS generate a graphical abstract** as the first visual element-2. Generate at minimum ONE additional schematic or diagram using scientific-schematics-3. Prefer 3-4 total figures for comprehensive papers (graphical abstract + methods flowchart + results visualization + conceptual diagram)+### No fabrication-### Graphical Abstract (REQUIRED)+Never invent or complete:-**Every scientific writeup MUST include a graphical abstract.** This is a visual summary of your paper that:-- Appears before or immediately after the text abstract-- Captures the entire paper's key message in one image-- Is suitable for journal table of contents display-- Uses landscape orientation (typically 1200x600px)+- citations, references, DOI, PMID, PMCID, ISBN, URLs, or quotations;+- results, data values, denominators, sample sizes, units, effect estimates,+ uncertainty, statistical tests, or significance claims;+- methods, materials, protocol details, software versions, analysis choices, or+ deviations;+- registrations, approvals, consent, ethics statements, participant details, or dates;+- authors, author order, CRediT roles, acknowledgments, or permissions;+- funding, sponsor roles, conflicts, data or code availability, or AI disclosures.-**Generate the graphical abstract FIRST:**-```bash-python scripts/generate_schematic.py "Graphical abstract for [paper title]: [brief description showing workflow from input → methods → key findings → conclusions]" -o figures/graphical_abstract.png-```+Use an explicit missing, unverified, or not-applicable state. Do not substitute plausible+boilerplate.++### Evidence binding++Every factual or numeric manuscript claim must map to verified evidence IDs. A human+verifier must open the source, confirm the proposition and locator, verify bibliographic+metadata, and record who verified it and when.++Search snippets, generated summaries, memory, and another work's bibliography may aid+discovery but do not verify a claim. See `references/evidence_workflow.md`.-**Graphical Abstract Requirements:**-- **Content**: Visual summary showing workflow, key methods, main findings, and conclusions-- **Style**: Clean, professional, suitable for journal TOC-- **Elements**: Include 3-5 key steps/concepts with connecting arrows or flow-- **Text**: Minimal labels, large readable fonts-- Log: `[HH:MM:SS] GENERATED: Graphical abstract for paper summary`+### Scientific fidelity-### Additional Figures (GENERATE EXTENSIVELY)+- Preserve uncertainty and alternative explanations.+- Distinguish confirmatory, exploratory, descriptive, and post hoc work.+- Keep methods and results consistent.+- Reconcile units, denominators, sample sizes, populations, time points, and labels.+- Report negative, null, adverse, unexpected, failed, and inconclusive findings when+ they belong to the study record.+- State concrete limitations and bound generalizability.+- Do not convert association into causation or non-significance into equivalence.-**⚠️ CRITICAL: Use BOTH scientific-schematics AND generate-image EXTENSIVELY throughout all documents.**+## Intake-Every document should be richly illustrated. Generate figures liberally - when in doubt, add a visual.+Before drafting, obtain or mark unresolved:-**MINIMUM Figure Requirements:**+- document type, study design, stage, audience, and target venue;+- current author instructions and policy access date;+- protocol, registration, analysis plan, amendments, and reporting guideline;+- manuscript or section scope;+- verified source manifest and claim registry;+- methods, results, tables, figures, and supplements;+- authorship, CRediT, declarations, and approval records;+- confidentiality classification and authorized processing boundary;+- data, code, materials, and repository constraints.-| Document Type | Minimum | Recommended |-|--------------|---------|-------------|-| Research Papers | 5 | 6-8 |-| Literature Reviews | 4 | 5-7 |-| Market Research | 20 | 25-30 |-| Presentations | 1/slide | 1-2/slide |-| Posters | 6 | 8-10 |-| Grants | 4 | 5-7 |-| Clinical Reports | 3 | 4-6 |+Do not ask for restricted source material if metadata or a local user-run audit is+sufficient.++## Workflow++### 1. Establish the local workspace++For a new draft, optionally generate fail-closed Markdown, JSON, and CSV scaffolds:-**Use scientific-schematics EXTENSIVELY for technical diagrams:**```bash-python scripts/generate_schematic.py "your diagram description" -o figures/output.png+python3 scripts/scaffold_manuscript.py \+ --output-dir ./draft-workspace \+ --document-id local-draft \+ --study-design randomized_trial \+ --guideline consort-2025```-- Study design and methodology flowcharts (CONSORT, PRISMA, STROBE)-- Conceptual framework diagrams-- Experimental workflow illustrations-- Data analysis pipeline diagrams-- Biological pathway or mechanism diagrams-- System architecture visualizations-- Neural network architectures-- Decision trees, algorithm flowcharts-- Comparison matrices, timeline diagrams-- Any technical concept that benefits from schematic visualization--**Use generate-image EXTENSIVELY for visual content:**+The generator never overwrites files. Its output is explicitly not submission-ready and+contains placeholders that the linter rejects.++### 2. Select reporting guidance++Choose by actual design and article type, then open the current official statement,+checklist, explanation document, extensions, and target-journal instructions.+```bash-python scripts/generate_image.py "your image description" -o figures/output.png+python3 scripts/select_reporting_guidelines.py select \+ --study-design randomized_trial```-- Photorealistic illustrations of concepts-- Medical/anatomical illustrations-- Environmental/ecological scenes-- Equipment and lab setup visualizations-- Artistic visualizations, infographics-- Cover images, header graphics-- Product mockups, prototype visualizations-- Any visual that enhances understanding or engagement--The AI will automatically:-- Create publication-quality images with proper formatting-- Review and refine through multiple iterations-- Ensure accessibility (colorblind-friendly, high contrast)-- Save outputs in the figures/ directory--**When in Doubt, Generate a Figure:**-- Complex concept → generate a schematic-- Data discussion → generate a visualization-- Process description → generate a flowchart-- Comparison → generate a comparison diagram-- Reader benefit → generate a visual--For detailed guidance, refer to the scientific-schematics and generate-image skill documentation.+Current major routes researched on 2026-07-24 include CONSORT 2025, SPIRIT 2025,+PRISMA 2020, STROBE, STARD and STARD-AI, TRIPOD+AI, CARE, ARRIVE 2.0, SQUIRE 2.0,+and CHEERS 2022 [SW-S06–SW-S18].----+The selector is non-scoring. It does not certify quality, compliance, completeness, or+acceptance. See `references/reporting_guidelines.md`.-## Core Capabilities--### 1. Manuscript Structure and Organization--**IMRAD Format**: Guide papers through the standard Introduction, Methods, Results, And Discussion structure used across most scientific disciplines. This includes:-- **Introduction**: Establish research context, identify gaps, state objectives-- **Methods**: Detail study design, populations, procedures, and analysis approaches-- **Results**: Present findings objectively without interpretation-- **Discussion**: Interpret results, acknowledge limitations, propose future directions--For detailed guidance on IMRAD structure, refer to `references/imrad_structure.md`.--**Alternative Structures**: Support discipline-specific formats including:-- Review articles (narrative, systematic, scoping)-- Case reports and case series-- Meta-analyses and pooled analyses-- Theoretical/modeling papers-- Methods papers and protocols--### 2. Section-Specific Writing Guidance--**Abstract Composition**: Craft concise, standalone summaries (100-250 words) that capture the paper's purpose, methods, results, and conclusions. Support both structured abstracts (with labeled sections) and unstructured single-paragraph formats.--**Introduction Development**: Build compelling introductions that:-- Establish the research problem's importance-- Review relevant literature systematically-- Identify knowledge gaps or controversies-- State clear research questions or hypotheses-- Explain the study's novelty and significance--**Methods Documentation**: Ensure reproducibility through:-- Detailed participant/sample descriptions-- Clear procedural documentation-- Statistical methods with justification-- Equipment and materials specifications-- Ethical approval and consent statements--**Results Presentation**: Present findings with:-- Logical flow from primary to secondary outcomes-- Integration with figures and tables-- Statistical significance with effect sizes-- Objective reporting without interpretation--**Discussion Construction**: Synthesize findings by:-- Relating results to research questions-- Comparing with existing literature-- Acknowledging limitations honestly-- Proposing mechanistic explanations-- Suggesting practical implications and future research--### 3. Citation and Reference Management--Apply citation styles correctly across disciplines. For comprehensive style guides, refer to `references/citation_styles.md`.--**Major Citation Styles:**-- **AMA (American Medical Association)**: Numbered superscript citations, common in medicine-- **Vancouver**: Numbered citations in square brackets, biomedical standard-- **APA (American Psychological Association)**: Author-date in-text citations, common in social sciences-- **Chicago**: Notes-bibliography or author-date, humanities and sciences-- **IEEE**: Numbered square brackets, engineering and computer science--**Best Practices:**-- Cite primary sources when possible-- Include recent literature (last 5-10 years for active fields)-- Balance citation distribution across introduction and discussion-- Verify all citations against original sources-- Use reference management software (Zotero, Mendeley, EndNote)--### 4. Figures and Tables--Create effective data visualizations that enhance comprehension. For detailed best practices, refer to `references/figures_tables.md`.--**When to Use Tables vs. Figures:**-- **Tables**: Precise numerical data, complex datasets, multiple variables requiring exact values-- **Figures**: Trends, patterns, relationships, comparisons best understood visually--**Design Principles:**-- Make each table/figure self-explanatory with complete captions-- Use consistent formatting and terminology across all display items-- Label all axes, columns, and rows with units-- Include sample sizes (n) and statistical annotations-- Follow the "one table/figure per 1000 words" guideline-- Avoid duplicating information between text, tables, and figures--**Common Figure Types:**-- Bar graphs: Comparing discrete categories-- Line graphs: Showing trends over time-- Scatterplots: Displaying correlations-- Box plots: Showing distributions and outliers-- Heatmaps: Visualizing matrices and patterns--### 5. Reporting Guidelines by Study Type--Ensure completeness and transparency by following established reporting standards. For comprehensive guideline details, refer to `references/reporting_guidelines.md`.--**Key Guidelines:**-- **CONSORT**: Randomized controlled trials-- **STROBE**: Observational studies (cohort, case-control, cross-sectional)-- **PRISMA**: Systematic reviews and meta-analyses-- **STARD**: Diagnostic accuracy studies-- **TRIPOD**: Prediction model studies-- **ARRIVE**: Animal research-- **CARE**: Case reports-- **SQUIRE**: Quality improvement studies-- **SPIRIT**: Study protocols for clinical trials-- **CHEERS**: Economic evaluations--Each guideline provides checklists ensuring all critical methodological elements are reported.--### 6. Writing Principles and Style--Apply fundamental scientific writing principles. For detailed guidance, refer to `references/writing_principles.md`.--**Clarity**:-- Use precise, unambiguous language-- Define technical terms and abbreviations at first use-- Maintain logical flow within and between paragraphs-- Use active voice when appropriate for clarity--**Conciseness**:-- Eliminate redundant words and phrases-- Favor shorter sentences (15-20 words average)-- Remove unnecessary qualifiers-- Respect word limits strictly--**Accuracy**:-- Report exact values with appropriate precision-- Use consistent terminology throughout-- Distinguish between observations and interpretations-- Acknowledge uncertainty appropriately--**Objectivity**:-- Present results without bias-- Avoid overstating findings or implications-- Acknowledge conflicting evidence-- Maintain professional, neutral tone--### 7. Writing Process: From Outline to Full Paragraphs--**CRITICAL: Always write in full paragraphs, never submit bullet points in scientific papers.**--Scientific papers must be written in complete, flowing prose. Use this two-stage approach for effective writing:--**Stage 1: Create Section Outlines with Key Points**--When starting a new section:-1. Use the research-lookup skill to gather relevant literature and data-2. Create a structured outline with bullet points marking:- - Main arguments or findings to present- - Key studies to cite- - Data points and statistics to include- - Logical flow and organization-3. These bullet points serve as scaffolding—they are NOT the final manuscript--**Example outline (Introduction section):**-```-- Background: AI in drug discovery gaining traction- * Cite recent reviews (Smith 2023, Jones 2024)- * Traditional methods are slow and expensive-- Gap: Limited application to rare diseases- * Only 2 prior studies (Lee 2022, Chen 2023)- * Small datasets remain a challenge-- Our approach: Transfer learning from common diseases- * Novel architecture combining X and Y-- Study objectives: Validate on 3 rare disease datasets+### 3. Build the evidence record++Assign:++- `E` IDs to sources in `source_manifest.json`;+- `C` IDs to claims in `claims.csv`;+- `N`, `M`, `O`, and `R` IDs to numeric facts, methods, outcomes, and results in+ `consistency_manifest.json`.++Store a hash of claim text in CSV rather than raw claim text. During drafting, append:++```text+[claim:C001] [evidence:E001,E002]```-**Stage 2: Convert Key Points to Full Paragraphs**+Do not mark a source verified until an accountable human has opened it and confirmed+the exact support.-Once the outline is complete, expand each bullet point into proper prose:+### 4. Create an evidence outline-1. **Transform bullet points into complete sentences** with subjects, verbs, and objects-2. **Add transitions** between sentences and ideas (however, moreover, in contrast, subsequently)-3. **Integrate citations naturally** within sentences, not as lists-4. **Expand with context and explanation** that bullet points omit-5. **Ensure logical flow** from one sentence to the next within each paragraph-6. **Vary sentence structure** to maintain reader engagement+Outline only from recorded evidence:-**Example conversion to prose:**+- objective or question;+- section purpose;+- claim IDs and evidence IDs;+- methods and result IDs;+- analysis intent and uncertainty;+- unresolved conflicts or missing information;+- applicable reporting topics.+Keep unsupported content in an unresolved-issues list, not manuscript prose.++### 5. Draft without adding facts++Transform the verified outline into venue-appropriate prose. Preserve all IDs during+drafting.++- Match title and abstract to the completed main text.+- Describe methods as performed.+- Present results in the declared order and analysis population.+- Separate result from interpretation unless the venue combines them.+- Compare with prior evidence only after verifying it.+- Keep conclusions within the observed design, population, and uncertainty.++Use IMRAD only when appropriate. Structured abstracts, lists, combined sections, and+alternative structures depend on study design and venue. See+`references/imrad_structure.md` and `references/writing_principles.md`.++### 6. Reconcile methods and results++Record repeated numeric facts and method-result mappings, then run:++```bash+python3 scripts/check_consistency.py consistency_manifest.json```-Artificial intelligence approaches have gained significant traction in drug discovery-pipelines over the past decade (Smith, 2023; Jones, 2024). While these computational-methods show promise for accelerating the identification of therapeutic candidates,-traditional experimental approaches remain slow and resource-intensive, often requiring-years of laboratory work and substantial financial investment. However, the application-of AI to rare diseases has been limited, with only two prior studies demonstrating-proof-of-concept results (Lee, 2022; Chen, 2023). The primary obstacle has been the-scarcity of training data for conditions affecting small patient populations.--To address this challenge, we developed a transfer learning approach that leverages-knowledge from well-characterized common diseases to predict therapeutic targets for-rare conditions. Our novel neural architecture combines convolutional layers for-molecular feature extraction with attention mechanisms for protein-ligand interaction-modeling. The objective of this study was to validate our approach across three-independent rare disease datasets, assessing both predictive accuracy and biological-interpretability of the results.-```-**Key Differences Between Outlines and Final Text:**--| Outline (Planning Stage) | Final Manuscript |-|--------------------------|------------------|-| Bullet points and fragments | Complete sentences and paragraphs |-| Telegraphic notes | Full explanations with context |-| List of citations | Citations integrated into prose |-| Abbreviated ideas | Developed arguments with transitions |-| For your eyes only | For publication and peer review |--**Common Mistakes to Avoid:**--- ❌ **Never** leave bullet points in the final manuscript-- ❌ **Never** submit lists where paragraphs should be-- ❌ **Don't** use numbered or bulleted lists in Results or Discussion sections (except for specific cases like study hypotheses or inclusion criteria)-- ❌ **Don't** write sentence fragments or incomplete thoughts-- ✅ **Do** use occasional lists only in Methods (e.g., inclusion/exclusion criteria, materials lists)-- ✅ **Do** ensure every section flows as connected prose-- ✅ **Do** read paragraphs aloud to check for natural flow--**When Lists ARE Acceptable (Limited Cases):**--Lists may appear in scientific papers only in specific contexts:-- **Methods**: Inclusion/exclusion criteria, materials and reagents, participant characteristics-- **Supplementary Materials**: Extended protocols, equipment lists, detailed parameters-- **Never in**: Abstract, Introduction, Results, Discussion, Conclusions--**Abstract Format Rule:**-- ❌ **NEVER** use labeled sections (Background:, Methods:, Results:, Conclusions:)-- ✅ **ALWAYS** write as flowing paragraph(s) with natural transitions-- Exception: Only use structured format if journal explicitly requires it in author guidelines--**Integration with Research Lookup:**--The research-lookup skill is essential for Stage 1 (creating outlines):-1. Search for relevant papers using research-lookup-2. Extract key findings, methods, and data-3. Organize findings as bullet points in your outline-4. Then convert the outline to full paragraphs in Stage 2--This two-stage process ensures you:-- Gather and organize information systematically-- Create logical structure before writing-- Produce polished, publication-ready prose-- Maintain focus on the narrative flow--### 8. Professional Report Formatting (Non-Journal Documents)--For research reports, technical reports, white papers, and other professional documents that are NOT journal manuscripts, use the `scientific_report.sty` LaTeX style package for a polished, professional appearance.--**When to Use Professional Report Formatting:**-- Research reports and technical reports-- White papers and policy briefs-- Grant reports and progress reports-- Industry reports and technical documentation-- Internal research summaries-- Feasibility studies and project deliverables--**When NOT to Use (Use Venue-Specific Formatting Instead):**-- Journal manuscripts → Use `venue-templates` skill-- Conference papers → Use `venue-templates` skill-- Academic theses → Use institutional templates--**The `scientific_report.sty` Style Package Provides:**--| Feature | Description |-|---------|-------------|-| Typography | Helvetica font family for modern, professional appearance |-| Color Scheme | Professional blues, greens, and accent colors |-| Box Environments | Colored boxes for key findings, methods, recommendations, limitations |-| Tables | Alternating row colors, professional headers |-| Figures | Consistent caption formatting |-| Scientific Commands | Shortcuts for p-values, effect sizes, confidence intervals |--**Box Environments for Content Organization:**--```latex-% Key findings (blue) - for major discoveries-\begin{keyfindings}[Title]-Content with key findings and statistics.-\end{keyfindings}--% Methodology (green) - for methods highlights-\begin{methodology}[Study Design]-Description of methods and procedures.-\end{methodology}--% Recommendations (purple) - for action items-\begin{recommendations}[Clinical Implications]-\begin{enumerate}- \item Specific recommendation 1- \item Specific recommendation 2-\end{enumerate}-\end{recommendations}--% Limitations (orange) - for caveats and cautions-\begin{limitations}[Study Limitations]-Description of limitations and their implications.-\end{limitations}+Resolve every mismatch manually. A changed value may be a legitimate analysis-set+difference, but that difference must be named rather than silently normalized.++### 7. Verify citations and claims++```bash+python3 scripts/validate_manifest.py source_manifest.json \+ --kind source --require-verified+python3 scripts/audit_claims.py manuscript.md claims.csv source_manifest.json+python3 scripts/check_references.py source_manifest.json```-**Professional Table Formatting:**--```latex-\begin{table}[htbp]-\centering-\caption{Results Summary}-\begin{tabular}{@{}lccc@{}}-\toprule-\textbf{Variable} & \textbf{Treatment} & \textbf{Control} & \textbf{p} \\-\midrule-Outcome 1 & \meansd{42.5}{8.3} & \meansd{35.2}{7.9} & <.001\sigthree \\-\rowcolor{tablealt} Outcome 2 & \meansd{3.8}{1.2} & \meansd{3.1}{1.1} & .012\sigone \\-Outcome 3 & \meansd{18.2}{4.5} & \meansd{17.8}{4.2} & .58\signs \\-\bottomrule-\end{tabular}--{\small \siglegend}-\end{table}+The reference checker validates syntax and duplicate identifiers without network+resolution. A human must still compare every identifier and quotation with the opened+source. Follow NLM *Citing Medicine* or the current official style required by the+venue [SW-S20, SW-S21].++### 8. Validate authorship and disclosure++Use journal criteria for authorship. Record the standardized CRediT roles as+contribution metadata; CRediT does not itself define authorship [SW-S19].++If AI was used, humans must verify all affected content and disclose the tool and+purpose according to current journal and publisher policy. ICMJE's January 2026+Recommendations require transparency and retain human accountability [SW-S01, SW-S02].++```bash+python3 scripts/validate_authorship.py authorship.json```-**Scientific Notation Commands:**--| Command | Output | Purpose |-|---------|--------|---------|-| `\pvalue{0.023}` | *p* = 0.023 | P-values |-| `\psig{< 0.001}` | ***p* = < 0.001** | Significant p-values (bold) |-| `\CI{0.45}{0.72}` | 95% CI [0.45, 0.72] | Confidence intervals |-| `\effectsize{d}{0.75}` | d = 0.75 | Effect sizes |-| `\samplesize{250}` | *n* = 250 | Sample sizes |-| `\meansd{42.5}{8.3}` | 42.5 ± 8.3 | Mean with SD |-| `\sigone`, `\sigtwo`, `\sigthree` | *, **, *** | Significance stars |--**Getting Started:**--```latex-\documentclass[11pt,letterpaper]{report}-\usepackage{scientific_report}--\begin{document}-\makereporttitle- {Report Title}- {Subtitle}- {Author Name}- {Institution}- {Date}--% Your content with professional formatting-\end{document}+Do not generate a disclosure from assumptions. See+`references/authorship_ai_confidentiality.md`.++### 9. Review declarations and open-science statements++Verify each statement independently:++- ethics and consent;+- registration and protocol;+- funding and sponsor role;+- conflicts and relationships;+- author contributions and acknowledgments;+- data, code, materials, and protocol availability;+- AI use.++Be as open as rights and responsibilities permit, but do not expose confidential,+personal, proprietary, licensed, or protected information. Record actual access+conditions. See `references/research_integrity_open_science.md`.++### 10. Use figures and tables only when warranted++Figures and tables are optional and provenance-bound. This skill does not generate+images or schematics.++For every retained display:++- link source data, code, transformations, and evidence IDs;+- reconcile values with prose and registries;+- document image processing, permissions, and licenses;+- include units, denominators, sample sizes, uncertainty, and analysis population;+- provide alt text and redundant non-color cues;+- perform a manual accessibility and scientific check at final size.++See `references/figures_tables.md`.++### 11. Record non-scoring guideline coverage++Record each bundled high-level topic as addressed, not applicable with rationale, or+missing:++```bash+python3 scripts/select_reporting_guidelines.py check reporting_coverage.json```-**Compilation**: Use XeLaTeX or LuaLaTeX for proper Helvetica font rendering:+Then complete the official checklist using actual manuscript locations. Never claim+adherence merely because the local coverage file passes.++### 12. Lint and approve+```bash-xelatex report.tex+python3 scripts/validate_manifest.py manuscript_manifest.json --kind manuscript+python3 scripts/lint_manuscript.py manuscript.md \+ --manifest manuscript_manifest.json```-For complete documentation, refer to:-- `assets/scientific_report.sty`: The style package-- `assets/scientific_report_template.tex`: Complete template example-- `assets/REPORT_FORMATTING_GUIDE.md`: Quick reference guide-- `references/professional_report_formatting.md`: Comprehensive formatting guide--### 9. Journal-Specific Formatting--Adapt manuscripts to journal requirements:-- Follow author guidelines for structure, length, and format-- Apply journal-specific citation styles-- Meet figure/table specifications (resolution, file formats, dimensions)-- Include required statements (funding, conflicts of interest, data availability, ethical approval)-- Adhere to word limits for each section-- Format according to template requirements when provided--### 10. Field-Specific Language and Terminology--Adapt language, terminology, and conventions to match the specific scientific discipline. Each field has established vocabulary, preferred phrasings, and domain-specific conventions that signal expertise and ensure clarity for the target audience.--**Identify Field-Specific Linguistic Conventions:**-- Review terminology used in recent high-impact papers in the target journal-- Note field-specific abbreviations, units, and notation systems-- Identify preferred terms (e.g., "participants" vs. "subjects," "compound" vs. "drug," "specimens" vs. "samples")-- Observe how methods, organisms, or techniques are typically described--**Biomedical and Clinical Sciences:**-- Use precise anatomical and clinical terminology (e.g., "myocardial infarction" not "heart attack" in formal writing)-- Follow standardized disease nomenclature (ICD, DSM, SNOMED-CT)-- Specify drug names using generic names first, brand names in parentheses if needed-- Use "patients" for clinical studies, "participants" for community-based research-- Follow Human Genome Variation Society (HGVS) nomenclature for genetic variants-- Report lab values with standard units (SI units in most international journals)--**Molecular Biology and Genetics:**-- Use italics for gene symbols (e.g., *TP53*), regular font for proteins (e.g., p53)-- Follow species-specific gene nomenclature (uppercase for human: *BRCA1*; sentence case for mouse: *Brca1*)-- Specify organism names in full at first mention, then use accepted abbreviations (e.g., *Escherichia coli*, then *E. coli*)-- Use standard genetic notation (e.g., +/+, +/-, -/- for genotypes)-- Employ established terminology for molecular techniques (e.g., "quantitative PCR" or "qPCR," not "real-time PCR")--**Chemistry and Pharmaceutical Sciences:**-- Follow IUPAC nomenclature for chemical compounds-- Use systematic names for novel compounds, common names for well-known substances-- Specify chemical structures using standard notation (e.g., SMILES, InChI for databases)-- Report concentrations with appropriate units (mM, μM, nM, or % w/v, v/v)-- Describe synthesis routes using accepted reaction nomenclature-- Use terms like "bioavailability," "pharmacokinetics," "IC50" consistently with field definitions--**Ecology and Environmental Sciences:**-- Use binomial nomenclature for species (italicized: *Homo sapiens*)-- Specify taxonomic authorities at first species mention when relevant-- Employ standardized habitat and ecosystem classifications-- Use consistent terminology for ecological metrics (e.g., "species richness," "Shannon diversity index")-- Describe sampling methods with field-standard terms (e.g., "transect," "quadrat," "mark-recapture")--**Physics and Engineering:**-- Follow SI units consistently unless field conventions dictate otherwise-- Use standard notation for physical quantities (scalars vs. vectors, tensors)-- Employ established terminology for phenomena (e.g., "quantum entanglement," "laminar flow")-- Specify equipment with model numbers and manufacturers when relevant-- Use mathematical notation consistent with field standards (e.g., ℏ for reduced Planck constant)--**Neuroscience:**-- Use standardized brain region nomenclature (e.g., refer to atlases like Allen Brain Atlas)-- Specify coordinates for brain regions using established stereotaxic systems-- Follow conventions for neural terminology (e.g., "action potential" not "spike" in formal writing)-- Use "neural activity," "neuronal firing," "brain activation" appropriately based on measurement method-- Describe recording techniques with proper specificity (e.g., "whole-cell patch clamp," "extracellular recording")--**Social and Behavioral Sciences:**-- Use person-first language when appropriate (e.g., "people with schizophrenia" not "schizophrenics")-- Employ standardized psychological constructs and validated assessment names-- Follow APA guidelines for reducing bias in language-- Specify theoretical frameworks using established terminology-- Use "participants" rather than "subjects" for human research--**General Principles:**--**Match Audience Expertise:**-- For specialized journals: Use field-specific terminology freely, define only highly specialized or novel terms-- For broad-impact journals (e.g., *Nature*, *Science*): Define more technical terms, provide context for specialized concepts-- For interdisciplinary audiences: Balance precision with accessibility, define terms at first use--**Define Technical Terms Strategically:**-- Define abbreviations at first use: "messenger RNA (mRNA)"-- Provide brief explanations for specialized techniques when writing for broader audiences-- Avoid over-defining terms well-known to the target audience (signals unfamiliarity with field)-- Create a glossary if numerous specialized terms are unavoidable--**Maintain Consistency:**-- Use the same term for the same concept throughout (don't alternate between "medication," "drug," and "pharmaceutical")-- Follow a consistent system for abbreviations (decide on "PCR" or "polymerase chain reaction" after first definition)-- Apply the same nomenclature system throughout (especially for genes, species, chemicals)--**Avoid Field Mixing Errors:**-- Don't use clinical terminology for basic science (e.g., don't call mice "patients")-- Avoid colloquialisms or overly general terms in place of precise field terminology-- Don't import terminology from adjacent fields without ensuring proper usage--**Verify Terminology Usage:**-- Consult field-specific style guides and nomenclature resources-- Check how terms are used in recent papers from the target journal-- Use domain-specific databases and ontologies (e.g., Gene Ontology, MeSH terms)-- When uncertain, cite a key reference that establishes terminology--### 11. Common Pitfalls to Avoid--**Top Rejection Reasons:**-1. Inappropriate, incomplete, or insufficiently described statistics-2. Over-interpretation of results or unsupported conclusions-3. Poorly described methods affecting reproducibility-4. Small, biased, or inappropriate samples-5. Poor writing quality or difficult-to-follow text-6. Inadequate literature review or context-7. Figures and tables that are unclear or poorly designed-8. Failure to follow reporting guidelines--**Writing Quality Issues:**-- Mixing tenses inappropriately (use past tense for methods/results, present for established facts)-- Excessive jargon or undefined acronyms-- Paragraph breaks that disrupt logical flow-- Missing transitions between sections-- Inconsistent notation or terminology--## Workflow for Manuscript Development--**Stage 1: Planning**-1. Identify target journal and review author guidelines-2. Determine applicable reporting guideline (CONSORT, STROBE, etc.)-3. Outline manuscript structure (usually IMRAD)-4. Plan figures and tables as the backbone of the paper--**Stage 2: Drafting** (Use two-stage writing process for each section)-1. Start with figures and tables (the core data story)-2. For each section below, follow the two-stage process:- - **First**: Create outline with bullet points using research-lookup- - **Second**: Convert bullet points to full paragraphs with flowing prose-3. Write Methods (often easiest to draft first)-4. Draft Results (describing figures/tables objectively)-5. Compose Discussion (interpreting findings)-6. Write Introduction (setting up the research question)-7. Craft Abstract (synthesizing the complete story)-8. Create Title (concise and descriptive)--**Remember**: Bullet points are for planning only—the final manuscript must be in complete paragraphs.--**Stage 3: Revision**-1. Check logical flow and "red thread" throughout-2. Verify consistency in terminology and notation-3. Ensure figures/tables are self-explanatory-4. Confirm adherence to reporting guidelines-5. Verify all citations are accurate and properly formatted-6. Check word counts for each section-7. Proofread for grammar, spelling, and clarity--**Stage 4: Final Preparation**-1. Format according to journal requirements-2. Prepare supplementary materials-3. Write cover letter highlighting significance-4. Complete submission checklists-5. Gather all required statements and forms--## Integration with Other Scientific Skills--This skill works effectively with:-- **Data analysis skills**: For generating results to report-- **Statistical analysis**: For determining appropriate statistical presentations-- **Literature review skills**: For contextualizing research-- **Figure creation tools**: For developing publication-quality visualizations-- **Venue-templates skill**: For venue-specific writing styles and formatting (journal manuscripts)-- **scientific_report.sty**: For professional reports, white papers, and technical documents--### Professional Reports vs. Journal Manuscripts--**Choose the right formatting approach:**--| Document Type | Formatting Approach |-|---------------|---------------------|-| Journal manuscripts | Use `venue-templates` skill |-| Conference papers | Use `venue-templates` skill |-| Research reports | Use `scientific_report.sty` (this skill) |-| White papers | Use `scientific_report.sty` (this skill) |-| Technical reports | Use `scientific_report.sty` (this skill) |-| Grant reports | Use `scientific_report.sty` (this skill) |--### Venue-Specific Writing Styles--**Before writing for a specific venue, consult the venue-templates skill for writing style guides:**--Different venues have dramatically different writing expectations:-- **Nature/Science**: Accessible, story-driven, broad significance-- **Cell Press**: Mechanistic depth, graphical abstracts, Highlights-- **Medical journals (NEJM, Lancet)**: Structured abstracts, evidence language-- **ML conferences (NeurIPS, ICML)**: Contribution bullets, ablation studies-- **CS conferences (CHI, ACL)**: Field-specific conventions--The venue-templates skill provides:-- `venue_writing_styles.md`: Master style comparison-- Venue-specific guides: `nature_science_style.md`, `cell_press_style.md`, `medical_journal_styles.md`, `ml_conference_style.md`, `cs_conference_style.md`-- `reviewer_expectations.md`: What reviewers look for at each venue--**Workflow**: First use this skill for general scientific writing principles (IMRAD, clarity, citations), then consult venue-templates for venue-specific style adaptation.--## References--This skill includes comprehensive reference files covering specific aspects of scientific writing:--- `references/imrad_structure.md`: Detailed guide to IMRAD format and section-specific content-- `references/citation_styles.md`: Complete citation style guides (APA, AMA, Vancouver, Chicago, IEEE)-- `references/figures_tables.md`: Best practices for creating effective data visualizations-- `references/reporting_guidelines.md`: Study-specific reporting standards and checklists-- `references/writing_principles.md`: Core principles of effective scientific communication-- `references/professional_report_formatting.md`: Guide to professional report styling with `scientific_report.sty`--## Assets--This skill includes LaTeX style packages and templates for professional report formatting:--- `assets/scientific_report.sty`: Professional LaTeX style package with Helvetica fonts, colored boxes, and attractive tables-- `assets/scientific_report_template.tex`: Complete report template demonstrating all style features-- `assets/REPORT_FORMATTING_GUIDE.md`: Quick reference guide for the style package--**Key Features of `scientific_report.sty`:**-- Helvetica font family for modern, professional appearance-- Professional color scheme (blues, greens, oranges, purples)-- Box environments: `keyfindings`, `methodology`, `resultsbox`, `recommendations`, `limitations`, `criticalnotice`, `definition`, `executivesummary`, `hypothesis`-- Tables with alternating row colors and professional headers-- Scientific notation commands for p-values, effect sizes, confidence intervals-- Professional headers and footers--**For venue-specific writing styles** (tone, voice, abstract format, reviewer expectations), see the **venue-templates** skill which provides comprehensive style guides for Nature/Science, Cell Press, medical journals, ML conferences, and CS conferences.--Load these references as needed when working on specific aspects of scientific writing.+The linter reports issue codes and line numbers without echoing manuscript text.+Sensitive-content warnings require manual review and are not a de-identification+certificate.++Only accountable humans may:++- resolve scientific ambiguities;+- approve author order and declarations;+- approve external disclosure or transfer;+- set `submission_ready` to true;+- remove the draft banner;+- authorize submission.++## Revision and peer review++Treat reviewer material as confidential. Do not upload it to an external service without+the required authorization and policy review [SW-S01, SW-S24].++For each requested change:++1. record the comment without exposing it outside the approved boundary;+2. classify it as editorial, scientific, statistical, policy, or unresolved;+3. identify affected claims, evidence, methods, results, and displays;+4. revise the registries before prose when facts change;+5. re-run every affected audit;+6. draft a response that states what changed and where;+7. obtain human approval.++Do not comply with a request that would fabricate, hide, overstate, or breach policy.++## Current policy caution++COPE's 2017 Core Practices were retired in 2024. As of 2026-07-24, COPE announced that+a replacement Code of Conduct would be published in 2026; do not describe the archived+Core Practices as current membership standards [SW-S04, SW-S05]. Distinguish formal+COPE positions from discussion documents, webinars, comments, and case advice.++## Formatting and submission++The former LaTeX assets were removed because a generic polished template could allow+plausible placeholders to ship. Use the Markdown scaffold and structured records.+Apply the target venue's current controlled template only after verification.++See:++- `assets/REPORT_FORMATTING_GUIDE.md`+- `references/professional_report_formatting.md`+- `references/journal_policies.md`++Formatting cannot convert an incomplete evidence record into a submission-ready paper.++## Bundled files++### Assets++- `assets/manuscript_scaffold.md`+- `assets/manuscript_manifest_template.json`+- `assets/source_manifest_template.json`+- `assets/claim_evidence_template.csv`+- `assets/consistency_manifest_template.json`+- `assets/authorship_template.json`+- `assets/reporting_coverage_template.json`+- `assets/reporting_guidelines.json`++### Scripts++- `scripts/scaffold_manuscript.py`+- `scripts/validate_manifest.py`+- `scripts/select_reporting_guidelines.py`+- `scripts/audit_claims.py`+- `scripts/check_consistency.py`+- `scripts/check_references.py`+- `scripts/validate_authorship.py`+- `scripts/lint_manuscript.py`++All scripts are local, deterministic, bounded, dependency-free, and network-free. See+`references/cli_reference.md`.++### References+- `references/evidence_workflow.md`+- `references/writing_principles.md`+- `references/imrad_structure.md`+- `references/citation_styles.md`+- `references/reporting_guidelines.md`+- `references/figures_tables.md`+- `references/authorship_ai_confidentiality.md`+- `references/research_integrity_open_science.md`+- `references/journal_policies.md`+- `references/professional_report_formatting.md`+- `references/cli_reference.md`+- `references/source_ledger.md`diff --git a/skills/scientific-writing/assets/REPORT_FORMATTING_GUIDE.md b/skills/scientific-writing/assets/REPORT_FORMATTING_GUIDE.mdindex e476fcd4..c8e67f35 100644--- a/skills/scientific-writing/assets/REPORT_FORMATTING_GUIDE.md+++ b/skills/scientific-writing/assets/REPORT_FORMATTING_GUIDE.md@@ -1,574 +1,60 @@-# Scientific Report Formatting Guide+# Fail-Closed Report Formatting Guide-Quick reference for using the `scientific_report.sty` style package.+This asset replaces the former LaTeX package and example report. The former template+contained plausible-looking placeholder findings that could compile into a polished but+unverified document. Use the Markdown scaffold and structured registries instead.-## Overview+## Safe default-The `scientific_report.sty` package provides professional formatting for scientific reports, technical documents, and white papers. It features:+1. Generate a workspace with `scripts/scaffold_manuscript.py`.+2. Keep the `DRAFT — NOT FOR SUBMISSION` banner while any placeholder or verification+ gate remains.+3. Draft in plain Markdown. Apply publisher formatting only after content verification.+4. Treat the target journal's current author instructions and supplied template as+ controlling.+5. Re-run every local audit after formatting because conversion can change citations,+ symbols, tables, and references.-- **Helvetica font family** for a clean, modern appearance-- **Professional color scheme** with blues, greens, and accent colors-- **Colored box environments** for organizing different types of content-- **Attractive tables** with alternating row colors and professional headers-- **Scientific notation commands** for p-values, effect sizes, and statistics-- **Professional headers and footers** with automatic section titles+## Hierarchy----+- Use one document title and a predictable heading hierarchy.+- Do not encode scientific meaning only with typography or color.+- Keep terminology, abbreviations, units, and statistical notation consistent.+- Preserve machine-readable identifiers and evidence markers until final rendering.+- Never replace a missing value with an aesthetically plausible value.-## Color Palette+## Tables-### Primary Colors (Blues)+- Every cell must derive from a named evidence record.+- Include units, analysis population, numerator and denominator where relevant.+- Distinguish missing, not measured, not applicable, and zero.+- Keep exact values consistent with prose and the numeric registry.+- Use editable tables unless the venue explicitly requires another format.-| Color Name | RGB | Hex | Usage |-|------------|-----|-----|-------|-| `primaryblue` | (0, 51, 102) | `#003366` | Headers, titles, primary elements |-| `secondaryblue` | (74, 144, 226) | `#4A90E2` | Subsections, secondary headings |-| `lightblue` | (220, 235, 252) | `#DCEBFC` | Key findings box backgrounds |-| `accentblue` | (0, 120, 215) | `#0078D7` | Accent highlights, hypothesis boxes |+## Figures-### Scientific Colors (Greens)+Figures are optional. This skill does not generate images. A retained figure must have:-| Color Name | RGB | Hex | Usage |-|------------|-----|-----|-------|-| `sciencegreen` | (0, 168, 150) | `#00A896` | Methodology boxes, positive findings |-| `lightgreen` | (220, 245, 240) | `#DCF5F0` | Methodology box backgrounds |-| `darkgreen` | (0, 128, 96) | `#008060` | Results boxes, strong evidence |+- a provenance record linking it to data, code, or a licensed source;+- a caption that identifies the analysis population, units, uncertainty, and panels;+- alt text that communicates the figure's purpose and principal pattern without adding+ unsupported interpretation;+- labels or patterns in addition to color;+- a manual check at the final display size;+- documented permissions and transformations for reused or adapted material.-### Warning Colors (Orange/Red)+Never invent a figure, image, diagram, graphical abstract, or missing visual result.-| Color Name | RGB | Hex | Usage |-|------------|-----|-----|-------|-| `cautionorange` | (255, 140, 66) | `#FF8C42` | Limitations, warnings, cautions |-| `lightorange` | (255, 243, 224) | `#FFF3E0` | Limitations box backgrounds |-| `criticalred` | (198, 40, 40) | `#C62828` | Critical notices, alerts |-| `lightred` | (255, 235, 238) | `#FFEBEE` | Critical notice backgrounds |+## Conversion gate-### Recommendation Colors+Before producing a submission format, confirm:-| Color Name | RGB | Hex | Usage |-|------------|-----|-----|-------|-| `recommendpurple` | (103, 58, 183) | `#673AB7` | Recommendations boxes |-| `lightpurple` | (237, 231, 246) | `#EDE7F6` | Recommendations box backgrounds |--### Neutral Colors--| Color Name | RGB | Hex | Usage |-|------------|-----|-----|-------|-| `darkgray` | (66, 66, 66) | `#424242` | Body text |-| `mediumgray` | (117, 117, 117) | `#757575` | Secondary text, definitions |-| `lightgray` | (245, 245, 245) | `#F5F5F5` | Backgrounds, definition boxes |-| `tablealt` | (248, 250, 252) | `#F8FAFC` | Alternating table rows |-------## Box Environments--### Key Findings Box (Blue)--For major findings, discoveries, and important results.--```latex-\begin{keyfindings}[Custom Title]-This study found that treatment A significantly outperformed-treatment B (\pvalue{0.001}, \effectsize{d}{0.75}).-\end{keyfindings}-```--### Methodology Box (Green)--For methods, procedures, and study design highlights.--```latex-\begin{methodology}[Study Design]-This randomized controlled trial employed a 2×2 factorial design-with pre-post measurements and 6-month follow-up.-\end{methodology}-```--### Results Box (Blue-Green)--For highlighting specific results and statistical findings.--```latex-\begin{resultsbox}[Primary Outcome]-Analysis revealed a significant main effect, F(2, 147) = 12.45,-\psig{< 0.001}, $\eta^2$ = 0.145.-\end{resultsbox}-```--### Recommendations Box (Purple)--For recommendations, implications, and action items.--```latex-\begin{recommendations}[Clinical Implications]-\begin{enumerate}- \item Implement screening protocol for high-risk patients- \item Adjust treatment dosage based on biomarker levels- \item Monitor patients at 3-month intervals-\end{enumerate}-\end{recommendations}-```--### Limitations Box (Orange)--For limitations, cautions, and caveats.--```latex-\begin{limitations}[Study Limitations]-\begin{itemize}- \item Sample limited to urban populations- \item Cross-sectional design precludes causal inference- \item Self-report measures may introduce bias-\end{itemize}-\end{limitations}-```--### Critical Notice Box (Red)--For critical warnings, important notices, or safety information.--```latex-\begin{criticalnotice}[Safety Warning]-Patients with contraindication X should not receive this treatment.-Consult specialist before proceeding.-\end{criticalnotice}-```--### Definition Box (Gray)--For definitions, notes, and supplementary information.--```latex-\begin{definition}[Key Term]-\textbf{Effect size} refers to a quantitative measure of the-magnitude of a phenomenon, independent of sample size.-\end{definition}-```--### Executive Summary Box (Special)--For executive summaries with enhanced styling and shadow effect.--```latex-\begin{executivesummary}[Report Overview]-This report presents findings from a comprehensive analysis-of [topic]. Key findings indicate that...-\end{executivesummary}-```--### Hypothesis Box (Light Blue)--For stating research hypotheses.--```latex-\begin{hypothesis}[Primary Hypothesis]-We hypothesize that intervention X will significantly improve-outcome Y compared to control conditions.-\end{hypothesis}-```-------## Pull Quotes--For highlighting important quotes or statements.--```latex-\begin{pullquote}-"These findings represent a paradigm shift in our understanding-of the underlying mechanisms."-\end{pullquote}-```-------## Statistic Boxes--For highlighting key statistics (use in rows of 3).--```latex-\begin{center}-\statbox{n = 500}{Participants}-\statbox{p < 0.001}{Significance}-\statbox{d = 0.75}{Effect Size}-\end{center}-```-------## Scientific Notation Commands--### P-Values--```latex-\pvalue{0.023} % Outputs: p = 0.023-\psig{< 0.001} % Outputs: p = < 0.001 (bold for significant)-```--### Confidence Intervals--```latex-\CI{0.45}{0.72} % Outputs: 95% CI [0.45, 0.72]-```--### Effect Sizes--```latex-\effectsize{d}{0.75} % Outputs: d = 0.75-\effectsize{r}{0.42} % Outputs: r = 0.42-\effectsize{F(2, 97)}{12.45} % Outputs: F(2, 97) = 12.45-```--### Sample Size--```latex-\samplesize{250} % Outputs: n = 250-```--### Mean with Standard Deviation--```latex-\meansd{42.5}{8.3} % Outputs: 42.5 ± 8.3-```--### Significance Indicators (for tables)--```latex-Result\sigone % * for p < 0.05-Result\sigtwo % ** for p < 0.01-Result\sigthree % *** for p < 0.001-Result\signs % ns for not significant--% Legend for table footnotes:-\siglegend % Outputs: *p < 0.05; **p < 0.01; ***p < 0.001; ns not significant-```--### Quality/Evidence Indicators--```latex-\qualityhigh % HIGH (green)-\qualitymedium % MEDIUM (orange)-\qualitylow % LOW (red)--\evidencestrong % Strong (green)-\evidencemoderate % Moderate (orange)-\evidenceweak % Weak (red)-```--### Trend Indicators--```latex-\trendup % Green up triangle ▲-\trenddown % Red down triangle ▼-\trendflat % Gray right arrow →-```--### Text Highlighting--```latex-\highlight{important text} % Blue bold text-```-------## Table Formatting--### Standard Table with Alternating Rows--```latex-\begin{table}[htbp]-\centering-\caption{Descriptive Statistics by Group}-\label{tab:descriptives}-\begin{tabular}{@{}lccc@{}}-\toprule-\textbf{Variable} & \textbf{Group A} & \textbf{Group B} & \textbf{p} \\-\midrule-Age (years) & \meansd{42.5}{8.3} & \meansd{43.1}{7.9} & .58 \\-\rowcolor{tablealt} Score 1 & \meansd{15.2}{3.4} & \meansd{18.7}{4.1} & <.001\sigthree \\-Score 2 & \meansd{22.8}{5.1} & \meansd{23.4}{4.8} & .42 \\-\rowcolor{tablealt} Score 3 & \meansd{8.9}{2.2} & \meansd{7.2}{2.5} & .003\sigtwo \\-\bottomrule-\end{tabular}--\vspace{0.5em}-{\small \siglegend}-\end{table}-```--### Table with Quality Indicators--```latex-\begin{tabular}{@{}llcc@{}}-\toprule-\textbf{Study} & \textbf{Design} & \textbf{Quality} & \textbf{Evidence} \\-\midrule-Smith et al. (2023) & RCT & \qualityhigh & \evidencestrong \\-\rowcolor{tablealt} Jones et al. (2022) & Cohort & \qualitymedium & \evidencemoderate \\-Lee et al. (2021) & Cross-sectional & \qualitylow & \evidenceweak \\-\bottomrule-\end{tabular}-```--### Table with Trend Indicators--```latex-\begin{tabular}{@{}lrrl@{}}-\toprule-\textbf{Metric} & \textbf{Baseline} & \textbf{Follow-up} & \textbf{Change} \\-\midrule-Score A & 42.5 & 58.3 & \trendup +37\% \\-\rowcolor{tablealt} Score B & 18.2 & 15.1 & \trenddown -17\% \\-Score C & 7.8 & 7.9 & \trendflat +1\% \\-\bottomrule-\end{tabular}-```-------## Figure Formatting--### Standard Figure--```latex-\begin{figure}[htbp]-\centering-\includegraphics[width=0.9\textwidth]{../figures/results_chart.png}-\caption{Comparison of Outcome Scores Across Treatment Conditions}-\label{fig:results}-\end{figure}-```--### Figure with Source Attribution--```latex-\begin{figure}[htbp]-\centering-\includegraphics[width=0.85\textwidth]{../figures/data_visualization.png}-\caption{Distribution of Participant Responses by Category}-\figuresource{Study data, collected January-March 2024}-\label{fig:distribution}-\end{figure}-```--### Figure with Note--```latex-\begin{figure}[htbp]-\centering-\includegraphics[width=0.8\textwidth]{../figures/model_diagram.png}-\caption{Conceptual Model of Proposed Relationships}-\figurenote{Solid arrows indicate direct effects; dashed arrows indicate moderated effects.}-\label{fig:model}-\end{figure}-```-------## Title Page--### Standard Title Page--```latex-\makereporttitle- {Research Report Title} % Title- {A Comprehensive Analysis} % Subtitle- {Author Name, PhD} % Author(s)- {Research Institution} % Institution- {January 2025} % Date-```--### Title Page with Cover Image--```latex-\makereporttitlewithimage- {Research Report Title} % Title- {A Comprehensive Analysis} % Subtitle- {../figures/cover_image.png} % Image path- {Author Name, PhD} % Author(s)- {Research Institution} % Institution- {January 2025} % Date-```-------## List Formatting--Lists automatically use blue bullets/numbers.--### Bullet Lists--```latex-\begin{itemize}- \item First item with automatic blue bullet- \item Second item- \item Third item-\end{itemize}-```--### Numbered Lists--```latex-\begin{enumerate}- \item First item with blue number- \item Second item- \item Third item-\end{enumerate}-```-------## Appendix Sections--```latex-\appendix--\chapter{Supplementary Materials}--\appendixsection{Additional Tables}-% Content appears in table of contents--\appendixsection{Instruments}-% Additional appendix content-```-------## Compilation--Compile with XeLaTeX or LuaLaTeX for best font rendering:--```bash-# Using XeLaTeX-xelatex report.tex-bibtex report # If using BibTeX-xelatex report.tex-xelatex report.tex--# Using latexmk (recommended)-latexmk -xelatex report.tex--# Using LuaLaTeX-lualatex report.tex-```-------## Common Patterns--### Results Section Example--```latex-\section{Primary Outcomes}--\begin{resultsbox}[Main Finding]-The intervention group showed significantly higher scores than-the control group, \effectsize{t(98)}{3.45}, \psig{< 0.001},-\effectsize{d}{0.69}, \CI{0.42}{0.96}.-\end{resultsbox}--Table~\ref{tab:outcomes} presents the complete results for all-outcome measures.--\begin{table}[htbp]-\centering-\caption{Outcome Measures by Treatment Condition}-\label{tab:outcomes}-\begin{tabular}{@{}lcccc@{}}-\toprule-\textbf{Measure} & \textbf{Control} & \textbf{Treatment} & \textbf{d} & \textbf{p} \\-\midrule-Primary & \meansd{42.1}{8.2} & \meansd{51.3}{9.1} & 0.69\sigthree & <.001 \\-\rowcolor{tablealt} Secondary & \meansd{3.2}{1.1} & \meansd{4.1}{1.3} & 0.52\sigtwo & .004 \\-Tertiary & \meansd{18.5}{4.2} & \meansd{19.2}{4.5} & 0.16\signs & .328 \\-\bottomrule-\end{tabular}-\end{table}-```--### Discussion Section Example--```latex-\section{Interpretation of Findings}--\begin{keyfindings}[Summary]-\begin{enumerate}- \item Primary hypothesis \highlight{supported} with large effect- \item Secondary hypothesis partially supported- \item Evidence quality: \evidencestrong-\end{enumerate}-\end{keyfindings}--\begin{limitations}-This study has several limitations that should be considered...-\end{limitations}--\begin{recommendations}[Future Research]-Future studies should address the following:-\begin{enumerate}- \item Replicate findings in diverse populations- \item Extend follow-up period to assess long-term effects- \item Investigate moderating variables-\end{enumerate}-\end{recommendations}-```-------## Troubleshooting--### Box Overflow-If box content overflows the page:-```latex-\newpage-\begin{keyfindings}[Continued...]-```--### Figure Placement-Use `[htbp]` for flexible placement, or `[H]` (requires `float` package) for exact:-```latex-\usepackage{float}-\begin{figure}[H]-```--### Table Too Wide-Use `\resizebox` or reduce font size:-```latex-\resizebox{\textwidth}{!}{-\begin{tabular}{...}-...-\end{tabular}-}-```--### Font Issues-If Helvetica isn't rendering, ensure you're using XeLaTeX or LuaLaTeX:-```bash-xelatex report.tex # NOT pdflatex-```-------## Quick Reference Card--| Purpose | Command/Environment |-|---------|---------------------|-| Major finding | `\begin{keyfindings}...\end{keyfindings}` |-| Methods | `\begin{methodology}...\end{methodology}` |-| Results | `\begin{resultsbox}...\end{resultsbox}` |-| Recommendation | `\begin{recommendations}...\end{recommendations}` |-| Limitation | `\begin{limitations}...\end{limitations}` |-| Warning | `\begin{criticalnotice}...\end{criticalnotice}` |-| Definition | `\begin{definition}...\end{definition}` |-| Executive summary | `\begin{executivesummary}...\end{executivesummary}` |-| Hypothesis | `\begin{hypothesis}...\end{hypothesis}` |-| P-value | `\pvalue{0.05}` or `\psig{< 0.001}` |-| Effect size | `\effectsize{d}{0.75}` |-| Sample size | `\samplesize{250}` |-| Mean ± SD | `\meansd{42.5}{8.3}` |-| CI | `\CI{0.38}{0.72}` |-| Highlight | `\highlight{text}` |-| Alt row | `\rowcolor{tablealt}` |-| Significance | `\sigone`, `\sigtwo`, `\sigthree`, `\signs` |+- placeholders are absent;+- factual and numeric claims map to verified evidence IDs;+- citations and reference identifiers pass local checks;+- methods, results, units, denominators, and sample sizes agree;+- authorship, CRediT roles, declarations, and AI use are human-approved;+- confidentiality and target-journal policy reviews are complete;+- reporting-guideline coverage was reviewed without treating it as a quality score.+Formatting quality cannot make incomplete evidence submission-ready.diff --git a/skills/scientific-writing/assets/authorship_template.json b/skills/scientific-writing/assets/authorship_template.jsonnew file mode 100644index 00000000..5dd0cd83--- /dev/null+++ b/skills/scientific-writing/assets/authorship_template.json@@ -0,0 +1,56 @@+{+ "accountability": {+ "all_authors_approved": false,+ "guarantor_author_ids": []+ },+ "ai_use": {+ "disclosed_in": [],+ "human_verification_complete": false,+ "journal_policy_checked": false,+ "tools": [],+ "used": false+ },+ "authors": [+ {+ "author_id": "A001",+ "authorship_criteria": {+ "accountable_for_work": false,+ "drafted_or_critically_revised": false,+ "final_approval": false,+ "substantial_contribution": false+ },+ "credit_roles": [],+ "is_human": true,+ "name": "[[TODO:human-author-name]]"+ }+ ],+ "contributors": [],+ "corresponding_author_id": "",+ "declarations": {+ "ai_use": {+ "content_sha256": "",+ "status": "missing",+ "verified_by": "",+ "verified_on": ""+ },+ "author_contributions": {+ "content_sha256": "",+ "status": "missing",+ "verified_by": "",+ "verified_on": ""+ },+ "conflicts": {+ "content_sha256": "",+ "status": "missing",+ "verified_by": "",+ "verified_on": ""+ },+ "funding": {+ "content_sha256": "",+ "status": "missing",+ "verified_by": "",+ "verified_on": ""+ }+ },+ "schema_version": "1.0"+}diff --git a/skills/scientific-writing/assets/claim_evidence_template.csv b/skills/scientific-writing/assets/claim_evidence_template.csvnew file mode 100644index 00000000..1745c057--- /dev/null+++ b/skills/scientific-writing/assets/claim_evidence_template.csv@@ -0,0 +1,2 @@+claim_id,section,claim_kind,claim_text_sha256,evidence_ids,verification_status,uncertainty,analysis_intent+C001,[[TODO:section]],factual,[[TODO:sha256-of-normalized-claim]],E001,unverified,not_estimated,not_applicablediff --git a/skills/scientific-writing/assets/consistency_manifest_template.json b/skills/scientific-writing/assets/consistency_manifest_template.jsonnew file mode 100644index 00000000..97d8c9a8--- /dev/null+++ b/skills/scientific-writing/assets/consistency_manifest_template.json@@ -0,0 +1,43 @@+{+ "methods": [+ {+ "analysis_intent": "confirmatory",+ "method_id": "M001",+ "name": "[[TODO:verified-method-name]]",+ "outcome_ids": [+ "O001"+ ],+ "protocol_status": "prespecified"+ }+ ],+ "numeric_facts": [+ {+ "analysis_set": "[[TODO:analysis-set]]",+ "concept": "[[TODO:fact-concept]]",+ "denominator": null,+ "evidence_ids": [+ "E001"+ ],+ "fact_id": "N001",+ "numerator": null,+ "sample_size": null,+ "section": "[[TODO:section]]",+ "unit": "[[TODO:unit]]",+ "value": null+ }+ ],+ "results": [+ {+ "analysis_intent": "confirmatory",+ "evidence_ids": [+ "E001"+ ],+ "method_id": "M001",+ "outcome_id": "O001",+ "reported_sections": [],+ "result_id": "R001",+ "sample_size": null+ }+ ],+ "schema_version": "1.0"+}diff --git a/skills/scientific-writing/assets/manuscript_manifest_template.json b/skills/scientific-writing/assets/manuscript_manifest_template.jsonnew file mode 100644index 00000000..7e68378e--- /dev/null+++ b/skills/scientific-writing/assets/manuscript_manifest_template.json@@ -0,0 +1,37 @@+{+ "confidentiality_review": {+ "completed": false,+ "external_services_authorized": false,+ "policy_checked": false,+ "verified_by": "",+ "verified_on": ""+ },+ "document_id": "draft-manuscript",+ "draft_status": "draft",+ "human_verification": {+ "completed": false,+ "verified_by": "",+ "verified_on": ""+ },+ "registries": {+ "authorship_manifest": "authorship.json",+ "claim_evidence": "claims.csv",+ "consistency_manifest": "consistency_manifest.json",+ "reporting_coverage": "reporting_coverage.json",+ "source_manifest": "source_manifest.json"+ },+ "reporting_guidelines": [],+ "required_statements": {+ "ai_disclosure": "missing",+ "author_contributions": "missing",+ "code_availability": "missing",+ "conflicts": "missing",+ "consent": "missing",+ "data_availability": "missing",+ "ethics": "missing",+ "funding": "missing"+ },+ "schema_version": "1.0",+ "study_design": "[[TODO:study-design]]",+ "submission_ready": false+}diff --git a/skills/scientific-writing/assets/manuscript_scaffold.md b/skills/scientific-writing/assets/manuscript_scaffold.mdnew file mode 100644index 00000000..96cdd508--- /dev/null+++ b/skills/scientific-writing/assets/manuscript_scaffold.md@@ -0,0 +1,65 @@+# DRAFT — NOT FOR SUBMISSION++This scaffold is intentionally incomplete. Remove this banner only after every local+validator passes and accountable human authors approve the final document.++# [[TODO: verified title]]++## Abstract++[[TODO: draft from verified methods and results only; preserve uncertainty and append+claim and evidence markers to every factual or numeric assertion]]++## Introduction++[[TODO: establish context from verified sources, state the gap without exaggeration,+and distinguish prior evidence from the present study]]++## Methods++[[TODO: report what was actually done, including design, materials or participants,+outcomes, analysis intent, deviations, ethics status, and provenance]]++## Results++[[TODO: report all prespecified, exploratory, negative, null, and adverse findings that+are supported by the evidence registries; keep denominators, units, and sample sizes+consistent]]++## Discussion++[[TODO: interpret only supported results, compare with verified evidence, preserve+alternative explanations, and state concrete limitations]]++## Author contributions++[[TODO: insert only the human-approved statement generated from the validated CRediT+record]]++## Funding++[[TODO: insert a verified funding statement or a verified not-applicable statement]]++## Competing interests++[[TODO: insert a verified disclosure or a verified not-applicable statement]]++## Ethics and consent++[[TODO: insert only verified approvals, identifiers, consent language, or a verified+not-applicable statement]]++## Data and code availability++[[TODO: state actual access conditions, restrictions, repositories, persistent+identifiers, and applicable consent or policy limits]]++## AI-use disclosure++[[TODO: follow the current target-journal policy; identify tools and purposes when+required; AI is not an author and humans remain accountable]]++## References++[[TODO: render only entries whose metadata and identifiers were verified against the+opened source]]diff --git a/skills/scientific-writing/assets/reporting_coverage_template.json b/skills/scientific-writing/assets/reporting_coverage_template.jsonnew file mode 100644index 00000000..7ef65f95--- /dev/null+++ b/skills/scientific-writing/assets/reporting_coverage_template.json@@ -0,0 +1,6 @@+{+ "disclaimer": "Non-scoring coverage aid only; not a quality appraisal or compliance certificate.",+ "guideline_id": "[[TODO:guideline-id]]",+ "items": [],+ "schema_version": "1.0"+}diff --git a/skills/scientific-writing/assets/reporting_guidelines.json b/skills/scientific-writing/assets/reporting_guidelines.jsonnew file mode 100644index 00000000..1336f7cd--- /dev/null+++ b/skills/scientific-writing/assets/reporting_guidelines.json@@ -0,0 +1,529 @@+{+ "as_of": "2026-07-24",+ "guidelines": [+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "design-and-randomization",+ "label": "Trial design, allocation, concealment, and masking"+ },+ {+ "id": "participants-and-flow",+ "label": "Eligibility, recruitment, analysis populations, and participant flow"+ },+ {+ "id": "outcomes-and-harms",+ "label": "Prespecified outcomes, estimates, uncertainty, and harms"+ },+ {+ "id": "registration-protocol-analysis-plan",+ "label": "Registration, protocol, analysis plan, and deviations"+ },+ {+ "id": "open-science-and-funding",+ "label": "Data sharing, funding, conflicts, and contributor information"+ }+ ],+ "id": "consort-2025",+ "name": "CONSORT 2025",+ "official_url": "https://www.consort-spirit.org/",+ "protocol": false,+ "role": "primary",+ "source_ids": [+ "SW-S07",+ "SW-S08"+ ],+ "study_designs": [+ "randomized_trial",+ "pilot_randomized_trial"+ ],+ "version": "2025"+ },+ {+ "conditions": {+ "ai": true+ },+ "coverage_topics": [+ {+ "id": "ai-intervention-description",+ "label": "AI intervention, inputs, outputs, version, and intended use"+ },+ {+ "id": "human-ai-interaction",+ "label": "Human oversight, user expertise, and interaction workflow"+ },+ {+ "id": "error-analysis",+ "label": "Performance errors, failure cases, and subgroup behavior"+ }+ ],+ "id": "consort-ai-2020",+ "name": "CONSORT-AI extension",+ "official_url": "https://www.equator-network.org/reporting-guidelines/consort-artificial-intelligence/",+ "protocol": false,+ "role": "extension",+ "source_ids": [+ "SW-S07",+ "SW-S31"+ ],+ "study_designs": [+ "randomized_trial",+ "pilot_randomized_trial"+ ],+ "version": "2020"+ },+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "administrative-information",+ "label": "Registration, version, roles, funding, and governance"+ },+ {+ "id": "design-and-interventions",+ "label": "Trial design, interventions, allocation, and masking"+ },+ {+ "id": "outcomes-and-analysis",+ "label": "Outcomes, sample size, analysis plan, and missing data"+ },+ {+ "id": "data-monitoring-and-harms",+ "label": "Data management, monitoring, auditing, and harms"+ },+ {+ "id": "ethics-dissemination-and-access",+ "label": "Ethics, consent, confidentiality, dissemination, and access"+ }+ ],+ "id": "spirit-2025",+ "name": "SPIRIT 2025",+ "official_url": "https://www.consort-spirit.org/",+ "protocol": true,+ "role": "primary",+ "source_ids": [+ "SW-S07",+ "SW-S09"+ ],+ "study_designs": [+ "randomized_trial",+ "pilot_randomized_trial"+ ],+ "version": "2025"+ },+ {+ "conditions": {+ "ai": true+ },+ "coverage_topics": [+ {+ "id": "ai-intervention-versioning",+ "label": "AI intervention version, updates, inputs, outputs, and workflow"+ },+ {+ "id": "human-ai-protocol",+ "label": "Human oversight, user expertise, and interaction protocol"+ },+ {+ "id": "ai-error-monitoring",+ "label": "Error handling, performance monitoring, and safety"+ }+ ],+ "id": "spirit-ai-2020",+ "name": "SPIRIT-AI extension",+ "official_url": "https://www.equator-network.org/reporting-guidelines/spirit-artificial-intelligence/",+ "protocol": true,+ "role": "extension",+ "source_ids": [+ "SW-S09",+ "SW-S32"+ ],+ "study_designs": [+ "randomized_trial",+ "pilot_randomized_trial"+ ],+ "version": "2020"+ },+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "eligibility-and-information-sources",+ "label": "Eligibility criteria, information sources, and complete search strategy"+ },+ {+ "id": "selection-and-data-collection",+ "label": "Selection, extraction, data items, and reviewer processes"+ },+ {+ "id": "bias-and-certainty",+ "label": "Risk of bias, reporting bias, and certainty assessment"+ },+ {+ "id": "synthesis-and-heterogeneity",+ "label": "Effect measures, synthesis methods, heterogeneity, and sensitivity analyses"+ },+ {+ "id": "registration-support-and-availability",+ "label": "Registration, protocol, amendments, support, conflicts, data, and code"+ }+ ],+ "id": "prisma-2020",+ "name": "PRISMA 2020",+ "official_url": "https://www.prisma-statement.org/prisma-2020",+ "protocol": false,+ "role": "primary",+ "source_ids": [+ "SW-S10"+ ],+ "study_designs": [+ "systematic_review",+ "meta_analysis"+ ],+ "version": "2020"+ },+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "design-setting-and-participants",+ "label": "Design, setting, dates, eligibility, selection, and follow-up"+ },+ {+ "id": "variables-data-sources-and-bias",+ "label": "Variables, measurement, data sources, and bias"+ },+ {+ "id": "study-size-and-statistics",+ "label": "Study size, quantitative variables, confounding, missing data, and sensitivity"+ },+ {+ "id": "participants-outcomes-and-estimates",+ "label": "Participant flow, descriptive data, outcomes, and adjusted estimates"+ },+ {+ "id": "limitations-generalizability-and-funding",+ "label": "Limitations, interpretation, generalizability, and funding"+ }+ ],+ "id": "strobe-2007",+ "name": "STROBE",+ "official_url": "https://www.strobe-statement.org/checklists/",+ "protocol": false,+ "role": "primary",+ "source_ids": [+ "SW-S11"+ ],+ "study_designs": [+ "cohort",+ "case_control",+ "cross_sectional",+ "observational"+ ],+ "version": "2007"+ },+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "participants-and-design",+ "label": "Participant selection, setting, design, and data collection"+ },+ {+ "id": "index-test-and-reference-standard",+ "label": "Index test, reference standard, thresholds, and blinding"+ },+ {+ "id": "analysis-and-indeterminate-results",+ "label": "Accuracy estimates, uncertainty, missing, and indeterminate results"+ },+ {+ "id": "flow-and-applicability",+ "label": "Participant flow, timing, adverse events, and applicability"+ }+ ],+ "id": "stard-2015",+ "name": "STARD 2015",+ "official_url": "https://resources.equator-network.org/reporting-guidelines/stard",+ "protocol": false,+ "role": "primary",+ "source_ids": [+ "SW-S12"+ ],+ "study_designs": [+ "diagnostic_accuracy"+ ],+ "version": "2015"+ },+ {+ "conditions": {+ "ai": true+ },+ "coverage_topics": [+ {+ "id": "dataset-and-model-provenance",+ "label": "Dataset provenance, model version, training status, and access"+ },+ {+ "id": "ai-test-conduct",+ "label": "AI index-test execution, human interaction, thresholds, and reference standard"+ },+ {+ "id": "fairness-failures-and-generalizability",+ "label": "Subgroups, fairness, failure cases, uncertainty, and generalizability"+ }+ ],+ "id": "stard-ai-2025",+ "name": "STARD-AI",+ "official_url": "https://www.nature.com/articles/s41591-025-03953-8",+ "protocol": false,+ "role": "extension",+ "source_ids": [+ "SW-S13"+ ],+ "study_designs": [+ "diagnostic_accuracy"+ ],+ "version": "2025"+ },+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "data-source-and-participants",+ "label": "Data source, participants, setting, and outcome definition"+ },+ {+ "id": "predictors-and-sample-size",+ "label": "Predictors, sample size, missing data, and class balance"+ },+ {+ "id": "model-development-and-validation",+ "label": "Model development, tuning, validation, and updating"+ },+ {+ "id": "performance-and-clinical-utility",+ "label": "Performance, uncertainty, calibration, discrimination, and utility"+ },+ {+ "id": "fairness-transparency-and-access",+ "label": "Subgroups, fairness, interpretability, model access, data, and code"+ }+ ],+ "id": "tripod-ai-2024",+ "name": "TRIPOD+AI",+ "official_url": "https://www.tripod-statement.org/",+ "protocol": false,+ "role": "primary",+ "source_ids": [+ "SW-S14"+ ],+ "study_designs": [+ "prediction_model",+ "diagnostic_prediction_model",+ "prognostic_prediction_model"+ ],+ "version": "2024"+ },+ {+ "conditions": {+ "llm": true+ },+ "coverage_topics": [+ {+ "id": "llm-task-and-version",+ "label": "Task definition, model identity, version, prompts, and updates"+ },+ {+ "id": "evaluation-and-human-oversight",+ "label": "Evaluation design, human oversight, comparators, and failure analysis"+ },+ {+ "id": "llm-safety-and-reproducibility",+ "label": "Privacy, bias, safety, reproducibility, and access constraints"+ }+ ],+ "id": "tripod-llm-2025",+ "name": "TRIPOD-LLM",+ "official_url": "https://www.tripod-statement.org/",+ "protocol": false,+ "role": "extension",+ "source_ids": [+ "SW-S14"+ ],+ "study_designs": [+ "prediction_model",+ "diagnostic_prediction_model",+ "prognostic_prediction_model"+ ],+ "version": "2025"+ },+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "patient-information-and-consent",+ "label": "De-identified patient information, consent, and perspective"+ },+ {+ "id": "timeline-and-clinical-findings",+ "label": "Timeline, clinical findings, diagnostic assessment, and reasoning"+ },+ {+ "id": "intervention-follow-up-and-outcomes",+ "label": "Interventions, follow-up, outcomes, adverse events, and adherence"+ },+ {+ "id": "discussion-and-limitations",+ "label": "Context, strengths, limitations, and cautious take-away lessons"+ }+ ],+ "id": "care-2013",+ "name": "CARE",+ "official_url": "https://www.care-statement.org/checklist",+ "protocol": false,+ "role": "primary",+ "source_ids": [+ "SW-S15"+ ],+ "study_designs": [+ "case_report"+ ],+ "version": "2013"+ },+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "design-sample-size-and-criteria",+ "label": "Study design, experimental unit, sample size, and inclusion or exclusion"+ },+ {+ "id": "randomization-blinding-and-outcomes",+ "label": "Randomization, blinding, outcomes, and statistical methods"+ },+ {+ "id": "animals-procedures-and-welfare",+ "label": "Animal details, procedures, housing, welfare, and adverse events"+ },+ {+ "id": "ethics-interpretation-and-data",+ "label": "Ethics, limitations, interpretation, protocol, data, and conflicts"+ }+ ],+ "id": "arrive-2.0-2020",+ "name": "ARRIVE 2.0",+ "official_url": "https://arriveguidelines.org/arrive-guidelines",+ "protocol": false,+ "role": "primary",+ "source_ids": [+ "SW-S16"+ ],+ "study_designs": [+ "animal_in_vivo"+ ],+ "version": "2.0 (2020)"+ },+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "problem-context-and-rationale",+ "label": "Local problem, available knowledge, context, rationale, and aims"+ },+ {+ "id": "intervention-study-and-measures",+ "label": "Intervention, study of the intervention, measures, and analysis"+ },+ {+ "id": "ethics-results-and-variation",+ "label": "Ethical considerations, evolution, outcomes, and variation over time"+ },+ {+ "id": "interpretation-limitations-and-sustainability",+ "label": "Interpretation, limitations, sustainability, spread, and funding"+ }+ ],+ "id": "squire-2.0-2015",+ "name": "SQUIRE 2.0",+ "official_url": "https://www.squire-statement.org/index.cfm?fuseaction=page.viewPage&pageID=471&nodeID=1",+ "protocol": false,+ "role": "primary",+ "source_ids": [+ "SW-S17"+ ],+ "study_designs": [+ "quality_improvement"+ ],+ "version": "2.0 (2015)"+ },+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "population-setting-perspective",+ "label": "Population, setting, perspective, comparators, and time horizon"+ },+ {+ "id": "effects-costs-and-currency",+ "label": "Health outcomes, resources, costs, currency, and price date"+ },+ {+ "id": "model-assumptions-and-uncertainty",+ "label": "Model, assumptions, analysis plan, uncertainty, and distributional effects"+ },+ {+ "id": "engagement-results-and-conflicts",+ "label": "Stakeholder engagement, results, limitations, funding, and conflicts"+ }+ ],+ "id": "cheers-2022",+ "name": "CHEERS 2022",+ "official_url": "https://www.ispor.org/heor-resources/good-practices/article/consolidated-health-economic-evaluation-reporting-standards-2022-cheers-2022-statement-updated-reporting-guidance-for-health-economic-evaluations",+ "protocol": false,+ "role": "primary",+ "source_ids": [+ "SW-S18"+ ],+ "study_designs": [+ "health_economic_evaluation"+ ],+ "version": "2022"+ },+ {+ "conditions": {},+ "coverage_topics": [+ {+ "id": "approach-context-and-researchers",+ "label": "Qualitative approach, context, researcher characteristics, and reflexivity"+ },+ {+ "id": "sampling-ethics-and-data-collection",+ "label": "Sampling, ethics, consent, data collection, and instruments"+ },+ {+ "id": "analysis-trustworthiness-and-findings",+ "label": "Analysis, trustworthiness, findings, quotations, and links to data"+ },+ {+ "id": "limitations-implications-and-funding",+ "label": "Limitations, implications, conflicts, and funding"+ }+ ],+ "id": "srqr-2014",+ "name": "SRQR",+ "official_url": "https://www.equator-network.org/reporting-guidelines/srqr/",+ "protocol": false,+ "role": "primary",+ "source_ids": [+ "SW-S33"+ ],+ "study_designs": [+ "qualitative"+ ],+ "version": "2014"+ }+ ],+ "schema_version": "1.0"+}diff --git a/skills/scientific-writing/assets/scientific_report.sty b/skills/scientific-writing/assets/scientific_report.stydeleted file mode 100644index a7ec307a..00000000--- a/skills/scientific-writing/assets/scientific_report.sty+++ /dev/null@@ -1,606 +0,0 @@-% scientific_report.sty - Professional Scientific Report Styling-% For use with XeLaTeX or LuaLaTeX-% Designed for research reports, technical reports, white papers, and similar documents-% NOT for journal manuscripts (use venue-templates for those)--\ProvidesPackage{scientific_report}[2024/01/01 Scientific Report Style]--% ============================================================================-% REQUIRED PACKAGES-% ============================================================================--% Page layout and geometry-\RequirePackage[margin=1in, headheight=14pt]{geometry}-\RequirePackage{setspace}--% Typography - Helvetica font family-\RequirePackage[utf8]{inputenc}-\RequirePackage[T1]{fontenc}-\RequirePackage{helvet}-\renewcommand{\familydefault}{\sfdefault}--% Colors and graphics-\RequirePackage{xcolor}-\RequirePackage{graphicx}-\RequirePackage{tikz}--% Tables-\RequirePackage{longtable}-\RequirePackage{booktabs}-\RequirePackage{multirow}-\RequirePackage{array}-\RequirePackage{colortbl}-\RequirePackage{tabularx}--% Lists and formatting-\RequirePackage{enumitem}-\RequirePackage{parskip}--% Boxes and callouts-\RequirePackage[most]{tcolorbox}--% Headers and footers-\RequirePackage{fancyhdr}-\RequirePackage{titlesec}--% Hyperlinks and references-\RequirePackage{hyperref}-\RequirePackage[numbers,sort&compress]{natbib}--% Math and scientific notation-\RequirePackage{amsmath}-\RequirePackage{amssymb}-\RequirePackage{siunitx}--% Captions-\RequirePackage{caption}-\RequirePackage{subcaption}--% ============================================================================-% COLOR DEFINITIONS - PROFESSIONAL SCIENTIFIC PALETTE-% ============================================================================--% Primary colors (professional blue palette)-\definecolor{primaryblue}{RGB}{0, 51, 102} % Deep navy blue - headers, titles-\definecolor{secondaryblue}{RGB}{74, 144, 226} % Medium blue - subsections-\definecolor{lightblue}{RGB}{220, 235, 252} % Light blue for backgrounds-\definecolor{accentblue}{RGB}{0, 120, 215} % Bright accent blue--% Scientific accent colors-\definecolor{sciencegreen}{RGB}{0, 168, 150} % Teal green - positive findings-\definecolor{lightgreen}{RGB}{220, 245, 240} % Light green background-\definecolor{darkgreen}{RGB}{0, 128, 96} % Dark green for emphasis--% Warning and caution colors-\definecolor{cautionorange}{RGB}{255, 140, 66} % Orange for warnings/limitations-\definecolor{lightorange}{RGB}{255, 243, 224} % Light orange background-\definecolor{criticalred}{RGB}{198, 40, 40} % Red for critical items-\definecolor{lightred}{RGB}{255, 235, 238} % Light red background--% Recommendation and action colors-\definecolor{recommendpurple}{RGB}{103, 58, 183} % Purple for recommendations-\definecolor{lightpurple}{RGB}{237, 231, 246} % Light purple background--% Neutral colors-\definecolor{darkgray}{RGB}{66, 66, 66} % Dark gray for body text-\definecolor{mediumgray}{RGB}{117, 117, 117} % Medium gray for secondary text-\definecolor{lightgray}{RGB}{245, 245, 245} % Light gray backgrounds-\definecolor{tablealt}{RGB}{248, 250, 252} % Alternating table row color-\definecolor{tableborder}{RGB}{200, 200, 200} % Table border color--% ============================================================================-% HYPERLINK CONFIGURATION-% ============================================================================--\hypersetup{- colorlinks=true,- linkcolor=primaryblue,- filecolor=primaryblue,- urlcolor=accentblue,- citecolor=secondaryblue,- pdftitle={Scientific Report},- pdfauthor={},- pdfsubject={Scientific Research},-}--% ============================================================================-% CHAPTER AND SECTION FORMATTING-% ============================================================================--% Chapter formatting - large number with colored title-\titleformat{\chapter}[display]-{\normalfont\huge\bfseries\color{primaryblue}}-{\chaptertitlename\ \thechapter}{20pt}{\Huge}-\titlespacing*{\chapter}{0pt}{-20pt}{40pt}--% Section formatting-\titleformat{\section}-{\normalfont\Large\bfseries\color{primaryblue}}-{\thesection}{1em}{}-\titlespacing*{\section}{0pt}{3.5ex plus 1ex minus .2ex}{2.3ex plus .2ex}--% Subsection formatting-\titleformat{\subsection}-{\normalfont\large\bfseries\color{secondaryblue}}-{\thesubsection}{1em}{}--% Subsubsection formatting-\titleformat{\subsubsection}-{\normalfont\normalsize\bfseries\color{darkgray}}-{\thesubsubsection}{1em}{}--% Paragraph formatting-\titleformat{\paragraph}[runin]-{\normalfont\normalsize\bfseries\color{darkgray}}-{\theparagraph}{1em}{}--% ============================================================================-% HEADER AND FOOTER CONFIGURATION-% ============================================================================--\pagestyle{fancy}-\fancyhf{}-\fancyhead[L]{\small\textit{\leftmark}}-\fancyhead[R]{\small\textit{Scientific Report}}-\fancyfoot[C]{\thepage}-\renewcommand{\headrulewidth}{0.4pt}-\renewcommand{\footrulewidth}{0.4pt}-\renewcommand{\headrule}{\hbox to\headwidth{\color{primaryblue}\leaders\hrule height \headrulewidth\hfill}}-\renewcommand{\footrule}{\hbox to\headwidth{\color{lightgray}\leaders\hrule height \footrulewidth\hfill}}--% Plain page style for chapter pages-\fancypagestyle{plain}{- \fancyhf{}- \fancyfoot[C]{\thepage}- \renewcommand{\headrulewidth}{0pt}- \renewcommand{\footrulewidth}{0.4pt}-}--% ============================================================================-% BOX ENVIRONMENTS - SCIENTIFIC CONTENT ORGANIZATION-% ============================================================================--% Key Findings Box (Blue) - For major findings and discoveries-\newtcolorbox{keyfindings}[1][Key Findings]{- colback=lightblue,- colframe=primaryblue,- fonttitle=\bfseries\color{white},- title=#1,- coltitle=white,- colbacktitle=primaryblue,- boxrule=1pt,- arc=3pt,- left=10pt,- right=10pt,- top=8pt,- bottom=8pt,- before skip=12pt,- after skip=12pt,-}--% Methodology Box (Green) - For methods and procedures-\newtcolorbox{methodology}[1][Methodology]{- colback=lightgreen,- colframe=sciencegreen,- fonttitle=\bfseries\color{white},- title=#1,- coltitle=white,- colbacktitle=sciencegreen,- boxrule=1pt,- arc=3pt,- left=10pt,- right=10pt,- top=8pt,- bottom=8pt,- before skip=12pt,- after skip=12pt,-}--% Results Box (Blue-Green) - For highlighting key results-\newtcolorbox{resultsbox}[1][Results Highlight]{- colback=lightblue!50!lightgreen!50,- colframe=darkgreen,- fonttitle=\bfseries\color{white},- title=#1,- coltitle=white,- colbacktitle=darkgreen,- boxrule=1pt,- arc=3pt,- left=10pt,- right=10pt,- top=8pt,- bottom=8pt,- before skip=12pt,- after skip=12pt,-}--% Recommendations Box (Purple) - For recommendations and implications-\newtcolorbox{recommendations}[1][Recommendations]{- colback=lightpurple,- colframe=recommendpurple,- fonttitle=\bfseries\color{white},- title=#1,- coltitle=white,- colbacktitle=recommendpurple,- boxrule=1pt,- arc=3pt,- left=10pt,- right=10pt,- top=8pt,- bottom=8pt,- before skip=12pt,- after skip=12pt,-}--% Warning/Limitations Box (Orange) - For limitations, cautions, caveats-\newtcolorbox{limitations}[1][Limitations]{- colback=lightorange,- colframe=cautionorange,- fonttitle=\bfseries\color{white},- title=#1,- coltitle=white,- colbacktitle=cautionorange,- boxrule=1pt,- arc=3pt,- left=10pt,- right=10pt,- top=8pt,- bottom=8pt,- before skip=12pt,- after skip=12pt,-}--% Critical Notice Box (Red) - For critical warnings or important notices-\newtcolorbox{criticalnotice}[1][Critical Notice]{- colback=lightred,- colframe=criticalred,- fonttitle=\bfseries\color{white},- title=#1,- coltitle=white,- colbacktitle=criticalred,- boxrule=1pt,- arc=3pt,- left=10pt,- right=10pt,- top=8pt,- bottom=8pt,- before skip=12pt,- after skip=12pt,-}--% Definition Box (Gray) - For definitions, notes, supplementary info-\newtcolorbox{definition}[1][Definition]{- colback=lightgray,- colframe=mediumgray,- fonttitle=\bfseries\color{darkgray},- title=#1,- coltitle=darkgray,- colbacktitle=lightgray,- boxrule=0.5pt,- arc=3pt,- left=10pt,- right=10pt,- top=8pt,- bottom=8pt,- before skip=12pt,- after skip=12pt,-}--% Executive Summary Box (Special styling with shadow)-\newtcolorbox{executivesummary}[1][Executive Summary]{- enhanced,- colback=white,- colframe=primaryblue,- fonttitle=\Large\bfseries\color{white},- title=#1,- coltitle=white,- colbacktitle=primaryblue,- boxrule=2pt,- arc=5pt,- left=15pt,- right=15pt,- top=12pt,- bottom=12pt,- before skip=15pt,- after skip=15pt,- shadow={2mm}{-2mm}{0mm}{black!20},-}--% Hypothesis Box (Light blue with border) - For stating hypotheses-\newtcolorbox{hypothesis}[1][Hypothesis]{- enhanced,- colback=lightblue!50,- colframe=accentblue,- fonttitle=\bfseries\color{white},- title=#1,- coltitle=white,- colbacktitle=accentblue,- boxrule=1pt,- arc=3pt,- left=10pt,- right=10pt,- top=8pt,- bottom=8pt,- before skip=12pt,- after skip=12pt,-}--% ============================================================================-% PULL QUOTE ENVIRONMENT-% ============================================================================--\newtcolorbox{pullquote}{- enhanced,- colback=lightgray,- colframe=lightgray,- boxrule=0pt,- borderline west={4pt}{0pt}{primaryblue},- arc=0pt,- left=15pt,- right=15pt,- top=10pt,- bottom=10pt,- before skip=15pt,- after skip=15pt,- fontupper=\large\itshape\color{darkgray},-}--% ============================================================================-% STATISTIC HIGHLIGHT BOX-% ============================================================================--\newcommand{\statbox}[2]{%- \begin{tcolorbox}[- colback=primaryblue,- colframe=primaryblue,- coltext=white,- arc=5pt,- boxrule=0pt,- width=0.3\textwidth,- halign=center,- valign=center,- before skip=10pt,- after skip=10pt,- ]- {\Huge\bfseries #1}\\[5pt]- {\small #2}- \end{tcolorbox}-}--% ============================================================================-% TABLE STYLING-% ============================================================================--% Alternating row colors command-\newcommand{\tablerowcolor}{\rowcolor{tablealt}}--% Table header styling-\newcommand{\tableheader}[1]{\textbf{\color{white}#1}}-\newcommand{\tableheaderrow}{\rowcolor{primaryblue}}--% Professional table environment-\newenvironment{sciencetable}[2][htbp]{%- \begin{table}[#1]- \centering- \caption{#2}- \small-}{%- \end{table}-}--% ============================================================================-% FIGURE STYLING-% ============================================================================--% Caption formatting-\captionsetup{- font=small,- labelfont={bf,color=primaryblue},- textfont={color=darkgray},- justification=centering,- margin=20pt,-}--% Figure with source attribution-\newcommand{\figuresource}[1]{%- \par\vspace{-8pt}- {\small\textit{Source: #1}}-}--% Figure note-\newcommand{\figurenote}[1]{%- \par\vspace{-8pt}- {\small\textit{Note: #1}}-}--% ============================================================================-% LIST STYLING-% ============================================================================--% Bullet list styling with blue bullets-\setlist[itemize]{- leftmargin=*,- label=\textcolor{primaryblue}{\textbullet},- topsep=5pt,- itemsep=3pt,-}--% Numbered list styling with blue numbers-\setlist[enumerate]{- leftmargin=*,- label=\textcolor{primaryblue}{\arabic*.},- topsep=5pt,- itemsep=3pt,-}--% ============================================================================-% SCIENTIFIC NOTATION COMMANDS-% ============================================================================--% Highlight important text-\newcommand{\highlight}[1]{\textbf{\textcolor{primaryblue}{#1}}}--% P-value formatting (with significance indicators)-\newcommand{\pvalue}[1]{%- \textit{p}~=~#1%-}--% Significant p-value (bold)-\newcommand{\psig}[1]{%- \textbf{\textit{p}~=~#1}%-}--% Confidence interval-\newcommand{\CI}[2]{%- 95\% CI [#1, #2]%-}--% Effect size formatting-\newcommand{\effectsize}[2]{%- #1~=~#2%-}--% Sample size-\newcommand{\samplesize}[1]{%- \textit{n}~=~#1%-}--% Mean with SD-\newcommand{\meansd}[2]{%- #1~$\pm$~#2%-}--% Significance indicators-\newcommand{\sigone}{\textsuperscript{*}} % p < 0.05-\newcommand{\sigtwo}{\textsuperscript{**}} % p < 0.01-\newcommand{\sigthree}{\textsuperscript{***}} % p < 0.001-\newcommand{\signs}{\textsuperscript{ns}} % not significant--% Significance legend (for table footnotes)-\newcommand{\siglegend}{%- \textsuperscript{*}\textit{p}~<~0.05;- \textsuperscript{**}\textit{p}~<~0.01;- \textsuperscript{***}\textit{p}~<~0.001;- \textsuperscript{ns}not significant%-}--% ============================================================================-% STATUS INDICATORS-% ============================================================================--% Trend indicators-\newcommand{\trendup}{\textcolor{darkgreen}{$\blacktriangle$}}-\newcommand{\trenddown}{\textcolor{criticalred}{$\blacktriangledown$}}-\newcommand{\trendflat}{\textcolor{mediumgray}{$\rightarrow$}}--% Quality/Rating indicators-\newcommand{\qualityhigh}{\textbf{\textcolor{darkgreen}{HIGH}}}-\newcommand{\qualitymedium}{\textbf{\textcolor{cautionorange}{MEDIUM}}}-\newcommand{\qualitylow}{\textbf{\textcolor{criticalred}{LOW}}}--% Evidence strength-\newcommand{\evidencestrong}{\textbf{\textcolor{darkgreen}{Strong}}}-\newcommand{\evidencemoderate}{\textbf{\textcolor{cautionorange}{Moderate}}}-\newcommand{\evidenceweak}{\textbf{\textcolor{criticalred}{Weak}}}--% ============================================================================-% TITLE PAGE COMMAND-% ============================================================================--\newcommand{\makereporttitle}[5]{%- % #1 = Report Title- % #2 = Subtitle- % #3 = Author(s)- % #4 = Institution/Organization- % #5 = Date- \begin{titlepage}- \centering- \vspace*{2cm}-- {\Huge\bfseries\color{primaryblue} #1\\[0.5cm]}- {\LARGE #2\\[2cm]}-- \vspace{2cm}-- {\Large\bfseries #3\\[0.5cm]}- {\large #4\\[2cm]}-- {\large\bfseries Date: #5\\[0.3cm]}-- \vfill-- \begin{tikzpicture}- \fill[primaryblue] (0,0) rectangle (\textwidth,0.5);- \end{tikzpicture}-- \end{titlepage}-}--% Alternative title page with image-\newcommand{\makereporttitlewithimage}[6]{%- % #1 = Report Title- % #2 = Subtitle- % #3 = Hero Image Path- % #4 = Author(s)- % #5 = Institution/Organization- % #6 = Date- \begin{titlepage}- \centering- \vspace*{1cm}-- {\Huge\bfseries\color{primaryblue} #1\\[0.5cm]}- {\LARGE #2\\[1.5cm]}-- \ifx&- \vspace{4cm}- \else- \includegraphics[width=0.8\textwidth]{#3}\\[1.5cm]- \fi-- {\Large\bfseries #4\\[0.5cm]}- {\large #5\\[1.5cm]}-- {\large\bfseries Date: #6}-- \vfill-- \begin{tikzpicture}- \fill[primaryblue] (0,0) rectangle (\textwidth,0.5);- \end{tikzpicture}-- \end{titlepage}-}--% ============================================================================-% APPENDIX SECTION COMMAND-% ============================================================================--\newcommand{\appendixsection}[1]{%- \section*{#1}- \addcontentsline{toc}{section}{#1}-}--% ============================================================================-% PAGE LAYOUT ADJUSTMENTS-% ============================================================================--% Spacing-\setstretch{1.15}-\setlength{\parskip}{0.5em}--% Prevent orphans and widows-\clubpenalty=10000-\widowpenalty=10000--% Float placement-\renewcommand{\topfraction}{0.9}-\renewcommand{\bottomfraction}{0.8}-\renewcommand{\textfraction}{0.07}-\renewcommand{\floatpagefraction}{0.7}--% ============================================================================-% END OF STYLE FILE-% ============================================================================--\endinput-diff --git a/skills/scientific-writing/assets/scientific_report_template.tex b/skills/scientific-writing/assets/scientific_report_template.texdeleted file mode 100644index cc450369..00000000--- a/skills/scientific-writing/assets/scientific_report_template.tex+++ /dev/null@@ -1,449 +0,0 @@-% Scientific Report Template-% Uses scientific_report.sty for professional formatting-% Compile with: xelatex or lualatex-%-% This template demonstrates the full capabilities of the scientific_report.sty-% style package for creating professional research reports, technical reports,-% and white papers.--\documentclass[11pt,letterpaper]{report}--% Load the scientific report style package-\usepackage{scientific_report}--% Additional packages (optional, add as needed)-\usepackage{lipsum} % For placeholder text - remove in actual documents--% ============================================================================-% DOCUMENT METADATA-% ============================================================================--\hypersetup{- pdftitle={Research Report Title},- pdfauthor={Author Name},- pdfsubject={Research Subject},- pdfkeywords={keyword1, keyword2, keyword3}-}--% ============================================================================-% DOCUMENT BEGIN-% ============================================================================--\begin{document}--% -----------------------------------------------------------------------------% TITLE PAGE-% ------------------------------------------------------------------------------\makereporttitle- {Research Report Title} % Title- {A Comprehensive Analysis of [Topic]} % Subtitle- {Author Name, PhD} % Author(s)- {Research Institution / Organization} % Institution- {January 2025} % Date--% Alternative: Title page with cover image-% \makereporttitlewithimage-% {Research Report Title}-% {A Comprehensive Analysis of [Topic]}-% {../figures/cover_image.png}-% {Author Name, PhD}-% {Research Institution / Organization}-% {January 2025}--% -----------------------------------------------------------------------------% FRONT MATTER-% ------------------------------------------------------------------------------\pagenumbering{roman}--% Table of Contents-\tableofcontents-\newpage--% List of Figures-\listoffigures-\newpage--% List of Tables-\listoftables-\newpage--% -----------------------------------------------------------------------------% EXECUTIVE SUMMARY-% ------------------------------------------------------------------------------\chapter*{Executive Summary}-\addcontentsline{toc}{chapter}{Executive Summary}--\begin{executivesummary}[Report Overview]-This report presents a comprehensive analysis of [topic]. Our investigation reveals significant findings that have implications for [field/application]. The research was conducted using [methodology] and involved [sample/data description].-\end{executivesummary}--\subsection*{Key Findings}--\begin{keyfindings}-\begin{enumerate}- \item \textbf{Finding 1:} Description of the first major finding with supporting data (\pvalue{0.001}, \samplesize{250}).- \item \textbf{Finding 2:} Description of the second major finding with effect size (\effectsize{d}{0.75}).- \item \textbf{Finding 3:} Description of the third major finding (\meansd{42.5}{8.3}).-\end{enumerate}-\end{keyfindings}--\subsection*{Recommendations}--\begin{recommendations}-\begin{enumerate}- \item Implement [specific action] to address [issue].- \item Allocate resources for [specific initiative].- \item Conduct follow-up research on [topic].-\end{enumerate}-\end{recommendations}--\newpage-\pagenumbering{arabic}--% -----------------------------------------------------------------------------% CHAPTER 1: INTRODUCTION-% ------------------------------------------------------------------------------\chapter{Introduction}--\section{Background}--This section provides context for the research. Include relevant background information, the current state of knowledge, and the rationale for the study.--\begin{definition}[Key Term]-A \textbf{key term} is defined as [definition]. This concept is fundamental to understanding the research presented in this report.-\end{definition}--\section{Research Objectives}--The primary objectives of this research are:--\begin{enumerate}- \item To investigate [objective 1]- \item To analyze [objective 2]- \item To evaluate [objective 3]-\end{enumerate}--\section{Hypotheses}--\begin{hypothesis}[Primary Hypothesis]-We hypothesize that [independent variable] will have a significant effect on [dependent variable], such that [expected direction of effect].-\end{hypothesis}--\section{Scope and Limitations}--\begin{limitations}[Study Scope]-This research focuses on [specific scope]. The following limitations should be considered when interpreting the results:-\begin{itemize}- \item Geographic limitation: [description]- \item Temporal limitation: [description]- \item Sample limitation: [description]-\end{itemize}-\end{limitations}--% -----------------------------------------------------------------------------% CHAPTER 2: METHODOLOGY-% ------------------------------------------------------------------------------\chapter{Methodology}--\section{Study Design}--\begin{methodology}[Research Design Overview]-This study employed a [type] design to investigate [research question]. The methodology was selected based on [rationale] and follows established guidelines for [type of research].-\end{methodology}--\section{Participants}--A total of \samplesize{500} participants were recruited from [population]. Table~\ref{tab:demographics} presents the demographic characteristics of the sample.--\begin{table}[htbp]-\centering-\caption{Participant Demographics}-\label{tab:demographics}-\begin{tabular}{@{}lcc@{}}-\toprule-\tableheader{Characteristic} & \tableheader{n} & \tableheader{\%} \\-\midrule-\textbf{Gender} & & \\-\quad Male & 245 & 49.0 \\-\rowcolor{tablealt} \quad Female & 255 & 51.0 \\-\textbf{Age Group} & & \\-\quad 18--30 & 150 & 30.0 \\-\rowcolor{tablealt} \quad 31--45 & 200 & 40.0 \\-\quad 46--60 & 120 & 24.0 \\-\rowcolor{tablealt} \quad 60+ & 30 & 6.0 \\-\bottomrule-\end{tabular}-\end{table}--\section{Instruments}--\subsection{Primary Measures}--The following instruments were used to collect data:--\begin{itemize}- \item \textbf{Instrument 1:} Description and psychometric properties- \item \textbf{Instrument 2:} Description and psychometric properties- \item \textbf{Instrument 3:} Description and psychometric properties-\end{itemize}--\section{Procedures}--Data collection occurred between [dates]. The procedure involved the following steps:--\begin{enumerate}- \item Informed consent was obtained from all participants.- \item Baseline assessments were administered.- \item Intervention/treatment was delivered (if applicable).- \item Follow-up assessments were conducted at [timepoints].-\end{enumerate}--\section{Statistical Analysis}--Data were analyzed using [software] version [X.X]. The following analyses were performed:--\begin{itemize}- \item Descriptive statistics for all variables- \item [Analysis type] to test hypothesis 1- \item [Analysis type] to test hypothesis 2-\end{itemize}--Statistical significance was set at $\alpha = 0.05$. Effect sizes were calculated using [method] and interpreted according to [guidelines].--% -----------------------------------------------------------------------------% CHAPTER 3: RESULTS-% ------------------------------------------------------------------------------\chapter{Results}--\section{Descriptive Statistics}--Table~\ref{tab:descriptives} presents the descriptive statistics for the primary outcome measures.--\begin{table}[htbp]-\centering-\caption{Descriptive Statistics for Primary Outcome Measures}-\label{tab:descriptives}-\begin{tabular}{@{}lccccc@{}}-\toprule-\tableheader{Variable} & \tableheader{n} & \tableheader{Mean} & \tableheader{SD} & \tableheader{Min} & \tableheader{Max} \\-\midrule-Outcome 1 & 500 & 42.5 & 8.3 & 18 & 72 \\-\rowcolor{tablealt} Outcome 2 & 498 & 3.7 & 1.2 & 1 & 7 \\-Outcome 3 & 495 & 128.4 & 24.7 & 68 & 195 \\-\rowcolor{tablealt} Outcome 4 & 500 & 0.68 & 0.15 & 0.28 & 0.95 \\-\bottomrule-\end{tabular}-\figurenote{SD = Standard Deviation}-\end{table}--\section{Primary Analyses}--\subsection{Hypothesis 1}--\begin{resultsbox}[Primary Finding]-Analysis revealed a significant effect of [IV] on [DV], \effectsize{F(2, 497)}{12.45}, \psig{< 0.001}, $\eta^2$ = 0.048. Post-hoc comparisons indicated that [specific findings].-\end{resultsbox}--The results support our primary hypothesis. As shown in Figure~\ref{fig:main_results}, participants in the experimental condition demonstrated significantly higher scores compared to the control group.--% Placeholder for figure-\begin{figure}[htbp]-\centering-\fbox{\parbox{0.8\textwidth}{\centering\vspace{3cm}[Figure: Main Results Comparison]\\Bar chart showing group differences\vspace{3cm}}}-\caption{Comparison of Outcome Scores by Experimental Condition}-\label{fig:main_results}-\figuresource{Study data}-\end{figure}--\subsection{Hypothesis 2}--Results indicated a moderate positive correlation between [variable 1] and [variable 2], \effectsize{r}{0.45}, \psig{< 0.001}, \CI{0.38}{0.52}.--\section{Secondary Analyses}--Table~\ref{tab:regression} presents the results of the regression analysis predicting [outcome].--\begin{table}[htbp]-\centering-\caption{Multiple Regression Analysis Predicting Outcome}-\label{tab:regression}-\begin{tabular}{@{}lcccc@{}}-\toprule-\tableheader{Predictor} & \tableheader{B} & \tableheader{SE} & \tableheader{$\beta$} & \tableheader{p} \\-\midrule-(Intercept) & 12.45 & 2.34 & --- & < .001 \\-\rowcolor{tablealt} Predictor 1 & 0.58 & 0.12 & 0.28\sigthree & < .001 \\-Predictor 2 & 0.34 & 0.09 & 0.22\sigtwo & .002 \\-\rowcolor{tablealt} Predictor 3 & 0.15 & 0.11 & 0.08\signs & .172 \\-Predictor 4 & -0.42 & 0.14 & -0.18\sigtwo & .003 \\-\midrule-\multicolumn{5}{l}{$R^2$ = 0.34, Adjusted $R^2$ = 0.33, \effectsize{F(4, 495)}{63.82}\sigthree} \\-\bottomrule-\end{tabular}--\vspace{0.5em}-{\small \siglegend}-\end{table}--% -----------------------------------------------------------------------------% CHAPTER 4: DISCUSSION-% ------------------------------------------------------------------------------\chapter{Discussion}--\section{Summary of Findings}--\begin{keyfindings}[Key Takeaways]-\begin{enumerate}- \item The primary hypothesis was \highlight{supported}, with significant effects observed for [variables].- \item Evidence quality for the main findings is \evidencestrong, based on effect sizes and replication potential.- \item Unexpected finding: [description of any surprising results].-\end{enumerate}-\end{keyfindings}--\section{Interpretation}--The findings from this study contribute to our understanding of [topic] in several important ways. First, the significant effect of [IV] on [DV] suggests that [interpretation]. This aligns with previous research by [Author] (Year), who found similar patterns in [context].--\begin{pullquote}-``These findings represent a significant advancement in our understanding of [topic] and have direct implications for [application/practice].''-\end{pullquote}--Second, the correlation between [variables] indicates that [interpretation]. This relationship has important implications for [field/practice].--\section{Implications}--\subsection{Theoretical Implications}--The results have several theoretical implications:--\begin{itemize}- \item Support for [theory/model]- \item Extension of [existing framework]- \item Challenge to [alternative perspective]-\end{itemize}--\subsection{Practical Implications}--\begin{recommendations}[Practical Applications]-Based on our findings, we recommend the following practical applications:-\begin{enumerate}- \item \textbf{For practitioners:} [specific recommendation]- \item \textbf{For policymakers:} [specific recommendation]- \item \textbf{For researchers:} [specific recommendation]-\end{enumerate}-\end{recommendations}--\section{Limitations}--\begin{limitations}[Study Limitations]-Several limitations should be considered when interpreting these findings:-\begin{itemize}- \item \textbf{Sample:} The sample was drawn from [population], which may limit generalizability to [other populations].- \item \textbf{Design:} The [cross-sectional/correlational] design precludes causal inference.- \item \textbf{Measurement:} Self-report measures may be subject to [bias type].-\end{itemize}-\end{limitations}--\section{Future Directions}--Future research should address the following questions:--\begin{enumerate}- \item Does the effect generalize to [different population/context]?- \item What mechanisms underlie the relationship between [variables]?- \item How do [moderating factors] influence the observed effects?-\end{enumerate}--% -----------------------------------------------------------------------------% CHAPTER 5: CONCLUSIONS-% ------------------------------------------------------------------------------\chapter{Conclusions}--\begin{executivesummary}[Conclusion]-This research investigated [topic] using [methodology] with a sample of \samplesize{500} participants. The findings demonstrate that [main conclusion]. These results have important implications for [field/practice] and suggest that [recommendation]. Future research should continue to explore [direction].-\end{executivesummary}--\section{Key Contributions}--\begin{keyfindings}[Research Contributions]-This study makes the following key contributions:-\begin{enumerate}- \item \textbf{Empirical contribution:} First demonstration of [finding] in [context].- \item \textbf{Methodological contribution:} Novel application of [method] to study [phenomenon].- \item \textbf{Practical contribution:} Evidence-based recommendations for [application].-\end{enumerate}-\end{keyfindings}--% -----------------------------------------------------------------------------% REFERENCES-% ------------------------------------------------------------------------------\chapter*{References}-\addcontentsline{toc}{chapter}{References}--% If using BibTeX:-% \bibliographystyle{apalike}-% \bibliography{references}--% Manual references for template demonstration:-\noindent-\hangindent=0.5in Author, A. A. (Year). Title of article. \textit{Journal Name}, \textit{Volume}(Issue), pages. https://doi.org/xxxxx--\vspace{0.5em}-\noindent-\hangindent=0.5in Author, B. B., \& Author, C. C. (Year). \textit{Title of book}. Publisher.--% -----------------------------------------------------------------------------% APPENDICES-% ------------------------------------------------------------------------------\appendix--\chapter{Supplementary Materials}--\appendixsection{Additional Tables}--Table~\ref{tab:appendix1} presents additional descriptive statistics not included in the main text.--\begin{table}[htbp]-\centering-\caption{Supplementary Descriptive Statistics}-\label{tab:appendix1}-\begin{tabular}{@{}lccc@{}}-\toprule-\tableheader{Variable} & \tableheader{Mean} & \tableheader{SD} & \tableheader{n} \\-\midrule-Variable A & 15.2 & 3.4 & 500 \\-\rowcolor{tablealt} Variable B & 22.8 & 5.1 & 498 \\-Variable C & 8.9 & 2.2 & 495 \\-\bottomrule-\end{tabular}-\end{table}--\appendixsection{Instruments}--Full text of instruments used in this study:--\begin{enumerate}- \item \textbf{Instrument Name 1:} [Description or full text]- \item \textbf{Instrument Name 2:} [Description or full text]-\end{enumerate}--\appendixsection{Additional Figures}--[Include any supplementary figures here]--% ============================================================================-% END DOCUMENT-% ============================================================================--\end{document}-diff --git a/skills/scientific-writing/assets/source_manifest_template.json b/skills/scientific-writing/assets/source_manifest_template.jsonnew file mode 100644index 00000000..666c084b--- /dev/null+++ b/skills/scientific-writing/assets/source_manifest_template.json@@ -0,0 +1,27 @@+{+ "schema_version": "1.0",+ "sources": [+ {+ "authors": [],+ "confidentiality": "public",+ "evidence_id": "E001",+ "identifiers": {+ "doi": "",+ "isbn": "",+ "pmcid": "",+ "pmid": "",+ "url": ""+ },+ "locator": "[[TODO:page-table-figure-section-or-record-location]]",+ "source_type": "other",+ "title": "[[TODO:verified-source-title]]",+ "verification": {+ "source_opened": false,+ "status": "unverified",+ "verified_by": "",+ "verified_on": ""+ },+ "year": null+ }+ ]+}diff --git a/skills/scientific-writing/references/authorship_ai_confidentiality.md b/skills/scientific-writing/references/authorship_ai_confidentiality.mdnew file mode 100644index 00000000..f310349a--- /dev/null+++ b/skills/scientific-writing/references/authorship_ai_confidentiality.md@@ -0,0 +1,111 @@+# Authorship, CRediT, AI, and Confidentiality++## Human authorship and accountability++Use the current target-journal authorship policy. For biomedical work, ICMJE's four+criteria require substantial contribution, drafting or critical revision, final+approval, and accountability for all aspects of the work [SW-S01].++AI systems and other nonhuman tools are not authors. They cannot approve the work,+accept accountability, disclose conflicts, or manage copyright and license agreements+[SW-S01, SW-S03].++Do not:++- add or remove an author without all required human approvals;+- infer contributions from author order, affiliations, or email;+- generate an author-contribution statement from incomplete records;+- use CRediT roles as a substitute for the venue's authorship criteria.++## CRediT++CRediT is the ANSI/NISO Z39.104-2022 taxonomy of 14 contributor roles. The standard+explicitly describes contributions and does not define authorship [SW-S19].++Record only roles confirmed by the contributor and accountable author team:++- Conceptualization+- Data curation+- Formal analysis+- Funding acquisition+- Investigation+- Methodology+- Project administration+- Resources+- Software+- Supervision+- Validation+- Visualization+- Writing – original draft+- Writing – review & editing++One person may have multiple roles; a project need not use every role. Non-author+contributors may also receive appropriate credit and acknowledgment subject to consent+and journal policy.++## AI-use disclosure++The January 2026 ICMJE Recommendations require transparency about which AI tool was+used and for what purpose, place writing assistance in acknowledgments, and place AI+used for data collection, analysis, or figure generation in Methods as applicable+[SW-S01, SW-S02]. COPE's formal position likewise requires disclosure and keeps full+responsibility with human authors [SW-S03].++Journal and publisher rules differ and evolve. Check them at the time of use and again+before submission. Record:++- tool, provider, and version or access date;+- purpose and affected stage;+- whether output entered text, code, analysis, tables, or figures;+- human verification performed;+- disclosure locations required by the venue;+- what material, if any, was sent outside the approved environment;+- authorization and policy review for any restricted transfer.++Do not fabricate an AI-use statement or claim that no AI was used. Obtain confirmation+from the human authors.++## Confidentiality boundary++Do not send any of the following to an external service without explicit authorization+and a documented policy review:++- unpublished manuscripts or drafts;+- peer-review or editorial material;+- sensitive or restricted data;+- protected health information or other personal data;+- proprietary or contract-restricted content;+- source documents, including full articles, reports, protocols, and datasets.++Authorization must come from a person or body empowered to grant it and must be+consistent with journal policy, consent, ethics approval, contracts, law, institutional+policy, and data-use terms. Removing obvious names does not by itself make content safe.++When authorization is absent or unclear, keep processing local and use only minimal+metadata. This skill's bundled tools make no network calls and do not read environment+variables or `.env` files.++ICMJE treats submitted manuscripts as privileged communications and warns editors and+reviewers not to upload them to AI systems where confidentiality cannot be assured+without author permission [SW-S01]. JAMA provides a journal-policy example with the same+confidentiality concern [SW-S24].++## COPE status as of the research date++COPE's 2017 Core Practices are historical: COPE states they were retired in 2024. As of+2026-07-24, its website stated that a replacement Code of Conduct would be published in+2026; do not present the archived Core Practices as current membership standards+[SW-S04, SW-S05]. Continue to use current topic-specific COPE guidance and distinguish+formal positions from discussion documents, webinars, comments, and case advice.++## Validation++Populate `authorship.json`, then run:++```bash+python3 scripts/validate_authorship.py authorship.json+```++The validator checks human authorship gates, exact CRediT role names, guarantors, final+approval, hashed declarations, AI disclosure, and restricted external-transfer gates.+It cannot adjudicate contribution disputes or determine who deserves authorship.diff --git a/skills/scientific-writing/references/citation_styles.md b/skills/scientific-writing/references/citation_styles.mdindex e27d1bb7..ce4bdd7b 100644--- a/skills/scientific-writing/references/citation_styles.md+++ b/skills/scientific-writing/references/citation_styles.md@@ -1,720 +1,92 @@-# Citation Styles Guide+# Citation Integrity and Reference Formatting-## Overview+## Verification before style-Citation styles provide standardized formats for acknowledging sources in scientific writing. Different disciplines prefer different styles, and journals typically specify which style to use. The five most common citation styles in science are AMA, Vancouver, APA, Chicago, and IEEE.+Formatting cannot repair an unverified reference. For every cited source:-## Choosing the Right Style+1. Open the source or authoritative bibliographic record.+2. Confirm the cited proposition at a precise locator.+3. Confirm authors or organization, title, publication state, venue, year, and version.+4. Copy identifiers exactly from the verified record.+5. Record corrections, retractions, expressions of concern, updates, and preprint status.+6. Assign an evidence ID and human verification record.-| Style | Primary Disciplines | In-Text Format |-|-------|-------------------|----------------|-| AMA | Medicine, health sciences | Superscript numbers¹ |-| Vancouver | Biomedical sciences | Numbers in brackets [1] |-| APA | Psychology, social sciences, education | Author-date (Smith, 2023) |-| Chicago | Humanities, history, some sciences | Notes-bibliography or author-date |-| IEEE | Engineering, computer science | Numbers in brackets [1] |-| ACS | Chemistry | Superscript numbers¹ or (1) |-| NLM | Life sciences, PubMed | Numbers in brackets [1] |+Do not cite a source that was not read for the proposition. Do not copy a DOI, PMID,+quotation, or reference from generated text, a search snippet, or another article+without verification. ICMJE assigns authors responsibility for reference accuracy and+rejects AI-generated material as a primary source [SW-S01].-**Default recommendation**: When in doubt, check the journal's author guidelines. Most biomedical journals use Vancouver or AMA style.+## Quotations and paraphrases-## AMA Style (American Medical Association)+- Verify every quotation character-for-character and record a stable locator.+- Preserve context, qualifications, and negation.+- Mark changes, omissions, or translations according to venue policy.+- Paraphrase from understanding, not by superficial word substitution.+- Obtain permissions where copyright or license terms require them.+- For personal communications or unpublished information, obtain required permission+ and follow current journal policy [SW-S01].-### Overview-- Used primarily in medical research-- Based on the *AMA Manual of Style* (11th edition, 2020)-- Numbered citations appearing as superscripts-- References listed numerically in order of appearance+## Source choice-### In-Text Citations+Prefer the original source for a reported method, dataset, result, policy, or guideline.+Use a review for synthesis when it actually supports the synthesized claim. Clearly+identify preprints and other non-peer-reviewed versions. Check that a later correction+or published version does not supersede the cited record.-**Basic format**: Superscript numerals outside periods and commas, inside semicolons and colons.+Do not use citation counts, venue prestige, recency, or a target percentage of recent+references as a substitute for relevance and evidentiary fit.-**Examples:**-```-Several studies have demonstrated this effect.¹--The results were inconclusive,² although Smith et al³ reported otherwise.--These findings³⁻⁵ suggest a correlation.--One meta-analysis⁶ found significant heterogeneity; however, the pooled effect was significant.⁷-```--**Multiple citations**: Use commas or hyphens for ranges-```-Multiple studies¹,³,⁵⁻⁷ have confirmed this.-```--**Same source cited multiple times**: Use the same number throughout--### Reference List Format--**Journal Articles:**-```-1. Author AA, Author BB, Author CC. Title of article. Journal Name. Year;Volume(Issue):Page range. doi:xx.xxxx-```--**Example:**-```-1. Smith JD, Johnson AB, Williams CD. Effectiveness of cognitive behavioral therapy for anxiety disorders. JAMA Psychiatry. 2023;80(5):456-464. doi:10.1001/jamapsychiatry.2023.0123-```--**Books:**-```-2. Author AA. Book Title. Edition. Publisher; Year.-```--**Book Chapters:**-```-3. Chapter Author AA. Chapter title. In: Editor AA, Editor BB, eds. Book Title. Edition. Publisher; Year:Page range.-```--**Online Resources:**-```-4. Organization Name. Page title. Website name. Published date. Updated date. Accessed date. URL-```--### Special Cases--**More than 6 authors**: List first 3, then "et al"-```-Smith JD, Jones AB, Williams CD, et al.-```--**No author**: Begin with title--**Advance online publication**:-```-Published online Month Day, Year. doi:xx.xxxx-```--## Vancouver Style--### Overview-- Developed by the International Committee of Medical Journal Editors (ICMJE)-- Described in *Recommendations for the Conduct, Reporting, Editing, and Publication of Scholarly Work in Medical Journals*-- Also called "author-number style"-- Numbered citations in square brackets-- References listed numerically--### In-Text Citations--**Basic format**: Numbers in square brackets after the relevant text, before periods and commas.--**Examples:**-```-Several studies have shown this effect [1].--The results were inconclusive [2], although Smith et al [3] reported otherwise.--These findings [3-5] suggest a correlation.--Multiple studies [1,3,5-7] have confirmed this.-```--### Reference List Format--**Journal Articles:**-```-1. Author AA, Author BB, Author CC. Title of article. Journal Name. Year;Volume(Issue):Page range.-```--**Example:**-```-1. Smith JD, Johnson AB, Williams CD. Effectiveness of cognitive behavioral therapy for anxiety disorders. JAMA Psychiatry. 2023;80(5):456-464.-```--**Books:**-```-2. Author AA, Author BB. Book title. Edition. Place of publication: Publisher; Year.-```--**Book Chapters:**-```-3. Chapter Author AA, Chapter Author BB. Chapter title. In: Editor AA, Editor BB, editors. Book title. Edition. Place: Publisher; Year. p. Page range.-```--**Electronic Sources:**-```-4. Author AA. Title of page [Internet]. Place: Publisher; Date of publication [cited Date of citation]. Available from: URL-```--### Special Cases+## Identifiers-**More than 6 authors**: List first 6, then "et al."+The local checker validates syntax and duplicates only. It does not resolve identifiers+and cannot establish that an identifier belongs to the recorded work.-**Journal title abbreviations**: Use PubMed/Index Medicus abbreviations-- *The Journal of the American Medical Association* → *JAMA*-- *Nature Medicine* → *Nat Med*+Supported local checks include:-**No volume or issue**: Use year and page numbers only+- DOI;+- PMID;+- PMCID;+- ISBN checksum;+- HTTP or HTTPS URL shape;+- duplicate normalized titles and identifiers.-**Article in press**: Use "[Epub ahead of print]" notation+After the local check, a human must compare each identifier with the opened source.-## APA Style (American Psychological Association)+## NLM and journal styles-### Overview-- Widely used in psychology, education, and social sciences-- Based on the *Publication Manual of the APA* (7th edition, 2020)-- Author-date format for in-text citations-- References listed alphabetically by author surname+For biomedical references, use *Citing Medicine* and NLM's sample references for the+relevant source type [SW-S20, SW-S21]. These cover articles, books, datasets, software,+and online material. The current target journal's instructions override generic style+examples.-### In-Text Citations+For APA, AMA, Chicago, IEEE, ACS, Vancouver-derived, or publisher-specific styles:-**Basic format**: (Author, Year)+- use the current official manual or journal style;+- render from verified structured metadata;+- check author truncation, title case, journal abbreviation, version, date, locator,+ and identifier rules;+- inspect the rendered list manually after conversion.-**Examples:**-```-One study found significant effects (Smith, 2023).--Smith (2023) found significant effects.--Multiple studies (Jones, 2020; Smith, 2023; Williams, 2024) support this conclusion.-```--**Two authors**: Use "&" in parentheses, "and" in narrative-```-(Smith & Jones, 2023)-Smith and Jones (2023) demonstrated...-```--**Three or more authors**: Use "et al." after first author-```-(Smith et al., 2023)-Smith et al. (2023) reported...-```--**Multiple works by same author(s) in same year**: Add letters-```-(Smith, 2023a, 2023b)-```--**Direct quotations**: Include page numbers-```-(Smith, 2023, p. 45)-"Quote text" (Smith, 2023, p. 45).-Smith (2023) stated, "Quote text" (p. 45).-```--### Reference List Format--**Journal Articles:**-```-Author, A. A., Author, B. B., & Author, C. C. (Year). Title of article. Journal Name, Volume(Issue), page range. https://doi.org/xx.xxxx-```--**Example:**-```-Smith, J. D., Johnson, A. B., & Williams, C. D. (2023). Effectiveness of cognitive behavioral therapy for anxiety disorders. JAMA Psychiatry, 80(5), 456-464. https://doi.org/10.1001/jamapsychiatry.2023.0123-```--**Books:**-```-Author, A. A. (Year). Book title: Subtitle (Edition). Publisher. https://doi.org/xx.xxxx-```--**Book Chapters:**-```-Chapter Author, A. A., & Chapter Author, B. B. (Year). Chapter title. In E. E. Editor & F. F. Editor (Eds.), Book title (pp. page range). Publisher.-```--**Websites:**-```-Author, A. A. (Year, Month Day). Page title. Website Name. URL-```--### Capitalization Rules-- Sentence case for article and book titles (capitalize only first word and proper nouns)-- Title case for journal names (capitalize all major words)--**Example:**-```-Smith, J. D. (2023). Effects of stress on cognitive performance: A meta-analysis. Journal of Experimental Psychology: General, 152(3), 456-478.-```--### Special Cases--**No author**: Move title to author position-```-Title of work. (Year). Journal Name...-```--**No date**: Use (n.d.)-```-Smith, J. D. (n.d.). Title...-```--**Up to 20 authors**: List all authors with "&" before last-**21 or more authors**: List first 19, then "...", then final author--## Chicago Style+Do not invent a complete-looking example reference. Templates should use explicit+fields or evidence IDs until verified metadata exists.-### Overview-- Based on *The Chicago Manual of Style* (17th edition, 2017)-- Two systems: Notes-Bibliography and Author-Date-- Notes-Bibliography common in humanities-- Author-Date common in sciences+## Citation audit-### Notes-Bibliography System+Before submission:-**In-Text**: Superscript numbers for footnotes or endnotes-```-One study demonstrated this effect.¹-```--**Note format:**-```-1. John D. Smith, Alice B. Johnson, and Carol D. Williams, "Effectiveness of Cognitive Behavioral Therapy for Anxiety Disorders," JAMA Psychiatry 80, no. 5 (2023): 456-64.-```--**Bibliography format:**-```-Smith, John D., Alice B. Johnson, and Carol D. Williams. "Effectiveness of Cognitive Behavioral Therapy for Anxiety Disorders." JAMA Psychiatry 80, no. 5 (2023): 456-64.-```+- every factual or numeric claim maps to verified evidence IDs;+- each in-text citation maps to a source-manifest record;+- every reference-list entry is cited unless the venue explicitly permits a+ bibliography;+- citation ordering and repeated citation behavior match the target style;+- reused figures, tables, datasets, software, protocols, and standards are attributed;+- direct quotations have locators and permissions where needed;+- duplicate and malformed identifiers are resolved;+- no retracted or corrected status is concealed.-### Author-Date System+Run:-**In-Text**: Similar to APA+```bash+python3 scripts/audit_claims.py manuscript.md claims.csv source_manifest.json+python3 scripts/check_references.py source_manifest.json```-(Smith, Johnson, and Williams 2023)-Smith, Johnson, and Williams (2023) found...-```--**Reference list**: Similar to APA but with different punctuation-```-Smith, John D., Alice B. Johnson, and Carol D. Williams. 2023. "Effectiveness of Cognitive Behavioral Therapy for Anxiety Disorders." JAMA Psychiatry 80 (5): 456-64.-```--### Special Features-- Full names in bibliography (not just initials)-- Uses "and" not "&"-- Different punctuation from APA--## IEEE Style--### Overview-- Used in engineering, computer science, and technology-- Published by the Institute of Electrical and Electronics Engineers-- Numbered citations in square brackets-- References listed numerically--### In-Text Citations--**Format**: Numbers in square brackets--**Examples:**-```-Several studies have demonstrated this effect [1].--The algorithm was described by Smith [2] and later improved [3], [4].--Multiple implementations [1]-[4] have been proposed.-```--### Reference List Format--**Journal Articles:**-```-[1] A. A. Author, B. B. Author, and C. C. Author, "Title of article," Journal Name, vol. X, no. X, pp. XX-XX, Month Year.-```--**Example:**-```-[1] J. D. Smith, A. B. Johnson, and C. D. Williams, "Effectiveness of cognitive behavioral therapy for anxiety disorders," JAMA Psychiatry, vol. 80, no. 5, pp. 456-464, May 2023.-```--**Books:**-```-[2] A. A. Author, Book Title, Edition. City, State: Publisher, Year.-```--**Conference Papers:**-```-[3] A. A. Author, "Paper title," in Proc. Conference Name, City, State, Year, pp. XX-XX.-```--**Online Sources:**-```-[4] A. A. Author. "Title." Website. URL (accessed Mon. Day, Year).-```--### Special Features-- Abbreviated first and middle names-- Uses "and" before last author (not comma)-- Month abbreviations (Jan., Feb., etc.)-- "vol." and "no." before volume and issue-- "pp." before page range--## Additional Styles--### ACS Style (American Chemical Society)--**In-Text**: Superscript numbers or numbers in parentheses-```-This reaction has been well studied.¹-This reaction has been well studied (1).-```--**Reference format:**-```-(1) Smith, J. D.; Johnson, A. B.; Williams, C. D. Title of Article. J. Am. Chem. Soc. 2023, 145, 1234-1245.-```--**Features:**-- Semicolons between authors-- Abbreviated journal names-- Year in bold-- No issue numbers--### NLM Style (National Library of Medicine)--**Very similar to Vancouver**, used by PubMed/MEDLINE--**Key differences:**-- Uses PubMed journal abbreviations-- Specific format for electronic publications-- PMID or PMCID can be included--**Example:**-```-Smith JD, Johnson AB, Williams CD. Effectiveness of cognitive behavioral therapy for anxiety disorders. JAMA Psychiatry. 2023 May;80(5):456-64. doi: 10.1001/jamapsychiatry.2023.0123. PMID: 12345678.-```--## General Citation Best Practices--### Across All Styles--**When to cite:**-- Direct quotations-- Paraphrased ideas from others-- Statistics, data, or figures from other sources-- Theories, models, or frameworks developed by others-- Information that is not common knowledge--**Citation density:**-- Introduction: Cite liberally to establish context-- Methods: Cite when referencing established protocols or instruments-- Results: Rarely cite (focus on your own findings)-- Discussion: Cite frequently when comparing to prior work--**Source quality:**-- Prefer peer-reviewed journal articles-- Cite original sources when possible (not secondary citations)-- Use recent sources (within 5-10 years for active fields)-- Ensure sources are reputable and relevant--**Common mistakes to avoid:**-- Inconsistent formatting-- Missing required elements (DOI, page numbers, etc.)-- Citing sources not actually read (citation chaining)-- Over-reliance on review articles instead of primary sources-- Including uncited references or missing cited references-- Incorrect author names or initials-- Wrong year of publication-- Truncated titles--### Managing Citations--**Reference Management Software:**-- **Zotero**: Free, open-source, browser integration-- **Mendeley**: Free, PDF annotation, social features-- **EndNote**: Commercial, powerful, institutional support-- **RefWorks**: Web-based, institutional subscriptions--**Software benefits:**-- Automatic formatting in multiple styles-- In-text citation insertion-- Reference list generation-- PDF organization-- Sharing capabilities--### Verifying Citations--**Before submission, check:**-1. Every in-text citation has a corresponding reference-2. Every reference is cited in text-3. Formatting is consistent throughout-4. Author names and initials are correct-5. Titles are accurate-6. Journal names match required abbreviations-7. Volume, issue, and page numbers are correct-8. DOIs are included (when required)-9. URLs are functional (for web sources)-10. Citations appear in correct order (numerical styles)--## DOI (Digital Object Identifier)--### What is a DOI?-A unique alphanumeric string identifying digital content permanently.--**Format:**-```-doi:10.1001/jamapsychiatry.2023.0123-or-https://doi.org/10.1001/jamapsychiatry.2023.0123-```--### When to include:-- Required by most journals for recent publications-- Preferred over URLs because DOIs don't change-- Look up DOIs at https://www.crossref.org/ if not provided--### Style-specific formatting:-- **AMA**: `doi:10.xxxx/xxxxx`-- **APA**: `https://doi.org/10.xxxx/xxxxx`-- **Vancouver**: Often omitted or added at journal's discretion-- **Chicago**: `https://doi.org/10.xxxx/xxxxx`--## Quick Reference: Journal Article Format--| Style | Format |-|-------|--------|-| **AMA** | Author AA, Author BB. Title of article. *Journal*. Year;Vol(Iss):pp. doi:xx |-| **Vancouver** | Author AA, Author BB. Title of article. Journal. Year;Vol(Iss):pp. |-| **APA** | Author, A. A., & Author, B. B. (Year). Title of article. *Journal*, Vol(Iss), pp. https://doi.org/xx |-| **Chicago A-D** | Author, A. A., and B. B. Author. Year. "Title." *Journal* Vol (Iss): pp. |-| **IEEE** | A. A. Author and B. B. Author, "Title," *Journal*, vol. X, no. X, pp. XX-XX, Mon. Year. |--## Common Abbreviations--### Journal Abbreviations-Follow the journal's specified system (usually Index Medicus or ISO):-- *The Journal of Biological Chemistry* → *J Biol Chem*-- *Proceedings of the National Academy of Sciences* → *Proc Natl Acad Sci USA*-- *Nature Medicine* → *Nat Med*--### Month Abbreviations-- Jan., Feb., Mar., Apr., May, June, July, Aug., Sept., Oct., Nov., Dec.-- Some styles use three-letter abbreviations without periods--### Edition Abbreviations-- 1st ed., 2nd ed., 3rd ed., etc.-- Or: 1st edition, 2nd edition--## Special Publication Types--### Preprints-```-APA: Author, A. A. (Year). Title [Preprint]. Repository Name. https://doi.org/xx.xxxx-```--### Theses and Dissertations-```-APA: Author, A. A. (Year). Title [Doctoral dissertation, University Name]. Repository Name. URL-```--### Conference Proceedings-```-IEEE: A. A. Author, "Title," in Proc. Conf. Name, City, Year, pp. XX-XX.-```--### Software/Code-```-APA: Author, A. A. (Year). Title (Version X.X) [Computer software]. Publisher. URL-```--### Datasets-```-APA: Author, A. A. (Year). Title of dataset (Version X) [Data set]. Repository. https://doi.org/xx.xxxx-```--## Transitioning Between Styles--When converting between citation styles:--1. **Use reference management software** for automatic conversion-2. **Check these elements** that vary by style:- - In-text citation format (numbered vs. author-date)- - Author name format (initials vs. full names)- - Title capitalization (sentence case vs. title case)- - Journal name formatting (abbreviated vs. full)- - Punctuation (periods, commas, semicolons)- - Use of italics and bold- - Order of elements-3. **Manually verify** after automatic conversion-4. **Check journal guidelines** for specific requirements--## Journal-Specific Citation Styles and Requirements--### How to Identify a Journal's Citation Style--**Step 1: Check Author Guidelines**-- Every journal provides author instructions (usually "Instructions for Authors" or "Author Guidelines")-- Citation style is typically specified in "References" or "Citations" section-- Look for example references formatted in the journal's style--**Step 2: Review Recent Publications**-- Examine 3-5 recent articles from your target journal-- Note the in-text citation format (numbered vs. author-date)-- Compare reference list formatting-- Check for journal-specific variations--**Step 3: Verify Journal-Specific Variations**-Some journals use modified versions of standard styles:-- Abbreviated vs. full journal names-- DOI inclusion requirements-- Article titles in title case vs. sentence case-- Maximum number of authors before "et al."--### Common Journals and Their Citation Styles--| Journal | Citation Style | Key Features |-|---------|---------------|--------------|-| **JAMA, JAMA Network journals** | AMA | Superscript numbers, abbreviated journal names, no issue numbers |-| **New England Journal of Medicine** | Modified Vancouver | Numbered brackets, abbreviated journals, limited authors (3 then et al) |-| **The Lancet** | Vancouver | Numbered brackets, PubMed abbreviations |-| **BMJ** | Vancouver | Numbered in-text, DOIs required when available |-| **Nature, Nature journals** | Nature style (numbered) | Numbered superscripts, abbreviated journals, no article titles in some journals |-| **Science** | Science style (numbered) | Numbered in-text, abbreviated format |-| **Cell, Cell Press journals** | Cell style (author-year) | Author-date, specific formatting for multiple citations |-| **PLOS journals** | Vancouver | Numbered brackets, full journal names in some PLOS journals |-| **Journal of Biological Chemistry** | JBC style (numbered) | Numbered in-text, specific abbreviation rules |-| **Psychological journals** | APA | Author-date, DOIs required |-| **IEEE journals** | IEEE | Numbered brackets, specific format for conference papers |-| **ACS journals** | ACS | Superscript or numbered, semicolons between authors |--### Journal Family Consistency--**Journals from the same publisher often share citation styles:**--**Elsevier journals:**-- Vary widely; check specific journal-- Many use numbered Vancouver-style-- Some allow author-date--**Springer Nature journals:**-- Nature journals: Nature style (numbered, abbreviated)-- Springer journals: Often numbered or author-date depending on field-- BMC journals: Vancouver with full journal names--**Wiley journals:**-- Varies by field-- Many biomedical journals use Vancouver-- Psychology/social science journals often use APA--**American Chemical Society (ACS):**-- All ACS journals use ACS style-- Consistent across Journal of American Chemical Society, Analytical Chemistry, etc.--### High-Impact Journal and Conference Preferences--| Venue | Field | Citation Preference | Key Features |-|-------|-------|-------------------|--------------|-| **Nature/Science** | Multidisciplinary | Numbered, abbreviated | Space-saving, broad readability |-| **Cell family** | Life sciences | Author-date or numbered | Attribution visibility |-| **NEJM/Lancet/JAMA** | Medicine | Vancouver/AMA numbered | Medical standard |-| **NeurIPS/ICML/ICLR** | Machine Learning | Numbered [1] or (Author, Year) | Varies by conference, check template |-| **CVPR/ICCV/ECCV** | Computer Vision | Numbered [1], IEEE-like | Compact format |-| **ACL/EMNLP** | NLP | Author-year (ACL style) | Attribution-focused |--### Adapting Citations for Different Target Journals--**When switching journals after desk rejection or withdrawal:**--**Use reference management software:**-1. Import references into Zotero, Mendeley, or EndNote-2. Select target journal's citation style from software library-3. Regenerate citations and reference list automatically-4. Manually verify formatting matches journal examples--**Key elements to check when converting:**-- In-text format (switch numbered ↔ author-date)-- Journal name abbreviation style-- Article title capitalization-- Author name format (initials vs. full names)-- DOI format and inclusion-- Issue number inclusion/exclusion-- Page number format--**Manual verification essential for:**-- Preprints and non-standard sources-- Software/datasets citations-- Conference proceedings-- Dissertations and theses--### Venue-Specific Evaluation Criteria--**Content expectations:**-- **High-impact journals**: >50% citations from last 5 years; primary sources preferred-- **Medical journals**: Recent clinical evidence; systematic reviews valued-- **ML conferences**: Recent papers (last 2-3 years); preprints (arXiv) acceptable-- **Self-citation**: Keep <20% across all venues--**Format compliance (often automated):**-- Match venue citation style exactly-- All in-text citations have corresponding references-- Include DOIs when required (journals) or arXiv IDs (ML conferences)-- Use correct abbreviations (PubMed for medical, standard for ML)--**ML conference specifics:**-- **NeurIPS/ICML/ICLR**: ArXiv preprints widely cited; recent work heavily valued-- **Page limits strict**: Citation formatting affects space-- **Supplementary material**: Can include extended bibliography-- **Double-blind review**: Avoid obvious self-citation patterns during review--### Citation Density by Venue Type--| Venue Type | Expected Citations | Key Notes |-|-----------|-------------------|-----------|-| **Nature/Science research** | 30-50 | Selective, high-impact citations |-| **Medical journals (RCT)** | 25-40 | Recent clinical evidence |-| **Field-specific journals** | 30-60 | Comprehensive field coverage |-| **ML conferences (8-page)** | 20-40 | Space-limited, recent work |-| **Review articles** | 100-300+ | Comprehensive coverage |--**ML conference citation practices:**-- **NeurIPS/ICML**: 25-40 references typical for 8-page papers-- **Workshop papers**: 15-25 references-- **ArXiv preprints**: Widely accepted and cited-- **Related work**: Concise but comprehensive; often moved to appendix-- **Recency critical**: Cite work from last 1-2 years when relevant--### Pre-Submission Citation Checklist--**Content:**-- [ ] ≥50% citations from last 5-10 years (or 2-3 years for ML conferences)-- [ ] <20% self-citations; balanced perspectives-- [ ] Primary sources cited (not citation chains)-- [ ] All claims supported by appropriate citations--**Format:**-- [ ] Style matches venue exactly (check template)-- [ ] All in-text citations in reference list and vice versa-- [ ] DOIs/arXiv IDs included as required-- [ ] Abbreviations match venue style--**ML conferences additional:**-- [ ] ArXiv preprints properly formatted-- [ ] Self-citations anonymized if double-blind review-- [ ] References fit within page limits--## Resources for Citation Styles--### Official Manuals-- AMA: https://www.amamanualofstyle.com/-- Vancouver/ICMJE: http://www.icmje.org/-- APA: https://apastyle.apa.org/-- Chicago: https://www.chicagomanualofstyle.org/-- IEEE: https://ieeeauthorcenter.ieee.org/--### Journal-Specific Style Guides-- Nature: https://www.nature.com/nature/for-authors/formatting-guide-- Science: https://www.science.org/content/page/instructions-authors-- Cell: https://www.cell.com/cell/authors-- JAMA: https://jamanetwork.com/journals/jama/pages/instructions-for-authors--### Quick Reference Guides-- Purdue OWL: https://owl.purdue.edu/-- Citation Machine: https://www.citationmachine.net/-- EasyBib: https://www.easybib.com/--### Reference Management-- Zotero: https://www.zotero.org/-- Mendeley: https://www.mendeley.com/-- EndNote: https://endnote.com/--### Journal Citation Style Databases-- Journal Citation Reports (Clarivate): Lists journal citation styles-- EndNote style repository: >7000 journal-specific styles-- Zotero Style Repository: https://www.zotero.org/stylesdiff --git a/skills/scientific-writing/references/cli_reference.md b/skills/scientific-writing/references/cli_reference.mdnew file mode 100644index 00000000..4eaa6f37--- /dev/null+++ b/skills/scientific-writing/references/cli_reference.md@@ -0,0 +1,113 @@+# Local CLI Reference++All bundled commands use only the Python standard library. They:++- accept explicit UTF-8 JSON, CSV, or Markdown files;+- reject symbolic-link inputs;+- cap file size, records, fields, JSON nodes, and nesting;+- make no network calls;+- read no environment variables or `.env` files;+- perform no dynamic evaluation or pickle loading;+- report issue codes, IDs, and line numbers without echoing manuscript or source text.++Run from the skill directory with Python 3.11 or newer.++## Scaffold++```bash+python3 scripts/scaffold_manuscript.py \+ --output-dir ./draft-workspace \+ --document-id local-draft \+ --study-design randomized_trial \+ --guideline consort-2025+```++The output directory must not exist. The command never overwrites files. Generated+documents are explicitly incomplete and not submission-ready.++## Manifest validation++```bash+python3 scripts/validate_manifest.py manuscript_manifest.json --kind manuscript+python3 scripts/validate_manifest.py source_manifest.json --kind source+python3 scripts/validate_manifest.py source_manifest.json --kind source --require-verified+```++The validator checks structure, IDs, verification gates, confidentiality status, and+required-statement status. It does not read files named inside the manifest.++## Reporting-guideline routing and coverage++```bash+python3 scripts/select_reporting_guidelines.py select --study-design systematic_review+python3 scripts/select_reporting_guidelines.py check reporting_coverage.json+```++Selection and coverage are non-scoring. Open the official guideline after selection.++## Claim and citation audit++```bash+python3 scripts/audit_claims.py manuscript.md claims.csv source_manifest.json+```++Required CSV headers:++```text+claim_id,section,claim_kind,claim_text_sha256,evidence_ids,verification_status,uncertainty,analysis_intent+```++Separate multiple evidence IDs with semicolons in CSV. Use inline Markdown markers:++```text+[claim:C001] [evidence:E001,E002]+```++The audit also flags numeric content without a claim marker.++## Numeric and methods-results consistency++```bash+python3 scripts/check_consistency.py consistency_manifest.json+```++The command checks duplicate concepts across sections, units, percentages against+numerators and denominators, sample sizes, evidence IDs, declared methods, outcome+mappings, and confirmatory or exploratory status.++## Reference identifiers and duplicates++```bash+python3 scripts/check_references.py source_manifest.json+```++The command checks local syntax and duplicates for DOI, PMID, PMCID, ISBN, URL, and+normalized title. It never resolves an identifier; a human must compare each value with+the opened source.++## Authorship and disclosure++```bash+python3 scripts/validate_authorship.py authorship.json+```++The command checks human authorship criteria, exact CRediT role names, corresponding+author and guarantor IDs, final approval, hashed declarations, AI disclosure, human+verification, journal-policy review, and authorization gates for restricted material.++## Language, placeholder, and confidentiality lint++```bash+python3 scripts/lint_manuscript.py manuscript.md \+ --manifest manuscript_manifest.json+```++Possible sensitive-content findings are review prompts, not a de-identification+certificate. The linter intentionally fails on unresolved placeholders.++## Exit behavior++- exit `0`: no error-level findings;+- exit `1`: invalid input or one or more error-level findings.++Warnings still require human review. JSON output is deterministic for the same inputs.diff --git a/skills/scientific-writing/references/evidence_workflow.md b/skills/scientific-writing/references/evidence_workflow.mdnew file mode 100644index 00000000..abc6e36e--- /dev/null+++ b/skills/scientific-writing/references/evidence_workflow.md@@ -0,0 +1,94 @@+# Evidence and Provenance Workflow++## Core separation++Drafting and evidence verification are different activities.++- **Drafting** organizes language from already recorded evidence IDs. A draft may remain+ incomplete and uncertain.+- **Verification** requires an accountable human to open the source, confirm the exact+ support and locator, check bibliographic metadata, and record who verified it and+ when.+- A fluent sentence is not evidence. Search snippets, generated summaries, memory, and+ another paper's reference list are discovery aids, not verified support.++## Registries++The scaffold creates five linked records:++1. `source_manifest.json` assigns each source an `E` ID and records identifiers,+ location, confidentiality class, and verification state.+2. `claims.csv` assigns each claim a `C` ID, stores a hash rather than raw claim text,+ and maps the claim to one or more verified `E` IDs.+3. `consistency_manifest.json` binds numeric facts, methods, outcomes, analysis intent,+ units, denominators, sample sizes, and result locations.+4. `authorship.json` records human authorship criteria, CRediT roles, accountability,+ declarations, and AI use.+5. `reporting_coverage.json` records high-level coverage without scoring or certifying+ the manuscript.++These registries contain metadata, not full source documents. Do not paste unpublished+manuscripts, peer-review files, PHI, sensitive datasets, proprietary content, or source+documents into them.++## Claim markers++Append machine-readable markers to every factual or numeric assertion while drafting:++```text+[claim:C001] [evidence:E001,E002]+```++An alternative citation marker is `[@E001]`. Keep the claim and evidence markers on the+same line until the audit passes. A final publisher conversion may replace evidence IDs+with rendered citations only after preserving an auditable mapping.++## Verification procedure++For each source:++1. Open the authoritative source or record.+2. Confirm title, author or organization, publication state, year, and identifiers.+3. Record the exact supporting location, such as section, page, table, figure, or+ registry field.+4. Confirm that the source supports the claim's direction, population, intervention or+ exposure, outcome, time point, and uncertainty.+5. Record caveats, retractions, corrections, expressions of concern, or version status.+6. Mark the source verified only after a named human completes the check.++For each claim:++1. Classify it as factual, numeric, method, result, interpretive, or declaration.+2. Hash the normalized claim text and store the hash in `claims.csv`.+3. Map it to verified evidence IDs.+4. Record uncertainty and whether the analysis was confirmatory, exploratory,+ descriptive, or not applicable.+5. Keep unsupported or conflicting claims out of submission-ready prose. If useful,+ retain them in a clearly marked unresolved-issues log.++## Drafting gates++Do not infer or complete missing:++- citations, identifiers, quotations, or source locators;+- data values, denominators, units, sample sizes, or statistical results;+- methods, protocol details, analysis decisions, or deviations;+- approvals, consent, registrations, author contributions, conflicts, funding, or+ availability statements.++Use explicit missing states. Preserve negative, null, adverse, unexpected, and+inconclusive findings. Never convert absence of evidence into evidence of no effect.++## Final audit++Run:++```bash+python3 scripts/validate_manifest.py source_manifest.json --kind source --require-verified+python3 scripts/audit_claims.py manuscript.md claims.csv source_manifest.json+python3 scripts/check_consistency.py consistency_manifest.json+python3 scripts/check_references.py source_manifest.json+```++Tool output contains IDs and line numbers, not manuscript or source text. A passing+machine audit supports review; it does not replace human scientific judgment.diff --git a/skills/scientific-writing/references/figures_tables.md b/skills/scientific-writing/references/figures_tables.mdindex 4f612425..7022338d 100644--- a/skills/scientific-writing/references/figures_tables.md+++ b/skills/scientific-writing/references/figures_tables.md@@ -1,806 +1,94 @@-# Figures and Tables Best Practices+# Optional Figures and Tables-## Overview+Figures and tables are optional. Include a display only when it communicates verified+evidence more clearly than prose and the target venue permits it. This skill does not+generate images, schematics, graphical abstracts, or synthetic scientific visuals.-Figures and tables are essential components of scientific papers, serving to display data patterns, summarize results, and provide evidence for conclusions. Effective visual displays enhance comprehension and can sustain reader interest while illustrating trends, patterns, and relationships not easily conveyed through text alone.+## Provenance gate-A recent Nature Cell Biology checklist (2025) emphasizes that creating clear and engaging scientific figures is crucial for communicating complex data with clarity, accessibility, and design excellence.+Each display needs a record containing:-## When to Use Tables vs. Figures+- stable display ID and version;+- source data or evidence IDs;+- code, query, or manual transformation used;+- accountable creator and reviewer;+- date generated or revised;+- analysis population, exclusions, and sample size;+- units, scales, denominators, and uncertainty definitions;+- license, attribution, and permission status for reused material;+- documented adjustments, cropping, compositing, or preprocessing.-### Use Tables When:-- Presenting precise numerical values that readers need to reference-- Comparing exact measurements across multiple variables-- Showing detailed statistical outputs-- Data cannot be adequately summarized in 1-2 sentences-- Readers need access to specific data points-- Displaying demographic or baseline characteristics-- Presenting multiple related statistical tests+Do not recreate missing source data from a screenshot or published graphic. Do not+alter an image in a way that hides, removes, duplicates, or misrepresents information.+Retain original files and an audit trail.-**Example use cases:**-- Baseline participant characteristics (age, sex, diagnosis, etc.)-- Detailed statistical model outputs (coefficients, p-values, confidence intervals)-- Dose-response data with exact values-- Gene expression levels for specific genes-- Chemical compositions or concentrations+## Choosing a form-### Use Figures When:-- Showing trends over time-- Displaying relationships or correlations-- Comparing groups visually-- Illustrating distributions-- Demonstrating patterns not easily seen in numbers-- Showing images (microscopy, radiography, etc.)-- Displaying workflows, diagrams, or schematics+Use:-**Example use cases:**-- Growth curves or time series-- Dose-response curves-- Scatter plots showing correlations-- Bar graphs comparing treatment groups-- Histograms showing distributions-- Heatmaps displaying patterns across conditions-- Microscopy images or Western blots+- prose for a small number of directly relevant values;+- a table when exact values and multidimensional comparison matter;+- a figure when pattern, distribution, relationship, sequence, or spatial information+ matters.-### General Decision Rule+Avoid duplicating the same information in prose, a table, and a figure. There is no+universal minimum, maximum, or display-per-word rule.-**Can the information be conveyed in 1-2 sentences of text?**-- Yes → Use text only-- No, and precise values are needed → Use a table-- No, and patterns/trends are most important → Use a figure+## Tables-## Core Design Principles+Check:-### 1. Self-Explanatory Display Items+- title and notes define population, time point, analysis set, units, and abbreviations;+- rows and columns preserve denominators and distinguish missing from zero;+- percentages can be recomputed from the recorded numerator and denominator;+- precision is consistent with the measurement and analysis;+- uncertainty and statistical quantities are named, not implied by symbols alone;+- values match the abstract, prose, figures, supplements, and consistency registry;+- cells remain accessible as text rather than an image when the venue allows.-**Each figure or table must stand alone without requiring the main text.**+## Figures-**Essential elements:**-- Complete, descriptive caption-- All abbreviations defined (in caption or footnote)-- Units of measurement clearly indicated-- Sample sizes (n) reported-- Statistical significance annotations explained-- Legend included (for figures with multiple data series)+Check:-**Example of self-explanatory caption:**-```-Figure 1. Mean systolic blood pressure (SBP) over 12 weeks in intervention and control groups.-Error bars represent standard error of the mean (SEM). Asterisks indicate significant-differences between groups at each time point (*p < 0.05, **p < 0.01, ***p < 0.001,-two-tailed t-tests). n = 48 per group. BP = blood pressure; SEM = standard error of mean.-```+- axes, scales, transformations, units, and reference lines are explicit;+- truncated or nonlinear scales are visible and justified;+- individual observations or distributions are shown when scientifically appropriate;+- uncertainty is defined;+- group sizes and exclusions are available;+- legends identify all encodings;+- colors, shapes, line styles, labels, or patterns provide redundant cues;+- image panels include scale and orientation information where relevant;+- the final exported file matches current journal format and size instructions.-### 2. Avoid Redundancy+Do not add significance stars or trend lines unless they map to a verified analysis.-**Do not duplicate information between text, tables, and figures.**+## Captions and alt text-**Bad practice:**-```-"Mean age was 45.2 years in Group A and 47.8 years in Group B. Mean BMI was 26.3 in-Group A and 28.1 in Group B. Mean systolic blood pressure was 132 mmHg in Group A..."-[Also shown in Table 1]-```+A caption should state what is shown, define panels and encodings, identify the analysis+population, units, uncertainty, and relevant methods, and link to evidence IDs during+drafting.-**Good practice:**-```-"Baseline characteristics were similar between groups (Table 1), with no significant-differences in age, BMI, or blood pressure (all p > 0.15)."-[Details in Table 1]-```+Alt text should:-**Key principle:** Text should highlight key findings from tables/figures, not repeat all data.+- identify the display type and purpose;+- summarize the principal visible pattern without adding a new conclusion;+- describe axes, groups, direction, and uncertainty needed to understand the display;+- avoid repeating the full caption or listing every data point;+- be reviewed manually with the final display.-### 3. Consistency+Automated accessibility checks do not verify scientific correctness. Inspect contrast,+color independence, reading order, label size, keyboard or screen-reader behavior where+applicable, and legibility at final size.-**Maintain uniform formatting across all display items:**-- Font types and sizes-- Color schemes-- Terminology and abbreviations-- Axis labels and units-- Statistical annotation methods-- Figure styles (all line graphs should look similar)+## Flow diagrams-**Example of inconsistency to avoid:**-- Figure 1 uses "standard error" while Figure 2 uses "SE"-- Figure 1 has blue/red color scheme while Figure 2 uses green/yellow-- Table 1 reports p-values as "p = 0.023" while Table 2 uses "p-value = .023"+Use the current official flow-diagram resource for the selected guideline, such as+CONSORT 2025 or PRISMA 2020 [SW-S07, SW-S10]. Populate it only from verified counts.+Reconcile every branch and denominator with the methods, results, and registry.-### 4. Optimal Quantity+## Final manual review-**Follow the "one display item per 1000 words" guideline.**--**Typical manuscript:**-- 3000-4000 words → 3-4 tables/figures total-- 5000-6000 words → 5-6 tables/figures total--**Quality over quantity:** A few well-designed, information-rich displays are better than many redundant or poorly designed ones.--### 5. Clarity and Simplicity--**Avoid cluttered or overly complex displays:**-- Don't include too many variables in one figure-- Use clear, readable fonts (minimum 8-10 pt in final size)-- Provide adequate spacing between elements-- Use high contrast (especially for color-blind accessibility)-- Remove unnecessary grid lines, borders, or decoration-- Maximize data-ink ratio (Tufte principle: minimize non-data ink)--## Figure Types and When to Use Them--### Bar Graphs--**Best for:**-- Comparing discrete categories or groups-- Showing counts or frequencies-- Displaying mean values with error bars--**Design guidelines:**-- Start y-axis at zero (unless showing small differences in large values)-- Order bars logically (by size, alphabetically, or temporally)-- Use error bars (SD, SEM, or CI) consistently-- Include sample sizes-- Avoid 3D effects (they distort perception)--**Common mistakes:**-- Not starting at zero (can exaggerate differences)-- Too many categories (consider table instead)-- Missing error bars--**Example applications:**-- Mean gene expression across tissue types-- Treatment group comparisons-- Frequency of adverse events--### Line Graphs--**Best for:**-- Showing trends over continuous variables (usually time)-- Displaying multiple groups on same axes-- Illustrating dose-response relationships--**Design guidelines:**-- Use different line styles or colors for groups-- Include data point markers for sparse data-- Show error bars or shaded confidence intervals-- Label axes clearly with units-- Use consistent intervals on x-axis--**Common mistakes:**-- Connecting discrete data points that shouldn't be connected-- Too many lines making graph unreadable-- Inconsistent time intervals without indication--**Example applications:**-- Growth curves-- Time course experiments-- Survival curves (Kaplan-Meier plots)-- Pharmacokinetic profiles--### Scatter Plots--**Best for:**-- Showing relationships between two continuous variables-- Displaying correlations-- Identifying outliers--**Design guidelines:**-- Include trend line or regression line with equation and R²-- Report correlation coefficient and p-value-- Use semi-transparent points if data overlap-- Consider logarithmic scales for wide ranges-- Mark outliers if relevant--**Common mistakes:**-- Not showing individual data points-- Using scatter plots for categorical data-- Missing correlation statistics--**Example applications:**-- Correlation between biomarkers-- Relationship between dose and response-- Method comparison (Bland-Altman plots)--### Box Plots (Box-and-Whisker Plots)--**Best for:**-- Showing distributions and spread-- Comparing distributions across groups-- Identifying outliers--**Design guidelines:**-- Clearly define box elements (median, quartiles, whiskers)-- Show or note outliers explicitly-- Consider violin plots for small sample sizes-- Overlay individual data points when n < 20--**Common mistakes:**-- Not defining what whiskers represent-- Using for very small samples without showing raw data-- Not marking outliers--**Example applications:**-- Comparing distributions across treatment groups-- Showing variability in measurements-- Quality control data--### Heatmaps--**Best for:**-- Displaying matrices of data-- Showing patterns across many conditions-- Representing clustering or grouping--**Design guidelines:**-- Use color scales that are perceptually uniform-- Include color scale bar with units-- Consider hierarchical clustering for rows/columns-- Use appropriate color scheme (diverging vs. sequential)-- Make axes labels readable--**Common mistakes:**-- Poor color choice (rainbow scales are often misleading)-- Too many rows/columns making labels unreadable-- No color scale bar--**Example applications:**-- Gene expression across samples-- Correlation matrices-- Time-series data across multiple variables--### Images (Microscopy, Gels, Blots)--**Best for:**-- Showing representative examples-- Demonstrating morphology or localization-- Presenting gel electrophoresis or Western blots--**Design guidelines:**-- Include scale bars (not magnification in caption)-- Show representative images with quantification in separate panel-- Label important features with arrows or labels-- Ensure adequate resolution (usually 300+ dpi)-- Show full, unmanipulated images with cropping noted-- Include all relevant controls--**Common mistakes:**-- No scale bar-- Over-processed or manipulated images-- Cherry-picking best images without quantification-- Insufficient resolution--**Example applications:**-- Histological sections-- Immunofluorescence-- Western blots-- Gel electrophoresis--### Forest Plots--**Best for:**-- Displaying meta-analysis results-- Showing effect sizes with confidence intervals-- Comparing multiple studies or subgroups--**Design guidelines:**-- Include point estimates and CI for each study-- Show overall pooled estimate clearly-- Include line of no effect (typically at 1.0 or 0)-- List study details or weights--**Example applications:**-- Meta-analyses-- Systematic reviews-- Subgroup analyses--### Flow Diagrams--**Best for:**-- Study participant flow (CONSORT diagrams)-- Systematic review search process (PRISMA diagrams)-- Experimental workflows--**Design guidelines:**-- Follow reporting guideline templates (CONSORT, PRISMA)-- Use consistent shapes and connectors-- Include numbers at each stage-- Clearly show inclusions and exclusions--## Table Design Guidelines--### Structure--**Basic anatomy:**-1. **Table number and title** (above table)-2. **Column headers** (with units)-3. **Row labels**-4. **Data cells** (with appropriate precision)-5. **Footnotes** (below table for abbreviations, statistics, notes)--### Formatting Best Practices--**Column headers:**-- Use clear, concise labels-- Include units in parentheses-- Use abbreviations sparingly (define in footnote)--**Data presentation:**-- Align decimal points in columns-- Use consistent decimal places (usually 1-2 for means)-- Report same precision across rows/columns-- Use en-dash (–) for "not applicable"-- Use appropriate precision (don't over-report)--**Statistical annotations:**-- Use superscript letters (ᵃ, ᵇ, ᶜ) or symbols (*, †, ‡) for footnotes-- Define p-value thresholds clearly-- Report exact p-values when possible (p = 0.032, not p < 0.05)--**Footnotes:**-- Define all abbreviations-- Explain statistical tests used-- Note any missing data-- Indicate data source if not original--### Example Table Format--```-Table 1. Baseline Characteristics of Study Participants--Characteristic Intervention (n=50) Control (n=48) p-value-─────────────────────────────────────────────────────────────────────────-Age, years 45.3 ± 8.2 47.1 ± 9.1 0.28-Male sex, n (%) 28 (56) 25 (52) 0.71-BMI, kg/m² 26.3 ± 3.8 27.1 ± 4.2 0.32-Current smoker, n (%) 12 (24) 15 (31) 0.42-Systolic BP, mmHg 132 ± 15 134 ± 18 0.54-─────────────────────────────────────────────────────────────────────────--Data presented as mean ± SD or n (%). p-values from independent t-tests for-continuous variables and χ² tests for categorical variables. BMI = body mass-index; BP = blood pressure; SD = standard deviation.-```--### Common Table Mistakes--1. **Excessive complexity** (too many rows/columns)-2. **Insufficient context** (missing units, unclear abbreviations)-3. **Over-precision** (reporting 5 decimal places for p-values)-4. **Missing sample sizes**-5. **No statistical comparisons when appropriate**-6. **Inconsistent formatting** across multiple tables-7. **Duplicate information** with figures or text--## Statistical Presentation in Figures and Tables--### Reporting Requirements--**For each comparison, report:**-1. **Point estimate** (mean, median, proportion)-2. **Measure of variability** (SD, SEM, CI)-3. **Sample size** (n)-4. **Test statistic** (t, F, χ², etc.)-5. **p-value** (exact when p > 0.001)-6. **Effect size** (when appropriate)--### Error Bars--**Choose the appropriate measure:**--| Measure | Meaning | When to Use |-|---------|---------|-------------|-| **SD (Standard Deviation)** | Variability in the data | Showing data spread |-| **SEM (Standard Error of Mean)** | Precision of mean estimate | Showing measurement precision |-| **95% CI (Confidence Interval)** | Range likely to contain true mean | Showing statistical significance |--**Key rule:** Always state which measure is shown.--**Example caption:**-```-"Error bars represent 95% confidence intervals."-NOT: "Error bars represent standard error."-```--**Recommendation:** 95% CI preferred because non-overlapping CIs indicate significant differences.--### Significance Indicators--**Common notation:**-```-* p < 0.05-** p < 0.01-*** p < 0.001-n.s. or NS = not significant-```--**Alternative:** Show exact p-values in table or caption--**Best practice:** Define significance indicators in every figure caption or table footnote.--## Accessibility Considerations--### Color-Blind Friendly Design--**Recommendations:**-- Use color palettes designed for color-blind accessibility-- Don't rely on color alone (add patterns, shapes, or labels)-- Test figures in grayscale-- Avoid red-green combinations--**Color-blind safe palettes:**-- Blue-Orange-- Purple-Yellow-- Colorbrewer2.org palettes-- Viridis, Plasma, Inferno (for heatmaps)--### High Contrast--**Ensure readability:**-- Dark text on light background (or vice versa)-- Avoid low-contrast color combinations (gray on gray)-- Use thick enough lines (minimum 0.5-1 pt)-- Large enough text (minimum 8-10 pt after scaling)--### Screen and Print Compatibility--**Design for both media:**-- Use vector formats when possible (PDF, EPS, SVG)-- Minimum 300 dpi for raster images (TIFF, PNG)-- Test appearance at final print size-- Ensure color figures work in grayscale if printed--## Technical Requirements--### File Formats--**Vector formats** (preferred for graphs and diagrams):-- **PDF**: Universal, preserves quality-- **EPS**: Encapsulated PostScript, publishing standard-- **SVG**: Scalable vector graphics, web-friendly--**Raster formats** (for photos and images):-- **TIFF**: Uncompressed, high quality, large files-- **PNG**: Lossless compression, good for screen-- **JPEG**: Lossy compression, avoid for data figures--**Avoid:**-- Low-resolution screenshots-- Figures copied from presentations (usually too low resolution)-- Heavily compressed JPEGs (artifacts)--### Resolution Requirements--**Minimum standards:**-- **Line art** (graphs, diagrams): 300-600 dpi-- **Halftones** (photos, grayscale): 300 dpi-- **Combination** (images with labels): 300-600 dpi--**Best practice:** Create figures at final size and resolution.--### Dimensions--**Check journal requirements:**-- **Single column**: typically 8-9 cm (3-3.5 inches) wide-- **Double column**: typically 17-18 cm (6.5-7 inches) wide-- **Full page**: varies by journal--**Recommendation:** Design figures to fit single column when possible.--### Image Manipulation--**Allowed:**-- Brightness/contrast adjustment applied to entire image-- Color balance adjustment-- Cropping (with notation)-- Rotation--**NOT allowed:**-- Selective editing (e.g., enhancing bands in gels)-- Removing background artifacts-- Splicing images without clear indication-- Any manipulation that obscures, eliminates, or misrepresents data--**Ethical requirement:** Report all image adjustments in Methods section.--## Figure and Table Numbering--### Numbering System--**Figures:**-- Number consecutively in order of first mention in text-- Use Arabic numerals: Figure 1, Figure 2, Figure 3...-- Supplementary figures: Figure S1, Figure S2...--**Tables:**-- Number separately from figures-- Use Arabic numerals: Table 1, Table 2, Table 3...-- Supplementary tables: Table S1, Table S2...--### In-Text References--**Format:**-```-"Results are shown in Figure 1."-"Participant characteristics are presented in Table 2."-"Multiple analyses confirmed this finding (Figures 3-5)."-```--**NOT:**-```-"Figure 1 below shows..." (avoid "above" or "below" - pagination may change)-"The figure shows..." (always use specific number)-```--## Captions--### Caption Structure--**For figures:**-```-Figure 1. [One-sentence title]. [Additional description sentences providing context,-defining abbreviations, explaining panels, describing statistical tests, and noting-sample sizes].-```--**For tables:**-```-Table 1. [Descriptive Title]-[Table contents]-[Footnotes defining abbreviations, statistical methods, and providing additional context]-```--### Caption Content--**Essential information:**-1. What is being shown (brief title)-2. Detailed description of content-3. Definition of all abbreviations and symbols-4. Sample sizes-5. Statistical tests used-6. Meaning of error bars or annotations-7. Panel labels explained (if multiple panels)--**Example comprehensive caption:**-```-Figure 3. Cognitive performance improves with treatment over 12 weeks. (A) Mean Mini-Mental-State Examination (MMSE) scores at baseline, 6 weeks, and 12 weeks for treatment (blue) and-placebo (gray) groups. (B) Individual participant trajectories for treatment group. Error bars-represent 95% confidence intervals. Asterisks indicate significant between-group differences-(*p < 0.05, **p < 0.01, ***p < 0.001; repeated measures ANOVA with Bonferroni correction).-n = 42 treatment, n = 40 placebo. MMSE scores range from 0-30, with higher scores indicating-better cognitive function.-```--## Journal-Specific Requirements--### Before Creating Figures/Tables--**Check journal guidelines for:**-- Preferred file formats-- Resolution requirements-- Color specifications (RGB vs. CMYK)-- Maximum number of display items-- Dimension requirements-- Font restrictions-- Whether to embed figures in manuscript or submit separately--### During Submission--**Prepare checklist:**-- [ ] All figures/tables numbered correctly-- [ ] All cited in text in order-- [ ] Captions complete and self-explanatory-- [ ] Abbreviations defined-- [ ] Correct file format and resolution-- [ ] Appropriate size/dimensions-- [ ] High enough quality for print-- [ ] Color-blind friendly (if using color)-- [ ] Permissions obtained (if adapting from others' work)--## Common Pitfalls to Avoid--### Content Issues-1. **Duplication** between text, tables, and figures-2. **Insufficient context** (unclear what is shown)-3. **Too much information** in one display-4. **Missing key information** (sample sizes, units, statistics)-5. **Cherry-picking** data without showing full picture--### Design Issues-6. **Poor color choices** (not color-blind friendly)-7. **Inconsistent formatting** across displays-8. **Cluttered or busy designs**-9. **Too small text** at final size-10. **Misleading visualizations** (truncated axes, 3D distortions)--### Technical Issues-11. **Insufficient resolution** (pixelated when printed)-12. **Wrong file format** (lossy compression, non-vector graphs)-13. **Improper image manipulation** (undeclared editing)-14. **Missing scale bars** on images-15. **Figures that don't work in grayscale** (if journal prints in B&W)--## Tools for Creating Figures--### Graphing Software-- **R (ggplot2)**: Highly customizable, publication-quality, reproducible-- **Python (matplotlib, seaborn)**: Flexible, programmable, widely used-- **GraphPad Prism**: User-friendly, statistics integrated, common in life sciences-- **Origin**: Advanced graphing, popular in physics/engineering-- **Excel**: Basic graphs, widely available, limited customization-- **MATLAB**: Technical computing, good for complex visualizations--### Image Processing-- **ImageJ/Fiji**: Free, powerful, widely used in microscopy-- **Adobe Photoshop**: Professional standard, extensive tools-- **GIMP**: Free alternative to Photoshop-- **Adobe Illustrator**: Vector graphics, figure assembly-- **Inkscape**: Free vector graphics editor--### Best Practices for Software Choice-- Use tools that produce vector output for graphs-- Learn one tool well rather than many superficially-- Script your figure generation for reproducibility-- Save original data files separately from figure files--## Journal-Specific Figure and Table Requirements--### Understanding Journal Expectations--**Different journals have vastly different requirements for figures and tables.** Before creating display items, always consult your target journal's author guidelines for specific requirements.--### Common Journal-Specific Variations--| Aspect | Variation by Journal | Example Journals |-|--------|---------------------|------------------|-| **Number allowed** | 4-10 display items for research articles | Nature (4-6), PLOS ONE (unlimited), Science (4-5) |-| **File format** | TIFF, EPS, PDF, AI, or specific formats | Nature (EPS/PDF for line art), Cell (TIFF preferred) |-| **Resolution** | 300-1000 dpi depending on type | JAMA (300-600 dpi), Nature (300+ dpi) |-| **Color** | RGB vs. CMYK | Print journals: CMYK; Online: RGB |-| **Dimensions** | Single vs. double column widths | Nature (89mm or 183mm), Science (specific templates) |-| **Figure legends** | Length limits, specific format | Some journals: 150 word max per legend |-| **Table format** | Editable vs. image | Most prefer editable tables, not images |--### Venue-Specific Requirements Summary--| Venue Type | Display Limit | Format | Resolution | Key Features |-|-----------|--------------|--------|------------|--------------|-| **Nature/Science** | 4-6 main | EPS/PDF/TIFF | 300+ dpi | Extended data allowed; multi-panel figures |-| **Medical journals** | 3-5 | TIFF/EPS | 300-600 dpi | CONSORT diagrams; conservative design |-| **PLOS ONE** | Unlimited | TIFF/EPS/PDF | 300+ dpi | Must work in grayscale |-| **ML conferences** | 4-6 in 8-page limit | PDF (vector preferred) | Print quality | Compact design; info-dense figures |--**ML Conference Figure Requirements:**--**NeurIPS/ICML/ICLR:**-- Figures count toward page limit (typically 8 pages including references)-- Vector graphics (PDF) preferred for plots-- High information density expected-- Supplementary material for additional figures-- LaTeX template provided (use neurips_2024.sty or equivalent)-- Figures must be legible when printed in grayscale--**Computer Vision (CVPR/ICCV/ECCV):**-- Qualitative results figures critical-- Side-by-side comparisons standard-- Must show failure cases-- Supplementary material for videos/additional examples-- Often 6-8 main figures in 8-page papers--**Key ML conference figure practices:**-- **Ablation studies**: Compact tables/plots showing component contributions-- **Architecture diagrams**: Clear, professional block diagrams-- **Performance plots**: Include error bars/confidence intervals-- **Qualitative examples**: Show diverse, representative samples-- **Comparison tables**: Concise, bold best results--### Evaluation Criteria Across Venues--**What reviewers check:**-- **Necessity**: Each figure/table supports conclusions-- **Quality**: Professional appearance, sufficient resolution-- **Clarity**: Self-explanatory with captions; proper labeling-- **Statistics**: Error bars, sample sizes, significance indicators-- **Consistency**: Formatting uniform across display items--**Common rejection reasons:**-- Poor resolution or image quality-- Missing error bars or sample sizes-- Unclear or missing labels-- Too many figures (exceeds venue limits)-- Figures duplicate text information--**ML conference specific evaluation:**-- **Ablation studies**: Must demonstrate component contributions-- **Baselines**: Comparison with relevant prior work required-- **Error bars**: Confidence intervals/std dev expected-- **Architecture diagrams**: Must be clear and informative-- **Space efficiency**: Information density valued (page limits strict)--### Caption/Legend Styles by Venue--| Venue Type | Style | Example Features |-|-----------|-------|------------------|-| **Nature/Science** | Concise | Brief; *P<0.05; minimal methods |-| **Medical** | Formal | Title case; 95% CIs; statistical tests spelled out |-| **PLOS/BMC** | Detailed | Complete sentences; all abbreviations defined |-| **ML conferences** | Technical | Architecture details; hyperparameters; dataset info |--**ML conference caption example:**-```-Figure 1. Architecture of proposed model. (a) Encoder with 12 transformer layers.-(b) Attention visualization. (c) Performance vs. baseline on ImageNet (error bars:-95% CI over 3 runs).-```-- Technical precision-- Hyperparameters when relevant-- Dataset/experimental setup details-- Compact to save space--### Quick Adaptation Guide--**When changing venues:**-- **Journal → ML conference**: Compress figures; increase information density; add hyperparameters to captions-- **ML conference → journal**: Expand captions; separate dense figures; add more methodological detail-- **Specialist → broad journal**: Simplify; add explanatory panels; define terms in captions-- **Broad → specialist journal**: Add technical detail; use field-standard plot types--### Pre-Submission Figure/Table Checklist--**Technical (all venues):**-- [ ] Meets format requirements (PDF/EPS/TIFF)-- [ ] Sufficient resolution (300+ dpi)-- [ ] Fits venue dimensions/page limits-- [ ] Self-explanatory captions-- [ ] All symbols/abbreviations defined-- [ ] Error bars defined; sample sizes noted--**ML conferences additional:**-- [ ] Figures fit in page limit (8-9 pages typical)-- [ ] Comparison with baselines shown-- [ ] Ablation studies included-- [ ] Architecture diagram clear-- [ ] Legible in grayscale--## Checklist for Final Review--### Before Submission--**For every figure:**-- [ ] High enough resolution (300+ dpi)?-- [ ] Correct file format per journal requirements?-- [ ] Correct dimensions for journal (single/double column)?-- [ ] Meets journal's RGB/CMYK requirements?-- [ ] Self-explanatory caption with all abbreviations defined?-- [ ] Caption length within journal limits?-- [ ] All symbols/colors explained in caption or legend?-- [ ] Error bars included and defined?-- [ ] Sample sizes noted?-- [ ] Statistical tests described?-- [ ] Axes labeled with units?-- [ ] Readable text at final print size?-- [ ] Works in grayscale or color-blind friendly?-- [ ] Referenced in text in correct order?-- [ ] Style matches target journal's published figures?--**For every table:**-- [ ] Clear, descriptive title?-- [ ] Title capitalization matches journal style?-- [ ] Column headers include units?-- [ ] Appropriate numerical precision?-- [ ] Abbreviations defined in footnotes?-- [ ] Statistical methods explained?-- [ ] Sample sizes included?-- [ ] Consistent formatting with other tables?-- [ ] Editable format (not image)?-- [ ] Referenced in text in correct order?-- [ ] Formatting matches target journal's tables?--**Overall:**-- [ ] Number of display items within journal limits?-- [ ] Appropriate number of display items (~1 per 1000 words)?-- [ ] No duplication between text, figures, and tables?-- [ ] Consistent formatting across all display items?-- [ ] All display items necessary (each tells important part of story)?-- [ ] Visual style matches target journal?-- [ ] Quality comparable to published examples in journal?+An accountable human should compare each display against source data and analysis+output, inspect permissions and confidentiality, verify captions and alt text, and+confirm the rendered export. Passing a file-format or consistency check does not certify+the display.diff --git a/skills/scientific-writing/references/imrad_structure.md b/skills/scientific-writing/references/imrad_structure.mdindex eda6607a..c53506c1 100644--- a/skills/scientific-writing/references/imrad_structure.md+++ b/skills/scientific-writing/references/imrad_structure.md@@ -1,686 +1,114 @@-# IMRAD Structure Guide+# Manuscript Structure and Consistency-## Overview+IMRAD is a useful default for many original-research reports, but the study design,+reporting guideline, article type, and current journal instructions control the final+structure [SW-S01, SW-S06].-IMRAD (Introduction, Methods, Results, And Discussion) is the predominant organizational structure for scientific journal articles of original research. Adopted as the majority format since the 1970s, it is now the standard in medical, health, biological, chemical, engineering, and computer sciences.+## Title and abstract-## Why IMRAD?+The title should identify the work accurately without adding novelty, causality, design,+or population claims that the manuscript does not support.-The IMRAD structure mirrors the scientific method:-- **Introduction**: What question did you ask?-- **Methods**: How did you study it?-- **Results**: What did you find?-- **Discussion**: What does it mean?+Draft the abstract after the main text. Mirror, do not reinterpret:-This logical flow makes scientific papers easier to write, read, and evaluate.+- objective or question;+- design, setting, population or material, and key methods;+- analysis population and prespecified primary result;+- estimate, uncertainty, denominator, and harms where relevant;+- conclusion limited to the reported evidence.-## Complete Manuscript Components--A full scientific manuscript typically includes these sections in order:--1. **Title**-2. **Abstract**-3. **Introduction**-4. **Methods** (also called Materials and Methods, Methodology)-5. **Results**-6. **Discussion** (sometimes combined with Results)-7. **Conclusion** (sometimes part of Discussion)-8. **Acknowledgments**-9. **References**-10. **Supplementary Materials** (if applicable)--## Title--### Purpose-Attract readers and accurately represent the paper's content.--### Guidelines-- Be concise yet descriptive (typically 10-15 words)-- Include key variables and the relationship studied-- Avoid abbreviations, jargon, and question formats (unless the journal allows)-- Make it specific enough to distinguish from other studies-- Include key search terms for discoverability--### Examples-- Good: "Effects of High-Intensity Interval Training on Cardiovascular Function in Older Adults"-- Too vague: "Exercise and Health"-- Too detailed: "A Randomized Controlled Trial Examining the Effects of High-Intensity Interval Training Compared to Moderate Continuous Training on Cardiovascular Function Measured by VO2 Max in Adults Aged 60-75 Years"--## Abstract--### Purpose-Provide a complete, standalone summary enabling readers to decide if the full paper is relevant to them.--### Format: Flowing Paragraphs (Default)--**⚠️ CRITICAL: Write abstracts as flowing paragraphs, NOT with labeled sections.**--Most scientific papers use **unstructured abstracts** written as one or two cohesive paragraphs. This is the standard format for the majority of journals including Nature, Science, Cell, PNAS, and most field-specific journals.--❌ **WRONG - Structured abstract with labels:**-```-Background: Hospital-acquired infections remain a major cause of morbidity.-Methods: We conducted a 12-month before-after study...-Results: Post-intervention, surface contamination decreased by 47%...-Conclusions: UV-C disinfection significantly reduced infection rates.-```--✅ **CORRECT - Flowing paragraph style:**-```-Hospital-acquired infections remain a major cause of morbidity, yet optimal-disinfection strategies remain unclear. We conducted a 12-month before-after-study in a 500-bed teaching hospital to evaluate UV-C disinfection added to-standard cleaning protocols. Environmental surfaces were cultured monthly and-infection rates tracked via surveillance data. Post-intervention, surface-contamination decreased by 47% (95% CI: 38-56%, p<0.001), and catheter-associated-urinary tract infections declined from 3.2 to 1.8 per 1000 catheter-days (RR=0.56,-95% CI: 0.38-0.83, p=0.004). No adverse effects were observed. These findings-demonstrate that UV-C disinfection significantly reduces environmental contamination-and infection rates, suggesting it may be a valuable addition to hospital infection-control programs.-```--### Abstract Structure (as unified paragraph)--While written as flowing prose, the abstract should cover these elements in order:--1. **Context and problem** (1-2 sentences): Why the research matters, what gap exists-2. **Study description** (1-2 sentences): What was done and how (study design, methods)-3. **Key findings** (2-4 sentences): Main results with specific quantitative data-4. **Significance** (1-2 sentences): Interpretation, implications, and conclusions--### Length-- Typically 150-300 words (check journal requirements)-- Some journals allow up to 350 words--### Key Rules-- Write the abstract **last** (after completing all other sections)-- **Write as flowing paragraph(s)** - no labeled sections-- Make it fully understandable without reading the paper-- Do not cite references in the abstract-- Avoid abbreviations or define them at first use-- Use past tense for methods and results, present tense for conclusions-- Include key quantitative results with statistical measures-- Use transitions to connect sentences naturally--### When to Use Structured Abstracts (Exception)--Only use labeled sections (Background/Objective, Methods, Results, Conclusions) when:-- The journal **explicitly requires** structured abstracts in their author guidelines-- Common in some medical journals (JAMA, BMJ, Annals of Internal Medicine)-- Always check journal requirements before formatting--Even for structured abstracts, write each section as complete sentences, not fragments.--### Example: Flowing Paragraph Abstract--```-Transcriptomic aging clocks offer unique advantages for assessing biological age by-capturing dynamic cellular states and acute responses to perturbations. Using the-ARCHS4 database containing uniformly processed RNA-seq data from over 1.2 million-human samples, we developed deep neural network models to predict chronological age-from gene expression profiles. Our best-performing model achieved a mean absolute-error of 4.2 years (R² = 0.89) on held-out test data, substantially outperforming-traditional machine learning approaches including elastic net regression (MAE = 6.8-years) and random forests (MAE = 5.9 years). Feature importance analysis identified-genes enriched in senescence, inflammation, and mitochondrial function pathways as-the strongest predictors. Cross-tissue validation revealed that lung and blood-samples yielded the most accurate predictions, while liver showed the highest-variance. These findings establish deep learning as a powerful approach for-transcriptomic age prediction and identify candidate biomarkers for biological-aging assessment.-```+Structured versus unstructured format is a venue decision. Do not apply a universal+format. Any number in the abstract must match the same concept and analysis set in the+main text and consistency registry.## Introduction-### Purpose-Convince readers that the research addresses an important question using an appropriate approach.--### Structure and Content--**Paragraph 1: The Big Picture**-- Establish the broad research area-- Explain why this topic matters-- Use present tense for established facts-- Keep it accessible to non-specialists--**Paragraphs 2-3: Narrowing Down**-- Review relevant prior research-- Show what is already known-- Identify controversies or limitations in existing work-- Create a logical progression toward the gap--**Paragraph 4: The Gap**-- Explicitly identify what remains unknown-- Explain why this knowledge gap is problematic-- Connect the gap to the big picture importance--**Final Paragraph: This Study**-- State the specific research question or hypothesis-- Describe the overall approach briefly-- Explain how this study addresses the gap-- Optional: Preview key findings (some journals discourage this)+Build a short evidence chain:-### Length-- Typically 1.5-2 pages (depending on journal)-- Usually 4-5 paragraphs-- Shorter for letters/brief communications+1. verified context;+2. what is known and uncertain;+3. the specific gap;+4. the objective, question, or prespecified hypothesis.-### Verb Tense-- **Present tense**: Established facts ("Exercise improves cardiovascular health")-- **Past tense**: Previous studies and their findings ("Smith et al. found that...")-- **Present/past tense**: Your study aims ("This study investigates..." or "This study investigated...")--### Common Mistakes to Avoid-- Starting too broad (e.g., "Since the beginning of time...")-- Exhaustive literature review (save for review articles)-- Citing irrelevant or outdated references-- Failing to identify a clear gap-- Weak justification for the study-- Not stating a clear research question or hypothesis-- Including methods or results (these belong in later sections)--### Key Questions to Answer-1. What do we know about this topic?-2. What don't we know? (the gap)-3. Why does this gap matter?-4. What did this study aim to find out?+Do not claim that no prior work exists unless a suitable search verifies that claim.+Avoid previewing unsupported results or inflating significance.## Methods-### Purpose-Provide sufficient detail for others to replicate the study and evaluate its validity.--### Key Principle-Another expert in the field should be able to repeat your experiment exactly as you performed it.--### Standard Subsections--#### Study Design-- State the overall design (e.g., randomized controlled trial, cohort study, cross-sectional survey)-- Justify the design choice if not obvious-- Mention blinding, randomization, or controls if applicable--#### Participants/Subjects/Sample-- Define the population of interest-- Describe inclusion and exclusion criteria precisely-- Report sample size and how it was determined (power analysis)-- Explain recruitment methods and setting-- For animals: specify species, strain, age, sex, housing conditions--#### Materials and Equipment-- List all materials, reagents, and equipment used-- Include manufacturer names and locations (in parentheses)-- Specify catalog numbers for specialized items-- Report software names and versions--#### Procedures-- Describe what was done in chronological order-- Include sufficient detail for replication-- Use subheadings to organize complex procedures-- Specify timing (e.g., "incubated for 2 hours at 37°C")-- For surveys/interviews: describe instruments, validation, administration--#### Measurements and Outcomes-- Define all variables measured-- Specify primary and secondary outcomes-- Describe measurement instruments and their validity-- Include units of measurement--#### Statistical Analysis-- Name all statistical tests used-- Justify test selection-- State significance level (typically α = 0.05)-- Report power analysis for sample size-- Name statistical software with version-- Describe handling of missing data-- Mention adjustments for multiple comparisons if applicable--#### Ethical Considerations-- State IRB/ethics committee approval (with approval number)-- Mention informed consent procedures-- For human studies: state adherence to Helsinki Declaration-- For animal studies: state adherence to relevant guidelines (e.g., ARRIVE)--### Length-- Typically 2-4 pages-- Proportional to study complexity--### Verb Tense-- **Past tense** for actions you performed ("We measured...", "Participants completed...")-- **Present tense** for established procedures ("PCR amplifies...", "The questionnaire contains...")--### Common Mistakes-- Insufficient detail for replication-- Methods appearing for the first time in Results-- Including results or discussion-- Missing statistical tests-- Undefined abbreviations-- Lack of ethical approval statement+Methods should permit evaluation and, where feasible, reproduction. Cover the elements+applicable to the design:++- design, setting, dates, and protocol or registration;+- participants, specimens, datasets, or source population;+- eligibility, selection, sampling, exclusions, and analysis populations;+- interventions, exposures, comparators, materials, instruments, and versions;+- outcomes, predictors, thresholds, time points, and measurement methods;+- bias controls, randomization, allocation, and masking where applicable;+- sample-size rationale;+- missing data, transformations, covariates, multiplicity, sensitivity analyses, and+ statistical or computational methods;+- confirmatory, exploratory, and descriptive status;+- ethics, consent, privacy, data governance, and approvals only when verified;+- data, code, materials, and protocol access conditions.++Record deviations and timing. Never reconstruct a method from a result merely to make+the paper appear consistent.## Results-### Purpose-Present the findings objectively without interpretation.--### Key Principle-Show, don't interpret. Save interpretation for the Discussion.--### Structure and Content--**Opening Paragraph**-- Describe the participants/sample characteristics-- Report recruitment flow (e.g., screened, enrolled, completed)-- Consider including a CONSORT-style flow diagram--**Subsequent Paragraphs**-- Present results in logical order (usually primary outcome first)-- Follow the order of objectives stated in Introduction-- Organize by theme or by chronology, depending on what's clearest-- Reference figures and tables by number--**Each Finding Should Include:**-- The observed result-- The direction of the effect-- The magnitude of the effect-- The statistical significance-- The confidence interval--**Example**: "Mean systolic blood pressure decreased by 12 mmHg in the intervention group compared to 3 mmHg in controls (difference: 9 mmHg, 95% CI: 4-14 mmHg, p=0.002)."--### Integration with Figures and Tables--**When to Use:**-- **Figures**: Trends, patterns, distributions, comparisons, relationships-- **Tables**: Precise values, demographic data, multiple variables--**How to Reference:**-- "Figure 1 shows the distribution of..." (not "Figure 1 below")-- "Table 2 presents baseline characteristics..."-- Don't repeat all table data in text; highlight key findings-- Each figure/table should be referenced in text--### Figures and Tables Guidelines-- Number consecutively in order of mention-- Include complete, standalone captions-- Define all abbreviations in caption or footnote-- Report sample sizes (n)-- Indicate statistical significance (*, p-values)-- Use consistent formatting--### Statistical Reporting--**Required Elements:**-- Test statistic (t, F, χ², etc.)-- Degrees of freedom-- p-value (exact if p > 0.001, otherwise report as "p < 0.001")-- Effect size and confidence interval-- Sample sizes--**Example**: "Groups differed significantly on test performance (t(48) = 3.21, p = 0.002, Cohen's d = 0.87, 95% CI: 0.34-1.40)."+Follow the declared objectives and outcomes. Report:-### Length-- Typically 2-4 pages-- Roughly equivalent to Methods length+- participant, sample, or record flow;+- exclusions, missingness, attrition, and analysis populations;+- descriptive information needed for interpretation;+- prespecified primary and secondary results;+- estimates with units, denominators, sample sizes, and uncertainty;+- exploratory, sensitivity, subgroup, negative, null, adverse, unexpected, and+ inconclusive findings with correct labels;+- protocol or analysis deviations that affect interpretation.-### Verb Tense-- **Past tense** for your findings ("The mean was...", "Participants showed...")--### Common Mistakes-- Interpreting results (save for Discussion)-- Repeating all table/figure data in text-- Presenting new methods-- Insufficient statistical detail-- Inconsistent units or notation-- Not addressing negative or unexpected findings-- Selective reporting (all tested hypotheses should be reported)--### Organization Strategies--**By Objective:**-```-Effect of intervention on primary outcome-Effect of intervention on secondary outcome A-Effect of intervention on secondary outcome B-```--**By Analysis Type:**-```-Descriptive statistics-Univariate analyses-Multivariate analyses-```--**Chronological:**-```-Baseline characteristics-Short-term outcomes (1 month)-Long-term outcomes (6 months)-```+Describe results before interpretation unless the venue combines Results and+Discussion. Do not equate a threshold crossing with scientific or practical importance.## Discussion-### Purpose-Interpret findings, relate them to existing knowledge, acknowledge limitations, and propose future directions.--### Structure and Content--**Paragraph 1: Summary of Main Findings**-- Restate the primary objective or hypothesis-- Summarize the principal findings in 2-4 sentences-- Avoid repeating details from Results-- State clearly whether the hypothesis was supported--**Paragraphs 2-4: Interpretation in Context**-- Compare your findings with previous research-- Explain agreements and disagreements with prior work-- Propose mechanisms or explanations for findings-- Discuss unexpected results-- Consider alternative explanations-- Address whether findings support or refute existing theories--**Paragraph 5: Strengths and Limitations**-- Acknowledge study limitations honestly-- Explain how limitations might affect interpretation-- Mention study strengths (design, sample, methods)-- Avoid generic limitations ("larger sample needed")—be specific--**Paragraph 6: Implications**-- Clinical implications (for medical research)-- Practical applications-- Policy implications-- Theoretical contributions--**Final Paragraph: Conclusions and Future Directions**-- Summarize the take-home message-- Suggest specific future research to address gaps or limitations-- End with a strong concluding statement--### Length-- Typically 3-5 pages-- Usually the longest section--### Verb Tense-- **Past tense**: Your study findings ("We found that...", "The results showed...")-- **Present tense**: Established facts and your interpretations ("This suggests that...", "These findings indicate...")-- **Future tense**: Implications and future research ("Future studies should investigate...")--### Discussion Strategies--**Comparing to Prior Work:**-```-"Our finding of a 30% reduction in symptoms aligns with Smith et al. (2023), who-reported a 28% reduction using a similar intervention. However, Jones et al. (2022)-found no significant effect, possibly due to their use of a less intensive protocol."-```--**Proposing Mechanisms:**-```-"The observed improvement in cognitive function may result from increased cerebral-blood flow, as evidenced by the concurrent increase in functional MRI signals in the-prefrontal cortex. This interpretation is consistent with the vascular hypothesis of-cognitive enhancement."-```--**Acknowledging Limitations:**-```-"The cross-sectional design prevents causal inference. Additionally, the convenience-sample from a single academic medical center may limit generalizability to community-settings. Self-reported measures may introduce recall bias, though we attempted to-minimize this through structured interviews."-```--### Common Mistakes-- Simply repeating results without interpretation-- Over-interpreting findings or claiming causation without warrant-- Ignoring inconsistent or negative findings-- Failing to compare with existing literature-- Introducing new data or methods-- Generic or superficial discussion of limitations-- Overgeneralization beyond the study population-- Missing the "so what?"—failing to explain significance--### Key Questions to Answer-1. What do these findings mean?-2. How do they compare to prior research?-3. Why might differences exist?-4. What are alternative explanations?-5. What are the limitations?-6. What are the practical implications?-7. What should future research investigate?--## Conclusion--### Purpose-Provide a concise summary of key findings and their significance.--### Placement-- May be a separate section or the final paragraph of Discussion (check journal requirements)--### Content-- 1-2 paragraphs maximum-- Restate the main finding(s)-- Emphasize the significance or implications-- End with a strong, memorable statement-- Do NOT introduce new information--### Example-```-This randomized trial demonstrates that a 12-week mindfulness intervention significantly-reduces anxiety symptoms in college students, with effects persisting at 6-month follow-up.-These findings support the integration of mindfulness-based programs into university mental-health services. Given the scalability and cost-effectiveness of group-based mindfulness-training, this approach offers a promising strategy to address the growing mental health-crisis in higher education.-```--## Additional Sections--### Acknowledgments-- Thank funding sources (with grant numbers)-- Acknowledge substantial contributions not qualifying for authorship-- Thank those who provided materials, equipment, or assistance-- Declare any conflicts of interest--### References-- Format according to journal style (see `citation_styles.md`)-- Verify all citations are accurate-- Ensure all citations appear in text and vice versa-- Typical range: 20-50 references for original research--### Supplementary Materials-- Additional figures, tables, or data sets-- Detailed protocols or questionnaires-- Video or audio files-- Large datasets or code repositories--## Tense Usage Summary--| Section | Verb Tense |-|---------|-----------|-| Abstract - Background | Present (established facts) or past (prior studies) |-| Abstract - Methods | Past |-| Abstract - Results | Past |-| Abstract - Conclusions | Present |-| Introduction - General background | Present |-| Introduction - Prior studies | Past |-| Introduction - Your objectives | Present or past |-| Methods | Past (your actions), present (general procedures) |-| Results | Past |-| Discussion - Your findings | Past |-| Discussion - Interpretations | Present |-| Discussion - Prior work | Present or past |-| Conclusion | Present |--## IMRAD Variations--### Combined Results and Discussion-- Some journals allow or require this format-- Interweaves presentation and interpretation-- Each result is presented then immediately discussed-- Useful for complex studies with multiple experiments--### IMRaD without separate Conclusion-- Conclusion integrated into final Discussion paragraph-- Common in many journals--### Extended IMRAD (ILMRaD)-- Adds "Literature Review" as separate section-- More common in theses and dissertations--## Adapting IMRAD to Different Study Types--### Clinical Trials-- Add CONSORT flow diagram in Results-- Include trial registration number in Methods-- Report adverse events in Results--### Systematic Reviews/Meta-Analyses-- Methods describes search strategy and inclusion criteria-- Results includes PRISMA flow diagram and synthesis-- May have additional sections (risk of bias assessment)--### Case Reports-- Introduction: background on the condition-- Case Presentation: replaces Methods and Results-- Discussion: relates case to literature--### Observational Studies-- Follow STROBE guidelines-- Careful attention to potential confounders in Methods-- Discussion addresses causality limitations--## Venue-Specific Structure Expectations--### Journal vs. Conference Formats--| Venue Type | Length | Structure | Methods Placement | Key Focus |-|-----------|--------|-----------|-------------------|-----------|-| **Nature/Science** | 2,000-4,500 words | Modified IMRAD | Supplement | Broad significance |-| **Medical** | 2,700-3,500 words | Strict IMRAD | Main text | Clinical outcomes |-| **Field journals** | 3,000-6,000 words | Standard IMRAD | Main text | Technical depth |-| **ML conferences** | 8-9 pages (~6,000 words) | Intro-Method-Experiments-Conclusion | Main text (concise) | Novel contribution |--### ML Conference Structure (NeurIPS/ICML/ICLR)--**Typical 8-page structure:**-1. **Abstract** (150-200 words): Problem, method, key results-2. **Introduction** (1 page): Motivation, contribution summary, related work overview-3. **Method** (2-3 pages): Technical approach, architecture, algorithms-4. **Experiments** (2-3 pages): Setup, datasets, baselines, results, ablations-5. **Related Work** (0.5-1 page, often in appendix): Detailed literature comparison-6. **Conclusion** (0.25-0.5 pages): Summary, limitations, future work-7. **References** (within page limit or separate depending on conference)-8. **Appendix/Supplement** (unlimited): Additional experiments, proofs, details--**Key differences from journals:**-- **Contribution bullets**: Often numbered list in intro (e.g., "Our contributions are: (1)... (2)... (3)...")-- **No separate Results/Discussion**: Integrated in Experiments section-- **Ablation studies**: Critical component showing what matters-- **Computational requirements**: Often required (training time, GPUs, memory)-- **Code availability**: Increasingly expected--### Section Length Proportions--| Venue | Intro | Methods | Results/Experiments | Discussion/Conclusion |-|-------|-------|---------|---------------------|----------------------|-| **Nature/Science** | 10% | 15%* | 40% | 35% |-| **Medical (NEJM/JAMA)** | 10% | 25% | 30% | 35% |-| **Field journals** | 20% | 25% | 30% | 25% |-| **ML conferences** | 12-15% | 30-35% | 40-45% | 5-8% |--*Methods often in supplement for Nature/Science--**Key medical journal features:**-- NEJM/Lancet/JAMA: Strict IMRAD; clinical focus; structured Discussion; CONSORT/STROBE compliance-- Clear primary/secondary outcomes; statistical pre-specification--**Key ML conference features:**-- Numbered contribution list in intro-- Method details with pseudocode/equations-- Extensive experiments: main results, ablations, analysis-- Brief conclusion (limitations noted)-- Related work often in appendix--### Writing Style by Venue--| Venue | Audience | Intro Focus | Methods Detail | Results/Experiments | Discussion/Conclusion |-|-------|----------|-------------|----------------|---------------------|----------------------|-| **Nature/Science** | Non-specialists | Broad significance | Brief, supplement | Story-driven | Broad implications |-| **Medical** | Clinicians | Clinical problem | Comprehensive | Primary outcome first | Clinical relevance |-| **Specialized** | Experts | Field context | Full technical | By experiment | Mechanistic depth |-| **ML conferences** | ML researchers | Novel contribution | Reproducible | Baselines, ablations | Brief, limitations |--**ML conference emphasis:**-- **Introduction**: Clear problem statement; numbered contributions; positioning vs. prior work-- **Method**: Mathematical notation; pseudocode; architecture diagrams; complexity analysis-- **Experiments**: Datasets described; multiple baselines; ablation studies; error analysis-- **Conclusion**: Summary; acknowledged limitations; broader impact (if required)--### Evaluation Across Venues--**What gets checked:**-- **Fit**: Appropriate for venue scope and audience-- **Length**: Within limits (strict for conferences)-- **Clarity**: Writing quality sufficient; claims supported-- **Reproducibility**: Methods enable replication-- **Completeness**: All outcomes reported; limitations acknowledged+Start from the verified findings, then:-**Common rejection reasons:**-- Insufficient significance for venue-- Methods lack detail for reproduction-- Results don't support claims-- Discussion overstates findings-- Page/word limits exceeded (conferences strict)+- answer the objective at the supported level of certainty;+- compare with verified prior evidence;+- consider alternative explanations;+- distinguish statistical, scientific, clinical, and practical interpretation;+- explain limitations and likely consequences;+- bound generalizability to the studied population, material, setting, and period;+- identify implications without prescribing action beyond the evidence.-**ML conference specific evaluation:**-- Clear problem formulation and motivation-- Novelty and contribution well-articulated-- Baselines comprehensive and fair-- Ablation studies demonstrate what works-- Code/data availability (increasingly required)-- Reproducibility information (seeds, hyperparameters)+Do not introduce new results, methods, approvals, or citations that bypass verification.-### Quick Adaptation Guide+## Declarations and end matter-**Journal → ML conference:**-- Condense intro; add numbered contributions-- Methods: keep concise, add pseudocode-- Combine Results+Discussion → Experiments section-- Add extensive ablations and baseline comparisons-- Brief conclusion with limitations+Treat each statement as data, not boilerplate:-**ML conference → Journal:**-- Expand introduction with more background-- Separate Methods section with full details-- Split Experiments into Results and Discussion-- Remove contribution numbering-- Expand limitations discussion+- author contributions and accountability;+- acknowledgments and permissions;+- funding and the funder's role;+- competing interests;+- ethics, consent, and registration;+- data, code, materials, and protocol availability;+- AI-use disclosure;+- references, figure legends, tables, and supplements.-**Specialist → Broad journal:**-- Simplify intro; emphasize broad significance-- Move technical methods to supplement-- Story-driven results organization-- Lead discussion with implications+Use verified or explicit not-applicable states. Never generate an approval identifier,+grant number, registration, author role, conflict declaration, or availability promise.-**Broad → Specialist:**-- Add detailed literature review-- Full methods in main text-- Organize results by experiment-- Add mechanistic discussion depth+## Cross-section audit-### Pre-Submission Structure Checklist+Before submission, compare:-**All venues:**-- [ ] Word/page count within limits-- [ ] Section proportions appropriate-- [ ] Writing style matches venue-- [ ] Methods enable reproducibility-- [ ] Limitations acknowledged+- objective ↔ outcome ↔ result ↔ conclusion;+- methods ↔ results;+- abstract ↔ main text ↔ tables ↔ figures ↔ supplement;+- units, denominators, sample sizes, labels, and time points;+- registration and protocol ↔ manuscript;+- in-text citations ↔ source manifest ↔ reference list.-**ML conferences add:**-- [ ] Contributions clearly listed-- [ ] Ablation studies included-- [ ] Baselines comprehensive-- [ ] Hyperparameters/seeds reported-- [ ] Code availability statement+Run `scripts/check_consistency.py` and complete a manual scientific review.diff --git a/skills/scientific-writing/references/journal_policies.md b/skills/scientific-writing/references/journal_policies.mdnew file mode 100644index 00000000..d68d4d8f--- /dev/null+++ b/skills/scientific-writing/references/journal_policies.md@@ -0,0 +1,56 @@+# Journal and Publisher Policy Review++Generic guidance never overrides the target journal's current instructions.++## Capture a dated policy record++Before drafting and again before submission, record:++- journal, article type, and policy URL;+- date accessed;+- word, abstract, reference, table, figure, and supplement limits;+- required structure and reporting guideline;+- registration, protocol, and analysis-plan requirements;+- ethics, consent, participant privacy, and image requirements;+- authorship, contributor, acknowledgment, and change-of-authorship rules;+- funding, conflicts, and sponsor-role disclosures;+- data, code, materials, and repository policies;+- preprint, prior dissemination, duplicate submission, and copyright policies;+- AI use by authors and any restrictions on external tools;+- peer-review model and confidentiality;+- file, accessibility, and submission-system requirements.++Do not guess an absent policy. Ask the journal or leave the decision unresolved.++## Official examples++- JAMA's current Instructions for Authors illustrate article-type-specific requirements+ and should be consulted directly for a JAMA submission [SW-S25].+- JAMA's AI guidance illustrates author disclosure, human responsibility, and+ confidentiality limits for peer review [SW-S24].+- Nature Portfolio's reporting and availability policy illustrates venue requirements+ for data, materials, code, protocols, restrictions, and access [SW-S22].+- Nature Portfolio's authorship policy illustrates publisher-specific accountability+ and contribution statements [SW-S23].+- PLOS Biology's data policy illustrates how sharing expectations interact with+ consent, privacy, legal, ethical, and sensitive-data restrictions [SW-S26].++These are examples, not defaults for other journals. Publisher-level policy and+journal-level instructions may both apply.++## Submission review++Perform a manual comparison against the live instructions:++1. Select the exact article type.+2. Confirm the latest reporting guideline and extensions.+3. Verify every required statement from source records.+4. Confirm whether checklists or flow diagrams must be uploaded.+5. Confirm data, code, and materials deposits actually exist and are accessible as+ stated.+6. Confirm author order, corresponding author, CRediT roles, and approvals.+7. Confirm AI-use disclosure wording and location with the human authors.+8. Verify files, anonymization, accessibility, permissions, and metadata.+9. Save the access date and policy URLs in the submission record.++Passing local tools does not establish venue compliance.diff --git a/skills/scientific-writing/references/professional_report_formatting.md b/skills/scientific-writing/references/professional_report_formatting.mdindex 58c581c1..6238874a 100644--- a/skills/scientific-writing/references/professional_report_formatting.md+++ b/skills/scientific-writing/references/professional_report_formatting.md@@ -1,664 +1,82 @@-# Professional Report Formatting for Scientific Documents+# Safe Formatting for Reports and Manuscripts-This reference guide covers professional formatting for scientific reports, technical documents, and white papers. Use the `scientific_report.sty` LaTeX style package for consistent, professional output.+## Content before presentation----+The former LaTeX style and demonstration report were removed. They could turn+plausible-looking placeholder findings into a polished PDF. This version uses+format-neutral Markdown and JSON/CSV registries so incompleteness remains visible.-## When to Use Professional Report Formatting+Do not format a draft as submission-ready while any verification gate is incomplete.+Visual polish is not evidence.-### Use This Style For:+## Workflow-- **Research reports** - Internal and external research summaries-- **Technical reports** - Detailed technical documentation and analyses-- **White papers** - Position papers and thought leadership documents-- **Grant reports** - Progress reports and final grant reports-- **Policy briefs** - Research-informed policy recommendations-- **Industry reports** - Technical reports for industry audiences-- **Internal research summaries** - Team and stakeholder communications-- **Feasibility studies** - Technical and research feasibility assessments-- **Project documentation** - Research project deliverables+1. Create a local scaffold.+2. Draft and verify content in Markdown.+3. Run manifest, claim, reference, consistency, authorship, coverage, and lint checks.+4. Obtain accountable human approval.+5. Copy the verified content into the current venue template.+6. Re-run checks that remain applicable and inspect the rendered output manually.-### Do NOT Use This Style For:+For a journal or conference, use its current author instructions and official template.+For an institutional report or thesis, use the institution's controlled template.-- **Journal manuscripts** → Use `venue-templates` skill for journal-specific formatting-- **Conference papers** → Use `venue-templates` skill for conference requirements-- **Academic theses/dissertations** → Use institutional templates-- **Peer-reviewed submissions** → Follow journal author guidelines+## Fail-closed placeholder policy-**Key Distinction**: Professional report formatting prioritizes visual appeal and readability for general audiences, while journal manuscripts must follow strict publisher requirements.+Permitted draft markers are intentionally conspicuous, such as `[[TODO:...]]`. The+language linter treats them as errors. Never replace an unresolved marker with generic+boilerplate, a guessed number, a fabricated statement, or an invented citation.----+Keep:-## Overview of scientific_report.sty+- `submission_ready` false;+- the draft banner visible;+- missing declaration statuses explicit;+- human and confidentiality gates incomplete;-The `scientific_report.sty` package provides:+until the underlying records are verified.-| Feature | Description |-|---------|-------------|-| Typography | Helvetica font family for modern, professional appearance |-| Color Scheme | Coordinated blues, greens, oranges, and purples |-| Box Environments | Colored boxes for organizing content types |-| Tables | Professional styling with alternating rows |-| Figures | Consistent caption formatting |-| Headers/Footers | Professional page headers and footers |-| Scientific Commands | Shortcuts for p-values, effect sizes, statistics |+## Headings and navigation-### Basic Document Setup+- Use a single title and logical heading levels.+- Preserve heading order when converting formats.+- Include lists of tables or figures only when useful or required.+- Use stable internal labels for tables, figures, appendices, and supplements.+- Ensure generated bookmarks and reading order match the visible structure.-```latex-\documentclass[11pt,letterpaper]{report}-\usepackage{scientific_report}+## Typography and layout-\begin{document}-% Your content here-\end{document}-```+- Use the venue's prescribed font, spacing, margins, page size, and line numbering.+- Do not use color, weight, or position as the only carrier of meaning.+- Keep equations, symbols, units, subscripts, and superscripts intact through+ conversion.+- Check widows, orphans, clipped content, broken links, and misplaced floats manually.-**Compilation**: Use XeLaTeX or LuaLaTeX for proper Helvetica font rendering:-```bash-xelatex document.tex-```+## Tables, figures, and accessibility----+Follow `figures_tables.md`. Verify alt text, captions, provenance, permissions, color+independence, reading order, label legibility, and final-size rendering. Do not create a+decorative visual simply to make a report appear complete.-## Box Environments for Content Organization+## References and declarations-### Purpose and Usage+References must render from verified metadata. After conversion, inspect identifier+links, special characters, author order, and citation order.-Colored boxes help readers quickly identify different types of content. Use them strategically to highlight important information.+Declarations must come from validated records. A style template must never supply a+default ethics approval, consent statement, funding source, conflict statement, author+contribution, data or code promise, or AI disclosure.-### Available Box Environments+## Archival handoff-| Environment | Color | Purpose |-|-------------|-------|---------|-| `keyfindings` | Blue | Major findings, discoveries, key takeaways |-| `methodology` | Green | Methods, procedures, study design |-| `resultsbox` | Blue-green | Statistical results, data highlights |-| `recommendations` | Purple | Recommendations, action items, implications |-| `limitations` | Orange | Limitations, cautions, caveats |-| `criticalnotice` | Red | Critical warnings, safety notices |-| `definition` | Gray | Definitions, notes, supplementary info |-| `executivesummary` | Blue (shadow) | Executive summaries |-| `hypothesis` | Light blue | Research hypotheses |+Retain:-### Key Findings Box--Use for major findings and important discoveries:--```latex-\begin{keyfindings}[Research Highlights]-Our analysis revealed three significant findings:-\begin{enumerate}- \item Treatment A was 40% more effective than control (\pvalue{0.001})- \item Effect sizes were clinically meaningful (\effectsize{d}{0.82})- \item Benefits persisted at 12-month follow-up-\end{enumerate}-\end{keyfindings}-```--**Best Practices:**-- Use sparingly (1-3 per chapter maximum)-- Reserve for genuinely important findings-- Include specific numbers and statistics-- Write concisely--### Methodology Box--Use for highlighting methods and procedures:--```latex-\begin{methodology}[Study Design]-This double-blind, randomized controlled trial employed a 2×2 factorial-design. Participants (\samplesize{450}) were randomized to one of four-conditions: (1) Treatment A, (2) Treatment B, (3) Combined A+B, or-(4) Placebo control.-\end{methodology}-```--**Best Practices:**-- Summarize key methodological features-- Use at the start of methods sections-- Include sample size and design type-- Keep technical but accessible--### Results Box--Use for highlighting specific statistical results:--```latex-\begin{resultsbox}[Primary Outcome Analysis]-Mixed-effects regression revealed a significant treatment × time-interaction, \effectsize{F(3, 446)}{8.72}, \psig{< 0.001},-$\eta^2_p$ = 0.055, indicating differential improvement across-treatment conditions over the study period.-\end{resultsbox}-```--**Best Practices:**-- Report complete statistical information-- Use scientific notation commands-- Include effect sizes alongside p-values-- One box per major analysis--### Recommendations Box--Use for recommendations and implications:--```latex-\begin{recommendations}[Clinical Practice Guidelines]-Based on our findings, we recommend:-\begin{enumerate}- \item \textbf{Primary recommendation:} Implement screening protocol- for high-risk populations.- \item \textbf{Secondary recommendation:} Adjust treatment intensity- based on baseline severity scores.- \item \textbf{Monitoring:} Reassess at 3-month intervals.-\end{enumerate}-\end{recommendations}-```--**Best Practices:**-- Make recommendations specific and actionable-- Prioritize with clear labels-- Link to supporting evidence-- Include implementation guidance--### Limitations Box--Use for limitations, caveats, and cautions:--```latex-\begin{limitations}[Study Limitations]-Several limitations should be considered:-\begin{itemize}- \item \textbf{Sample:} Participants were recruited from academic- medical centers, limiting generalizability to community settings.- \item \textbf{Design:} The observational design precludes causal- inference about treatment effects.- \item \textbf{Attrition:} 15% dropout rate may introduce bias.-\end{itemize}-\end{limitations}-```--**Best Practices:**-- Be honest and thorough-- Explain implications of each limitation-- Suggest how future research could address limitations-- Don't over-qualify findings--### Critical Notice Box--Use for critical warnings or safety information:--```latex-\begin{criticalnotice}[Safety Warning]-\textbf{Contraindication:} This intervention is contraindicated for-patients with [condition]. Monitor for [adverse effects] and discontinue-immediately if [symptoms] occur. Report serious adverse events to [contact].-\end{criticalnotice}-```--**Best Practices:**-- Reserve for genuinely critical information-- Be clear and direct-- Include specific actions to take-- Provide contact information if relevant--### Definition Box--Use for definitions and explanatory notes:--```latex-\begin{definition}[Effect Size]-An \textbf{effect size} is a quantitative measure of the magnitude of a-phenomenon. Unlike significance tests, effect sizes are independent of-sample size and allow comparison across studies. Common measures include-Cohen's \textit{d} for mean differences and Pearson's \textit{r} for-correlations.-\end{definition}-```--**Best Practices:**-- Define technical terms at first use-- Keep definitions concise-- Include practical interpretation guidance-- Use for audience-appropriate terms-------## Professional Table Formatting--### Design Principles--1. **Clean appearance**: Use `booktabs` rules (`\toprule`, `\midrule`, `\bottomrule`)-2. **Alternating rows**: Apply `\rowcolor{tablealt}` to every other row-3. **Clear headers**: Bold headers for column identification-4. **Appropriate precision**: Report statistics to appropriate decimal places-5. **Complete information**: Include sample sizes, units, and notes--### Standard Data Table--```latex-\begin{table}[htbp]-\centering-\caption{Demographic Characteristics by Treatment Group}-\label{tab:demographics}-\begin{tabular}{@{}lcc@{}}-\toprule-\textbf{Characteristic} & \textbf{Treatment} & \textbf{Control} \\- & (\samplesize{225}) & (\samplesize{225}) \\-\midrule-Age, years, \meansd{M}{SD} & \meansd{42.3}{12.5} & \meansd{43.1}{11.8} \\-\rowcolor{tablealt} Female, n (\%) & 128 (56.9) & 121 (53.8) \\-Education, years, \meansd{M}{SD} & \meansd{14.2}{2.8} & \meansd{14.5}{2.6} \\-\rowcolor{tablealt} Baseline score, \meansd{M}{SD} & \meansd{52.4}{15.3} & \meansd{51.8}{14.9} \\-\bottomrule-\end{tabular}-\figurenote{No significant differences between groups at baseline (all \textit{p} > .10).}-\end{table}-```--### Results Table with Significance Indicators--```latex-\begin{table}[htbp]-\centering-\caption{Treatment Effects on Primary and Secondary Outcomes}-\label{tab:results}-\begin{tabular}{@{}lcccc@{}}-\toprule-\textbf{Outcome} & \textbf{Treatment} & \textbf{Control} & \textbf{Effect} & \textbf{p} \\- & \meansd{M}{SD} & \meansd{M}{SD} & \textbf{(d)} & \\-\midrule-Primary outcome & \meansd{68.4}{14.2} & \meansd{54.1}{15.8} & 0.95\sigthree & <.001 \\-\rowcolor{tablealt} Secondary A & \meansd{4.2}{1.1} & \meansd{3.5}{1.2} & 0.61\sigtwo & .003 \\-Secondary B & \meansd{22.8}{5.4} & \meansd{21.2}{5.1} & 0.31\sigone & .042 \\-\rowcolor{tablealt} Secondary C & \meansd{8.9}{2.3} & \meansd{8.5}{2.4} & 0.17\signs & .285 \\-\bottomrule-\end{tabular}--\vspace{0.5em}-{\small \siglegend}-\end{table}-```--### Comparison Table with Quality Ratings--```latex-\begin{table}[htbp]-\centering-\caption{Evidence Summary by Study}-\label{tab:evidence}-\begin{tabular}{@{}llccc@{}}-\toprule-\textbf{Study} & \textbf{Design} & \textbf{N} & \textbf{Quality} & \textbf{Evidence} \\-\midrule-Smith et al. (2024) & RCT & 450 & \qualityhigh & \evidencestrong \\-\rowcolor{tablealt} Jones et al. (2023) & Cohort & 1,250 & \qualitymedium & \evidencemoderate \\-Chen et al. (2023) & Case-control & 320 & \qualitymedium & \evidencemoderate \\-\rowcolor{tablealt} Lee et al. (2022) & Cross-sectional & 890 & \qualitylow & \evidenceweak \\-\bottomrule-\end{tabular}-\end{table}-```-------## Figure and Caption Styling--### Caption Formatting--The style package automatically formats captions with:-- Blue, bold figure labels-- Gray descriptive text-- Centered alignment with margins--### Standard Figure--```latex-\begin{figure}[htbp]-\centering-\includegraphics[width=0.9\textwidth]{../figures/results_comparison.png}-\caption{Comparison of Outcome Scores by Treatment Condition and Time Point}-\label{fig:results}-\end{figure}-```--### Figure with Source Attribution--```latex-\begin{figure}[htbp]-\centering-\includegraphics[width=0.85\textwidth]{../figures/trend_analysis.png}-\caption{Trends in Key Metrics Over the Study Period}-\figuresource{Study data collected January--December 2024}-\label{fig:trends}-\end{figure}-```--### Figure with Explanatory Note--```latex-\begin{figure}[htbp]-\centering-\includegraphics[width=0.8\textwidth]{../figures/conceptual_model.png}-\caption{Conceptual Model of Hypothesized Relationships}-\figurenote{Solid arrows indicate primary pathways; dashed arrows indicate moderated relationships. Numbers represent standardized coefficients.}-\label{fig:model}-\end{figure}-```-------## Color Palette and Visual Hierarchy--### Color Usage Guidelines--| Color | Use For | Avoid Using For |-|-------|---------|-----------------|-| Primary Blue | Headers, important findings | Warnings, cautions |-| Science Green | Methods, positive results | Negative findings |-| Orange | Cautions, limitations | Positive findings |-| Red | Critical warnings | Routine content |-| Purple | Recommendations | Findings, methods |-| Gray | Definitions, notes | Key findings |--### Visual Hierarchy--1. **Executive summary boxes** (shadow effect) - Most prominent-2. **Colored content boxes** - High prominence for key content-3. **Tables with color** - Medium prominence for data-4. **Body text** - Standard prominence-5. **Definition boxes** - Lower prominence for supplementary info--### Accessibility Considerations--- Color palette is designed to be distinguishable for common color vision deficiencies-- All boxes have both color AND structural indicators (borders, backgrounds)-- Text maintains sufficient contrast ratios-- Don't rely solely on color to convey meaning-------## Typography Guidelines--### Font Specifications--| Element | Font | Size | Color |-|---------|------|------|-------|-| Body text | Helvetica | 11pt | Dark gray (#424242) |-| Chapter titles | Helvetica Bold | Huge | Primary blue (#003366) |-| Section headings | Helvetica Bold | Large | Primary blue (#003366) |-| Subsections | Helvetica Bold | large | Secondary blue (#4A90E2) |-| Subsubsections | Helvetica Bold | normalsize | Dark gray (#424242) |--### Spacing--- Line spacing: 1.15 (for readability)-- Paragraph spacing: 0.5em between paragraphs-- Page margins: 1 inch on all sides--### Best Typography Practices--1. **Consistency**: Use the same formatting for similar elements-2. **Hierarchy**: Use visual weight to indicate importance-3. **Readability**: Adequate spacing and contrast-4. **Professionalism**: Avoid mixing fonts or excessive formatting-------## Scientific Notation Commands Reference--### Statistical Reporting--| Command | Output | When to Use |-|---------|--------|-------------|-| `\pvalue{0.023}` | *p* = 0.023 | Report p-values |-| `\psig{< 0.001}` | ***p*** = < 0.001 | Significant p-values (bold) |-| `\CI{0.45}{0.72}` | 95% CI [0.45, 0.72] | Confidence intervals |-| `\effectsize{d}{0.75}` | d = 0.75 | Effect sizes |-| `\samplesize{250}` | *n* = 250 | Sample sizes |-| `\meansd{42.5}{8.3}` | 42.5 ± 8.3 | Mean with SD |--### Significance Indicators--| Command | Output | Meaning |-|---------|--------|---------|-| `\sigone` | * | p < 0.05 |-| `\sigtwo` | ** | p < 0.01 |-| `\sigthree` | *** | p < 0.001 |-| `\signs` | ns | not significant |-| `\siglegend` | Full legend | For table footnotes |--### Quality and Evidence Ratings--| Command | Output | Meaning |-|---------|--------|---------|-| `\qualityhigh` | **HIGH** (green) | High quality |-| `\qualitymedium` | **MEDIUM** (orange) | Moderate quality |-| `\qualitylow` | **LOW** (red) | Low quality |-| `\evidencestrong` | **Strong** (green) | Strong evidence |-| `\evidencemoderate` | **Moderate** (orange) | Moderate evidence |-| `\evidenceweak` | **Weak** (red) | Weak evidence |--### Trend Indicators--| Command | Symbol | Meaning |-|---------|--------|---------|-| `\trendup` | ▲ (green) | Increasing trend |-| `\trenddown` | ▼ (red) | Decreasing trend |-| `\trendflat` | → (gray) | Stable/no change |-------## Complete LaTeX Examples--### Executive Summary Example--```latex-\chapter*{Executive Summary}-\addcontentsline{toc}{chapter}{Executive Summary}--\begin{executivesummary}[Report Highlights]-This report presents findings from a comprehensive study of [topic]-involving \samplesize{450} participants across 12 research sites.-The research addressed [key question] using [methodology].-\end{executivesummary}--\subsection*{Key Findings}--\begin{keyfindings}-\begin{enumerate}- \item The primary intervention demonstrated a large effect- (\effectsize{d}{0.82}, \psig{< 0.001}).- \item Benefits were maintained at 12-month follow-up.- \item Cost-effectiveness analysis supports implementation.-\end{enumerate}-\end{keyfindings}--\subsection*{Recommendations}--\begin{recommendations}-Based on these findings, we recommend:-\begin{enumerate}- \item Implement the intervention in [settings].- \item Train practitioners using the standardized protocol.- \item Monitor outcomes using the validated measures.-\end{enumerate}-\end{recommendations}-```--### Methods Section Example--```latex-\chapter{Methods}--\begin{methodology}[Study Overview]-This randomized controlled trial employed a parallel-group design with-1:1 allocation to intervention or control conditions. The study was-conducted across 12 sites between January 2023 and December 2024.-\end{methodology}--\section{Participants}--A total of \samplesize{450} participants were enrolled. Eligibility-criteria were:--\begin{itemize}- \item Age 18--65 years- \item Diagnosis of [condition] per [criteria]- \item No contraindications to [intervention]-\end{itemize}--Table~\ref{tab:participants} presents participant characteristics.--\begin{limitations}[Recruitment Challenges]-Recruitment was slower than anticipated due to [reasons]. The final-sample was 10% below target, which may affect statistical power for-secondary analyses.-\end{limitations}-```--### Results Section Example--```latex-\chapter{Results}--\section{Primary Outcome}--\begin{resultsbox}[Primary Analysis]-Mixed-effects regression revealed a significant treatment effect,-\effectsize{F(1, 448)}{42.18}, \psig{< 0.001}, with a large effect-size (\effectsize{d}{0.82}). The treatment group showed significantly-greater improvement (\meansd{16.4}{5.2} points) compared to control-(\meansd{8.1}{4.8} points).-\end{resultsbox}--Figure~\ref{fig:primary} illustrates the treatment effects over time.--\begin{figure}[htbp]-\centering-\includegraphics[width=0.9\textwidth]{../figures/primary_outcome.png}-\caption{Primary Outcome Scores by Treatment Group and Time Point}-\figurenote{Error bars represent 95\% confidence intervals.}-\label{fig:primary}-\end{figure}--\section{Secondary Outcomes}--Results for secondary outcomes are presented in Table~\ref{tab:secondary}.-```--### Discussion Section Example--```latex-\chapter{Discussion}--\section{Summary of Findings}--\begin{keyfindings}[Main Conclusions]-\begin{enumerate}- \item The intervention was highly effective (primary hypothesis- \highlight{supported})- \item Effects were clinically meaningful and durable- \item Evidence strength: \evidencestrong-\end{enumerate}-\end{keyfindings}--\section{Limitations}--\begin{limitations}-Several limitations warrant consideration:-\begin{itemize}- \item The sample was predominantly [demographic], limiting- generalizability.- \item Attrition was higher in the control group (18\% vs. 12\%).- \item Self-report measures may be subject to response bias.-\end{itemize}-\end{limitations}--\section{Implications}--\begin{recommendations}[Research Implications]-\begin{enumerate}- \item Replicate in diverse populations- \item Investigate mechanisms of change- \item Test implementation strategies-\end{enumerate}-\end{recommendations}--\begin{recommendations}[Practice Implications]-\begin{enumerate}- \item Adopt the intervention in [settings]- \item Train providers using standardized protocols- \item Monitor fidelity and outcomes-\end{enumerate}-\end{recommendations}-```-------## Checklist: Professional Report Quality--Before finalizing your report, verify:--### Formatting-- [ ] Using `scientific_report.sty` package-- [ ] Compiled with XeLaTeX or LuaLaTeX-- [ ] Helvetica font rendering correctly-- [ ] Colors displaying properly--### Content Organization-- [ ] Executive summary present and complete-- [ ] Key findings highlighted in boxes-- [ ] Methods clearly described-- [ ] Results properly formatted with statistics-- [ ] Limitations acknowledged-- [ ] Recommendations are specific and actionable--### Tables-- [ ] All tables have captions and labels-- [ ] Alternating row colors applied-- [ ] Significance indicators explained-- [ ] Numbers formatted consistently--### Figures-- [ ] All figures have captions and labels-- [ ] Sources attributed where appropriate-- [ ] Resolution sufficient for printing (300 DPI)-- [ ] Referenced in text--### Statistical Reporting-- [ ] P-values reported appropriately-- [ ] Effect sizes included-- [ ] Confidence intervals where relevant-- [ ] Sample sizes stated--### Professional Appearance-- [ ] Consistent formatting throughout-- [ ] No orphaned headers or widows-- [ ] Page breaks at appropriate locations-- [ ] References complete and formatted-------## Resources--### Files in This Skill--- `assets/scientific_report.sty` - The LaTeX style package-- `assets/scientific_report_template.tex` - Complete report template-- `assets/REPORT_FORMATTING_GUIDE.md` - Quick reference guide--### Related Skills--- `venue-templates` - For journal manuscripts and conference papers-- `scientific-schematics` - For generating diagrams and figures-- `generate-image` - For creating illustrations and graphics--### External Resources--- [LaTeX Wikibook](https://en.wikibooks.org/wiki/LaTeX) - General LaTeX reference-- [Booktabs Package Documentation](https://ctan.org/pkg/booktabs) - Professional table styling-- [tcolorbox Package Documentation](https://ctan.org/pkg/tcolorbox) - Colored box environments+- the verified Markdown source;+- the structured registries;+- the exact venue template version;+- conversion instructions and software versions;+- the final rendered file;+- validator outputs and human approval record.+Do not archive sensitive source documents alongside a public manuscript package unless+authorization, consent, law, contracts, and policy permit it.diff --git a/skills/scientific-writing/references/reporting_guidelines.md b/skills/scientific-writing/references/reporting_guidelines.mdindex e9864705..fe55f07c 100644--- a/skills/scientific-writing/references/reporting_guidelines.md+++ b/skills/scientific-writing/references/reporting_guidelines.md@@ -1,748 +1,107 @@-# Reporting Guidelines for Scientific Studies--## Overview--Reporting guidelines are evidence-based recommendations for what information should be included when reporting specific types of research studies. They provide checklists and flow diagrams to ensure complete, accurate, and transparent reporting, which is essential for readers to assess study validity and for other researchers to replicate the work.--The EQUATOR Network (Enhancing the QUAlity and Transparency Of health Research) maintains a comprehensive library of reporting guidelines. Using appropriate reporting guidelines improves manuscript quality and increases the likelihood of publication acceptance.--## Why Use Reporting Guidelines?--### Benefits--**For authors:**-- Ensures nothing important is forgotten-- Increases acceptance rates-- Improves manuscript organization-- Reduces reviewer requests for additional information--**For readers and reviewers:**-- Enables critical appraisal of study validity-- Facilitates systematic reviews and meta-analyses-- Improves understanding of what was actually done--**For science:**-- Enhances reproducibility-- Reduces research waste-- Improves transparency-- Enables better evidence synthesis--### When to Use--- **During study design**: Many guidelines include protocol versions (e.g., SPIRIT for trial protocols)-- **During manuscript drafting**: Use checklist to ensure all items are covered-- **Before submission**: Verify adherence and often submit checklist with manuscript-- **Many journals require**: Reporting guideline checklists as part of submission--## Major Reporting Guidelines by Study Type--### CONSORT - Randomized Controlled Trials--**Full name:** Consolidated Standards of Reporting Trials--**When to use:** Any randomized controlled trial (RCT), including pilot and feasibility trials--**Latest version:** CONSORT 2010 (updated statement)--**Key components:**-- **Checklist**: 25 items covering title, abstract, introduction, methods, results, discussion-- **Flow diagram**: Participant flow through enrollment, allocation, follow-up, and analysis--**Main checklist items:**-1. Title identifies study as randomized trial-2. Structured abstract-3. Scientific background and rationale-4. Specific objectives and hypotheses-5. Trial design description (parallel, crossover, factorial, etc.)-6. Eligibility criteria for participants-7. Settings and locations of data collection-8. Interventions described in sufficient detail for replication-9. Primary and secondary outcomes defined-10. Sample size determination and power calculation-11. Randomization sequence generation-12. Allocation concealment mechanism-13. Blinding implementation-14. Statistical methods-15. Participant flow with reasons for dropouts-16. Recruitment dates and follow-up dates-17. Baseline characteristics table-18. Analysis results for each outcome-19. Harms and adverse events-20. Trial limitations-21. Generalizability-22. Interpretation consistent with results-23. Trial registration number-24. Full protocol access-25. Funding sources--**Extensions for specific designs:**-- CONSORT for cluster randomized trials-- CONSORT for non-inferiority and equivalence trials-- CONSORT for pragmatic trials-- CONSORT for crossover trials-- CONSORT for N-of-1 trials-- CONSORT for stepped wedge designs--**Where to access:** http://www.consort-statement.org/--### STROBE - Observational Studies--**Full name:** Strengthening the Reporting of Observational Studies in Epidemiology--**When to use:** Cohort studies, case-control studies, and cross-sectional studies--**Latest version:** STROBE 2007 (widely adopted standard)--**Key study designs covered:**-- **Cohort**: Follow exposed and unexposed groups forward in time-- **Case-control**: Compare exposure history between cases and controls-- **Cross-sectional**: Measure exposure and outcome simultaneously--**Main checklist items (22 items):**-1. Title and abstract indicate study design-2. Background and rationale-3. Objectives-4. Study design with rationale-5. Setting, locations, and dates-6. Eligibility criteria and selection methods-7. Variables clearly defined (outcomes, exposures, confounders)-8. Data sources and measurement methods-9. Bias management strategies-10. Study size justification-11. Handling of quantitative variables-12. Statistical methods including confounding and interactions-13. Sensitivity analyses-14. Participant flow with reasons for non-participation-15. Descriptive data including follow-up time-16. Outcome data-17. Main results with unadjusted and adjusted estimates-18. Other analyses (subgroups, sensitivity analyses)-19. Key results summary-20. Limitations with potential bias discussion-21. Interpretation and generalizability-22. Funding sources and role--**Extensions:**-- STROBE-ME (Molecular Epidemiology)-- RECORD (Routinely collected health data)-- STROBE-RDS (Respondent-driven sampling)--**Where to access:** https://www.strobe-statement.org/--### PRISMA - Systematic Reviews and Meta-Analyses--**Full name:** Preferred Reporting Items for Systematic Reviews and Meta-Analyses--**When to use:** Systematic reviews with or without meta-analysis--**Latest version:** PRISMA 2020 (significant update)--**Key components:**-- **Checklist**: 27 items covering all sections-- **Flow diagram**: Study selection process--**Main sections:**-1. **Title**: Identify as systematic review/meta-analysis-2. **Abstract**: Structured summary-3. **Introduction**: Rationale and objectives-4. **Methods**:- - Eligibility criteria- - Information sources (databases, dates)- - Search strategy (full strategy for at least one database)- - Selection process- - Data collection process- - Data items extracted- - Risk of bias assessment- - Effect measures- - Synthesis methods- - Reporting bias assessment- - Certainty assessment (e.g., GRADE)-5. **Results**:- - Study selection flow diagram- - Study characteristics- - Risk of bias assessment results- - Synthesis results (meta-analysis if applicable)- - Reporting biases- - Certainty of evidence-6. **Discussion**:- - Limitations- - Interpretation- - Implications--**Extensions:**-- PRISMA for Abstracts-- PRISMA for Protocols (PRISMA-P)-- PRISMA for Network Meta-Analyses-- PRISMA for Scoping Reviews (PRISMA-ScR)-- PRISMA for Individual Patient Data-- PRISMA for Diagnostic Test Accuracy-- PRISMA for Equity-focused reviews--**Where to access:** http://www.prisma-statement.org/--### SPIRIT - Study Protocols for Clinical Trials--**Full name:** Standard Protocol Items: Recommendations for Interventional Trials--**When to use:** Protocols for randomized trials and other planned intervention studies--**Latest version:** SPIRIT 2013--**Purpose:** Ensure trial protocols contain complete descriptions before trial begins--**Main checklist items (33 items):**-- Administrative information (title, trial registration, funding)-- Introduction (background, rationale, objectives)-- Methods: Trial design- - Study setting- - Eligibility criteria- - Interventions in detail- - Outcomes (primary and secondary)- - Participant timeline- - Sample size calculation- - Recruitment strategy- - Allocation and randomization- - Blinding- - Data collection methods- - Data management- - Statistical methods- - Monitoring (data monitoring committee)- - Harms reporting- - Auditing-- Ethics and dissemination- - Ethics approval- - Consent procedures- - Confidentiality- - Dissemination plans--**Where to access:** https://www.spirit-statement.org/--### STARD - Diagnostic Accuracy Studies--**Full name:** Standards for Reporting of Diagnostic Accuracy Studies--**When to use:** Studies evaluating diagnostic test accuracy--**Latest version:** STARD 2015--**Main checklist items (30 items):**-1. Study design identification-2. Background information and objectives-3. Study design description-4. Participant selection criteria and recruitment-5. Data collection methods-6. Index test description and execution-7. Reference standard description-8. Rationale for choosing reference standard-9. Test result definition and cutoffs-10. Flow of participants with timing-11. Baseline demographic and clinical characteristics-12. Cross-tabulation of index test results by reference standard-13. Estimates of diagnostic accuracy with confidence intervals-14. Handling of indeterminate results-15. Adverse events from testing--**Flow diagram:** Shows participant flow and test results--**Where to access:** https://www.equator-network.org/reporting-guidelines/stard/--### TRIPOD - Prediction Model Studies--**Full name:** Transparent Reporting of a multivariable prediction model for Individual Prognosis Or Diagnosis--**When to use:** Studies developing, validating, or updating prediction models--**Latest version:** TRIPOD 2015--**Types of studies:**-- Model development only-- Model development with validation-- External validation of existing model-- Model update--**Main checklist items (22 items):**-1. Title identifies study as prediction model study-2. Abstract summarizes key elements-3. Background and objectives-4. Data source and participants-5. Outcome definition-6. Predictors (candidate and selected)-7. Sample size justification-8. Missing data handling-9. Model building procedure-10. Model specification (equation or algorithm)-11. Model performance measures-12. Risk groups if used-13. Participant flow diagram-14. Model development results-15. Model performance-16. Model updating if applicable--**Where to access:** https://www.tripod-statement.org/--### ARRIVE - Animal Research--**Full name:** Animal Research: Reporting of In Vivo Experiments--**When to use:** All in vivo animal studies--**Latest version:** ARRIVE 2.0 (2020 update)--**Two sets of items:**--**ARRIVE Essential 10** (minimum requirements):-1. Study design-2. Sample size calculation-3. Inclusion and exclusion criteria-4. Randomization-5. Blinding-6. Outcome measures-7. Statistical methods-8. Experimental animals (species, strain, sex, age)-9. Experimental procedures-10. Results and interpretation--**ARRIVE Recommended Set** (additional items for full reporting):-- Abstract, background, objectives-- Ethics statement-- Housing and husbandry-- Animal care and monitoring-- Interpretation and generalizability-- Protocol registration-- Data access--**Where to access:** https://arriveguidelines.org/--### CARE - Case Reports--**Full name:** CAse REport Guidelines--**When to use:** Case reports and case series--**Latest version:** CARE 2013--**Main checklist items (13 items):**-1. Title with "case report"-2. Abstract summarizing case-3. Introduction with case background-4. Patient information (demographics, primary concern)-5. Clinical findings-6. Timeline of events-7. Diagnostic assessment-8. Therapeutic intervention-9. Follow-up and outcomes-10. Discussion with strengths and limitations-11. Patient perspective-12. Informed consent--**Where to access:** https://www.care-statement.org/--### SQUIRE - Quality Improvement Studies--**Full name:** Standards for QUality Improvement Reporting Excellence--**When to use:** Healthcare quality improvement reports--**Latest version:** SQUIRE 2.0 (2015)--**Main sections (18 items):**-1. Title and abstract-2. Introduction (problem description, available knowledge, rationale, objectives)-3. Methods (context, intervention, study design, measures, analysis, ethical review)-4. Results (intervention, outcomes)-5. Discussion (summary, interpretation, limitations, conclusions)-6. Other information (funding)--**Where to access:** http://www.squire-statement.org/--### CHEERS - Economic Evaluations--**Full name:** Consolidated Health Economic Evaluation Reporting Standards--**When to use:** Health economic evaluations--**Latest version:** CHEERS 2022 (major update from 2013)--**Main checklist items (28 items):**-1. Title identification as economic evaluation-2. Abstract-3. Background and objectives-4. Target population and subgroups-5. Setting and location-6. Study perspective-7. Comparators-8. Time horizon-9. Discount rate-10. Selection of outcomes-11. Measurement of effectiveness-12. Measurement and valuation of costs-13. Currency and price adjustments-14. Choice of model-15. Assumptions-16. Analytical methods--**Where to access:** https://www.equator-network.org/reporting-guidelines/cheers/--### SRQR - Qualitative Research--**Full name:** Standards for Reporting Qualitative Research--**When to use:** Qualitative and mixed methods research--**Latest version:** SRQR 2014--**Main sections:**-- Title and abstract-- Introduction (problem formulation, purpose)-- Methods (qualitative approach, researcher characteristics, context, sampling strategy, ethical issues, data collection, data analysis, trustworthiness)-- Results (synthesis and interpretation, links to empirical data)-- Discussion (limitations, implications)--**Alternative:** COREQ (Consolidated criteria for reporting qualitative research) for interviews and focus groups--**Where to access:** https://www.equator-network.org/reporting-guidelines/srqr/--## How to Use Reporting Guidelines--### During Study Planning--1. **Identify relevant guideline** based on study design-2. **Review checklist items** that require planning (e.g., randomization, blinding)-3. **Design study** to ensure all required elements will be captured-4. **Consider protocol guidelines** (e.g., SPIRIT for trials)--### During Manuscript Drafting--1. **Download checklist** from guideline website-2. **Work through each item** systematically-3. **Note where each item is addressed** in manuscript (page/line numbers)-4. **Revise manuscript** to include missing items-5. **Use flow diagrams** as appropriate--### Before Submission--1. **Complete formal checklist** with page numbers-2. **Review all items** are adequately addressed-3. **Include checklist** with submission if journal requires-4. **Note guideline adherence** in cover letter or methods--### Example Checklist Entry-+# Reporting-Guideline Selection and Coverage++## Purpose and limits++Reporting guidelines help authors report study design, conduct, analysis, and findings+completely enough for appraisal. They do not make a study rigorous, replace a protocol,+repair missing methods, appraise risk of bias, certify compliance, or predict acceptance.+The bundled selector and coverage checker are deliberately non-scoring [SW-S06, SW-S12].++Always open the current official statement, checklist, explanation-and-elaboration+document, relevant extensions, and target-journal instructions. The bundled registry is+a dated routing aid, not a copy of any official checklist.++## Current major guidance as researched++- **Randomized-trial results:** CONSORT 2025. The joint official site provides the+ statement, checklist, expanded checklist, flow diagram, and explanation and+ elaboration [SW-S07, SW-S08].+- **Randomized-trial protocols:** SPIRIT 2025 and its participant-timeline resources+ [SW-S07, SW-S09].+- **Systematic reviews and meta-analyses:** PRISMA 2020. Choose relevant extensions,+ such as protocol, scoping-review, search, or diagnostic-accuracy guidance, from the+ official PRISMA and EQUATOR sites [SW-S10, SW-S06].+- **Cohort, case-control, and cross-sectional studies:** STROBE and the applicable+ design-specific checklist [SW-S11].+- **Diagnostic-accuracy studies:** STARD 2015; add STARD-AI for an AI-centered+ diagnostic-accuracy study [SW-S12, SW-S13].+- **Clinical prediction models:** TRIPOD+AI 2024 covers regression and machine-learning+ prediction-model studies and replaces TRIPOD 2015; add TRIPOD-LLM for biomedical or+ healthcare LLM studies within its scope [SW-S14].+- **Case reports:** CARE 2013, including consent-sensitive reporting [SW-S15].+- **In vivo animal research:** ARRIVE 2.0, using both the Essential 10 and Recommended+ Set as appropriate [SW-S16].+- **Healthcare quality improvement:** SQUIRE 2.0 [SW-S17].+- **Health economic evaluations:** CHEERS 2022 [SW-S18].+- **Qualitative research:** use SRQR generally and verify whether COREQ or another+ design-specific guideline is more appropriate through EQUATOR [SW-S06].++For AI intervention trials or protocols, check CONSORT-AI or SPIRIT-AI in addition to+the current parent statement. For routinely collected data, harms, equity, patient-+reported outcomes, clusters, noninferiority, pilot studies, and other special designs,+search EQUATOR for a current extension [SW-S06].++## Selector++Use the offline registry:++```bash+python3 scripts/select_reporting_guidelines.py select --study-design randomized_trial+python3 scripts/select_reporting_guidelines.py select --study-design randomized_trial --protocol+python3 scripts/select_reporting_guidelines.py select --study-design diagnostic_accuracy --ai+python3 scripts/select_reporting_guidelines.py select --study-design prediction_model --ai --llm```-Item 7: Eligibility criteria for participants, and the settings and locations where the data were collected-Page 6, lines 112-125: "Participants were community-dwelling adults aged 60-85 years with mild cognitive impairment (MCI) as defined by Petersen criteria. Exclusion criteria included dementia diagnosis, major psychiatric disorders, or unstable medical conditions. Recruitment occurred from three memory clinics in Boston, MA, between January 2022 and December 2023."-```--## Finding the Right Guideline--### EQUATOR Network Search--**Website:** https://www.equator-network.org/--**How to use:**-1. Select your study design from the wizard-2. Browse by health research category-3. Search for specific keywords-4. Filter by guideline status (development stage)--### By Study Design--| If your study is a... | Use this guideline |-|----------------------|-------------------|-| Randomized controlled trial | CONSORT |-| Cohort, case-control, or cross-sectional study | STROBE |-| Systematic review or meta-analysis | PRISMA |-| Protocol for a trial | SPIRIT |-| Diagnostic accuracy study | STARD |-| Prediction model study | TRIPOD |-| Animal study | ARRIVE |-| Case report | CARE |-| Quality improvement study | SQUIRE |-| Economic evaluation | CHEERS |-| Qualitative research | SRQR or COREQ |--### Multiple Guidelines--**Some studies may require multiple guidelines:**--**Example 1:** Pilot RCT with qualitative component-- CONSORT for quantitative arm-- SRQR for qualitative component--**Example 2:** Systematic review of diagnostic tests-- PRISMA for review methods-- STARD considerations for included studies--## Extensions and Adaptations--Many reporting guidelines have extensions for specific contexts:--### CONSORT Extensions (examples)-- **CONSORT for Abstracts**: Structured abstracts for RCT reports-- **CONSORT for Harms**: Reporting adverse events-- **CONSORT-EHEALTH**: eHealth interventions-- **CONSORT-SPI**: Social and psychological interventions+The result is a candidate set. A human must confirm:-### PRISMA Extensions (examples)+- the actual design and article type;+- whether a protocol or results report is being written;+- every relevant extension;+- current version and corrections;+- target-journal requirements.-- **PRISMA-P**: Protocols for systematic reviews-- **PRISMA for Abstracts**: Conference abstracts-- **PRISMA-NMA**: Network meta-analyses-- **PRISMA-IPD**: Individual patient data reviews-- **PRISMA-S**: Search strategies-- **PRISMA-DTA**: Diagnostic test accuracy reviews+If no local match exists, search the official EQUATOR library rather than forcing the+nearest guideline.-### STROBE Extensions (examples)+## Coverage record-- **STROBE-ME**: Molecular epidemiology-- **RECORD**: Routinely collected health data+The bundled `coverage_topics` are original high-level prompts. They do not reproduce+official item wording or numbering.-## Creating Flow Diagrams+For each topic, record:-### CONSORT Flow Diagram+- `addressed`, with manuscript locations;+- `not_applicable`, with a rationale;+- `missing`.-**Four stages:**-1. **Enrollment**: Assessed for eligibility-2. **Allocation**: Randomly assigned to groups-3. **Follow-up**: Received intervention, lost to follow-up-4. **Analysis**: Included in analysis+Then run:-**Example:**+```bash+python3 scripts/select_reporting_guidelines.py check reporting_coverage.json```-Assessed for eligibility (n=250)- ↓-Excluded (n=50)- • Did not meet criteria (n=30)- • Declined to participate (n=15)- • Other reasons (n=5)- ↓-Randomized (n=200)- ├─────────────────┬─────────────────┐- ↓ ↓ ↓-Allocated to Allocated to Allocated to-Intervention A Intervention B Control-(n=67) (n=66) (n=67)- ↓ ↓ ↓-Lost to follow-up Lost to follow-up Lost to follow-up-(n=3) (n=5) (n=2)- ↓ ↓ ↓-Analyzed Analyzed Analyzed-(n=64) (n=61) (n=65)-```--### PRISMA Flow Diagram--**Stages:**-1. **Identification**: Records from databases and registers-2. **Screening**: Records screened, excluded-3. **Included**: Studies included in review and synthesis--**New features in PRISMA 2020:**-- Separate tracking for database and register searches-- Tracking of duplicate removal-- Clear distinction between reports and studies--## Common Mistakes and How to Avoid Them--### Mistake 1: Not Using Guidelines at All--**Impact:** Missing critical information, lower chance of acceptance--**Solution:** Identify and use appropriate guideline from study planning stage--### Mistake 2: Using Guidelines Only After Manuscript is Complete--**Impact:** May realize key data were not collected or documented--**Solution:** Review guidelines during study design and data collection--### Mistake 3: Incomplete Checklist Completion--**Impact:** Missed items remain unreported--**Solution:** Systematically address every single checklist item--### Mistake 4: Using Outdated Guidelines--**Impact:** Missing recent improvements in reporting standards--**Solution:** Always check for latest version on official guideline website--### Mistake 5: Using Wrong Guideline for Study Design--**Impact:** Important design-specific elements not reported--**Solution:** Carefully match study design to appropriate guideline--### Mistake 6: Not Submitting Checklist When Required--**Impact:** Editorial desk rejection or delays--**Solution:** Check journal submission guidelines and include checklist--### Mistake 7: Generic Reporting Without Specificity--**Impact:** Insufficient detail for replication or appraisal--**Solution:** Provide specific, detailed information for each item--## Journal Requirements--### Many Journals Now Require:--1. **Statement of adherence** to reporting guidelines in Methods-2. **Completed checklist** uploaded as supplementary file-3. **Page/line numbers** on checklist indicating where items are addressed-4. **Flow diagrams** as figures in manuscript--### Example Methods Statement:--```-"This study is reported in accordance with the Strengthening the Reporting of-Observational Studies in Epidemiology (STROBE) statement. A completed STROBE-checklist is provided as Supplementary File 1."-```--### Journals with Strong Requirements:--- PLOS journals (require checklists for specific designs)-- BMJ (requires CONSORT, PRISMA, and others)-- The Lancet (requires adherence statements)-- JAMA and JAMA Network journals (require checklists)-- Nature portfolio journals (encourage guidelines)--## Resources--### Official Guideline Websites--- **EQUATOR Network**: https://www.equator-network.org/-- **CONSORT**: http://www.consort-statement.org/-- **STROBE**: https://www.strobe-statement.org/-- **PRISMA**: http://www.prisma-statement.org/-- **SPIRIT**: https://www.spirit-statement.org/-- **ARRIVE**: https://arriveguidelines.org/-- **CARE**: https://www.care-statement.org/--### Training Materials--- EQUATOR Network provides webinars and training resources-- Many guidelines have explanatory papers published in medical journals-- Universities often provide workshops on reporting guidelines--### Software Tools--- **Some reference managers** can insert reporting guideline citations-- **Covidence, RevMan** for systematic review reporting-- **PRISMA flow diagram generator**: http://prisma.thetacollaborative.ca/--## Checklist: Using Reporting Guidelines--**Before starting your study:**-- [ ] Identified appropriate reporting guideline(s)-- [ ] Reviewed checklist items requiring prospective planning-- [ ] Designed study to capture all required elements-- [ ] Registered protocol if applicable--**During manuscript drafting:**-- [ ] Downloaded latest version of guideline checklist-- [ ] Systematically addressed each checklist item-- [ ] Created required flow diagram-- [ ] Noted where each item is addressed (page/line)--**Before submission:**-- [ ] Completed formal checklist with page numbers-- [ ] Verified all items adequately addressed-- [ ] Included adherence statement in Methods-- [ ] Prepared checklist as supplementary file if required-- [ ] Checked journal-specific requirements-- [ ] Mentioned guideline adherence in cover letter--## Venue-Specific Reporting Requirements--### Reporting Standards by Venue Type--| Venue Type | Guideline Use | Transparency Requirements |-|-----------|--------------|---------------------------|-| **Medical journals** | Mandatory (CONSORT, STROBE, etc.) | Checklist required at submission |-| **PLOS/BMC** | Mandatory for study types | Checklist uploaded as supplement |-| **Nature/Science** | Recommended | Methods completeness emphasized |-| **ML conferences** | No formal guidelines | Reproducibility details required |--### ML Conference Reporting Standards--**NeurIPS/ICML/ICLR reproducibility requirements:**-- **Datasets**: Names, versions, access methods, preprocessing-- **Code**: Availability statement; GitHub common-- **Hyperparameters**: All settings reported (learning rate, batch size, etc.)-- **Seeds**: Random seeds for reproducibility-- **Computational resources**: GPUs used, training time-- **Statistical significance**: Error bars, confidence intervals, multiple runs-- **Broader Impact** statement (NeurIPS): Societal implications--**What to include (typically in appendix):**-- Complete hyperparameter settings-- Training details and convergence criteria-- Hardware specifications-- Software versions (PyTorch 2.0, etc.)-- Dataset splits and any preprocessing-- Evaluation metrics and protocols--### Enforcement and Evaluation--**What gets checked:**-- **Medical journals**: Checklist uploaded; adherence statement in Methods; systematic completeness-- **PLOS/BMC**: Mandatory checklists for certain designs; reproducibility emphasized-- **High-impact**: Methods sufficiency for replication (checklist often not required)-- **ML conferences**: Reproducibility checklist (NeurIPS); code availability increasingly expected--**Common issues leading to rejection:**-- Missing required checklists (medical journals)-- Insufficient methods detail for reproduction-- Missing key information (randomization, blinding, power calculation)-- No data/code availability statement when required--**Methods statement examples:**--**Journal (STROBE):**-```-This study followed STROBE reporting guidelines. Checklist provided in Supplement 1.-```--**ML conference (reproducibility):**-```-Code available at github.com/user/project. All hyperparameters in Appendix A.-Training used 4×A100 GPUs (~20 hours). Seeds: {42, 123, 456}.-```--### Pre-Submission Reporting Checklist--**For clinical trials (medical journals):**-- [ ] CONSORT checklist complete with page numbers-- [ ] Trial registration number in abstract and methods-- [ ] CONSORT flow diagram included-- [ ] Statistical analysis plan described-- [ ] Adherence statement in Methods--**For observational studies (medical/epidemiology):**-- [ ] STROBE checklist complete-- [ ] Study design clearly stated-- [ ] Statistical methods detailed-- [ ] Confounders addressed-- [ ] Adherence statement in Methods--**For systematic reviews:**-- [ ] PRISMA checklist complete-- [ ] PRISMA flow diagram included-- [ ] Protocol registered (PROSPERO)-- [ ] Search strategy documented-- [ ] Risk of bias assessment included-**For ML conference papers:**-- [ ] All datasets named with versions-- [ ] Code availability stated (GitHub link if available)-- [ ] Hyperparameters listed (appendix acceptable)-- [ ] Random seeds reported-- [ ] Computational resources specified-- [ ] Error bars/confidence intervals shown-- [ ] Broader Impact statement (if required)+A pass means every bundled topic has an allowed status and location or rationale. It+does not mean every official checklist item is satisfied or well reported.++## Workflow++1. Select candidate guidance during planning.+2. Open the official statement and explanation document.+3. Record prospective items in the protocol, registry, or analysis plan where+ applicable.+4. Draft the manuscript from evidence and methods records.+5. Complete the official checklist with actual manuscript locations.+6. Record missing items honestly; do not invent information to fill them.+7. Submit the official checklist or flow diagram if the journal requires it.+8. Re-check guideline and journal versions immediately before submission.++## Frequent errors++- treating a checklist as a design-quality score;+- claiming adherence when only a subset was reviewed;+- using an outdated parent statement while overlooking a current update;+- omitting a relevant extension;+- writing a missing method into the paper as though it occurred;+- checking boxes without recording manuscript locations;+- assuming a journal endorsement means submission requirements are identical across+ article types.diff --git a/skills/scientific-writing/references/research_integrity_open_science.md b/skills/scientific-writing/references/research_integrity_open_science.mdnew file mode 100644index 00000000..63eb7302--- /dev/null+++ b/skills/scientific-writing/references/research_integrity_open_science.md@@ -0,0 +1,97 @@+# Research Integrity and Responsible Open Science++## Integrity principles++The ALLEA 2023 Code frames research integrity around reliability, honesty, respect, and+accountability across disciplines and research settings [SW-S27]. Apply those principles+throughout drafting, not only at submission.++- Preserve the original record and an audit trail.+- Report methods, deviations, uncertainty, and findings honestly.+- Correct material errors promptly and transparently.+- Respect participants, communities, collaborators, animals, the environment, and+ legitimate rights in knowledge and data.+- Assign credit fairly and accept accountability.+- Do not fabricate, falsify, plagiarize, selectively omit, or conceal provenance.++If potential misconduct or a material error appears, preserve records and follow the+institutional, funder, journal, and legal process. Do not investigate by exposing+sensitive material to unapproved systems.++## Open science with safeguards++UNESCO's Recommendation supports accessible, inclusive, equitable, and sustainable open+science while recognizing legitimate restrictions for confidentiality, personal+information, intellectual property, threatened resources, and protected knowledge+[SW-S28].++For every data, code, materials, and protocol statement:++1. Confirm ownership, consent, ethics terms, contracts, law, and repository policy.+2. Identify what underlies the reported claims.+3. Choose an appropriate repository and access model.+4. Record versions, persistent identifiers, licenses, metadata, and retention.+5. State restrictions and an actual access process.+6. Verify that the deposited files match the analysis and do not expose restricted+ information.++Do not promise public availability merely because a template asks for it. "Available on+request" must describe a real, authorized, sustainable process if the venue permits that+form.++## Prospective transparency++Where applicable, record:++- study registration;+- protocol and amendments;+- analysis plan and timing;+- outcome and model definitions;+- data-management and sharing plan;+- materials, software, environment, and versions;+- departures from prespecification.++The Center for Open Science's TOP 2025 framework provides practices for registration,+protocols, analysis plans, materials, data, code, reporting transparency, and+verification [SW-S30]. These practices are flexible policy components, not a universal+score for an individual manuscript.++NIH's Data Management and Sharing Policy applies to covered NIH research and expects+planning, budgeting, submission of a plan, and compliance with the approved plan+[SW-S29]. Check the specific funder, award, institute, and effective requirements.++## Reproducibility package++When policy and rights permit, preserve:++- immutable raw-data references rather than uncontrolled copies;+- cleaned or analysis-ready data with provenance;+- executable analysis code and environment information;+- software and model versions;+- randomization or seed handling where relevant;+- machine-readable tables behind reported displays;+- a mapping from outputs to manuscript claims;+- checksums, releases, and persistent identifiers.++Never share secrets, credentials, direct identifiers, restricted variables, proprietary+source code, or licensed source documents in a public package.++## Corrections and versions++Before submission, check for corrected, retracted, superseded, or updated sources. After+dissemination:++- preserve the original version where policy requires;+- describe what changed and why;+- link corrections to the affected record;+- update downstream data, code, tables, and claims;+- notify the appropriate journal, repository, collaborators, and oversight bodies.++Do not silently edit a scientific record in a way that hides a material change.++## Negative and null findings++Open science includes an accurate record of outcomes that do not support the preferred+narrative. Preserve negative, null, adverse, failed, and inconclusive results when they+are part of the study record. Describe their uncertainty and limitations; do not+reinterpret them as proof of absence.diff --git a/skills/scientific-writing/references/source_ledger.md b/skills/scientific-writing/references/source_ledger.mdnew file mode 100644index 00000000..5831ab51--- /dev/null+++ b/skills/scientific-writing/references/source_ledger.md@@ -0,0 +1,268 @@+# Source Ledger++Research date: **2026-07-24**++Method: targeted `parallel-cli search` and `parallel-cli extract` queries restricted to+official guideline organizations, standards bodies, government sites, and original+statement publications. No search-result artifacts are bundled. Re-check every source+and the target journal immediately before submission because policies can change.++Source IDs in this ledger ground factual statements in the skill. They are not evidence+IDs for a user's manuscript.++## Publication ethics, authorship, and AI++### SW-S01 — ICMJE Recommendations++- Organization: International Committee of Medical Journal Editors+- Version: Updated January 2026+- URL: https://www.icmje.org/icmje-recommendations.pdf+- Used for: authorship criteria, human accountability, AI disclosure, reference+ verification, confidentiality, peer review, reporting guidelines, corrections, and+ data-access expectations.++### SW-S02 — ICMJE January 2026 update notice++- Organization: ICMJE+- Date: January 2026+- URL: https://www.icmje.org/news-and-editorials/updated_recommendations_jan2026.html+- Used for: confirmation that the 2026 update added expanded AI guidance and author+ access-to-data guidance.++### SW-S03 — COPE position on authorship and AI tools++- Organization: Committee on Publication Ethics+- Formal position last reviewed: 2023; current page retrieved 2026-07-24+- URL: https://publicationethics.org/guidance/cope-position/authorship-and-ai-tools+- Used for: AI cannot be an author; authors disclose use and remain responsible.++### SW-S04 — COPE Code of Conduct status++- Organization: COPE+- Current page date surfaced by search: 2026-07-15+- URL: https://publicationethics.org/membership/code-of-conduct+- Used for: as of the research date, the 2017 Core Practices had been retired in 2024+ and COPE stated that a replacement Code of Conduct would be published in 2026.++### SW-S05 — COPE history of Code and Core Practices++- Organization: COPE+- URL: https://publicationethics.org/about/what-we-do/our-story/history-code-conduct+- Used for: historical context only; archived Core Practices must not be presented as+ current membership standards.++## Reporting guidelines++### SW-S06 — EQUATOR reporting-guideline library++- Organization: EQUATOR Network+- URL: https://www.equator-network.org/reporting-guidelines/+- Used for: study-type discovery, extensions, translations, and current official links.++### SW-S07 — Joint SPIRIT–CONSORT resource++- Organization: SPIRIT–CONSORT+- Version: CONSORT 2025 and SPIRIT 2025+- URL: https://www.consort-spirit.org/+- Used for: current statements, editable checklists, expanded checklists, flow or+ timeline diagrams, and explanation-and-elaboration resources.++### SW-S08 — CONSORT 2025 statement++- Original statement publication: BMJ+- Date: 2025+- URL: https://www.bmj.com/content/389/bmj-2024-081123+- Used for: current randomized-trial reporting statement and scope.++### SW-S09 — SPIRIT 2025 statement++- Original statement publication: JAMA+- Date: 2025-04-28+- URL: https://jamanetwork.com/journals/jama/fullarticle/2833408+- Used for: current randomized-trial protocol reporting statement and scope.++### SW-S10 — PRISMA 2020++- Organization: PRISMA+- URL: https://www.prisma-statement.org/prisma-2020+- Checklist URL: https://www.prisma-statement.org/prisma-2020-checklist+- Used for: systematic review and meta-analysis reporting.++### SW-S11 — STROBE checklists++- Organization: STROBE Initiative+- Version: original 2007 statement; current official checklist page+- URL: https://www.strobe-statement.org/checklists/+- Used for: cohort, case-control, and cross-sectional study reporting.++### SW-S12 — STARD++- Organization: UK EQUATOR Centre+- Version shown by source: STARD 2015 v1.1+- URL: https://resources.equator-network.org/reporting-guidelines/stard+- Used for: diagnostic-accuracy reporting and the explicit distinction between+ reporting completeness and appraisal of study quality.++### SW-S13 — STARD-AI++- Original consensus statement publication: Nature Medicine+- Date: 2025+- URL: https://www.nature.com/articles/s41591-025-03953-8+- Used for: diagnostic-accuracy studies evaluating AI systems.++### SW-S14 — TRIPOD+AI and TRIPOD-LLM++- Organization: TRIPOD+- Versions: TRIPOD+AI 2024; TRIPOD-LLM 2025+- URL: https://www.tripod-statement.org/+- EQUATOR record: https://www.equator-network.org/reporting-guidelines/tripod-statement+- Used for: prediction-model studies using regression or machine learning and the LLM+ extension. The official site states that TRIPOD+AI replaces TRIPOD 2015.++### SW-S15 — CARE++- Organization: CARE+- Version: 2013+- URL: https://www.care-statement.org/checklist+- Used for: case-report reporting and consent-sensitive coverage.++### SW-S16 — ARRIVE 2.0++- Organization: NC3Rs ARRIVE+- Date: 2020+- URL: https://arriveguidelines.org/arrive-guidelines+- Author checklists: https://arriveguidelines.org/resources/author-checklists+- Used for: in vivo animal research, Essential 10, and Recommended Set.++### SW-S17 — SQUIRE 2.0++- Organization: SQUIRE+- Date: 2015+- URL: https://www.squire-statement.org/index.cfm?fuseaction=page.viewPage&pageID=471&nodeID=1+- Used for: healthcare quality-improvement reporting.++### SW-S18 — CHEERS 2022++- Organization: ISPOR+- Date: 2022+- URL: https://www.ispor.org/heor-resources/good-practices/article/consolidated-health-economic-evaluation-reporting-standards-2022-cheers-2022-statement-updated-reporting-guidance-for-health-economic-evaluations+- EQUATOR record: https://www.equator-network.org/reporting-guidelines/cheers/+- Used for: health economic evaluation reporting.++### SW-S31 — CONSORT-AI extension++- Organization: EQUATOR Network record for the CONSORT-AI Working Group+- Date: 2020; EQUATOR record updated 2026-04-04+- URL: https://www.equator-network.org/reporting-guidelines/consort-artificial-intelligence/+- Used for: trial reports evaluating interventions with an AI component.++### SW-S32 — SPIRIT-AI extension++- Organization: EQUATOR Network record for the SPIRIT-AI Working Group+- Date: 2020; EQUATOR record updated 2025-05-30+- URL: https://www.equator-network.org/reporting-guidelines/spirit-artificial-intelligence/+- Used for: protocols for trials evaluating interventions with an AI component.++### SW-S33 — SRQR++- Organization: EQUATOR Network record for the original guideline+- Date: 2014; EQUATOR record updated 2023-01-18+- URL: https://www.equator-network.org/reporting-guidelines/srqr/+- Used for: reporting qualitative research studies.++## Contributions and references++### SW-S19 — CRediT Contributor Role Taxonomy++- Standards body: NISO+- Standard: ANSI/NISO Z39.104-2022+- URL: https://credit.niso.org/+- Role definitions: https://credit.niso.org/contributor-roles/+- Used for: the 14 contribution roles and the rule that CRediT describes+ contributions but does not determine authorship.++### SW-S20 — NLM Citing Medicine++- Organization: U.S. National Library of Medicine+- URL: https://www.ncbi.nlm.nih.gov/books/NBK7256/+- Used for: source-type-specific biomedical reference formatting.++### SW-S21 — NLM sample references++- Organization: U.S. National Library of Medicine+- URL: https://www.nlm.nih.gov/bsd/uniform_requirements.html+- Used for: verified examples for articles, datasets, software, and online material.++## Journal-policy examples++### SW-S22 — Nature Portfolio reporting and availability policies++- Publisher: Nature Portfolio+- URL: https://www.nature.com/nature-portfolio/editorial-policies/reporting-standards+- Used for: journal-specific reporting, materials, data, code, protocol, and restriction+ disclosures as an example of a publisher policy.++### SW-S23 — Nature Portfolio authorship policy++- Publisher: Nature Portfolio+- URL: https://www.nature.com/nature-portfolio/editorial-policies/authorship+- Used for: authorship, contribution statements, and accountability as a journal-policy+ example.++### SW-S24 — JAMA guidance on AI use++- Publisher: JAMA Network+- Date: 2023-07-27+- URL: https://jamanetwork.com/journals/jama/fullarticle/2807956+- Used for: an example journal policy on authors, reviewers, editors, disclosure, and+ confidential peer-review material.++### SW-S25 — JAMA Instructions for Authors++- Journal: JAMA+- URL: https://jamanetwork.com/journals/jama/pages/instructions-for-authors+- Used for: an example of venue-specific article types, limits, statements, and+ submission requirements.++### SW-S26 — PLOS Biology data availability policy++- Publisher: PLOS+- URL: https://journals.plos.org/plosbiology/s/data-availability+- Used for: an example policy that balances availability with consent, privacy, legal,+ ethical, and other sensitive-data restrictions.++## Research integrity and open science++### SW-S27 — European Code of Conduct for Research Integrity++- Organization: ALLEA+- Version: 2023 revised edition+- DOI: 10.26356/ECOC+- URL: https://allea.org/portfolio-item/european-code-of-conduct-2023+- Used for: reliability, honesty, respect, accountability, data practices, open science,+ and responsible research culture.++### SW-S28 — UNESCO Recommendation on Open Science++- Organization: UNESCO+- Adopted: 2021+- URL: https://www.unesco.org/en/open-science/about+- Used for: openness that is equitable and as open as possible while respecting+ confidentiality, personal information, intellectual property, and other legitimate+ restrictions.++### SW-S29 — NIH Data Management and Sharing Policy++- Organization: U.S. National Institutes of Health+- Effective: 2023-01-25+- URL: https://grants.nih.gov/policy-and-compliance/policy-topics/sharing-policies/dms/policy-overview+- Used for: planning, budgeting, submitting, and complying with data-management and+ sharing plans where the policy applies.++### SW-S30 — TOP Guidelines++- Organization: Center for Open Science+- Version: TOP 2025+- URL: https://www.cos.io/initiatives/top-guidelines+- Used for: study registration, protocols, analysis plans, materials, data, code,+ reporting transparency, and verification-oriented policy practices.diff --git a/skills/scientific-writing/references/writing_principles.md b/skills/scientific-writing/references/writing_principles.mdindex 83cb5772..5fcd5012 100644--- a/skills/scientific-writing/references/writing_principles.md+++ b/skills/scientific-writing/references/writing_principles.md@@ -1,824 +1,97 @@-# Scientific Writing Principles+# Evidence-Bound Scientific Writing Principles-## Overview+## Accuracy before fluency-Effective scientific writing requires mastering fundamental principles that ensure clarity, precision, and impact. Unlike creative or narrative writing, scientific writing prioritizes accuracy, conciseness, and objectivity. This guide covers the core principles that distinguish good scientific writing from poor writing and provides practical strategies for improvement.+The accountable human authors are responsible for accuracy, integrity, originality,+attribution, and disclosure, including material prepared with AI assistance+[SW-S01, SW-S03]. Do not improve prose by changing scientific meaning.-## The Three Pillars of Scientific Writing+Apply these rules:-### 1. Clarity+- Preserve the distinction between observation, estimate, interpretation, and+ speculation.+- Match the strength of each verb to the design and evidence.+- Do not turn association into causation.+- Do not turn statistical non-significance into equivalence or proof of no effect.+- Report uncertainty with the estimate and keep its interpretation proportional.+- Preserve conflicting evidence and credible alternative explanations.+- State what is unknown instead of filling a gap.-**Definition:** Writing that is immediately understandable to the intended audience without ambiguity or confusion.+## Confirmatory and exploratory work-**Why it matters:** Science is complex enough without unclear writing adding confusion. Readers should focus on understanding the science, not deciphering the prose.+Label analyses according to their actual provenance.-#### Strategies for Clarity+- **Confirmatory**: prespecified before the relevant analysis or unblinding threshold,+ with deviations recorded.+- **Exploratory**: generated or materially changed after examining relevant data.+- **Descriptive**: summarizes observed data without a confirmatory inferential claim.-**Use precise, unambiguous language:**-```-Poor: "The drug seemed to help quite a few patients."-Better: "The drug reduced symptoms in 68% (32/47) of patients."-```+Do not relabel a post hoc analysis as prespecified. Explain amendments, timing, and+rationale. Keep exploratory results useful but visibly exploratory.-**Define technical terms at first use:**-```-"We measured brain-derived neurotrophic factor (BDNF), a protein involved in-neuronal survival and plasticity."-```+## Complete reporting-**Maintain logical flow within and between paragraphs:**-- Each paragraph should have one main idea-- Topic sentence introduces the paragraph's focus-- Supporting sentences develop that focus-- Transition sentences connect paragraphs+Retain findings regardless of direction:-**Use active voice when it improves clarity:**-```-Passive (less clear): "The samples were analyzed by the researchers."-Active (clearer): "Researchers analyzed the samples."-```+- primary and secondary outcomes;+- negative, null, adverse, and unexpected findings;+- missing data and attrition;+- sensitivity and subgroup analyses with their status;+- protocol or analysis-plan deviations;+- failed or inconclusive experiments when relevant to interpretation.-However, passive voice is acceptable and often preferred in Methods when the action is more important than the actor:-```-"Blood samples were collected at baseline and after 6 weeks."-```+Selective omission can distort the record. Corrections should be prompt, transparent,+and linked to the affected version [SW-S01, SW-S27].-**Break up long, complex sentences:**-```-Poor: "The results of our study, which involved 200 participants recruited from-three hospitals and followed for 12 months with assessments every 4 weeks using-validated questionnaires, showed significant improvements in the intervention-group."+## Numbers and units-Better: "Our study involved 200 participants recruited from three hospitals.-Participants were followed for 12 months with assessments every 4 weeks using-validated questionnaires. The intervention group showed significant improvements."-```+Every reported number needs:-**Use specific verbs:**-```-Weak: "The study looked at depression in adolescents."-Stronger: "The study examined factors contributing to depression in adolescents."-```+- a stable concept name;+- unit and scale;+- numerator and denominator when applicable;+- analysis population and sample size;+- time point;+- estimate and uncertainty where applicable;+- method or result ID;+- evidence ID.-#### Common Clarity Problems+Keep precision justified by measurement and analysis. Distinguish zero from missing,+below detection, not measured, and not applicable. Run the consistency checker after+every substantive edit.-**Ambiguous pronouns:**-```-Poor: "Group A received the drug and Group B received placebo. They showed-improvement."-(Who is "they"?)+## Methods and results-Better: "Group A received the drug and Group B received placebo. The drug-treated-group showed improvement."-```+Methods describe what was actually done, not what would have been ideal. Results must+not introduce an undeclared method. For each result, verify:-**Misplaced modifiers:**-```-Poor: "We measured blood pressure in patients using an automated monitor."-(Are the patients using the monitor, or are we?)+- the outcome was defined;+- the analysis method exists in the methods registry;+- the analysis intent agrees;+- exclusions and analysis populations agree;+- transformations, covariates, multiplicity handling, and missing-data methods agree;+- the reported value, unit, denominator, sample size, and uncertainty agree everywhere.-Better: "Using an automated monitor, we measured blood pressure in patients."-```+## Limitations and generalizability-**Unclear referents:**-```-Poor: "The increase in expression was accompanied by decreased proliferation, which-was unexpected."-(What was unexpected—the decrease, the accompaniment, or both?)+Name concrete sources of bias, imprecision, missingness, measurement error, model+limitations, multiplicity, and limited transportability. Explain likely direction or+consequence when evidence supports that explanation. Do not add a generic limitations+paragraph merely to satisfy form.-Better: "The increase in expression was accompanied by decreased proliferation.-This inverse relationship was unexpected."-```+## Language review-### 2. Conciseness+Prefer direct, precise prose, but do not impose arbitrary sentence length, citation+density, recency percentage, figure count, or reference count. Those heuristics can+encourage unsupported content and vary by field and venue.-**Definition:** Expressing ideas in the fewest words necessary without sacrificing clarity or completeness.+Use person-centered or identity-affirming language according to community preference,+study context, and current venue policy. Preserve participant self-description when+appropriate. Define abbreviations and use one term for one concept.-**Why it matters:** Concise writing respects readers' time. Every unnecessary word is a missed opportunity for clarity and impact. As the principle states: "We value concise writing because we value time."+## Draft status-#### Strategies for Conciseness--**Eliminate redundant words and phrases:**--| Wordy | Concise |-|-------|---------|-| "due to the fact that" | "because" |-| "in order to" | "to" |-| "it is important to note that" | [delete] |-| "a total of 50 participants" | "50 participants" |-| "completely eliminate" | "eliminate" |-| "has been shown to be" | "is" |-| "in the event that" | "if" |-| "at the present time" | "now" or "currently" |-| "conduct an investigation into" | "investigate" |-| "give consideration to" | "consider" |--**Avoid throat-clearing phrases:**-```-Wordy: "It is interesting to note that the results of our study demonstrate that..."-Concise: "Our results demonstrate that..." or "The results show that..."-```--**Use strong verbs instead of noun+verb combinations:**--| Wordy | Concise |-|-------|---------|-| "make a decision" | "decide" |-| "perform an analysis" | "analyze" |-| "conduct a study" | "study" or "studied" |-| "make an assessment" | "assess" |-| "provide information about" | "inform" |--**Eliminate unnecessary intensifiers:**-```-Wordy: "The results were very significant."-Concise: "The results were significant." (p-value conveys the degree)-```--**Avoid repeating information unnecessarily:**-```-Redundant: "The results showed that participants in the intervention group, who-received the treatment intervention, had better outcomes."-Concise: "The intervention group had better outcomes."-```--**Favor shorter constructions:**-```-Wordy: "In spite of the fact that the sample size was small..."-Concise: "Although the sample size was small..."-```--#### Acceptable Length vs. Unnecessary Length--**Not all long sentences are bad:**-```-This detailed sentence is fine: "We analyzed blood samples using liquid-chromatography-tandem mass spectrometry (LC-MS/MS) with a Waters Acquity UPLC-system coupled to a Xevo TQ-S mass spectrometer (Waters Corporation, Milford, MA)."--Why? Because each element is necessary information.-```--**The key question:** Can any word be removed without losing meaning or precision? If yes, remove it.--### 3. Accuracy--**Definition:** Precise, correct representation of data, methods, and interpretations.--**Why it matters:** Scientific credibility depends on accuracy. Inaccurate reporting undermines the entire scientific enterprise.--#### Strategies for Accuracy--**Report exact values with appropriate precision:**-```-Poor: "The mean was about 25."-Better: "The mean was 24.7 ± 3.2 (SD)."-```--**Match precision to measurement capability:**-```-Inappropriate: "Mean age was 45.237 years" (implies false precision)-Appropriate: "Mean age was 45.2 years"-```--**Use consistent terminology throughout:**-```-Inconsistent: Introduction calls it "cognitive function," Methods call it "mental-performance," Results call it "intellectual ability."--Consistent: Use "cognitive function" throughout, or define explicitly: "cognitive-function (also termed mental performance)"-```--**Distinguish observations from interpretations:**-```-Observation: "Mean blood pressure decreased from 145 to 132 mmHg (p=0.003)."-Interpretation: "This suggests the intervention effectively lowers blood pressure."-```--**Be specific about uncertainty:**-```-Vague: "There may be some error in these measurements."-Specific: "Measurements have a standard error of ±2.5 mmHg based on instrument-specifications."-```--**Use correct statistical language:**-```-Incorrect: "The correlation was highly significant (p=0.03)."-Correct: "The correlation was statistically significant (p=0.03)."-(p=0.03 is not "highly" significant; that's reserved for p<0.001)-```--**Verify all numbers:**-- Check that numbers in text match tables/figures-- Verify that n values sum correctly-- Confirm percentages are correctly calculated-- Double-check all statistics--#### Common Accuracy Problems--**Overgeneralization:**-```-Poor: "Exercise prevents depression."-Better: "In our sample, participants randomized to the exercise intervention showed-fewer depressive symptoms than controls (mean difference 3.2 points on the BDI-II,-95% CI: 1.5-4.9, p<0.001)."-```--**Unwarranted causal claims:**-```-Poor (from observational study): "Vitamin D supplementation reduces cancer risk."-Better: "Vitamin D levels were inversely associated with cancer incidence in this-cohort (HR=0.82, 95% CI: 0.71-0.95)."-```--**Imprecise numerical descriptions:**-```-Vague: "Many participants dropped out."-Precise: "15/50 (30%) participants withdrew before study completion."-```--## Additional Key Principles--### 4. Objectivity--**Definition:** Presenting information impartially without bias, exaggeration, or unsupported opinion.--**Strategies:**--**Present results without bias:**-```-Biased: "As expected, our superior method performed better."-Objective: "Method A showed higher accuracy than Method B (87% vs. 76%, p=0.02)."-```--**Acknowledge conflicting evidence:**-```-"Our findings contrast with Smith et al. (2022), who reported no significant effect.-This discrepancy may result from differences in intervention intensity or population-characteristics."-```--**Avoid emotional or evaluative language:**-```-Subjective: "The results were disappointing and concerning."-Objective: "The intervention did not significantly reduce symptoms (p=0.42)."-```--**Distinguish fact from speculation:**-```-"The observed decrease in cell viability was accompanied by increased caspase-3-activity, suggesting that apoptosis may be the primary mechanism of cell death."-(Uses "suggesting" and "may be" to indicate interpretation)-```--### 5. Consistency--**Maintain consistency throughout the manuscript:**--**Terminology:**-- Use the same term for the same concept (not synonyms for variety)-- Define abbreviations at first use and use consistently thereafter-- Use standard nomenclature for genes, proteins, chemicals--**Notation:**-- Statistical notation (p-value format, CI presentation)-- Units of measurement-- Number formatting (decimal places)--**Tense:**-- Past tense for your specific study actions-- Present tense for established facts-- See detailed tense guide in IMRAD structure reference--**Style:**-- Follow journal guidelines consistently-- Citation format-- Heading capitalization-- Number vs. word for numerals--### 6. Logical Organization--**Create a clear "red thread" through the manuscript:**--**Paragraph structure:**-1. Topic sentence (main idea)-2. Supporting sentences (evidence, explanation)-3. Concluding/transition sentence (link to next idea)--**Section flow:**-- Each section builds logically on the previous-- Questions raised in Introduction are answered in Results-- Findings presented in Results are interpreted in Discussion--**Signposting:**-```-"First, we examined..."-"Next, we investigated..."-"Finally, we assessed..."-```--**Parallelism:**-```-Not parallel: "Aims were to (1) measure blood pressure, (2) assessment of-cognitive function, and (3) we wanted to evaluate mood."--Parallel: "Aims were to (1) measure blood pressure, (2) assess cognitive-function, and (3) evaluate mood."-```--## Verb Tense in Scientific Writing--### General Guidelines--**Present tense** for:-- Established facts and general truths- - "DNA is composed of nucleotides."-- Conclusions you are drawing- - "These findings suggest that..."-- Referring to figures and tables- - "Figure 1 shows the distribution..."--**Past tense** for:-- Specific findings from completed research (yours and others')- - "Smith et al. (2022) found that..."- - "We observed a significant decrease..."-- Methods you performed- - "Participants completed questionnaires at baseline."--**Present perfect** for:-- Recent developments with current relevance- - "Recent studies have demonstrated..."-- Research area background- - "Several approaches have been proposed..."--### Section-Specific Tense--| Section | Primary Tense | Examples |-|---------|---------------|----------|-| **Abstract - Background** | Present or present perfect | "Depression affects millions" / "Research has shown..." |-| **Abstract - Methods** | Past | "We recruited 100 participants" |-| **Abstract - Results** | Past | "The intervention reduced symptoms" |-| **Abstract - Conclusions** | Present | "These findings suggest..." |-| **Introduction - Background** | Present (facts), present perfect (research) | "Exercise is beneficial" / "Studies have shown..." |-| **Introduction - Gap** | Present or present perfect | "However, little is known..." |-| **Introduction - This study** | Past or present | "We investigated..." / "This study investigates..." |-| **Methods** | Past | "We collected samples..." |-| **Results** | Past | "Mean age was 45 years" |-| **Discussion - Your findings** | Past | "We found that..." |-| **Discussion - Interpretation** | Present | "This suggests..." |-| **Discussion - Prior work** | Past or present | "Smith found..." / "Previous work demonstrates..." |--## Common Writing Pitfalls--### 1. Jargon Overload--**Problem:** Excessive use of technical terms without definition--**Example:**-```-Poor: "We utilized qRT-PCR to quantify mRNA expression via SYBR-Green-based-fluorescence detection following cDNA synthesis from total RNA using oligo-dT primers."--Better: "We quantified mRNA expression using quantitative reverse transcription PCR-(qRT-PCR). Total RNA was reverse transcribed to complementary DNA (cDNA) using-oligo-dT primers, then amplified with SYBR Green fluorescent detection."-```--### 2. Nominalization--**Problem:** Turning verbs into nouns, making writing heavy and indirect--**Examples:**--| Nominalized | Direct |-|-------------|--------|-| "give consideration to" | "consider" |-| "make an assumption" | "assume" |-| "perform an investigation" | "investigate" |-| "conduct an examination" | "examine" |-| "achieve a reduction" | "reduce" |--### 3. Hedging Excessively or Insufficiently--**Excessive hedging** (sounds uncertain):-```-"It could perhaps be possible that the intervention might possibly have some effect-on symptoms under certain conditions."-```--**Insufficient hedging** (overstates conclusions):-```-"The intervention cures depression."-```--**Appropriate hedging:**-```-"The intervention significantly reduced depressive symptoms in this sample,-suggesting it may be effective for treating mild to moderate depression."-```--**Hedging words to use appropriately:**-- Suggests, indicates, implies (not proves, demonstrates for correlational data)-- May, might, could (possibilities)-- Appears to, seems to (observations needing confirmation)-- Likely, probably, possibly (degrees of certainty)--### 4. Anthropomorphism--**Problem:** Attributing human characteristics to non-human entities--**Examples:**--| Anthropomorphic | Scientific |-|----------------|-----------|-| "The study wanted to examine..." | "We aimed to examine..." or "The study examined..." |-| "The data suggest they want..." | "The data suggest that..." |-| "This paper will prove..." | "This paper demonstrates..." |-| "Table 1 tells us..." | "Table 1 shows..." |--### 5. Abbreviation Abuse--**Problems:**-- Too many abbreviations burden the reader-- Abbreviating terms used only once or twice-- Not defining abbreviations at first use--**Guidelines:**-- Only abbreviate terms used ≥3-4 times-- Define at first use in abstract (if used in abstract)-- Define at first use in main text-- Don't abbreviate in title-- Limit to 3-4 new abbreviations per paper when possible-- Use standard abbreviations (DNA, RNA, HIV, etc.) without definition--**Example:**-```-Poor: "We measured Brain-Derived Neurotrophic Factor (BDNF) at baseline. BDNF-levels were elevated."-(Only used twice, abbreviation unnecessary)--Better: "We measured brain-derived neurotrophic factor at baseline. Levels were-elevated."-```--## Specific Sentence-Level Issues--### Dangling Modifiers--**Problem:**-```-"After incubating for 2 hours, we measured absorbance."-(The sentence suggests "we" were incubated)--Better: "After incubating samples for 2 hours, we measured absorbance."-Or: "After 2-hour incubation, we measured absorbance."-```--### Misplaced Commas--**Common errors:**--**Between subject and verb:**-```-Wrong: "The participants in the intervention group, showed improvement."-Right: "The participants in the intervention group showed improvement."-```--**In compound predicates:**-```-Wrong: "We measured blood pressure, and recorded symptoms."-Right: "We measured blood pressure and recorded symptoms."-(No comma before "and" when it doesn't join independent clauses)-```--### Pronoun Agreement--```-Wrong: "Each participant completed their questionnaire."-Right: "Each participant completed his or her questionnaire."-Or better: "Participants completed their questionnaires."-```--### Subject-Verb Agreement--```-Wrong: "The group of participants were heterogeneous."-Right: "The group of participants was heterogeneous."-(Subject is "group" [singular], not "participants")--But: "The participants were heterogeneous." (Plural subject)-```--## Word Choice--### Commonly Confused Words in Scientific Writing--| Often Misused | Correct Usage |-|---------------|---------------|-| **affect / effect** | Affect (verb): influence; Effect (noun): result; Effect (verb): bring about |-| **among / between** | Among: three or more; Between: two |-| **continual / continuous** | Continual: repeated; Continuous: uninterrupted |-| **data is / data are** | Data are (plural); datum is (singular) |-| **fewer / less** | Fewer: countable items; Less: continuous quantities |-| **i.e. / e.g.** | i.e. (that is): restatement; e.g. (for example): examples |-| **imply / infer** | Imply: suggest; Infer: deduce |-| **parameter / variable** | Parameter: population value; Variable: measured characteristic |-| **principal / principle** | Principal: main; Principle: rule or concept |-| **significant** | Reserve for statistical significance, not importance |-| **that / which** | That: restrictive clause; Which: nonrestrictive clause |--### Words to Avoid or Use Carefully--**Avoid informal language:**-- "a lot of" → "many" or "substantial"-- "got" → "obtained" or "became"-- "showed up" → "appeared" or "was evident"--**Avoid vague quantifiers:**-- "some" → specify how many-- "often" → specify frequency-- "recently" → specify timeframe--**Avoid unnecessary modifiers:**-- "very significant" → "significant" (p-value shows degree)-- "quite large" → "large" or specify size-- "rather interesting" → delete or explain why--## Numbers and Units--### When to Use Numerals vs. Words--**Use numerals for:**-- All numbers ≥10-- Numbers with units (5 mg, 3 mL)-- Statistical values (p=0.03, t=2.14)-- Ages, dates, times-- Scores and scales-- Percentages (15%)--**Use words for:**-- Numbers <10 when not connected to units (five participants)-- Numbers beginning a sentence (spell out or restructure)--**Examples:**-```-"Five participants withdrew" OR "There were 5 withdrawals"-(NOT: "5 participants withdrew")--"We tested 15 samples at 3 time points"-"Mean age was 45 years"-```--### Units and Formatting--**Guidelines:**-- Space between number and unit (5 mg, not 5mg)-- No period after units (mg not mg.)-- Use SI units unless field convention differs-- Be consistent in decimal places-- Use commas for thousands in text (12,500 not 12500)--**Ranges:**-- Use en-dash (–) for ranges: 15–20 mg-- Include unit only after second number: 15–20 mg (not 15 mg–20 mg)--## Paragraph Structure--### Ideal Paragraph Length--**Guidelines:**-- 3-7 sentences typically-- One main idea per paragraph-- Too short (<2 sentences): may indicate idea needs development or combining-- Too long (>10 sentences): may need splitting--### Paragraph Coherence--**Techniques:**--**1. Topic sentence:**-```-"Exercise training improves cardiovascular function through multiple mechanisms.-[Following sentences explain these mechanisms]"-```--**2. Transitional phrases:**-- First, second, third, finally-- Furthermore, moreover, in addition-- However, nevertheless, conversely-- Therefore, thus, consequently-- For example, specifically, particularly--**3. Repetition of key terms:**-```-"...this mechanism of action. This mechanism may explain..."-(Not: "...this mechanism. This process may explain...")-```--**4. Parallel structure:**-```-"Group A received the drug. Group B received placebo. Group C received no treatment."-(Not: "Group A received the drug. Placebo was given to Group B. No treatment was-provided to the third group.")-```--## Revision Checklist--### Content Level--- [ ] Does every sentence add value?-- [ ] Are claims supported by data?-- [ ] Is the logic clear and sound?-- [ ] Are interpretations warranted by results?--### Paragraph Level--- [ ] Does each paragraph have one main idea?-- [ ] Are paragraphs in logical order?-- [ ] Are transitions smooth?-- [ ] Is there a clear "red thread"?--### Sentence Level--- [ ] Are sentences clear and concise?-- [ ] Is sentence structure varied?-- [ ] Are there no dangling modifiers?-- [ ] Do subjects and verbs agree?--### Word Level--- [ ] Is word choice precise?-- [ ] Are technical terms defined?-- [ ] Is terminology consistent?-- [ ] Are abbreviations necessary and defined?-- [ ] Are numbers formatted correctly?--### Grammar and Mechanics--- [ ] Is verb tense correct and consistent?-- [ ] Are commas used correctly?-- [ ] Do pronouns agree with antecedents?-- [ ] Is punctuation correct?-- [ ] Is spelling correct (including technical terms)?--## Tools for Improving Writing--### Grammar and Style Checkers--- **Grammarly**: Grammar, style, clarity-- **ProWritingAid**: In-depth writing analysis-- **Hemingway Editor**: Readability, simplification-- **LanguageTool**: Open-source grammar checker--**Caution:** These tools don't understand scientific writing conventions. Use them as a starting point, not final arbiter.--### Readability Metrics--**Flesch Reading Ease:**-- 60-70: acceptable for scientific papers-- <60: may be too complex--**Caution:** Don't sacrifice precision for readability scores designed for general audiences.--### Peer Review--**Most valuable tool:**-- Ask colleagues to read and provide feedback-- Identify unclear passages-- Check logical flow-- Verify interpretations are warranted--## Additional Resources--### Books on Scientific Writing--- *The Elements of Style* by Strunk & White (classic on clear writing)-- *On Writing Well* by William Zinsser-- *Scientific Writing: A Reader and Writer's Guide* by Jean-Luc Lebrun-- *How to Write a Scientific Paper* by George M. Whitesides-- *Style: Lessons in Clarity and Grace* by Joseph Williams--### Online Resources--- **Academic Phrasebank** (University of Manchester): Common academic phrases-- **Purdue OWL**: Grammar, punctuation, style-- **Nature Masterclasses**: Scientific writing courses-- **WritingCenters**: Many universities provide free online resources--### University Writing Centers--Most research universities offer:-- Individual consultations-- Workshops on scientific writing-- Online resources and handouts-- Support for non-native English speakers--## Venue-Specific Writing Styles--### Four Major Writing Style Categories--1. **Broad-audience accessible** (Nature, Science, PNAS)-2. **Clinical-professional** (NEJM, Lancet, JAMA)-3. **Technical-specialist** (field-specific journals)-4. **ML conference** (NeurIPS, ICML, ICLR, CVPR)--### Writing Style Comparison--| Aspect | Nature/Science | Medical | Specialized | ML Conference |-|--------|---------------|---------|-------------|---------------|-| **Sentence length** | 15-20 words | 12-18 words | 18-25 words | 12-20 words |-| **Vocabulary** | Minimal jargon | Clinical terms | Field-specific | Technical + math |-| **Tone** | Engaging, significant | Conservative | Formal | Direct, contribution-focused |-| **Key phrases** | "Here we show" | "We conducted" | "To elucidate" | "We propose", "Our contributions" |--**ML Conference Style:**--**Characteristics:**-- Direct, technical language with mathematical notation-- Contribution-focused (numbered lists common)-- Assumes ML expertise (CNNs, transformers, SGD, etc.)-- Emphasizes novelty and performance gains-- Pseudocode and equations expected--**Example opening (NeurIPS style):**-```-Vision transformers have achieved state-of-the-art performance on image classification,-but their quadratic complexity limits applicability to high-resolution images. We propose-Efficient-ViT, which reduces complexity to O(n log n) while maintaining accuracy. Our-contributions are: (1) a novel sparse attention mechanism, (2) theoretical analysis-showing preserved expressive power, and (3) empirical validation on ImageNet showing-15% speedup with comparable accuracy.-```-- Problem stated with technical context-- Solution previewed-- Numbered contributions-- Quantitative claims--### Key Writing Differences--| Aspect | Nature/Science | Medical | Specialized | ML Conference |-|--------|---------------|---------|-------------|---------------|-| **Paragraph length** | 3-5 sentences | 5-7 sentences | 6-10 sentences | 4-6 sentences |-| **Math/equations** | Minimize | Rare | Moderate | Essential |-| **Active voice** | Preferred | Mixed | Passive OK | Preferred |-| **Hedging** | Moderate | Conservative | Detailed | Minimal (claim gains) |-| **Figure integration** | Tight | Systematic | Detailed | Dense, in-page |--### Evaluation Focus by Venue--| Venue | Key Evaluation Criteria |-|-------|------------------------|-| **Nature/Science** | Accessible to non-specialists? Broad significance clear? Compelling story? |-| **Medical** | Clinical relevance apparent? Professional tone? Methods adequate? |-| **Specialized** | Technical precision? Field expertise shown? Methods detailed? |-| **ML conferences** | Clear contributions? Claims supported by experiments? Reproducible? |--**Common rejection reasons:**-- Poor writing quality/unclear prose-- Inappropriate style for venue-- Overstated claims-- Methods insufficient for reproduction-- Missing key details (baselines, ablations for ML; statistics for journals)--### Quick Style Adaptation Guide--| From → To | Key Changes |-|-----------|-------------|-| **Journal → ML conference** | Add numbered contributions; include equations/pseudocode; emphasize quantitative gains; condense prose |-| **ML conference → Journal** | Remove contribution numbering; expand motivation; separate Results/Discussion; reduce equations in main text |-| **Specialist → Broad** | Simplify language; emphasize broad implications; explain technical concepts; add context for non-experts |-| **Broad → Specialist** | Add technical detail; use field terminology freely; expand mechanistic discussion; cite field literature |-| **Basic science → Clinical** | Add patient/clinical context; use clinical language; emphasize outcomes/implications; cite clinical evidence |--### Pre-Submission Style Checklist--**All venues:**-- [ ] Writing style matches 3-5 recent papers from venue-- [ ] Sentence length appropriate-- [ ] Technical vocabulary level correct-- [ ] Tone consistent with venue-- [ ] No overstated claims--**ML conferences add:**-- [ ] Contributions clearly numbered in intro-- [ ] Mathematical notation correct and consistent-- [ ] Pseudocode/algorithms included where appropriate-- [ ] Claims quantified (e.g., "15% faster", "2.3% accuracy gain")-- [ ] Limitations acknowledged--## Final Thoughts--Effective scientific writing is a skill developed through practice. Key principles:--1. **Clarity** trumps complexity-2. **Conciseness** respects readers' time-3. **Accuracy** builds credibility-4. **Objectivity** maintains scientific integrity-5. **Consistency** aids comprehension-6. **Logical organization** guides readers-7. **Journal-specific adaptation** maximizes publication success--**Remember:** The goal is not to impress readers with vocabulary or complexity, but to communicate your science clearly and precisely so readers can understand, evaluate, and build upon your work. Adapt your writing style to match your target journal's expectations and audience.+Bullets, notes, and placeholders are acceptable in an internal outline. They are not+submission-ready. Final structure may include lists when the target venue or content+benefits from them; there is no universal rule that every scientific section must be+continuous prose.diff --git a/skills/scientific-writing/scripts/_common.py b/skills/scientific-writing/scripts/_common.pynew file mode 100644index 00000000..f57d5f10--- /dev/null+++ b/skills/scientific-writing/scripts/_common.py@@ -0,0 +1,240 @@+"""Shared, dependency-free safety helpers for scientific-writing CLIs."""++from __future__ import annotations++import csv+import io+import json+import sys+from collections.abc import Iterable+from dataclasses import asdict, dataclass+from pathlib import Path+from typing import Any++MAX_FILE_BYTES = 5_000_000+MAX_RECORDS = 10_000+MAX_JSON_NODES = 100_000+MAX_JSON_DEPTH = 50+MAX_CSV_FIELD_BYTES = 100_000+++class InputError(ValueError):+ """Raised when a local input fails a bounded safety check."""+++@dataclass(frozen=True)+class Issue:+ severity: str+ code: str+ location: str | None = None+ item_id: str | None = None++ def to_dict(self) -> dict[str, str]:+ return {key: value for key, value in asdict(self).items() if value is not None}+++def _checked_file(path_value: str | Path, suffixes: Iterable[str]) -> Path:+ path = Path(path_value)+ allowed = {suffix.lower() for suffix in suffixes}+ if path.is_symlink():+ raise InputError("symbolic-link inputs are not accepted")+ if not path.is_file():+ raise InputError("input must be an existing regular file")+ if path.suffix.lower() not in allowed:+ raise InputError(+ f"input extension must be one of: {', '.join(sorted(allowed))}"+ )+ if path.stat().st_size > MAX_FILE_BYTES:+ raise InputError(f"input exceeds {MAX_FILE_BYTES} bytes")+ return path+++def read_text(path_value: str | Path, suffixes: Iterable[str]) -> str:+ path = _checked_file(path_value, suffixes)+ try:+ return path.read_text(encoding="utf-8")+ except UnicodeDecodeError as exc:+ raise InputError("input must be UTF-8 text") from exc+++def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for key, value in pairs:+ if key in result:+ raise InputError("JSON contains a duplicate object key")+ result[key] = value+ return result+++def _reject_nonfinite_json(_value: str) -> None:+ raise InputError("JSON non-finite numbers are not accepted")+++def _check_json_bounds(value: Any, depth: int = 0) -> int:+ if depth > MAX_JSON_DEPTH:+ raise InputError(f"JSON nesting exceeds {MAX_JSON_DEPTH} levels")+ count = 1+ if isinstance(value, dict):+ for child in value.values():+ count += _check_json_bounds(child, depth + 1)+ elif isinstance(value, list):+ if len(value) > MAX_RECORDS:+ raise InputError(f"JSON array exceeds {MAX_RECORDS} records")+ for child in value:+ count += _check_json_bounds(child, depth + 1)+ if count > MAX_JSON_NODES:+ raise InputError(f"JSON exceeds {MAX_JSON_NODES} nodes")+ return count+++def read_json(path_value: str | Path) -> Any:+ text = read_text(path_value, {".json"})+ try:+ value = json.loads(+ text,+ object_pairs_hook=_reject_duplicate_keys,+ parse_constant=_reject_nonfinite_json,+ )+ except (json.JSONDecodeError, RecursionError) as exc:+ raise InputError("input is not valid bounded JSON") from exc+ _check_json_bounds(value)+ return value+++def read_csv(path_value: str | Path) -> tuple[list[str], list[dict[str, str]]]:+ text = read_text(path_value, {".csv"})+ csv.field_size_limit(MAX_CSV_FIELD_BYTES)+ try:+ reader = csv.DictReader(io.StringIO(text, newline=""))+ fields = list(reader.fieldnames or [])+ if not fields or any(not field for field in fields):+ raise InputError("CSV requires a non-empty header row")+ if len(set(fields)) != len(fields):+ raise InputError("CSV contains duplicate header names")+ rows: list[dict[str, str]] = []+ for index, row in enumerate(reader, start=1):+ if index > MAX_RECORDS:+ raise InputError(f"CSV exceeds {MAX_RECORDS} data rows")+ if None in row:+ raise InputError("CSV row has more fields than the header")+ rows.append({key: value or "" for key, value in row.items()})+ except csv.Error as exc:+ raise InputError("input is not valid bounded CSV") from exc+ return fields, rows+++def issue(+ severity: str,+ code: str,+ *,+ location: str | None = None,+ item_id: str | None = None,+) -> Issue:+ if severity not in {"error", "warning", "info"}:+ raise ValueError("unsupported issue severity")+ return Issue(severity=severity, code=code, location=location, item_id=item_id)+++def emit_report(+ tool: str,+ issues: Iterable[Issue],+ *,+ summary: dict[str, Any] | None = None,+) -> int:+ ordered = sorted(+ issues,+ key=lambda item: (+ {"error": 0, "warning": 1, "info": 2}[item.severity],+ item.code,+ item.location or "",+ item.item_id or "",+ ),+ )+ error_count = sum(item.severity == "error" for item in ordered)+ warning_count = sum(item.severity == "warning" for item in ordered)+ payload = {+ "tool": tool,+ "status": "fail" if error_count else "pass",+ "summary": {+ "errors": error_count,+ "warnings": warning_count,+ **(summary or {}),+ },+ "issues": [item.to_dict() for item in ordered],+ }+ print(json.dumps(payload, indent=2, sort_keys=True))+ return 1 if error_count else 0+++def emit_input_error(tool: str, exc: Exception) -> int:+ return emit_report(+ tool,+ [issue("error", "INVALID_INPUT", location=type(exc).__name__)],+ )+++def require_object(value: Any, label: str = "root") -> dict[str, Any]:+ if not isinstance(value, dict):+ raise InputError(f"{label} must be a JSON object")+ return value+++def require_list(value: Any, label: str) -> list[Any]:+ if not isinstance(value, list):+ raise InputError(f"{label} must be a JSON array")+ if len(value) > MAX_RECORDS:+ raise InputError(f"{label} exceeds {MAX_RECORDS} records")+ return value+++def is_nonempty_string(value: Any) -> bool:+ return isinstance(value, str) and bool(value.strip())+++def is_placeholder(value: Any) -> bool:+ if not isinstance(value, str):+ return False+ lowered = value.strip().lower()+ return (+ not lowered+ or "[[todo" in lowered+ or lowered in {"todo", "tbd", "tk", "replace_me", "unknown"}+ )+++def write_new_text(+ path_value: str | Path, content: str, suffixes: Iterable[str]+) -> Path:+ path = Path(path_value)+ allowed = {suffix.lower() for suffix in suffixes}+ if path.suffix.lower() not in allowed:+ raise InputError(+ f"output extension must be one of: {', '.join(sorted(allowed))}"+ )+ if path.exists() or path.is_symlink():+ raise InputError("output already exists; refusing to overwrite")+ parent = path.parent+ if not parent.is_dir() or parent.is_symlink():+ raise InputError("output parent must be an existing regular directory")+ encoded = content.encode("utf-8")+ if len(encoded) > MAX_FILE_BYTES:+ raise InputError(f"output exceeds {MAX_FILE_BYTES} bytes")+ with path.open("x", encoding="utf-8", newline="\n") as handle:+ handle.write(content)+ return path+++def main_guard(tool: str, callback: Any) -> int:+ try:+ return int(callback())+ except (InputError, OSError, ValueError) as exc:+ return emit_input_error(tool, exc)+++def run(tool: str, callback: Any) -> None:+ raise SystemExit(main_guard(tool, callback))+++if __name__ == "__main__":+ print("This module is imported by the scientific-writing command-line tools.")+ sys.exit(0)diff --git a/skills/scientific-writing/scripts/audit_claims.py b/skills/scientific-writing/scripts/audit_claims.pynew file mode 100644index 00000000..ed14ff88--- /dev/null+++ b/skills/scientific-writing/scripts/audit_claims.py@@ -0,0 +1,241 @@+"""Audit claim-to-evidence mappings and local citation markers."""++from __future__ import annotations++import argparse+import re+from typing import Any++from _common import (+ InputError,+ Issue,+ emit_report,+ is_nonempty_string,+ issue,+ read_csv,+ read_json,+ read_text,+ require_list,+ require_object,+ run,+)++TOOL = "audit_claims"+REQUIRED_FIELDS = {+ "claim_id",+ "section",+ "claim_kind",+ "claim_text_sha256",+ "evidence_ids",+ "verification_status",+ "uncertainty",+ "analysis_intent",+}+CLAIM_ID_RE = re.compile(r"^C[0-9]{3,8}$")+EVIDENCE_ID_RE = re.compile(r"^E[0-9]{3,8}$")+SHA256_RE = re.compile(r"^[a-f0-9]{64}$")+CLAIM_MARKER_RE = re.compile(r"\[claim:(C[0-9]{3,8})\]")+EVIDENCE_MARKER_RE = re.compile(+ r"\[evidence:((?:E[0-9]{3,8})(?:\s*,\s*E[0-9]{3,8})*)\]"+)+CITATION_MARKER_RE = re.compile(r"\[@(E[0-9]{3,8})\]")+NUMERIC_RE = re.compile(r"(?<![A-Za-z])(?:[<>]=?\s*)?[0-9]+(?:\.[0-9]+)?%?")+CLAIM_KINDS = {"factual", "numeric", "method", "result", "interpretive", "declaration"}+UNCERTAINTY = {"not_applicable", "not_estimated", "low", "moderate", "high"}+ANALYSIS_INTENT = {"confirmatory", "exploratory", "descriptive", "not_applicable"}+++def _split_evidence_ids(value: str) -> list[str]:+ return [part.strip() for part in value.split(";") if part.strip()]+++def load_sources(path: str) -> dict[str, bool]:+ data = require_object(read_json(path), "source_manifest")+ sources: dict[str, bool] = {}+ for index, raw_source in enumerate(require_list(data.get("sources"), "sources")):+ source = require_object(raw_source, f"sources[{index}]")+ evidence_id = source.get("evidence_id")+ if not isinstance(evidence_id, str) or not EVIDENCE_ID_RE.fullmatch(+ evidence_id+ ):+ raise InputError("source manifest contains an invalid evidence_id")+ if evidence_id in sources:+ raise InputError("source manifest contains duplicate evidence_id values")+ verification = require_object(source.get("verification"), "verification")+ sources[evidence_id] = (+ verification.get("status") == "verified"+ and verification.get("source_opened") is True+ )+ return sources+++def load_claims(+ path: str,+ sources: dict[str, bool],+) -> tuple[dict[str, dict[str, Any]], list[Issue]]:+ fields, rows = read_csv(path)+ if set(fields) != REQUIRED_FIELDS:+ missing = ",".join(sorted(REQUIRED_FIELDS - set(fields)))+ extra = ",".join(sorted(set(fields) - REQUIRED_FIELDS))+ raise InputError(+ f"claim registry headers must match the schema; missing={missing}; extra={extra}"+ )+ issues: list[Issue] = []+ claims: dict[str, dict[str, Any]] = {}+ for row_number, row in enumerate(rows, start=2):+ location = f"row:{row_number}"+ claim_id = row["claim_id"].strip()+ if not CLAIM_ID_RE.fullmatch(claim_id):+ issues.append(issue("error", "INVALID_CLAIM_ID", location=location))+ continue+ if claim_id in claims:+ issues.append(issue("error", "DUPLICATE_CLAIM_ID", item_id=claim_id))+ continue+ claims[claim_id] = row+ if row["claim_kind"] not in CLAIM_KINDS:+ issues.append(issue("error", "INVALID_CLAIM_KIND", item_id=claim_id))+ if not is_nonempty_string(row["section"]):+ issues.append(issue("error", "MISSING_CLAIM_SECTION", item_id=claim_id))+ if not SHA256_RE.fullmatch(row["claim_text_sha256"]):+ issues.append(issue("error", "INVALID_CLAIM_TEXT_HASH", item_id=claim_id))+ if row["verification_status"] != "verified":+ issues.append(issue("error", "CLAIM_NOT_VERIFIED", item_id=claim_id))+ if row["uncertainty"] not in UNCERTAINTY:+ issues.append(+ issue("error", "INVALID_UNCERTAINTY_STATUS", item_id=claim_id)+ )+ if row["analysis_intent"] not in ANALYSIS_INTENT:+ issues.append(issue("error", "INVALID_ANALYSIS_INTENT", item_id=claim_id))++ evidence_ids = _split_evidence_ids(row["evidence_ids"])+ row["_evidence_ids"] = evidence_ids+ if not evidence_ids:+ issues.append(issue("error", "CLAIM_WITHOUT_EVIDENCE", item_id=claim_id))+ for evidence_id in evidence_ids:+ if not EVIDENCE_ID_RE.fullmatch(evidence_id):+ issues.append(+ issue("error", "INVALID_CLAIM_EVIDENCE_ID", item_id=claim_id)+ )+ elif evidence_id not in sources:+ issues.append(+ issue("error", "UNKNOWN_CLAIM_EVIDENCE", item_id=claim_id)+ )+ elif not sources[evidence_id]:+ issues.append(+ issue("error", "UNVERIFIED_CLAIM_EVIDENCE", item_id=claim_id)+ )+ return claims, issues+++def audit_markdown(+ text: str,+ claims: dict[str, dict[str, Any]],+ sources: dict[str, bool],+) -> tuple[list[Issue], set[str]]:+ issues: list[Issue] = []+ used_claims: set[str] = set()+ in_fence = False+ for line_number, line in enumerate(text.splitlines(), start=1):+ stripped = line.strip()+ if stripped.startswith(("```", "~~~")):+ in_fence = not in_fence+ continue+ if in_fence or not stripped or stripped.startswith(("#", "<!--")):+ continue++ line_claims = CLAIM_MARKER_RE.findall(line)+ line_evidence: set[str] = set(CITATION_MARKER_RE.findall(line))+ for group in EVIDENCE_MARKER_RE.findall(line):+ line_evidence.update(part.strip() for part in group.split(","))++ for evidence_id in sorted(line_evidence):+ if evidence_id not in sources:+ issues.append(+ issue(+ "error",+ "UNKNOWN_CITATION_MARKER",+ location=f"line:{line_number}",+ item_id=evidence_id,+ )+ )+ elif not sources[evidence_id]:+ issues.append(+ issue(+ "error",+ "UNVERIFIED_CITATION_MARKER",+ location=f"line:{line_number}",+ item_id=evidence_id,+ )+ )++ for claim_id in line_claims:+ used_claims.add(claim_id)+ if claim_id not in claims:+ issues.append(+ issue(+ "error",+ "UNKNOWN_CLAIM_MARKER",+ location=f"line:{line_number}",+ item_id=claim_id,+ )+ )+ continue+ expected = set(claims[claim_id].get("_evidence_ids", []))+ if not expected.issubset(line_evidence):+ issues.append(+ issue(+ "error",+ "CLAIM_MARKER_MISSING_EVIDENCE_MARKER",+ location=f"line:{line_number}",+ item_id=claim_id,+ )+ )++ if NUMERIC_RE.search(line) and not line_claims:+ issues.append(+ issue(+ "error",+ "UNTAGGED_NUMERIC_CONTENT",+ location=f"line:{line_number}",+ )+ )+ return issues, used_claims+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Audit local Markdown claim markers against a CSV claim registry and "+ "verified JSON source manifest. Output never includes manuscript text."+ )+ )+ parser.add_argument("manuscript", help="UTF-8 Markdown manuscript")+ parser.add_argument("claims", help="UTF-8 CSV claim-evidence registry")+ parser.add_argument("sources", help="UTF-8 JSON source manifest")+ return parser+++def cli() -> int:+ args = build_parser().parse_args()+ sources = load_sources(args.sources)+ claims, issues = load_claims(args.claims, sources)+ text = read_text(args.manuscript, {".md", ".markdown"})+ markdown_issues, used_claims = audit_markdown(text, claims, sources)+ issues.extend(markdown_issues)+ for claim_id in sorted(set(claims) - used_claims):+ issues.append(+ issue("warning", "CLAIM_NOT_USED_IN_MANUSCRIPT", item_id=claim_id)+ )+ return emit_report(+ TOOL,+ issues,+ summary={+ "claims_registered": len(claims),+ "claims_used": len(used_claims),+ "sources_registered": len(sources),+ },+ )+++if __name__ == "__main__":+ run(TOOL, cli)diff --git a/skills/scientific-writing/scripts/check_consistency.py b/skills/scientific-writing/scripts/check_consistency.pynew file mode 100644index 00000000..415be5ce--- /dev/null+++ b/skills/scientific-writing/scripts/check_consistency.py@@ -0,0 +1,408 @@+"""Check numeric and methods-results consistency in a bounded JSON registry."""++from __future__ import annotations++import argparse+import math+import re+from typing import Any++from _common import (+ InputError,+ Issue,+ emit_report,+ is_nonempty_string,+ is_placeholder,+ issue,+ read_json,+ require_list,+ require_object,+ run,+)++TOOL = "check_consistency"+FACT_ID_RE = re.compile(r"^N[0-9]{3,8}$")+METHOD_ID_RE = re.compile(r"^M[0-9]{3,8}$")+RESULT_ID_RE = re.compile(r"^R[0-9]{3,8}$")+OUTCOME_ID_RE = re.compile(r"^O[0-9]{3,8}$")+EVIDENCE_ID_RE = re.compile(r"^E[0-9]{3,8}$")+ANALYSIS_INTENT = {"confirmatory", "exploratory", "descriptive"}+PROTOCOL_STATUS = {+ "prespecified",+ "amended_before_analysis",+ "post_hoc",+ "not_applicable",+}+ROOT_FIELDS = {"schema_version", "numeric_facts", "methods", "results"}+FACT_FIELDS = {+ "fact_id",+ "concept",+ "section",+ "value",+ "unit",+ "numerator",+ "denominator",+ "sample_size",+ "analysis_set",+ "evidence_ids",+}+METHOD_FIELDS = {+ "method_id",+ "name",+ "analysis_intent",+ "protocol_status",+ "outcome_ids",+}+RESULT_FIELDS = {+ "result_id",+ "method_id",+ "outcome_id",+ "analysis_intent",+ "sample_size",+ "evidence_ids",+ "reported_sections",+}+++def _is_number(value: Any) -> bool:+ return (+ isinstance(value, (int, float))+ and not isinstance(value, bool)+ and math.isfinite(value)+ )+++def _check_fields(+ value: dict[str, Any],+ expected: set[str],+ *,+ location: str,+ issues: list[Issue],+) -> None:+ for key in sorted(set(value) - expected):+ issues.append(+ issue("error", "UNKNOWN_SCHEMA_FIELD", location=location, item_id=key)+ )+ for key in sorted(expected - set(value)):+ issues.append(+ issue("error", "MISSING_SCHEMA_FIELD", location=location, item_id=key)+ )+++def _validate_ids(+ values: Any,+ *,+ pattern: re.Pattern[str],+ location: str,+ code: str,+ issues: list[Issue],+) -> list[str]:+ ids = require_list(values, location)+ valid: list[str] = []+ for raw_value in ids:+ if not isinstance(raw_value, str) or not pattern.fullmatch(raw_value):+ issues.append(issue("error", code, location=location))+ else:+ valid.append(raw_value)+ return valid+++def validate_numeric_facts(data: dict[str, Any]) -> tuple[list[Issue], int]:+ issues: list[Issue] = []+ facts = require_list(data.get("numeric_facts"), "numeric_facts")+ seen_ids: set[str] = set()+ by_concept: dict[+ tuple[str, str],+ tuple[float, str, str, int | None, float | None, float | None],+ ] = {}+ for index, raw_fact in enumerate(facts):+ fact = require_object(raw_fact, f"numeric_facts[{index}]")+ location = f"numeric_facts[{index}]"+ _check_fields(fact, FACT_FIELDS, location=location, issues=issues)+ fact_id = fact.get("fact_id")+ if not isinstance(fact_id, str) or not FACT_ID_RE.fullmatch(fact_id):+ issues.append(issue("error", "INVALID_FACT_ID", location=location))+ fact_id = None+ elif fact_id in seen_ids:+ issues.append(issue("error", "DUPLICATE_FACT_ID", item_id=fact_id))+ else:+ seen_ids.add(fact_id)++ concept = fact.get("concept")+ section = fact.get("section")+ unit = fact.get("unit")+ analysis_set = fact.get("analysis_set")+ for key, value in {+ "concept": concept,+ "section": section,+ "unit": unit,+ "analysis_set": analysis_set,+ }.items():+ if not is_nonempty_string(value) or is_placeholder(value):+ issues.append(+ issue("error", "MISSING_FACT_FIELD", location=key, item_id=fact_id)+ )++ value = fact.get("value")+ if not _is_number(value):+ issues.append(issue("error", "INVALID_FACT_VALUE", item_id=fact_id))+ sample_size = fact.get("sample_size")+ if sample_size is not None and (+ not isinstance(sample_size, int)+ or isinstance(sample_size, bool)+ or sample_size <= 0+ ):+ issues.append(issue("error", "INVALID_FACT_SAMPLE_SIZE", item_id=fact_id))++ numerator = fact.get("numerator")+ denominator = fact.get("denominator")+ if numerator is not None or denominator is not None:+ if (+ not _is_number(numerator)+ or not _is_number(denominator)+ or denominator <= 0+ ):+ issues.append(+ issue("error", "INVALID_NUMERATOR_DENOMINATOR", item_id=fact_id)+ )+ elif numerator > denominator:+ issues.append(+ issue("error", "NUMERATOR_EXCEEDS_DENOMINATOR", item_id=fact_id)+ )+ elif unit == "percent" and _is_number(value):+ expected = 100.0 * float(numerator) / float(denominator)+ if not math.isclose(float(value), expected, rel_tol=0.0, abs_tol=0.05):+ issues.append(+ issue("error", "PERCENT_DENOMINATOR_MISMATCH", item_id=fact_id)+ )++ evidence_ids = _validate_ids(+ fact.get("evidence_ids"),+ pattern=EVIDENCE_ID_RE,+ location=f"{location}.evidence_ids",+ code="INVALID_FACT_EVIDENCE_ID",+ issues=issues,+ )+ if not evidence_ids:+ issues.append(issue("error", "FACT_WITHOUT_EVIDENCE", item_id=fact_id))++ if (+ is_nonempty_string(concept)+ and is_nonempty_string(analysis_set)+ and is_nonempty_string(unit)+ and _is_number(value)+ and is_nonempty_string(section)+ ):+ key = (str(concept), str(analysis_set))+ prior = by_concept.get(key)+ current = (+ float(value),+ str(unit),+ str(section),+ (+ sample_size+ if isinstance(sample_size, int)+ and not isinstance(sample_size, bool)+ and sample_size > 0+ else None+ ),+ float(numerator) if _is_number(numerator) else None,+ float(denominator) if _is_number(denominator) else None,+ )+ if prior is not None:+ if prior[1] != current[1]:+ issues.append(issue("error", "UNIT_MISMATCH", item_id=fact_id))+ elif not math.isclose(prior[0], current[0], rel_tol=0.0, abs_tol=1e-12):+ issues.append(+ issue("error", "CROSS_SECTION_VALUE_MISMATCH", item_id=fact_id)+ )+ if prior[3] != current[3]:+ issues.append(+ issue(+ "error",+ "CROSS_SECTION_SAMPLE_SIZE_MISMATCH",+ item_id=fact_id,+ )+ )+ if prior[4:] != current[4:]:+ issues.append(+ issue(+ "error",+ "CROSS_SECTION_DENOMINATOR_MISMATCH",+ item_id=fact_id,+ )+ )+ else:+ by_concept[key] = current+ return issues, len(facts)+++def validate_methods_results(data: dict[str, Any]) -> tuple[list[Issue], int, int]:+ issues: list[Issue] = []+ methods: dict[str, dict[str, Any]] = {}+ expected_outcomes: dict[str, set[str]] = {}+ for index, raw_method in enumerate(require_list(data.get("methods"), "methods")):+ method = require_object(raw_method, f"methods[{index}]")+ _check_fields(+ method,+ METHOD_FIELDS,+ location=f"methods[{index}]",+ issues=issues,+ )+ method_id = method.get("method_id")+ if not isinstance(method_id, str) or not METHOD_ID_RE.fullmatch(method_id):+ issues.append(+ issue("error", "INVALID_METHOD_ID", location=f"methods[{index}]")+ )+ continue+ if method_id in methods:+ issues.append(issue("error", "DUPLICATE_METHOD_ID", item_id=method_id))+ continue+ methods[method_id] = method+ if not is_nonempty_string(method.get("name")) or is_placeholder(+ method.get("name")+ ):+ issues.append(issue("error", "MISSING_METHOD_NAME", item_id=method_id))+ if method.get("analysis_intent") not in ANALYSIS_INTENT:+ issues.append(+ issue("error", "INVALID_METHOD_ANALYSIS_INTENT", item_id=method_id)+ )+ if method.get("protocol_status") not in PROTOCOL_STATUS:+ issues.append(issue("error", "INVALID_PROTOCOL_STATUS", item_id=method_id))+ outcomes = set(+ _validate_ids(+ method.get("outcome_ids"),+ pattern=OUTCOME_ID_RE,+ location=f"methods[{index}].outcome_ids",+ code="INVALID_METHOD_OUTCOME_ID",+ issues=issues,+ )+ )+ if not outcomes:+ issues.append(issue("error", "METHOD_WITHOUT_OUTCOME", item_id=method_id))+ expected_outcomes[method_id] = outcomes++ results = require_list(data.get("results"), "results")+ seen_result_ids: set[str] = set()+ observed_outcomes: dict[str, set[str]] = {method_id: set() for method_id in methods}+ for index, raw_result in enumerate(results):+ result = require_object(raw_result, f"results[{index}]")+ _check_fields(+ result,+ RESULT_FIELDS,+ location=f"results[{index}]",+ issues=issues,+ )+ result_id = result.get("result_id")+ if not isinstance(result_id, str) or not RESULT_ID_RE.fullmatch(result_id):+ issues.append(+ issue("error", "INVALID_RESULT_ID", location=f"results[{index}]")+ )+ result_id = None+ elif result_id in seen_result_ids:+ issues.append(issue("error", "DUPLICATE_RESULT_ID", item_id=result_id))+ else:+ seen_result_ids.add(result_id)++ method_id = result.get("method_id")+ outcome_id = result.get("outcome_id")+ if method_id not in methods:+ issues.append(+ issue("error", "RESULT_WITHOUT_DECLARED_METHOD", item_id=result_id)+ )+ else:+ if not isinstance(outcome_id, str) or not OUTCOME_ID_RE.fullmatch(+ outcome_id+ ):+ issues.append(+ issue("error", "INVALID_RESULT_OUTCOME_ID", item_id=result_id)+ )+ else:+ observed_outcomes[method_id].add(outcome_id)+ if outcome_id not in expected_outcomes[method_id]:+ issues.append(+ issue("error", "UNDECLARED_RESULT_OUTCOME", item_id=result_id)+ )+ if result.get("analysis_intent") != methods[method_id].get(+ "analysis_intent"+ ):+ issues.append(+ issue("error", "ANALYSIS_INTENT_MISMATCH", item_id=result_id)+ )++ sample_size = result.get("sample_size")+ if (+ not isinstance(sample_size, int)+ or isinstance(sample_size, bool)+ or sample_size <= 0+ ):+ issues.append(+ issue("error", "INVALID_RESULT_SAMPLE_SIZE", item_id=result_id)+ )+ evidence_ids = _validate_ids(+ result.get("evidence_ids"),+ pattern=EVIDENCE_ID_RE,+ location=f"results[{index}].evidence_ids",+ code="INVALID_RESULT_EVIDENCE_ID",+ issues=issues,+ )+ if not evidence_ids:+ issues.append(issue("error", "RESULT_WITHOUT_EVIDENCE", item_id=result_id))+ sections = result.get("reported_sections")+ if (+ not isinstance(sections, list)+ or not sections+ or not all(is_nonempty_string(value) for value in sections)+ ):+ issues.append(+ issue("error", "RESULT_WITHOUT_REPORTED_SECTION", item_id=result_id)+ )++ for method_id, outcomes in expected_outcomes.items():+ for outcome_id in sorted(outcomes - observed_outcomes.get(method_id, set())):+ issues.append(+ issue(+ "error",+ "METHOD_OUTCOME_WITHOUT_RESULT",+ location=method_id,+ item_id=outcome_id,+ )+ )+ return issues, len(methods), len(results)+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Check a local JSON registry for repeated numeric values, units, "+ "denominators, sample sizes, and declared methods-results mappings."+ )+ )+ parser.add_argument("registry", help="UTF-8 JSON consistency registry")+ return parser+++def cli() -> int:+ args = build_parser().parse_args()+ data = require_object(read_json(args.registry), "consistency_registry")+ root_issues: list[Issue] = []+ _check_fields(data, ROOT_FIELDS, location="root", issues=root_issues)+ if data.get("schema_version") != "1.0":+ raise InputError("unsupported consistency registry version")+ issues, fact_count = validate_numeric_facts(data)+ issues.extend(root_issues)+ method_issues, method_count, result_count = validate_methods_results(data)+ issues.extend(method_issues)+ return emit_report(+ TOOL,+ issues,+ summary={+ "numeric_facts": fact_count,+ "methods": method_count,+ "results": result_count,+ },+ )+++if __name__ == "__main__":+ run(TOOL, cli)diff --git a/skills/scientific-writing/scripts/check_references.py b/skills/scientific-writing/scripts/check_references.pynew file mode 100644index 00000000..dbc38306--- /dev/null+++ b/skills/scientific-writing/scripts/check_references.py@@ -0,0 +1,219 @@+"""Check local reference identifiers and duplicates without resolving them."""++from __future__ import annotations++import argparse+import re+import unicodedata+from typing import Any++from _common import (+ InputError,+ Issue,+ emit_report,+ is_nonempty_string,+ issue,+ read_json,+ require_list,+ require_object,+ run,+)+from validate_manifest import validate_source_manifest++TOOL = "check_references"+EVIDENCE_ID_RE = re.compile(r"^E[0-9]{3,8}$")+DOI_RE = re.compile(r"^10\.[0-9]{4,9}/\S+$", re.IGNORECASE)+PMID_RE = re.compile(r"^[1-9][0-9]{0,8}$")+PMCID_RE = re.compile(r"^PMC[1-9][0-9]{0,8}$", re.IGNORECASE)+URL_RE = re.compile(r"^https?://[^\s]+$", re.IGNORECASE)+++def normalize_doi(value: str) -> str:+ normalized = value.strip().lower()+ for prefix in ("https://doi.org/", "http://doi.org/", "doi:"):+ if normalized.startswith(prefix):+ normalized = normalized[len(prefix) :]+ break+ return normalized.rstrip(".,;")+++def normalize_title(value: str) -> str:+ decomposed = unicodedata.normalize("NFKD", value).casefold()+ return " ".join(re.findall(r"[a-z0-9]+", decomposed))+++def normalize_isbn(value: str) -> str:+ return re.sub(r"[^0-9Xx]", "", value)+++def valid_isbn(value: str) -> bool:+ normalized = normalize_isbn(value)+ if len(normalized) == 10:+ if not re.fullmatch(r"[0-9]{9}[0-9Xx]", normalized):+ return False+ total = sum(+ (10 - index) * (10 if char.lower() == "x" else int(char))+ for index, char in enumerate(normalized)+ )+ return total % 11 == 0+ if len(normalized) == 13 and normalized.isdigit():+ total = sum(+ int(char) * (1 if index % 2 == 0 else 3)+ for index, char in enumerate(normalized)+ )+ return total % 10 == 0+ return False+++def _record_duplicate(+ seen: dict[str, str],+ normalized: str,+ evidence_id: str,+ code: str,+ issues: list[Issue],+) -> None:+ if not normalized:+ return+ prior = seen.get(normalized)+ if prior is not None and prior != evidence_id:+ issues.append(+ issue(+ "error",+ code,+ location=prior,+ item_id=evidence_id,+ )+ )+ else:+ seen[normalized] = evidence_id+++def check_sources(data: dict[str, Any]) -> tuple[list[Issue], int]:+ issues = validate_source_manifest(data, require_verified=False)+ sources = require_list(data.get("sources"), "sources")+ evidence_ids: set[str] = set()+ seen_dois: dict[str, str] = {}+ seen_pmids: dict[str, str] = {}+ seen_pmcids: dict[str, str] = {}+ seen_isbns: dict[str, str] = {}+ seen_titles: dict[str, str] = {}++ for index, raw_source in enumerate(sources):+ source = require_object(raw_source, f"sources[{index}]")+ evidence_id = source.get("evidence_id")+ if not isinstance(evidence_id, str) or not EVIDENCE_ID_RE.fullmatch(+ evidence_id+ ):+ issues.append(+ issue("error", "INVALID_EVIDENCE_ID", location=f"sources[{index}]")+ )+ continue+ if evidence_id in evidence_ids:+ issues.append(issue("error", "DUPLICATE_EVIDENCE_ID", item_id=evidence_id))+ continue+ evidence_ids.add(evidence_id)++ title = source.get("title")+ if is_nonempty_string(title):+ _record_duplicate(+ seen_titles,+ normalize_title(str(title)),+ evidence_id,+ "POSSIBLE_DUPLICATE_TITLE",+ issues,+ )++ identifiers = require_object(+ source.get("identifiers"), f"sources[{index}].identifiers"+ )+ doi = identifiers.get("doi")+ if is_nonempty_string(doi):+ normalized_doi = normalize_doi(str(doi))+ if not DOI_RE.fullmatch(normalized_doi):+ issues.append(issue("error", "MALFORMED_DOI", item_id=evidence_id))+ else:+ _record_duplicate(+ seen_dois,+ normalized_doi,+ evidence_id,+ "DUPLICATE_DOI",+ issues,+ )++ pmid = identifiers.get("pmid")+ if is_nonempty_string(pmid):+ normalized_pmid = str(pmid).strip()+ if not PMID_RE.fullmatch(normalized_pmid):+ issues.append(issue("error", "MALFORMED_PMID", item_id=evidence_id))+ else:+ _record_duplicate(+ seen_pmids,+ normalized_pmid,+ evidence_id,+ "DUPLICATE_PMID",+ issues,+ )++ pmcid = identifiers.get("pmcid")+ if is_nonempty_string(pmcid):+ normalized_pmcid = str(pmcid).strip().upper()+ if not PMCID_RE.fullmatch(normalized_pmcid):+ issues.append(issue("error", "MALFORMED_PMCID", item_id=evidence_id))+ else:+ _record_duplicate(+ seen_pmcids,+ normalized_pmcid,+ evidence_id,+ "DUPLICATE_PMCID",+ issues,+ )++ isbn = identifiers.get("isbn")+ if is_nonempty_string(isbn):+ normalized_isbn = normalize_isbn(str(isbn))+ if not valid_isbn(normalized_isbn):+ issues.append(issue("error", "MALFORMED_ISBN", item_id=evidence_id))+ else:+ _record_duplicate(+ seen_isbns,+ normalized_isbn.upper(),+ evidence_id,+ "DUPLICATE_ISBN",+ issues,+ )++ url = identifiers.get("url")+ if is_nonempty_string(url) and not URL_RE.fullmatch(str(url).strip()):+ issues.append(issue("error", "MALFORMED_URL", item_id=evidence_id))++ if not any(is_nonempty_string(value) for value in identifiers.values()):+ issues.append(+ issue("warning", "NO_IDENTIFIER_TO_CHECK", item_id=evidence_id)+ )+ return issues, len(sources)+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Validate DOI, PMID, PMCID, ISBN, and URL syntax and flag duplicates "+ "in a local source manifest. No identifier is resolved over a network."+ )+ )+ parser.add_argument("sources", help="UTF-8 JSON source manifest")+ return parser+++def cli() -> int:+ args = build_parser().parse_args()+ data = require_object(read_json(args.sources), "source_manifest")+ if data.get("schema_version") != "1.0":+ raise InputError("unsupported source-manifest version")+ issues, count = check_sources(data)+ return emit_report(+ TOOL, issues, summary={"sources_checked": count, "network_used": False}+ )+++if __name__ == "__main__":+ run(TOOL, cli)diff --git a/skills/scientific-writing/scripts/generate_image.py b/skills/scientific-writing/scripts/generate_image.pydeleted file mode 100755index 9c613b89..00000000--- a/skills/scientific-writing/scripts/generate_image.py+++ /dev/null@@ -1,281 +0,0 @@-#!/usr/bin/env python3-"""-Generate and edit images using OpenRouter API with various image generation models.--Supports models like:-- google/gemini-3.1-flash-image-preview (generation and editing)-- black-forest-labs/flux.2-pro (generation and editing)-- black-forest-labs/flux.2-flex (generation)-- And more image generation models available on OpenRouter--For image editing, provide an input image along with an editing prompt.-"""--import sys-import json-import base64-import argparse-from pathlib import Path-from typing import Optional---def check_env_file() -> Optional[str]:- """Check if .env file exists and contains OPENROUTER_API_KEY."""- # Look for .env in current directory and parent directories- current_dir = Path.cwd()- for parent in [current_dir] + list(current_dir.parents):- env_file = parent / ".env"- if env_file.exists():- with open(env_file, 'r') as f:- for line in f:- if line.startswith('OPENROUTER_API_KEY='):- api_key = line.split('=', 1)[1].strip().strip('"').strip("'")- if api_key:- return api_key- return None---def load_image_as_base64(image_path: str) -> str:- """Load an image file and return it as a base64 data URL."""- path = Path(image_path)- if not path.exists():- print(f"❌ Error: Image file not found: {image_path}")- sys.exit(1)-- # Determine MIME type from extension- ext = path.suffix.lower()- mime_types = {- '.png': 'image/png',- '.jpg': 'image/jpeg',- '.jpeg': 'image/jpeg',- '.gif': 'image/gif',- '.webp': 'image/webp',- }- mime_type = mime_types.get(ext, 'image/png')-- with open(path, 'rb') as f:- image_data = f.read()-- base64_data = base64.b64encode(image_data).decode('utf-8')- return f"data:{mime_type};base64,{base64_data}"---def save_base64_image(base64_data: str, output_path: str) -> None:- """Save base64 encoded image to file."""- # Remove data URL prefix if present- if ',' in base64_data:- base64_data = base64_data.split(',', 1)[1]-- # Decode and save- image_data = base64.b64decode(base64_data)- with open(output_path, 'wb') as f:- f.write(image_data)---def generate_image(- prompt: str,- model: str = "google/gemini-3.1-flash-image-preview",- output_path: str = "generated_image.png",- api_key: Optional[str] = None,- input_image: Optional[str] = None-) -> dict:- """- Generate or edit an image using OpenRouter API.-- Args:- prompt: Text description of the image to generate, or editing instructions- model: OpenRouter model ID (default: google/gemini-3.1-flash-image-preview)- output_path: Path to save the generated image- api_key: OpenRouter API key (will check .env if not provided)- input_image: Path to an input image for editing (optional)-- Returns:- dict: Response from OpenRouter API- """- try:- import requests- except ImportError:- print("Error: 'requests' library not found. Install with: pip install requests")- sys.exit(1)-- # Check for API key- if not api_key:- api_key = check_env_file()-- if not api_key:- print("❌ Error: OPENROUTER_API_KEY not found!")- print("\nPlease create a .env file in your project directory with:")- print("OPENROUTER_API_KEY=your-api-key-here")- print("\nOr set the environment variable:")- print("export OPENROUTER_API_KEY=your-api-key-here")- print("\nGet your API key from: https://openrouter.ai/keys")- sys.exit(1)-- # Determine if this is generation or editing- is_editing = input_image is not None-- if is_editing:- print(f"✏️ Editing image with model: {model}")- print(f"📷 Input image: {input_image}")- print(f"📝 Edit prompt: {prompt}")-- # Load input image as base64- image_data_url = load_image_as_base64(input_image)-- # Build multimodal message content for image editing- message_content = [- {- "type": "text",- "text": prompt- },- {- "type": "image_url",- "image_url": {- "url": image_data_url- }- }- ]- else:- print(f"🎨 Generating image with model: {model}")- print(f"📝 Prompt: {prompt}")- message_content = prompt-- # Make API request- response = requests.post(- url="https://openrouter.ai/api/v1/chat/completions",- headers={- "Authorization": f"Bearer {api_key}",- "Content-Type": "application/json",- },- json={- "model": model,- "messages": [- {- "role": "user",- "content": message_content- }- ],- "modalities": ["image", "text"]- }- )-- # Check for errors- if response.status_code != 200:- print(f"❌ API Error ({response.status_code}): {response.text}")- sys.exit(1)-- result = response.json()-- # Extract and save image- if result.get("choices"):- message = result["choices"][0]["message"]-- # Handle both 'images' and 'content' response formats- images = []-- if message.get("images"):- images = message["images"]- elif message.get("content"):- # Some models return content as array with image parts- content = message["content"]- if isinstance(content, list):- for part in content:- if isinstance(part, dict) and part.get("type") == "image":- images.append(part)-- if images:- # Save the first image- image = images[0]- if "image_url" in image:- image_url = image["image_url"]["url"]- save_base64_image(image_url, output_path)- print(f"✅ Image saved to: {output_path}")- elif "url" in image:- save_base64_image(image["url"], output_path)- print(f"✅ Image saved to: {output_path}")- else:- print(f"⚠️ Unexpected image format: {image}")- else:- print("⚠️ No image found in response")- if message.get("content"):- print(f"Response content: {message['content']}")- else:- print("❌ No choices in response")- print(f"Response: {json.dumps(result, indent=2)}")-- return result---def main():- parser = argparse.ArgumentParser(- description="Generate or edit images using OpenRouter API",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Examples:- # Generate with default model (Gemini 3.1 Flash Image Preview)- python generate_image.py "A beautiful sunset over mountains"-- # Use a specific model- python generate_image.py "A cat in space" --model "black-forest-labs/flux.2-pro"-- # Specify output path- python generate_image.py "Abstract art" --output my_image.png-- # Edit an existing image- python generate_image.py "Make the sky purple" --input photo.jpg --output edited.png-- # Edit with a specific model- python generate_image.py "Add a hat to the person" --input portrait.png -m "black-forest-labs/flux.2-pro"--Popular image models:- - google/gemini-3.1-flash-image-preview (default, high quality, generation + editing)- - black-forest-labs/flux.2-pro (fast, high quality, generation + editing)- - black-forest-labs/flux.2-flex (development version)- """- )-- parser.add_argument(- "prompt",- type=str,- help="Text description of the image to generate, or editing instructions"- )-- parser.add_argument(- "--model", "-m",- type=str,- default="google/gemini-3.1-flash-image-preview",- help="OpenRouter model ID (default: google/gemini-3.1-flash-image-preview)"- )-- parser.add_argument(- "--output", "-o",- type=str,- default="generated_image.png",- help="Output file path (default: generated_image.png)"- )-- parser.add_argument(- "--input", "-i",- type=str,- help="Input image path for editing (enables edit mode)"- )-- parser.add_argument(- "--api-key",- type=str,- help="OpenRouter API key (will check .env if not provided)"- )-- args = parser.parse_args()-- generate_image(- prompt=args.prompt,- model=args.model,- output_path=args.output,- api_key=args.api_key,- input_image=args.input- )---if __name__ == "__main__":- main()diff --git a/skills/scientific-writing/scripts/generate_schematic.py b/skills/scientific-writing/scripts/generate_schematic.pydeleted file mode 100644index 43331870..00000000--- a/skills/scientific-writing/scripts/generate_schematic.py+++ /dev/null@@ -1,139 +0,0 @@-#!/usr/bin/env python3-"""-Scientific schematic generation using Nano Banana 2.--Generate any scientific diagram by describing it in natural language.-Nano Banana 2 handles everything automatically with smart iterative refinement.--Smart iteration: Only regenerates if quality is below threshold for your document type.-Quality review: Uses Gemini 3.6 Flash for professional scientific evaluation.--Usage:- # Generate for journal paper (highest quality threshold)- python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal-- # Generate for presentation (lower threshold, faster)- python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation-- # Generate for poster- python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster-"""--import argparse-import os-import subprocess-import sys-from pathlib import Path---def main():- """Command-line interface."""- parser = argparse.ArgumentParser(- description="Generate scientific schematics using AI with smart iterative refinement",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-How it works:- Simply describe your diagram in natural language- Nano Banana 2 generates it automatically with:- - Smart iteration (only regenerates if quality is below threshold)- - Quality review by Gemini 3.6 Flash- - Document-type aware quality thresholds- - Publication-ready output--Document Types (quality thresholds):- journal 8.5/10 - Nature, Science, peer-reviewed journals- conference 8.0/10 - Conference papers- thesis 8.0/10 - Dissertations, theses- grant 8.0/10 - Grant proposals- preprint 7.5/10 - arXiv, bioRxiv, etc.- report 7.5/10 - Technical reports- poster 7.0/10 - Academic posters- presentation 6.5/10 - Slides, talks- default 7.5/10 - General purpose--Examples:- # Generate for journal paper (strict quality)- python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal-- # Generate for poster (moderate quality)- python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster-- # Generate for slides (faster, lower threshold)- python generate_schematic.py "System diagram" -o system.png --doc-type presentation-- # Custom max iterations- python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2-- # Verbose output- python generate_schematic.py "Circuit diagram" -o circuit.png -v--Environment Variables:- OPENROUTER_API_KEY Required for AI generation- """- )-- parser.add_argument("prompt",- help="Description of the diagram to generate")- parser.add_argument("-o", "--output", required=True,- help="Output file path")- parser.add_argument("--doc-type", default="default",- choices=["journal", "conference", "poster", "presentation",- "report", "grant", "thesis", "preprint", "default"],- help="Document type for quality threshold (default: default)")- parser.add_argument("--iterations", type=int, default=2,- help="Maximum refinement iterations (default: 2, max: 2)")- parser.add_argument("--api-key",- help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")- parser.add_argument("-v", "--verbose", action="store_true",- help="Verbose output")-- args = parser.parse_args()-- # Check for API key- api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")- if not api_key:- print("Error: OPENROUTER_API_KEY environment variable not set")- print("\nFor AI generation, you need an OpenRouter API key.")- print("Get one at: https://openrouter.ai/keys")- print("\nSet it with:")- print(" export OPENROUTER_API_KEY='your_api_key'")- print("\nOr use --api-key flag")- sys.exit(1)-- # Find AI generation script- script_dir = Path(__file__).parent- ai_script = script_dir / "generate_schematic_ai.py"-- if not ai_script.exists():- print(f"Error: AI generation script not found: {ai_script}")- sys.exit(1)-- # Build command- cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]-- if args.doc_type != "default":- cmd.extend(["--doc-type", args.doc_type])-- # Enforce max 2 iterations- iterations = min(args.iterations, 2)- if iterations != 2:- cmd.extend(["--iterations", str(iterations)])-- if args.verbose:- cmd.append("-v")-- # Execute — pass API key via environment to avoid exposure in process listings- try:- env = os.environ.copy()- if api_key:- env["OPENROUTER_API_KEY"] = api_key- result = subprocess.run(cmd, check=False, env=env)- sys.exit(result.returncode)- except Exception as e:- print(f"Error executing AI generation: {e}")- sys.exit(1)---if __name__ == "__main__":- main()-diff --git a/skills/scientific-writing/scripts/generate_schematic_ai.py b/skills/scientific-writing/scripts/generate_schematic_ai.pydeleted file mode 100644index 651b6c76..00000000--- a/skills/scientific-writing/scripts/generate_schematic_ai.py+++ /dev/null@@ -1,817 +0,0 @@-#!/usr/bin/env python3-"""-AI-powered scientific schematic generation using Nano Banana 2.--This script uses a smart iterative refinement approach:-1. Generate initial image with Nano Banana 2-2. AI quality review using Gemini 3.6 Flash for scientific critique-3. Only regenerate if quality is below threshold for document type-4. Repeat until quality meets standards (max iterations)--Requirements:- - OPENROUTER_API_KEY environment variable- - requests library--Usage:- python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png- python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2- python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster-"""--import argparse-import base64-import json-import os-import sys-import time-from pathlib import Path-from typing import Optional, Dict, Any, List, Tuple--try:- import requests-except ImportError:- print("Error: requests library not found. Install with: pip install requests")- sys.exit(1)--# Try to load .env file from multiple potential locations-def _load_env_file():- """Load .env file from current directory or script directory only."""- try:- from dotenv import load_dotenv- except ImportError:- return False-- for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:- if candidate.exists():- load_dotenv(dotenv_path=candidate, override=False)- return True-- return False---class ScientificSchematicGenerator:- """Generate scientific schematics using AI with smart iterative refinement.-- Uses Gemini 3.6 Flash for quality review to determine if regeneration is needed.- Multiple passes only occur if the generated schematic doesn't meet the- quality threshold for the target document type.- """-- # Quality thresholds by document type (score out of 10)- # Higher thresholds for more formal publications- QUALITY_THRESHOLDS = {- "journal": 8.5, # Nature, Science, etc. - highest standards- "conference": 8.0, # Conference papers - high standards- "poster": 7.0, # Academic posters - good quality- "presentation": 6.5, # Slides/talks - clear but less formal- "report": 7.5, # Technical reports - professional- "grant": 8.0, # Grant proposals - must be compelling- "thesis": 8.0, # Dissertations - formal academic- "preprint": 7.5, # arXiv, etc. - good quality- "default": 7.5, # Default threshold- }-- # Scientific diagram best practices prompt template- SCIENTIFIC_DIAGRAM_GUIDELINES = """-Create a high-quality scientific diagram with these requirements:--VISUAL QUALITY:-- Clean white or light background (no textures or gradients)-- High contrast for readability and printing-- Professional, publication-ready appearance-- Sharp, clear lines and text-- Adequate spacing between elements to prevent crowding--TYPOGRAPHY:-- Clear, readable sans-serif fonts (Arial, Helvetica style)-- Minimum 10pt font size for all labels-- Consistent font sizes throughout-- All text horizontal or clearly readable-- No overlapping text--SCIENTIFIC STANDARDS:-- Accurate representation of concepts-- Clear labels for all components-- Include scale bars, legends, or axes where appropriate-- Use standard scientific notation and symbols-- Include units where applicable--ACCESSIBILITY:-- Colorblind-friendly color palette (use Okabe-Ito colors if using color)-- High contrast between elements-- Redundant encoding (shapes + colors, not just colors)-- Works well in grayscale--LAYOUT:-- Logical flow (left-to-right or top-to-bottom)-- Clear visual hierarchy-- Balanced composition-- Appropriate use of whitespace-- No clutter or unnecessary decorative elements--IMPORTANT - NO FIGURE NUMBERS:-- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image-- Do NOT add captions or titles like "Figure: ..." at the top or bottom-- Figure numbers and captions are added separately in the document/LaTeX-- The diagram should contain only the visual content itself-"""-- def __init__(self, api_key: Optional[str] = None, verbose: bool = False):- """- Initialize the generator.-- Args:- api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)- verbose: Print detailed progress information- """- # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file- self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")-- # If not found in environment, try loading from .env file- if not self.api_key:- _load_env_file()- self.api_key = os.getenv("OPENROUTER_API_KEY")-- if not self.api_key:- raise ValueError(- "OPENROUTER_API_KEY not found. Please either:\n"- " 1. Set the OPENROUTER_API_KEY environment variable\n"- " 2. Add OPENROUTER_API_KEY to your .env file\n"- " 3. Pass api_key parameter to the constructor\n"- "Get your API key from: https://openrouter.ai/keys"- )-- self.verbose = verbose- self._last_error = None # Track last error for better reporting- self.base_url = "https://openrouter.ai/api/v1"- # Nano Banana 2 - Google's advanced image generation model- # https://openrouter.ai/google/gemini-3.6-flash- self.image_model = "google/gemini-3.1-flash-image-preview"- # Gemini 3.6 Flash for quality review - excellent vision and reasoning- self.review_model = "google/gemini-3.6-flash"-- def _log(self, message: str):- """Log message if verbose mode is enabled."""- if self.verbose:- print(f"[{time.strftime('%H:%M:%S')}] {message}")-- def _make_request(self, model: str, messages: List[Dict[str, Any]],- modalities: Optional[List[str]] = None) -> Dict[str, Any]:- """- Make a request to OpenRouter API.-- Args:- model: Model identifier- messages: List of message dictionaries- modalities: Optional list of modalities (e.g., ["image", "text"])-- Returns:- API response as dictionary- """- headers = {- "Authorization": f"Bearer {self.api_key}",- "Content-Type": "application/json",- "HTTP-Referer": "https://github.com/scientific-writer",- "X-Title": "Scientific Schematic Generator"- }-- payload = {- "model": model,- "messages": messages- }-- if modalities:- payload["modalities"] = modalities-- self._log(f"Making request to {model}...")-- try:- response = requests.post(- f"{self.base_url}/chat/completions",- headers=headers,- json=payload,- timeout=120- )-- # Try to get response body even on error- try:- response_json = response.json()- except json.JSONDecodeError:- response_json = {"raw_text": response.text[:500]}-- # Check for HTTP errors but include response body in error message- if response.status_code != 200:- error_detail = response_json.get("error", response_json)- self._log(f"HTTP {response.status_code}: {error_detail}")- raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")-- return response_json- except requests.exceptions.Timeout:- raise RuntimeError("API request timed out after 120 seconds")- except requests.exceptions.RequestException as e:- raise RuntimeError(f"API request failed: {str(e)}")-- def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:- """- Extract base64-encoded image from API response.-- For Nano Banana 2, images are returned in the 'images' field of the message,- not in the 'content' field.-- Args:- response: API response dictionary-- Returns:- Image bytes or None if not found- """- try:- choices = response.get("choices", [])- if not choices:- self._log("No choices in response")- return None-- message = choices[0].get("message", {})-- # IMPORTANT: Nano Banana 2 returns images in the 'images' field- images = message.get("images", [])- if images and len(images) > 0:- self._log(f"Found {len(images)} image(s) in 'images' field")-- # Get first image- first_image = images[0]- if isinstance(first_image, dict):- # Extract image_url- if first_image.get("type") == "image_url":- url = first_image.get("image_url", {})- if isinstance(url, dict):- url = url.get("url", "")-- if url and url.startswith("data:image"):- # Extract base64 data after comma- if "," in url:- base64_str = url.split(",", 1)[1]- # Clean whitespace- base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')- self._log(f"Extracted base64 data (length: {len(base64_str)})")- return base64.b64decode(base64_str)-- # Fallback: check content field (for other models or future changes)- content = message.get("content", "")-- if self.verbose:- self._log(f"Content type: {type(content)}, length: {len(str(content))}")-- # Handle string content- if isinstance(content, str) and "data:image" in content:- import re- match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)- if match:- base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')- self._log(f"Found image in content field (length: {len(base64_str)})")- return base64.b64decode(base64_str)-- # Handle list content- if isinstance(content, list):- for i, block in enumerate(content):- if isinstance(block, dict) and block.get("type") == "image_url":- url = block.get("image_url", {})- if isinstance(url, dict):- url = url.get("url", "")- if url and url.startswith("data:image") and "," in url:- base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')- self._log(f"Found image in content block {i}")- return base64.b64decode(base64_str)-- self._log("No image data found in response")- return None-- except Exception as e:- self._log(f"Error extracting image: {str(e)}")- import traceback- if self.verbose:- traceback.print_exc()- return None-- def _image_to_base64(self, image_path: str) -> str:- """- Convert image file to base64 data URL.-- Args:- image_path: Path to image file-- Returns:- Base64 data URL string- """- with open(image_path, "rb") as f:- image_data = f.read()-- # Determine image type from extension- ext = Path(image_path).suffix.lower()- mime_type = {- ".png": "image/png",- ".jpg": "image/jpeg",- ".jpeg": "image/jpeg",- ".gif": "image/gif",- ".webp": "image/webp"- }.get(ext, "image/png")-- base64_data = base64.b64encode(image_data).decode("utf-8")- return f"data:{mime_type};base64,{base64_data}"-- def generate_image(self, prompt: str) -> Optional[bytes]:- """- Generate an image using Nano Banana 2.-- Args:- prompt: Description of the diagram to generate-- Returns:- Image bytes or None if generation failed- """- self._last_error = None # Reset error-- messages = [- {- "role": "user",- "content": prompt- }- ]-- try:- response = self._make_request(- model=self.image_model,- messages=messages,- modalities=["image", "text"]- )-- # Debug: print response structure if verbose- if self.verbose:- self._log(f"Response keys: {response.keys()}")- if "error" in response:- self._log(f"API Error: {response['error']}")- if "choices" in response and response["choices"]:- msg = response["choices"][0].get("message", {})- self._log(f"Message keys: {msg.keys()}")- # Show content preview without printing huge base64 data- content = msg.get("content", "")- if isinstance(content, str):- preview = content[:200] + "..." if len(content) > 200 else content- self._log(f"Content preview: {preview}")- elif isinstance(content, list):- self._log(f"Content is list with {len(content)} items")- for i, item in enumerate(content[:3]):- if isinstance(item, dict):- self._log(f" Item {i}: type={item.get('type')}")-- # Check for API errors in response- if "error" in response:- error_msg = response["error"]- if isinstance(error_msg, dict):- error_msg = error_msg.get("message", str(error_msg))- self._last_error = f"API Error: {error_msg}"- print(f"✗ {self._last_error}")- return None-- image_data = self._extract_image_from_response(response)- if image_data:- self._log(f"✓ Generated image ({len(image_data)} bytes)")- else:- self._last_error = "No image data in API response - model may not support image generation"- self._log(f"✗ {self._last_error}")- # Additional debug info when image extraction fails- if self.verbose and "choices" in response:- msg = response["choices"][0].get("message", {})- self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")-- return image_data- except RuntimeError as e:- self._last_error = str(e)- self._log(f"✗ Generation failed: {self._last_error}")- return None- except Exception as e:- self._last_error = f"Unexpected error: {str(e)}"- self._log(f"✗ Generation failed: {self._last_error}")- import traceback- if self.verbose:- traceback.print_exc()- return None-- def review_image(self, image_path: str, original_prompt: str,- iteration: int, doc_type: str = "default",- max_iterations: int = 2) -> Tuple[str, float, bool]:- """- Review generated image using Gemini 3.6 Flash for quality analysis.-- Uses Gemini 3.6 Flash's superior vision and reasoning capabilities to- evaluate the schematic quality and determine if regeneration is needed.-- Args:- image_path: Path to the generated image- original_prompt: Original user prompt- iteration: Current iteration number- doc_type: Document type (journal, poster, presentation, etc.)- max_iterations: Maximum iterations allowed-- Returns:- Tuple of (critique text, quality score 0-10, needs_improvement bool)- """- # Use Gemini 3.6 Flash for review - excellent vision and analysis- image_data_url = self._image_to_base64(image_path)-- # Get quality threshold for this document type- threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),- self.QUALITY_THRESHOLDS["default"])-- review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.--ORIGINAL REQUEST: {original_prompt}--DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)-ITERATION: {iteration}/{max_iterations}--Carefully evaluate this diagram on these criteria:--1. **Scientific Accuracy** (0-2 points)- - Correct representation of concepts- - Proper notation and symbols- - Accurate relationships shown--2. **Clarity and Readability** (0-2 points)- - Easy to understand at a glance- - Clear visual hierarchy- - No ambiguous elements--3. **Label Quality** (0-2 points)- - All important elements labeled- - Labels are readable (appropriate font size)- - Consistent labeling style--4. **Layout and Composition** (0-2 points)- - Logical flow (top-to-bottom or left-to-right)- - Balanced use of space- - No overlapping elements--5. **Professional Appearance** (0-2 points)- - Publication-ready quality- - Clean, crisp lines and shapes- - Appropriate colors/contrast--RESPOND IN THIS EXACT FORMAT:-SCORE: [total score 0-10]--STRENGTHS:-- [strength 1]-- [strength 2]--ISSUES:-- [issue 1 if any]-- [issue 2 if any]--VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]--If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.-If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""-- messages = [- {- "role": "user",- "content": [- {- "type": "text",- "text": review_prompt- },- {- "type": "image_url",- "image_url": {- "url": image_data_url- }- }- ]- }- ]-- try:- # Use Gemini 3.6 Flash for high-quality review- response = self._make_request(- model=self.review_model,- messages=messages- )-- # Extract text response- choices = response.get("choices", [])- if not choices:- return "Image generated successfully", 8.0-- message = choices[0].get("message", {})- content = message.get("content", "")-- # Check reasoning field (Nano Banana 2 puts analysis here)- reasoning = message.get("reasoning", "")- if reasoning and not content:- content = reasoning-- if isinstance(content, list):- # Extract text from content blocks- text_parts = []- for block in content:- if isinstance(block, dict) and block.get("type") == "text":- text_parts.append(block.get("text", ""))- content = "\n".join(text_parts)-- # Try to extract score- score = 7.5 # Default score if extraction fails- import re-- # Look for SCORE: X or SCORE: X/10 format- score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)- if score_match:- score = float(score_match.group(1))- else:- # Fallback: look for any score pattern- score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)- if score_match:- score = float(score_match.group(1))-- # Determine if improvement is needed based on verdict or score- needs_improvement = False- if "NEEDS_IMPROVEMENT" in content.upper():- needs_improvement = True- elif score < threshold:- needs_improvement = True-- self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")- self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")-- return (content if content else "Image generated successfully",- score,- needs_improvement)- except Exception as e:- self._log(f"Review skipped: {str(e)}")- # Don't fail the whole process if review fails - assume acceptable- return "Image generated successfully (review skipped)", 7.5, False-- def improve_prompt(self, original_prompt: str, critique: str,- iteration: int) -> str:- """- Improve the generation prompt based on critique.-- Args:- original_prompt: Original user prompt- critique: Review critique from previous iteration- iteration: Current iteration number-- Returns:- Improved prompt for next generation- """- improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}--USER REQUEST: {original_prompt}--ITERATION {iteration}: Based on previous feedback, address these specific improvements:-{critique}--Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""-- return improved_prompt-- def generate_iterative(self, user_prompt: str, output_path: str,- iterations: int = 2,- doc_type: str = "default") -> Dict[str, Any]:- """- Generate scientific schematic with smart iterative refinement.-- Only regenerates if the quality score is below the threshold for the- specified document type. This saves API calls and time when the first- generation is already good enough.-- Args:- user_prompt: User's description of desired diagram- output_path: Path to save final image- iterations: Maximum refinement iterations (default: 2, max: 2)- doc_type: Document type for quality threshold (journal, poster, etc.)-- Returns:- Dictionary with generation results and metadata- """- output_path = Path(output_path)- output_dir = output_path.parent- output_dir.mkdir(parents=True, exist_ok=True)-- base_name = output_path.stem- extension = output_path.suffix or ".png"-- # Get quality threshold for this document type- threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),- self.QUALITY_THRESHOLDS["default"])-- results = {- "user_prompt": user_prompt,- "doc_type": doc_type,- "quality_threshold": threshold,- "iterations": [],- "final_image": None,- "final_score": 0.0,- "success": False,- "early_stop": False,- "early_stop_reason": None- }-- current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}--USER REQUEST: {user_prompt}--Generate a publication-quality scientific diagram that meets all the guidelines above."""-- print(f"\n{'='*60}")- print(f"Generating Scientific Schematic")- print(f"{'='*60}")- print(f"Description: {user_prompt}")- print(f"Document Type: {doc_type}")- print(f"Quality Threshold: {threshold}/10")- print(f"Max Iterations: {iterations}")- print(f"Output: {output_path}")- print(f"{'='*60}\n")-- for i in range(1, iterations + 1):- print(f"\n[Iteration {i}/{iterations}]")- print("-" * 40)-- # Generate image- print(f"Generating image...")- image_data = self.generate_image(current_prompt)-- if not image_data:- error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')- print(f"✗ Generation failed: {error_msg}")- results["iterations"].append({- "iteration": i,- "success": False,- "error": error_msg- })- continue-- # Save iteration image- iter_path = output_dir / f"{base_name}_v{i}{extension}"- with open(iter_path, "wb") as f:- f.write(image_data)- print(f"✓ Saved: {iter_path}")-- # Review image using Gemini 3.6 Flash- print(f"Reviewing image with Gemini 3.6 Flash...")- critique, score, needs_improvement = self.review_image(- str(iter_path), user_prompt, i, doc_type, iterations- )- print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")-- # Save iteration results- iteration_result = {- "iteration": i,- "image_path": str(iter_path),- "prompt": current_prompt,- "critique": critique,- "score": score,- "needs_improvement": needs_improvement,- "success": True- }- results["iterations"].append(iteration_result)-- # Check if quality is acceptable - STOP EARLY if so- if not needs_improvement:- print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")- print(f" No further iterations needed!")- results["final_image"] = str(iter_path)- results["final_score"] = score- results["success"] = True- results["early_stop"] = True- results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"- break-- # If this is the last iteration, we're done regardless- if i == iterations:- print(f"\n⚠ Maximum iterations reached")- results["final_image"] = str(iter_path)- results["final_score"] = score- results["success"] = True- break-- # Quality below threshold - improve prompt for next iteration- print(f"\n⚠ Quality below threshold ({score} < {threshold})")- print(f"Improving prompt based on feedback...")- current_prompt = self.improve_prompt(user_prompt, critique, i + 1)-- # Copy final version to output path- if results["success"] and results["final_image"]:- final_iter_path = Path(results["final_image"])- if final_iter_path != output_path:- import shutil- shutil.copy(final_iter_path, output_path)- print(f"\n✓ Final image: {output_path}")-- # Save review log- log_path = output_dir / f"{base_name}_review_log.json"- with open(log_path, "w") as f:- json.dump(results, f, indent=2)- print(f"✓ Review log: {log_path}")-- print(f"\n{'='*60}")- print(f"Generation Complete!")- print(f"Final Score: {results['final_score']}/10")- if results["early_stop"]:- print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")- print(f"{'='*60}\n")-- return results---def main():- """Command-line interface."""- parser = argparse.ArgumentParser(- description="Generate scientific schematics using AI with smart iterative refinement",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Examples:- # Generate a flowchart for a journal paper- python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal-- # Generate neural network architecture for presentation (lower threshold)- python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation-- # Generate with custom max iterations for poster- python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster-- # Verbose output- python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v--Document Types (quality thresholds):- journal 8.5/10 - Nature, Science, peer-reviewed journals- conference 8.0/10 - Conference papers- thesis 8.0/10 - Dissertations, theses- grant 8.0/10 - Grant proposals- preprint 7.5/10 - arXiv, bioRxiv, etc.- report 7.5/10 - Technical reports- poster 7.0/10 - Academic posters- presentation 6.5/10 - Slides, talks- default 7.5/10 - General purpose--Note: Multiple iterations only occur if quality is BELOW the threshold.- If the first generation meets the threshold, no extra API calls are made.--Environment:- OPENROUTER_API_KEY OpenRouter API key (required)- """- )-- parser.add_argument("prompt", help="Description of the diagram to generate")- parser.add_argument("-o", "--output", required=True,- help="Output image path (e.g., diagram.png)")- parser.add_argument("--iterations", type=int, default=2,- help="Maximum refinement iterations (default: 2, max: 2)")- parser.add_argument("--doc-type", default="default",- choices=["journal", "conference", "poster", "presentation",- "report", "grant", "thesis", "preprint", "default"],- help="Document type for quality threshold (default: default)")- parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")- parser.add_argument("-v", "--verbose", action="store_true",- help="Verbose output")-- args = parser.parse_args()-- # Check for API key- api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")- if not api_key:- print("Error: OPENROUTER_API_KEY environment variable not set")- print("\nSet it with:")- print(" export OPENROUTER_API_KEY='your_api_key'")- print("\nOr provide via --api-key flag")- sys.exit(1)-- # Validate iterations - enforce max of 2- if args.iterations < 1 or args.iterations > 2:- print("Error: Iterations must be between 1 and 2")- sys.exit(1)-- try:- generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)- results = generator.generate_iterative(- user_prompt=args.prompt,- output_path=args.output,- iterations=args.iterations,- doc_type=args.doc_type- )-- if results["success"]:- print(f"\n✓ Success! Image saved to: {args.output}")- if results.get("early_stop"):- print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")- sys.exit(0)- else:- print(f"\n✗ Generation failed. Check review log for details.")- sys.exit(1)- except Exception as e:- print(f"\n✗ Error: {str(e)}")- sys.exit(1)---if __name__ == "__main__":- main()-diff --git a/skills/scientific-writing/scripts/lint_manuscript.py b/skills/scientific-writing/scripts/lint_manuscript.pynew file mode 100644index 00000000..81472e6e--- /dev/null+++ b/skills/scientific-writing/scripts/lint_manuscript.py@@ -0,0 +1,171 @@+"""Lint manuscript Markdown for placeholders, language risks, and sensitive content."""++from __future__ import annotations++import argparse+import re+from typing import Any++from _common import (+ Issue,+ emit_report,+ issue,+ read_json,+ read_text,+ require_object,+ run,+)++TOOL = "lint_manuscript"+PLACEHOLDER_PATTERNS = (+ re.compile(r"\[\[\s*TODO\b", re.IGNORECASE),+ re.compile(r"\b(?:TODO|TBD|TK)\b", re.IGNORECASE),+ re.compile(r"\[\s*(?:insert|add|describe|replace)[^\]]*\]", re.IGNORECASE),+ re.compile(r"\blorem ipsum\b", re.IGNORECASE),+ re.compile(r"\bX{4,}\b"),+)+SENSITIVE_PATTERNS = (+ re.compile(r"\b(?:MRN|medical record number)\s*[:#]", re.IGNORECASE),+ re.compile(r"\b(?:SSN|social security number)\s*[:#]", re.IGNORECASE),+ re.compile(r"\b(?:DOB|date of birth)\s*[:#]", re.IGNORECASE),+ re.compile(r"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b", re.IGNORECASE),+ re.compile(+ r"\b(?:PHI|protected health information|patient name|participant name)\b",+ re.IGNORECASE,+ ),+ re.compile(r"\b(?:confidential|proprietary|trade secret)\b", re.IGNORECASE),+ re.compile(+ r"\b(?:peer[- ]review material|unpublished manuscript)\b", re.IGNORECASE+ ),+)+DECLARATION_RE = re.compile(+ r"\b(?:ethics (?:approval|committee)|IRB|informed consent|funded by|"+ r"conflict[s]? of interest|data (?:are|is) available|code (?:is|are) available)\b",+ re.IGNORECASE,+)+OVERSTATEMENT_RE = re.compile(+ r"\b(?:proves?|definitively|guarantees?|no limitations|universally|"+ r"highly significant|no effect)\b",+ re.IGNORECASE,+)+CAUSAL_RE = re.compile(+ r"\b(?:causes?|caused|proves?|demonstrates? that)\b", re.IGNORECASE+)+CLAIM_MARKER_RE = re.compile(r"\[claim:C[0-9]{3,8}\]")+EVIDENCE_MARKER_RE = re.compile(r"(?:\[evidence:E[0-9]|\[@E[0-9])")+OBSERVATIONAL_DESIGNS = {+ "observational",+ "cohort",+ "case_control",+ "cross_sectional",+ "routinely_collected_health_data",+}+++def load_manifest(path: str | None) -> tuple[dict[str, Any] | None, list[Issue]]:+ if path is None:+ return None, [+ issue(+ "warning",+ "CONFIDENTIALITY_GATE_NOT_CHECKED",+ location="manifest",+ )+ ]+ data = require_object(read_json(path), "manuscript_manifest")+ issues: list[Issue] = []+ review = require_object(+ data.get("confidentiality_review"), "confidentiality_review"+ )+ if review.get("completed") is not True:+ issues.append(+ issue("error", "CONFIDENTIALITY_REVIEW_INCOMPLETE", location="manifest")+ )+ if review.get("policy_checked") is not True:+ issues.append(issue("error", "POLICY_REVIEW_INCOMPLETE", location="manifest"))+ return data, issues+++def lint_text(text: str, manifest: dict[str, Any] | None) -> list[Issue]:+ issues: list[Issue] = []+ study_design = str((manifest or {}).get("study_design", "")).casefold()+ submission_ready = (manifest or {}).get("submission_ready") is True+ in_fence = False+ for line_number, line in enumerate(text.splitlines(), start=1):+ stripped = line.strip()+ if stripped.startswith(("```", "~~~")):+ in_fence = not in_fence+ continue+ if in_fence:+ continue+ location = f"line:{line_number}"+ for pattern in PLACEHOLDER_PATTERNS:+ if pattern.search(line):+ issues.append(+ issue("error", "UNRESOLVED_PLACEHOLDER", location=location)+ )+ break+ for pattern in SENSITIVE_PATTERNS:+ if pattern.search(line):+ issues.append(+ issue("warning", "POTENTIAL_RESTRICTED_CONTENT", location=location)+ )+ break+ if DECLARATION_RE.search(line) and not (+ CLAIM_MARKER_RE.search(line) and EVIDENCE_MARKER_RE.search(line)+ ):+ issues.append(+ issue(+ "error", "DECLARATION_WITHOUT_EVIDENCE_MARKERS", location=location+ )+ )+ if OVERSTATEMENT_RE.search(line):+ issues.append(+ issue("warning", "POTENTIAL_OVERSTATEMENT", location=location)+ )+ if study_design in OBSERVATIONAL_DESIGNS and CAUSAL_RE.search(line):+ issues.append(+ issue(+ "warning",+ "CAUSAL_LANGUAGE_FOR_OBSERVATIONAL_DESIGN",+ location=location,+ )+ )+ if submission_ready and "NOT FOR SUBMISSION" in line.upper():+ issues.append(+ issue("error", "DRAFT_BANNER_ON_READY_MANUSCRIPT", location=location)+ )+ if not text.strip():+ issues.append(issue("error", "EMPTY_MANUSCRIPT", location="document"))+ return issues+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Lint local Markdown without echoing source text. Flags unresolved "+ "placeholders, risky declarations, possible sensitive content, and "+ "language that needs human review."+ )+ )+ parser.add_argument("manuscript", help="UTF-8 Markdown manuscript")+ parser.add_argument(+ "--manifest",+ help="optional UTF-8 JSON manuscript manifest with confidentiality gates",+ )+ return parser+++def cli() -> int:+ args = build_parser().parse_args()+ manifest, issues = load_manifest(args.manifest)+ text = read_text(args.manuscript, {".md", ".markdown"})+ issues.extend(lint_text(text, manifest))+ return emit_report(+ TOOL,+ issues,+ summary={"lines_checked": len(text.splitlines()), "raw_text_echoed": False},+ )+++if __name__ == "__main__":+ run(TOOL, cli)diff --git a/skills/scientific-writing/scripts/scaffold_manuscript.py b/skills/scientific-writing/scripts/scaffold_manuscript.pynew file mode 100644index 00000000..f60dd74b--- /dev/null+++ b/skills/scientific-writing/scripts/scaffold_manuscript.py@@ -0,0 +1,143 @@+"""Generate a local, explicitly incomplete manuscript workspace."""++from __future__ import annotations++import argparse+import json+import re+from pathlib import Path+from typing import Any++from _common import (+ InputError,+ emit_report,+ read_json,+ read_text,+ require_object,+ run,+ write_new_text,+)++TOOL = "scaffold_manuscript"+ASSET_DIR = Path(__file__).resolve().parents[1] / "assets"+DOCUMENT_ID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9._-]{1,63}$")+GUIDELINE_ID_RE = re.compile(r"^[a-z][a-z0-9.-]{1,63}$")+TEMPLATE_FILES = {+ "manuscript.md": "manuscript_scaffold.md",+ "claims.csv": "claim_evidence_template.csv",+ "source_manifest.json": "source_manifest_template.json",+ "consistency_manifest.json": "consistency_manifest_template.json",+ "authorship.json": "authorship_template.json",+}+++def _json_text(value: Any) -> str:+ return json.dumps(value, indent=2, sort_keys=True) + "\n"+++def _prepare_manifest(+ *,+ document_id: str,+ study_design: str,+ guidelines: list[str],+) -> str:+ data = require_object(+ read_json(ASSET_DIR / "manuscript_manifest_template.json"),+ "manuscript_manifest_template",+ )+ data["document_id"] = document_id+ data["study_design"] = study_design+ data["reporting_guidelines"] = guidelines+ return _json_text(data)+++def _prepare_coverage(guidelines: list[str]) -> str:+ data = require_object(+ read_json(ASSET_DIR / "reporting_coverage_template.json"),+ "reporting_coverage_template",+ )+ data["guideline_id"] = guidelines[0] if guidelines else "[[TODO:guideline-id]]"+ return _json_text(data)+++def generate(+ output_dir: Path,+ *,+ document_id: str,+ study_design: str,+ guidelines: list[str],+) -> list[str]:+ if output_dir.exists() or output_dir.is_symlink():+ raise InputError("output directory already exists; refusing to overwrite")+ parent = output_dir.parent+ if not parent.is_dir() or parent.is_symlink():+ raise InputError("output parent must be an existing regular directory")++ prepared: dict[str, str] = {+ destination: read_text(ASSET_DIR / source, {Path(source).suffix})+ for destination, source in TEMPLATE_FILES.items()+ }+ prepared["manuscript_manifest.json"] = _prepare_manifest(+ document_id=document_id,+ study_design=study_design,+ guidelines=guidelines,+ )+ prepared["reporting_coverage.json"] = _prepare_coverage(guidelines)++ output_dir.mkdir(mode=0o700)+ for filename in sorted(prepared):+ write_new_text(+ output_dir / filename,+ prepared[filename],+ {Path(filename).suffix},+ )+ return sorted(prepared)+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Create a deterministic local manuscript workspace. Generated files "+ "are marked incomplete and must pass all validators before submission."+ )+ )+ parser.add_argument("--output-dir", required=True, help="new directory to create")+ parser.add_argument("--document-id", required=True)+ parser.add_argument("--study-design", required=True)+ parser.add_argument(+ "--guideline",+ action="append",+ default=[],+ help="candidate reporting-guideline ID; repeat as needed",+ )+ return parser+++def cli() -> int:+ args = build_parser().parse_args()+ if not DOCUMENT_ID_RE.fullmatch(args.document_id):+ raise InputError("document-id must be 2-64 safe identifier characters")+ if not DOCUMENT_ID_RE.fullmatch(args.study_design):+ raise InputError("study-design must be a safe identifier")+ guidelines = sorted(set(args.guideline))+ if any(not GUIDELINE_ID_RE.fullmatch(value) for value in guidelines):+ raise InputError("guideline IDs must be safe lowercase identifiers")+ files = generate(+ Path(args.output_dir),+ document_id=args.document_id,+ study_design=args.study_design,+ guidelines=guidelines,+ )+ return emit_report(+ TOOL,+ [],+ summary={+ "files_created": files,+ "submission_ready": False,+ "overwrites": False,+ },+ )+++if __name__ == "__main__":+ run(TOOL, cli)diff --git a/skills/scientific-writing/scripts/select_reporting_guidelines.py b/skills/scientific-writing/scripts/select_reporting_guidelines.pynew file mode 100644index 00000000..7d23b877--- /dev/null+++ b/skills/scientific-writing/scripts/select_reporting_guidelines.py@@ -0,0 +1,214 @@+"""Select reporting guidance and check non-scoring coverage metadata."""++from __future__ import annotations++import argparse+from pathlib import Path+from typing import Any++from _common import (+ InputError,+ Issue,+ emit_report,+ is_nonempty_string,+ issue,+ read_json,+ require_list,+ require_object,+ run,+)++TOOL = "select_reporting_guidelines"+REGISTRY_PATH = (+ Path(__file__).resolve().parents[1] / "assets" / "reporting_guidelines.json"+)+DISCLAIMER = (+ "Selection and coverage are non-scoring aids. They do not reproduce an official "+ "checklist, appraise study quality, certify compliance, or replace the current "+ "guideline and target-journal instructions."+)+++def load_registry() -> dict[str, dict[str, Any]]:+ root = require_object(read_json(REGISTRY_PATH), "registry")+ if root.get("schema_version") != "1.0":+ raise InputError("unsupported reporting-guideline registry version")+ raw_items = require_list(root.get("guidelines"), "guidelines")+ registry: dict[str, dict[str, Any]] = {}+ for raw_item in raw_items:+ item = require_object(raw_item, "guideline")+ guideline_id = item.get("id")+ if not is_nonempty_string(guideline_id) or guideline_id in registry:+ raise InputError("registry guideline IDs must be non-empty and unique")+ registry[guideline_id] = item+ return registry+++def _condition_matches(item: dict[str, Any], args: argparse.Namespace) -> bool:+ conditions = require_object(item.get("conditions", {}), "conditions")+ for flag in ("ai", "llm", "routinely_collected", "qualitative_component"):+ required = conditions.get(flag)+ if required is True and not getattr(args, flag):+ return False+ return True+++def select_guidelines(+ registry: dict[str, dict[str, Any]],+ args: argparse.Namespace,+) -> tuple[list[str], list[str], list[Issue]]:+ primary: list[str] = []+ extensions: list[str] = []+ issues: list[Issue] = []+ for guideline_id, item in registry.items():+ designs = require_list(+ item.get("study_designs"), f"{guideline_id}.study_designs"+ )+ if args.study_design not in designs:+ continue+ if bool(item.get("protocol")) != bool(args.protocol):+ continue+ if not _condition_matches(item, args):+ continue+ if item.get("role") == "primary":+ primary.append(guideline_id)+ elif item.get("role") == "extension":+ extensions.append(guideline_id)++ if not primary:+ issues.append(+ issue("warning", "NO_PRIMARY_LOCAL_MATCH", item_id=args.study_design)+ )+ if args.llm and not args.ai:+ issues.append(issue("error", "LLM_REQUIRES_AI_FLAG", location="arguments"))+ return sorted(primary), sorted(extensions), issues+++def check_coverage(+ registry: dict[str, dict[str, Any]],+ coverage_path: str,+) -> tuple[list[Issue], dict[str, Any]]:+ data = require_object(read_json(coverage_path), "coverage")+ if data.get("schema_version") != "1.0":+ raise InputError("unsupported reporting-coverage schema version")+ guideline_id = data.get("guideline_id")+ if guideline_id not in registry:+ raise InputError("coverage guideline_id is not in the bundled registry")+ guideline = registry[guideline_id]+ expected = {+ item["id"]: item+ for item in (+ require_object(raw, "coverage_topic")+ for raw in require_list(guideline.get("coverage_topics"), "coverage_topics")+ )+ }++ issues: list[Issue] = []+ observed: dict[str, dict[str, Any]] = {}+ for index, raw_item in enumerate(require_list(data.get("items"), "items")):+ item = require_object(raw_item, f"items[{index}]")+ topic_id = item.get("topic_id")+ if topic_id not in expected:+ issues.append(+ issue("error", "UNKNOWN_COVERAGE_TOPIC", location=f"items[{index}]")+ )+ continue+ if topic_id in observed:+ issues.append(+ issue("error", "DUPLICATE_COVERAGE_TOPIC", item_id=str(topic_id))+ )+ continue+ observed[str(topic_id)] = item+ status = item.get("status")+ if status not in {"addressed", "not_applicable", "missing"}:+ issues.append(+ issue("error", "INVALID_COVERAGE_STATUS", item_id=str(topic_id))+ )+ if status == "addressed":+ locations = item.get("locations")+ if (+ not isinstance(locations, list)+ or not locations+ or not all(is_nonempty_string(value) for value in locations)+ ):+ issues.append(+ issue(+ "error",+ "ADDRESSED_TOPIC_WITHOUT_LOCATION",+ item_id=str(topic_id),+ )+ )+ if status == "not_applicable" and not is_nonempty_string(item.get("rationale")):+ issues.append(+ issue(+ "error", "NOT_APPLICABLE_WITHOUT_RATIONALE", item_id=str(topic_id)+ )+ )+ if status == "missing":+ issues.append(+ issue("error", "COVERAGE_TOPIC_MISSING", item_id=str(topic_id))+ )++ for topic_id in sorted(set(expected) - set(observed)):+ issues.append(issue("error", "COVERAGE_TOPIC_NOT_RECORDED", item_id=topic_id))++ summary = {+ "guideline_id": guideline_id,+ "topics_expected": len(expected),+ "topics_recorded": len(observed),+ "coverage_status": (+ "incomplete"+ if any(item.severity == "error" for item in issues)+ else "all_bundled_topics_addressed"+ ),+ "disclaimer": DISCLAIMER,+ }+ return issues, summary+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Use the bundled offline registry to select candidate reporting guidance "+ "or validate a non-scoring coverage record."+ )+ )+ subparsers = parser.add_subparsers(dest="command", required=True)++ select_parser = subparsers.add_parser(+ "select",+ help="select candidate guidelines from study metadata",+ )+ select_parser.add_argument("--study-design", required=True)+ select_parser.add_argument("--protocol", action="store_true")+ select_parser.add_argument("--ai", action="store_true")+ select_parser.add_argument("--llm", action="store_true")+ select_parser.add_argument("--routinely-collected", action="store_true")+ select_parser.add_argument("--qualitative-component", action="store_true")++ check_parser = subparsers.add_parser(+ "check",+ help="validate high-level coverage metadata",+ )+ check_parser.add_argument("coverage", help="UTF-8 JSON coverage record")+ return parser+++def cli() -> int:+ args = build_parser().parse_args()+ registry = load_registry()+ if args.command == "select":+ primary, extensions, issues = select_guidelines(registry, args)+ summary = {+ "study_design": args.study_design,+ "primary": primary,+ "extensions": extensions,+ "disclaimer": DISCLAIMER,+ }+ else:+ issues, summary = check_coverage(registry, args.coverage)+ return emit_report(TOOL, issues, summary=summary)+++if __name__ == "__main__":+ run(TOOL, cli)diff --git a/skills/scientific-writing/scripts/validate_authorship.py b/skills/scientific-writing/scripts/validate_authorship.pynew file mode 100644index 00000000..ffa9f496--- /dev/null+++ b/skills/scientific-writing/scripts/validate_authorship.py@@ -0,0 +1,322 @@+"""Validate human authorship, CRediT roles, accountability, and AI disclosure."""++from __future__ import annotations++import argparse+import re+from typing import Any++from _common import (+ InputError,+ Issue,+ emit_report,+ is_nonempty_string,+ is_placeholder,+ issue,+ read_json,+ require_list,+ require_object,+ run,+)++TOOL = "validate_authorship"+AUTHOR_ID_RE = re.compile(r"^A[0-9]{3,8}$")+CONTRIBUTOR_ID_RE = re.compile(r"^K[0-9]{3,8}$")+DATE_RE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$")+SHA256_RE = re.compile(r"^[a-f0-9]{64}$")+CREDIT_ROLES = {+ "conceptualization",+ "data curation",+ "formal analysis",+ "funding acquisition",+ "investigation",+ "methodology",+ "project administration",+ "resources",+ "software",+ "supervision",+ "validation",+ "visualization",+ "writing – original draft",+ "writing – review & editing",+}+AUTHORSHIP_CRITERIA = {+ "substantial_contribution",+ "drafted_or_critically_revised",+ "final_approval",+ "accountable_for_work",+}+DISCLOSURE_LOCATIONS = {"cover_letter", "acknowledgments", "methods", "other"}+MATERIAL_CLASSES = {+ "none",+ "public_text",+ "unpublished_manuscript",+ "peer_review_material",+ "source_documents",+ "sensitive_data",+ "phi",+ "proprietary_content",+}+RESTRICTED_MATERIAL_CLASSES = MATERIAL_CLASSES - {"none", "public_text"}+++def _validate_roles(+ roles_value: Any,+ *,+ item_id: str,+ issues: list[Issue],+) -> None:+ roles = require_list(roles_value, f"{item_id}.credit_roles")+ if not roles:+ issues.append(issue("error", "NO_CREDIT_ROLE", item_id=item_id))+ normalized: set[str] = set()+ for role in roles:+ if not isinstance(role, str) or role.casefold() not in CREDIT_ROLES:+ issues.append(issue("error", "INVALID_CREDIT_ROLE", item_id=item_id))+ elif role.casefold() in normalized:+ issues.append(issue("error", "DUPLICATE_CREDIT_ROLE", item_id=item_id))+ else:+ normalized.add(role.casefold())+++def validate_people(data: dict[str, Any]) -> tuple[list[Issue], set[str]]:+ issues: list[Issue] = []+ author_ids: set[str] = set()+ for index, raw_author in enumerate(require_list(data.get("authors"), "authors")):+ author = require_object(raw_author, f"authors[{index}]")+ author_id = author.get("author_id")+ if not isinstance(author_id, str) or not AUTHOR_ID_RE.fullmatch(author_id):+ issues.append(+ issue("error", "INVALID_AUTHOR_ID", location=f"authors[{index}]")+ )+ continue+ if author_id in author_ids:+ issues.append(issue("error", "DUPLICATE_AUTHOR_ID", item_id=author_id))+ continue+ author_ids.add(author_id)+ if author.get("is_human") is not True:+ issues.append(+ issue("error", "NONHUMAN_AUTHOR_PROHIBITED", item_id=author_id)+ )+ if not is_nonempty_string(author.get("name")) or is_placeholder(+ author.get("name")+ ):+ issues.append(issue("error", "MISSING_AUTHOR_NAME", item_id=author_id))+ criteria = require_object(+ author.get("authorship_criteria"),+ f"{author_id}.authorship_criteria",+ )+ for criterion in AUTHORSHIP_CRITERIA:+ if criteria.get(criterion) is not True:+ issues.append(+ issue(+ "error",+ "AUTHORSHIP_CRITERION_NOT_MET",+ location=criterion,+ item_id=author_id,+ )+ )+ _validate_roles(author.get("credit_roles"), item_id=author_id, issues=issues)++ if not author_ids:+ issues.append(issue("error", "NO_HUMAN_AUTHORS", location="authors"))++ contributor_ids: set[str] = set()+ for index, raw_contributor in enumerate(+ require_list(data.get("contributors", []), "contributors")+ ):+ contributor = require_object(raw_contributor, f"contributors[{index}]")+ contributor_id = contributor.get("contributor_id")+ if (+ not isinstance(contributor_id, str)+ or not CONTRIBUTOR_ID_RE.fullmatch(contributor_id)+ or contributor_id in contributor_ids+ ):+ issues.append(+ issue(+ "error",+ "INVALID_OR_DUPLICATE_CONTRIBUTOR_ID",+ location=f"contributors[{index}]",+ )+ )+ continue+ contributor_ids.add(contributor_id)+ if contributor.get("is_human") is not True:+ issues.append(+ issue("error", "NONHUMAN_CONTRIBUTOR_RECORD", item_id=contributor_id)+ )+ _validate_roles(+ contributor.get("credit_roles"),+ item_id=contributor_id,+ issues=issues,+ )+ return issues, author_ids+++def validate_accountability(+ data: dict[str, Any],+ author_ids: set[str],+) -> list[Issue]:+ issues: list[Issue] = []+ corresponding = data.get("corresponding_author_id")+ if corresponding not in author_ids:+ issues.append(issue("error", "INVALID_CORRESPONDING_AUTHOR"))+ accountability = require_object(data.get("accountability"), "accountability")+ if accountability.get("all_authors_approved") is not True:+ issues.append(+ issue("error", "FINAL_APPROVAL_INCOMPLETE", location="accountability")+ )+ guarantors = require_list(+ accountability.get("guarantor_author_ids"), "guarantor_author_ids"+ )+ if not guarantors:+ issues.append(+ issue("error", "NO_ACCOUNTABILITY_GUARANTOR", location="accountability")+ )+ for guarantor in guarantors:+ if guarantor not in author_ids:+ issues.append(+ issue("error", "INVALID_GUARANTOR_AUTHOR", item_id=str(guarantor))+ )+ return issues+++def validate_ai_disclosure(data: dict[str, Any]) -> tuple[list[Issue], int]:+ issues: list[Issue] = []+ ai_use = require_object(data.get("ai_use"), "ai_use")+ used = ai_use.get("used")+ if not isinstance(used, bool):+ issues.append(issue("error", "AI_USED_NOT_BOOLEAN", location="ai_use"))+ used = False+ tools = require_list(ai_use.get("tools"), "ai_use.tools")+ if used and not tools:+ issues.append(issue("error", "AI_USE_WITHOUT_TOOL_RECORD", location="ai_use"))+ if not used and tools:+ issues.append(issue("error", "AI_TOOL_RECORDED_WHEN_UNUSED", location="ai_use"))++ if ai_use.get("human_verification_complete") is not True:+ issues.append(issue("error", "AI_OUTPUT_NOT_HUMAN_VERIFIED", location="ai_use"))+ if ai_use.get("journal_policy_checked") is not True:+ issues.append(+ issue("error", "JOURNAL_AI_POLICY_NOT_CHECKED", location="ai_use")+ )+ locations = require_list(ai_use.get("disclosed_in"), "ai_use.disclosed_in")+ if used and not locations:+ issues.append(issue("error", "AI_USE_NOT_DISCLOSED", location="ai_use"))+ for location in locations:+ if location not in DISCLOSURE_LOCATIONS:+ issues.append(+ issue("error", "INVALID_AI_DISCLOSURE_LOCATION", location="ai_use")+ )++ for index, raw_tool in enumerate(tools):+ tool = require_object(raw_tool, f"ai_use.tools[{index}]")+ tool_id = f"tool:{index + 1}"+ for key in ("name", "version", "provider", "purpose"):+ if not is_nonempty_string(tool.get(key)) or is_placeholder(tool.get(key)):+ issues.append(+ issue(+ "error",+ "INCOMPLETE_AI_TOOL_RECORD",+ location=key,+ item_id=tool_id,+ )+ )+ material_class = tool.get("materials_sent")+ if material_class not in MATERIAL_CLASSES:+ issues.append(issue("error", "INVALID_AI_MATERIAL_CLASS", item_id=tool_id))+ if not isinstance(tool.get("external_service"), bool):+ issues.append(+ issue("error", "EXTERNAL_SERVICE_NOT_BOOLEAN", item_id=tool_id)+ )+ if (+ tool.get("external_service") is True+ and material_class in RESTRICTED_MATERIAL_CLASSES+ ):+ if tool.get("explicit_authorization") is not True:+ issues.append(+ issue(+ "error",+ "RESTRICTED_EXTERNAL_TRANSFER_UNAUTHORIZED",+ item_id=tool_id,+ )+ )+ if tool.get("policy_reviewed") is not True:+ issues.append(+ issue(+ "error",+ "RESTRICTED_EXTERNAL_TRANSFER_POLICY_UNREVIEWED",+ item_id=tool_id,+ )+ )+ return issues, len(tools)+++def validate_declarations(data: dict[str, Any]) -> list[Issue]:+ issues: list[Issue] = []+ declarations = require_object(data.get("declarations"), "declarations")+ for declaration_id in (+ "ai_use",+ "author_contributions",+ "conflicts",+ "funding",+ ):+ declaration = require_object(+ declarations.get(declaration_id),+ f"declarations.{declaration_id}",+ )+ if declaration.get("status") not in {"verified", "not_applicable"}:+ issues.append(+ issue("error", "DECLARATION_NOT_VERIFIED", item_id=declaration_id)+ )+ if not SHA256_RE.fullmatch(str(declaration.get("content_sha256", ""))):+ issues.append(+ issue("error", "INVALID_DECLARATION_HASH", item_id=declaration_id)+ )+ if not is_nonempty_string(declaration.get("verified_by")):+ issues.append(+ issue("error", "DECLARATION_VERIFIER_MISSING", item_id=declaration_id)+ )+ if not DATE_RE.fullmatch(str(declaration.get("verified_on", ""))):+ issues.append(+ issue("error", "INVALID_DECLARATION_DATE", item_id=declaration_id)+ )+ return issues+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Validate a local authorship JSON record against human accountability, "+ "CRediT role names, AI disclosure, and restricted-material transfer gates."+ )+ )+ parser.add_argument(+ "authorship", help="UTF-8 JSON authorship and disclosure record"+ )+ return parser+++def cli() -> int:+ args = build_parser().parse_args()+ data = require_object(read_json(args.authorship), "authorship")+ if data.get("schema_version") != "1.0":+ raise InputError("unsupported authorship schema version")+ issues, author_ids = validate_people(data)+ issues.extend(validate_accountability(data, author_ids))+ ai_issues, tool_count = validate_ai_disclosure(data)+ issues.extend(ai_issues)+ issues.extend(validate_declarations(data))+ return emit_report(+ TOOL,+ issues,+ summary={+ "authors": len(author_ids),+ "ai_tools": tool_count,+ "credit_taxonomy": "ANSI/NISO Z39.104-2022",+ },+ )+++if __name__ == "__main__":+ run(TOOL, cli)diff --git a/skills/scientific-writing/scripts/validate_manifest.py b/skills/scientific-writing/scripts/validate_manifest.pynew file mode 100644index 00000000..088ea5f1--- /dev/null+++ b/skills/scientific-writing/scripts/validate_manifest.py@@ -0,0 +1,460 @@+"""Validate bounded manuscript and source manifests without network access."""++from __future__ import annotations++import argparse+import re+from typing import Any++from _common import (+ InputError,+ Issue,+ emit_report,+ is_nonempty_string,+ is_placeholder,+ issue,+ read_json,+ require_list,+ require_object,+ run,+)++TOOL = "validate_manifest"+ID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9._-]{1,63}$")+EVIDENCE_ID_RE = re.compile(r"^E[0-9]{3,8}$")+DATE_RE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$")+SOURCE_TYPES = {+ "journal_article",+ "book",+ "chapter",+ "conference_paper",+ "dataset",+ "software",+ "preprint",+ "report",+ "policy",+ "guideline",+ "registry",+ "webpage",+ "other",+}+CONFIDENTIALITY = {"public", "restricted", "sensitive", "proprietary"}+DRAFT_STATUSES = {"draft", "internal_review", "submission_candidate", "submitted"}+STATEMENT_STATUSES = {"not_applicable", "missing", "draft", "verified"}+MANUSCRIPT_FIELDS = {+ "schema_version",+ "document_id",+ "study_design",+ "draft_status",+ "submission_ready",+ "registries",+ "reporting_guidelines",+ "human_verification",+ "confidentiality_review",+ "required_statements",+}+SOURCE_FIELDS = {+ "evidence_id",+ "source_type",+ "title",+ "authors",+ "year",+ "identifiers",+ "locator",+ "confidentiality",+ "verification",+}+IDENTIFIER_FIELDS = {"doi", "pmid", "pmcid", "isbn", "url"}+VERIFICATION_FIELDS = {"status", "source_opened", "verified_by", "verified_on"}+++def _check_unknown_fields(+ obj: dict[str, Any],+ allowed: set[str],+ *,+ location: str,+ issues: list[Issue],+) -> None:+ for key in sorted(set(obj) - allowed):+ issues.append(+ issue("error", "UNKNOWN_SCHEMA_FIELD", location=location, item_id=key)+ )+++def _missing_or_placeholder(+ obj: dict[str, Any],+ key: str,+ *,+ location: str,+ issues: list[Issue],+) -> None:+ value = obj.get(key)+ if not is_nonempty_string(value) or is_placeholder(value):+ issues.append(+ issue("error", "MISSING_VERIFIED_VALUE", location=location, item_id=key)+ )+++def _validate_human_gate(+ value: Any,+ *,+ location: str,+ submission_ready: bool,+ issues: list[Issue],+) -> None:+ gate = require_object(value, location)+ completed = gate.get("completed")+ if not isinstance(completed, bool):+ issues.append(issue("error", "GATE_COMPLETED_NOT_BOOLEAN", location=location))+ return+ if completed:+ _missing_or_placeholder(gate, "verified_by", location=location, issues=issues)+ verified_on = gate.get("verified_on")+ if not isinstance(verified_on, str) or not DATE_RE.fullmatch(verified_on):+ issues.append(+ issue("error", "INVALID_VERIFICATION_DATE", location=location)+ )+ elif submission_ready:+ issues.append(issue("error", "SUBMISSION_GATE_INCOMPLETE", location=location))+++def validate_manuscript_manifest(data: dict[str, Any]) -> list[Issue]:+ issues: list[Issue] = []+ _check_unknown_fields(+ data,+ MANUSCRIPT_FIELDS,+ location="root",+ issues=issues,+ )+ if data.get("schema_version") != "1.0":+ issues.append(+ issue("error", "UNSUPPORTED_SCHEMA_VERSION", location="schema_version")+ )++ document_id = data.get("document_id")+ if not isinstance(document_id, str) or not ID_RE.fullmatch(document_id):+ issues.append(issue("error", "INVALID_DOCUMENT_ID", location="document_id"))+ _missing_or_placeholder(data, "study_design", location="root", issues=issues)++ draft_status = data.get("draft_status")+ if draft_status not in DRAFT_STATUSES:+ issues.append(issue("error", "INVALID_DRAFT_STATUS", location="draft_status"))+ submission_ready = data.get("submission_ready")+ if not isinstance(submission_ready, bool):+ issues.append(+ issue("error", "SUBMISSION_READY_NOT_BOOLEAN", location="submission_ready")+ )+ submission_ready = False++ paths = require_object(data.get("registries"), "registries")+ for key in (+ "source_manifest",+ "claim_evidence",+ "consistency_manifest",+ "authorship_manifest",+ "reporting_coverage",+ ):+ _missing_or_placeholder(paths, key, location="registries", issues=issues)++ guidelines = require_list(data.get("reporting_guidelines"), "reporting_guidelines")+ if submission_ready and not guidelines:+ issues.append(+ issue(+ "error",+ "NO_REPORTING_GUIDELINE_RECORDED",+ location="reporting_guidelines",+ )+ )+ for index, guideline_id in enumerate(guidelines):+ if not isinstance(guideline_id, str) or not ID_RE.fullmatch(guideline_id):+ issues.append(+ issue(+ "error",+ "INVALID_GUIDELINE_ID",+ location=f"reporting_guidelines[{index}]",+ )+ )++ _validate_human_gate(+ data.get("human_verification"),+ location="human_verification",+ submission_ready=bool(submission_ready),+ issues=issues,+ )+ confidentiality = require_object(+ data.get("confidentiality_review"), "confidentiality_review"+ )+ _validate_human_gate(+ confidentiality,+ location="confidentiality_review",+ submission_ready=bool(submission_ready),+ issues=issues,+ )+ if not isinstance(confidentiality.get("policy_checked"), bool):+ issues.append(+ issue(+ "error", "POLICY_CHECKED_NOT_BOOLEAN", location="confidentiality_review"+ )+ )+ elif submission_ready and not confidentiality["policy_checked"]:+ issues.append(+ issue(+ "error", "POLICY_REVIEW_INCOMPLETE", location="confidentiality_review"+ )+ )+ if not isinstance(confidentiality.get("external_services_authorized"), bool):+ issues.append(+ issue(+ "error",+ "EXTERNAL_AUTHORIZATION_NOT_BOOLEAN",+ location="confidentiality_review",+ )+ )++ statements = require_object(data.get("required_statements"), "required_statements")+ for key in (+ "ethics",+ "consent",+ "funding",+ "conflicts",+ "data_availability",+ "code_availability",+ "author_contributions",+ "ai_disclosure",+ ):+ status = statements.get(key)+ if status not in STATEMENT_STATUSES:+ issues.append(issue("error", "INVALID_STATEMENT_STATUS", location=key))+ elif submission_ready and status in {"missing", "draft"}:+ issues.append(issue("error", "UNVERIFIED_REQUIRED_STATEMENT", location=key))++ if submission_ready and draft_status not in {"submission_candidate", "submitted"}:+ issues.append(issue("error", "READY_STATUS_MISMATCH", location="draft_status"))+ return issues+++def validate_source_manifest(+ data: dict[str, Any],+ *,+ require_verified: bool,+) -> list[Issue]:+ issues: list[Issue] = []+ _check_unknown_fields(+ data,+ {"schema_version", "sources"},+ location="root",+ issues=issues,+ )+ if data.get("schema_version") != "1.0":+ issues.append(+ issue("error", "UNSUPPORTED_SCHEMA_VERSION", location="schema_version")+ )+ sources = require_list(data.get("sources"), "sources")+ seen_ids: set[str] = set()+ for index, raw_source in enumerate(sources):+ location = f"sources[{index}]"+ source = require_object(raw_source, location)+ _check_unknown_fields(+ source,+ SOURCE_FIELDS,+ location=location,+ issues=issues,+ )+ evidence_id = source.get("evidence_id")+ if not isinstance(evidence_id, str) or not EVIDENCE_ID_RE.fullmatch(+ evidence_id+ ):+ issues.append(issue("error", "INVALID_EVIDENCE_ID", location=location))+ evidence_id = None+ elif evidence_id in seen_ids:+ issues.append(+ issue(+ "error",+ "DUPLICATE_EVIDENCE_ID",+ location=location,+ item_id=evidence_id,+ )+ )+ else:+ seen_ids.add(evidence_id)++ if source.get("source_type") not in SOURCE_TYPES:+ issues.append(+ issue(+ "error",+ "INVALID_SOURCE_TYPE",+ location=location,+ item_id=evidence_id,+ )+ )+ _missing_or_placeholder(source, "title", location=location, issues=issues)+ authors = require_list(source.get("authors"), f"{location}.authors")+ for author in authors:+ if not is_nonempty_string(author) or is_placeholder(author):+ issues.append(+ issue(+ "error",+ "INVALID_SOURCE_AUTHOR",+ location=location,+ item_id=evidence_id,+ )+ )++ year = source.get("year")+ if year is not None and (+ not isinstance(year, int)+ or isinstance(year, bool)+ or not 1000 <= year <= 2100+ ):+ issues.append(+ issue(+ "error",+ "INVALID_SOURCE_YEAR",+ location=location,+ item_id=evidence_id,+ )+ )++ identifiers = require_object(+ source.get("identifiers"), f"{location}.identifiers"+ )+ _check_unknown_fields(+ identifiers,+ IDENTIFIER_FIELDS,+ location=f"{location}.identifiers",+ issues=issues,+ )+ if not any(is_nonempty_string(value) for value in identifiers.values()):+ issues.append(+ issue(+ "warning",+ "NO_SOURCE_IDENTIFIER",+ location=location,+ item_id=evidence_id,+ )+ )+ if not is_nonempty_string(source.get("locator")) or is_placeholder(+ source.get("locator")+ ):+ issues.append(+ issue(+ "error",+ "MISSING_SOURCE_LOCATOR",+ location=location,+ item_id=evidence_id,+ )+ )++ confidentiality = source.get("confidentiality")+ if confidentiality not in CONFIDENTIALITY:+ issues.append(+ issue(+ "error",+ "INVALID_CONFIDENTIALITY_CLASS",+ location=location,+ item_id=evidence_id,+ )+ )++ verification = require_object(+ source.get("verification"), f"{location}.verification"+ )+ _check_unknown_fields(+ verification,+ VERIFICATION_FIELDS,+ location=f"{location}.verification",+ issues=issues,+ )+ status = verification.get("status")+ if status not in {"unverified", "verified", "rejected"}:+ issues.append(+ issue(+ "error",+ "INVALID_VERIFICATION_STATUS",+ location=location,+ item_id=evidence_id,+ )+ )+ if status == "verified":+ _missing_or_placeholder(+ verification,+ "verified_by",+ location=location,+ issues=issues,+ )+ verified_on = verification.get("verified_on")+ if not isinstance(verified_on, str) or not DATE_RE.fullmatch(verified_on):+ issues.append(+ issue(+ "error",+ "INVALID_VERIFICATION_DATE",+ location=location,+ item_id=evidence_id,+ )+ )+ if verification.get("source_opened") is not True:+ issues.append(+ issue(+ "error",+ "SOURCE_NOT_OPENED_FOR_VERIFICATION",+ location=location,+ item_id=evidence_id,+ )+ )+ elif require_verified:+ issues.append(+ issue(+ "error",+ "SOURCE_NOT_VERIFIED",+ location=location,+ item_id=evidence_id,+ )+ )+ return issues+++def detect_kind(data: dict[str, Any]) -> str:+ if "sources" in data:+ return "source"+ if "document_id" in data:+ return "manuscript"+ raise InputError("unable to infer manifest kind")+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Validate a local JSON manuscript or source manifest. "+ "No network calls or identifier resolution are performed."+ )+ )+ parser.add_argument("manifest", help="UTF-8 JSON manifest (maximum 5 MB)")+ parser.add_argument(+ "--kind",+ choices=("auto", "manuscript", "source"),+ default="auto",+ help="manifest schema to validate (default: infer from keys)",+ )+ parser.add_argument(+ "--require-verified",+ action="store_true",+ help="for source manifests, fail if any source is not verified",+ )+ return parser+++def cli() -> int:+ args = build_parser().parse_args()+ data = require_object(read_json(args.manifest))+ kind = detect_kind(data) if args.kind == "auto" else args.kind+ if kind == "manuscript":+ issues = validate_manuscript_manifest(data)+ records = 1+ else:+ issues = validate_source_manifest(data, require_verified=args.require_verified)+ records = len(require_list(data.get("sources"), "sources"))+ return emit_report(TOOL, issues, summary={"kind": kind, "records": records})+++if __name__ == "__main__":+ run(TOOL, cli)diff --git a/skills/scientific-writing/tests/synthetic.py b/skills/scientific-writing/tests/synthetic.pynew file mode 100644index 00000000..d4a688f3--- /dev/null+++ b/skills/scientific-writing/tests/synthetic.py@@ -0,0 +1,187 @@+"""Synthetic, non-submission fixtures for local scientific-writing tests."""++from __future__ import annotations++import hashlib+++def valid_source_manifest() -> dict:+ return {+ "schema_version": "1.0",+ "sources": [+ {+ "evidence_id": "E001",+ "source_type": "guideline",+ "title": "European Code of Conduct for Research Integrity",+ "authors": ["ALLEA"],+ "year": 2023,+ "identifiers": {+ "doi": "10.26356/ECOC",+ "pmid": "",+ "pmcid": "",+ "isbn": "",+ "url": "https://allea.org/portfolio-item/european-code-of-conduct-2023",+ },+ "locator": "Research integrity principles",+ "confidentiality": "public",+ "verification": {+ "status": "verified",+ "source_opened": True,+ "verified_by": "Test verifier",+ "verified_on": "2026-07-24",+ },+ }+ ],+ }+++def valid_claim_csv() -> str:+ digest = hashlib.sha256(b"test claim").hexdigest()+ return (+ "claim_id,section,claim_kind,claim_text_sha256,evidence_ids,"+ "verification_status,uncertainty,analysis_intent\n"+ f"C001,Introduction,factual,{digest},E001,verified,not_applicable,"+ "not_applicable\n"+ )+++def valid_consistency_manifest() -> dict:+ return {+ "schema_version": "1.0",+ "numeric_facts": [+ {+ "fact_id": "N001",+ "concept": "synthetic_count",+ "section": "Methods",+ "value": 2,+ "unit": "records",+ "numerator": None,+ "denominator": None,+ "sample_size": 2,+ "analysis_set": "synthetic_set",+ "evidence_ids": ["E001"],+ },+ {+ "fact_id": "N002",+ "concept": "synthetic_count",+ "section": "Results",+ "value": 2,+ "unit": "records",+ "numerator": None,+ "denominator": None,+ "sample_size": 2,+ "analysis_set": "synthetic_set",+ "evidence_ids": ["E001"],+ },+ ],+ "methods": [+ {+ "method_id": "M001",+ "name": "Synthetic deterministic check",+ "analysis_intent": "descriptive",+ "protocol_status": "not_applicable",+ "outcome_ids": ["O001"],+ }+ ],+ "results": [+ {+ "result_id": "R001",+ "method_id": "M001",+ "outcome_id": "O001",+ "analysis_intent": "descriptive",+ "sample_size": 2,+ "evidence_ids": ["E001"],+ "reported_sections": ["Results"],+ }+ ],+ }+++def valid_authorship_manifest() -> dict:+ digest = hashlib.sha256(b"not applicable in synthetic fixture").hexdigest()+ declaration = {+ "status": "not_applicable",+ "content_sha256": digest,+ "verified_by": "Test verifier",+ "verified_on": "2026-07-24",+ }+ return {+ "schema_version": "1.0",+ "authors": [+ {+ "author_id": "A001",+ "name": "Example Human",+ "is_human": True,+ "authorship_criteria": {+ "substantial_contribution": True,+ "drafted_or_critically_revised": True,+ "final_approval": True,+ "accountable_for_work": True,+ },+ "credit_roles": [+ "Conceptualization",+ "Writing – original draft",+ "Writing – review & editing",+ ],+ }+ ],+ "contributors": [],+ "corresponding_author_id": "A001",+ "accountability": {+ "all_authors_approved": True,+ "guarantor_author_ids": ["A001"],+ },+ "ai_use": {+ "used": False,+ "tools": [],+ "disclosed_in": [],+ "human_verification_complete": True,+ "journal_policy_checked": True,+ },+ "declarations": {+ "ai_use": dict(declaration),+ "author_contributions": dict(declaration),+ "conflicts": dict(declaration),+ "funding": dict(declaration),+ },+ }+++def valid_manuscript_manifest() -> dict:+ return {+ "schema_version": "1.0",+ "document_id": "test-manuscript",+ "study_design": "randomized_trial",+ "draft_status": "submission_candidate",+ "submission_ready": True,+ "registries": {+ "source_manifest": "source_manifest.json",+ "claim_evidence": "claims.csv",+ "consistency_manifest": "consistency_manifest.json",+ "authorship_manifest": "authorship.json",+ "reporting_coverage": "reporting_coverage.json",+ },+ "reporting_guidelines": ["consort-2025"],+ "human_verification": {+ "completed": True,+ "verified_by": "Test verifier",+ "verified_on": "2026-07-24",+ },+ "confidentiality_review": {+ "completed": True,+ "verified_by": "Test verifier",+ "verified_on": "2026-07-24",+ "policy_checked": True,+ "external_services_authorized": False,+ },+ "required_statements": {+ "ethics": "not_applicable",+ "consent": "not_applicable",+ "funding": "not_applicable",+ "conflicts": "not_applicable",+ "data_availability": "not_applicable",+ "code_availability": "not_applicable",+ "author_contributions": "verified",+ "ai_disclosure": "not_applicable",+ },+ }diff --git a/skills/scientific-writing/tests/test_scripts.py b/skills/scientific-writing/tests/test_scripts.pynew file mode 100644index 00000000..9928edf6--- /dev/null+++ b/skills/scientific-writing/tests/test_scripts.py@@ -0,0 +1,218 @@+"""Behavior tests for dependency-free scientific-writing scripts."""++from __future__ import annotations++import argparse+import json+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+SCRIPTS = ROOT / "scripts"+sys.path.insert(0, str(SCRIPTS))+sys.path.insert(0, str(Path(__file__).resolve().parent))++import audit_claims+import check_consistency+import check_references+import lint_manuscript+import scaffold_manuscript+import select_reporting_guidelines+import validate_authorship+import validate_manifest+from _common import InputError, read_json+from synthetic import (+ valid_authorship_manifest,+ valid_claim_csv,+ valid_consistency_manifest,+ valid_manuscript_manifest,+ valid_source_manifest,+)+++class ScriptTests(unittest.TestCase):+ def write_json(self, directory: Path, name: str, value: object) -> Path:+ path = directory / name+ path.write_text(json.dumps(value), encoding="utf-8")+ return path++ def test_valid_manuscript_and_source_manifests(self) -> None:+ self.assertEqual(+ validate_manifest.validate_manuscript_manifest(valid_manuscript_manifest()),+ [],+ )+ self.assertEqual(+ validate_manifest.validate_source_manifest(+ valid_source_manifest(),+ require_verified=True,+ ),+ [],+ )++ def test_json_reader_rejects_nonfinite_values(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ path = Path(temporary) / "invalid.json"+ path.write_text('{"value": NaN}', encoding="utf-8")+ with self.assertRaises(InputError):+ read_json(path)++ def test_source_template_fails_closed(self) -> None:+ template = json.loads(+ (ROOT / "assets" / "source_manifest_template.json").read_text(+ encoding="utf-8"+ )+ )+ issues = validate_manifest.validate_source_manifest(+ template,+ require_verified=True,+ )+ self.assertTrue(any(item.severity == "error" for item in issues))++ def test_reporting_selector_and_non_scoring_coverage(self) -> None:+ registry = select_reporting_guidelines.load_registry()+ args = argparse.Namespace(+ study_design="randomized_trial",+ protocol=False,+ ai=False,+ llm=False,+ routinely_collected=False,+ qualitative_component=False,+ )+ primary, extensions, issues = select_reporting_guidelines.select_guidelines(+ registry, args+ )+ self.assertIn("consort-2025", primary)+ self.assertEqual(extensions, [])+ self.assertEqual(issues, [])++ guideline = registry["consort-2025"]+ coverage = {+ "schema_version": "1.0",+ "guideline_id": "consort-2025",+ "items": [+ {+ "topic_id": topic["id"],+ "status": "addressed",+ "locations": ["Methods"],+ "rationale": "",+ }+ for topic in guideline["coverage_topics"]+ ],+ }+ with tempfile.TemporaryDirectory() as temporary:+ path = self.write_json(Path(temporary), "coverage.json", coverage)+ coverage_issues, summary = select_reporting_guidelines.check_coverage(+ registry,+ str(path),+ )+ self.assertEqual(coverage_issues, [])+ self.assertIn("non-scoring", summary["disclaimer"])++ def test_claim_audit_accepts_verified_mappings(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ directory = Path(temporary)+ sources_path = self.write_json(+ directory,+ "sources.json",+ valid_source_manifest(),+ )+ claims_path = directory / "claims.csv"+ claims_path.write_text(valid_claim_csv(), encoding="utf-8")+ manuscript = "Verified test statement [claim:C001] [evidence:E001]\n"+ sources = audit_claims.load_sources(str(sources_path))+ claims, claim_issues = audit_claims.load_claims(str(claims_path), sources)+ markdown_issues, used = audit_claims.audit_markdown(+ manuscript,+ claims,+ sources,+ )+ self.assertEqual(claim_issues, [])+ self.assertEqual(markdown_issues, [])+ self.assertEqual(used, {"C001"})++ def test_claim_audit_flags_untagged_number(self) -> None:+ issues, _ = audit_claims.audit_markdown(+ "An unsupported value is 7.\n",+ {},+ {},+ )+ self.assertTrue(any(item.code == "UNTAGGED_NUMERIC_CONTENT" for item in issues))++ def test_consistency_checks_methods_results_and_numbers(self) -> None:+ data = valid_consistency_manifest()+ fact_issues, fact_count = check_consistency.validate_numeric_facts(data)+ method_issues, method_count, result_count = (+ check_consistency.validate_methods_results(data)+ )+ self.assertEqual(fact_issues, [])+ self.assertEqual(method_issues, [])+ self.assertEqual((fact_count, method_count, result_count), (2, 1, 1))++ data["numeric_facts"][1]["value"] = 3+ mismatch, _ = check_consistency.validate_numeric_facts(data)+ self.assertTrue(+ any(item.code == "CROSS_SECTION_VALUE_MISMATCH" for item in mismatch)+ )+ data["numeric_facts"][1]["value"] = 2+ data["numeric_facts"][1]["sample_size"] = 3+ mismatch, _ = check_consistency.validate_numeric_facts(data)+ self.assertTrue(+ any(item.code == "CROSS_SECTION_SAMPLE_SIZE_MISMATCH" for item in mismatch)+ )++ def test_reference_checker_is_offline_and_detects_duplicate(self) -> None:+ data = valid_source_manifest()+ issues, count = check_references.check_sources(data)+ self.assertEqual(issues, [])+ self.assertEqual(count, 1)++ duplicate = dict(data["sources"][0])+ duplicate["evidence_id"] = "E002"+ data["sources"].append(duplicate)+ issues, _ = check_references.check_sources(data)+ self.assertTrue(any(item.code == "DUPLICATE_DOI" for item in issues))++ def test_authorship_validator_requires_human_accountability(self) -> None:+ data = valid_authorship_manifest()+ issues, author_ids = validate_authorship.validate_people(data)+ issues.extend(validate_authorship.validate_accountability(data, author_ids))+ ai_issues, _ = validate_authorship.validate_ai_disclosure(data)+ issues.extend(ai_issues)+ issues.extend(validate_authorship.validate_declarations(data))+ self.assertEqual(issues, [])++ data["authors"][0]["is_human"] = False+ issues, _ = validate_authorship.validate_people(data)+ self.assertTrue(+ any(item.code == "NONHUMAN_AUTHOR_PROHIBITED" for item in issues)+ )++ def test_lint_flags_placeholders_without_echoing_text(self) -> None:+ manifest = valid_manuscript_manifest()+ clean = lint_manuscript.lint_text("Verified prose without a claim.\n", manifest)+ self.assertEqual(clean, [])+ findings = lint_manuscript.lint_text("[[TODO: unresolved]]\n", manifest)+ self.assertTrue(any(item.code == "UNRESOLVED_PLACEHOLDER" for item in findings))+ self.assertTrue(all("[[TODO" not in str(item.to_dict()) for item in findings))++ def test_scaffold_is_local_and_not_submission_ready(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ output = Path(temporary) / "workspace"+ files = scaffold_manuscript.generate(+ output,+ document_id="test-draft",+ study_design="randomized_trial",+ guidelines=["consort-2025"],+ )+ manifest = json.loads(+ (output / "manuscript_manifest.json").read_text(encoding="utf-8")+ )+ self.assertFalse(manifest["submission_ready"])+ self.assertIn("manuscript.md", files)+ self.assertTrue((output / "claims.csv").is_file())+++if __name__ == "__main__":+ unittest.main()diff --git a/skills/scientific-writing/tests/test_static.py b/skills/scientific-writing/tests/test_static.pynew file mode 100644index 00000000..bfcdb2dd--- /dev/null+++ b/skills/scientific-writing/tests/test_static.py@@ -0,0 +1,175 @@+"""Static safety and packaging tests for scientific-writing."""++from __future__ import annotations++import ast+import csv+import io+import json+import re+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+REPO_ROOT = ROOT.parents[1]+SCRIPT_DIR = ROOT / "scripts"+++class StaticTests(unittest.TestCase):+ def test_skill_frontmatter_and_length(self) -> None:+ text = (ROOT / "SKILL.md").read_text(encoding="utf-8")+ self.assertLess(len(text.splitlines()), 500)+ self.assertTrue(text.startswith("---\n"))+ self.assertIn(' version: "2.0"', text)+ self.assertIn("license: MIT", text)+ self.assertIn("compatibility:", text)+ self.assertNotIn("required_environment_variables", text)+ self.assertNotIn("OPENROUTER_API_KEY", text)++ def test_removed_external_generation_files_stay_removed(self) -> None:+ removed = {+ "generate_image.py",+ "generate_schematic.py",+ "generate_schematic_ai.py",+ "scientific_report.sty",+ "scientific_report_template.tex",+ }+ present = {path.name for path in ROOT.rglob("*") if path.is_file()}+ self.assertTrue(removed.isdisjoint(present))++ def test_all_python_is_parseable(self) -> None:+ for path in sorted(ROOT.rglob("*.py")):+ with self.subTest(path=path.relative_to(ROOT)):+ ast.parse(path.read_text(encoding="utf-8"), filename=str(path))++ def test_runtime_scripts_have_no_network_dynamic_eval_or_process_imports(+ self,+ ) -> None:+ banned_import_roots = {+ "aiohttp",+ "dotenv",+ "httpx",+ "marshal",+ "pickle",+ "requests",+ "socket",+ "subprocess",+ "urllib",+ }+ banned_calls = {"eval", "exec", "compile", "__import__"}+ for path in sorted(SCRIPT_DIR.glob("*.py")):+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ imported: set[str] = set()+ called: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ imported.update(alias.name.split(".")[0] for alias in node.names)+ elif isinstance(node, ast.ImportFrom) and node.module:+ imported.add(node.module.split(".")[0])+ elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):+ called.add(node.func.id)+ with self.subTest(path=path.name):+ self.assertTrue(banned_import_roots.isdisjoint(imported))+ self.assertTrue(banned_calls.isdisjoint(called))++ def test_runtime_scripts_do_not_read_environment(self) -> None:+ forbidden = (+ "os.environ",+ "os.getenv",+ "getenv(",+ "environ[",+ "load_dotenv",+ )+ for path in sorted(SCRIPT_DIR.glob("*.py")):+ text = path.read_text(encoding="utf-8")+ with self.subTest(path=path.name):+ for token in forbidden:+ self.assertNotIn(token, text)++ def test_json_and_csv_assets_are_well_formed(self) -> None:+ for path in sorted((ROOT / "assets").glob("*.json")):+ with self.subTest(path=path.name):+ json.loads(path.read_text(encoding="utf-8"))+ for path in sorted((ROOT / "assets").glob("*.csv")):+ with self.subTest(path=path.name):+ rows = list(csv.reader(io.StringIO(path.read_text(encoding="utf-8"))))+ self.assertGreaterEqual(len(rows), 2)+ self.assertEqual(len(rows[0]), len(rows[1]))++ def test_templates_are_explicitly_incomplete(self) -> None:+ manifest = json.loads(+ (ROOT / "assets" / "manuscript_manifest_template.json").read_text(+ encoding="utf-8"+ )+ )+ self.assertFalse(manifest["submission_ready"])+ scaffold = (ROOT / "assets" / "manuscript_scaffold.md").read_text(+ encoding="utf-8"+ )+ self.assertIn("NOT FOR SUBMISSION", scaffold)+ self.assertIn("[[TODO:", scaffold)++ def test_registry_sources_exist_in_dated_ledger(self) -> None:+ registry = json.loads(+ (ROOT / "assets" / "reporting_guidelines.json").read_text(encoding="utf-8")+ )+ ledger = (ROOT / "references" / "source_ledger.md").read_text(encoding="utf-8")+ self.assertIn("2026-07-24", ledger)+ ledger_ids = set(re.findall(r"SW-S[0-9]{2}", ledger))+ used_ids = {+ source_id+ for guideline in registry["guidelines"]+ for source_id in guideline["source_ids"]+ }+ self.assertTrue(used_ids.issubset(ledger_ids))++ def test_relative_markdown_links_resolve(self) -> None:+ link_re = re.compile(r"\[[^\]]+\]\(([^)]+)\)")+ for path in sorted(ROOT.rglob("*.md")):+ text = path.read_text(encoding="utf-8")+ for target in link_re.findall(text):+ if (+ target.startswith(("http://", "https://", "#", "mailto:"))+ or " " in target+ ):+ continue+ clean_target = target.split("#", 1)[0]+ if not clean_target:+ continue+ with self.subTest(path=path.relative_to(ROOT), target=target):+ self.assertTrue((path.parent / clean_target).resolve().is_file())++ def test_no_cross_skill_calls_or_external_image_workflows(self) -> None:+ text = "\n".join(+ path.read_text(encoding="utf-8")+ for path in sorted(ROOT.rglob("*"))+ if (+ path.is_file()+ and path.suffix in {".md", ".py", ".json", ".csv"}+ and "tests" not in path.relative_to(ROOT).parts+ )+ )+ forbidden = {+ "research-lookup skill",+ "scientific-schematics",+ "venue-templates skill",+ "openrouter.ai",+ "generate_image.py",+ "generate_schematic.py",+ }+ self.assertTrue(all(token not in text for token in forbidden))++ def test_no_bytecode_or_cache_artifacts(self) -> None:+ artifacts = [+ path+ for path in ROOT.rglob("*")+ if path.is_file() and path.suffix in {".pyc", ".pyo"}+ ]+ self.assertEqual(artifacts, [])++ def test_changes_remain_scoped_to_skill(self) -> None:+ self.assertEqual(ROOT, REPO_ROOT / "skills" / "scientific-writing")+++if __name__ == "__main__":+ unittest.main()