brief-lens 0.1.2 → 0.1.3

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 (85) hide show
  1. package/dist/python/prompts/chat_insights.md +34 -0
  2. package/dist/python/src/chat_cli.py +28 -9
  3. package/dist/python/src/chat_insights.py +200 -0
  4. package/dist/python/src/local_llm/config.py +5 -0
  5. package/dist/python/src/local_llm/indexer.py +63 -10
  6. package/dist/python/src/workflow/definitions/chat_insights.py +83 -0
  7. package/dist/python/src/workflow/definitions/daily.py +4 -1
  8. package/dist/python/web/routers/chat.py +36 -19
  9. package/dist/python/web/routers/config.py +28 -0
  10. package/dist/web/.next-pack/BUILD_ID +1 -1
  11. package/dist/web/.next-pack/app-build-manifest.json +33 -32
  12. package/dist/web/.next-pack/app-path-routes-manifest.json +1 -1
  13. package/dist/web/.next-pack/build-manifest.json +2 -2
  14. package/dist/web/.next-pack/prerender-manifest.json +1 -1
  15. package/dist/web/.next-pack/server/app/(main)/auth/page.js.nft.json +1 -1
  16. package/dist/web/.next-pack/server/app/(main)/auth/page_client-reference-manifest.js +1 -1
  17. package/dist/web/.next-pack/server/app/(main)/briefing/page.js.nft.json +1 -1
  18. package/dist/web/.next-pack/server/app/(main)/briefing/page_client-reference-manifest.js +1 -1
  19. package/dist/web/.next-pack/server/app/(main)/chat/page.js +1 -1
  20. package/dist/web/.next-pack/server/app/(main)/chat/page.js.nft.json +1 -1
  21. package/dist/web/.next-pack/server/app/(main)/chat/page_client-reference-manifest.js +1 -1
  22. package/dist/web/.next-pack/server/app/(main)/config/usage/page.js.nft.json +1 -1
  23. package/dist/web/.next-pack/server/app/(main)/config/usage/page_client-reference-manifest.js +1 -1
  24. package/dist/web/.next-pack/server/app/(main)/credentials/page.js.nft.json +1 -1
  25. package/dist/web/.next-pack/server/app/(main)/credentials/page_client-reference-manifest.js +1 -1
  26. package/dist/web/.next-pack/server/app/(main)/geopolitical/page.js.nft.json +1 -1
  27. package/dist/web/.next-pack/server/app/(main)/geopolitical/page_client-reference-manifest.js +1 -1
  28. package/dist/web/.next-pack/server/app/(main)/journal/page.js +1 -1
  29. package/dist/web/.next-pack/server/app/(main)/journal/page.js.nft.json +1 -1
  30. package/dist/web/.next-pack/server/app/(main)/journal/page_client-reference-manifest.js +1 -1
  31. package/dist/web/.next-pack/server/app/(main)/monitor/page.js.nft.json +1 -1
  32. package/dist/web/.next-pack/server/app/(main)/monitor/page_client-reference-manifest.js +1 -1
  33. package/dist/web/.next-pack/server/app/(main)/portfolio/page.js.nft.json +1 -1
  34. package/dist/web/.next-pack/server/app/(main)/portfolio/page_client-reference-manifest.js +1 -1
  35. package/dist/web/.next-pack/server/app/(main)/run/page.js.nft.json +1 -1
  36. package/dist/web/.next-pack/server/app/(main)/run/page_client-reference-manifest.js +1 -1
  37. package/dist/web/.next-pack/server/app/(main)/watch-sectors/page.js.nft.json +1 -1
  38. package/dist/web/.next-pack/server/app/(main)/watch-sectors/page_client-reference-manifest.js +1 -1
  39. package/dist/web/.next-pack/server/app/(main)/workspace/page.js.nft.json +1 -1
  40. package/dist/web/.next-pack/server/app/(main)/workspace/page_client-reference-manifest.js +1 -1
  41. package/dist/web/.next-pack/server/app/_not-found/page.js.nft.json +1 -1
  42. package/dist/web/.next-pack/server/app/_not-found/page_client-reference-manifest.js +1 -1
  43. package/dist/web/.next-pack/server/app/_not-found.html +2 -2
  44. package/dist/web/.next-pack/server/app/_not-found.rsc +1 -1
  45. package/dist/web/.next-pack/server/app/api/[...path]/route.js.nft.json +1 -1
  46. package/dist/web/.next-pack/server/app/api/attachments/[...path]/route.js.nft.json +1 -1
  47. package/dist/web/.next-pack/server/app/api/attachments/upload/route.js.nft.json +1 -1
  48. package/dist/web/.next-pack/server/app/api/images/[...path]/route.js.nft.json +1 -1
  49. package/dist/web/.next-pack/server/app/api/images/upload/route.js.nft.json +1 -1
  50. package/dist/web/.next-pack/server/app/icon.svg/route.js.nft.json +1 -1
  51. package/dist/web/.next-pack/server/app/page.js +9 -9
  52. package/dist/web/.next-pack/server/app/page.js.nft.json +1 -1
  53. package/dist/web/.next-pack/server/app/page_client-reference-manifest.js +1 -1
  54. package/dist/web/.next-pack/server/app-paths-manifest.json +6 -6
  55. package/dist/web/.next-pack/server/chunks/1442.js +2 -2
  56. package/dist/web/.next-pack/server/chunks/899.js +1 -0
  57. package/dist/web/.next-pack/server/pages/404.html +2 -2
  58. package/dist/web/.next-pack/server/pages/500.html +1 -1
  59. package/dist/web/.next-pack/server/pages/_app.js.nft.json +1 -1
  60. package/dist/web/.next-pack/server/pages/_document.js.nft.json +1 -1
  61. package/dist/web/.next-pack/server/pages/_error.js.nft.json +1 -1
  62. package/dist/web/.next-pack/server/server-reference-manifest.json +1 -1
  63. package/dist/web/.next-pack/static/chunks/2793-3a816c3e63003cd6.js +1 -0
  64. package/dist/web/.next-pack/static/chunks/4397-f2bbfac974a09e4a.js +1 -0
  65. package/dist/web/.next-pack/static/chunks/6739-73ae2a518896a21d.js +1 -0
  66. package/dist/web/.next-pack/static/chunks/9095-7b51a045d7ef3c03.js +1 -0
  67. package/dist/web/.next-pack/static/chunks/app/(main)/briefing/page-2bd110800f6f6092.js +1 -0
  68. package/dist/web/.next-pack/static/chunks/app/(main)/chat/page-4787522c9ae8eb98.js +1 -0
  69. package/dist/web/.next-pack/static/chunks/app/(main)/journal/page-f06bd837eb652eec.js +1 -0
  70. package/dist/web/.next-pack/static/chunks/app/(main)/layout-722c5f8b47c03713.js +1 -0
  71. package/dist/web/.next-pack/static/chunks/app/page-31f1d43bab366b86.js +1 -0
  72. package/dist/web/.next-pack/static/css/eeafe748380067e9.css +3 -0
  73. package/package.json +1 -1
  74. package/dist/web/.next-pack/server/chunks/3462.js +0 -1
  75. package/dist/web/.next-pack/static/chunks/2941-b28caa63b1192cbf.js +0 -1
  76. package/dist/web/.next-pack/static/chunks/6739-26a12feb3f34ac69.js +0 -1
  77. package/dist/web/.next-pack/static/chunks/8480-3e063ceeceee7e6a.js +0 -1
  78. package/dist/web/.next-pack/static/chunks/app/(main)/briefing/page-32855bc0aad3c4c5.js +0 -1
  79. package/dist/web/.next-pack/static/chunks/app/(main)/chat/page-f176f405e29e9deb.js +0 -1
  80. package/dist/web/.next-pack/static/chunks/app/(main)/journal/page-d0b70496ffe17f8d.js +0 -1
  81. package/dist/web/.next-pack/static/chunks/app/(main)/layout-b0cecbd1d6c9d290.js +0 -1
  82. package/dist/web/.next-pack/static/chunks/app/page-ecd907ac75b147cf.js +0 -1
  83. package/dist/web/.next-pack/static/css/ddefc688f27e14b2.css +0 -3
  84. /package/dist/web/.next-pack/static/{VdoUHqMuKEB2yUBQvac5b → HRelvfbIJ8aRo0S_dK4jo}/_buildManifest.js +0 -0
  85. /package/dist/web/.next-pack/static/{VdoUHqMuKEB2yUBQvac5b → HRelvfbIJ8aRo0S_dK4jo}/_ssgManifest.js +0 -0
