ReMe/cookbook/daily_paper/README.md
jinliyl 1687179f84
Some checks are pending
Pre-commit / run (ubuntu-latest) (push) Waiting to run
Tests ReMe / Unit Tests - py3.13 (push) Waiting to run
Tests ReMe / Unit Tests - py3.11 (push) Waiting to run
Tests ReMe / Unit Tests - py3.12 (push) Waiting to run
Windows Smoke / CLI smoke - py3.11 (push) Waiting to run
feat: add Auto Fin cookbook and managed outbound proxy support (#392)
* feat: add ssh proxy

* feat: add ssh proxy

* feat: add ssh proxy

* feat: add ssh proxy

* feat: add prompt

* feat: add agent wrapper

* feat: add agent wrapper

* feat: add agent wrapper

* feat: add tushare skill

* feat: add tushare skill

* feat: add tushare skill

* feat: add none stream

* chore(deps): update dependency versions in pyproject.toml

- Bump claude-agent-sdk from 0.2.123 to 0.2.126
- Upgrade pre-commit to version 4.6.1 or higher
- Upgrade pytest to version 9.1.1 or higher

* feat(agent_wrapper): add session compaction support and unify session commands

- Introduce compact_session method to BaseAgentWrapper and implement it in AsAgentWrapper, CcAgentWrapper, and CodexAgentWrapper
- Add session_command module with SessionCommandResult dataclass and handle_session_command function for /clear and /compact commands
- Update __init__.py exports to include session_command handlers
- Modify DingTalkWaitStep to handle session commands via handle_session_command function
- Remove streaming mode from DingTalkWaitStep and simplify reply handling to final Markdown replies only
- Add unit tests for session compaction methods and session command handling across wrappers and DingTalk integration
- Clean up and remove obsolete streaming and card rendering code from DingTalk wait step
- Adjust daily_cookbook.yaml to remove stream and card_update_interval config entries for DingTalk wait step

* feat(auto_fin): add Auto Fin simulated portfolio cookbook workflow

- Add comprehensive Auto Fin schema exports for multiple models and enums
- Implement base class and helpers for Auto Fin analysis steps
- Create file, state, and formatting utilities for Auto Fin with atomic file writes and locking
- Define Auto Fin pipeline with four analysis agents: backtest, event, portfolio, and US correlation
- Register Auto Fin package in cookbook workflows and schema initialization
- Add detailed documentation in markdown describing the system design, workflow, and data contracts

* feat(outbound_proxy): add application-scoped outbound HTTP proxy components

- Introduce BaseOutboundProxy and OutboundProxyEndpoint as core contracts
- Implement FixedHttpOutboundProxy for external HTTP proxy integration
- Add SshHttpOutboundProxy providing SSH-backed local HTTP proxy tunnels
- Register outbound proxy components in component registry and enumeration
- Update components package to include outbound_proxy module
- Add dependency on pproxy for SSH HTTP proxy bridging
- Include comprehensive unit tests covering proxy lifecycle, validation,
  environment merging, error handling, readiness, and monitoring mechanisms

* refactor(network): replace SSH proxy with explicit HTTP outbound proxy

- Remove SSH proxy helper implementation and references in codebase
- Add support for explicit HTTP proxy URL in arXiv and HuggingFace clients
- Modify clients to use async context manager for consistent resource handling
- Update daily paper steps to forward outbound proxy configuration explicitly
- Change tests to cover new proxy usage model and remove SSH proxy mocks
- Add outbound proxy component configuration in daily_cookbook.yaml
- Ensure proxy URL usage disables environment trust in HTTP clients
- Fix app context component enum access to be defensive against missing keys

* feat(agent_wrapper): add managed proxy support for command environments

- Introduce BaseOutboundProxy binding in BaseAgentWrapper for outbound proxy management
- Add bash_environment and command_proxy_environment properties to apply proxy settings
- Update WorkspaceBackend instantiation in AsAgentWrapper to use bash_environment
- Inject managed proxy export commands into Claude Code Bash commands via hooks
- Enhance CodexAgentWrapper to include managed proxy in shell environment policy
- Modify daily_cookbook.yaml steps to specify outbound_proxy as default where needed
- Add comprehensive unit tests verifying managed proxy injection and environment isolation
- Ensure subprocess_environment remains unchanged while proxy is applied selectively to commands

* refactor(memory): replace search job_tools with memory in daily cookbook config

- Change workspace_dir default from .reme to reme_workspace
- Replace search job_tools with memory across multiple components and jobs
- Update descriptions to reflect long-term memory retrieval instead of search
- Modify system prompts to instruct using memory for retrieving notes
- Adjust unit tests to verify memory job_tools and job presence instead of search
- Ensure consistency in configuration and tests for memory backend usage

* refactor(config): rename memory to memory_search in daily cookbook config

- Change all occurrences of "memory" to "memory_search" in job_tools and job definitions
- Update related system prompts to reflect the new memory_search terminology
- Modify unit tests to assert the presence of memory_search instead of memory
- Ensure consistency across skills, job tools, and backend configurations in multiple components

* feat(auto_fin): add deterministic quantitative research and ranking fusion

- Introduce new schema models: EtfScore, RankingMetrics, ExtremeAnalysis,
  DimensionRanking, and FusionRanking to represent deterministic research outputs
- Add ranking data to event, backtest, us_correlation, and portfolio analysis outputs
- Implement ranking_section renderer to format Top20 scores and diagnostics in Markdown
- Develop AutoFinQuantStep for deterministic ETF ranking using TuShare data, Polars,
  and a custom extremely randomized tree ensemble
- Integrate quantitative rankings into backtest and portfolio analysis steps and reports
- Extend auto_fin pipeline with new quant_enabled and quant_required config options
- Enforce ranking constraints like unique codes, contiguous ranks, and normalized fusion weights
- Update analysis YAMLs with rules limiting data freshness, universe, and ranking usage
- Incorporate ranking outputs into all major markdown report bodies in Auto Fin pipeline
- Add concurrency-limited asynchronous TuShare client to fetch required market data
- Introduce cross-sectional rank correlation and NDCG metrics for ranking quality evaluation

* feat(auto_fin): implement stage-wise notification and reporting for analysis pipeline

- Refactor notification config in daily_cookbook.yaml to support dispatch steps
- Update AutoFinNotificationStep to deduplicate notifications per run stage
- Add _notify_stage method in pipeline to send notifications for each analysis stage
- Implement persistence and notification for event, backtest, US correlation, and portfolio stages
- Modify pipeline flow to persist reports and notify after each stage completion
- Adjust metadata to track notifications and errors per stage
- Update tests to verify stage-wise notification sending and deduplication
- Remove older combined report persistence in favor of modular stage handling

* feat(auto_fin): add outbound proxy support for Tushare API usage

- Introduce BaseOutboundProxy reference in AutoFinPipelineStep and AutoFinQuantStep
- Update TushareResearchClient and trade calendar fetch to accept and use proxy URL
- Create _ProxiedTushareApi adapter to route Tushare requests via explicit HTTP proxy
- Modify create_tushare_api utility to optionally return proxied API client
- Add unit tests covering proxy forwarding and client behavior with managed proxies
- Ensure proxy usage respects explicit proxy URL over environment fallback
- Integrate outbound proxy into data fetching and quantitative research steps

* feat(auto_fin): enforce checkpoint time validation and add state models

- Introduce AnalysisState base class and specific states for event, backtest, and US correlation analyses
- Replace analysis output types with corresponding state classes in run schemas
- Add require_checkpoint_reached method to validate decision_at/data_cutoff against current time
- Enforce checkpoint time checks before analysis steps in event, backtest, portfolio, and quant analyses
- Refactor quant data loading to include adjustment factors and apply price adjustments without fallback
- Update analysis YAML docs to require real-time checkpoint validation and forbid using future data
- Improve portfolio run serialization by excluding redundant legacy fields and nested proposed actions
- Add helper to extract readable sections from persisted checkpoint documents
- Fix event analysis output validation to reject events and sources with future timestamps

* feat(auto_fin): auto-select latest reached checkpoint if none specified

- Extend checkpoint config to accept empty string for auto selection
- Add static method to compute latest checkpoint reached by current time
- Modify pipeline step to auto-select checkpoint based on trade calendar and time
- Adjust force flag default depending on whether checkpoint is explicit or auto
- Log details when checkpoint is auto-selected to improve observability
- Add comprehensive tests for auto checkpoint selection logic and edge cases
- Remove deprecated default and required constraints from force parameter in config

* refactor(auto_fin): unify datetime comparison with compare_datetimes utility

- Replace direct datetime comparisons with compare_datetimes function calls
- Use cmp_to_key with compare_datetimes for sorting datetime tuples and lists
- Update validation logic in backtest, event, analysis, and ledger modules for consistent datetime handling
- Add unit tests to verify handling of naive and aware datetime comparisons in event and backtest validations
- Ensure marked_at and interval_end timestamps are set and compared consistently using compare_datetimes
- Improve correctness of ordering and conditional checks related to timestamps throughout auto_fin steps and ledger code

* feat(auto_fin): add datetime comparison helper for mixed timezone data

- Implement compare_datetimes function to handle naive and aware datetimes
- Ensure naive datetime is interpreted in the known timezone of the counterpart
- Facilitate comparisons between legacy and timezone-aware Auto Fin data
- Add module docstring explaining purpose of the helpers

* docs(auto_fin): enforce unique ETF representative per sub-theme in analysis rules

- Update backtest.yaml to recommend or highlight only one ETF per sub-theme for ETF analyses
- Modify event.yaml to map only one representative ETF per sub-theme, avoiding duplicate recommendations
- Revise portfolio.yaml to restrict holdings/buys to a single ETF per sub-theme, preventing repeated buys of highly overlapping ETFs
- Adjust us_correlation.yaml to retain only one representative A-share ETF per sub-theme for mapping or recommendation
- Add test to verify presence of new sub-theme uniqueness guidance in step prompts

* feat(auto_fin): separate draft model and include deterministic fusion ranking

- Introduce _PortfolioProposalDraft pydantic model for agent-authored fields before ranking
- Discard any "fusion_ranking" data from draft to prevent conflicts with canonical ranking
- Modify AutoFinPortfolioStep to receive draft, enrich with fusion_ranking, and produce final output
- Update tests to use _PortfolioProposalDraft and validate deterministic fusion ranking propagation
- Add async test verifying fusion ranking is correctly set in portfolio output with no errors

* refactor(auto_fin): rewrite and simplify Auto Fin schema and steps

- Remove legacy Auto Fin analysis step modules and helpers
- Replace complex ranking and portfolio models with simplified current-news models
- Update schema to focus on news-case workflow with new domain models
- Remove A-share decision checkpoints and backtest details from schema
- Simplify recommendation and decision output structures
- Clean up deprecated state and utility functions
- Update Auto Fin steps initialization to new pipeline steps only
- Improve uniqueness validation for themes and ETFs in research plan

* feat(auto_fin): implement full local cache and analysis workflow for Auto Fin

- Add AutoFinDataStep to prepare and cache daily TuShare data with lookback
- Add AutoFinAnalysisStep to analyze cached data and generate Markdown report
- Implement detailed time window, ETF filtering, and historical case validation
- Introduce YAML prompts for planning and decision-making steps
- Update .gitignore to include reme_workspace/
- Clean up config and import structure for auto_fin steps
- Remove old pipeline.py and consolidate functionality into new modules
- Use polars for efficient CSV reading and data processing
- Ensure atomic writes and strict JSON serialization for cache files
- Enforce rules on news timing, ETF universe, and historical case usage

* fix(auto_fin): restrict news data source to '财联社' in analysis and cache

- Update analysis templates to specify current news as from '财联社' only
- Modify news fetching functions to filter by source '财联社'
- Add validation method to check cached news source correctness
- Update news caching logic to exclude non-'财联社' news
- Enhance unit tests with multiple sources to ensure filtering works
- Confirm news API calls include source filter parameter as '财联社'

* refactor(auto_fin): convert I/O methods to asynchronous implementations

- Change _news, _dataset, and _theme_data methods to async for improved concurrency
- Move JSONL and CSV reading operations to asynchronous wrappers using asyncio.to_thread
- Remove synchronous _read_jsonl and _read_csv functions, integrate them as static async class methods
- Update cache validation methods to async, awaiting I/O operations accordingly
- Adjust usage of dataset and news retrieval in analysis step to await asynchronous methods
- Add async unit test to validate JSONL reading with unicode line separators
- Preserve existing functionality while enabling non-blocking file and data access

* fix(nx_file_graph): defer networkx import and improve dependency handling

- Move networkx import inside NxFileGraph constructor for lazy loading
- Raise ImportError with original exception context if networkx is missing
- Remove module-level fallback assignment of nx to None
- Expand test to block loading of multiple optional core dependencies eagerly
- Change exception type in test from ModuleNotFoundError to AssertionError
- Update test comments to reflect broader optional dependency checks

* feat(embedding_store): add quota retry delay mechanism for embedding requests

- Introduce quota_retry_delay parameter to configure wait time before retry on quota exhaustion
- Implement detection of insufficient quota errors in LocalEmbeddingStore without external SDK
- Add retry logic with custom delay when quota is insufficient during embedding requests
- Update configuration to set max_retries and quota_retry_delay defaults for embedding store
- Add unit tests covering quota exhaustion retry behavior with delay and opt-in control
- Ensure existing retry behavior remains unchanged if quota_retry_delay is not set

* feat(auto_fin): add detailed logging to analysis and data fetching steps

- Add _preview static method for bounded diagnostic output in analysis.py
- Log prompt start, completion, errors, and validation details in _reply method
- Add info logs for major processing steps in execute method of analysis.py
- Add debug and info logs for cache validation, data fetching, and pagination in data.py
- Log conditions for skipping reports and cache plans in data.py execute method
- Log download summaries and cache writes for news and ETF data
- Improve error logging with exception details in cache validation functions
- Ensure all logs include context such as record counts, paths, and parameters

* refactor(auto_fin): overhaul Auto Fin workflow and schema contracts

- Replace old Auto Fin schema models with comprehensive new data classes
- Remove legacy Auto Fin analysis step in favor of modular agent-based steps
- Introduce AutoFinAgentStep for validating structured agent replies
- Simplify data cleaning and JSONL writing utilities for news cache
- Remove synchronous and asynchronous dataset methods from analysis step
- Redefine Auto Fin analysis configuration for 360-day news retention and multi-step pipeline
- Remove embedded analysis prompt templates and replace with agent-driven logic
- Update __init__.py exports to match new step implementations and remove deprecated classes
- Improve error handling and validation in agent step reply processing
- Clean up redundant imports and unused code in analysis and data preparation modules

* feat(auto_fin): add detailed logging for analysis and data processing steps

- Add timing logs to measure agent prompt processing duration in analysis.py
- Log news cache hits and news write paths with record counts in data.py
- Include detailed info logs for news download start and completion in data.py
- Add start, progress, and completion logs with topic and event counts in history.py
- Log start and completion of merge step including path and ETF count in merge.py
- Add start and done logs with window and news counts in topic.py

* feat(auto_fin): enhance schema and steps with detailed ETF and event modeling

- Replace and add multiple AutoFin schema classes to support detailed ETF selection,
  historical research, market analysis, forecast models, and report output with validation
- Implement Shanghai timezone normalization and strict validation in schema models
- Remove deprecated AutoFin analysis agent step and consolidate reply handling in base step
- Introduce AutoFinStep base class with shared helpers for prompt handling, data fetching,
  logging, and JSONL file operations
- Add AutoFinDataStep to manage daily news data complete with schedule validation, caching,
  and source validation logic
- Update cookbook configuration to customize auto_fin step parameters and simplify
  outbound proxy settings
- Refactor imports and clean unused code for better maintainability

* feat(auto_fin): introduce detailed historical event resolution and market similarity analysis

- Add AutoFinHistoricalEventReference and AutoFinHistoricalSimilarity models for refined event referencing and similarity judgment
- Implement validation to ensure non-empty critical fields and uniqueness of historical news IDs
- Develop method to resolve Agent-selected historical event references from workspace files with strict path and existence checks
- Enrich historical events with market entry and future returns data after resolution
- Redesign market step to calculate similarity-weighted ETF forecasts based on matched historical event similarities
- Enforce validation on matched historical events for uniqueness and proper weight summation
- Simplify merge step output to final Markdown report without YAML frontmatter and redundant fields
- Update user instructions for history search, market, and merge steps to reflect new data structures and responsibilities
- Adjust test suite to cover new schema and step behavior changes, including enhanced validation and JSON output formats

* feat(auto_fin): add new cron jobs and output analysis jsonl

- Add new cron jobs auto_fin_1145_cron and auto_fin_1800_cron with auto_fin_steps
- Change auto_fin_0930_cron schedule to run Monday to Sunday
- Extend merge step to write analysis data to auto_fin_analysis.jsonl
- Update unit tests to verify new cron jobs and their steps configuration

* fix(auto_fin): improve atomic file write and refresh daily index

- Change temporary file naming to include UUID for uniqueness and hidden prefix
- Replace atomic write method from using Path.replace to os.replace with safe unlink
- Add import and use os.replace for safer file replace operation
- Refresh daily index after writing auto finance markdown and JSONL files
- Import and call refresh_day_index in merge step to update file index asynchronously

* docs(cookbook): add optional SSH proxy configuration in README files

- Introduce optional SSH proxy setup in auto-fin and daily_paper cookbooks
- Provide instructions to enable outbound proxy via `daily_cookbook.yaml` and environment variables
- Add `REME_PROXY_IP` and `REME_PROXY_ACCOUNT` environment variables descriptions in multiple README files
- Update English and Chinese README and README_ZH documents with proxy details
- Maintain consistent formatting of environment variable tables across documents

* fix(file_io): include schema_version in hidden metadata keys

- Added "schema_version" to _INDEX_HIDDEN_METADATA_KEYS in _daily_index.py
- Updated _render_notes_block to always include additional keys regardless of schema_version

fix(deps): move pproxy dependency to later in pyproject.toml

- Removed pproxy from early dependencies list
- Added pproxy back near the end of dependency list for better ordering

fix(outbound_proxy): require pproxy package for ssh_http proxy

- Added importlib.util check for pproxy package presence
- Raise RuntimeError if pproxy is not installed when using SSH HTTP outbound proxy
- Improved error message suggests installing reme-ai with 'core' extra

* docs(readme): update News section with new Cookbook workflows

- Clarify introduction of optional Cookbooks with Daily Paper and Auto Fin workflows
- Update English README to reflect both paper discovery and file-native ETF event research
- Revise Chinese README to include financial news and historical market data research capability
- Maintain announcement of paper acceptance at Findings of ACL 2026

* feat(auto_fin): add calculation results to final Markdown output

- Implement _calculation_results to summarize forecast for each ETF analyzed
- Include program-calculated results in the JSON input for the Markdown report
- Update YAML template to incorporate calculation results and adjust recommendation rules
- Refine recommendation logic to rely on event impact judgments combined with calculation outputs
- Modify tests to verify presence of calculation results and updated report content and format

* up prompt

* fix(keyword_index): ignore non-indexable chunks during keyword sync

- Add is_indexable method to base and BM25 keyword index classes to check text tokenizability
- Update local file store to exclude non-indexable chunks from expected document IDs to prevent rebuild
- Fix JSONL chunker to correctly handle Unicode line separator U+2028 inside JSON strings without splitting
- Add test to ensure non-empty but non-indexable chunk does not trigger keyword index rebuild
- Add test to verify U+2028 character does not cause incorrect JSONL record splitting
2026-07-25 18:09:39 +08:00

18 KiB

Daily Paper Cookbook

中文

Daily Paper is a local-first, file-native workflow for turning research rankings into a daily reading package.

Capabilities

  • Collect papers from the Hugging Face weekly and monthly rankings while excluding yesterday's papers and recent recommendations.
  • Rank and select candidates, then use Claude Code to produce detailed Chinese notes and a five-minute Chinese brief.
  • Keep PDFs, notes, and memories as ordinary user-owned files; indexes and caches remain rebuildable.
  • Support daily scheduling, optional DingTalk delivery, conversation memory, auto-dream consolidation, and BM25 recall for the background DingTalk agent.

The workflow is assembled by daily_cookbook.yaml. Its schemas live in reme/schema/daily_paper.py, and its steps live in reme/steps/cookbook/daily_paper/.

Quick start

Daily Paper requires Python 3.11 or later, the core dependencies, network access to Hugging Face and arXiv, and credentials for the configured Claude Code endpoint. Auto-memory and auto-dream additionally require the AgentScope LLM credentials.

From the repository root:

python -m pip install -e ".[core]"
export CLAUDE_CODE_API_KEY="your-api-key"
reme start config=daily_cookbook job=daily_paper

The built-in configuration uses qwen3.7-max through DashScope's Anthropic-compatible endpoint. Override CLAUDE_CODE_MODEL_NAME and CLAUDE_CODE_BASE_URL when using another compatible model or provider.

This is enough to generate paper notes and the daily brief. To use auto-memory and auto-dream, also configure:

export LLM_API_KEY="your-api-key"

By default, outputs are written under reme_workspace/ in the directory where ReMe starts.

Optional SSH proxy

The outbound proxy is disabled by default. To enable it, uncomment components.outbound_proxy.default in daily_cookbook.yaml, configure non-interactive SSH authentication, and set:

export REME_PROXY_IP="your-ssh-proxy-host"
export REME_PROXY_ACCOUNT="your-ssh-account"

What it creates

A successful run writes ordinary PDFs and Markdown files beneath workspace_dir:

reme_workspace/
├── daily/
│   ├── YYYY-MM-DD.md
│   └── YYYY-MM-DD/
│       ├── daily-paper-brief.md
│       ├── paper-<arxiv-id>.md
│       └── ...
├── resource/
│   └── papers/
│       ├── <arxiv-id>.pdf
│       └── ...
├── digest/
│   ├── personal/
│   ├── project/
│   ├── resource/
│   └── wiki/
├── metadata/
│   └── ... derived catalogs, indexes, and caches
└── mem_session/
    ├── agentscope/
    └── claude_config/
  • paper-<arxiv-id>.md is a detailed Chinese reading note with YAML frontmatter linking back to the source PDF and paper pages.
  • daily-paper-brief.md is a roughly five-minute Chinese digest with wikilinks to every selected paper note.
  • daily/YYYY-MM-DD.md is a derived day index rebuilt from the Markdown files for that date.
  • resource/papers/ holds reusable source PDFs.
  • digest/ contains durable auto-dream output; files there remain ordinary user-owned Markdown.
  • metadata/ and search caches are derived state. reindex rebuilds the file store, BM25 index, and graph from source files.

The paper notes are the source of truth for recommendation history: their frontmatter contains the arxiv_id values used for future deduplication. The day index is derived and can be rebuilt. The workflow does not currently write a separate run manifest.

How the workflow works

flowchart LR
    HF[Hugging Face<br/>weekly + monthly] --> C[1. Collect]
    Y[Yesterday's papers] --> C
    H[Recent local notes] --> C
    C --> R[2. Rank]
    R --> S[3. Select]
    S --> A[4. Analyze PDFs]
    A --> D[5. Build brief]
    D --> N[6. Notify DingTalk]
    A --> P[PDFs + paper notes]
    D --> B[Brief + day index]

1. Collect and deduplicate

The Collect step fetches the weekly ranking for the run date's ISO week, the monthly ranking for its calendar month, and the Hugging Face Daily Papers IDs for exactly the previous calendar day. It merges weekly and monthly metadata by arXiv ID and preserves each list's display rank.

It then scans daily/<prior-date>/paper-*.md over the configured history window and excludes IDs found in note frontmatter. The job fails clearly if no eligible papers remain.

2. Rank candidates

The Rank step uses reciprocal-rank fusion:

score = 1 / (rrf_k + monthly_rank)
      + weekly_weight / (rrf_k + weekly_rank)

A missing rank contributes zero. Candidates are ordered by fused score, upvotes, and arXiv ID. The bounded candidate pool also reserves several positions for papers whose titles or summaries match memory-related terms such as agent memory, memory retrieval, continual learning, context compression, knowledge graphs, and RAG. This reserve is a simple keyword heuristic, not a semantic classifier.

3. Select papers

Claude Code receives the bounded candidate pool and returns a structured PaperSelection. The implementation requires exactly top_k unique in-pool IDs with consecutive ranks. Invalid output is returned to the agent once as validation feedback; a second invalid response fails the job.

4. Download and analyze PDFs

Selected papers are processed sequentially. For each paper, the workflow:

  1. validates the modern arXiv ID format;
  2. downloads and validates the PDF, or reuses an existing file with a valid %PDF- header;
  3. extracts text with pypdf, adding page markers and applying page and character limits;
  4. asks Claude Code for a structured detailed reading; and
  5. writes normalized frontmatter plus the generated Markdown body.

The current extractor requires a usable PDF text layer. Scanned or image-only PDFs fail because there is no OCR fallback. If extraction exceeds a configured limit, the note records that the input was truncated.

5. Build the brief and index

Claude Code reads every detailed note and produces the daily brief. The code verifies that each source-note wikilink is present and appends any missing links before writing the file. It then rebuilds daily/YYYY-MM-DD.md from that day's Markdown frontmatter.

6. Optionally notify DingTalk

The final step sends the brief body, without YAML frontmatter, to each configured DingTalk group in order. With no conversation IDs it is a no-op. If one group fails, the step still attempts the remaining groups and reports the combined failure afterward.

The standalone configuration separates agent wrappers by responsibility:

  • daily_paper selects papers, analyzes them, and builds the brief. It keeps Claude Code's normal local tools and disables WebSearch, but currently has no memory-retrieval job configured.
  • dingtalk_wait runs the background DingTalk agent and exposes memory_search as a callable tool.
  • memory runs auto-memory and the LLM-backed auto-dream steps through AgentScope. Its built-in shell and file tools are disabled; memory changes go through the narrower ReMe jobs such as daily_write, read, edit, and write.

The built-in memory_search job uses BM25 over Markdown under daily/ and digest/. ReMe's search step can fuse vector results, but this cookbook does not configure an embedding store by default, so vector retrieval is not run. node_search is a narrower digest recall tool used internally by auto-dream.

index_update_loop indexes existing memory files when the service starts and watches those directories for later changes. Run reindex when recovering the derived file store or forcing a complete index rebuild. Source Markdown and PDFs are not deleted by reindex.

auto_memory writes or updates one daily note from caller-supplied conversation messages and a stable session_id. auto_dream scans recent daily notes, integrates durable units under digest/, and writes interest topics. Both are on-demand jobs in this cookbook; no auto-dream cron is configured. The DingTalk agent can recall through memory_search, but it does not automatically call auto_memory after a conversation.

Dates, reruns, and idempotency

  • date must be an exact YYYY-MM-DD value. When omitted, the job uses today in the application timezone, which is Asia/Shanghai in the built-in configuration.
  • “Yesterday” means date - 1 day, not the previous 24 hours.
  • history_days considers prior dated note directories only; the current run date is never part of its history scan.
  • If daily/<date>/daily-paper-brief.md already exists and force=false, collection, ranking, model calls, PDF work, and digest generation are skipped. The existing brief remains available to the DingTalk notification step.
  • force=true regenerates the notes and brief. Existing valid PDFs are still reused.

Each PDF, detailed note, and final brief uses a temporary file followed by replacement so callers do not see a partially written file. The complete multi-file workflow is not transactional, and there is no global lock for two concurrent runs of the same date.

Running the cookbook

The main jobs in the standalone configuration are:

Job Behavior
daily_paper On-demand generation through the CLI or HTTP service
daily_paper_cron The same pipeline every day at 08:00 in Asia/Shanghai
dingtalk_wait A supervised background DingTalk agent with memory_search
auto_memory Write or update a daily note from conversation messages
auto_dream Consolidate recent daily notes into digest memory and interests
memory_search BM25 recall over daily and digest Markdown
reindex Rebuild derived search state from existing memory files
index_update_loop Initialize and continuously update search state in service mode

Supporting jobs such as node_search, daily_list, daily_write, read, write, edit, and frontmatter updates provide the constrained tools used by the memory agent.

One-time runs

The quick-start command generates today's brief. To generate a specific date with selected overrides:

reme start \
  config=daily_cookbook \
  job=daily_paper \
  date=2026-07-21 \
  top_k=3 \
  history_days=30

Regenerate a date whose brief already exists:

reme start config=daily_cookbook job=daily_paper date=2026-07-21 force=true

Add service.show_metadata=true to a one-time command when the response metadata is useful for diagnostics.

Long-running service and cron

Start the standalone HTTP service and its scheduled/background jobs:

reme start config=daily_cookbook

It listens on 127.0.0.1:8001 by default, so it can run beside the default ReMe service. Call the on-demand job from another terminal with either the ReMe client or HTTP:

reme daily_paper host=127.0.0.1 port=8001
curl -s http://127.0.0.1:8001/daily_paper \
  -H 'Content-Type: application/json' \
  -d '{"date":"2026-07-21","top_k":3,"force":false}'

Recall memory, record a conversation, consolidate it, or explicitly rebuild the search index:

reme memory_search host=127.0.0.1 port=8001 query="agent memory" limit=5

reme auto_memory host=127.0.0.1 port=8001 \
  session_id=example-session \
  messages='[{"name":"user","role":"user","content":"I prefer concise paper summaries."}]'

reme auto_dream host=127.0.0.1 port=8001 date=2026-07-21
reme reindex host=127.0.0.1 port=8001

Service and schedule settings can be overridden at startup:

reme start \
  config=daily_cookbook \
  service.host=0.0.0.0 \
  service.port=8101 \
  jobs.daily_paper_cron.cron="30 7 * * *"

Configuration

The most useful job settings are:

Setting Default Purpose
candidate_limit 20 Maximum number of papers sent to selection
memory_reserve 5 Candidate positions reserved by the memory-keyword heuristic
top_k 3 Number of papers selected and analyzed
rrf_k 60 Reciprocal-rank fusion constant
weekly_weight 0.7 Weight of the weekly ranking in fusion
history_days 30 Prior recommendation window excluded by arXiv ID
hf_timeout 30 seconds Hugging Face request timeout
hf_max_retries 3 Maximum Hugging Face request attempts
pdf_timeout 90 seconds arXiv download timeout
max_pdf_bytes 52428800 Maximum PDF size (50 MiB)
max_pdf_pages 80 Maximum pages extracted for analysis
max_pdf_chars 240000 Maximum extracted characters sent for one paper

The public job parameters are date, force, top_k, weekly_weight, and history_days. Explicit invocation values take precedence over the job defaults.

The standalone application also accepts these environment variables:

Variable Purpose
DAILY_PAPER_WORKSPACE_DIR Overrides the default reme_workspace
DAILY_PAPER_PROJECT_PATH Repository/project path visible to Claude Code
REME_PROXY_IP Optional SSH proxy host
REME_PROXY_ACCOUNT Optional SSH proxy account
DAILY_PAPER_HOST / DAILY_PAPER_PORT HTTP bind address
CLAUDE_CODE_API_KEY API key for the Claude Code endpoint
CLAUDE_CODE_MODEL_NAME Claude Code model; default qwen3.7-max
CLAUDE_CODE_BASE_URL Claude Code Anthropic-compatible endpoint
LLM_API_KEY API key for the AgentScope memory model
LLM_MODEL_NAME Memory model; default qwen3.7-max
LLM_BASE_URL Memory model's Anthropic-compatible endpoint

DAILY_PAPER_PROJECT_PATH defaults to .. relative to the workspace. With the default reme_workspace, starting from the repository root resolves it back to the repository. If the workspace lives elsewhere, set both paths explicitly.

ReMe loads an uncommitted .env file found from the current directory upward, so the same values may be placed there instead of exported in the shell.

DingTalk configuration

DingTalk is optional. Configure it only when brief delivery or the background DingTalk agent is needed:

DINGTALK_APP_KEY=your-app-key
DINGTALK_APP_SECRET=your-app-secret
DINGTALK_ROBOT_CODE=your-robot-code
DINGTALK_CONVERSATION_IDS=cid-group-one,cid-group-two

DINGTALK_CONVERSATION_IDS is required only for proactive brief delivery. The background dingtalk_wait job uses the first three credentials but not the conversation list.

Failure recovery and boundaries

Situation Behavior
Temporary Hugging Face failure Retries with exponential delay up to hf_max_retries attempts
No eligible papers Fails before ranking
Invalid top_k or selection output Fails after validation; selection output gets one retry
Oversized, invalid, or textless PDF Stops during analysis
PDF exceeds page or character limits Continues with truncated text and records the truncation
One paper analysis fails Stops the job; earlier PDFs and notes remain on disk
Brief misses a source-note link Appends the missing wikilink before writing
Auto-dream partial integration Successful units remain; failed paths are not checkpointed

To recover, inspect the date's notes and PDFs, fix the network, credential, model, or PDF issue, then rerun the same date with force=true. Valid cached PDFs will be reused.

The built-in Claude Code components run with permission_mode: bypassPermissions and disable WebSearch. dingtalk_wait can call the local memory_search job; daily_paper currently has no job tools. The analysis and brief prompts constrain what the agent should read, but these steps do not set a strict per-call tool allowlist or an operating-system sandbox. The AgentScope memory wrapper disables its built-in shell and filesystem tools, but runs its ReMe job tools in bypass permission mode. Run the cookbook only with a trusted project and workspace, and tighten the agent configuration before shared or production use.

Tests

The focused unit suite mocks Hugging Face, arXiv, Claude Code, and DingTalk boundaries:

python -m pip install -e ".[dev,core]"
pytest tests/unit/test_daily_paper.py -v

Real runs access external services and may incur model costs; they should not be used as ordinary unit tests.