brief-lens 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +3 -2
  2. package/dist/python/prompts/briefing_sectors.md +10 -1
  3. package/dist/python/prompts/briefing_sectors_api.md +3 -1
  4. package/dist/python/src/chat_insights.py +3 -2
  5. package/dist/python/src/chat_session.py +7 -0
  6. package/dist/python/src/claude_runner.py +131 -1
  7. package/dist/python/src/config.py +2 -4
  8. package/dist/python/src/constants.py +5 -0
  9. package/dist/python/src/credentials.py +84 -8
  10. package/dist/python/src/generator/briefing.py +42 -22
  11. package/dist/python/src/generator/briefscript_notion.py +2 -2
  12. package/dist/python/src/generator/briefscript_render.py +8 -2
  13. package/dist/python/src/generator/briefscript_schema.py +23 -1
  14. package/dist/python/src/generator/briefscript_slides.py +8 -6
  15. package/dist/python/src/generator/briefscript_speech.py +3 -1
  16. package/dist/python/src/generator/weekly_summary.py +9 -2
  17. package/dist/python/src/handler.py +11 -3
  18. package/dist/python/src/input_retention.py +173 -0
  19. package/dist/python/src/journal_store.py +12 -2
  20. package/dist/python/src/judgment_ingest.py +5 -2
  21. package/dist/python/src/local_llm/briefing/generate.py +1 -0
  22. package/dist/python/src/local_llm/indexer.py +1 -1
  23. package/dist/python/src/model_rates.json +2 -1
  24. package/dist/python/src/money/cli.py +33 -3
  25. package/dist/python/src/money/importer.py +16 -0
  26. package/dist/python/src/notifier/local_md.py +2 -2
  27. package/dist/python/src/notifier/markdown.py +3 -1
  28. package/dist/python/src/paths.py +13 -0
  29. package/dist/python/src/portfolio_snapshot/cli.py +2 -2
  30. package/dist/python/src/private_files.py +87 -0
  31. package/dist/python/src/rate_check.py +1 -0
  32. package/dist/python/src/usage_report.py +0 -1
  33. package/dist/python/src/workflow/cli.py +3 -1
  34. package/dist/python/src/workflow/definitions/chat_insights.py +2 -2
  35. package/dist/python/src/workflow/definitions/daily.py +4 -1
  36. package/dist/python/src/workflow/definitions/input_prune.py +34 -0
  37. package/dist/python/web/app.py +3 -0
  38. package/dist/python/web/routers/archive.py +52 -3
  39. package/dist/python/web/routers/chat.py +96 -7
  40. package/dist/python/web/routers/credentials.py +43 -0
  41. package/dist/web/.next-pack/BUILD_ID +1 -1
  42. package/dist/web/.next-pack/app-build-manifest.json +42 -40
  43. package/dist/web/.next-pack/app-path-routes-manifest.json +6 -6
  44. package/dist/web/.next-pack/build-manifest.json +2 -2
  45. package/dist/web/.next-pack/prerender-manifest.json +3 -3
  46. package/dist/web/.next-pack/server/app/(main)/auth/page.js +2 -2
  47. package/dist/web/.next-pack/server/app/(main)/auth/page.js.nft.json +1 -1
  48. package/dist/web/.next-pack/server/app/(main)/auth/page_client-reference-manifest.js +1 -1
  49. package/dist/web/.next-pack/server/app/(main)/briefing/page.js +2 -2
  50. package/dist/web/.next-pack/server/app/(main)/briefing/page.js.nft.json +1 -1
  51. package/dist/web/.next-pack/server/app/(main)/briefing/page_client-reference-manifest.js +1 -1
  52. package/dist/web/.next-pack/server/app/(main)/chat/page.js +2 -2
  53. package/dist/web/.next-pack/server/app/(main)/chat/page.js.nft.json +1 -1
  54. package/dist/web/.next-pack/server/app/(main)/chat/page_client-reference-manifest.js +1 -1
  55. package/dist/web/.next-pack/server/app/(main)/config/usage/page.js +2 -2
  56. package/dist/web/.next-pack/server/app/(main)/config/usage/page.js.nft.json +1 -1
  57. package/dist/web/.next-pack/server/app/(main)/config/usage/page_client-reference-manifest.js +1 -1
  58. package/dist/web/.next-pack/server/app/(main)/credentials/page.js +2 -2
  59. package/dist/web/.next-pack/server/app/(main)/credentials/page.js.nft.json +1 -1
  60. package/dist/web/.next-pack/server/app/(main)/credentials/page_client-reference-manifest.js +1 -1
  61. package/dist/web/.next-pack/server/app/(main)/geopolitical/page.js +2 -2
  62. package/dist/web/.next-pack/server/app/(main)/geopolitical/page.js.nft.json +1 -1
  63. package/dist/web/.next-pack/server/app/(main)/geopolitical/page_client-reference-manifest.js +1 -1
  64. package/dist/web/.next-pack/server/app/(main)/journal/page.js +2 -2
  65. package/dist/web/.next-pack/server/app/(main)/journal/page.js.nft.json +1 -1
  66. package/dist/web/.next-pack/server/app/(main)/journal/page_client-reference-manifest.js +1 -1
  67. package/dist/web/.next-pack/server/app/(main)/monitor/page.js +2 -2
  68. package/dist/web/.next-pack/server/app/(main)/monitor/page.js.nft.json +1 -1
  69. package/dist/web/.next-pack/server/app/(main)/monitor/page_client-reference-manifest.js +1 -1
  70. package/dist/web/.next-pack/server/app/(main)/portfolio/page.js +2 -2
  71. package/dist/web/.next-pack/server/app/(main)/portfolio/page.js.nft.json +1 -1
  72. package/dist/web/.next-pack/server/app/(main)/portfolio/page_client-reference-manifest.js +1 -1
  73. package/dist/web/.next-pack/server/app/(main)/run/page.js +2 -2
  74. package/dist/web/.next-pack/server/app/(main)/run/page.js.nft.json +1 -1
  75. package/dist/web/.next-pack/server/app/(main)/run/page_client-reference-manifest.js +1 -1
  76. package/dist/web/.next-pack/server/app/(main)/watch-sectors/page.js +2 -2
  77. package/dist/web/.next-pack/server/app/(main)/watch-sectors/page.js.nft.json +1 -1
  78. package/dist/web/.next-pack/server/app/(main)/watch-sectors/page_client-reference-manifest.js +1 -1
  79. package/dist/web/.next-pack/server/app/(main)/workspace/page.js +2 -2
  80. package/dist/web/.next-pack/server/app/(main)/workspace/page.js.nft.json +1 -1
  81. package/dist/web/.next-pack/server/app/(main)/workspace/page_client-reference-manifest.js +1 -1
  82. package/dist/web/.next-pack/server/app/_not-found/page.js +1 -1
  83. package/dist/web/.next-pack/server/app/_not-found/page.js.nft.json +1 -1
  84. package/dist/web/.next-pack/server/app/_not-found/page_client-reference-manifest.js +1 -1
  85. package/dist/web/.next-pack/server/app/_not-found.html +2 -2
  86. package/dist/web/.next-pack/server/app/_not-found.rsc +1 -1
  87. package/dist/web/.next-pack/server/app/api/[...path]/route.js +1 -1
  88. package/dist/web/.next-pack/server/app/api/[...path]/route.js.nft.json +1 -1
  89. package/dist/web/.next-pack/server/app/api/[...path]/route_client-reference-manifest.js +1 -1
  90. package/dist/web/.next-pack/server/app/api/attachments/[...path]/route.js +1 -1
  91. package/dist/web/.next-pack/server/app/api/attachments/[...path]/route.js.nft.json +1 -1
  92. package/dist/web/.next-pack/server/app/api/attachments/[...path]/route_client-reference-manifest.js +1 -1
  93. package/dist/web/.next-pack/server/app/api/attachments/upload/route.js +1 -1
  94. package/dist/web/.next-pack/server/app/api/attachments/upload/route.js.nft.json +1 -1
  95. package/dist/web/.next-pack/server/app/api/attachments/upload/route_client-reference-manifest.js +1 -1
  96. package/dist/web/.next-pack/server/app/api/images/[...path]/route.js +1 -1
  97. package/dist/web/.next-pack/server/app/api/images/[...path]/route.js.nft.json +1 -1
  98. package/dist/web/.next-pack/server/app/api/images/[...path]/route_client-reference-manifest.js +1 -1
  99. package/dist/web/.next-pack/server/app/api/images/upload/route.js +1 -1
  100. package/dist/web/.next-pack/server/app/api/images/upload/route.js.nft.json +1 -1
  101. package/dist/web/.next-pack/server/app/api/images/upload/route_client-reference-manifest.js +1 -1
  102. package/dist/web/.next-pack/server/app/icon.svg/route.js +1 -1
  103. package/dist/web/.next-pack/server/app/icon.svg/route.js.nft.json +1 -1
  104. package/dist/web/.next-pack/server/app/page.js +1 -1
  105. package/dist/web/.next-pack/server/app/page.js.nft.json +1 -1
  106. package/dist/web/.next-pack/server/app/page_client-reference-manifest.js +1 -1
  107. package/dist/web/.next-pack/server/app-paths-manifest.json +6 -6
  108. package/dist/web/.next-pack/server/chunks/1347.js +2 -2
  109. package/dist/web/.next-pack/server/chunks/1692.js +1 -1
  110. package/dist/web/.next-pack/server/chunks/{4983.js → 2213.js} +1 -1
  111. package/dist/web/.next-pack/server/chunks/{4887.js → 3897.js} +3 -3
  112. package/dist/web/.next-pack/server/chunks/5219.js +8 -0
  113. package/dist/web/.next-pack/server/chunks/7374.js +21 -0
  114. package/dist/web/.next-pack/server/chunks/9110.js +1 -1
  115. package/dist/web/.next-pack/server/pages/404.html +2 -2
  116. package/dist/web/.next-pack/server/pages/500.html +1 -1
  117. package/dist/web/.next-pack/server/pages/_app.js.nft.json +1 -1
  118. package/dist/web/.next-pack/server/pages/_document.js.nft.json +1 -1
  119. package/dist/web/.next-pack/server/pages/_error.js.nft.json +1 -1
  120. package/dist/web/.next-pack/server/pages-manifest.json +1 -1
  121. package/dist/web/.next-pack/server/server-reference-manifest.json +1 -1
  122. package/dist/web/.next-pack/static/chunks/6292-64dda8c7c791b41f.js +1 -0
  123. package/dist/web/.next-pack/static/chunks/7555-3dad4c2b7cce43ce.js +1 -0
  124. package/dist/web/.next-pack/static/chunks/{8625-053b60d296b472a1.js → 8625-c1e89d56a186ce14.js} +1 -1
  125. package/dist/web/.next-pack/static/chunks/app/(main)/briefing/page-106e8b178dd30dc2.js +1 -0
  126. package/dist/web/.next-pack/static/chunks/app/(main)/credentials/page-8d18181bdc269181.js +1 -0
  127. package/dist/web/.next-pack/static/chunks/app/(main)/journal/page-8d893d497aa2303e.js +1 -0
  128. package/dist/web/.next-pack/static/chunks/app/(main)/layout-44701007707a325a.js +1 -0
  129. package/dist/web/.next-pack/static/chunks/app/page-e478eeb25eaa8664.js +1 -0
  130. package/dist/web/package.json +5 -2
  131. package/lib/args.mjs +21 -1
  132. package/lib/home.mjs +15 -2
  133. package/lib/host.mjs +55 -0
  134. package/lib/preflight.mjs +11 -4
  135. package/lib/serve.mjs +16 -8
  136. package/package.json +2 -2
  137. package/dist/web/.next-pack/server/chunks/4410.js +0 -21
  138. package/dist/web/.next-pack/server/chunks/8640.js +0 -8
  139. package/dist/web/.next-pack/static/chunks/7555-dd9a2ec853548b5e.js +0 -1
  140. package/dist/web/.next-pack/static/chunks/app/(main)/briefing/page-e281f84f36f96ce7.js +0 -1
  141. package/dist/web/.next-pack/static/chunks/app/(main)/credentials/page-8fe06728bfd39a7d.js +0 -1
  142. package/dist/web/.next-pack/static/chunks/app/(main)/journal/page-3577d3add31eb50f.js +0 -1
  143. package/dist/web/.next-pack/static/chunks/app/(main)/layout-4f2eb21e40c439ea.js +0 -1
  144. package/dist/web/.next-pack/static/chunks/app/page-0cf601f660005544.js +0 -1
  145. /package/dist/web/.next-pack/static/{y0P7BP_hkbxmUb1rrMaMH → bSsIsQRxqBbd4eDe1ibcc}/_buildManifest.js +0 -0
  146. /package/dist/web/.next-pack/static/{y0P7BP_hkbxmUb1rrMaMH → bSsIsQRxqBbd4eDe1ibcc}/_ssgManifest.js +0 -0