@@ -0,0 +1,34 @@
1
+ あなたは、個人が毎日使っているチャット(マーケットブリーフィングを文脈に持つ Claude Code セッション)の利用傾向を分析するアナリストです。
2
+
3
+ 以下の「集計値」はプログラムで数えた確定値です。件数や割合を書くときはこの値だけを使い、自分で数え直したり推測で補ったりしないでください。発言の分類件数のように集計値にない数字を出す場合は、発言一覧から数えたことが分かるように「約」を付けてください。
4
+
5
+ ## 集計値
6
+ ```json
7
+ $stats
8
+ ```
9
+
10
+ 会話記録がすでに消えていて分析に含められなかった日付: $missing
11
+
12
+ ## 発言一覧(ユーザーの発言のみ、日付付き)
13
+ $turns
14
+
15
+ ## 出力形式
16
+ 日本語の Markdown で、次の見出しをこの順に出力してください。前置きや締めの挨拶は不要です。
17
+
18
+ ### 結論
19
+ 2〜3文。このチャットが実際に何の場として使われているかと、いちばん大きな発見。
20
+
21
+ ### 何を頼んでいるか
22
+ 分類(例: 投資調査、開発・運用、家計・生活、その他)ごとの件数と代表例の表。
23
+
24
+ ### 繰り返している流れ
25
+ 同じ形の依頼が何度も続いている箇所を、日付と流れ(A → B → C)で挙げる。繰り返しがなければ「なし」。
26
+
27
+ ### やり残し
28
+ 「決算後に確認」「下がったら見る」など、後で確認すると言ったまま次の発言で触れていない項目。日付付きで。
29
+
30
+ ### 自動化の候補
31
+ 表: 候補 / 何をするか / 根拠になった発言の日付 / 優先度(高・中・低)。根拠のない候補は出さない。
32
+
33
+ ### 書き方と時間帯
34
+ 集計値から読み取れること(発言の短さ、時間帯、よく使うスキルやツール)を3点以内。
@@ -1,25 +1,19 @@
1
1
  """Interactive Q&A session using a daily briefing as context."""
