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
@@ -20,7 +20,7 @@ from src.generator.briefscript_render import (
20
20
  _CONFIDENCE_MARKERS,
21
21
  _FAILED_NOTE,
22
22
  _MISSING_NOTE,
23
- _QUIET_SECTOR_NOTE,
23
+ _empty_sector_note,
24
24
  FX_HEADING,
25
25
  GEOPOLITICS_HEADING,
26
26
  _heading,
@@ -118,7 +118,9 @@ def _holdings(deck: _Deck, block: HoldingsBlock, market: MarketSnapshot) -> None
118
118
 
119
119
  def _sectors(deck: _Deck, block: SectorsBlock) -> None:
120
120
  notes = {note.sector: note for note in block.content.sectors}
121
- moved, quiet = [], []
121
+ moved: list[str] = []
122
+ # Sector names per empty-note label, so unconfirmed ones are not listed as quiet.
123
+ empty: dict[str, list[str]] = {}
122
124
  for sector in dict.fromkeys(" ".join(s.split()) for s in block.sectors if s.strip()):
123
125
  note = notes.get(sector)
124
126
  if note is None:
@@ -127,10 +129,10 @@ def _sectors(deck: _Deck, block: SectorsBlock) -> None:
127
129
  # One claim per sector: the deck is an overview, the page has the rest.
128
130
  moved.append(f"- {_text(sector)}:{deck.claim(note.claims[0], block.content.sources)}")
129
131
  else:
130
- quiet.append(_text(sector))
131
- slides = _chunks(moved, deck.max_claims) or ([[]] if quiet else [])
132
- if quiet:
133
- slides[-1] = [*slides[-1], f"- {_QUIET_SECTOR_NOTE}:{', '.join(quiet)}"]
132
+ empty.setdefault(_empty_sector_note(note), []).append(_text(sector))
133
+ slides = _chunks(moved, deck.max_claims) or ([[]] if empty else [])
134
+ if empty:
135
+ slides[-1] = [*slides[-1], *(f"- {label}:{', '.join(names)}" for label, names in empty.items())]
134
136
  for lines in slides:
135
137
  deck.add(_SECTORS_TITLE, lines)
136
138
 
@@ -35,6 +35,7 @@ _CLOSING = "以上です。"
35
35
  _SPOKEN_CONFIDENCE = {"confirmed": "", "inferred": "推測ですが、", "unknown": "未確認ですが、"}
36
36
  _QUOTE_FAILED = "株価を取得できませんでした"
37
37
  _QUIET_SECTOR = "目立った動きはありませんでした"
38
+ _UNVERIFIED_SECTOR = "今日の動きを確認できませんでした"
38
39
 
39
40
  # Written-only marks: emphasis, code, heading hashes, [n] citations and the
40
41
  # 〔推測〕 / 〔未確認〕 markers the page versions carry.
@@ -110,7 +111,8 @@ def _sectors(block: SectorsBlock) -> list[list[str]]:
110
111
  continue
111
112
  name = _say(sector)
112
113
  if not note.claims:
113
- paragraphs.append([f"{name.rstrip('。')}は、{_QUIET_SECTOR}。"])
114
+ said = _QUIET_SECTOR if note.empty_reason == "quiet" else _UNVERIFIED_SECTOR
115
+ paragraphs.append([f"{name.rstrip('。')}は、{said}。"])
114
116
  else:
115
117
  paragraphs.append([name, *(_claim(c) for c in note.claims)])
116
118
  return paragraphs
@@ -1,7 +1,7 @@
1
1
  """Generate the weekly briefing summary."""
2
2
  from datetime import date, timedelta
3
3
 
4
- from src.claude_runner import get_model, run_claude
4
+ from src.claude_runner import describe_model, get_model, record_fallbacks, run_claude
5
5
  from src.constants import TIMEOUT_WEEKLY_SUMMARY
6
6
  from src.generator.prompt import render
7
7
  from src.logger import get_logger
@@ -39,4 +39,11 @@ def generate_weekly_summary(pages: list[dict]) -> str:
39
39
  prompt = render("weekly_summary", briefings=_format_briefings(pages), week_label=week_label())
40
40
 
41
41
  logger.info("generating weekly summary (model=%s, pages=%d)...", get_model(), len(pages))
42
- return run_claude(prompt, "週次サマリー生成", TIMEOUT_WEEKLY_SUMMARY)
42
+ with record_fallbacks() as fallbacks:
43
+ summary = run_claude(prompt, "週次サマリー生成", TIMEOUT_WEEKLY_SUMMARY)
44
+ # The line above names the model asked for; this one names the model that answered.
45
+ logger.info(
46
+ "weekly summary generated (model=%s)",
47
+ describe_model(get_model(), fallbacks.models, partial=fallbacks.partial),
48
+ )
49
+ return summary
@@ -10,7 +10,7 @@ existing tests.
10
10
  from datetime import date
11
11
 
12
12
  from src.charts.price_comparison import generate_price_comparison
13
- from src.claude_runner import get_model
13
+ from src.claude_runner import describe_model, get_model, record_fallbacks
14
14
  from src.config import CONFIG
15
15
  from src.constants import (
16
16
  BRIEFING_CHART_PERIOD,
@@ -116,12 +116,20 @@ def _briefing_md(ctx) -> str:
116
116
  return render_document_markdown(ctx.results["generate"])
117
117
 
118
118
 
119
+ def _model_label(ctx) -> str:
120
+ """The model that answered, naming any fallback the CLI switched to (#532)."""
121
+ doc = ctx.results["generate"]
122
+ return describe_model(get_model(), doc.fallback_models, partial=doc.fallback_partial)
123
+
124
+
119
125
  def step_generate(ctx) -> BriefingDocument:
120
126
  """The briefing as IR (#513); deliveries render it on the way out."""
121
127
  logger.info("generating briefing (WebSearch)...")
122
128
  fx, fx_change_pct = ctx.results["fx"]
123
129
  stocks, quotes = ctx.results["stocks"]
124
- doc = generate_briefing_document(stocks, CONFIG, fx, quotes=quotes, fx_change_pct=fx_change_pct)
130
+ with record_fallbacks() as fallbacks:
131
+ doc = generate_briefing_document(stocks, CONFIG, fx, quotes=quotes, fx_change_pct=fx_change_pct)
132
+ doc.set_fallbacks(fallbacks.models, fallbacks.partial)
125
133
  briefing = render_document_markdown(doc)
126
134
  logger.debug("briefing generated (length=%d)", len(briefing))
127
135
 
@@ -235,7 +243,7 @@ def skip_notion(ctx) -> bool:
235
243
  def step_deliver_notion(ctx) -> str | None:
236
244
  logger.info("creating Notion page...")
237
245
  briefing = _briefing_md(ctx)
238
- footer = f"---\nModel: {get_model()}"
246
+ footer = f"---\nModel: {_model_label(ctx)}"
239
247
  notion_text = f"{briefing}\n\n{footer}"
240
248
  metrics = extract_briefing_metrics(briefing, CONFIG.portfolio.tickers)
241
249
  page = dict(
@@ -0,0 +1,173 @@
1
+ """Delete raw inputs once they have been processed (#605, policy in #598).
2
+
3
+ Two kinds of raw input pile up under ``input/``:
4
+
5
+ * **Bank statements** (``input/money/*.csv``). After a real import the ledger
6
+ holds every row, ``desc_raw`` included, and re-importing is a no-op for rows
7
+ already stored, so the CSV is a redundant plaintext copy. Recovery is to
8
+ download it from the bank again. Each import is recorded with the file's
9
+ hash; a file is deleted only when that hash still matches, so a re-downloaded
10
+ or edited file is never removed early. Hand-transcribed ``manual`` files have
11
+ no upstream and are never deleted, and nothing outside ``input/`` is touched.
12
+ * **Chat/journal uploads** (``input/images/YYYY-MM-DD/``,
13
+ ``input/attachments/YYYY-MM-DD/``). Most are read once when a message is
14
+ sent, but saved journal entries link to some of them, so a file is deleted
15
+ only when nothing under ``output/`` references its ``/api/<kind>/...`` URL.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import json
21
+ import logging
22
+ import re
23
+ from dataclasses import dataclass, field
24
+ from datetime import date, datetime, timedelta
25
+ from pathlib import Path
26
+
27
+ from src.private_files import write_private_text
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ # Parsers whose files have no upstream copy to re-download.
32
+ KEEP_PARSERS = frozenset({"manual"})
33
+ UPLOAD_KINDS = ("images", "attachments")
34
+ # Text files under output/ that can hold a link to an upload.
35
+ _REFERENCE_SUFFIXES = frozenset({".md", ".json", ".jsonl", ".txt"})
36
+ _UPLOAD_URL_RE = re.compile(r"/api/(?:images|attachments)/\d{4}-\d{2}-\d{2}/[^\s)\"'<>\]]+")
37
+
38
+
39
+ @dataclass
40
+ class PruneResult:
41
+ deleted: list[Path] = field(default_factory=list)
42
+
43
+
44
+ def _sha256(path: Path) -> str:
45
+ return hashlib.sha256(path.read_bytes()).hexdigest()
46
+
47
+
48
+ def _load_log(log_path: Path) -> list[dict]:
49
+ if not log_path.exists():
50
+ return []
51
+ entries = []
52
+ for number, line in enumerate(log_path.read_text(encoding="utf-8").splitlines(), 1):
53
+ if not line.strip():
54
+ continue
55
+ try:
56
+ entry = json.loads(line)
57
+ if not all(isinstance(entry.get(k), str) for k in ("path", "parser", "sha256")):
58
+ raise ValueError("missing field")
59
+ datetime.fromisoformat(entry["imported_at"])
60
+ except (ValueError, KeyError, TypeError, AttributeError):
61
+ logger.warning("%s:%d: unreadable import record skipped", log_path, number)
62
+ continue
63
+ entries.append(entry)
64
+ return entries
65
+
66
+
67
+ def _save_log(log_path: Path, entries: list[dict]) -> None:
68
+ text = "".join(json.dumps(e, ensure_ascii=False) + "\n" for e in entries)
69
+ write_private_text(log_path, text)
70
+
71
+
72
+ def record_imports(log_path: Path, files: list[tuple[Path, str]], *, now: datetime) -> None:
73
+ """Record ``(path, parser)`` pairs as imported at ``now``; a re-import resets the clock."""
74
+ entries = {e["path"]: e for e in _load_log(log_path)}
75
+ for path, parser in files:
76
+ resolved = path.resolve()
77
+ entries[str(resolved)] = {
78
+ "path": str(resolved),
79
+ "parser": parser,
80
+ "sha256": _sha256(resolved),
81
+ "imported_at": now.isoformat(timespec="seconds"),
82
+ }
83
+ _save_log(log_path, list(entries.values()))
84
+
85
+
86
+ def _prune_statements(
87
+ input_dir: Path, log_path: Path, cutoff: datetime, dry_run: bool
88
+ ) -> list[Path]:
89
+ root = input_dir.resolve()
90
+ deleted: list[Path] = []
91
+ remaining: list[dict] = []
92
+ for entry in _load_log(log_path):
93
+ path = Path(entry["path"])
94
+ if not path.is_file():
95
+ continue # already gone: forget it
96
+ due = (
97
+ entry["parser"] not in KEEP_PARSERS
98
+ and path.is_relative_to(root)
99
+ and datetime.fromisoformat(entry["imported_at"]) < cutoff
100
+ and _sha256(path) == entry["sha256"]
101
+ )
102
+ if not due:
103
+ remaining.append(entry)
104
+ continue
105
+ deleted.append(path)
106
+ if not dry_run:
107
+ path.unlink()
108
+ logger.info("deleted imported statement %s", path)
109
+ if not dry_run and log_path.exists():
110
+ _save_log(log_path, remaining)
111
+ return deleted
112
+
113
+
114
+ def _referenced_urls(output_dir: Path) -> set[str]:
115
+ found: set[str] = set()
116
+ if not output_dir.is_dir():
117
+ return found
118
+ for path in output_dir.rglob("*"):
119
+ if path.suffix not in _REFERENCE_SUFFIXES or not path.is_file():
120
+ continue
121
+ try:
122
+ found.update(_UPLOAD_URL_RE.findall(path.read_text(encoding="utf-8", errors="ignore")))
123
+ except OSError:
124
+ continue
125
+ return found
126
+
127
+
128
+ def _prune_uploads(
129
+ input_dir: Path, output_dir: Path, cutoff_day: date, dry_run: bool
130
+ ) -> list[Path]:
131
+ referenced: set[str] | None = None # scanned lazily: most runs find nothing old
132
+ deleted: list[Path] = []
133
+ for kind in UPLOAD_KINDS:
134
+ base = input_dir / kind
135
+ if not base.is_dir():
136
+ continue
137
+ for day_dir in sorted(p for p in base.iterdir() if p.is_dir()):
138
+ try:
139
+ day = date.fromisoformat(day_dir.name)
140
+ except ValueError:
141
+ continue # not one of ours
142
+ if day >= cutoff_day:
143
+ continue
144
+ if referenced is None:
145
+ referenced = _referenced_urls(output_dir)
146
+ for path in sorted(p for p in day_dir.iterdir() if p.is_file()):
147
+ if f"/api/{kind}/{day_dir.name}/{path.name}" in referenced:
148
+ continue
149
+ deleted.append(path)
150
+ if not dry_run:
151
+ path.unlink()
152
+ logger.info("deleted unreferenced upload %s", path)
153
+ if not dry_run and not any(day_dir.iterdir()):
154
+ day_dir.rmdir()
155
+ return deleted
156
+
157
+
158
+ def prune(
159
+ *,
160
+ input_dir: Path,
161
+ output_dir: Path,
162
+ import_log: Path,
163
+ now: datetime,
164
+ retention_days: int,
165
+ dry_run: bool = False,
166
+ ) -> PruneResult:
167
+ """Delete processed inputs older than ``retention_days``; see the module docstring."""
168
+ cutoff = now - timedelta(days=retention_days)
169
+ result = PruneResult()
170
+ result.deleted += _prune_statements(input_dir, import_log, cutoff, dry_run)
171
+ result.deleted += _prune_uploads(input_dir, output_dir, cutoff.date(), dry_run)
172
+ return result
173
+
@@ -107,10 +107,20 @@ def _merge_sidecar(entry_id: str, updates: dict) -> None:
107
107
  MAX_ITEM_LENGTH = 20 # shared limit for sidebar titles / item labels
108
108
 
109
109
  _LEADING_MARKUP_RE = re.compile(r"^[\s#*_>-]+")
110
- _TRAILING_MARKUP_RE = re.compile(r"[\s#*_>:]+$")
110
+ # Trailing markup is stripped with a scan, not `[\s#*_>:]+$`: re.sub retries
111
+ # that pattern from every start position, which is quadratic on a long run of
112
+ # those characters followed by anything else.
113
+ _TRAILING_MARKUP_CHARS = frozenset("#*_>:")
111
114
  _LABEL_ONLY_LINES = {"you", "ai"} # matches USER_LABEL/AI_LABEL in journalQa.ts
112
115
 
113
116
 
117
+ def _strip_trailing_markup(text: str) -> str:
118
+ end = len(text)
119
+ while end and (text[end - 1].isspace() or text[end - 1] in _TRAILING_MARKUP_CHARS):
120
+ end -= 1
121
+ return text[:end]
122
+
123
+
114
124
  def derive_title(content: str) -> str:
115
125
  """Derive a short (<=MAX_ITEM_LENGTH char) sidebar title from an entry's raw content.
116
126
 
@@ -120,7 +130,7 @@ def derive_title(content: str) -> str:
120
130
  labels like ``**You:**``, list bullets) before truncating.
121
131
  """
122
132
  for line in content.splitlines():
123
- text = _TRAILING_MARKUP_RE.sub("", _LEADING_MARKUP_RE.sub("", line)).strip()
133
+ text = _strip_trailing_markup(_LEADING_MARKUP_RE.sub("", line)).strip()
124
134
  if text and text.lower() not in _LABEL_ONLY_LINES:
125
135
  return text[:MAX_ITEM_LENGTH].rstrip()
126
136
  return ""
@@ -41,11 +41,14 @@ def record_comment_as_judgment(comment: dict) -> bool:
41
41
  cmd = [
42
42
  str(JUDGE_BIN), "note",
43
43
  "--domain", JUDGE_DOMAIN,
44
- "--reason", reason,
45
- "--context", context,
44
+ # `--flag=value` keeps a comment that starts with "-" from being read
45
+ # as another option by judge's argument parser.
46
+ f"--reason={reason}",
47
+ f"--context={context}",
46
48
  "--tags", "notion-comment",
47
49
  ]
48
50
  try:
51
+ # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-tainted-env-args.dangerous-subprocess-use-tainted-env-args -- argv list, no shell; user text is a single --flag=value argument
49
52
  subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=JUDGE_TIMEOUT_SEC)
50
53
  except (subprocess.CalledProcessError, OSError, subprocess.TimeoutExpired) as exc:
51
54
  logger.warning("judge note failed for comment %s: %s", comment.get("comment_id"), exc)
@@ -61,6 +61,7 @@ def generate_local_briefing(
61
61
  num_ctx,
62
62
  )
63
63
  else:
64
+ # nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- "tokens" is a count, not a credential
64
65
  logger.info(
65
66
  "[briefing] prompt est. %d tokens (%d chars) / num_ctx=%s",
66
67
  est_tokens,
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import hashlib
6
6
  import sys
7
- from dataclasses import dataclass, field
7
+ from dataclasses import dataclass
8
8
  from pathlib import Path
9
9
  from typing import Iterator, Protocol
10
10
 
@@ -7,7 +7,8 @@
7
7
  "Cache rates follow the standard multipliers on the input rate -- 5-minute",
8
8
  "write 1.25x, 1-hour write 2x, read 0.1x -- unless a model publishes its own,",
9
9
  "as claude-fable-5-1 (0.025x) and claude-opus-5-5 / claude-sonnet-5-5 (0.05x) do for reads. There is no pricing API to fetch these",
10
- "from; see docs/guides/usage-monitoring.md.",
10
+ "from. The pricing doc is deliberately not auto-applied either (a missing rate is detectable, a wrong one is not);",
11
+ "see the \"Pricing\" section of docs/guides/usage-monitoring.md.",
11
12
  "claude-haiku-5-5 is priced by prompt length; the entry holds the <=100k-token tier and is flagged \"tiered\": true,",
12
13
  "so requests over 100k tokens are under-counted and a higher Claude Code bill is not reported as drift.",
13
14
  "as_of is the date the table was last checked against the pricing doc (rate_check --check-upstream); the Monitor tab shows it. Bump it whenever you re-check."
@@ -4,15 +4,19 @@ from __future__ import annotations
4
4
  import argparse
5
5
  import re
6
6
  from collections import defaultdict
7
+ from datetime import datetime
7
8
  from pathlib import Path
8
9
 
9
10
  from . import report as report_mod
10
11
  from . import store
11
12
  from .categorize import uncategorized
12
- from .importer import ImportSummary, import_paths, rebuild
13
+ from .importer import ImportSummary, import_log_path, import_paths, rebuild
13
14
  from .models import OUTPUT_DIR, RULES_PATH, STORE_PATH, MoneyError, Transaction
14
15
  from .rules import Rules, load_rules
15
16
  from .transfers import unpaired_transfer_candidates
17
+ from src import input_retention, paths
18
+ from src.constants import INPUT_RETENTION_DAYS
19
+ from src.private_files import write_private_text
16
20
 
17
21
 
18
22
  def _print_import(summary: ImportSummary) -> None:
@@ -117,9 +121,8 @@ def _cmd_report(args: argparse.Namespace, rules: Rules) -> None:
117
121
  if args.stdout:
118
122
  print(text, end="")
119
123
  return
120
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
121
124
  out = OUTPUT_DIR / out_name
122
- out.write_text(text, encoding="utf-8")
125
+ write_private_text(out, text)
123
126
  print(f"wrote {out}")
124
127
 
125
128
 
@@ -157,6 +160,26 @@ def _cmd_review(args: argparse.Namespace, rules: Rules) -> None:
157
160
  )
158
161
 
159
162
 
163
+ def _cmd_prune(args: argparse.Namespace, rules: Rules) -> None:
164
+ result = input_retention.prune(
165
+ input_dir=paths.INPUT_DIR,
166
+ output_dir=paths.OUTPUT_DIR,
167
+ import_log=import_log_path(args.store),
168
+ now=datetime.now(),
169
+ retention_days=INPUT_RETENTION_DAYS,
170
+ dry_run=args.dry_run,
171
+ )
172
+ if not result.deleted:
173
+ print("削除対象はありません")
174
+ return
175
+ for path in result.deleted:
176
+ print(f" {path}")
177
+ verb = "削除対象" if args.dry_run else "削除しました"
178
+ print(f"\n{verb}: {len(result.deleted)} 件(処理から {INPUT_RETENTION_DAYS} 日経過)")
179
+ if args.dry_run:
180
+ print("(--dry-run のため削除していません)")
181
+
182
+
160
183
  def build_parser() -> argparse.ArgumentParser:
161
184
  parser = argparse.ArgumentParser(
162
185
  prog="money", description="Import bank statements and report monthly cash flow."
@@ -183,6 +206,13 @@ def build_parser() -> argparse.ArgumentParser:
183
206
 
184
207
  reviewer = sub.add_parser("review", help="what still needs a human: unclassified, unpaired")
185
208
  reviewer.set_defaults(func=_cmd_review)
209
+
210
+ pruner = sub.add_parser(
211
+ "prune",
212
+ help=f"delete imported statements and unreferenced uploads after {INPUT_RETENTION_DAYS} days",
213
+ )
214
+ pruner.add_argument("--dry-run", action="store_true", help="list what would be deleted")
215
+ pruner.set_defaults(func=_cmd_prune)
186
216
  return parser
187
217
 
188
218
 
@@ -8,8 +8,11 @@ matching half of a transfer is regularly imported later than the first.
8
8
  from __future__ import annotations
9
9
 
10
10
  from dataclasses import dataclass, field
11
+ from datetime import datetime
11
12
  from pathlib import Path
12
13
 
14
+ from src import input_retention
15
+
13
16
  from . import store
14
17
  from .categorize import categorize
15
18
  from .models import MoneyError, Transaction, UnknownFormatError
@@ -83,6 +86,7 @@ def import_paths(
83
86
  store_path: Path,
84
87
  rules: Rules,
85
88
  dry_run: bool = False,
89
+ import_log: Path | None = None,
86
90
  ) -> ImportSummary:
87
91
  summary = ImportSummary(dry_run=dry_run)
88
92
  existing = store.load(store_path)
@@ -115,4 +119,16 @@ def import_paths(
115
119
  summary.stored = len(merged)
116
120
  if not dry_run:
117
121
  store.save(store_path, merged)
122
+ # Recorded only after the store is saved: a file is prunable once its
123
+ # rows are safely in the ledger, never before.
124
+ input_retention.record_imports(
125
+ import_log or import_log_path(store_path),
126
+ [(f.path, f.parser) for f in summary.files],
127
+ now=datetime.now(),
128
+ )
118
129
  return summary
130
+
131
+
132
+ def import_log_path(store_path: Path) -> Path:
133
+ """Where imports into ``store_path`` are recorded: beside the ledger."""
134
+ return store_path.with_name("imports.jsonl")
@@ -4,6 +4,7 @@ from pathlib import Path
4
4
 
5
5
  from src.generator.briefscript_schema import BriefingDocument
6
6
  from src.logger import get_logger
7
+ from src.private_files import write_private_text
7
8
 
8
9
  logger = get_logger(__name__)
9
10
 
@@ -31,9 +32,8 @@ def save_briefing_md(
31
32
  )
32
33
 
33
34
  today = today or date.today()
34
- output_dir.mkdir(parents=True, exist_ok=True)
35
35
  path = output_dir / f"briefing_{today.strftime('%Y-%m-%d')}.md"
36
- path.write_text(text, encoding="utf-8")
36
+ write_private_text(path, text)
37
37
  logger.info("local MD written: %s (%d chars)", path, len(text))
38
38
 
39
39
  if rotation_enabled:
@@ -179,7 +179,9 @@ def _split_label_colon(line: str) -> list[str]:
179
179
  # The colon sits inside an unclosed Markdown link label
180
180
  # (e.g. "- [heading:body](url)"); splitting here would tear the link in two.
181
181
  return [line]
182
- label = label_part.strip("* ").rstrip("\uFF1A:")
182
+ # Drop the colon before the ** markers: the colon may sit inside the bold
183
+ # ("**label\uFF1A**") or after it ("**label**\uFF1A"), and both must strip cleanly.
184
+ label = label_part.rstrip("\uFF1A:").strip("* ")
183
185
  if not label:
184
186
  return [line]
185
187
  content = re.sub(r"^\*+\s*|\s*\*+$", "", m.group(3).strip())
@@ -42,6 +42,19 @@ def resolve_state_dir(env: Mapping[str, str] = os.environ) -> Path:
42
42
 
43
43
 
44
44
  DATA_HOME = resolve_data_home()
45
+
46
+
47
+ def dotenv_paths() -> list[Path]:
48
+ """Return the .env files the app loads (see ``config.dotenv_files``).
49
+
50
+ Clone layout: the repo-root .env, i.e. the directory holding ``apps/``.
51
+ Relocated data home: only ``$BRIEF_LENS_HOME/.env``.
52
+ """
53
+ if DATA_HOME != APP_ROOT:
54
+ return [DATA_HOME / ".env"]
55
+ return [APP_ROOT.parents[1] / ".env"]
56
+
57
+
45
58
  CONFIG_DIR = DATA_HOME / "config"
46
59
  OUTPUT_DIR = DATA_HOME / "output"
47
60
  LOG_DIR = DATA_HOME / "log"
@@ -7,6 +7,7 @@ from pathlib import Path
7
7
  from .models import HOLDINGS_PATH, OUTPUT_DIR, HoldingsError, load_holdings
8
8
  from .render import render_snapshot
9
9
  from .valuation import FX_FALLBACK, build_snapshot
10
+ from src.private_files import write_private_text
10
11
 
11
12
 
12
13
  def main(argv: list[str] | None = None) -> None:
@@ -38,7 +39,6 @@ def main(argv: list[str] | None = None) -> None:
38
39
  if args.stdout:
39
40
  print(text)
40
41
  return
41
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
42
42
  out = OUTPUT_DIR / f"snapshot_{holdings.as_of}.md"
43
- out.write_text(text, encoding="utf-8")
43
+ write_private_text(out, text)
44
44
  print(f"wrote {out}")
@@ -0,0 +1,87 @@
1
+ """Owner-only permissions for personal data (files 0600, directories 0700).
2
+
3
+ Personal config, raw statements and generated reports must not be readable by
4
+ other local users. Writers go through ``write_private_text`` /
5
+ ``ensure_private_dir``; ``warn_loose_permissions`` reports anything that is
6
+ group/world accessible without changing it, so a surprising mode is the
7
+ owner's decision.
8
+ """
9
+ import logging
10
+ import os
11
+ import stat
12
+ from collections.abc import Iterable
13
+ from pathlib import Path
14
+
15
+ from src import paths
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ PRIVATE_FILE_MODE = 0o600
20
+ PRIVATE_DIR_MODE = 0o700
21
+ _LOOSE_BITS = 0o077
22
+
23
+ PERSONAL_CONFIG_FILES = (
24
+ "briefing.json",
25
+ "holdings.json",
26
+ "money_rules.json",
27
+ "self_agent_profile.md",
28
+ )
29
+
30
+
31
+ def ensure_private_dir(path: Path) -> None:
32
+ """Create ``path`` (and parents) and make the leaf directory 0700."""
33
+ path.mkdir(parents=True, exist_ok=True)
34
+ path.chmod(PRIVATE_DIR_MODE)
35
+
36
+
37
+ def write_private_text(path: Path, text: str, encoding: str = "utf-8") -> None:
38
+ """Write ``text`` to ``path`` with mode 0600, tightening an existing file."""
39
+ ensure_private_dir(path.parent)
40
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, PRIVATE_FILE_MODE)
41
+ try:
42
+ with os.fdopen(fd, "w", encoding=encoding) as fh:
43
+ fh.write(text)
44
+ finally:
45
+ # os.open's mode is ignored for a file that already exists.
46
+ path.chmod(PRIVATE_FILE_MODE)
47
+
48
+
49
+ def personal_paths() -> list[Path]:
50
+ """Files and directories that hold personal data or credentials."""
51
+ files = [paths.CONFIG_DIR / name for name in PERSONAL_CONFIG_FILES]
52
+ return [*files, *paths.dotenv_paths(), paths.INPUT_DIR, paths.OUTPUT_DIR]
53
+
54
+
55
+ def _loose_entries(candidates: Iterable[Path]) -> list[tuple[Path, int, bool]]:
56
+ """Return ``(path, mode, is_dir)`` for existing paths open to group/others.
57
+
58
+ Each path is stat'ed once, so a path removed mid-check cannot raise later.
59
+ """
60
+ loose = []
61
+ for path in candidates:
62
+ try:
63
+ st = path.stat()
64
+ except FileNotFoundError:
65
+ continue
66
+ mode = stat.S_IMODE(st.st_mode)
67
+ if mode & _LOOSE_BITS:
68
+ loose.append((path, mode, stat.S_ISDIR(st.st_mode)))
69
+ return loose
70
+
71
+
72
+ def find_loose_paths(candidates: Iterable[Path]) -> list[Path]:
73
+ """Return existing paths readable/writable by group or others."""
74
+ return [path for path, _, _ in _loose_entries(candidates)]
75
+
76
+
77
+ def warn_loose_permissions(candidates: Iterable[Path] | None = None) -> list[Path]:
78
+ """Log one warning per loose path (path and mode only) and return them."""
79
+ entries = _loose_entries(personal_paths() if candidates is None else candidates)
80
+ for path, mode, is_dir in entries:
81
+ expected = PRIVATE_DIR_MODE if is_dir else PRIVATE_FILE_MODE
82
+ logger.warning(
83
+ "personal data is accessible to other users: %s has mode %03o (expected %03o); "
84
+ "fix with: chmod %03o %s",
85
+ path, mode, expected, expected, path,
86
+ )
87
+ return [path for path, _, _ in entries]
@@ -327,6 +327,7 @@ def diff_upstream(
327
327
  def fetch_pricing_doc(timeout: float = 30) -> str:
328
328
  # The docs host answers urllib's default User-Agent with 403.
329
329
  request = urllib.request.Request(PRICING_URL, headers={"User-Agent": "ai-agent-cli rate_check"})
330
+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected -- request URL is the fixed https PRICING_URL constant
330
331
  with urllib.request.urlopen(request, timeout=timeout) as resp: # noqa: S310 — fixed https URL
331
332
  return resp.read().decode("utf-8")
332
333
 
@@ -1,7 +1,6 @@
1
1
  """Aggregate log/usage/*.jsonl and print token/cost totals per label and per day."""
2
2
  import argparse
3
3
  import json
4
- import sys
5
4
  from collections import defaultdict
6
5
  from datetime import datetime, timedelta
7
6
  from pathlib import Path