package/README.md CHANGED
@@ -15,16 +15,17 @@ then starts the API and Web UI and opens your browser.
15
15
 
16
16
  ## Requirements
17
17
 
18
- - Node.js 18+
18
+ - Node.js 18.18+ (19.x needs 19.8+)
19
19
  - [uv](https://docs.astral.sh/uv/)
20
20
  - [Claude Code](https://docs.claude.com/en/docs/claude-code) CLI, logged in, on a paid Claude plan (Pro/Max)
21
- - macOS or Linux
21
+ - macOS. On Linux, use the [Docker setup](https://github.com/KazusaNakagawa/ai-agent-cli/blob/main/docs/guides/docker.md) instead
22
22
 
23
23
  ## Options
24
24
 
25
25
  ```
26
26
  --port <n> Web UI port (default: 3000)
27
27
  --api-port <n> API port (default: 8000)
28
+ --host <addr> Address the Web UI binds to (default: 127.0.0.1; for the Docker setup)
28
29
  --home <dir> Data home (default: $BRIEF_LENS_HOME or ~/.brief-lens)
29
30
  --no-browser Do not open the browser
30
31
  -v, --version Print the version
@@ -1,6 +1,13 @@
1
1
  あなたは株式市場アナリストです。必ず日本語で回答してください。
2
2
  WebSearchを使って今日の最新情報を調べ、以下の監視セクター全件について動向をレポートしてください。
3
3
 
4
+ 実行日: $today(日本時間)
5
+
6
+ ## 調べ方のルール
7
+ - 各セクターは、そのセクターを対象にした検索を最低 1 回行う。市場全体の検索結果だけで済ませないこと。
8
+ - 使うのは、直前の取引日(週末や祝日の明けは、休場前の最後の取引日)から実行日までの記事だけ。休場中に出た記事も使ってよいが、直前の取引日の記事を必ず確認すること。前年以前の同じ日付の記事など、期間外の記事は根拠にしないこと。
9
+ - 期間内の記事が見つからないときは、クエリを変えて(英語と日本語の切り替え、企業名やティッカーでの検索など)もう一度検索する。
10
+
4
11
  ## 監視セクターと主要銘柄
5
12
  各セクター全件について、今日の動きを調査してください。
6
13
  $watch_sectors
@@ -13,7 +20,9 @@ $stocks
13
20
  - `sectors` には上の監視セクターを全件、1セクター1回ずつ、セクター名をそのまま書いて入れる。
14
21
  - 各セクターの `claims` は 0〜3 個。1つの claim は 1 文(目安 80 字以内)で、何が起きたか・なぜ動いたかを書く。
15
22
  - **今日の株価・騰落率は書かないこと**(上の株価は動きの大小を判断する参考情報)。記事で確認した決算数値・受注額などは書いてよい。
16
- - 目立った動きがないセクターは `claims` を空にする(「動き限定的」とシステムが表示する)。「監視を継続」のような中身のない claim で埋めないこと。
23
+ - `claims` が空のセクターは、`empty_reason` に理由を必ず入れる。「監視を継続」のような中身のない claim で埋めないこと。
24
+ - `quiet`: 期間内の記事を確認したうえで、目立った動きがなかった(「動き限定的」とシステムが表示する)。
25
+ - `unverified`: 検索しても期間内の記事が見つからず、動きの有無を判断できなかった(「未確認」とシステムが表示する)。そのセクターを検索していない場合もこちら。
17
26
  - `related_tickers` には claims に関係する銘柄のティッカーを最大 5 個入れる(なければ空)。
18
27
  - `confidence` の付け方:
19
28
  - `confirmed`: 記事で確認できた事実。必ず `source_ids` で出典を1つ以上挙げる。
@@ -21,7 +21,9 @@ Markdownで記述し、Notionで見やすくなるよう以下の構造を厳守
21
21
 
22
22
  ### 今日のセクター動向(全セクター)
23
23
 
24
- 監視セクター全件について記載(目立った動きがないセクターは「動き限定的」と一言添えるだけでよい)
24
+ 監視セクター全件について記載する。
25
+ - 取得済み記事でそのセクターを確認でき、目立った動きがない場合は「動き限定的」と一言添える。
26
+ - 取得済み記事がそのセクターを扱っていない場合は「〔未確認〕今日の動きは確認できませんでした。」と書く。「動き限定的」にしない。
25
27
 
26
28
  #### セクター名(例: AI・クラウド)
27
29
  何が起きたか・なぜ動いたか(関連銘柄を括弧内に)
@@ -21,6 +21,7 @@ from pathlib import Path
21
21
  from typing import Iterable
22
22
 
23
23
  from src import paths
24
+ from src.private_files import ensure_private_dir, write_private_text
24
25
 
25
26
  SESSIONS_DIR = paths.OUTPUT_DIR / "briefing" / ".sessions"
26
27
  ARCHIVE_DIR = paths.OUTPUT_DIR / "chat_archive"
@@ -122,7 +123,7 @@ def archive_sessions(
122
123
  result = ArchiveResult()
123
124
  if not sessions_dir.is_dir():
124
125
  return result
125
- archive_dir.mkdir(parents=True, exist_ok=True)
126
+ ensure_private_dir(archive_dir)
126
127
  for session_file in sorted(p for p in sessions_dir.iterdir() if p.is_file()):
127
128
  session_date = session_file.name
128
129
  transcript = _find_transcript(session_file.read_text().strip(), transcripts_dir)
@@ -133,7 +134,7 @@ def archive_sessions(
133
134
  if not turns:
134
135
  continue
135
136
  out = archive_dir / f"{session_date}.jsonl"
136
- out.write_text("\n".join(json.dumps(t, ensure_ascii=False) for t in turns) + "\n", encoding="utf-8")
137
+ write_private_text(out, "\n".join(json.dumps(t, ensure_ascii=False) for t in turns) + "\n")
137
138
  result.archived.append(session_date)
138
139
  return result
139
140
 
@@ -76,6 +76,13 @@ def build_journal_cmd(
76
76
  f"{wrap_untrusted(journal_context, label='journal_entries')}\n"
77
77
  "=== END ==="
78
78
  )
79
+ if trusted_write_dirs:
80
+ # The working directory is read-only (#639): a bare file name would fail.
81
+ context += (
82
+ "\n\nファイルを保存できる場所は次のディレクトリの中だけです。"
83
+ "保存するときは、この中の絶対パスを指定してください:\n"
84
+ + "\n".join(f"- {d}" for d in trusted_write_dirs)
85
+ )
79
86
  return [
80
87
  "claude",
81
88
  "--session-id", session_id,
@@ -4,6 +4,9 @@ import shutil
4
4
  import subprocess
5
5
  import threading
6
6
  import time
7
+ from collections.abc import Iterator
8
+ from contextlib import contextmanager
9
+ from contextvars import ContextVar
7
10
  from dataclasses import dataclass
8
11
  from datetime import datetime
9
12
 
@@ -293,6 +296,126 @@ def _warn_if_fell_back(result: _StreamResult, model: str, label: str) -> None:
293
296
  )
294
297
 
295
298
 
299
+ class FallbackReport:
300
+ """What the claude CLI did about fallbacks while a ``record_fallbacks`` scope was open.
301
+
302
+ ``run_claude`` returns only text, so which model actually answered has no
303
+ other way out of it. Every successful call is counted, with the fallback
304
+ models it switched to (none for most calls), because a run made of several
305
+ calls can fall back on only some of them. Calls come from worker threads,
306
+ hence the lock.
307
+ """
308
+
309
+ def __init__(self, parent: "FallbackReport | None" = None, *, deferred: bool = False) -> None:
310
+ self._models: list[str] = []
311
+ self._calls = 0
312
+ self._fallback_calls = 0
313
+ self._lock = threading.Lock()
314
+ self._parent = parent
315
+ # A deferred report keeps its calls to itself until ``commit()``, for
316
+ # callers that may still reject a response after run_claude returned it.
317
+ self._deferred = deferred
318
+ self._log: list[tuple[str, ...]] = []
319
+
320
+ def add_call(self, models: tuple[str, ...]) -> None:
321
+ """Record one successful call and the fallback models it switched to."""
322
+ with self._lock:
323
+ self._calls += 1
324
+ if models:
325
+ self._fallback_calls += 1
326
+ for model in models:
327
+ if model not in self._models:
328
+ self._models.append(model)
329
+ self._log.append(models)
330
+ if self._parent is not None and not self._deferred:
331
+ self._parent.add_call(models)
332
+
333
+ def commit(self) -> None:
334
+ """Hand the calls of a deferred report to the enclosing scope (no-op otherwise)."""
335
+ with self._lock:
336
+ if not self._deferred:
337
+ return
338
+ self._deferred = False
339
+ log = list(self._log)
340
+ if self._parent is not None:
341
+ for models in log:
342
+ self._parent.add_call(models)
343
+
344
+ @property
345
+ def models(self) -> tuple[str, ...]:
346
+ """Distinct fallback models in the order they were first used."""
347
+ with self._lock:
348
+ return tuple(self._models)
349
+
350
+ @property
351
+ def partial(self) -> bool:
352
+ """True when some, but not all, of the calls fell back."""
353
+ with self._lock:
354
+ return 0 < self._fallback_calls < self._calls
355
+
356
+
357
+ # Context-local, so two runs in one process (a briefing and a chat answer in the
358
+ # web server) never see each other's fallbacks. Threads started inside a scope
359
+ # do not inherit it on their own; see ``generator.briefing._submit``.
360
+ _fallback_report: ContextVar["FallbackReport | None"] = ContextVar("claude_fallback_report", default=None)
361
+
362
+
363
+ @contextmanager
364
+ def record_fallbacks() -> Iterator[FallbackReport]:
365
+ """Collect the fallback models used by every ``run_claude`` call made inside.
366
+
367
+ Scopes nest: an inner scope also reports to the one around it.
368
+ """
369
+ report = FallbackReport(parent=_fallback_report.get())
370
+ token = _fallback_report.set(report)
371
+ try:
372
+ yield report
373
+ finally:
374
+ _fallback_report.reset(token)
375
+
376
+
377
+ @contextmanager
378
+ def tentative_fallbacks() -> Iterator[FallbackReport]:
379
+ """Like ``record_fallbacks``, but the enclosing scope only sees the calls after ``commit()``.
380
+
381
+ Use it around a call whose response the caller may still reject (schema
382
+ validation, retry), so a discarded attempt leaves no fallback model behind.
383
+ """
384
+ report = FallbackReport(parent=_fallback_report.get(), deferred=True)
385
+ token = _fallback_report.set(report)
386
+ try:
387
+ yield report
388
+ finally:
389
+ _fallback_report.reset(token)
390
+
391
+
392
+ def describe_model(
393
+ primary: str, fallbacks: tuple[str, ...] | list[str] = (), *, partial: bool = False,
394
+ ) -> str:
395
+ """Name the model(s) that answered, e.g. for a footer or a log line.
396
+
397
+ - no fallback: ``primary``
398
+ - every call fell back: ``claude-haiku-5-5 (fallback from <primary>)``
399
+ - only some calls fell back (``partial``): ``<primary> (some calls fell back
400
+ to claude-haiku-5-5)``, so a reader does not take the whole run, the main
401
+ analysis included, to have come from the fallback.
402
+ """
403
+ if not fallbacks:
404
+ return primary
405
+ names = ", ".join(fallbacks)
406
+ if partial:
407
+ return f"{primary} (some calls fell back to {names})"
408
+ return f"{names} (fallback from {primary})"
409
+
410
+
411
+ def _record_call(result: _StreamResult) -> None:
412
+ """Count one successful call, with any fallback the CLI switched to, in the open scope."""
413
+ report = _fallback_report.get()
414
+ if report is not None:
415
+ # tuple() so a list (get_fallback_models() returns one) is not dropped.
416
+ report.add_call(tuple(getattr(result, "fallback_models", None) or ()))
417
+
418
+
296
419
  def _backoff_delay(attempt: int) -> float:
297
420
  """Return the seconds to wait before the ``attempt``-th retry (1-indexed)."""
298
421
  return RETRY_BASE_DELAY * (RETRY_BACKOFF_FACTOR ** (attempt - 1))
@@ -362,6 +485,9 @@ def run_claude(
362
485
  "--output-format", "stream-json",
363
486
  "--verbose",
364
487
  "--include-partial-messages",
488
+ # --allowedTools only adds approvals, and the local settings may already
489
+ # allow a shell; --tools removes every other built-in tool (#639).
490
+ "--tools", "WebSearch",
365
491
  "--allowedTools", "WebSearch",
366
492
  "--model", model,
367
493
  # Project-level settings.local.json can pre-approve Skill(*) and MCP
@@ -396,7 +522,11 @@ def run_claude(
396
522
  if result.returncode == 0:
397
523
  logger.info("claude CLI done: %s (%d chars)", label, len(result.stdout))
398
524
  _warn_if_fell_back(result, model, label)
399
- return _parse_and_log_usage(result.stdout, label, structured=json_schema is not None)
525
+ text = _parse_and_log_usage(result.stdout, label, structured=json_schema is not None)
526
+ # After parsing: a response that fails to parse is discarded and
527
+ # must not leave its fallback model in the report.
528
+ _record_call(result)
529
+ return text
400
530
 
401
531
  logger.error(
402
532
  "claude CLI error [%s] rc=%d attempt=%d/%d\nstdout=%s\nstderr=%s",
@@ -31,14 +31,12 @@ logger = get_logger(__name__)
31
31
  def dotenv_files() -> list[Path]:
32
32
  """Return the .env files to load, in order.
33
33
 
34
- Clone layout: the repo-root .env (one level above apps/python/). With a
34
+ Clone layout: the repo-root .env (two levels above apps/python/). With a
35
35
  relocated data home (``BRIEF_LENS_HOME``) only the data-home .env is used —
36
36
  load_dotenv never overrides a variable that is already set, so also
37
37
  loading the repo file first would silently shadow the data-home values.
38
38
  """
39
- if paths.DATA_HOME != paths.APP_ROOT:
40
- return [paths.DATA_HOME / ".env"]
41
- return [paths.APP_ROOT.parent / ".env"]
39
+ return paths.dotenv_paths()
42
40
 
43
41
 
44
42
  # Since credentials.get_credential() prefers values already in the keychain,
@@ -76,6 +76,11 @@ BRIEFING_CHART_PERIOD = "1y"
76
76
 
77
77
  # Briefing local MD retention (number of newest dated files to keep)
78
78
  BRIEFING_MD_RETENTION_DAYS = 7
79
+
80
+ # Raw inputs (imported bank CSVs, unreferenced chat/journal uploads) are deleted
81
+ # this many days after processing (#605, policy in #598). Recovery for a
82
+ # statement is re-downloading it from the bank; the ledger keeps every row.
83
+ INPUT_RETENTION_DAYS = 3
79
84
  # When False, _prune_old is skipped and all dated files are kept indefinitely
80
85
  BRIEFING_MD_ROTATION_ENABLED = False
81
86
  # When True, skip the pipeline if today's briefing MD already exists (prevents
@@ -1,15 +1,18 @@
1
1
  """OS Keychain wrapper + .env fallback.
2
2
 
3
3
  Stores credentials in the OS keychain via `python-keyring`. On read, falls back
4
- to the same-named environment variable only when the keychain returns ``None``.
4
+ to the same-named environment variable when the keychain has no value or cannot
5
+ be read. The fallback is logged per key (never the value), reported by
6
+ ``credential_sources()``, and refused when ``STRICT_ENV`` is set.
5
7
  Writes always go to the keychain (.env is immutable).
6
8
 
7
9
  Names outside the allowed set (`ALLOWED_KEYS`) raise ``ValueError``. This guards
8
10
  both the ``/api/credentials`` input sanitization and against operational
9
11
  mistakes that would store unknown keys.
10
12
  """
13
+ import logging
11
14
  import os
12
- from typing import Any
15
+ from typing import Any, Literal
13
16
 
14
17
  import keyring
15
18
 
@@ -32,6 +35,21 @@ ALLOWED_KEYS: tuple[str, ...] = (
32
35
 
33
36
  _backend: Any = keyring
34
37
 
38
+ # Opt-in: when truthy, a value that would come from the environment (e.g. a
39
+ # plaintext .env) raises instead. Tests and CI leave it unset.
40
+ STRICT_ENV = "BRIEF_LENS_STRICT_CREDENTIALS"
41
+ _TRUTHY = frozenset({"1", "true", "yes", "on"})
42
+
43
+ Source = Literal["keychain", "env"] | None
44
+
45
+ logger = logging.getLogger(__name__)
46
+ # Keys whose environment fallback was already logged in this process.
47
+ _fallback_logged: set[str] = set()
48
+
49
+
50
+ class CredentialSourceError(RuntimeError):
51
+ """Strict mode refused a credential that is not readable from the keychain."""
52
+
35
53
 
36
54
  def _ensure_allowed(name: str) -> None:
37
55
  if name not in ALLOWED_KEYS:
@@ -43,17 +61,62 @@ def service_name() -> str:
43
61
  return RELOCATED_SERVICE if paths.DATA_HOME != paths.APP_ROOT else SERVICE
44
62
 
45
63
 
46
- def get_credential(name: str) -> str | None:
47
- _ensure_allowed(name)
64
+ def strict_mode() -> bool:
65
+ """True when ``STRICT_ENV`` forbids reading credentials from the environment."""
66
+ return os.environ.get(STRICT_ENV, "").strip().lower() in _TRUTHY
67
+
68
+
69
+ def _resolve(name: str) -> tuple[str | None, Source, bool]:
70
+ """Return ``(value, source, keychain_failed)`` without enforcing strict mode."""
71
+ keychain_failed = False
48
72
  try:
49
73
  value = _backend.get_password(service_name(), name)
50
74
  except keyring.errors.KeyringError:
51
- # No backend, or a locked / denied Keychain (e.g. a cancelled macOS
52
- # prompt): fall back to the environment rather than crash the caller.
75
+ # No backend, or a locked / denied Keychain (e.g. a cancelled macOS prompt).
53
76
  value = None
77
+ keychain_failed = True
54
78
  if value:
79
+ return value, "keychain", keychain_failed
80
+ env_value = os.environ.get(name) or None
81
+ if env_value:
82
+ return env_value, "env", keychain_failed
83
+ return None, None, keychain_failed
84
+
85
+
86
+ def get_credential(name: str) -> str | None:
87
+ """Read ``name`` from the keychain, falling back to the environment.
88
+
89
+ The fallback logs the key name once per process (never the value). In
90
+ strict mode it raises ``CredentialSourceError`` instead, as does a keychain
91
+ that cannot be read; a key set nowhere still returns ``None`` so optional
92
+ credentials keep working.
93
+ """
94
+ _ensure_allowed(name)
95
+ value, source, keychain_failed = _resolve(name)
96
+ if source == "keychain":
55
97
  return value
56
- return os.environ.get(name) or None
98
+ if strict_mode():
99
+ if keychain_failed:
100
+ raise CredentialSourceError(
101
+ f"{name}: the OS keychain could not be read and {STRICT_ENV} "
102
+ "forbids the environment fallback. Unlock the keychain and retry."
103
+ )
104
+ if source == "env":
105
+ raise CredentialSourceError(
106
+ f"{name} is not in the OS keychain and {STRICT_ENV} forbids reading it "
107
+ "from the environment. Store it in the keychain (Settings → Credentials) "
108
+ "and remove it from .env."
109
+ )
110
+ if source == "env" and name not in _fallback_logged:
111
+ _fallback_logged.add(name)
112
+ # The rule fires on the word "credential" in the message; the value is
113
+ # never passed (pinned by test_env_fallback_logs_key_and_source_but_not_value).
114
+ logger.warning( # nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- logs the key name only
115
+ "credential %s read from the environment, not the OS keychain; "
116
+ "store it in the keychain and remove it from .env",
117
+ name,
118
+ )
119
+ return value
57
120
 
58
121
 
59
122
  def set_credential(name: str, value: str) -> None:
@@ -61,10 +124,23 @@ def set_credential(name: str, value: str) -> None:
61
124
  _backend.set_password(service_name(), name, value)
62
125
 
63
126
 
127
+ def has_keychain_entry(name: str) -> bool:
128
+ """True when the keychain holds ``name``; raises ``KeyringError`` if unreadable."""
129
+ _ensure_allowed(name)
130
+ return _backend.get_password(service_name(), name) is not None
131
+
132
+
64
133
  def delete_credential(name: str) -> None:
65
134
  _ensure_allowed(name)
66
135
  _backend.delete_password(service_name(), name)
67
136
 
68
137
 
138
+ def credential_sources() -> dict[str, Source]:
139
+ """Where each allow-listed key currently resolves from: keychain, env, or unset."""
140
+ return {name: _resolve(name)[1] for name in ALLOWED_KEYS}
141
+
142
+
69
143
  def list_credentials() -> dict[str, bool]:
70
- return {name: get_credential(name) is not None for name in ALLOWED_KEYS}
144
+ # Resolve without strict enforcement: listing must not raise, and the
145
+ # sources endpoint is what tells the user a value comes from the environment.
146
+ return {name: source is not None for name, source in credential_sources().items()}
@@ -1,3 +1,4 @@
1
+ import contextvars
1
2
  import json
2
3
  from concurrent.futures import ThreadPoolExecutor, as_completed
3
4
  from datetime import date
@@ -6,7 +7,7 @@ from pathlib import Path
6
7
 
7
8
  from pydantic import ValidationError
8
9
 
9
- from src.claude_runner import run_claude
10
+ from src.claude_runner import run_claude, tentative_fallbacks
10
11
  from src.config import BriefingConfig
11
12
  from src.constants import (
12
13
  BRIEFSCRIPT_VALIDATION_MAX_ATTEMPTS,
@@ -206,13 +207,16 @@ def _watch_sector_names(config: BriefingConfig) -> list[str]:
206
207
  ))
207
208
 
208
209
 
209
- def generate_sectors_section(stocks: str, config: BriefingConfig) -> SectorsSection:
210
+ def generate_sectors_section(
211
+ stocks: str, config: BriefingConfig, today: date | None = None,
212
+ ) -> SectorsSection:
210
213
  """Run the sector sweep as validated BriefScript (#514)."""
211
214
  sectors = _watch_sector_names(config)
212
215
  prompt = render(
213
216
  "briefing_sectors",
214
217
  watch_sectors=build_watch_sectors_context(config),
215
218
  stocks=stocks,
219
+ today=(today or date.today()).isoformat(),
216
220
  )
217
221
  return _generate_validated(
218
222
  prompt, "セクタースイープ", TIMEOUT_BRIEFING_SECTORS, sectors_json_schema(sectors),
@@ -265,22 +269,28 @@ def _generate_validated(prompt: str, label: str, timeout: int, schema: dict, par
265
269
  base_prompt = prompt
266
270
  last_error = ""
267
271
  for attempt in range(1, BRIEFSCRIPT_VALIDATION_MAX_ATTEMPTS + 1):
268
- raw = run_claude(
269
- prompt, label, timeout,
270
- max_attempts=RETRY_MAX_ATTEMPTS_BRIEFING, json_schema=schema,
271
- )
272
- try:
273
- return parse(json.loads(raw))
274
- except (json.JSONDecodeError, ValidationError) as e:
275
- last_error = str(e)
276
- logger.warning(
277
- "%s BriefScript failed validation (attempt %d/%d): %s",
278
- label, attempt, BRIEFSCRIPT_VALIDATION_MAX_ATTEMPTS, _truncate_error(last_error),
279
- )
280
- prompt = (
281
- f"{base_prompt}\n\n## 前回の出力のエラー\n"
282
- f"前回の出力は次の検証エラーで却下されました。直して出力し直してください。\n{last_error}"
272
+ # An attempt's fallbacks reach the enclosing report only once its
273
+ # output validates, so a rejected attempt leaves no model behind.
274
+ with tentative_fallbacks() as attempt_report:
275
+ raw = run_claude(
276
+ prompt, label, timeout,
277
+ max_attempts=RETRY_MAX_ATTEMPTS_BRIEFING, json_schema=schema,
283
278
  )
279
+ try:
280
+ parsed = parse(json.loads(raw))
281
+ except (json.JSONDecodeError, ValidationError) as e:
282
+ last_error = str(e)
283
+ else:
284
+ attempt_report.commit()
285
+ return parsed
286
+ logger.warning(
287
+ "%s BriefScript failed validation (attempt %d/%d): %s",
288
+ label, attempt, BRIEFSCRIPT_VALIDATION_MAX_ATTEMPTS, _truncate_error(last_error),
289
+ )
290
+ prompt = (
291
+ f"{base_prompt}\n\n## 前回の出力のエラー\n"
292
+ f"前回の出力は次の検証エラーで却下されました。直して出力し直してください。\n{last_error}"
293
+ )
284
294
  raise BriefScriptError(f"{label} BriefScript invalid after retries: {_truncate_error(last_error)}")
285
295
 
286
296
 
@@ -345,6 +355,16 @@ def _sectors_block(section: SectorsSection, config: BriefingConfig) -> SectorsBl
345
355
  return SectorsBlock(sectors=_watch_sector_names(config), content=section)
346
356
 
347
357
 
358
+ def _submit(executor: ThreadPoolExecutor, fn, /, *args, **kwargs):
359
+ """Submit ``fn`` to run in a copy of the caller's context.
360
+
361
+ ``ThreadPoolExecutor`` does not carry context variables into its workers, so
362
+ without this a ``record_fallbacks`` scope opened around the briefing would
363
+ miss every call made on the pool threads.
364
+ """
365
+ return executor.submit(contextvars.copy_context().run, fn, *args, **kwargs)
366
+
367
+
348
368
  def generate_briefing_document(
349
369
  stocks: str,
350
370
  config: BriefingConfig,
@@ -382,18 +402,18 @@ def generate_briefing_document(
382
402
  )
383
403
  with ThreadPoolExecutor(max_workers=3) as executor:
384
404
  if briefscript:
385
- main = executor.submit(generate_main_section, render("briefing_main", **main_parts), config)
405
+ main = _submit(executor, generate_main_section, render("briefing_main", **main_parts), config)
386
406
  else:
387
- main = executor.submit(
388
- run_claude, render("briefing", **main_parts), "メイン分析", TIMEOUT_BRIEFING_MAIN,
407
+ main = _submit(
408
+ executor, run_claude, render("briefing", **main_parts), "メイン分析", TIMEOUT_BRIEFING_MAIN,
389
409
  max_attempts=RETRY_MAX_ATTEMPTS_BRIEFING,
390
410
  )
391
411
  futures = {
392
412
  main: "main",
393
- executor.submit(generate_sectors_section, stocks, config): "sectors",
413
+ _submit(executor, generate_sectors_section, stocks, config, today): "sectors",
394
414
  }
395
415
  if briefscript:
396
- futures[executor.submit(generate_holdings, stocks, config)] = "holdings"
416
+ futures[_submit(executor, generate_holdings, stocks, config)] = "holdings"
397
417
  results: dict = {}
398
418
  errors: dict[str, str] = {}
399
419
  for future in as_completed(futures):
@@ -19,7 +19,6 @@ from src.generator.briefscript_render import (
19
19
  _FAILED_NOTE,
20
20
  _MISSING_NOTE,
21
21
  _MISSING_SECTOR_NOTE,
22
- _QUIET_SECTOR_NOTE,
23
22
  FX_HEADING,
24
23
  GEOPOLITICS_HEADING,
25
24
  HOLDINGS_HEADING,
@@ -27,6 +26,7 @@ from src.generator.briefscript_render import (
27
26
  SECTORS_SECTION_HEADING,
28
27
  STORIES_HEADING,
29
28
  SUMMARY_HEADING,
29
+ _empty_sector_note,
30
30
  _heading,
31
31
  _number_sources,
32
32
  _plain,
@@ -151,7 +151,7 @@ def _sectors_blocks(block: SectorsBlock) -> list[dict]:
151
151
  if note is None:
152
152
  blocks.append(_bullet(_text(_MISSING_SECTOR_NOTE)))
153
153
  elif not note.claims:
154
- blocks.append(_bullet(_text(_QUIET_SECTOR_NOTE)))
154
+ blocks.append(_bullet(_text(_empty_sector_note(note))))
155
155
  else:
156
156
  blocks += _claim_bullets(note.claims, numbers, section.sources)
157
157
  tickers = [t for t in (_plain(x) for x in (note.related_tickers if note else ())) if t]
@@ -22,6 +22,7 @@ from src.generator.briefscript_schema import (
22
22
  MarketSnapshot,
23
23
  QuoteSnapshot,
24
24
  SectorsBlock,
25
+ SectorNote,
25
26
  SectorsSection,
26
27
  Source,
27
28
  )
@@ -47,7 +48,8 @@ _MISSING_NOTE = "〔未確認〕今日の材料は確認できませんでした
47
48
  _FAILED_NOTE = "〔未確認〕本日の示唆は生成できませんでした。"
48
49
  # Bullet for a sector with no claims: the model found no material move.
49
50
  _QUIET_SECTOR_NOTE = "動き限定的"
50
- # Bullet for a configured sector the LLM returned nothing for.
51
+ # Bullet for a configured sector whose current news could not be confirmed:
52
+ # either nothing was returned for it, or its empty note is not marked quiet.
51
53
  _MISSING_SECTOR_NOTE = "〔未確認〕今日の動きは確認できませんでした。"
52
54
 
53
55
  _LEADING_HASHES = re.compile(r"^\s*#+\s*")
@@ -162,6 +164,10 @@ def render_holdings_markdown(
162
164
  return "\n\n".join(blocks + _source_list(numbers, section.sources))
163
165
 
164
166
 
167
+ def _empty_sector_note(note: SectorNote) -> str:
168
+ return _QUIET_SECTOR_NOTE if note.empty_reason == "quiet" else _MISSING_SECTOR_NOTE
169
+
170
+
165
171
  def render_sectors_markdown(section: SectorsSection, sectors: list[str]) -> str:
166
172
  """The sector sweep: every configured sector once, in configured order.
167
173
 
@@ -178,7 +184,7 @@ def render_sectors_markdown(section: SectorsSection, sectors: list[str]) -> str:
178
184
  if note is None:
179
185
  bullets = [f"- {_MISSING_SECTOR_NOTE}"]
180
186
  elif not note.claims:
181
- bullets = [f"- {_QUIET_SECTOR_NOTE}"]
187
+ bullets = [f"- {_empty_sector_note(note)}"]
182
188
  else:
183
189
  bullets = [_bullet(c, numbers) for c in note.claims]
184
190
  tickers = [t for t in (_plain(x) for x in (note.related_tickers if note else ())) if t]
@@ -24,6 +24,7 @@ from pydantic import (
24
24
  ConfigDict,
25
25
  Field,
26
26
  HttpUrl,
27
+ PrivateAttr,
27
28
  ValidationInfo,
28
29
  field_validator,
29
30
  model_validator,
@@ -90,8 +91,10 @@ class SectorNote(BaseModel):
90
91
  model_config = _STRICT
91
92
 
92
93
  sector: str = Field(min_length=1)
93
- # Empty means no material move today; the renderer says so.
94
94
  claims: list[Claim] = Field(default_factory=list, max_length=3)
95
+ # Why claims is empty (#613); ignored when there are claims. Only an explicit
96
+ # "quiet" is reported as a quiet day, so a missing value is not a retry.
97
+ empty_reason: Literal["quiet", "unverified"] | None = None
95
98
  related_tickers: list[str] = Field(default_factory=list, max_length=5)
96
99
 
97
100
 
@@ -348,6 +351,25 @@ class BriefingDocument(BaseModel):
348
351
  market: MarketSnapshot = Field(default_factory=MarketSnapshot)
349
352
  sections: list[Section] = Field(default_factory=list)
350
353
 
354
+ # How this run was produced, not part of the briefing: kept out of the
355
+ # schema and the serialized form, and read by the deliveries for the footer.
356
+ _fallback_models: tuple[str, ...] = PrivateAttr(default=())
357
+ _fallback_partial: bool = PrivateAttr(default=False)
358
+
359
+ @property
360
+ def fallback_models(self) -> tuple[str, ...]:
361
+ """Models the claude CLI fell back to while generating this briefing."""
362
+ return self._fallback_models
363
+
364
+ @property
365
+ def fallback_partial(self) -> bool:
366
+ """True when only some of the generation calls fell back."""
367
+ return self._fallback_partial
368
+
369
+ def set_fallbacks(self, models: tuple[str, ...], partial: bool = False) -> None:
370
+ self._fallback_models = tuple(models)
371
+ self._fallback_partial = partial
372
+
351
373
 
352
374
  def _fold(name: str, *, upper: bool) -> str:
353
375
  # Tickers compare case-insensitively; sector names (often Japanese) only