2
2
  import argparse
3
- import os
4
3
  import subprocess
5
4
  import sys
6
5
  from datetime import date
7
6
  from pathlib import Path
8
7
 
9
8
  from src import paths
9
+ from src import state as state_mod
10
10
  from src.chat_session import build_cmd, session_name_for
11
+ from src.claude_runner import build_env
11
12
 
12
13
  BRIEFING_DIR = paths.OUTPUT_DIR / "briefing"
13
14
  SESSIONS_DIR = BRIEFING_DIR / ".sessions"
14
15
 
15
16
 
16
- def claude_env() -> dict[str, str]:
17
- """Return the parent environment without Anthropic API credentials."""
18
- env = os.environ.copy()
19
- env.pop("ANTHROPIC_API_KEY", None)
20
- return env
21
-
22
-
23
17
  def list_sessions(sessions_dir: Path) -> None:
24
18
  files = sorted(f for f in sessions_dir.iterdir() if f.is_file()) if sessions_dir.exists() else []
25
19
  if not files:
@@ -30,6 +24,24 @@ def list_sessions(sessions_dir: Path) -> None:
30
24
  print(f" {f.name} {f.read_text().strip()}")
31
25
 
32
26
 
27
+ def _auth_mode() -> str:
28
+ """Return the configured auth_mode, falling back to "cli" with a warning.
29
+
30
+ The chat CLI never read state.json before auth_mode support, so a corrupt
31
+ file (JSONDecodeError) or an invalid auth_mode value (ValueError) must not
32
+ brick bin/chat.sh with a raw traceback — warn readably and run on the
33
+ OAuth session instead, matching the pre-change behaviour.
34
+ """
35
+ try:
36
+ return state_mod.read_state().auth_mode
37
+ except (ValueError, OSError) as exc:
38
+ print(
39
+ f"Warning: could not read state ({exc}); falling back to cli auth mode.",
40
+ file=sys.stderr,
41
+ )
42
+ return "cli"
43
+
44
+
33
45
  def _print_intro(target_date: str, session_file: Path, is_resume: bool) -> None:
34
46
  """Tell the user which session they're in. Lives here (not in build_cmd) so
35
47
  the library function stays silent for SSE use."""
@@ -46,7 +58,14 @@ def run_claude(target_date: str, briefing_file: Path, session_file: Path) -> int
46
58
  initial context for new sessions, and session_file stores the saved Claude
47
59
  session id. Returns the final subprocess exit code.
