donelog 0.1.0__py3-none-any.whl

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.

Potentially problematic release.


This version of donelog might be problematic. Click here for more details.

donelog/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """donelog: record what your AI coding agent did as tasks, and search them later."""
2
+
3
+ # Written here instead of read with importlib.metadata: that lookup took about
4
+ # 0.2 s on every command. tests/test_version.py checks it matches pyproject.toml.
5
+ __version__ = "0.1.0"
donelog/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow running donelog with `python -m donelog`."""
2
+
3
+ from donelog.cli import run
4
+
5
+ run()
donelog/ask.py ADDED
@@ -0,0 +1,260 @@
1
+ """AI search: answer a plain-language question from the task log.
2
+
3
+ Flow:
4
+ 1. Narrow the tasks down to at most MAX_CANDIDATES by keyword overlap and
5
+ newness, so the prompt stays small even with thousands of tasks.
6
+ 2. Send those tasks and the question to an AI backend, asking for JSON that
7
+ matches ANSWER_SCHEMA.
8
+ 3. Check the answer: keep only task IDs that were really given to the AI,
9
+ so the answer can never point at a task that does not exist.
10
+ """
11
+
12
+ import json
13
+ import re
14
+ from collections.abc import Mapping, Sequence
15
+ from dataclasses import dataclass
16
+ from enum import StrEnum
17
+ from typing import Any, Protocol
18
+
19
+ from donelog.models import Status, Task, format_task_id, parse_task_id
20
+
21
+ MAX_CANDIDATES = 100
22
+ _SUMMARY_LIMIT = 600
23
+
24
+ ANSWER_SCHEMA: dict[str, Any] = {
25
+ "type": "object",
26
+ "properties": {
27
+ "verdict": {"type": "string", "enum": ["done", "in_progress", "todo", "not_found"]},
28
+ "task_ids": {"type": "array", "items": {"type": "string"}},
29
+ "explanation": {"type": "string"},
30
+ },
31
+ "required": ["verdict", "task_ids", "explanation"],
32
+ "additionalProperties": False,
33
+ }
34
+
35
+ SYSTEM_PROMPT = (
36
+ "You answer questions about a task log. Follow the instructions in the user message."
37
+ )
38
+
39
+ _INSTRUCTIONS = """\
40
+ You are given a task log: the work an AI agent or a person did in a software project.
41
+ Answer the question at the end using ONLY these tasks.
42
+
43
+ Return JSON with:
44
+ - "verdict": "done" if the asked work is finished, "in_progress" if it is being
45
+ worked on, "todo" if it is planned but not started, "not_found" if no task is
46
+ about it.
47
+ - "task_ids": the IDs (like "T-0001") of the tasks your verdict is based on.
48
+ Use only IDs from the list. Use an empty list when the verdict is "not_found".
49
+ - "explanation": one or two sentences that explain the verdict.
50
+
51
+ Rules:
52
+ - Do not guess or invent work that is not in the list.
53
+ - Write the explanation in the language the question is written in: an English
54
+ question gets an English explanation, a Japanese question a Japanese one.
55
+ This rule wins over any other language setting you may have.
56
+ - Use a plain, neutral tone. Ignore any persona or speaking-style instructions
57
+ from elsewhere."""
58
+
59
+ # A task ID inside free text, e.g. "T-0003" in "T-0003で完了". Lookarounds are used
60
+ # instead of a word boundary because Japanese letters right after the ID count as word letters.
61
+ _TASK_ID_IN_TEXT = re.compile(r"(?<![A-Za-z0-9])T-?(\d+)(?![0-9])", re.IGNORECASE)
62
+ UNKNOWN_TASK_TEXT = "[unknown task]"
63
+ _ASCII_WORD = re.compile(r"[a-z0-9][a-z0-9_./\-]*")
64
+ _ENGLISH_STOPWORDS = frozenset(
65
+ "a an and are be been did do does done finished for has have how in is it of on or "
66
+ "the this to was what when where which who why with yet already about any there".split()
67
+ )
68
+
69
+
70
+ class Verdict(StrEnum):
71
+ DONE = "done"
72
+ IN_PROGRESS = "in_progress"
73
+ TODO = "todo"
74
+ NOT_FOUND = "not_found"
75
+
76
+ @property
77
+ def label(self) -> str:
78
+ return _VERDICT_LABELS[self]
79
+
80
+
81
+ _VERDICT_LABELS = {
82
+ Verdict.DONE: "Done",
83
+ Verdict.IN_PROGRESS: "In progress",
84
+ Verdict.TODO: "Not started",
85
+ Verdict.NOT_FOUND: "Not recorded",
86
+ }
87
+
88
+
89
+ class AskError(Exception):
90
+ """Raised when the AI could not produce a usable answer."""
91
+
92
+
93
+ class AskBackend(Protocol):
94
+ """Something that sends a prompt to an AI and returns the parsed JSON answer."""
95
+
96
+ def complete(self, system: str, prompt: str, schema: Mapping[str, Any]) -> Mapping[str, Any]:
97
+ """Return the JSON object the AI produced. Raise AskError on failure."""
98
+ ...
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class Answer:
103
+ verdict: Verdict
104
+ tasks: tuple[Task, ...]
105
+ explanation: str
106
+ dropped_ids: tuple[str, ...] = ()
107
+
108
+
109
+ # --- step 1: narrow down ----------------------------------------------------
110
+
111
+
112
+ def _is_hiragana(char: str) -> bool:
113
+ return "\u3040" <= char <= "\u309f"
114
+
115
+
116
+ def extract_terms(question: str) -> frozenset[str]:
117
+ """Pick search terms from a question.
118
+
119
+ English words of two or more letters (minus common words) are used as they
120
+ are. Japanese text has no spaces, so it is cut into overlapping pairs of
121
+ characters ("ログイン機能" -> ログ, グイ, イン, ン機, 機能). Pairs with hiragana are
122
+ skipped, because they are mostly particles and verb endings (って, った).
123
+ """
124
+ text = question.lower()
125
+ terms = {
126
+ word
127
+ for word in _ASCII_WORD.findall(text)
128
+ if len(word) >= 2 and word not in _ENGLISH_STOPWORDS
129
+ }
130
+ for run in re.findall(r"[^\x00-\x7f]+", text):
131
+ letters = [char if char.isalnum() else " " for char in run]
132
+ for chunk in "".join(letters).split():
133
+ for start in range(len(chunk) - 1):
134
+ pair = chunk[start : start + 2]
135
+ if not any(_is_hiragana(char) for char in pair):
136
+ terms.add(pair)
137
+ return frozenset(terms)
138
+
139
+
140
+ def _haystack(task: Task) -> str:
141
+ return " ".join([task.title, task.summary, *task.files, *task.tags]).lower()
142
+
143
+
144
+ def select_candidates(
145
+ tasks: Sequence[Task], question: str, limit: int = MAX_CANDIDATES
146
+ ) -> list[Task]:
147
+ """Return at most `limit` tasks: the best keyword matches, newest first among equals.
148
+
149
+ `tasks` must already be sorted newest first.
150
+ """
151
+ if len(tasks) <= limit:
152
+ return list(tasks)
153
+ terms = extract_terms(question)
154
+ if not terms:
155
+ return list(tasks[:limit])
156
+
157
+ def score(task: Task) -> int:
158
+ haystack = _haystack(task)
159
+ return sum(1 for term in terms if term in haystack)
160
+
161
+ # sorted() is stable, so tasks with the same score stay newest first.
162
+ return sorted(tasks, key=score, reverse=True)[:limit]
163
+
164
+
165
+ # --- step 2: prompt ---------------------------------------------------------
166
+
167
+
168
+ def _task_for_prompt(task: Task) -> dict[str, object]:
169
+ summary = task.summary
170
+ if len(summary) > _SUMMARY_LIMIT:
171
+ summary = summary[:_SUMMARY_LIMIT] + "…"
172
+ return {
173
+ "id": task.display_id,
174
+ "title": task.title,
175
+ "status": task.status.value,
176
+ "summary": summary,
177
+ "files": list(task.files),
178
+ "tags": list(task.tags),
179
+ "updated_at": task.updated_at,
180
+ }
181
+
182
+
183
+ def build_prompt(question: str, candidates: Sequence[Task], total: int) -> str:
184
+ lines = [_INSTRUCTIONS, ""]
185
+ if total > len(candidates):
186
+ lines.append(
187
+ f"Task log: the {len(candidates)} tasks most related to the question "
188
+ f"(out of {total}), newest first:"
189
+ )
190
+ else:
191
+ lines.append(f"Task log ({len(candidates)} tasks, newest first):")
192
+ lines.extend(json.dumps(_task_for_prompt(task), ensure_ascii=False) for task in candidates)
193
+ lines.extend(["", f"Question: {question.strip()}"])
194
+ return "\n".join(lines)
195
+
196
+
197
+ # --- step 3: check the answer -----------------------------------------------
198
+
199
+
200
+ def _replace_unknown_ids(text: str, known_ids: set[int]) -> str:
201
+ """Replace task IDs in `text` that are not in the task log with "[unknown task]"."""
202
+
203
+ def replace(match: re.Match[str]) -> str:
204
+ task_id = int(match.group(1))
205
+ return format_task_id(task_id) if task_id in known_ids else UNKNOWN_TASK_TEXT
206
+
207
+ return _TASK_ID_IN_TEXT.sub(replace, text)
208
+
209
+
210
+ def build_answer(raw: Mapping[str, Any], candidates: Sequence[Task]) -> Answer:
211
+ """Turn the AI's JSON into an Answer, removing task IDs that were not given."""
212
+ try:
213
+ verdict = Verdict(str(raw.get("verdict")))
214
+ except ValueError as error:
215
+ raise AskError(f"The AI returned an unknown verdict: {raw.get('verdict')!r}") from error
216
+
217
+ raw_ids = raw.get("task_ids") or []
218
+ if not isinstance(raw_ids, list):
219
+ raise AskError("The AI returned task_ids in an unexpected format.")
220
+ known = {task.id: task for task in candidates}
221
+ kept: list[Task] = []
222
+ dropped: list[str] = []
223
+ for raw_id in raw_ids:
224
+ try:
225
+ task = known.get(parse_task_id(str(raw_id)))
226
+ except ValueError:
227
+ task = None
228
+ if task is None:
229
+ dropped.append(str(raw_id))
230
+ elif task not in kept:
231
+ kept.append(task)
232
+
233
+ explanation = _replace_unknown_ids(str(raw.get("explanation") or "").strip(), set(known))
234
+ if verdict is not Verdict.NOT_FOUND and not kept:
235
+ # A verdict with no real evidence is not trustworthy (F-22).
236
+ verdict = Verdict.NOT_FOUND
237
+ explanation = "No task in the task log supports an answer to this question."
238
+ elif verdict is Verdict.DONE and not any(task.status is Status.DONE for task in kept):
239
+ # "Done" needs at least one finished task as evidence.
240
+ has_open = any(task.status is Status.IN_PROGRESS for task in kept)
241
+ verdict = Verdict.IN_PROGRESS if has_open else Verdict.TODO
242
+ explanation = "None of the related tasks is marked done yet."
243
+ if verdict is Verdict.NOT_FOUND:
244
+ kept = []
245
+ return Answer(verdict, tuple(kept), explanation, tuple(dropped))
246
+
247
+
248
+ # --- all steps ----------------------------------------------------------------
249
+
250
+
251
+ def ask(question: str, tasks: Sequence[Task], backend: AskBackend) -> Answer:
252
+ """Answer `question` from `tasks` (newest first) using `backend`."""
253
+ if not question.strip():
254
+ raise AskError("Please write a question.")
255
+ if not tasks:
256
+ return Answer(Verdict.NOT_FOUND, (), "The task log has no tasks yet.")
257
+ candidates = select_candidates(tasks, question)
258
+ prompt = build_prompt(question, candidates, total=len(tasks))
259
+ raw = backend.complete(SYSTEM_PROMPT, prompt, ANSWER_SCHEMA)
260
+ return build_answer(raw, candidates)
donelog/backends.py ADDED
@@ -0,0 +1,266 @@
1
+ """AI backends for `donelog ask`.
2
+
3
+ - ClaudeCodeBackend runs the installed Claude Code in non-interactive mode
4
+ (`claude -p`). It removes ANTHROPIC_API_KEY (and other variables that switch
5
+ billing) from the child process, so Claude Code always uses the user's
6
+ Pro/Max plan instead of pay-per-use API billing.
7
+ - AnthropicApiBackend calls the Anthropic API with the key in
8
+ DONELOG_ANTHROPIC_API_KEY. It needs the optional `anthropic` package.
9
+
10
+ Neither backend reads or creates .env files.
11
+ """
12
+
13
+ import json
14
+ import os
15
+ import subprocess
16
+ import tempfile
17
+ from collections.abc import Callable, Mapping
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from donelog.ask import AskBackend, AskError
22
+ from donelog.config import Backend, Config
23
+ from donelog.process import (
24
+ check_batch_arguments,
25
+ find_executable,
26
+ is_batch_file,
27
+ run_with_timeout,
28
+ )
29
+
30
+ API_KEY_ENV = "DONELOG_ANTHROPIC_API_KEY"
31
+ DEFAULT_API_MODEL = "claude-opus-5-5"
32
+ DEFAULT_TIMEOUT_SECONDS = 120
33
+
34
+ # Removed from the environment of the Claude Code that donelog starts:
35
+ # - variables that would make Claude Code bill an API key or a cloud provider
36
+ # instead of the Pro/Max plan,
37
+ # - donelog's own API key, which Claude Code does not need,
38
+ # - variables that mark "running inside another Claude Code session".
39
+ _REMOVED_CHILD_ENV = (
40
+ "ANTHROPIC_API_KEY",
41
+ "ANTHROPIC_AUTH_TOKEN",
42
+ "CLAUDE_CODE_USE_BEDROCK",
43
+ "CLAUDE_CODE_USE_VERTEX",
44
+ "CLAUDE_CODE_USE_FOUNDRY",
45
+ API_KEY_ENV,
46
+ "CLAUDECODE",
47
+ "CLAUDE_CODE_ENTRYPOINT",
48
+ )
49
+
50
+ Runner = Callable[..., subprocess.CompletedProcess[str]]
51
+
52
+
53
+ def _tail(text: str, limit: int = 500) -> str:
54
+ text = text.strip()
55
+ return text if len(text) <= limit else "…" + text[-limit:]
56
+
57
+
58
+ class ClaudeCodeBackend:
59
+ """Answer with `claude -p` (uses the Claude plan, no API key)."""
60
+
61
+ def __init__(
62
+ self,
63
+ model: str | None = None,
64
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
65
+ executable: str | None = None,
66
+ runner: Runner = run_with_timeout,
67
+ ) -> None:
68
+ self._model = model
69
+ self._timeout = timeout
70
+ self._executable = executable
71
+ self._runner = runner
72
+
73
+ def build_command(self, executable: str, system: str, schema: Mapping[str, Any]) -> list[str]:
74
+ # Everything that varies (tasks, question, instructions) goes through
75
+ # stdin. On Windows `claude` is often a .cmd file, and cmd.exe would
76
+ # mangle arguments that contain characters such as & | % ^ or newlines.
77
+ command = [
78
+ executable,
79
+ "-p",
80
+ "--output-format",
81
+ "json",
82
+ "--json-schema",
83
+ json.dumps(schema, separators=(",", ":")),
84
+ "--tools",
85
+ "",
86
+ "--strict-mcp-config",
87
+ "--no-session-persistence",
88
+ "--system-prompt",
89
+ system,
90
+ "--settings",
91
+ json.dumps({"disableAllHooks": True}, separators=(",", ":")),
92
+ # Only the user's own settings: a project's .claude/settings.json
93
+ # could change the API endpoint or environment of this request.
94
+ "--setting-sources",
95
+ "user",
96
+ ]
97
+ if self._model:
98
+ command += ["--model", self._model]
99
+ if is_batch_file(executable):
100
+ check_batch_arguments(command[1:])
101
+ return command
102
+
103
+ @staticmethod
104
+ def child_environment() -> dict[str, str]:
105
+ env = dict(os.environ)
106
+ for name in _REMOVED_CHILD_ENV:
107
+ env.pop(name, None)
108
+ return env
109
+
110
+ def complete(self, system: str, prompt: str, schema: Mapping[str, Any]) -> Mapping[str, Any]:
111
+ executable = self._executable or find_executable("claude")
112
+ if executable is None:
113
+ raise AskError(
114
+ "Claude Code (the `claude` command) was not found. Install Claude Code, "
115
+ 'or set "ask_backend" to "anthropic-api" in .donelog/config.json.'
116
+ )
117
+ try:
118
+ command = self.build_command(executable, system, schema)
119
+ except ValueError as error:
120
+ raise AskError(f"Refusing to run Claude Code: {error}") from error
121
+ try:
122
+ # An empty folder, so no project CLAUDE.md or settings are picked up.
123
+ with tempfile.TemporaryDirectory(prefix="donelog-ask-") as workdir:
124
+ completed = self._runner(
125
+ command,
126
+ input=prompt,
127
+ timeout=self._timeout,
128
+ env=self.child_environment(),
129
+ cwd=Path(workdir),
130
+ )
131
+ except subprocess.TimeoutExpired as error:
132
+ raise AskError(
133
+ f"Claude Code did not answer within {self._timeout:.0f} seconds."
134
+ ) from error
135
+ except OSError as error:
136
+ raise AskError(f"Could not start Claude Code: {error}") from error
137
+
138
+ if completed.returncode != 0:
139
+ detail = _tail(completed.stderr or completed.stdout or "")
140
+ raise AskError(
141
+ f"Claude Code exited with code {completed.returncode}. "
142
+ "If you are not logged in, run `claude` once and log in."
143
+ + (f"\n{detail}" if detail else "")
144
+ )
145
+ return self._parse_output(completed.stdout)
146
+
147
+ @staticmethod
148
+ def _parse_output(stdout: str) -> Mapping[str, Any]:
149
+ try:
150
+ envelope = json.loads(stdout)
151
+ except ValueError as error:
152
+ message = f"Claude Code returned output that is not JSON: {_tail(stdout)}"
153
+ raise AskError(message) from error
154
+ if not isinstance(envelope, dict):
155
+ raise AskError("Claude Code returned an unexpected result.")
156
+ if envelope.get("is_error"):
157
+ raise AskError(f"Claude Code reported an error: {_tail(str(envelope.get('result')))}")
158
+
159
+ structured = envelope.get("structured_output")
160
+ if isinstance(structured, dict):
161
+ return structured
162
+ try:
163
+ parsed = json.loads(str(envelope.get("result", "")))
164
+ except ValueError as error:
165
+ raise AskError("Claude Code did not return the answer as JSON.") from error
166
+ if not isinstance(parsed, dict):
167
+ raise AskError("Claude Code did not return the answer as a JSON object.")
168
+ return parsed
169
+
170
+
171
+ class AnthropicApiBackend:
172
+ """Answer with the Anthropic API (pay per use, key from DONELOG_ANTHROPIC_API_KEY)."""
173
+
174
+ def __init__(
175
+ self,
176
+ model: str | None = None,
177
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
178
+ client_factory: Callable[[str, float], Any] | None = None,
179
+ ) -> None:
180
+ self._model = model or DEFAULT_API_MODEL
181
+ self._timeout = timeout
182
+ self._client_factory = client_factory
183
+
184
+ def _make_client(self, api_key: str) -> Any:
185
+ if self._client_factory is not None:
186
+ return self._client_factory(api_key, self._timeout)
187
+ try:
188
+ import anthropic
189
+ except ImportError as error:
190
+ raise AskError(
191
+ "The anthropic-api backend needs the optional `anthropic` package. "
192
+ 'Reinstall donelog with it, for example: uv tool install --reinstall ".[api]"'
193
+ ) from error
194
+ # Pass the key explicitly so the SDK never falls back to ANTHROPIC_API_KEY.
195
+ return anthropic.Anthropic(api_key=api_key, timeout=self._timeout, max_retries=2)
196
+
197
+ def complete(self, system: str, prompt: str, schema: Mapping[str, Any]) -> Mapping[str, Any]:
198
+ api_key = os.environ.get(API_KEY_ENV, "").strip()
199
+ if not api_key:
200
+ raise AskError(
201
+ f"Set the {API_KEY_ENV} environment variable to use the anthropic-api backend."
202
+ )
203
+ client = self._make_client(api_key)
204
+ try:
205
+ response = client.beta.messages.create(
206
+ model=self._model,
207
+ max_tokens=16000,
208
+ betas=["server-side-fallback-2026-07-01"],
209
+ fallbacks="default",
210
+ system=system,
211
+ messages=[{"role": "user", "content": prompt}],
212
+ output_config={
213
+ "effort": "medium",
214
+ "format": {"type": "json_schema", "schema": dict(schema)},
215
+ },
216
+ )
217
+ except Exception as error:
218
+ raise AskError(_describe_api_error(error)) from error
219
+
220
+ if getattr(response, "stop_reason", None) == "refusal":
221
+ raise AskError("Claude declined to answer this question.")
222
+ text = next(
223
+ (block.text for block in response.content if getattr(block, "type", "") == "text"),
224
+ None,
225
+ )
226
+ if text is None:
227
+ raise AskError("The Anthropic API returned no text.")
228
+ try:
229
+ parsed = json.loads(text)
230
+ except ValueError as error:
231
+ raise AskError("The Anthropic API did not return the answer as JSON.") from error
232
+ if not isinstance(parsed, dict):
233
+ raise AskError("The Anthropic API did not return the answer as a JSON object.")
234
+ return parsed
235
+
236
+
237
+ def _describe_api_error(error: Exception) -> str:
238
+ """Explain an Anthropic SDK error in plain words (without the API key)."""
239
+ try:
240
+ import anthropic
241
+ except ImportError: # only reachable with a custom client_factory in tests
242
+ return f"The Anthropic API request failed: {type(error).__name__}"
243
+
244
+ if isinstance(error, anthropic.AuthenticationError):
245
+ return f"The API key in {API_KEY_ENV} was rejected. Check that it is correct."
246
+ if isinstance(error, anthropic.PermissionDeniedError):
247
+ return "This API key is not allowed to use this model."
248
+ if isinstance(error, anthropic.NotFoundError):
249
+ return 'The model was not found. Check "model" in .donelog/config.json.'
250
+ if isinstance(error, anthropic.RateLimitError):
251
+ return "The Anthropic API is rate limiting requests. Please try again later."
252
+ if isinstance(error, anthropic.APIStatusError):
253
+ return f"The Anthropic API returned an error (HTTP {error.status_code})."
254
+ if isinstance(error, anthropic.APITimeoutError):
255
+ return "The Anthropic API did not answer in time. Please try again."
256
+ if isinstance(error, anthropic.APIConnectionError):
257
+ return "Could not reach the Anthropic API. Check your internet connection."
258
+ return f"The Anthropic API request failed: {type(error).__name__}"
259
+
260
+
261
+ def make_backend(config: Config, override: Backend | None = None) -> AskBackend:
262
+ """Create the backend chosen by `override` or by the project's config."""
263
+ choice = override or config.ask_backend
264
+ if choice is Backend.ANTHROPIC_API:
265
+ return AnthropicApiBackend(model=config.model)
266
+ return ClaudeCodeBackend(model=config.model)