48
60
  """
49
- env = claude_env()
61
+ auth_mode = _auth_mode()
62
+ env = build_env(auth_mode=auth_mode)
63
+ if auth_mode == "api" and "ANTHROPIC_API_KEY" not in env:
64
+ print(
65
+ "Warning: auth_mode is 'api' but no ANTHROPIC_API_KEY was found in "
66
+ "the Keychain or .env; the session will run on the OAuth subscription.",
67
+ file=sys.stderr,
68
+ )
50
69
 
51
70
  is_resume = session_file.exists()
52
71
  cmd = build_cmd(target_date, briefing_file, session_file)
@@ -0,0 +1,200 @@
1
+ """Archive chat.sh conversations and analyze how they are used.
2
+
3
+ chat.sh only records a Claude session id per briefing date
4
+ (``output/briefing/.sessions/<date>``). The conversation itself lives in
5
+ Claude Code's transcript store, which prunes old transcripts (30 days by
6
+ default), so most of the history is gone before anyone looks at it. The
7
+ archive step copies each session's turns into ``output/chat_archive/`` while
8
+ the transcript still exists; the analysis step reads that archive back.
9
+
10
+ The archive never shrinks: a session whose transcript has already been pruned
11
+ keeps whatever was archived for it earlier.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import statistics
17
+ from collections import Counter
18
+ from dataclasses import dataclass, field
19
+ from datetime import date, datetime, timedelta
20
+ from pathlib import Path
21
+ from typing import Iterable
22
+
23
+ from src import paths
24
+
25
+ SESSIONS_DIR = paths.OUTPUT_DIR / "briefing" / ".sessions"
26
+ ARCHIVE_DIR = paths.OUTPUT_DIR / "chat_archive"
27
+ REPORT_DIR = paths.OUTPUT_DIR / "chat_insights"
28
+ TRANSCRIPTS_DIR = Path.home() / ".claude" / "projects"
29
+
30
+ WINDOW_DAYS = 28
31
+ SHORT_PROMPT_CHARS = 20
32
+
33
+ # Text the harness injects as a "user" turn: system reminders, loaded skill
34
+ # bodies, tool-load acknowledgements, and the briefing context chat.sh sends
35
+ # as the first message of a new session.
36
+ _INJECTED_PREFIXES = (
37
+ "<",
38
+ "Base directory for this skill",
39
+ "Tool loaded",
40
+ "[Request interrupted",
41
+ )
42
+
43
+
44
+ @dataclass
45
+ class ArchiveResult:
46
+ archived: list[str] = field(default_factory=list)
47
+ missing: list[str] = field(default_factory=list)
48
+
49
+
50
+ def _is_injected(text: str) -> bool:
51
+ if text.startswith(_INJECTED_PREFIXES):
52
+ return True
53
+ return text.startswith("以下は") and "ブリーフィング" in text[:60]
54
+
55
+
56
+ def _text_of(content) -> str | None:
57
+ """Return the plain text of a message, or None for a tool-only message."""
58
+ if isinstance(content, str):
59
+ return content
60
+ if not isinstance(content, list):
61
+ return None
62
+ texts = [c.get("text", "") for c in content if isinstance(c, dict) and c.get("type") == "text"]
63
+ return "\n".join(texts) if texts else None
64
+
65
+
66
+ def _tool_names(content) -> list[str]:
67
+ if not isinstance(content, list):
68
+ return []
69
+ names = []
70
+ for c in content:
71
+ if isinstance(c, dict) and c.get("type") == "tool_use":
72
+ name = c.get("name", "")
73
+ if name == "Skill":
74
+ name = f"Skill:{c.get('input', {}).get('skill', '')}"
75
+ elif name.startswith("mcp__"):
76
+ # mcp__<server>__<tool> → <tool>; the server prefix is noise here.
77
+ name = name.rsplit("__", 1)[-1]
78
+ names.append(name)
79
+ return names
80
+
81
+
82
+ def extract_turns(transcript: Path, session_date: str) -> list[dict]:
83
+ """Read one Claude Code transcript and return its human-readable turns.
84
+
85
+ User turns keep only what the person typed. Assistant turns keep their text
86
+ and the names of the tools they called, which is enough to see what kind of
87
+ work a request turned into without archiving tool payloads.
88
+ """
89
+ turns: list[dict] = []
90
+ for line in transcript.read_text(encoding="utf-8").splitlines():
91
+ try:
92
+ ev = json.loads(line)
93
+ except json.JSONDecodeError:
94
+ continue
95
+ role = ev.get("type")
96
+ if role not in ("user", "assistant") or ev.get("isMeta"):
97
+ continue
98
+ content = ev.get("message", {}).get("content")
99
+ text = (_text_of(content) or "").strip()
100
+ tools = _tool_names(content) if role == "assistant" else []
101
+ if role == "user" and (not text or _is_injected(text)):
102
+ continue
103
+ if role == "assistant" and not text and not tools:
104
+ continue
105
+ turns.append(
106
+ {"date": session_date, "ts": ev.get("timestamp"), "role": role, "text": text, "tools": tools}
107
+ )
108
+ return turns
109
+
110
+
111
+ def _find_transcript(session_id: str, transcripts_dir: Path) -> Path | None:
112
+ hits = sorted(transcripts_dir.glob(f"*/{session_id}.jsonl"))
113
+ return hits[0] if hits else None
114
+
115
+
116
+ def archive_sessions(
117
+ sessions_dir: Path = SESSIONS_DIR,
118
+ transcripts_dir: Path = TRANSCRIPTS_DIR,
119
+ archive_dir: Path = ARCHIVE_DIR,
120
+ ) -> ArchiveResult:
121
+ """Copy every chat.sh session whose transcript still exists into the archive."""
122
+ result = ArchiveResult()
123
+ if not sessions_dir.is_dir():
124
+ return result
125
+ archive_dir.mkdir(parents=True, exist_ok=True)
126
+ for session_file in sorted(p for p in sessions_dir.iterdir() if p.is_file()):
127
+ session_date = session_file.name
128
+ transcript = _find_transcript(session_file.read_text().strip(), transcripts_dir)
129
+ if transcript is None:
130
+ result.missing.append(session_date)
131
+ continue
132
+ turns = extract_turns(transcript, session_date)
133
+ if not turns:
134
+ continue
135
+ 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
+ result.archived.append(session_date)
138
+ return result
139
+
140
+
141
+ def load_archive(archive_dir: Path, since: date) -> list[dict]:
142
+ """Return archived turns from sessions dated on or after ``since``."""
143
+ turns: list[dict] = []
144
+ if not archive_dir.is_dir():
145
+ return turns
146
+ for f in sorted(archive_dir.glob("*.jsonl")):
147
+ try:
148
+ if date.fromisoformat(f.stem) < since:
149
+ continue
150
+ except ValueError:
151
+ continue
152
+ turns.extend(json.loads(line) for line in f.read_text(encoding="utf-8").splitlines() if line.strip())
153
+ return turns
154
+
155
+
156
+ def _local_hour(ts: str | None) -> int | None:
157
+ if not ts:
158
+ return None
159
+ try:
160
+ return datetime.fromisoformat(ts.replace("Z", "+00:00")).astimezone().hour
161
+ except ValueError:
162
+ return None
163
+
164
+
165
+ def compute_stats(turns: Iterable[dict]) -> dict:
166
+ """Deterministic usage numbers, computed here so the model never has to count."""
167
+ turns = list(turns)
168
+ user = [t for t in turns if t["role"] == "user"]
169
+ lengths = [len(t["text"]) for t in user]
170
+ hours = Counter(h for h in (_local_hour(t["ts"]) for t in user) if h is not None)
171
+ tools = Counter(name for t in turns for name in t.get("tools", []))
172
+ skills = Counter(n.split(":", 1)[1] for n in tools.elements() if n.startswith("Skill:"))
173
+ return {
174
+ "sessions": len({t["date"] for t in turns}),
175
+ "user_turns": len(user),
176
+ "median_prompt_chars": statistics.median(lengths) if lengths else 0,
177
+ "short_prompts": sum(n <= SHORT_PROMPT_CHARS for n in lengths),
178
+ "hours": dict(sorted(hours.items())),
179
+ "top_tools": dict(Counter({k: v for k, v in tools.items() if not k.startswith("Skill:")}).most_common(10)),
180
+ "skills": dict(skills.most_common()),
181
+ }
182
+
183
+
184
+ def build_prompt(turns: list[dict], stats: dict, missing: list[str]) -> str:
185
+ from src.generator.prompt import render
186
+ from src.prompt_safety import wrap_untrusted
187
+
188
+ user_lines = "\n".join(
189
+ f"[{t['date']}] {t['text'].replace(chr(10), ' ')[:300]}" for t in turns if t["role"] == "user"
190
+ )
191
+ return render(
192
+ "chat_insights",
193
+ stats=json.dumps(stats, ensure_ascii=False, indent=2),
194
+ missing=", ".join(missing) if missing else "なし",
195
+ turns=wrap_untrusted(user_lines, label="chat_user_turns"),
196
+ )
197
+
198
+
199
+ def window_start(today: date, days: int = WINDOW_DAYS) -> date:
200
+ return today - timedelta(days=days)
@@ -32,6 +32,10 @@ DEFAULT_TEMPERATURE = 0.2
32
32
  DEFAULT_TOP_K = 6
33
33
  DEFAULT_CHUNK_LINES = 40
34
34
  DEFAULT_CHUNK_OVERLAP = 8
35
+ # Upper bound on a chunk's text. Ollama runs embedding models with a 2048-token
36
+ # ubatch and the whole input must fit in it (num_ctx does not lift this), so a
37
+ # 40-line window of dense Japanese tables (~3,500+ chars) fails to embed (#553).
38
+ DEFAULT_CHUNK_MAX_CHARS = 2000
35
39
  DEFAULT_REPO_ROOT = Path.home() / "work" / "ai-agent"
36
40
  DEFAULT_CHROMA_REL = Path("apps/python/.chroma_db")
37
41
  COLLECTION_NAME = "ai_agent_repo"
@@ -67,6 +71,7 @@ class LocalLLMConfig:
67
71
  chroma_path: Path
68
72
  chunk_lines: int
69
73
  chunk_overlap: int
74
+ chunk_max_chars: int = DEFAULT_CHUNK_MAX_CHARS
70
75
  # Extra directory names excluded on top of EXCLUDE_DIRS. Lets a caller
71
76
  # (e.g. the Obsidian vault indexer) skip vault-internal folders without
72
77
  # changing the global exclusion set. Empty = existing behavior.
@@ -50,7 +50,55 @@ def iter_source_files(cfg: LocalLLMConfig) -> Iterator[Path]:
50
50
  yield path
51
51
 
52
52
 
53
+ def _make_chunk(rel: str, start: int, end: int, body: str) -> Chunk:
54
+ cid = hashlib.sha256(
55
+ f"{rel}:{start}-{end}:{body}".encode("utf-8")
56
+ ).hexdigest()
57
+ return Chunk(
58
+ chunk_id=cid,
59
+ source_path=rel,
60
+ start_line=start,
61
+ end_line=end,
62
+ text=body,
63
+ )
64
+
65
+
66
+ def _split_over_cap(
67
+ lines: list[str], first_line: int, max_chars: int
68
+ ) -> Iterator[tuple[int, int, str]]:
69
+ """Yield (start, end, body) pieces of ``lines``, each at most ``max_chars``.
70
+
71
+ Lines are packed greedily into contiguous, non-overlapping pieces; a
72
+ single line longer than the cap is cut into character slices that all
73
+ report that line as both start and end.
74
+ """
75
+ buf: list[str] = []
76
+ buf_start = first_line
77
+ buf_len = 0
78
+ for offset, line in enumerate(lines):
79
+ lineno = first_line + offset
80
+ if len(line) > max_chars:
81
+ if buf:
82
+ yield buf_start, lineno - 1, "\n".join(buf)
83
+ buf, buf_len = [], 0
84
+ for k in range(0, len(line), max_chars):
85
+ yield lineno, lineno, line[k:k + max_chars]
86
+ buf_start = lineno + 1
87
+ continue
88
+ added = len(line) + (1 if buf else 0)
89
+ if buf and buf_len + added > max_chars:
90
+ yield buf_start, lineno - 1, "\n".join(buf)
91
+ buf, buf_len, buf_start = [], 0, lineno
92
+ added = len(line)
93
+ buf.append(line)
94
+ buf_len += added
95
+ if buf:
96
+ yield buf_start, first_line + len(lines) - 1, "\n".join(buf)
97
+
98
+
53
99
  def chunk_file(path: Path, cfg: LocalLLMConfig) -> list[Chunk]:
100
+ if cfg.chunk_max_chars <= 0:
101
+ raise ValueError(f"chunk_max_chars must be positive, got {cfg.chunk_max_chars}")
54
102
  text = path.read_text(encoding="utf-8", errors="replace")
55
103
  lines = text.splitlines()
56
104
  if not lines:
@@ -59,21 +107,26 @@ def chunk_file(path: Path, cfg: LocalLLMConfig) -> list[Chunk]:
59
107
  rel = path.relative_to(cfg.repo_root).as_posix()
60
108
  step = cfg.chunk_lines - cfg.chunk_overlap
61
109
  out: list[Chunk] = []
110
+ seen: set[str] = set()
62
111
  i = 0
63
112
  while i < len(lines):
64
113
  start = i + 1
65
114
  end = min(i + cfg.chunk_lines, len(lines))
66
115
  body = "\n".join(lines[i:end])
67
- cid = hashlib.sha256(
68
- f"{rel}:{start}-{end}:{body}".encode("utf-8")
69
- ).hexdigest()
70
- out.append(Chunk(
71
- chunk_id=cid,
72
- source_path=rel,
73
- start_line=start,
74
- end_line=end,
75
- text=body,
76
- ))
116
+ if len(body) <= cfg.chunk_max_chars:
117
+ # Same text and ID as before the cap existed, so already-indexed
118
+ # chunks are not re-embedded.
119
+ pieces = [(start, end, body)]
120
+ else:
121
+ pieces = list(_split_over_cap(lines[i:end], start, cfg.chunk_max_chars))
122
+ for s, e, b in pieces:
123
+ c = _make_chunk(rel, s, e, b)
124
+ # Overlapping windows can re-split into identical pieces; a batch
125
+ # upsert with duplicate IDs is rejected by Chroma.
126
+ if c.chunk_id in seen:
127
+ continue
128
+ seen.add(c.chunk_id)
129
+ out.append(c)
77
130
  if end >= len(lines):
78
131
  break
79
132
  i += step
@@ -0,0 +1,83 @@
1
+ """chat.sh conversation archive and usage analysis, declared as workflows.
2
+
3
+ ``chat-archive`` is free and runs inside ``daily``: it has to run while Claude
4
+ Code still holds the transcripts, which it prunes after 30 days by default.
5
+ ``chat-insights`` adds the paid analysis and is run by hand (or weekly).
6
+
7
+ ``src.chat_insights`` is imported at call time, like the other definitions
8
+ bind their handlers, so registry discovery stays cheap and tests can point the
9
+ module's directories at a fixture tree.
10
+ """
11
+ from datetime import date
12
+ from typing import Any
13
+
14
+ from src.workflow.model import Step, StepContext, Workflow
15
+
16
+ ANALYZE_TIMEOUT_SEC = 600
17
+
18
+
19
+ def archive(ctx: StepContext) -> dict[str, Any]:
20
+ from src import chat_insights
21
+
22
+ result = chat_insights.archive_sessions(
23
+ chat_insights.SESSIONS_DIR, chat_insights.TRANSCRIPTS_DIR, chat_insights.ARCHIVE_DIR
24
+ )
25
+ ctx.logger.info(
26
+ "chat archive: %d session(s) archived, %d already pruned by Claude Code",
27
+ len(result.archived),
28
+ len(result.missing),
29
+ )
30
+ return {"archived": result.archived, "missing": result.missing}
31
+
32
+
33
+ def collect(ctx: StepContext) -> dict[str, Any]:
34
+ from src import chat_insights
35
+
36
+ turns = chat_insights.load_archive(
37
+ chat_insights.ARCHIVE_DIR, chat_insights.window_start(date.today())
38
+ )
39
+ return {"turns": turns, "stats": chat_insights.compute_stats(turns)}
40
+
41
+
42
+ def skip_without_turns(ctx: StepContext) -> bool:
43
+ return not ctx.results["collect"]["stats"]["user_turns"]
44
+
45
+
46
+ def analyze(ctx: StepContext) -> str:
47
+ from src import chat_insights
48
+ from src.claude_runner import run_claude
49
+
50
+ collected = ctx.results["collect"]
51
+ prompt = chat_insights.build_prompt(
52
+ collected["turns"], collected["stats"], ctx.results["archive"]["missing"]
53
+ )
54
+ return run_claude(prompt, label="チャット傾向分析", timeout=ANALYZE_TIMEOUT_SEC)
55
+
56
+
57
+ def persist(ctx: StepContext) -> str:
58
+ from src import chat_insights
59
+
60
+ today = date.today().isoformat()
61
+ chat_insights.REPORT_DIR.mkdir(parents=True, exist_ok=True)
62
+ out = chat_insights.REPORT_DIR / f"chat-insights_{today}.md"
63
+ out.write_text(f"# チャット傾向レポート ({today})\n\n{ctx.results['analyze']}\n", encoding="utf-8")
64
+ ctx.logger.info("chat insights written: %s", out)
65
+ return str(out)
66
+
67
+
68
+ CHAT_ARCHIVE = Workflow(
69
+ id="chat-archive",
70
+ title="Archive chat.sh conversations before Claude Code prunes them",
71
+ steps=(Step("archive", archive),),
72
+ )
73
+
74
+ CHAT_INSIGHTS = Workflow(
75
+ id="chat-insights",
76
+ title="Analyze recent chat.sh usage into a trend report",
77
+ steps=(
78
+ Step("archive", archive),
79
+ Step("collect", collect),
80
+ Step("analyze", analyze, skip_if=skip_without_turns),
81
+ Step("persist", persist, skip_if=skip_without_turns),
82
+ ),
83
+ )
@@ -49,7 +49,7 @@ def _child(workflow_id: str) -> Callable[[StepContext], Any]:
49
49
 
50
50
  DAILY = Workflow(
51
51
  id="daily",
52
- title="Daily briefing, the weekly recap on its day, then the model-rate check",
52
+ title="Daily briefing, the weekly recap on its day, the chat archive, then the model-rate check",
53
53
  steps=(
54
54
  Step("preflight", _preflight, preamble=True),
55
55
  # Not ``best_effort``: bin/run.sh ran under ``set -e``, so a failed
@@ -57,6 +57,9 @@ DAILY = Workflow(
57
57
  # that produced nothing to recap does not go on to recap it.
58
58
  Step("briefing", _child("briefing")),
59
59
  Step("weekly", _child("weekly")),
60
+ # best_effort: copying chat transcripts must never cost the morning its
61
+ # model-rate check. It runs daily because Claude Code prunes them.
62
+ Step("chat-archive", _child("chat-archive"), best_effort=True),
60
63
  # Last on purpose (#475): an unpriced model fails the run so it is
61
64
  # noticed the next morning, but only after both deliveries went out.
62
65
  Step("model-rates", _child("model-rates")),
@@ -136,6 +136,10 @@ def _validate_image_path(image_path: str | None) -> Path | None:
136
136
  # stream-json output already in CHAT_STREAM_FLAGS.
137
137
  IMAGE_INPUT_FLAGS = ["--input-format", "stream-json"]
138
138
 
139
+ # Images one message may carry. Each upload is capped at 5 MB, so this also
140
+ # bounds the base64 payload piped into the CLI.
141
+ MAX_IMAGES_PER_MESSAGE = 5
142
+
139
143
  _IMAGE_MEDIA_TYPES = {
140
144
  "jpg": "image/jpeg",
141
145
  "jpeg": "image/jpeg",
@@ -145,25 +149,36 @@ _IMAGE_MEDIA_TYPES = {
145
149
  }
146
150
 
147
151
 
148
- def _build_image_message(img_path: Path, question: str) -> str:
149
- """Build a stream-json input envelope carrying a base64 image + the question.
152
+ def _resolve_image_paths(image_paths: list[str], image_path: str | None) -> list[Path]:
153
+ """Validate every attached image. ``image_path`` is the single-image field
154
+ older clients still send; it is appended after ``image_paths``."""
155
+ raw = [*image_paths, *([image_path] if image_path else [])]
156
+ if len(raw) > MAX_IMAGES_PER_MESSAGE:
157
+ raise HTTPException(
158
+ status_code=400,
159
+ detail=f"At most {MAX_IMAGES_PER_MESSAGE} images per message",
160
+ )
161
+ return [path for path in map(_validate_image_path, raw) if path is not None]
162
+
163
+
164
+ def _build_image_message(img_paths: list[Path], question: str) -> str:
165
+ """Build a stream-json input envelope carrying base64 images + the question.
150
166
 
151
167
  The claude CLI's stream-json input expects newline-delimited
152
168
  ``{"type":"user","message":{...}}`` objects whose ``content`` uses the
153
- Messages API block format. The trailing newline terminates the record.
169
+ Messages API block format. One image block per attachment, in order, then
170
+ the question. The trailing newline terminates the record.
154
171
  """
155
- b64 = base64.b64encode(img_path.read_bytes()).decode()
156
- ext = img_path.suffix.lstrip(".").lower()
157
- media = _IMAGE_MEDIA_TYPES.get(ext, "image/png")
172
+ blocks: list[dict] = []
173
+ for img_path in img_paths:
174
+ b64 = base64.b64encode(img_path.read_bytes()).decode()
175
+ ext = img_path.suffix.lstrip(".").lower()
176
+ media = _IMAGE_MEDIA_TYPES.get(ext, "image/png")
177
+ blocks.append({"type": "image", "source": {"type": "base64", "media_type": media, "data": b64}})
178
+ blocks.append({"type": "text", "text": question})
158
179
  return json.dumps({
159
180
  "type": "user",
160
- "message": {
161
- "role": "user",
162
- "content": [
163
- {"type": "image", "source": {"type": "base64", "media_type": media, "data": b64}},
164
- {"type": "text", "text": question},
165
- ],
166
- },
181
+ "message": {"role": "user", "content": blocks},
167
182
  }) + "\n"
168
183
 
169
184
 
@@ -173,6 +188,7 @@ class ChatBody(BaseModel):
173
188
  date: str = Field(pattern=r"^\d{4}-\d{2}-\d{2}$")
174
189
  question: str = Field(min_length=1)
175
190
  image_path: str | None = None
191
+ image_paths: list[str] = Field(default_factory=list, max_length=MAX_IMAGES_PER_MESSAGE)
176
192
  # Opt-in cross-date RAG (#395): searches past briefings via the
177
193
  # local-LLM chromadb index and injects matches into the new session's
178
194
  # system prompt alongside today's briefing. Off by default so existing
@@ -386,10 +402,10 @@ def post_chat(body: ChatBody, background_tasks: BackgroundTasks) -> ChatPostResp
386
402
  )
387
403
 
388
404
  SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
389
- img_path = _validate_image_path(body.image_path)
405
+ img_paths = _resolve_image_paths(body.image_paths, body.image_path)
390
406
  image_message: str | None = None
391
- if img_path:
392
- image_message = _build_image_message(img_path, body.question)
407
+ if img_paths:
408
+ image_message = _build_image_message(img_paths, body.question)
393
409
  cmd = [*build_cmd(body.date, briefing_file, session_file, history_context, vault_context), "-p", *IMAGE_INPUT_FLAGS, *CHAT_STREAM_FLAGS]
394
410
  else:
395
411
  cmd = [*build_cmd(body.date, briefing_file, session_file, history_context, vault_context), "-p", body.question, *CHAT_STREAM_FLAGS]
@@ -412,6 +428,7 @@ class JournalChatBody(BaseModel):
412
428
  # How many most-recent journal days to load as brainstorm context.
413
429
  days: int = Field(default=7, ge=1, le=31)
414
430
  image_path: str | None = None
431
+ image_paths: list[str] = Field(default_factory=list, max_length=MAX_IMAGES_PER_MESSAGE)
415
432
 
416
433
 
417
434
  def _gather_journal_context(days: int, max_chars: int | None = None) -> str:
@@ -468,10 +485,10 @@ def post_journal_chat(
468
485
  session_file = sessions_dir / today
469
486
 
470
487
  trusted_write_dirs = config.get_journal_chat_trusted_write_dirs()
471
- img_path = _validate_image_path(body.image_path)
488
+ img_paths = _resolve_image_paths(body.image_paths, body.image_path)
472
489
  image_message: str | None = None
473
- if img_path:
474
- image_message = _build_image_message(img_path, body.question)
490
+ if img_paths:
491
+ image_message = _build_image_message(img_paths, body.question)
475
492
  cmd = [*build_journal_cmd(today, context, session_file, trusted_write_dirs), "-p", *IMAGE_INPUT_FLAGS, *CHAT_STREAM_FLAGS]
476
493
  else:
477
494
  cmd = [*build_journal_cmd(today, context, session_file, trusted_write_dirs), "-p", body.question, *CHAT_STREAM_FLAGS]
@@ -30,6 +30,10 @@ def _config_path() -> Path:
30
30
  )
31
31
 
32
32
 
33
+ def _template_path() -> Path:
34
+ return paths.CONFIG_DIR / "briefing.json.example"
35
+
36
+
33
37
  @router.get("/config", response_model=BriefingConfigSchema)
34
38
  def get_config() -> BriefingConfigSchema:
35
39
  path = _config_path()
@@ -62,3 +66,27 @@ def put_config(payload: BriefingConfigSchema) -> dict:
62
66
  Path(tmp_path).unlink(missing_ok=True)
63
67
  raise
64
68
  return data
69
+
70
+
71
+ @router.post("/config/seed")
72
+ def seed_config() -> dict:
73
+ """Create briefing.json from the bundled template when it is missing.
74
+
75
+ The onboarding wizard calls this when the user skips setup, so a source
76
+ checkout (where nothing has created the file yet) still opens on usable
77
+ defaults. An existing file is never touched.
78
+ """
79
+ path = _config_path()
80
+ if path.exists():
81
+ return {"created": False}
82
+ template = _template_path()
83
+ if not template.is_file():
84
+ raise HTTPException(status_code=500, detail="briefing.json template not found")
85
+ path.parent.mkdir(parents=True, exist_ok=True)
86
+ try:
87
+ # "x" fails if another request created the file in the meantime.
88
+ with path.open("x", encoding="utf-8") as f:
89
+ f.write(template.read_text(encoding="utf-8"))
90
+ except FileExistsError:
91
+ return {"created": False}
92
+ return {"created": True}
@@ -1 +1 @@
1
- VdoUHqMuKEB2yUBQvac5b
1
+ HRelvfbIJ8aRo0S_dK4jo